首页 C++.Design.Patterns.and.Derivatives.Pricing(第二版…

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

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

上传者: along 2011-12-14 评分1 评论1 下载639 收藏0 阅读量1602 暂无简介 简介 举报

简介:本文档为《C++.Design.Patterns.and.Derivatives.Pricing(第二版)pdf》,可适用于源代码领域,主题内容包含ThispageintentionallyleftblankCDESIGNPATTERNSANDDERIVATIVESPRICINGndeditio符等。

ThispageintentionallyleftblankCDESIGNPATTERNSANDDERIVATIVESPRICINGndeditionDesignpatternsarethecuttingedgeparadigmforprogramminginobjectorientedlanguagesHeretheyarediscussedinthecontextofimplementingfinancialmodelsinCAssumingonlyabasicknowledgeofCandmathematicalfinance,thereaderistaughthowtoproducewelldesigned,structured,reusablecodeviaconcreteexamplesThisneweditionincludesseveralnewchaptersdescribinghowtoincreaserobustnessinthepresenceofexceptions,howtodesignagenericfactory,howtointerfaceCwithEXCEL,andhowtoimprovecodedesignusingtheideaofdecouplingCompleteANSIISOcompatibleCsourcecodeishostedonanaccompanyingwebsiteforthereadertostudyindetail,andreuseastheyseefitAgoodunderstandingofCdesignisanecessityforworkingfinancialmathematicianthisbookprovidesathoroughintroductiontothetopicMathematics,FinanceandRiskEditorialBoardMarkBroadie,GraduateSchoolofBusiness,ColumbiaUniversitySamHowison,MathematicalInstitute,UniversityofOxfordNeilJohnson,CentreforComputationalFinance,UniversityofOxfordGeorgePapanicolaou,DepartmentofMathematics,StanfordUniversityCDESIGNPATTERNSANDDERIVATIVESPRICINGMSJOSHIUniversityofMelbourneCAMBRIDGEUNIVERSITYPRESSCambridge,NewYork,Melbourne,Madrid,CapeTown,Singapore,SãoPauloCambridgeUniversityPressTheEdinburghBuilding,CambridgeCBRU,UKFirstpublishedinprintformatISBNISBNMSJoshiInformationonthistitle:wwwcambridgeorgThispublicationisincopyrightSubjecttostatutoryexceptionandtotheprovisionofrelevantcollectivelicensingagreements,noreproductionofanypartmaytakeplacewithoutthewrittenpermissionofCambridgeUniversityPressCambridgeUniversityPresshasnoresponsibilityforthepersistenceoraccuracyofurlsforexternalorthirdpartyinternetwebsitesreferredtointhispublication,anddoesnotguaranteethatanycontentonsuchwebsitesis,orwillremain,accurateorappropriatePublishedintheUnitedStatesofAmericabyCambridgeUniversityPress,NewYorkwwwcambridgeorgeBook(NetLibrary)paperbackToJaneContentsPrefacepagexiiiAcknowledgementsxviAsimpleMonteCarlomodelIntroductionThetheoryAsimpleimplementationofaMonteCarlocalloptionpricerCritiquingthesimpleMonteCarloroutineIdentifyingtheclassesWhatwilltheclassesbuyusWhyobjectorientedprogrammingKeypointsExercisesEncapsulationImplementingthepayoffclassPrivacyUsingthepayoffclassFurtherextensibilitydefectsTheopen–closedprincipleKeypointsExercisesInheritanceandvirtualfunctions‘isa’CodinginheritanceVirtualfunctionsWhywemustpasstheinheritedobjectbyreferenceNotknowingthetypeandvirtualdestructionAddingextrapayoffswithoutchangingfilesviiviiiContentsKeypointsExercisesBridgingwithavirtualconstructorTheproblemAfirstsolutionVirtualconstructionTheruleofthreeThebridgeBewareofnewAparametersclassKeypointsExercisesStrategies,decoration,andstatisticsDifferingoutputsDesigningastatisticsgathererUsingthestatisticsgathererTemplatesandwrappersAconvergencetableDecorationKeypointsExercisesArandomnumbersclassWhyDesignconsiderationsThebaseclassAlinearcongruentialgeneratorandtheadapterpatternAntitheticsamplingviadecorationUsingtherandomnumbergeneratorclassKeypointsExercisesAnexoticsengineandthetemplatepatternIntroductionIdentifyingcomponentsCommunicationbetweenthecomponentsThebaseclassesABlack–ScholespathgenerationengineAnarithmeticAsianoptionPuttingitalltogetherKeypointsExercisesContentsixTreesIntroductionThedesignTheTreeProductclassAtreeclassPricingonthetreeKeypointsExercisesSolvers,templates,andimpliedvolatilitiesTheproblemFunctionobjectsBisectingwithatemplateNewton–RaphsonandfunctiontemplateargumentsUsingNewton–RaphsontodoimpliedvolatilitiesTheprosandconsoftemplatizationKeypointsExercisesThefactoryTheproblemThebasicideaThesingletonpatternCodingthefactoryAutomaticregistrationUsingthefactoryKeypointsExercisesDesignpatternsrevisitedIntroductionCreationalpatternsStructuralpatternsBehaviouralpatternsWhydesignpatternsFurtherreadingKeypointsExerciseThesituationinIntroductionCompilersandthestandardlibraryBoostxContentsQuantLibxlwKeypointsExercisesExceptionsIntroductionSafetyguaranteesTheuseofsmartpointersTheruleofalmostzeroCommandstoneveruseMakingthewrapperclassexceptionsafeThrowinginspecialfunctionsFloatingpointexceptionsKeypointsTemplatizingthefactoryIntroductionUsinginheritancetoaddstructureThecuriouslyrecurringtemplatepatternUsingargumentlistsTheprivatepartoftheArgumentListclassTheimplementationoftheArgumentListCellmatricesCellsandtheArgumentListsThetemplatefactoryUsingthetemplatizedfactoryKeypointsExercisesInterfacingwithEXCELIntroductionUsageBasicdatatypesExtendeddatatypesxlwcommandsTheinterfacefileTheinterfacegeneratorTroubleshootingDebuggingwithxllsKeypointsExercisesContentsxiDecouplingIntroductionHeaderfilesSplittingfilesDirectionofinformationflowandlevelizationClassesasinsulatorsinliningTemplatecodeFunctionalinterfacesPimplsKeypointsExercisesAppendixABlack–ScholesformulasAppendixBDistributionfunctionsAppendixCAsimplearrayclassCChoosinganarrayclassCAsimplearrayclassCAsimplearrayclassAppendixDThecodeDUsingthecodeDCompilersDLicenseAppendixEGlossaryBibliographyIndexPrefaceThisbookisaimedatareaderwhohasstudiedanintroductorybookonmathematicalfinanceandanintroductorybookonCbutdoesnotknowhowtoputthetwotogetherMyobjectiveistoteachthereadernotjusthowtoimplementmodelsinCbutmoreimportantlyhowtothinkinanobjectorientedwayTherearealreadymanybooksonobjectorientedprogramminghowever,theexamplestendnottofeelrealtothefinancialmathematiciansointhisbookweworkexclusivelywithexamplesfromderivativespricingWedonotattempttocoverallsortsoffinancialmodelsbutinsteadexamineafewindepthwiththeobjectiveatalltimesofusingthemtoillustratecertainOOideasWeproceedlargelybyexample,rewriting,ourdesignsasnewconceptsareintroduced,insteadofworkingoutagreatdesignatthestartWhilstthisapproachisnotoptimalfromadesignstandpoint,itismorepedagogicallyaccessibleAnaspectofthisisthatourexamplesaredesignedtoemphasizedesignprinciplesratherthantoillustrateotherfeaturesofcoding,suchasnumericalefficiencyorexceptionsafetyWecommencebyintroducingasimpleMonteCarlomodelwhichdoesnotuseOOtechniquesbutratheristhesimplestproceduralmodelforpricingacalloptiononecouldwriteWeexamineitsshortcomingsanddiscusshowclassesnaturallyarisefromtheconceptsinvolvedinitsconstructionInChapter,wemoveontotheconceptofencapsulation–theideathataclassallowstoexpressarealworldanalogueanditsbehaviourspreciselyInordertoillustrateencapsulation,welookathowaclasscanbedefinedforthepayoffofavanillaoptionWealsoseethattheclasswehavedefinedhascertaindefects,andthisnaturallyleadsontotheopen–closedprincipleInChapter,weseehowabetterpayoffclasscanbedefinedbyusinginheritanceandvirtualfunctionsThisraisestechnicalissuesinvolvingdestructionandpassingarguments,whichweaddressWealsoseehowthisapproachiscompatiblewiththeopen–closedprinciplexiiixivPrefaceUsingvirtualfunctionscausesproblemsregardingthecopyingofobjectsofunknowntype,andinChapterweaddresstheseproblemsWedosobyintroducingvirtualconstructorsandthebridgepatternWedigresstodiscussthe‘ruleofthree’andtheslownessofnewTheideasareillustratedviaavanillaoptionsclassandaparametersclassWiththesenewtechniquesatourdisposal,wemoveontolookingatmorecomplicateddesignpatternsinChapterWefirstintroducethestrategypatternthatexpressestheideathatdecisionsonpartofanalgorithmcanbedeferredbydelegatingresponsibilitiestoanauxiliaryclassWethenlookathowtemplatescanbeusedtowriteawrapperclassthatremovesalotofourdifficultieswithmemoryhandlingAsanapplicationofthesetechniques,wedevelopaconvergencetableusingthedecoratorpatternInChapter,welookathowtodeveloparandomnumbersclassWefirstexaminewhyweneedaclassandthendevelopasimpleimplementationwhichprovidesareusableinterfaceandanadequaterandomnumbergeneratorWeusetheimplementationtointroduceandillustratetheadapterpattern,andtoexaminefurtherthedecoratorpatternWemoveontoourfirstnontrivialapplicationinChapter,whereweusetheclassesdevelopedsofarintheimplementationofaMonteCarlopricerforpathdependentexoticderivativesAspartofthisdesign,weintroduceandusethetemplatepatternWefinishwiththepricingofAsianoptionsWeshiftfromMonteCarlototreesinChapterWeseethesimilaritiesanddifferencesbetweenthetwotechniques,andimplementareusabledesignAspartofthedesign,wereusesomeoftheclassesdevelopedearlierforMonteCarloWereturntothetopicoftemplatesinChapterWeillustratetheirusebydesigningreusablesolverclassesTheseclassesarethenusedtodefineimpliedvolatilityfunctionsEnroute,welookatfunctionobjectsandpointerstomemberfunctionsWefinishwithadiscussionoftheprosandconsoftemplatizationInChapter,welookatourmostadvancedtopic:thefactorypatternThispatternsallowstheadditionofnewfunctionalitytoaprogramwithoutchanginganyexistingfilesAspartofthedesign,weintroducethesingletonpatternWepauseinChaptertoclassify,summarize,anddiscussthedesignpatternswehaveintroducedInparticular,weseehowtheycanbedividedintocreational,structural,andbehaviouralpatternsWealsoreviewtheliteratureondesignpatternstogivethereaderaguideforfurtherstudyThefinalfourchaptersarenewforthesecondeditionIntheseourfocusisdifferent:ratherthanfocussingexclusivelyondesignpatterns,welookatsomeotherimportantaspectsofgoodcodingthatneophytestoCtendtobeunawareofPrefacexvInChapter,wetakeahistoricallookatthesituationinandatwhathaschangedinrecentyearsbothinCandthefinancialengineeringcommunity’suseofitThestudyofexceptionsafetyisthetopicofChapterWeseehowmakingtherequirementthatcodefunctionswellinthepresenceofexceptionsplacesalargenumberofconstraintsonstyleWeintroducesomeeasytechniquestodealwiththeseconstraintsInChapter,wereturntothefactorypatternTheoriginalfactorypatternrequiredustowritesimilarcodeeverytimeweintroducedanewclasshierarchywenowseehow,byusingargumentlistsandtemplates,afullygeneralfactoryclasscanbecodedandreusedforeverInChapter,welookatsomethingratherdifferentthatisveryimportantindaytodayworkforaquant:interfacingwithEXCELInparticular,weexaminethexlwpackageforbuildingxllsThispackagecontainsallthecodenecessarytoexposeaCfunctiontoEXCEL,andevencontainsaparsertowritethenewcoderequiredforeachfunctionTheconceptofphysicaldesignisintroducedinChapterWeseehowtheobjectiveofreducingcompiletimescanaffectourcodeorganizationanddesignThecodefortheexamplesinthefirstchaptersofthisbookcanbefreelydownloadedfromwwwmarkjoshicomdesign,andanybugfixeswillbepostedthereThecodefortheremainingchaptersistakenfromthexlwprojectandcanbedownloadedfromxlwsourceforgenetAllexamplecodeistakenfromreleaseAcknowledgementsIamgratefultotheRoyalBankofScotlandforprovidingastimulatingenvironmentinwhichtolearn,studyanddomathematicalfinanceMostofmyviewsoncodingCandfinancialmodellinghavebeendevelopedduringmytimeworkingthereMyunderstandingofthetopichasbeenformedthroughdailydiscussionswithcurrentandformercolleaguesincludingChrisHunter,PeterJackel,DherminderKainth,SukhdeepMahal,RobinNicholsonandJochenTheisIamalsogratefultoahostofpeoplefortheirmanycommentsonthemanuscript,includingAlexBarnard,DherminderKainth,RobKitching,SukhdeepMahal,NadimMahassen,HughMcBride,AlanStaceyandPatrikSundbergIwouldalsoliketothankDavidTranahandtherestoftheteamatCambridgeUniversityPressfortheircarefulworkandattentiontodetailFinallymywifehasbeenverysupportiveIamgratefultoanumberofpeoplefortheircommentsonthesecondedition,withparticularthankstoChrisBeveridge,NarinderClaire,NickDensonandLorenzoLieschxviAsimpleMonteCarlomodelIntroductionInthefirstpartofthisbook,weshallstudythepricingofderivativesusingMonteCarlosimulationWedothisnottostudytheintricaciesofMonteCarlobutbecauseitprovidesmanyconvenientexamplesofconceptsthatcanbeabstractedWeproceedbyexample,thatiswefirstgiveasimpleprogram,discussitsgoodpoints,itsshortcomings,variouswaysroundthemandthenmoveontoanewexampleWecarryoutthisprocedurerepeatedlyandeventuallyendupwithafancyprogramWebeginwitharoutinetopricevanillacalloptionsbyMonteCarloThetheoryWecommencebydiscussingthetheoryThemodelforstockpriceevolutionisdSt=µStdtσStdWt,()andarisklessbond,B,growsatacontinuouslycompoundingraterTheBlack–Scholespricingtheorythentellsusthatthepriceofavanillaoption,withexpiryTandpayofff,isequaltoerTE(f(ST)),wheretheexpectationistakenundertheassociatedriskneutralprocess,dSt=rStdtσStdWt()Wesolveequation()bypassingtothelogandusingIto’slemmawecomputedlogSt=(rσ)dtσdWt()Asthisprocessisconstantcoefficient,ithasthesolutionlogSt=logS(rσ)tσWt()AsimpleMonteCarlomodelSinceWtisaBrownianmotion,WTisdistributedasaGaussianwithmeanzeroandvarianceT,sowecanwriteWT=TN(,),()andhencelogST=logS(rσ)TσTN(,),()orequivalently,ST=Se(rσ)TσTN(,)()ThepriceofavanillaoptionisthereforeequaltoerTE(f(Se(rσ)TσTN(,)))TheobjectiveofourMonteCarlosimulationistoapproximatethisexpectationbyusingthelawoflargenumbers,whichtellsusthatifYjareasequenceofidenticallydistributedindependentrandomvariables,thenwithprobabilitythesequenceNNj=YjconvergestoE(Y)SothealgorithmtopriceacalloptionbyMonteCarloisclearWedrawarandomvariable,x,fromanN(,)distributionandcomputef(Se(rσ)TσTx),wheref(S)=(SK)WedothismanytimesandtaketheaverageWethenmultiplythisaveragebyerTandwearedoneAsimpleimplementationofaMonteCarlocalloptionpricerAfirstimplementationisgivenintheprogramSimpleMCMaincppListing(SimpleMCMaincpp)requiresRandomcpp#include<Randomh>#include<iostream>#include<cmath>usingnamespacestdAsimpleimplementationofaMonteCarlocalloptionpricerdoubleSimpleMonteCarlo(doubleExpiry,doubleStrike,doubleSpot,doubleVol,doubler,unsignedlongNumberOfPaths){doublevariance=Vol*Vol*ExpirydoublerootVariance=sqrt(variance)doubleitoCorrection=*variancedoublemovedSpot=Spot*exp(r*ExpiryitoCorrection)doublethisSpotdoublerunningSum=for(unsignedlongi=i<NumberOfPathsi){doublethisGaussian=GetOneGaussianByBoxMuller()thisSpot=movedSpot*exp(rootVariance*thisGaussian)doublethisPayoff=thisSpotStrikethisPayoff=thisPayoff>thisPayoff:runningSum=thisPayoff}doublemean=runningSumNumberOfPathsmean*=exp(r*Expiry)returnmean}intmain(){doubleExpirydoubleStrikedoubleSpotdoubleVoldoublerunsignedlongNumberOfPathscout<<"nEnterexpiryn"cin>>ExpiryAsimpleMonteCarlomodelcout<<"nEnterstriken"cin>>Strikecout<<"nEnterspotn"cin>>Spotcout<<"nEntervoln"cin>>Volcout<<"nrn"cin>>rcout<<"nNumberofpathsn"cin>>NumberOfPathsdoubleresult=SimpleMonteCarlo(Expiry,Strike,Spot,Vol,r,NumberOfPaths)cout<<"thepriceis"<<result<<"n"doubletmpcin>>tmpreturn}OurprogramusestheauxiliaryfilesRandomhandRandomcppListing(Randomh)#ifndefRANDOMH#defineRANDOMHdoubleGetOneGaussianBySummation()doubleGetOneGaussianByBoxMuller()#endifAsimpleimplementationofaMonteCarlocalloptionpricerListing(Randomcpp)#include<Randomh>#include<cstdlib>#include<cmath>thebasicmathfunctionsshouldbeinnamespacestdbutaren’tinVCPP#if!defined(MSCVER)usingnamespacestd#endifdoubleGetOneGaussianBySummation(){doubleresult=for(unsignedlongj=j<j)result=rand()staticcast<double>(RANDMAX)result=returnresult}doubleGetOneGaussianByBoxMuller(){doubleresultdoublexdoubleydoublesizeSquareddo{x=*rand()staticcast<double>(RANDMAX)y=*rand()staticcast<double>(RANDMAX)sizeSquared=x*xy*y}while(sizeSquared>=)AsimpleMonteCarlomodelresult=x*sqrt(*log(sizeSquared)sizeSquared)returnresult}WefirstincludetheheaderfileRandomhNotethattheprogramhas<Randomh>ratherthan"Randomh"ThismeansthatwehavesetourcompilersettingstolookforheaderfilesinthedirectorywhereRandomhisInthiscase,thisisinthedirectoryC

职业精品

分销渠道选择.ppt

辞职申请书(优质范文).doc

公司年检申请书doc.doc

厂家和经销商代理合同.doc

用户评论(1)

0/200
上传我的资料

精彩专题

相关资料换一换

资料评价:

/ 310
所需积分:1 立即下载

意见
反馈

返回
顶部