finance c++ programming course [part 1] – installation

C++ finance course for beginners – part 1 – hello world

REQUIREMENTS:
– microsoft visual studio express 2012 (it’s free,older versions are similar. there are slight differences between microsoft and linux c++)
– some programming experience in another language

Course objectives:

-price various derivatives using c++ code
-use basic quantlib and boost functions useful in financial engineering

C++ ,Boost and Quantlib install

1)install visual studio 2012 express :

http://www.microsoft.com/visualstudio/eng/downloads#d-express-windows-desktop

install visual studio 2012 c++

install visual studio 2012 c++

2) install boost

Hello world finance c++

Hello world finance c++


– download latest version of boost from http://www.boost.org

c++ boost download

c++ boost download

– unpack it into drive C:
[so its unpacked into c:\boost_1_53_0 ]

– go to the dir c:\boost_1_53_0 and run bootstrap.bat
– run b2.exe
it will take few hours to build!

build boost library

build boost library

– go to dir c:\boost_1_53_0\stage
move whole dir “lib” to c:\boost_1_53_0\ so all built libraries are inside c:\boost_1_53_0\lib

3) install quantlib

download quantlib
http://sourceforge.net/projects/quantlib/files/

quantlib download

quantlib download

unpack it to C:\

– open visual studio express for desktop

File->Open project -> QuantLib_vc10.sln

quantlib solution

quantlib solution

Choose “update” in the next dialog . it will convert files to visual studio 2012 format

in the solution explorer window select QuantLib
press Shift-F4 (or Menu->View->Property pages)

change “include directories” variable to include path to boost
change “library directories” variable to include path to boost\lib

set boost directories

set boost directories

now delete all projects except QuantLib from the solution (click on every project in solution explorer and press “del”)

press F7 to build quantlib [or menu->build->build solution]

Hello world program

Menu -> New Project

choose Visual C++ -> Win32 Console Application

new win32 console app

new win32 console app

press OK->NEXT (do NOT press FINISH yet)

check “Empty Project”
uncheck “Security…” box

new empty project

new empty project

click Finish

right Click on ConsoleApplication1 anc change include and library directory to include QuantLib and boost directories:

hello world c++ finance

hello world c++ finance

right click on “Source Files” -> Add ->Add New Item

add new c++ file

add new c++ file

in the window copy paste following code:

#include <ql/quantlib.hpp>
#include <iostream>

using namespace QuantLib;

void main()
{
	
	Date date1(30,January,2013);
	Date date2;
	date2=date1+1*Years;

std::cout<<date2;

int dummy;std::cin>>dummy;
}
hello world quantlib

hello world quantlib

press F7 to compile

double click on error :

quantlib compile error visual studio 2012

quantlib compile error visual studio 2012

and change the following line :

#  error "unknown Microsoft compiler"

by

#  define QL_LIB_TOOLSET "vc100"

so it looks like that:

quantlib compile error

quantlib compile error

press F7 to build project and F5 to run

hello world quantlib

hello world quantlib

quick explanation of the code:

#include <ql/quantlib.hpp>
#include <iostream>

these lines just insert files named quantlib.hpp and iostream into your source file
quantlib.hpp is needed to have quantlib functions and definitions (Date object)
and iostream is used to write to output console

using namespace QuantLib;

without this line you’d had to write “QuantLib::” before every quantlib object

void main()
{
	
	Date date1(30,January,2013);
	Date date2;
	date2=date1+1*Years;

std::cout<<date2;

int dummy;std::cin>>dummy;
}

these lines define main function
in c++ when console program starts it automatically start executing the function main()

	Date date1(30,January,2013);
	Date date2;

here we define two QuantLib objects(variables) date1 and date2 and assign a value for the first variable

date2=date1+1*Years;
std::cout<<date2;

here we assign value for date2 to be 1 year from date1

and std::cout part prints the result to console

int dummy;std::cin>>dummy;

this is needed to pause the screen

debugging C++ program

to debug program left click where the red dot appears and press F5

debugging c++ program

debugging c++ program

the program will start debug and you can hover cursor over the variable to see it's value

as you can see date1 will show some long number instead of date .It's because internally quantlib uses Excel format for dates .
press F10 to execute instructions one by one of F5 again to continue program until next break point

Posted in quant finance coding course

FX forward valuation excel

Here we’ll show how to value FX forwards (Foreign eXchange) on EURUSD exchange rate in excel with quantlib excel addin

