爱问 爱问共享资料 爱问分类
首页 > > > C++.Design.Patterns.and.Derivatives.Pricing(第二版…

C++.Design.Patterns.and.Derivatives.Pricing(第二版).pdf

C++.Design.Patterns.and.Derivat…

上传者: along
638次下载 0人收藏 暂无简介 简介 2011-12-14 举报

简介:C++学习参考

ThispageintentionallyleftblankC++DESIGNPATTERNSANDDERIVATIVESPRICING2ndeditionDesignpatternsarethecutting-edgeparadigmforprogramminginobject-orientedlan-guages.HeretheyarediscussedinthecontextofimplementingfinancialmodelsinC++.AssumingonlyabasicknowledgeofC++andmathematicalfinance,thereaderistaughthowtoproducewell-designed,structured,reusablecodeviaconcreteexamples.Thisneweditionincludesseveralnewchaptersdescribinghowtoincreaserobustnessinthepresenceofexceptions,howtodesignagenericfactory,howtointerfaceC++withEXCEL,andhowtoimprovecodedesignusingtheideaofdecoupling.CompleteANSI/ISOcompatibleC++sourcecodeishostedonanaccompanyingwebsiteforthereadertostudyindetail,andreuseastheyseefit.AgoodunderstandingofC++designisanecessityforworkingfinancialmathemati-cian;thisbookprovidesathoroughintroductiontothetopic.Mathematics,FinanceandRiskEditorialBoardMarkBroadie,GraduateSchoolofBusiness,ColumbiaUniversitySamHowison,MathematicalInstitute,UniversityofOxfordNeilJohnson,CentreforComputationalFinance,UniversityofOxfordGeorgePapanicolaou,DepartmentofMathematics,StanfordUniversityC++DESIGNPATTERNSANDDERIVATIVESPRICINGM.S.JOSHIUniversityofMelbourneCAMBRIDGEUNIVERSITYPRESSCambridge,NewYork,Melbourne,Madrid,CapeTown,Singapore,SãoPauloCambridgeUniversityPressTheEdinburghBuilding,CambridgeCB28RU,UKFirstpublishedinprintformatISBN-13978-0-521-72162-2ISBN-13978-0-511-39693-9M.S.Joshi20082008Informationonthistitle:www.cambridge.org/9780521721622Thispublicationisincopyright.Subjecttostatutoryexceptionandtotheprovisionofrelevantcollectivelicensingagreements,noreproductionofanypartmaytakeplacewithoutthewrittenpermissionofCambridgeUniversityPress.CambridgeUniversityPresshasnoresponsibilityforthepersistenceoraccuracyofurlsforexternalorthird-partyinternetwebsitesreferredtointhispublication,anddoesnotguaranteethatanycontentonsuchwebsitesis,orwillremain,accurateorappropriate.PublishedintheUnitedStatesofAmericabyCambridgeUniversityPress,NewYorkwww.cambridge.orgeBook(NetLibrary)paperbackToJaneContentsPrefacepagexiiiAcknowledgementsxvi1AsimpleMonteCarlomodel11.1Introduction11.2Thetheory11.3AsimpleimplementationofaMonteCarlocalloptionpricer21.4CritiquingthesimpleMonteCarloroutine71.5Identifyingtheclasses91.6Whatwilltheclassesbuyus?101.7Whyobject-orientedprogramming?111.8Keypoints111.9Exercises122Encapsulation132.1Implementingthepay-offclass132.2Privacy152.3Usingthepay-offclass162.4Furtherextensibilitydefects192.5Theopen–closedprinciple202.6Keypoints212.7Exercises223Inheritanceandvirtualfunctions233.1‘isa’233.2Codinginheritance243.3Virtualfunctions243.4Whywemustpasstheinheritedobjectbyreference293.5Notknowingthetypeandvirtualdestruction303.6Addingextrapay-offswithoutchangingfiles34viiviiiContents3.7Keypoints373.8Exercises374Bridgingwithavirtualconstructor384.1Theproblem384.2Afirstsolution394.3Virtualconstruction434.4Theruleofthree514.5Thebridge534.6Bewareofnew574.7Aparametersclass584.8Keypoints654.9Exercises655Strategies,decoration,andstatistics665.1Differingoutputs665.2Designingastatisticsgatherer665.3Usingthestatisticsgatherer695.4Templatesandwrappers735.5Aconvergencetable775.6Decoration805.7Keypoints815.8Exercises816Arandomnumbersclass836.1Why?836.2Designconsiderations846.3Thebaseclass866.4Alinearcongruentialgeneratorandtheadapterpattern886.5Anti-theticsamplingviadecoration936.6Usingtherandomnumbergeneratorclass976.7Keypoints1026.8Exercises1027Anexoticsengineandthetemplatepattern1037.1Introduction1037.2Identifyingcomponents1047.3Communicationbetweenthecomponents1057.4Thebaseclasses1067.5ABlack–Scholespathgenerationengine1117.6AnarithmeticAsianoption1157.7Puttingitalltogether1177.8Keypoints1207.9Exercises120Contentsix8Trees1218.1Introduction1218.2Thedesign1238.3TheTreeProductclass1258.4Atreeclass1298.5Pricingonthetree1358.6Keypoints1398.7Exercises1399Solvers,templates,andimpliedvolatilities1419.1Theproblem1419.2Functionobjects1429.3Bisectingwithatemplate1459.4Newton–Raphsonandfunctiontemplatearguments1499.5UsingNewton–Raphsontodoimpliedvolatilities1519.6Theprosandconsoftemplatization1549.7Keypoints1569.8Exercises15610Thefactory15710.1Theproblem15710.2Thebasicidea15710.3Thesingletonpattern15810.4Codingthefactory15910.5Automaticregistration16210.6Usingthefactory16510.7Keypoints16610.8Exercises16711Designpatternsrevisited16811.1Introduction16811.2Creationalpatterns16811.3Structuralpatterns16911.4Behaviouralpatterns17011.5Whydesignpatterns?17111.6Furtherreading17211.7Keypoints17211.8Exercise17312Thesituationin200717412.1Introduction17412.2Compilersandthestandardlibrary17412.3Boost176xContents12.4QuantLib17712.5xlw17712.6Keypoints17812.7Exercises17813Exceptions17913.1Introduction17913.2Safetyguarantees18013.3Theuseofsmartpointers18013.4Theruleofalmostzero18313.5Commandstoneveruse18413.6Makingthewrapperclassexceptionsafe18513.7Throwinginspecialfunctions18613.8Floatingpointexceptions18713.9Keypoints19214Templatizingthefactory19714.1Introduction19714.2Usinginheritancetoaddstructure19714.3Thecuriouslyrecurringtemplatepattern19914.4Usingargumentlists20014.5TheprivatepartoftheArgumentListclass20614.6TheimplementationoftheArgumentList20814.7Cellmatrices22014.8CellsandtheArgumentLists22414.9Thetemplatefactory23214.10Usingthetemplatizedfactory23714.11Keypoints24214.12Exercises24315InterfacingwithEXCEL24415.1Introduction24415.2Usage24515.3Basicdatatypes24715.4Extendeddatatypes24815.5xlwcommands25015.6Theinterfacefile25015.7Theinterfacegenerator25315.8Troubleshooting25415.9Debuggingwithxlls25415.10Keypoints25515.11Exercises255Contentsxi16Decoupling25616.1Introduction25616.2Headerfiles25616.3Splittingfiles25916.4Directionofinformationflowandlevelization26016.5Classesasinsulators26216.6inlining26216.7Templatecode26316.8Functionalinterfaces26416.9Pimpls26416.10Keypoints26516.11Exercises265AppendixABlack–Scholesformulas266AppendixBDistributionfunctions270AppendixCAsimplearrayclass274C.1Choosinganarrayclass274C.2Asimplearrayclass275C.3Asimplearrayclass278AppendixDThecode285D.1Usingthecode285D.2Compilers285D.3License285AppendixEGlossary286Bibliography287Index289PrefaceThisbookisaimedatareaderwhohasstudiedanintroductorybookonmathemat-icalfinanceandanintroductorybookonC++butdoesnotknowhowtoputthetwotogether.MyobjectiveistoteachthereadernotjusthowtoimplementmodelsinC++butmoreimportantlyhowtothinkinanobject-orientedway.Therearealreadymanybooksonobject-orientedprogramming;however,theexamplestendnottofeelrealtothefinancialmathematiciansointhisbookweworkexclusivelywithexamplesfromderivativespricing.WedonotattempttocoverallsortsoffinancialmodelsbutinsteadexamineafewindepthwiththeobjectiveatalltimesofusingthemtoillustratecertainOOideas.Weproceedlargelybyexample,rewriting,ourdesignsasnewconceptsareintroduced,insteadofworkingoutagreatdesignatthestart.Whilstthisapproachisnotoptimalfromadesignstandpoint,itismorepedagogicallyaccessible.Anaspectofthisisthatourexamplesaredesignedtoemphasizedesignprinciplesratherthantoillustrateotherfeaturesofcoding,suchasnumericalefficiencyorexceptionsafety.WecommencebyintroducingasimpleMonteCarlomodelwhichdoesnotuseOOtechniquesbutratheristhesimplestproceduralmodelforpricingacalloptiononecouldwrite.Weexamineitsshortcomingsanddiscusshowclassesnaturallyarisefromtheconceptsinvolvedinitsconstruction.InChapter2,wemoveontotheconceptofencapsulation–theideathataclassallowstoexpressareal-worldanalogueanditsbehavioursprecisely.Inordertoillustrateencapsulation,welookathowaclasscanbedefinedforthepay-offofavanillaoption.Wealsoseethattheclasswehavedefinedhascertaindefects,andthisnaturallyleadsontotheopen–closedprinciple.InChapter3,weseehowabetterpay-offclasscanbedefinedbyusinginheri-tanceandvirtualfunctions.Thisraisestechnicalissuesinvolvingdestructionandpassingarguments,whichweaddress.Wealsoseehowthisapproachiscompatiblewiththeopen–closedprinciple.xiiixivPrefaceUsingvirtualfunctionscausesproblemsregardingthecopyingofobjectsofun-knowntype,andinChapter4weaddresstheseproblems.Wedosobyintroducingvirtualconstructorsandthebridgepattern.Wedigresstodiscussthe‘ruleofthree’andtheslownessofnew.Theideasareillustratedviaavanillaoptionsclassandaparametersclass.Withthesenewtechniquesatourdisposal,wemoveontolookingatmorecom-plicateddesignpatternsinChapter5.Wefirstintroducethestrategypatternthatexpressestheideathatdecisionsonpartofanalgorithmcanbedeferredbydele-gatingresponsibilitiestoanauxiliaryclass.Wethenlookathowtemplatescanbeusedtowriteawrapperclassthatremovesalotofourdifficultieswithmemoryhandling.Asanapplicationofthesetechniques,wedevelopaconvergencetableusingthedecoratorpattern.InChapter6,welookathowtodeveloparandomnumbersclass.Wefirstexam-inewhyweneedaclassandthendevelopasimpleimplementationwhichprovidesareusableinterfaceandanadequaterandomnumbergenerator.Weusetheimple-mentationtointroduceandillustratetheadapterpattern,andtoexaminefurtherthedecoratorpattern.Wemoveontoourfirstnon-trivialapplicationinChapter7,whereweusetheclassesdevelopedsofarintheimplementationofaMonteCarlopricerforpath-dependentexoticderivatives.Aspartofthisdesign,weintroduceandusethetem-platepattern.WefinishwiththepricingofAsianoptions.WeshiftfromMonteCarlototreesinChapter8.Weseethesimilaritiesanddifferencesbetweenthetwotechniques,andimplementareusabledesign.Aspartofthedesign,wereusesomeoftheclassesdevelopedearlierforMonteCarlo.WereturntothetopicoftemplatesinChapter9.Weillustratetheirusebydesign-ingreusablesolverclasses.Theseclassesarethenusedtodefineimpliedvolatilityfunctions.Enroute,welookatfunctionobjectsandpointerstomemberfunctions.Wefinishwithadiscussionoftheprosandconsoftemplatization.InChapter10,welookatourmostadvancedtopic:thefactorypattern.Thispatternsallowstheadditionofnewfunctionalitytoaprogramwithoutchanginganyexistingfiles.Aspartofthedesign,weintroducethesingletonpattern.WepauseinChapter11toclassify,summarize,anddiscussthedesignpatternswehaveintroduced.Inparticular,weseehowtheycanbedividedintocreational,structural,andbehaviouralpatterns.Wealsoreviewtheliteratureondesignpatternstogivethereaderaguideforfurtherstudy.Thefinalfourchaptersarenewforthesecondedition.Intheseourfocusisdifferent:ratherthanfocussingexclusivelyondesignpatterns,welookatsomeotherimportantaspectsofgoodcodingthatneophytestoC++tendtobeunawareof.PrefacexvInChapter12,wetakeahistoricallookatthesituationin2007andatwhathaschangedinrecentyearsbothinC++andthefinancialengineeringcommunity’suseofit.ThestudyofexceptionsafetyisthetopicofChapter13.Weseehowmakingtherequirementthatcodefunctionswellinthepresenceofexceptionsplacesalargenumberofconstraintsonstyle.Weintroducesomeeasytechniquestodealwiththeseconstraints.InChapter14,wereturntothefactorypattern.Theoriginalfactorypatternre-quiredustowritesimilarcodeeverytimeweintroducedanewclasshierarchy;wenowseehow,byusingargumentlistsandtemplates,afullygeneralfactoryclasscanbecodedandreusedforever.InChapter15,welookatsomethingratherdifferentthatisveryimportantinday-to-dayworkforaquant:interfacingwithEXCEL.Inparticular,weexaminethexlwpackageforbuildingxlls.ThispackagecontainsallthecodenecessarytoexposeaC++functiontoEXCEL,andevencontainsaparsertowritethenewcoderequiredforeachfunction.TheconceptofphysicaldesignisintroducedinChapter16.Weseehowtheobjectiveofreducingcompiletimescanaffectourcodeorganizationanddesign.Thecodefortheexamplesinthefirst11chaptersofthisbookcanbefreelydownloadedfromwww.markjoshi.com/design,andanybugfixeswillbepostedthere.Thecodefortheremainingchaptersistakenfromthexlwprojectandcanbedownloadedfromxlw.sourceforge.net.Allexamplecodeistakenfromrelease2.1.AcknowledgementsIamgratefultotheRoyalBankofScotlandforprovidingastimulatingenviron-mentinwhichtolearn,studyanddomathematicalfinance.MostofmyviewsoncodingC++andfinancialmodellinghavebeendevelopedduringmytimework-ingthere.MyunderstandingofthetopichasbeenformedthroughdailydiscussionswithcurrentandformercolleaguesincludingChrisHunter,PeterJackel,Dhermin-derKainth,SukhdeepMahal,RobinNicholsonandJochenTheis.Iamalsograte-fultoahostofpeoplefortheirmanycommentsonthemanuscript,includingAlexBarnard,DherminderKainth,RobKitching,SukhdeepMahal,NadimMahassen,HughMcBride,AlanStaceyandPatrikSundberg.IwouldalsoliketothankDavidTranahandtherestoftheteamatCambridgeUniversityPressfortheircarefulworkandattentiontodetail.Finallymywifehasbeenverysupportive.Iamgratefultoanumberofpeoplefortheircommentsonthesecondedi-tion,withparticularthankstoChrisBeveridge,NarinderClaire,NickDensonandLorenzoLiesch.xvi1AsimpleMonteCarlomodel1.1IntroductionInthefirstpartofthisbook,weshallstudythepricingofderivativesusingMonteCarlosimulation.WedothisnottostudytheintricaciesofMonteCarlobutbecauseitprovidesmanyconvenientexamplesofconceptsthatcanbeabstracted.Wepro-ceedbyexample,thatiswefirstgiveasimpleprogram,discussitsgoodpoints,itsshortcomings,variouswaysroundthemandthenmoveontoanewexample.Wecarryoutthisprocedurerepeatedlyandeventuallyendupwithafancyprogram.WebeginwitharoutinetopricevanillacalloptionsbyMonteCarlo.1.2ThetheoryWecommencebydiscussingthetheory.ThemodelforstockpriceevolutionisdSt=µStdt+σStdWt,(1.1)andarisklessbond,B,growsatacontinuouslycompoundingrater.TheBlack–Scholespricingtheorythentellsusthatthepriceofavanillaoption,withexpiryTandpay-offf,isequaltoerTE(f(ST)),wheretheexpectationistakenundertheassociatedrisk-neutralprocess,dSt=rStdt+σStdWt.(1.2)Wesolveequation(1.2)bypassingtothelogandusingIto’slemma;wecomputedlogSt=(r12σ2)dt+σdWt.(1.3)Asthisprocessisconstant-coefficient,ithasthesolutionlogSt=logS0+(r12σ2)t+σWt.(1.4)12AsimpleMonteCarlomodelSinceWtisaBrownianmotion,WTisdistributedasaGaussianwithmeanzeroandvarianceT,sowecanwriteWT=TN(0,1),(1.5)andhencelogST=logS0+(r12σ2)T+σTN(0,1),(1.6)orequivalently,ST=S0e(r12σ2)T+σTN(0,1).(1.7)ThepriceofavanillaoptionisthereforeequaltoerTE(f(S0e(r12σ2)T+σTN(0,1))).TheobjectiveofourMonteCarlosimulationistoapproximatethisexpectationbyusingthelawoflargenumbers,whichtellsusthatifYjareasequenceofidenticallydistributedindependentrandomvariables,thenwithprobability1thesequence1NNj=1YjconvergestoE(Y1).SothealgorithmtopriceacalloptionbyMonteCarloisclear.Wedrawarandomvariable,x,fromanN(0,1)distributionandcomputef(S0e(r12σ2)T+σTx),wheref(S)=(SK)+.Wedothismanytimesandtaketheaverage.WethenmultiplythisaveragebyerTandwearedone.1.3AsimpleimplementationofaMonteCarlocalloptionpricerAfirstimplementationisgivenintheprogramSimpleMCMain1.cpp.Listing1.1(SimpleMCMain1.cpp)//requiresRandom1.cpp#include<Random1.h>#include<iostream>#include<cmath>usingnamespacestd;1.3AsimpleimplementationofaMonteCarlocalloptionpricer3doubleSimpleMonteCarlo1(doubleExpiry,doubleStrike,doubleSpot,doubleVol,doubler,unsignedlongNumberOfPaths){doublevariance=Vol*Vol*Expiry;doublerootVariance=sqrt(variance);doubleitoCorrection=-0.5*variance;doublemovedSpot=Spot*exp(r*Expiry+itoCorrection);doublethisSpot;doublerunningSum=0;for(unsignedlongi=0;i<NumberOfPaths;i++){doublethisGaussian=GetOneGaussianByBoxMuller();thisSpot=movedSpot*exp(rootVariance*thisGaussian);doublethisPayoff=thisSpot-Strike;thisPayoff=thisPayoff>0?thisPayoff:0;runningSum+=thisPayoff;}doublemean=runningSum/NumberOfPaths;mean*=exp(-r*Expiry);returnmean;}intmain(){doubleExpiry;doubleStrike;doubleSpot;doubleVol;doubler;unsignedlongNumberOfPaths;cout<<"\nEnterexpiry\n";cin>>Expiry;4AsimpleMonteCarlomodelcout<<"\nEnterstrike\n";cin>>Strike;cout<<"\nEnterspot\n";cin>>Spot;cout<<"\nEntervol\n";cin>>Vol;cout<<"\nr\n";cin>>r;cout<<"\nNumberofpaths\n";cin>>NumberOfPaths;doubleresult=SimpleMonteCarlo1(Expiry,Strike,Spot,Vol,r,NumberOfPaths);cout<<"thepriceis"<<result<<"\n";doubletmp;cin>>tmp;return0;}OurprogramusestheauxiliaryfilesRandom1.handRandom1.cpp.Listing1.2(Random1.h)#ifndefRANDOM1_H#defineRANDOM1_HdoubleGetOneGaussianBySummation();doubleGetOneGaussianByBoxMuller();#endif1.3AsimpleimplementationofaMonteCarlocalloptionpricer5Listing1.3(Random1.cpp)#include<Random1.h>#include<cstdlib>#include<cmath>//thebasicmathfunctionsshouldbeinnamespace//stdbutaren’tinVCPP6#if!defined(_MSC_VER)usingnamespacestd;#endifdoubleGetOneGaussianBySummation(){doubleresult=0;for(unsignedlongj=0;j<12;j++)result+=rand()/static_cast<double>(RAND_MAX);result-=6.0;returnresult;}doubleGetOneGaussianByBoxMuller(){doubleresult;doublex;doubley;doublesizeSquared;do{x=2.0*rand()/static_cast<double>(RAND_MAX)-1;y=2.0*rand()/static_cast<double>(RAND_MAX)-1;sizeSquared=x*x+y*y;}while(sizeSquared>=1.0);6AsimpleMonteCarlomodelresult=x*sqrt(-2*log(sizeSquared)/sizeSquared);returnresult;}WefirstincludetheheaderfileRandom1.h.Notethattheprogramhas<Random1.h>ratherthan"Random1.h".Thismeansthatwehavesetourcom-pilersettingstolookforheaderfilesinthedirectorywhereRandom1.his.Inthiscase,thisisinthedirectoryC/

C++.Design.Patterns.and.Derivatives.Pricing(第二版).pdf

C++.Design.Patterns.and.Derivat…

上传者: along
638次下载 0人收藏 暂无简介 简介 2011-12-14 举报

简介:C++学习参考

ThispageintentionallyleftblankC++DESIGNPATTERNSANDDERIVATIVESPRICING2ndeditionDesignpatternsarethecutting-edgeparadigmforprogramminginobject-orientedlan-guages.HeretheyarediscussedinthecontextofimplementingfinancialmodelsinC++.AssumingonlyabasicknowledgeofC++andmathematicalfinance,thereaderistaughthowtoproducewell-designed,structured,reusablecodeviaconcreteexamples.Thisneweditionincludesseveralnewchaptersdescribinghowtoincreaserobustnessinthepresenceofexceptions,howtodesignagenericfactory,howtointerfaceC++withEXCEL,andhowtoimprovecodedesignusingtheideaofdecoupling.CompleteANSI/ISOcompatibleC++sourcecodeishostedonanaccompanyingwebsiteforthereadertostudyindetail,andreuseastheyseefit.AgoodunderstandingofC++designisanecessityforworkingfinancialmathemati-cian;thisbookprovidesathoroughintroductiontothetopic.Mathematics,FinanceandRiskEditorialBoardMarkBroadie,GraduateSchoolofBusiness,ColumbiaUniversitySamHowison,MathematicalInstitute,UniversityofOxfordNeilJohnson,CentreforComputationalFinance,UniversityofOxfordGeorgePapanicolaou,DepartmentofMathematics,StanfordUniversityC++DESIGNPATTERNSANDDERIVATIVESPRICINGM.S.JOSHIUniversityofMelbourneCAMBRIDGEUNIVERSITYPRESSCambridge,NewYork,Melbourne,Madrid,CapeTown,Singapore,SãoPauloCambridgeUniversityPressTheEdinburghBuilding,CambridgeCB28RU,UKFirstpublishedinprintformatISBN-13978-0-521-72162-2ISBN-13978-0-511-39693-9M.S.Joshi20082008Informationonthistitle:www.cambridge.org/9780521721622Thispublicationisincopyright.Subjecttostatutoryexceptionandtotheprovisionofrelevantcollectivelicensingagreements,noreproductionofanypartmaytakeplacewithoutthewrittenpermissionofCambridgeUniversityPress.CambridgeUniversityPresshasnoresponsibilityforthepersistenceoraccuracyofurlsforexternalorthird-partyinternetwebsitesreferredtointhispublication,anddoesnotguaranteethatanycontentonsuchwebsitesis,orwillremain,accurateorappropriate.PublishedintheUnitedStatesofAmericabyCambridgeUniversityPress,NewYorkwww.cambridge.orgeBook(NetLibrary)paperbackToJaneContentsPrefacepagexiiiAcknowledgementsxvi1AsimpleMonteCarlomodel11.1Introduction11.2Thetheory11.3AsimpleimplementationofaMonteCarlocalloptionpricer21.4CritiquingthesimpleMonteCarloroutine71.5Identifyingtheclasses91.6Whatwilltheclassesbuyus?101.7Whyobject-orientedprogramming?111.8Keypoints111.9Exercises122Encapsulation132.1Implementingthepay-offclass132.2Privacy152.3Usingthepay-offclass162.4Furtherextensibilitydefects192.5Theopen–closedprinciple202.6Keypoints212.7Exercises223Inheritanceandvirtualfunctions233.1‘isa’233.2Codinginheritance243.3Virtualfunctions243.4Whywemustpasstheinheritedobjectbyreference293.5Notknowingthetypeandvirtualdestruction303.6Addingextrapay-offswithoutchangingfiles34viiviiiContents3.7Keypoints373.8Exercises374Bridgingwithavirtualconstructor384.1Theproblem384.2Afirstsolution394.3Virtualconstruction434.4Theruleofthree514.5Thebridge534.6Bewareofnew574.7Aparametersclass584.8Keypoints654.9Exercises655Strategies,decoration,andstatistics665.1Differingoutputs665.2Designingastatisticsgatherer665.3Usingthestatisticsgatherer695.4Templatesandwrappers735.5Aconvergencetable775.6Decoration805.7Keypoints815.8Exercises816Arandomnumbersclass836.1Why?836.2Designconsiderations846.3Thebaseclass866.4Alinearcongruentialgeneratorandtheadapterpattern886.5Anti-theticsamplingviadecoration936.6Usingtherandomnumbergeneratorclass976.7Keypoints1026.8Exercises1027Anexoticsengineandthetemplatepattern1037.1Introduction1037.2Identifyingcomponents1047.3Communicationbetweenthecomponents1057.4Thebaseclasses1067.5ABlack–Scholespathgenerationengine1117.6AnarithmeticAsianoption1157.7Puttingitalltogether1177.8Keypoints1207.9Exercises120Contentsix8Trees1218.1Introduction1218.2Thedesign1238.3TheTreeProductclass1258.4Atreeclass1298.5Pricingonthetree1358.6Keypoints1398.7Exercises1399Solvers,templates,andimpliedvolatilities1419.1Theproblem1419.2Functionobjects1429.3Bisectingwithatemplate1459.4Newton–Raphsonandfunctiontemplatearguments1499.5UsingNewton–Raphsontodoimpliedvolatilities1519.6Theprosandconsoftemplatization1549.7Keypoints1569.8Exercises15610Thefactory15710.1Theproblem15710.2Thebasicidea15710.3Thesingletonpattern15810.4Codingthefactory15910.5Automaticregistration16210.6Usingthefactory16510.7Keypoints16610.8Exercises16711Designpatternsrevisited16811.1Introduction16811.2Creationalpatterns16811.3Structuralpatterns16911.4Behaviouralpatterns17011.5Whydesignpatterns?17111.6Furtherreading17211.7Keypoints17211.8Exercise17312Thesituationin200717412.1Introduction17412.2Compilersandthestandardlibrary17412.3Boost176xContents12.4QuantLib17712.5xlw17712.6Keypoints17812.7Exercises17813Exceptions17913.1Introduction17913.2Safetyguarantees18013.3Theuseofsmartpointers18013.4Theruleofalmostzero18313.5Commandstoneveruse18413.6Makingthewrapperclassexceptionsafe18513.7Throwinginspecialfunctions18613.8Floatingpointexceptions18713.9Keypoints19214Templatizingthefactory19714.1Introduction19714.2Usinginheritancetoaddstructure19714.3Thecuriouslyrecurringtemplatepattern19914.4Usingargumentlists20014.5TheprivatepartoftheArgumentListclass20614.6TheimplementationoftheArgumentList20814.7Cellmatrices22014.8CellsandtheArgumentLists22414.9Thetemplatefactory23214.10Usingthetemplatizedfactory23714.11Keypoints24214.12Exercises24315InterfacingwithEXCEL24415.1Introduction24415.2Usage24515.3Basicdatatypes24715.4Extendeddatatypes24815.5xlwcommands25015.6Theinterfacefile25015.7Theinterfacegenerator25315.8Troubleshooting25415.9Debuggingwithxlls25415.10Keypoints25515.11Exercises255Contentsxi16Decoupling25616.1Introduction25616.2Headerfiles25616.3Splittingfiles25916.4Directionofinformationflowandlevelization26016.5Classesasinsulators26216.6inlining26216.7Templatecode26316.8Functionalinterfaces26416.9Pimpls26416.10Keypoints26516.11Exercises265AppendixABlack–Scholesformulas266AppendixBDistributionfunctions270AppendixCAsimplearrayclass274C.1Choosinganarrayclass274C.2Asimplearrayclass275C.3Asimplearrayclass278AppendixDThecode285D.1Usingthecode285D.2Compilers285D.3License285AppendixEGlossary286Bibliography287Index289PrefaceThisbookisaimedatareaderwhohasstudiedanintroductorybookonmathemat-icalfinanceandanintroductorybookonC++butdoesnotknowhowtoputthetwotogether.MyobjectiveistoteachthereadernotjusthowtoimplementmodelsinC++butmoreimportantlyhowtothinkinanobject-orientedway.Therearealreadymanybooksonobject-orientedprogramming;however,theexamplestendnottofeelrealtothefinancialmathematiciansointhisbookweworkexclusivelywithexamplesfromderivativespricing.WedonotattempttocoverallsortsoffinancialmodelsbutinsteadexamineafewindepthwiththeobjectiveatalltimesofusingthemtoillustratecertainOOideas.Weproceedlargelybyexample,rewriting,ourdesignsasnewconceptsareintroduced,insteadofworkingoutagreatdesignatthestart.Whilstthisapproachisnotoptimalfromadesignstandpoint,itismorepedagogicallyaccessible.Anaspectofthisisthatourexamplesaredesignedtoemphasizedesignprinciplesratherthantoillustrateotherfeaturesofcoding,suchasnumericalefficiencyorexceptionsafety.WecommencebyintroducingasimpleMonteCarlomodelwhichdoesnotuseOOtechniquesbutratheristhesimplestproceduralmodelforpricingacalloptiononecouldwrite.Weexamineitsshortcomingsanddiscusshowclassesnaturallyarisefromtheconceptsinvolvedinitsconstruction.InChapter2,wemoveontotheconceptofencapsulation–theideathataclassallowstoexpressareal-worldanalogueanditsbehavioursprecisely.Inordertoillustrateencapsulation,welookathowaclasscanbedefinedforthepay-offofavanillaoption.Wealsoseethattheclasswehavedefinedhascertaindefects,andthisnaturallyleadsontotheopen–closedprinciple.InChapter3,weseehowabetterpay-offclasscanbedefinedbyusinginheri-tanceandvirtualfunctions.Thisraisestechnicalissuesinvolvingdestructionandpassingarguments,whichweaddress.Wealsoseehowthisapproachiscompatiblewiththeopen–closedprinciple.xiiixivPrefaceUsingvirtualfunctionscausesproblemsregardingthecopyingofobjectsofun-knowntype,andinChapter4weaddresstheseproblems.Wedosobyintroducingvirtualconstructorsandthebridgepattern.Wedigresstodiscussthe‘ruleofthree’andtheslownessofnew.Theideasareillustratedviaavanillaoptionsclassandaparametersclass.Withthesenewtechniquesatourdisposal,wemoveontolookingatmorecom-plicateddesignpatternsinChapter5.Wefirstintroducethestrategypatternthatexpressestheideathatdecisionsonpartofanalgorithmcanbedeferredbydele-gatingresponsibilitiestoanauxiliaryclass.Wethenlookathowtemplatescanbeusedtowriteawrapperclassthatremovesalotofourdifficultieswithmemoryhandling.Asanapplicationofthesetechniques,wedevelopaconvergencetableusingthedecoratorpattern.InChapter6,welookathowtodeveloparandomnumbersclass.Wefirstexam-inewhyweneedaclassandthendevelopasimpleimplementationwhichprovidesareusableinterfaceandanadequaterandomnumbergenerator.Weusetheimple-mentationtointroduceandillustratetheadapterpattern,andtoexaminefurtherthedecoratorpattern.Wemoveontoourfirstnon-trivialapplicationinChapter7,whereweusetheclassesdevelopedsofarintheimplementationofaMonteCarlopricerforpath-dependentexoticderivatives.Aspartofthisdesign,weintroduceandusethetem-platepattern.WefinishwiththepricingofAsianoptions.WeshiftfromMonteCarlototreesinChapter8.Weseethesimilaritiesanddifferencesbetweenthetwotechniques,andimplementareusabledesign.Aspartofthedesign,wereusesomeoftheclassesdevelopedearlierforMonteCarlo.WereturntothetopicoftemplatesinChapter9.Weillustratetheirusebydesign-ingreusablesolverclasses.Theseclassesarethenusedtodefineimpliedvolatilityfunctions.Enroute,welookatfunctionobjectsandpointerstomemberfunctions.Wefinishwithadiscussionoftheprosandconsoftemplatization.InChapter10,welookatourmostadvancedtopic:thefactorypattern.Thispatternsallowstheadditionofnewfunctionalitytoaprogramwithoutchanginganyexistingfiles.Aspartofthedesign,weintroducethesingletonpattern.WepauseinChapter11toclassify,summarize,anddiscussthedesignpatternswehaveintroduced.Inparticular,weseehowtheycanbedividedintocreational,structural,andbehaviouralpatterns.Wealsoreviewtheliteratureondesignpatternstogivethereaderaguideforfurtherstudy.Thefinalfourchaptersarenewforthesecondedition.Intheseourfocusisdifferent:ratherthanfocussingexclusivelyondesignpatterns,welookatsomeotherimportantaspectsofgoodcodingthatneophytestoC++tendtobeunawareof.PrefacexvInChapter12,wetakeahistoricallookatthesituationin2007andatwhathaschangedinrecentyearsbothinC++andthefinancialengineeringcommunity’suseofit.ThestudyofexceptionsafetyisthetopicofChapter13.Weseehowmakingtherequirementthatcodefunctionswellinthepresenceofexceptionsplacesalargenumberofconstraintsonstyle.Weintroducesomeeasytechniquestodealwiththeseconstraints.InChapter14,wereturntothefactorypattern.Theoriginalfactorypatternre-quiredustowritesimilarcodeeverytimeweintroducedanewclasshierarchy;wenowseehow,byusingargumentlistsandtemplates,afullygeneralfactoryclasscanbecodedandreusedforever.InChapter15,welookatsomethingratherdifferentthatisveryimportantinday-to-dayworkforaquant:interfacingwithEXCEL.Inparticular,weexaminethexlwpackageforbuildingxlls.ThispackagecontainsallthecodenecessarytoexposeaC++functiontoEXCEL,andevencontainsaparsertowritethenewcoderequiredforeachfunction.TheconceptofphysicaldesignisintroducedinChapter16.Weseehowtheobjectiveofreducingcompiletimescanaffectourcodeorganizationanddesign.Thecodefortheexamplesinthefirst11chaptersofthisbookcanbefreelydownloadedfromwww.markjoshi.com/design,andanybugfixeswillbepostedthere.Thecodefortheremainingchaptersistakenfromthexlwprojectandcanbedownloadedfromxlw.sourceforge.net.Allexamplecodeistakenfromrelease2.1.AcknowledgementsIamgratefultotheRoyalBankofScotlandforprovidingastimulatingenviron-mentinwhichtolearn,studyanddomathematicalfinance.MostofmyviewsoncodingC++andfinancialmodellinghavebeendevelopedduringmytimework-ingthere.MyunderstandingofthetopichasbeenformedthroughdailydiscussionswithcurrentandformercolleaguesincludingChrisHunter,PeterJackel,Dhermin-derKainth,SukhdeepMahal,RobinNicholsonandJochenTheis.Iamalsograte-fultoahostofpeoplefortheirmanycommentsonthemanuscript,includingAlexBarnard,DherminderKainth,RobKitching,SukhdeepMahal,NadimMahassen,HughMcBride,AlanStaceyandPatrikSundberg.IwouldalsoliketothankDavidTranahandtherestoftheteamatCambridgeUniversityPressfortheircarefulworkandattentiontodetail.Finallymywifehasbeenverysupportive.Iamgratefultoanumberofpeoplefortheircommentsonthesecondedi-tion,withparticularthankstoChrisBeveridge,NarinderClaire,NickDensonandLorenzoLiesch.xvi1AsimpleMonteCarlomodel1.1IntroductionInthefirstpartofthisbook,weshallstudythepricingofderivativesusingMonteCarlosimulation.WedothisnottostudytheintricaciesofMonteCarlobutbecauseitprovidesmanyconvenientexamplesofconceptsthatcanbeabstracted.Wepro-ceedbyexample,thatiswefirstgiveasimpleprogram,discussitsgoodpoints,itsshortcomings,variouswaysroundthemandthenmoveontoanewexample.Wecarryoutthisprocedurerepeatedlyandeventuallyendupwithafancyprogram.WebeginwitharoutinetopricevanillacalloptionsbyMonteCarlo.1.2ThetheoryWecommencebydiscussingthetheory.ThemodelforstockpriceevolutionisdSt=µStdt+σStdWt,(1.1)andarisklessbond,B,growsatacontinuouslycompoundingrater.TheBlack–Scholespricingtheorythentellsusthatthepriceofavanillaoption,withexpiryTandpay-offf,isequaltoerTE(f(ST)),wheretheexpectationistakenundertheassociatedrisk-neutralprocess,dSt=rStdt+σStdWt.(1.2)Wesolveequation(1.2)bypassingtothelogandusingIto’slemma;wecomputedlogSt=(r12σ2)dt+σdWt.(1.3)Asthisprocessisconstant-coefficient,ithasthesolutionlogSt=logS0+(r12σ2)t+σWt.(1.4)12AsimpleMonteCarlomodelSinceWtisaBrownianmotion,WTisdistributedasaGaussianwithmeanzeroandvarianceT,sowecanwriteWT=TN(0,1),(1.5)andhencelogST=logS0+(r12σ2)T+σTN(0,1),(1.6)orequivalently,ST=S0e(r12σ2)T+σTN(0,1).(1.7)ThepriceofavanillaoptionisthereforeequaltoerTE(f(S0e(r12σ2)T+σTN(0,1))).TheobjectiveofourMonteCarlosimulationistoapproximatethisexpectationbyusingthelawoflargenumbers,whichtellsusthatifYjareasequenceofidenticallydistributedindependentrandomvariables,thenwithprobability1thesequence1NNj=1YjconvergestoE(Y1).SothealgorithmtopriceacalloptionbyMonteCarloisclear.Wedrawarandomvariable,x,fromanN(0,1)distributionandcomputef(S0e(r12σ2)T+σTx),wheref(S)=(SK)+.Wedothismanytimesandtaketheaverage.WethenmultiplythisaveragebyerTandwearedone.1.3AsimpleimplementationofaMonteCarlocalloptionpricerAfirstimplementationisgivenintheprogramSimpleMCMain1.cpp.Listing1.1(SimpleMCMain1.cpp)//requiresRandom1.cpp#include<Random1.h>#include<iostream>#include<cmath>usingnamespacestd;1.3AsimpleimplementationofaMonteCarlocalloptionpricer3doubleSimpleMonteCarlo1(doubleExpiry,doubleStrike,doubleSpot,doubleVol,doubler,unsignedlongNumberOfPaths){doublevariance=Vol*Vol*Expiry;doublerootVariance=sqrt(variance);doubleitoCorrection=-0.5*variance;doublemovedSpot=Spot*exp(r*Expiry+itoCorrection);doublethisSpot;doublerunningSum=0;for(unsignedlongi=0;i<NumberOfPaths;i++){doublethisGaussian=GetOneGaussianByBoxMuller();thisSpot=movedSpot*exp(rootVariance*thisGaussian);doublethisPayoff=thisSpot-Strike;thisPayoff=thisPayoff>0?thisPayoff:0;runningSum+=thisPayoff;}doublemean=runningSum/NumberOfPaths;mean*=exp(-r*Expiry);returnmean;}intmain(){doubleExpiry;doubleStrike;doubleSpot;doubleVol;doubler;unsignedlongNumberOfPaths;cout<<"\nEnterexpiry\n";cin>>Expiry;4AsimpleMonteCarlomodelcout<<"\nEnterstrike\n";cin>>Strike;cout<<"\nEnterspot\n";cin>>Spot;cout<<"\nEntervol\n";cin>>Vol;cout<<"\nr\n";cin>>r;cout<<"\nNumberofpaths\n";cin>>NumberOfPaths;doubleresult=SimpleMonteCarlo1(Expiry,Strike,Spot,Vol,r,NumberOfPaths);cout<<"thepriceis"<<result<<"\n";doubletmp;cin>>tmp;return0;}OurprogramusestheauxiliaryfilesRandom1.handRandom1.cpp.Listing1.2(Random1.h)#ifndefRANDOM1_H#defineRANDOM1_HdoubleGetOneGaussianBySummation();doubleGetOneGaussianByBoxMuller();#endif1.3AsimpleimplementationofaMonteCarlocalloptionpricer5Listing1.3(Random1.cpp)#include<Random1.h>#include<cstdlib>#include<cmath>//thebasicmathfunctionsshouldbeinnamespace//stdbutaren’tinVCPP6#if!defined(_MSC_VER)usingnamespacestd;#endifdoubleGetOneGaussianBySummation(){doubleresult=0;for(unsignedlongj=0;j<12;j++)result+=rand()/static_cast<double>(RAND_MAX);result-=6.0;returnresult;}doubleGetOneGaussianByBoxMuller(){doubleresult;doublex;doubley;doublesizeSquared;do{x=2.0*rand()/static_cast<double>(RAND_MAX)-1;y=2.0*rand()/static_cast<double>(RAND_MAX)-1;sizeSquared=x*x+y*y;}while(sizeSquared>=1.0);6AsimpleMonteCarlomodelresult=x*sqrt(-2*log(sizeSquared)/sizeSquared);returnresult;}WefirstincludetheheaderfileRandom1.h.Notethattheprogramhas<Random1.h>ratherthan"Random1.h".Thismeansthatwehavesetourcom-pilersettingstolookforheaderfilesinthedirectorywhereRandom1.his.Inthiscase,thisisinthedirectoryC/
  • 相关资料
  • 该用户的其他资料
  • 名称/格式
  • 下载次数
  • 资料大小
  • 名称/格式
  • 下载次数
  • 资料大小

用户评论(1)

0/200
上传我的资料
关闭

请选择举报的类型

关闭

提示

提交成功!

感谢您对爱问共享资料的支持,我们将尽快核实并处理您的举报信息。

关闭

提示

提交失败!

您的举报信息提交失败,请重试!

关闭

提示

重复举报!

亲爱的用户!感觉您对爱问共享资料的支持,请勿重复举报噢!

全屏 缩小 放大
收藏
资料评价:

/ 310
所需积分:1 立即下载
返回
顶部
举报
资料
关闭

温馨提示

感谢您对爱问共享资料的支持,精彩活动将尽快为您呈现,敬请期待!