how to value interest rate swap with 2 curves with QuantLib C++ (quantlib swap example)

example of interest rate swap derivative valuation in c++ with quantlib.
for quantlib excel valuation see http://www.pricederivatives.com/en/amortizing-swap-valuation-excel-example/

maturity: 20 nov 2022
nominal: 1M
init date: 20 nov 2012
floating leg pays: Euribor 3m + 2% every 3 months
fixed leg pays:4% anually

calendar: TARGET
day counting convention fixed leg: 30/360
day counting convention floating leg: Actual/360

market data :

last fixing for Euribor 3m : 1%

for discounting we’ll use Eonia curve (could be obtained from reuters or bloomberg)
(here we’ll use faux market data)

[date] [discount factor]

31 Dec 2013 0.99
31 Dec 2024 0.80

for euribor forwards calculation we’ll use projecting curve (euribor 3m):

[date] [discount factor]

31 dec 2013 0.999
31 dec 2024 0.89

QuantLib swap example c++ code for valuation of this swap contract for 31/dec/2012 :

#include <ql/quantlib.hpp>

using namespace std;
using namespace QuantLib;
using namespace boost;

int main()
{
vector<Date> dates; 
vector<DiscountFactor> discountFactor; 

Date valuationDate(31,December,2012);
Settings::instance().evaluationDate()=valuationDate;

dates.push_back(valuationDate); discountFactor.push_back(1.0); 
dates.push_back(Date(31,December, 2013));  discountFactor.push_back(0.99); 
dates.push_back(Date(31,December, 2024));  discountFactor.push_back(0.80); 
shared_ptr<YieldTermStructure> forwardCurve(new InterpolatedDiscountCurve<LogLinear>(dates,discountFactor,Actual360())); 

discountFactor.pop_back();discountFactor.pop_back();

discountFactor.push_back(0.999);
discountFactor.push_back(0.89);

shared_ptr<YieldTermStructure> oisCurve(new InterpolatedDiscountCurve<LogLinear>(dates,discountFactor,Actual360())); 

Handle<YieldTermStructure> discountingTermStructure(oisCurve);
Handle<YieldTermStructure> forwardingTermStructure(forwardCurve);

Real nominal = 1000000.0;
Date previousResetDate(20,November,2012);
Date maturity(20,November,2022);
double spread = 0.02;
double fixedRate=0.04;

shared_ptr<IborIndex> euribor(new Euribor(3*Months,forwardingTermStructure));
euribor->addFixing(euribor->fixingDate(previousResetDate),0.01,true);
		
VanillaSwap::Type swapType = VanillaSwap::Payer;

Schedule fixedSchedule(previousResetDate, maturity,1*Years,
                               TARGET(), ModifiedFollowing,ModifiedFollowing,
                               DateGeneration::Forward, false);

Schedule floatSchedule(previousResetDate,maturity,3*Months,
                               TARGET(),ModifiedFollowing ,ModifiedFollowing,
                               DateGeneration::Forward, false);
        
VanillaSwap swap(VanillaSwap::Payer, nominal,fixedSchedule, fixedRate, Thirty360(),
            floatSchedule, euribor, spread,Actual360());
     
shared_ptr<PricingEngine> swapEngine(new DiscountingSwapEngine(discountingTermStructure));

swap.setPricingEngine(swapEngine);
       
double res=swap.NPV();

}


Posted in quantlib Tagged with: ,

How to value FX forward pricing example

FX forward

Definition

An FX Forward contract is an agreement to buy or sell a fixed amount of foreign currency at previously agreed exchange rate (called strike) at defined date (called maturity).

FX Forward Valuation Calculator

fx forward

fx forward

FX forward example

  1. trade date : 1/oct/2012
  2. maturity date: 1/oct/2013

on maturity date A will buy 100 USD at exchange rate EURUSD 1.23

FX forward pricing

What market data do we need?

  1. forward points
  2. EUR discount curve

Forward points for 1 month represent how many basis points to add to current spot to know the forward EURUSD exchange rate
(for valuation date of today could be found on page fxstreet)

for example if forward points for EURUSD for 1 month is 30 and eurusd spot for valuation date is 1.234 then
the forward rate EURUSD for valuation date+ 1 month would be $$1.234+30/10000=1.237$$