in this example we’ll need following market data:

  • EURUSD spot
  • EURUSD forward points (can get from bloomberg or reuters)
  • EUR discount curve (for example EUR 6m curve)
  • In this spreadsheet we first construct syntetic USD yield curve based on EURUSD forward points, so after we could use usual formulas for FX forward valuation

    FX forward valuation excel:

    FX forward valuation excel

    FX forward valuation excel EURUSD example

    Posted in OTC derivatives valuation

    Amortizing interest rate swap valuation excel example

    Amortizing interest rate swap valuation excel with 2 curves example:

    for online amortizing interest rate swap valuation with credit valuation adjustment see Online Amortizing Interest rate swap valuation with CVA and OIS discounting
    for quantlib python version see Amortizing Interest rate swap valuation with python quantlib

    In this example we value amortizing swap with 2 flat curves : discount curve and forwarding curve.
    You can get curves in this format on Bloomberg or Reuters terminals.
    to get real value of swap paste curves for your valuation date and adjust arguments in formulas.
    set appropriate daycount conventions (usually actual/360 or 30/360) and calendars (usually TARGET in European contracts) from termsheet.

    1) first install quantlib addin at http://quantlib.org/quantlibxl/ -> download
    2) open file at QuantLibXL\xll\QuantLibXL-vc90-mt-s-1_2_0.xll
    3) open spreadsheet ctrl-alt-f9 to recalculate all

    interest rate swap valuation excel

    interest rate swap valuation excel

    for quantlib c++ valuation see http://www.pricederivatives.com/en/how-to-value-swap-with-2-curves-with-quantlib-quantlib-swap-example/

    Posted in OTC derivatives valuation, quantlib Tagged with: , ,

    Simple Derivatives CVA Calculation Example (credit valuation adjustment) excel

    Here we show simplest method called current net exposure

    for more elaborated Monte-Carlo method using python see CVA with monte carlo calculation

    for online interest rate swaps and OTC derivatives valuation with CVA see Derivatives accounting calculators

    CVA calculation online with current net exposure method online

    derivatives CVA calculation example:

    lets say we have derivatives portfolio with the same counterparty which consist of 2 amortizing swaps
    one approximate method for would be to calculate Net exposure at valuation time

    lets say swap1 worth today 2M$
    swap2 worth -1M$

    if there’s a netting agreement then total today’s exposure is (1-R)*(2M-1M) = (1-R)*1M $
    R is recovery normally supposed to be at 40%

    then CVA would be price to hedge this exposure with CDS (fixed leg of CDS)

    lets say counterparty Credit Defualt Swap spread is flat 300 pb (3%)

    then the cost of this hedge would be approximately

    CVA=3% * (maturity in years) * (1-R) *1M $

    if we want to improve the quality of this approximation we could take average exposure of swaps until maturity (at maturity exposure to swap is 0) which equals exposure today /2

    so final formula would be

    CVA=0.5*3% * (maturity in years) * (1-R) *1M $

    in case that two swaps have different maturity then we would have to weight the exposure by maturity factor of each instrument

    if total exposure is negative with this method CVA=0 and we would have to take own CDS spread to calculate DVA (debit valuation adjustment)

    example cva calculation in Excel (you can edit cells)

    FAS 157 require derivatives CVA to be calculated for fair value of derivatives, as well as basel 3 for banks

    Derivatives CVA calculation example excel

    to calculate value of annuity properly we can use quantlib addin from http://quantlib.org/quantlibxl/

    1) first install quantlib addin at http://quantlib.org/quantlibxl/ -> download
    2) open file at QuantLibXL\xll\QuantLibXL-vc90-mt-s-1_2_0.xll
    3) open spreadsheet ctrl-alt-f9 to recalculate all

    Here we calculate simplified derivatives CVA/DVA for a portfolio of 3 OTC derivatives with the same counterparty
    if net current exposure is negative then we’ll have only DVA and we’ll use institution’s own CDS spread, else we’ll have only CVA and we’ll need to apply counterparty CDS spreads (both found on bloomberg or reuters terminals).

    In this example we use sample flat curve for discounting. For proper use we’ll need to paste real curve for desired valuation date (also found on bloomberg or reuters)
    the standard recovery of 40% is used.

    to calculate annuity we’ll calculate swap value with 0 floating leg using quantlib addin functions for swap.

    download excel:

    cva calculation excel

    cva calculation excel

    references:
    Stein_H_FeSeminar_Sp12.pdf
    investopedia

    credit value adjustement

    credit value adjustement

    Posted in OTC derivatives valuation Tagged with: , , ,

    what is an OAS spread for bond

    Option Adjusted spread (OAS) is usually calculated for bonds with embedded options (call or put)
    OAS is a constant spread over discounting curve you have to apply to back up market price of the bond
    this spread is adjusted to embedded options

    example
    company A senior bond with embedded call feature is worth today 101$
    if OAS spread is 5% it means that if you want to calculate senior bond of the same company A , which does not have this optionality you would have to shift the discounting curve up 5% (constant spread) to get market price of this simple bond

    OAS spread could be used as CDS spread on this company A , if no other CDS quotes are available

    Posted in OTC derivatives valuation

    call option 101

    what is a call option?

    it’s an option which give right (=option) to buyer to buy a stock at fixed price called strike

    example of call option

    company A buys a european call option on Microsoft stock with strike 10 and maturity 1 jan 2015

    it means that if on 1/jan/2015 MSFT costs 12$ A would buy from B MSFT stocks at 10$ each . making profit of 2$/option

    if MSFT costs less than 10$ ,then A would not buy the stock and let the option expire

    Payoff

    Black-Scholes Valuation

    european option (exercicable only on maturity date) can be valued with Black-Scholes formula

    Black-Scholes formula explanation

    payoff could be written as $$ (S-K)^+ $$ ‘+’ means that if expression inside is negative we take it as 0
    formula de Black-Scholes tells us that call’s price is an approximation to payoff formula as equals
    $$ Call= S Proba1 – DiscountFactor K Proba2 $$
    where Proba2 is a probability that S> K at time T and Proba1 is the same , but “in another probability measure” (whoch makes a small difference between Proba1 y Proba2)

    Posted in OTC derivatives valuation

    financial derivatives 101

    what are the financial derivatives?

    basically it’s a contract which price is based on price of another financial asset

    example of a derivative

    company A buys a derivative form bank B by which
    B will pay 1 million euros if Ibex 35 index is bigger than 20000 points in one year’s time (this on is called digital call option)

    Types of derivatives

    there’re derivatives which can be bought in organized markets , like stock exchanges , and there are other type which are negotiated in private
    OTC derivatives (over the counter)

    also, derivatives could be classified by underlying security:

    interest rate derivatives

    example: dirivatives whose payout depends on level of Euribor , for example swaps

    FX derivatives

    example: payout depens on EURUSD exchange rate

    Equity derivatives

    example: payout depends on Santander stock price

    credit derivatives

    example: A pays B 1 million if company C goes broke

    commodity derivatives

    A pays B difference between precio del crudo Brent crude price and Ural crude price

    another way to classify them is by exercise type:

    american exercise

    option can be exercised at any date before maturity

    european exercise

    option can be executed only at maturity

    bermudan exercise

    option can be executed at various time points

    derivatives markets

    OTC derivatives market is huge: total outstanding notion at the end of 2011 was 10 time bigger than world GDP (700 trillion $)

    Posted in OTC derivatives valuation Tagged with:

    quanto adjustment formula example

    what is a quanto adjustment?

    it’s an adjustment to forward price of underlying if payoff’s currency is diferent from underlying’s currency

    example

    if payoff currency is EUREUR and underlying is in USD (for example DowJones index)
    then we’ll need to adjust dividend yield of Dow jones by this quanto adjustment formula:
    FX=EURUSD   (numeraire USD)
    S= DJ index (USD)
    $$ q=q-\rho \sigma_{FX} \sigma_{S}$$
    $$\rho$$ is a correlation between EURUSD and and Dow Jones
    Posted in OTC derivatives valuation Tagged with:

    how to value Eonia swap

    what is an EONIA swap (call money swap)?

    it’s a swap where we exchange fixed rate for variable rate calculated with dayly EONIA rate (Euro OverNight Index Average)
    the payments are based on average EONIA rate , which corresponds to reinvest both notional and received interest at EONIA rate

    How to value Eonia swap?

    for a Eonia – Fixed swap payout is calculated as:

    $$ r_{efrective}=\frac{1}{\delta_{periodBegin->periodEnd} } (\prod_{i=1}^{N} [1+\delta_{i->i+1}r_{i} ] – 1 ) $$
    so, to value floating leg we’ll need EONIA fixings from init of the period until valuation date
    year fraction $$\delta$$ is based on Actual/360
    for future fixings instead of calculating forwards every day we could calculate
    $$ r_{effective}=\frac{1}{\delta_{periodBegin->periodEnd}} (\frac{df_{periodBegin}}{df_{periodEnd}}-1) $$

    Posted in OTC derivatives valuation Tagged with:

    accounting for stock options

    What is a stock option plan?

    it’s a executive’s incentive plan whoch consists in giving employee a number of stock options which can be exercised only after certain period have passed (vesting period), normally few years

    Accounting for stock options

    normally we could value it like an american call option.
    Black -Scholes formula is not applicable here , because it hold only for european options (it could be applied if stock pays on dividends though).

    one can use numerical methods like binary trees or approximative methods (like approximation of Barone-Adesi and Whaley , for example)

    Vesting period generally lasts several years.Valuation of these options normally do not depend on this period as in the contracts there are additional clauses whoch stipulate that option could be executed before vesting period ends and there fore it would be generally hedged with american option.
    vesting period plays role in accounting as the cost of option is generally divided between vesting years [from start of plan until vesting period ends]

    to value these plans you can use following Accounting for stock options calculator
    employee stock option plan calculator

    Posted in OTC derivatives valuation Tagged with: