C++:实现量化设置期限结构,然后确定价格如“价格收益率”或“收益率价格”测试实例


#include <ql/qldefines.hpp>
#if !defined(BOOST_ALL_NO_LIB) && defined(BOOST_MSVC)
#  include <ql/auto_link.hpp>
#endif
#include <ql/instruments/bonds/zerocouponbond.hpp>
#include <ql/instruments/bonds/floatingratebond.hpp>
#include <ql/pricingengines/bond/discountingbondengine.hpp>
#include <ql/cashflows/couponpricer.hpp>
#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>
#include <ql/termstructures/yield/bondhelpers.hpp>
#include <ql/termstructures/volatility/optionlet/constantoptionletvol.hpp>
#include <ql/indexes/ibor/euribor.hpp>
#include <ql/indexes/ibor/usdlibor.hpp>
#include <ql/time/calendars/target.hpp>
#include <ql/time/calendars/unitedstates.hpp>
#include <ql/time/daycounters/actualactual.hpp>
#include <ql/time/daycounters/actual360.hpp>
#include <ql/time/daycounters/thirty360.hpp>#include <iostream>
#include <iomanip>using namespace QuantLib;int main(int, char* []) {try {std::cout << std::endl;/************************  MARKET DATA  ************************/Calendar calendar = TARGET();Date settlementDate(18, September, 2008);// must be a business daysettlementDate = calendar.adjust(settlementDate);Integer fixingDays = 3;Natural settlementDays = 3;Date todaysDate = calendar.advance(settlementDate, -fixingDays, Days);// nothing to do with Date::todaysDateSettings::instance().evaluationDate() = todaysDate;std::cout << "Today: " << todaysDate.weekday()<< ", " << todaysDate << std::endl;std::cout << "Settlement date: " << settlementDate.weekday()<< ", " << settlementDate << std::endl;// Building of the bonds discounting yield curve/************************  RATE HELPERS ************************/// RateHelpers are built from the above quotes together with// other instrument dependant infos.  Quotes are passed in// relinkable handles which could be relinked to some other// data source later.// Common data// ZC rates for the short endRate zc3mQuote=0.0096;Rate zc6mQuote=0.0145;Rate zc1yQuote=0.0194;ext::shared_ptr<Quote> zc3mRate(new SimpleQuote(zc3mQuote));ext::shared_ptr<Quote> zc6mRate(new SimpleQuote(zc6mQuote));ext::shared_ptr<Quote> zc1yRate(new SimpleQuote(zc1yQuote));DayCounter zcBondsDayCounter = Actual365Fixed();ext::shared_ptr<RateHelper> zc3m(new DepositRateHelper(Handle<Quote>(zc3mRate),3*Months, fixingDays,calendar, ModifiedFollowing,true, zcBondsDayCounter));ext::shared_ptr<RateHelper> zc6m(new DepositRateHelper(Handle<Quote>(zc6mRate),6*Months, fixingDays,calendar, ModifiedFollowing,true, zcBondsDayCounter));ext::shared_ptr<RateHelper> zc1y(new DepositRateHelper(Handle<Quote>(zc1yRate),1*Years, fixingDays,calendar, ModifiedFollowing,true, zcBondsDayCounter));// setup bondsReal redemption = 100.0;const Size numberOfBonds = 5;Date issueDates[] = {Date (15, March, 2005),Date (15, June, 2005),Date (30, June, 2006),Date (15, November, 2002),Date (15, May, 1987)};Date maturities[] = {Date (31, August, 2010),Date (31, August, 2011),Date (31, August, 2013),Date (15, August, 2018),Date (15, May, 2038)};Real couponRates[] = {0.02375,0.04625,0.03125,0.04000,0.04500};Real marketQuotes[] = {100.390625,106.21875,100.59375,101.6875,102.140625};std::vector< ext::shared_ptr<SimpleQuote> > quote;for (Real marketQuote : marketQuotes) {ext::shared_ptr<SimpleQuote> cp(new SimpleQuote(marketQuote));quote.push_back(cp);}RelinkableHandle<Quote> quoteHandle[numberOfBonds];for (Size i=0; i<numberOfBonds; i++) {quoteHandle[i].linkTo(quote[i]);}// Definition of the rate helpersstd::vector<ext::shared_ptr<BondHelper> > bondsHelpers;for (Size i=0; i<numberOfBonds; i++) {Schedule schedule(issueDates[i], maturities[i], Period(Semiannual), UnitedStates(UnitedStates::GovernmentBond),Unadjusted, Unadjusted, DateGeneration::Backward, false);ext::shared_ptr<FixedRateBondHelper> bondHelper(new FixedRateBondHelper(quoteHandle[i],settlementDays,100.0,schedule,std::vector<Rate>(1,couponRates[i]),ActualActual(ActualActual::Bond),Unadjusted,redemption,issueDates[i]));// the above could also be done by creating a// FixedRateBond instance and writing://// ext::shared_ptr<BondHelper> bondHelper(//         new BondHelper(quoteHandle[i], bond));//// This would also work for bonds that still don't have a// specialized helper, such as floating-rate bonds.bondsHelpers.push_back(bondHelper);}/***********************  CURVE BUILDING ***********************/// Any DayCounter would be fine.// ActualActual::ISDA ensures that 30 years is 30.0DayCounter termStructureDayCounter =ActualActual(ActualActual::ISDA);// A depo-bond curvestd::vector<ext::shared_ptr<RateHelper> > bondInstruments;// Adding the ZC bonds to the curve for the short endbondInstruments.push_back(zc3m);bondInstruments.push_back(zc6m);bondInstruments.push_back(zc1y);// Adding the Fixed rate bonds to the curve for the long endfor (Size i=0; i<numberOfBonds; i++) {bondInstruments.push_back(bondsHelpers[i]);}ext::shared_ptr<YieldTermStructure> bondDiscountingTermStructure(new PiecewiseYieldCurve<Discount,LogLinear>(settlementDate, bondInstruments,termStructureDayCounter));// Building of the Libor forecasting curve// depositsRate d1wQuote=0.043375;Rate d1mQuote=0.031875;Rate d3mQuote=0.0320375;Rate d6mQuote=0.03385;Rate d9mQuote=0.0338125;Rate d1yQuote=0.0335125;// swapsRate s2yQuote=0.0295;Rate s3yQuote=0.0323;Rate s5yQuote=0.0359;Rate s10yQuote=0.0412;Rate s15yQuote=0.0433;/***********************    QUOTES    ***********************/// SimpleQuote stores a value which can be manually changed;// other Quote subclasses could read the value from a database// or some kind of data feed.// depositsext::shared_ptr<Quote> d1wRate(new SimpleQuote(d1wQuote));ext::shared_ptr<Quote> d1mRate(new SimpleQuote(d1mQuote));ext::shared_ptr<Quote> d3mRate(new SimpleQuote(d3mQuote));ext::shared_ptr<Quote> d6mRate(new SimpleQuote(d6mQuote));ext::shared_ptr<Quote> d9mRate(new SimpleQuote(d9mQuote));ext::shared_ptr<Quote> d1yRate(new SimpleQuote(d1yQuote));// swapsext::shared_ptr<Quote> s2yRate(new SimpleQuote(s2yQuote));ext::shared_ptr<Quote> s3yRate(new SimpleQuote(s3yQuote));ext::shared_ptr<Quote> s5yRate(new SimpleQuote(s5yQuote));ext::shared_ptr<Quote> s10yRate(new SimpleQuote(s10yQuote));ext::shared_ptr<Quote> s15yRate(new SimpleQuote(s15yQuote));/************************  RATE HELPERS ************************/// RateHelpers are built from the above quotes together with// other instrument dependant infos.  Quotes are passed in// relinkable handles which could be relinked to some other// data source later.// depositsDayCounter depositDayCounter = Actual360();ext::shared_ptr<RateHelper> d1w(new DepositRateHelper(Handle<Quote>(d1wRate),1*Weeks, fixingDays,calendar, ModifiedFollowing,true, depositDayCounter));ext::shared_ptr<RateHelper> d1m(new DepositRateHelper(Handle<Quote>(d1mRate),1*Months, fixingDays,calendar, ModifiedFollowing,true, depositDayCounter));ext::shared_ptr<RateHelper> d3m(new DepositRateHelper(Handle<Quote>(d3mRate),3*Months, fixingDays,calendar, ModifiedFollowing,true, depositDayCounter));ext::shared_ptr<RateHelper> d6m(new DepositRateHelper(Handle<Quote>(d6mRate),6*Months, fixingDays,calendar, ModifiedFollowing,true, depositDayCounter));ext::shared_ptr<RateHelper> d9m(new DepositRateHelper(Handle<Quote>(d9mRate),9*Months, fixingDays,calendar, ModifiedFollowing,true, depositDayCounter));ext::shared_ptr<RateHelper> d1y(new DepositRateHelper(Handle<Quote>(d1yRate),1*Years, fixingDays,calendar, ModifiedFollowing,true, depositDayCounter));// setup swapsFrequency swFixedLegFrequency = Annual;BusinessDayConvention swFixedLegConvention = Unadjusted;DayCounter swFixedLegDayCounter = Thirty360(Thirty360::European);ext::shared_ptr<IborIndex> swFloatingLegIndex(new Euribor6M);const Period forwardStart(1*Days);ext::shared_ptr<RateHelper> s2y(new SwapRateHelper(Handle<Quote>(s2yRate), 2*Years,calendar, swFixedLegFrequency,swFixedLegConvention, swFixedLegDayCounter,swFloatingLegIndex, Handle<Quote>(),forwardStart));ext::shared_ptr<RateHelper> s3y(new SwapRateHelper(Handle<Quote>(s3yRate), 3*Years,calendar, swFixedLegFrequency,swFixedLegConvention, swFixedLegDayCounter,swFloatingLegIndex, Handle<Quote>(),forwardStart));ext::shared_ptr<RateHelper> s5y(new SwapRateHelper(Handle<Quote>(s5yRate), 5*Years,calendar, swFixedLegFrequency,swFixedLegConvention, swFixedLegDayCounter,swFloatingLegIndex, Handle<Quote>(),forwardStart));ext::shared_ptr<RateHelper> s10y(new SwapRateHelper(Handle<Quote>(s10yRate), 10*Years,calendar, swFixedLegFrequency,swFixedLegConvention, swFixedLegDayCounter,swFloatingLegIndex, Handle<Quote>(),forwardStart));ext::shared_ptr<RateHelper> s15y(new SwapRateHelper(Handle<Quote>(s15yRate), 15*Years,calendar, swFixedLegFrequency,swFixedLegConvention, swFixedLegDayCounter,swFloatingLegIndex, Handle<Quote>(),forwardStart));/***********************  CURVE BUILDING ***********************/// Any DayCounter would be fine.// ActualActual::ISDA ensures that 30 years is 30.0// A depo-swap curvestd::vector<ext::shared_ptr<RateHelper> > depoSwapInstruments;depoSwapInstruments.push_back(d1w);depoSwapInstruments.push_back(d1m);depoSwapInstruments.push_back(d3m);depoSwapInstruments.push_back(d6m);depoSwapInstruments.push_back(d9m);depoSwapInstruments.push_back(d1y);depoSwapInstruments.push_back(s2y);depoSwapInstruments.push_back(s3y);depoSwapInstruments.push_back(s5y);depoSwapInstruments.push_back(s10y);depoSwapInstruments.push_back(s15y);ext::shared_ptr<YieldTermStructure> depoSwapTermStructure(new PiecewiseYieldCurve<Discount,LogLinear>(settlementDate, depoSwapInstruments,termStructureDayCounter));// Term structures that will be used for pricing:// the one used for discounting cash flowsRelinkableHandle<YieldTermStructure> discountingTermStructure;// the one used for forward rate forecastingRelinkableHandle<YieldTermStructure> forecastingTermStructure;/********************** BONDS TO BE PRICED ***********************/// Common dataReal faceAmount = 100;// Pricing engineext::shared_ptr<PricingEngine> bondEngine(new DiscountingBondEngine(discountingTermStructure));// Zero coupon bondZeroCouponBond zeroCouponBond(settlementDays,UnitedStates(UnitedStates::GovernmentBond),faceAmount,Date(15,August,2013),Following,Real(116.92),Date(15,August,2003));zeroCouponBond.setPricingEngine(bondEngine);// Fixed 4.5% US Treasury NoteSchedule fixedBondSchedule(Date(15, May, 2007),Date(15,May,2017), Period(Semiannual),UnitedStates(UnitedStates::GovernmentBond),Unadjusted, Unadjusted, DateGeneration::Backward, false);FixedRateBond fixedRateBond(settlementDays,faceAmount,fixedBondSchedule,std::vector<Rate>(1, 0.045),ActualActual(ActualActual::Bond),ModifiedFollowing,100.0, Date(15, May, 2007));fixedRateBond.setPricingEngine(bondEngine);// Floating rate bond (3M USD Libor + 0.1%)// Should and will be priced on another curve later...RelinkableHandle<YieldTermStructure> liborTermStructure;const ext::shared_ptr<IborIndex> libor3m(new USDLibor(Period(3,Months),liborTermStructure));libor3m->addFixing(Date(17, July, 2008),0.0278625);Schedule floatingBondSchedule(Date(21, October, 2005),Date(21, October, 2010), Period(Quarterly),UnitedStates(UnitedStates::NYSE),Unadjusted, Unadjusted, DateGeneration::Backward, true);FloatingRateBond floatingRateBond(settlementDays,faceAmount,floatingBondSchedule,libor3m,Actual360(),ModifiedFollowing,Natural(2),// Gearingsstd::vector<Real>(1, 1.0),// Spreadsstd::vector<Rate>(1, 0.001),// Capsstd::vector<Rate>(),// Floorsstd::vector<Rate>(),// Fixing in arrearstrue,Real(100.0),Date(21, October, 2005));floatingRateBond.setPricingEngine(bondEngine);// Coupon pricersext::shared_ptr<IborCouponPricer> pricer(new BlackIborCouponPricer);// optionLet volatilitiesVolatility volatility = 0.0;Handle<OptionletVolatilityStructure> vol;vol = Handle<OptionletVolatilityStructure>(ext::shared_ptr<OptionletVolatilityStructure>(newConstantOptionletVolatility(settlementDays,calendar,ModifiedFollowing,volatility,Actual365Fixed())));pricer->setCapletVolatility(vol);setCouponPricer(floatingRateBond.cashflows(),pricer);// Yield curve bootstrappingforecastingTermStructure.linkTo(depoSwapTermStructure);discountingTermStructure.linkTo(bondDiscountingTermStructure);// We are using the depo & swap curve to estimate the future Libor ratesliborTermStructure.linkTo(depoSwapTermStructure);/**************** BOND PRICING *****************/std::cout << std::endl;// write column headingsSize widths[] = { 18, 10, 10, 10 };std::cout << std::setw(widths[0]) <<  "                 "<< std::setw(widths[1]) << "ZC"<< std::setw(widths[2]) << "Fixed"<< std::setw(widths[3]) << "Floating"<< std::endl;Size width = widths[0] + widths[1] + widths[2] + widths[3];std::string rule(width, '-');std::cout << rule << std::endl;std::cout << std::fixed;std::cout << std::setprecision(2);std::cout << std::setw(widths[0]) << "Net present value"<< std::setw(widths[1]) << zeroCouponBond.NPV()<< std::setw(widths[2]) << fixedRateBond.NPV()<< std::setw(widths[3]) << floatingRateBond.NPV()<< std::endl;std::cout << std::setw(widths[0]) << "Clean price"<< std::setw(widths[1]) << zeroCouponBond.cleanPrice()<< std::setw(widths[2]) << fixedRateBond.cleanPrice()<< std::setw(widths[3]) << floatingRateBond.cleanPrice()<< std::endl;std::cout << std::setw(widths[0]) << "Dirty price"<< std::setw(widths[1]) << zeroCouponBond.dirtyPrice()<< std::setw(widths[2]) << fixedRateBond.dirtyPrice()<< std::setw(widths[3]) << floatingRateBond.dirtyPrice()<< std::endl;std::cout << std::setw(widths[0]) << "Accrued coupon"<< std::setw(widths[1]) << zeroCouponBond.accruedAmount()<< std::setw(widths[2]) << fixedRateBond.accruedAmount()<< std::setw(widths[3]) << floatingRateBond.accruedAmount()<< std::endl;std::cout << std::setw(widths[0]) << "Previous coupon"<< std::setw(widths[1]) << "N/A" // zeroCouponBond<< std::setw(widths[2]) << io::rate(fixedRateBond.previousCouponRate())<< std::setw(widths[3]) << io::rate(floatingRateBond.previousCouponRate())<< std::endl;std::cout << std::setw(widths[0]) << "Next coupon"<< std::setw(widths[1]) << "N/A" // zeroCouponBond<< std::setw(widths[2]) << io::rate(fixedRateBond.nextCouponRate())<< std::setw(widths[3]) << io::rate(floatingRateBond.nextCouponRate())<< std::endl;std::cout << std::setw(widths[0]) << "Yield"<< std::setw(widths[1])<< io::rate(zeroCouponBond.yield(Actual360(),Compounded,Annual))<< std::setw(widths[2])<< io::rate(fixedRateBond.yield(Actual360(),Compounded,Annual))<< std::setw(widths[3])<< io::rate(floatingRateBond.yield(Actual360(),Compounded,Annual))<< std::endl;std::cout << std::endl;// Other computationsstd::cout << "Sample indirect computations (for the floating rate bond): " << std::endl;std::cout << rule << std::endl;std::cout << "Yield to Clean Price: "<< floatingRateBond.cleanPrice(floatingRateBond.yield(Actual360(),Compounded,Annual),Actual360(),Compounded,Annual,settlementDate) << std::endl;std::cout << "Clean Price to Yield: "<< io::rate(floatingRateBond.yield(floatingRateBond.cleanPrice(),Actual360(),Compounded,Annual,settlementDate)) << std::endl;/* "Yield to Price""Price to Yield" */return 0;} catch (std::exception& e) {std::cerr << e.what() << std::endl;return 1;} catch (...) {std::cerr << "unknown error" << std::endl;return 1;}
}