FX forward valuation algorithm

  1. calculate forward exchange rate in euros: Forward in dollars=spot+Forwardpoints/10000 , Forward in Euros=1/ForwardInDollars
  2. caclulate net value of transaction at maturity: NetValue=Nominal*(Forward-Strike)
  3. discount it to valuation date with EUR discount curve: NPV=DiscountFactorEUR(maturity)*NetValue

FX forward example valuation:

valuation date: 1/oct/2012

market data:

forward FX points EURUSD 12months = 100

discount factor EUR (1/oct/2013) = 0.9

Spot EURUSD (1/oct/2012) = 1.234

1) calculate FX Forward for 12 months maturity:

Forward 12m EURUSD=1.234+100/10000  = 1.244

Forward USDEUR = 1/1.244=0.8039

2) calculate value at maturity:

strike in EUR = 1/1.23 = 0.813

Value(maturity)=100 (0.8039-0.813)=-0.91496 EUR

3) descount value to valuation date

NPV= 0.9*(-0.91496)=-0.82346 EUR

Excel calculation example (you can edit white cells):

Excel offline file using quantlib addin:
FX forward valuation example EURUSD using quantlib excel addin

Posted in OTC derivatives valuation Tagged with: , , ,

how to install python quantlib windows

Here we’ll show two ways to install quantlib package for python under windows [under unix/linux just install quantlib-python package from your favorite package installer]

first way (somewhat lengthy) is to compile it youself
second and easy way is install it from winpython package (see below)

Compile and install

you’ll need visual studio 2008 because python is compiled with it

install python 2.7

download quantlib 

download quantlib-swig (can be for linux distribution, for example for debian)

download boost 1.47 version is ok

