Table Of ContentImplementing QuantLib
Luigi Ballabio
Thisbookisforsaleathttp://leanpub.com/implementingquantlib
Thisversionwaspublishedon2020-09-07
ThisisaLeanpubbook.LeanpubempowersauthorsandpublisherswiththeLeanPublishing
process.LeanPublishingistheactofpublishinganin-progressebookusinglightweighttoolsand
manyiterationstogetreaderfeedback,pivotuntilyouhavetherightbookandbuildtractiononce
youdo.
©2014-2020LuigiBallabio
Tweet This Book!
PleasehelpLuigiBallabiobyspreadingthewordaboutthisbookonTwitter!
Thesuggestedhashtagforthisbookis#quantlib.
Findoutwhatotherpeoplearesayingaboutthebookbyclickingonthislinktosearchforthis
hashtagonTwitter:
#quantlib
Also By Luigi Ballabio
QuantLibPythonCookbook
构建 QuantLib
Implementing QuantLib の和訳
Contents
1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
2. Financialinstrumentsandpricingengines . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.1 TheInstrumentclass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.1.1 Interfaceandrequirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.1.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1.3 Example:interest-rateswap . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.1.4 Furtherdevelopments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Pricingengines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2.1 Example:plain-vanillaoption . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3. Termstructures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.1 TheTermStructureclass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.1.1 Interfaceandrequirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.1.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.2 Interest-ratetermstructures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.1 Interfaceandimplementation . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.2 Discount,forward-rate,andzero-ratecurves. . . . . . . . . . . . . . . . . 33
3.2.3 Example:bootstrappinganinterpolatedcurve . . . . . . . . . . . . . . . . 37
3.2.4 Example:addingz-spreadtoaninterest-ratecurve . . . . . . . . . . . . . 47
3.3 Othertermstructures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
3.3.1 Default-probabilitytermstructures . . . . . . . . . . . . . . . . . . . . . . 49
3.3.2 Inflationtermstructures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
3.3.3 Volatilitytermstructures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.3.4 Equityvolatilitystructures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
3.3.5 Interest-ratevolatilitystructures . . . . . . . . . . . . . . . . . . . . . . . . 58
4. Cashflowsandcoupons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.1 TheCashFlowclass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.2 Interest-ratecoupons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
4.2.1 Fixed-ratecoupons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
4.2.2 Floating-ratecoupons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
4.2.3 Example:LIBORcoupons . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
4.2.4 Example:capped/flooredcoupons . . . . . . . . . . . . . . . . . . . . . . . 78
CONTENTS
4.2.5 Generatingcash-flowsequences . . . . . . . . . . . . . . . . . . . . . . . . 84
4.2.6 Othercouponsandfurtherdevelopments . . . . . . . . . . . . . . . . . . . 87
4.3 Cash-flowanalysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
4.3.1 Example:fixed-ratebonds . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
5. Parameterizedmodelsandcalibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
5.1 TheCalibrationHelperclass. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
5.1.1 Example:theHestonmodel . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
5.2 Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
5.3 TheCalibratedModelclass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
5.3.1 Example:theHestonmodel,continued . . . . . . . . . . . . . . . . . . . . 114
6. TheMonteCarloframework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
6.1 Pathgeneration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
6.1.1 Random-numbergeneration . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
6.1.2 Stochasticprocesses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
6.1.3 Randompathgenerators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
6.2 Pricingonapath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
6.3 Puttingitalltogether . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
6.3.1 MonteCarlotraits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
6.3.2 TheMonteCarlomodel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
6.3.3 MonteCarlosimulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
6.3.4 Example:basketoption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
7. Thetreeframework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
7.1 TheLatticeandDiscretizedAssetclasses . . . . . . . . . . . . . . . . . . . . . . 155
7.1.1 Example:discretizedbonds . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
7.1.2 Example:discretizedoption . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
7.2 Treesandtree-basedlattices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
7.2.1 TheTreeclasstemplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
7.2.2 Binomialandtrinomialtrees . . . . . . . . . . . . . . . . . . . . . . . . . . 172
7.2.3 TheTreeLatticeclasstemplate . . . . . . . . . . . . . . . . . . . . . . . . 182
7.3 Tree-basedengines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
7.3.1 Example:callablefixed-ratebonds . . . . . . . . . . . . . . . . . . . . . . . 189
8. Thefinite-differenceframework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
8.1 Theoldframework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
8.1.1 Differentialoperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
8.1.2 Evolutionschemes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
8.1.3 Boundaryconditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
8.1.4 Stepconditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
8.1.5 TheFiniteDifferenceModelclass . . . . . . . . . . . . . . . . . . . . . . 207
8.1.6 Example:Americanoption . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
8.1.7 Time-dependentoperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
CONTENTS
8.2 Thenewframework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
8.2.1 Meshers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
8.2.2 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
8.2.3 Examples:Black-Scholesoperators . . . . . . . . . . . . . . . . . . . . . . . 238
8.2.4 Initial,boundary,andstepconditions . . . . . . . . . . . . . . . . . . . . . 242
8.2.5 Schemesandsolvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
9. Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
A.Oddsandends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Basictypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Datecalculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Datesandperiods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Calendars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Day-countconventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Schedules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Finance-relatedclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Marketquotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Interestrates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
Exercisesandpayoffs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
Math-relatedclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Interpolations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
One-dimensionalsolvers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Optimizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Linearalgebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
Globalsettings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Smartpointersandhandles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
Errorreporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Disposableobjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
Designpatterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
TheObserverpattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
TheSingletonpattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
TheVisitorpattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
B.Codeconventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
QuantLiblicense . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
CONTENTS i
Theauthorhasusedgoodfaitheffortinpreparationofthisbook,butmakesnoexpressedorimplied
warrantyofanykindanddisclaimswithoutlimitationallresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesinconnectionwithorarisingoutofthe
useoftheinformationorprogramscontainedherein.Useoftheinformationandinstructionsinthis
bookisatyourownrisk.
ThecoverimageisinthepublicdomainandavailablefromtheNewYorkPublicLibrary.Thecover
fontisOpenSansCondensed,releasedbySteveMattesonundertheApacheLicenseversion2.0.
1. Introduction
Withtheenthusiasmofyouth,theQuantLibwebsiteusedtostatethatQuantLibaimedatbecoming
“the standard free/open-source financial library.” By interpreting such statement a bit loosely, one
might say that it has somewhat succeeded—albeit by employing the rather devious trick of being
thefirst,andthusforsometimetheonly open-sourcefinanciallibrary¹.
Standard or not, the project is thriving; at the time of this writing, each new release is downloaded
a few thousand times, there is a steady stream of contributions from users, and the library seems
to be used in the real world—as far as I can guess through the usual shroud of secrecy used in the
financialworld.Allinall,asaprojectadministrator,Icandeclaremyselfahappycamper.
Butallthemoreforthat,thelackofproperdocumentationshows.Althoughadetailedclassreference
isavailable(thatwasaneasytask,sinceitcanbegeneratedautomatically)itdoesn’tletoneseethe
forestforthetrees;sothatanewusermightgettheimpressionthattheQuantLibdevelopersshare
theviewsoftheBellmanfromLewisCarroll’sHuntingoftheSnark:
“WhatuseareMercator’sNorthPolesandEquators,
Tropics,ZonesandMeridianLines?”
SotheBellmanwouldcry:andthecrewwouldreply,
“Theyaremerelyconventionalsigns!”
The purpose of this book is to fill a part of the existing void. It is a report on the design and
implementation of QuantLib, alike in spirit—but, hopefully, with less frightening results—to the
HowIdidit book²prominentlyfeaturedinMelBrooks’YoungFrankenstein.Ifyouare—orwantto
be—a QuantLib user, you will find here useful information on the design of the library that might
not be readily apparent when reading the code. If you’re working in quantitative finance, even if
not using QuantLib, you can still read it as a field report on the design of a financial library. You
will find that it covers issues that you might also face, as well as some possible solutions and their
rationale.Basedonyourconstraints,itispossible—evenlikely—thatyouwillchooseothersolutions;
butyoumightprofitfromthisdiscussionjustthesame.
Inmydescriptions,I’llalsopointoutshortcomingsinthecurrentimplementation;nottodisparage
thelibrary(I’mprettymuchinvolvedinit,afterall)butformoreusefulpurposes.Ontheonehand,
describing the existing pitfalls will help developers avoid them; on the other hand, it might show
howtoimprovethelibrary.Indeed,italreadyhappenedthatreviewingthecodeforthisbookcaused
metogobackandmodifyitforthebetter.
¹Afewgentleusershappenedtorefertoourlibraryas“theQuantLib.”AsmuchasIliketheexpression,modestyandhabithavesofar
preventedmefromusingit.
²Inthiscase,ofcourse,itwouldbe“Howwedidit.”
1
Introduction 2
For reasons of both space and time, I won’t be able to cover every aspect of the library. In the first
half of the book, I’ll describe a few of the most important classes, such as those modeling financial
instruments and term structures; this will give you a view of the larger architecture of the library.
Inthesecondhalf,I’lldescribeafewspecializedframeworks,suchasthoseusedforcreatingMonte
Carlo or finite-differences models. Some of those are more polished than others; I hope that their
currentshortcomingswillbeasinterestingastheirstrongpoints.
The book is primarily aimed at users wanting to extend the library with their own instruments or
models;ifyoudesiretodoso,thedescriptionoftheavailableclasshierarchiesandframeworkswill
provide you with information about the hooks youneed to integrate your code with QuantLib and
takeadvantageofitsfacilities.Ifyou’renotthiskindofuser,don’tclosethebookyet;youcanfind
usefulinformationtoo.However,youmightwanttolookattheQuantLibPythonCookbookinstead.
ItcanbeusefultoC++users,too.
* * *
Andnow,asistradition,afewnotesonthestyleandrequirementsofthisbook.
KnowledgeofbothC++andquantitativefinanceisassumed.I’venopretenseofbeingabletoteach
you either one, and this book is thick enough already. Here, I just describe the implementation and
design of QuantLib; I’ll leave it to other and better authors to describe the problem domain on one
hand,andthelanguagesyntaxandtricksontheother.
Asyoualreadynoticed,I’llwriteinthefirstpersonsingular.True,itmightlookratherself-centered—
asamatteroffact,Ihopeyoustillhaven’tputdownthebookinannoyance—butwewouldfeelrather
pompousifweweretousethefirstpersonplural.Theauthorofthisbookfeelsthesameaboutusing
thethirdperson.Afterabitofthinking,Ioptedforalessformalbutmorecomfortablestyle(which,
asyounoted,alsoincludesaliberaluseofcontractions).Forthesamereason,I’llbeaddressingyou
insteadoftheproverbialacutereader.Theuseofthesingularwillalsohelptoavoidconfusion;when
Iusetheplural,IdescribeworkdonebytheQuantLibdevelopersasagroup.
I will describe the evolution of a design when it is interesting on its own, or relevant for the final
result. For the sake of clarity, in most cases I’ll skip over the blind alleys and wrong turns taken;
put together design decisions which were made at different times; and only show the final design,
sometimessimplified.Thiswillstillleavemewithplentytosay:inthewordsoftheAlabamaShakes,
“why”isanawfullotofquestion.
I will point out the use of design patterns in the code I describe. Mind you, I’m not advocating
cramming your code with them; they should be applied when they’re useful, not for their own
sake.³ However, QuantLib is now the result of several years of coding and refactoring, both based
on user feedback and new requirements being added over time. It is only natural that the design
evolvedtowardpatterns.
³AmorethoroughexpositionofthispointcanbefoundinKerievsky,2004.