该博文为原创文章,未经博主同意不得转。
本文章博客地址:https://cplusplus.blog.csdn.net/article/details/128247678

C++:实现量化设置期限结构,然后确定价格如“价格收益率”或“收益率价格”测试实例相关推荐

  1. C++:实现量化如何建立一个期限结构,并为一个简单的FRA远期利率协议测试实例

    C++:实现量化如何建立一个期限结构,并为一个简单的FRA远期利率协议测试实例 #include <ql/qldefines.hpp> #if !defined(BOOST_ALL_NO_ ...

  2. python 波动率锥_期权波动率期限结构与日历价差策略

    波动率的期限结构 波动率期限结构描述的是隐含波动率会随期权剩余期限的不同有所变化. 平价期权的波动率与期权剩余期限之间的常见的关系是:当短期波动率非常低时,波动率函数是期权剩余期限时间的增函数:当短期 ...

  3. 【转】期限结构Carry收益 期货多品种对冲模型

    期限结构与carry大致定义 简单来说,展期收益就是不同月间合约的价差.这种收益也被称为carry收益,一般意义上的carry是指票息所得和资金成本之间的差.举例说,如果你借钱5%成本买企业债并收到了 ...

  4. 期货市场的免费午餐?期限结构Carry收益模型分享

    我们有没有注意到:同一商品期货合约,由于交割时间不同,价格有很大差异?这种差异如果可以被利用,我们即可获得一种特殊的收益--展期收益. 展期收益定义 每个期货合约都有自己固定的生命周期,这个周期在交割 ...

  5. 投资学 U15 利率期限结构 习题解读

    好题 概念 10,14不同时期的期限结构--本质就是债券估值 16通过HPR的计算,复习预期理论下的一年期YTM的投资学意义 计算 18,19实际是一道题,通过金融工程,复习无套利均衡交易策略 基础题 ...

  6. 利率风险结构和期限结构

    1. 风险结构 风险结构是为了解释为什么不同的机构发行的相同到期期限的债券利率不同. 违约风险(default risk):该风险是指债券的借款人可能违约,因此不同的程度的违约可能性会产生风险溢价.该 ...

  7. 金融工程利率期限结构matlab,2016年武汉大学金融工程实验报告固守内容+利率期限结构及MATLAB应用.pdf...

    2016年武汉大学金融工程实验报告固守内容利率期限结构及MATLAB应用 Dec.30.2016 金融工程实 验报告 固定收益证券和利率期限结 构及MATLAB应用 2016 12 30 金融工程试验 ...

  8. 金融工程利率期限结构matlab,2016年武汉大学金融工程实验报告固守内容+利率期限结构及MATLAB应用...

    <2016年武汉大学金融工程实验报告固守内容+利率期限结构及MATLAB应用>由会员分享,可在线阅读,更多相关<2016年武汉大学金融工程实验报告固守内容+利率期限结构及MATLAB ...

  9. 波动率期限结构与日历价差策略

    波动率的期限结构 波动率期限结构描述的是隐含波动率会随期权剩余期限的不同有所变化. 平价期权的波动率与期权剩余期限之间的常见的关系是:当短期波动率非常低时,波动率函数是期权剩余期限时间的增函数:当短期 ...