extract all this to directory without spaces in name [there’s a bug in python script if ther’re spaces

modify enviroment variables:

INCLUDE = path to boost

QL_DIR = path to quantlib

build quantlib

go to swig/python dir

execute:

python setup.py build --compiler=msvc

python setup.py install

if you have several visual studio installations (VS 2012 and VS 2008 for example) you’ll need to run this from visual studio command promt (and indicating full path to python.exe)

Easy way with WinPython

install WinPython

download Quantlib package for your platform from here

run winpython control panel .exe
and point to downloaded quantlib package , Install

to use QuantLib run

from QuantLib import *

Posted in quantlib

simple example Libor Market Model (BGM)

Libor Market Model is a model where Libor forwards have log-normal distribution in their’s respective probability measures (called T-measure)

example of Libor Market Model with just 2 forwards:

$$ P_3(t)$$ is a price at time t of zero-coupon bond paying at $$T_3$$

$$ F_{T_1->T_2}(t)$$ is Libor forward [fixing $$T_1$$, maturity $$T_2$$]

Libor Market Model

Libor Market Model

lets take a numeraire=bond $$P_3(t)$$

in LMM forward $$ F_{T_2->T_3}(t)$$ is martingale i.e. it has the following dynamics in the $$P_3(t)$$ measure de:
$$ dF_{2->3}(t)=F_{2->3}(t) \sigma_2 dW_2(t) $$
from this dynamics we could deduce the Black formula for caplet $$T_2->T_3$$
[this is the formula which is used by market , that why Libor market model]

forward $$F_{1->2}$$ is not a martingale anymore and will have a drift

$$ dF_{1->2}(t)=F_{1->2}(t) ( drift(t) + \sigma_1 dW_1(t) )$$

Browinan motions $$W_1(t) and W_2(t)$$ are usually correlated

$$ dW_1(t)dW_2(t)=\rho dt $$

this drift(t) can be calculated (idea : $$ (1+\delta F_{1->2} ) (1+\delta F_{1->2}) $$ must be martingale )

once we have a formula for drift we could simulate the simultanious dynamics of both forwards with monte-carlo and calculate any payoff dependend on these forwards

– long jumps

as drift depends on forwards to simulate long jumps first project forwards with F(0) values , get F(T) then use 0.5(F(0)+F(T)) as constant forwards in drift to get F(T) second time

Posted in OTC derivatives valuation Tagged with:

why discount collaterized swaps with EONIA?

the collateral at every moment must coincide with value mark-to-market of swap

let’s take as a example simple swap with just one cashflow , which pays 100 euros at time T [it has no variable leg]

at time T swap’s value is 100 euros
so collateral value is also 100
at time T-1 (previous day) how much collateral we have to put?
if collateral is in EUR and grows with overnight EONIA rate
we must put 100 euros (=value of cashflow) decounted with EONIA rate
but as collateral coincides with MTM of derivative the cashflow must be discounted with the same rate

another example

if swap is in EUR but the collateral is in USD we still have to discount the derivative with OIS rate (usd fed funds)

Posted in OTC derivatives valuation Tagged with: ,

how to caclulate fair value of interest rate swap

how to caclulate fair value of interest rate swap

Online Interest Rate Swap Calculator

tipical example of interest rate swap contract between A and B:

example of swap

init date: 1/5/2012
maturity date: 1/5/2014
notional: 1 000 000 Eur
payments: annually
day counting convention: Actual/360
calendar: TARGET
bad day convention: Modified Following
A pays: fixed rate 4%
B pays: Euribor 12m

this contract can be represented by following cashflow diagram:

swap cashflows

swap cashflows

Euribor rates generally are fixed at the beginning of the period (in our case one year before payment)

how to calculate fair value?

valuation algorithm

  1. calculate net cashflow at every paydate
  2. discount each cashflow to valuation date
  3. sum all net discounted cashflows
payment 1 (1/5/2013)
A pays 4% on 1 000 000 = 40000 eur
we must multiply this quantity by year fraction with base Act/360 = frac(1/5/2012 -> 1/5/2013) = 1.014
so finally A pays 40000*1.014=40560 eur
B pays euribor 12m fixed on 1/5/2012 [  1.321 % ] i.e. B pays 1000000*0.01321*1.014 = 13394 eur
net pay1 = 40560 – 13394 =  27166 eur
this cashflow we must discount with EUR discount curve caclulated on 31/12/2012
suppose that discount factor for 1/5/2013 is 0.9
so discounted cashflow 1 will be 27166*0.9 = 24449 eur
payment 2 (1/5/2014)
A pays 4% on 1 000 000 = 40000 eur
multiply it by year fraction 1.014
A pays 40000*1.014=40560 eur
B pays euribor 12m fixed on 1/5/2013
this date is in the future so we must estimate it (=calculate euribor forward) with forwarding yield curve Euribor 12m on 31/12/2012
we can calculate this forward by formula:
$$ F= \frac{1}{YearFrac(1/5/2013 -> 1/5/2014)}(\frac{ DF(1/5/2013)}{DF(1/5/2014)}-1) $$
here the year fraction is calculated with the convention of the discounting curve  (suppose its the same act/360 convention)
if DF(1/5/2013)=0.8
and DF(1/5/2014)=0.85
then B would pay 1000000*0.058*1.014 = 58812 eur
net pay1 = 40560 – 58812 =  -18252 eur
this cashflow we must discount with the discounting yield curve with reference date 31/12/2012
suppose that discount factor( 1/5/2014)= 0.7
so discounted cashflow1 is -18252*0.7 =-12776.4 eur
So , this swap’s fair value on 31/12/2012 is -12776.4 eur
Posted in OTC derivatives valuation Tagged with:

how to construct yield curve in quantlib [ quantlib yield curve example ]

bloomberg or reuters can give you already bootstrapped curve in format [date] [discount factor]

here we’ll show a quantlib yield curve example construction

yield curve normally is used for getting a discount factor for a given date and for calculating euribor forwards

here we’ll show code snippet with quantlib which show show to use these functions

market date example:

valuation date: 31/dec/2012

[date] [discount factor]
30/12/2013 0.99
30/12/2014 0.98

we’ll calculate discount factor for 25/june /2013 and euribor forward 6m for the same date

#include <ql/quantlib.hpp>

using namespace std;
using namespace QuantLib;
using namespace boost;

int main()
{

vector<Date> dates; 
vector<DiscountFactor> discountFactor; 

Date valuationDate(31,December,2012);

dates.push_back(valuationDate); discountFactor.push_back(1.0); 

dates.push_back(Date(30,December, 2013));  discountFactor.push_back(0.99); 
dates.push_back(Date(30,December, 2014));  discountFactor.push_back(0.98); 

shared_ptr<YieldTermStructure> curve(new InterpolatedDiscountCurve<LogLinear>(dates,discountFactor,Actual360())); 

//discount factor
Date datex(25,June,2013);
double discount=curve->discount(datex);

//euribor forward
Period period(6*Months);
boost::shared_ptr<IborIndex> euribor(new Euribor(period));
double forward6m=curve->forwardRate(datex,period,curve->dayCounter(),QuantLib::Compounding::Simple);

}


Posted in quantlib

monte carlo method in finance

whats is monte carlo method in finance?

its a numerical method for calculating option’s price.
it consist in generating many possible scenarios and calculate average.

example – call option

suppose Black-Scholes (lognormal) dynamics for underlying stock S. suppose interest rate and dividends are 0:

$$dS=S \sigma dW_t $$
$$dW_t$$ is standard browinian motion

1) discretize the equation with just one time step:
$$ S_1=S_0+S_0\sigma \epsilon $$
where
$$\epsilon$$ is a standard gaussian