最新文章

  1. 菜鸟学习javascript实例教程
  2. GitHub高效搜索
  3. mysql四个对勾_Mysql like查询语句中,结果包含反斜杠 \ 字符的,需要替换成四个反斜杠 \\\\...
  4. python3练习,python3练习题 - 来自菜鸟的独白
  5. LSMW批处理使用方法(06)_步骤4、5
  6. 小程序各种姿势实现登录
  7. pline加点lisp_用Autolisp 在AutoCAD中实现多种曲线的绘制
  8. MVC和WebForm区别
  9. IOS AVPlayer视频播放器 AVPlayerViewController视频播放控制器
  10. 中国电信与阿里巴巴签署全面战略合作协议
  11. oracle 客户端配置
  12. 开源3D游戏引擎Irrlicht简介
  13. 【君思智慧园区】物业管理系统解决方案
  14. 【经典】对static关键字深入理解
  15. 02_Snaker表介绍
  16. Excel筛选两列重复的内容
  17. 区块链的概念定义是什么
  18. php函数名命名规范,PHP语言的命名规则
  19. svg去掉黑色自带背景图
  20. [Vue warn]: Invalid vnode type when creating vnode: .

热门文章

  1. 视频解码opencv、ffmpeg、decord三种方式速度对比
  2. Qt美化调色控件(支持RGB,HSL调色,渐变色,十六进制,屏幕取色器,常用颜色)
  3. 新品上架,标题怎样写,关键字怎样选,如何选择合适自己店铺商品的关键词
  4. 211研究生学长,研二去实习,研三拿下四个30万+offer
  5. 连续学习入门(三):Permuted MNIST/Split MNIST/Sequential MNIST 数据集
  6. win10中没有本地策略组、本地用户和组
  7. 四川好的计算机单招专科学校,四川最好的单招学校有哪些?
  8. 医疗大数据的分析和挖掘发展现状以及未来的应用前景
  9. Altium Designer 自动保存
  10. 怀化驾考系统的敏感程度