2) generate N random gaussian numbers $$ \epsilon_1,\epsilon_2,\epsilon_3,..\epsilon_N $$
3) calculate $$S_1$$ for every $$\epsilon$$
so we’ll have $$ S_1(\epsilon_1) , S_1(\epsilon_2) ,.., S_1(\epsilon_N) $$
4) calculate payoff of the option for every $$ S_i$$
call payoff is$$ (S_1(\epsilon_1)-K)^+ $$
5) calculate option’s price as average of these payoffs

if interest rates are not 0 we’d need to change S dynamics and discount payoff with corresponding discount factor

Posted in OTC derivatives valuation

ito lemma in finance

to derive equations for asset price evolution one uses Ito lemma:

$$ d f(X_t,Y_t) = f_{x}(X)dX+f_{y}(Y)dY+f_{xy}dXdY + \frac{1}{2} f_{xx}(X) dXdX+ \frac{1}{2} f_{yy}(Y) dY dY $$

basically its the same as Taylor formula for 2 variables developed until 2nd order.

when applying Ito’s lema the following formulas are useful:

$$ dW_tdW_t=dt $$
$$ dt_tdW_t=0 $$
$$ dtdt=0 $$

Applications

it’s used for example to derive Black-Scholes equation [in partial derivatives]

Posted in math

Girsanov theorem finance

to change the probability measure one uses Girsanov theorem (formula):

$$ \frac{N_a(0)}{N_a(T)} d \mathbb{P}_a=\frac{N_b(0)}{N_b(T)} d \mathbb{P}_b$$

$$N_a$$ is numeraire (price of any non dividend paying asset, usually bond or bank account) and it’s correspoding probability measure is $$P_a$$

$$N_b$$ is another numeraire with it’s probability measure $$P_b$$

Applications

expectation of short rate is forward rate under T-forward measure

– prove that $$E^T(r_T|F_t)=f_{T->T+dT}(t)$$

where $$E^T$$ is a expectation under T-forward measure (where bond $$P_{->T}$$ is numeraire
and $$f_{T->T+dT}(t)$$ is an instantaneous forward rate for time T as seen at time t

– write bond price in two forms:

$$P_{->T}(t)=E^{RN}(e^{-\int_t^Tr_sds}|F_t)$$
$$P_{->T}(t)=e^{-\int_t^Tf_s(t)ds}$$
so
$$E^{RN}(e^{-\int_t^Tr_sds}|F_t)=e^{-\int_t^Tf_s(t)ds}$$
1) differentiate both parts by T
2) change measure from Risk-neutral to T-forward measure from time t to time T (as usual rule apply girsanov formula between times when the process is stochastic ,in this case not between 0 and t for example)

Black Scholes formula

to calculate the term $$E(S_T 1_{S_T>K})$$ one uses girsanov to pass from risk neutral measure to forward measure where $$S_t$$ is numeraire

Libor In Arrears Convexity adjustment

Simple example libor in arrears convexity adjustment to change from T1 measure to T2 measure

Posted in math