本文整理汇总了C++中RelinkableHandle类的典型用法代码示例。如果您正苦于以下问题:C++ RelinkableHandle类的具体用法?C++ RelinkableHandle怎么用?C++ RelinkableHandle使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RelinkableHandle类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: BOOST_TEST_MESSAGE
void DefaultProbabilityCurveTest::testSingleInstrumentBootstrap() {
BOOST_TEST_MESSAGE("Testing single-instrument curve bootstrap...");
Calendar calendar = TARGET();
Date today = Settings::instance().evaluationDate();
Integer settlementDays = 0;
Real quote = 0.005;
Period tenor = 2*Years;
Frequency frequency = Quarterly;
BusinessDayConvention convention = Following;
DateGeneration::Rule rule = DateGeneration::TwentiethIMM;
DayCounter dayCounter = Thirty360();
Real recoveryRate = 0.4;
RelinkableHandle<YieldTermStructure> discountCurve;
discountCurve.linkTo(boost::shared_ptr<YieldTermStructure>(
new FlatForward(today,0.06,Actual360())));
std::vector<boost::shared_ptr<DefaultProbabilityHelper> > helpers(1);
helpers[0] = boost::shared_ptr<DefaultProbabilityHelper>(
new SpreadCdsHelper(quote, tenor,
settlementDays, calendar,
frequency, convention, rule,
dayCounter, recoveryRate,
discountCurve));
PiecewiseDefaultCurve<HazardRate,BackwardFlat> defaultCurve(today, helpers,
dayCounter);
defaultCurve.recalculate();
}
示例2: BOOST_TEST_MESSAGE
void OptionletStripperTest::testSwitchStrike() {
BOOST_TEST_MESSAGE("Testing switch strike level and recalibration of level "
"in case of curve relinking...");
CommonVars vars;
Settings::instance().evaluationDate() = Date(28, October, 2013);
vars.setCapFloorTermVolSurface();
RelinkableHandle< YieldTermStructure > yieldTermStructure;
yieldTermStructure.linkTo(boost::shared_ptr< FlatForward >(
new FlatForward(0, vars.calendar, 0.03, vars.dayCounter)));
shared_ptr< IborIndex > iborIndex(new Euribor6M(yieldTermStructure));
boost::shared_ptr< OptionletStripper1 > optionletStripper1(
new OptionletStripper1(vars.capFloorVolSurface, iborIndex,
Null< Rate >(), vars.accuracy));
#if defined(QL_USE_INDEXED_COUPON)
Real expected = 0.02981258;
#else
Real expected = 0.02981223;
#endif
Real error = std::fabs(optionletStripper1->switchStrike() - expected);
if (error > vars.tolerance)
BOOST_FAIL("\nSwitchstrike not correctly computed: "
<< "\nexpected switch strike: " << io::rate(expected)
<< "\ncomputed switch strike: "
<< io::rate(optionletStripper1->switchStrike())
<< "\nerror: " << io::rate(error)
<< "\ntolerance: " << io::rate(vars.tolerance));
yieldTermStructure.linkTo(boost::shared_ptr< FlatForward >(
new FlatForward(0, vars.calendar, 0.05, vars.dayCounter)));
#if defined(QL_USE_INDEXED_COUPON)
expected = 0.0499381;
#else
expected = 0.0499371;
#endif
error = std::fabs(optionletStripper1->switchStrike() - expected);
if (error > vars.tolerance)
BOOST_FAIL("\nSwitchstrike not correctly computed: "
<< "\nexpected switch strike: " << io::rate(expected)
<< "\ncomputed switch strike: "
<< io::rate(optionletStripper1->switchStrike())
<< "\nerror: " << io::rate(error)
<< "\ntolerance: " << io::rate(vars.tolerance));
}
示例3: BOOST_TEST_MESSAGE
void TermStructureTest::testCreateWithNullUnderlying() {
BOOST_TEST_MESSAGE(
"Testing that a zero-spreaded curve can be created with "
"a null underlying curve...");
CommonVars vars;
Handle<Quote> spread(ext::shared_ptr<Quote>(new SimpleQuote(0.01)));
RelinkableHandle<YieldTermStructure> underlying;
// this shouldn't throw
ext::shared_ptr<YieldTermStructure> spreaded(
new ZeroSpreadedTermStructure(underlying,spread));
// if we do this, the curve can work.
underlying.linkTo(vars.termStructure);
// check that we can use it
spreaded->referenceDate();
}
示例4: BOOST_MESSAGE
void NthToDefaultTest::testGaussStudent() {
BOOST_MESSAGE ("Testing nth-to-default against Hull-White values "
"with Gaussian and Student copula...");
SavedSettings backup;
/*************************
* Tolerances
*/
Real relTolerance = 0.015; // relative difference
Real absTolerance = 1; // absolute difference in bp
Period timeUnit = 1*Weeks; // required to reach accuracy
Size names = 10;
QL_REQUIRE (LENGTH(hwDataDist) == names,
"hwDataDist length does not match");
Real rate = 0.05;
DayCounter dc = Actual365Fixed();
Compounding cmp = Continuous; // Simple;
Real recovery = 0.4;
vector<Real> lambda (names, 0.01);
Schedule schedule = MakeSchedule().from(Date (1, September, 2006))
.to(Date (1, September, 2011))
.withTenor(3*Months)
.withCalendar(TARGET());
Date asofDate(31, August, 2006);
Settings::instance().evaluationDate() = asofDate;
vector<Date> gridDates;
gridDates.push_back (asofDate);
gridDates.push_back (TARGET().advance (asofDate, Period (1, Years)));
gridDates.push_back (TARGET().advance (asofDate, Period (5, Years)));
gridDates.push_back (TARGET().advance (asofDate, Period (7, Years)));
shared_ptr<YieldTermStructure> yieldPtr (new FlatForward (asofDate, rate, dc, cmp));
Handle<YieldTermStructure> yieldHandle (yieldPtr);
vector<Handle<DefaultProbabilityTermStructure> > probabilities;
Period maxTerm (10, Years);
for (Size i = 0; i < lambda.size(); i++) {
Handle<Quote> h(shared_ptr<Quote>(new SimpleQuote(lambda[i])));
shared_ptr<DefaultProbabilityTermStructure> ptr (
new FlatHazardRate(asofDate, h, dc));
probabilities.push_back(Handle<DefaultProbabilityTermStructure>(ptr));
}
shared_ptr<SimpleQuote> simpleQuote (new SimpleQuote(0.3));
Handle<Quote> correlationHandle (simpleQuote);
shared_ptr<OneFactorCopula> gaussianCopula (
new OneFactorGaussianCopula (correlationHandle));
shared_ptr<OneFactorCopula> studentCopula (
new OneFactorStudentCopula (correlationHandle, 5, 5));
RelinkableHandle<OneFactorCopula> copula;
vector<NthToDefault> ntd;
for (Size i = 1; i <= probabilities.size(); i++)
ntd.push_back (NthToDefault (i, probabilities, recovery,
copula, Protection::Seller,
100.0, schedule, 0.02, Actual360(),
true, yieldHandle, timeUnit));
QL_REQUIRE (LENGTH(hwCorrelation) == 3,
"correlation length does not match");
Real maxDiff = 0;
simpleQuote->setValue (0.3);
copula.linkTo (gaussianCopula);
for (Size i = 0; i < ntd.size(); i++) {
QL_REQUIRE (ntd[i].rank() == hwDataDist[i].rank, "rank does not match");
Real diff = 1e4 * ntd[i].fairPremium() - hwDataDist[i].spread[0];
maxDiff = max (maxDiff, fabs (diff));
BOOST_CHECK_MESSAGE (fabs(diff / hwDataDist[i].spread[0]) ||
fabs(diff) < absTolerance,
"tolerance " << relTolerance << "|"
<< absTolerance << " exceeded");
}
copula.linkTo (studentCopula);
maxDiff = 0;
for (Size i = 0; i < ntd.size(); i++) {
QL_REQUIRE (ntd[i].rank() == hwDataDist[i].rank, "rank does not match");
Real diff = 1e4 * ntd[i].fairPremium() - hwDataDist[i].spread[3];
maxDiff = max (maxDiff, fabs (diff));
BOOST_CHECK_MESSAGE (fabs(diff / hwDataDist[i].spread[3]) ||
fabs(diff) < absTolerance,
"tolerance " << relTolerance << "|"
//.........这里部分代码省略.........
示例5: BOOST_TEST_MESSAGE
void CreditDefaultSwapTest::testCachedValue() {
BOOST_TEST_MESSAGE("Testing credit-default swap against cached values...");
SavedSettings backup;
// Initialize curves
Settings::instance().evaluationDate() = Date(9,June,2006);
Date today = Settings::instance().evaluationDate();
Calendar calendar = TARGET();
Handle<Quote> hazardRate = Handle<Quote>(
ext::shared_ptr<Quote>(new SimpleQuote(0.01234)));
RelinkableHandle<DefaultProbabilityTermStructure> probabilityCurve;
probabilityCurve.linkTo(
ext::shared_ptr<DefaultProbabilityTermStructure>(
new FlatHazardRate(0, calendar, hazardRate, Actual360())));
RelinkableHandle<YieldTermStructure> discountCurve;
discountCurve.linkTo(ext::shared_ptr<YieldTermStructure>(
new FlatForward(today,0.06,Actual360())));
// Build the schedule
Date issueDate = calendar.advance(today, -1, Years);
Date maturity = calendar.advance(issueDate, 10, Years);
Frequency frequency = Semiannual;
BusinessDayConvention convention = ModifiedFollowing;
Schedule schedule(issueDate, maturity, Period(frequency), calendar,
convention, convention, DateGeneration::Forward, false);
// Build the CDS
Rate fixedRate = 0.0120;
DayCounter dayCount = Actual360();
Real notional = 10000.0;
Real recoveryRate = 0.4;
CreditDefaultSwap cds(Protection::Seller, notional, fixedRate,
schedule, convention, dayCount, true, true);
cds.setPricingEngine(ext::shared_ptr<PricingEngine>(
new MidPointCdsEngine(probabilityCurve,recoveryRate,discountCurve)));
Real npv = 295.0153398;
Rate fairRate = 0.007517539081;
Real calculatedNpv = cds.NPV();
Rate calculatedFairRate = cds.fairSpread();
Real tolerance = 1.0e-7;
if (std::fabs(calculatedNpv - npv) > tolerance)
BOOST_ERROR(
"Failed to reproduce NPV with mid-point engine\n"
<< std::setprecision(10)
<< " calculated NPV: " << calculatedNpv << "\n"
<< " expected NPV: " << npv);
if (std::fabs(calculatedFairRate - fairRate) > tolerance)
BOOST_ERROR(
"Failed to reproduce fair rate with mid-point engine\n"
<< std::setprecision(10)
<< " calculated fair rate: " << calculatedFairRate << "\n"
<< " expected fair rate: " << fairRate);
cds.setPricingEngine(ext::shared_ptr<PricingEngine>(
new IntegralCdsEngine(1*Days,probabilityCurve,
recoveryRate,discountCurve)));
calculatedNpv = cds.NPV();
calculatedFairRate = cds.fairSpread();
tolerance = 1.0e-5;
if (std::fabs(calculatedNpv - npv) > notional*tolerance*10)
BOOST_ERROR(
"Failed to reproduce NPV with integral engine "
"(step = 1 day)\n"
<< std::setprecision(10)
<< " calculated NPV: " << calculatedNpv << "\n"
<< " expected NPV: " << npv);
if (std::fabs(calculatedFairRate - fairRate) > tolerance)
BOOST_ERROR(
"Failed to reproduce fair rate with integral engine "
"(step = 1 day)\n"
<< std::setprecision(10)
<< " calculated fair rate: " << calculatedFairRate << "\n"
<< " expected fair rate: " << fairRate);
cds.setPricingEngine(ext::shared_ptr<PricingEngine>(
new IntegralCdsEngine(1*Weeks,probabilityCurve,
recoveryRate,discountCurve)));
calculatedNpv = cds.NPV();
calculatedFairRate = cds.fairSpread();
tolerance = 1.0e-5;
if (std::fabs(calculatedNpv - npv) > notional*tolerance*10)
BOOST_ERROR(
"Failed to reproduce NPV with integral engine "
"(step = 1 week)\n"
//.........这里部分代码省略.........
示例6: main
int main(int, char* []) {
try {
boost::timer timer;
std::cout << std::endl;
/*********************
*** MARKET DATA ***
*********************/
RelinkableHandle<YieldTermStructure> euriborTermStructure;
boost::shared_ptr<IborIndex> euribor3m(
new Euribor3M(euriborTermStructure));
Date todaysDate = Date(23, May, 2006);
Settings::instance().evaluationDate() = todaysDate;
Calendar calendar = euribor3m->fixingCalendar();
Integer fixingDays = euribor3m->fixingDays();
Date settlementDate = calendar.advance(todaysDate, fixingDays, Days);
std::cout << "Today: " << todaysDate.weekday()
<< ", " << todaysDate << std::endl;
std::cout << "Settlement date: " << settlementDate.weekday()
<< ", " << settlementDate << std::endl;
// 3 month term FRA quotes (index refers to monthsToStart)
Rate threeMonthFraQuote[10];
threeMonthFraQuote[1]=0.030;
threeMonthFraQuote[2]=0.031;
threeMonthFraQuote[3]=0.032;
threeMonthFraQuote[6]=0.033;
threeMonthFraQuote[9]=0.034;
/********************
*** 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.
// FRAs
boost::shared_ptr<SimpleQuote> fra1x4Rate(
new SimpleQuote(threeMonthFraQuote[1]));
boost::shared_ptr<SimpleQuote> fra2x5Rate(
new SimpleQuote(threeMonthFraQuote[2]));
boost::shared_ptr<SimpleQuote> fra3x6Rate(
new SimpleQuote(threeMonthFraQuote[3]));
boost::shared_ptr<SimpleQuote> fra6x9Rate(
new SimpleQuote(threeMonthFraQuote[6]));
boost::shared_ptr<SimpleQuote> fra9x12Rate(
new SimpleQuote(threeMonthFraQuote[9]));
RelinkableHandle<Quote> h1x4; h1x4.linkTo(fra1x4Rate);
RelinkableHandle<Quote> h2x5; h2x5.linkTo(fra2x5Rate);
RelinkableHandle<Quote> h3x6; h3x6.linkTo(fra3x6Rate);
RelinkableHandle<Quote> h6x9; h6x9.linkTo(fra6x9Rate);
RelinkableHandle<Quote> h9x12; h9x12.linkTo(fra9x12Rate);
/*********************
*** 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.
DayCounter fraDayCounter = euribor3m->dayCounter();
BusinessDayConvention convention = euribor3m->businessDayConvention();
bool endOfMonth = euribor3m->endOfMonth();
boost::shared_ptr<RateHelper> fra1x4(
new FraRateHelper(h1x4, 1, 4,
fixingDays, calendar, convention,
endOfMonth, fraDayCounter));
boost::shared_ptr<RateHelper> fra2x5(
new FraRateHelper(h2x5, 2, 5,
fixingDays, calendar, convention,
endOfMonth, fraDayCounter));
boost::shared_ptr<RateHelper> fra3x6(
new FraRateHelper(h3x6, 3, 6,
fixingDays, calendar, convention,
endOfMonth, fraDayCounter));
boost::shared_ptr<RateHelper> fra6x9(
new FraRateHelper(h6x9, 6, 9,
fixingDays, calendar, convention,
endOfMonth, fraDayCounter));
boost::shared_ptr<RateHelper> fra9x12(
new FraRateHelper(h9x12, 9, 12,
//.........这里部分代码省略.........
示例7: main
/*Market Data -> FRA Quote -> FRA rate helper -> Curve Building -> Construct FRA*/
int main(int, char* []) {
try {
boost::timer timer;
std::cout << std::endl;
std::ifstream file("data.csv");
CSVRow data_row;
file >> data_row;
const size_t num_data = data_row.size()/2;
/*********************
*** MARKET DATA ***
*********************/
RelinkableHandle<YieldTermStructure> euriborTermStructure;
boost::shared_ptr<IborIndex> euribor3m(
new Euribor3M(euriborTermStructure));
Date todaysDate = Date(23, May, 2006);
Settings::instance().evaluationDate() = todaysDate;
Calendar calendar = euribor3m->fixingCalendar();
Integer fixingDays = euribor3m->fixingDays();
Date settlementDate = calendar.advance(todaysDate, fixingDays, Days);
std::cout << "Today: " << todaysDate.weekday()
<< ", " << todaysDate << std::endl;
std::cout << "Settlement date: " << settlementDate.weekday()
<< ", " << settlementDate << std::endl;
// 3 month term FRA quotes (index refers to monthsToStart)
vector <stFRAMarketData> vecMarketData;
for(size_t i = 0 ; i < num_data; i++) {
stFRAMarketData element_data;
convertFromString(element_data.iMonthToStart, data_row[i]);
element_data.iTermDuration = 3; //3 month term
convertFromString(element_data.rateFraQuote, data_row[i + num_data]);
vecMarketData.push_back(element_data);
}
/********************
*** 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.
// FRAs
std::vector <boost::shared_ptr<SimpleQuote> > vecFRAQuote;
for(size_t i = 0 ; i < num_data; i++) {
boost::shared_ptr<SimpleQuote> fraRate(new SimpleQuote(vecMarketData[i].rateFraQuote));
vecFRAQuote.push_back(fraRate);
}
std::vector <RelinkableHandle<Quote> > vecQuoteHandle;
for(size_t i = 0 ; i < num_data; i++) {
RelinkableHandle<Quote> hQuote;
hQuote.linkTo(vecFRAQuote[i]);
vecQuoteHandle.push_back(hQuote);
}
/*********************
*** 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.
DayCounter fraDayCounter = euribor3m->dayCounter();
BusinessDayConvention convention = euribor3m->businessDayConvention();
bool endOfMonth = euribor3m->endOfMonth();
std::vector < boost::shared_ptr<RateHelper> > vecRateHelper;
for(size_t i = 0 ; i < num_data; i++) {
boost::shared_ptr<RateHelper> fra_helper(
new FraRateHelper(vecQuoteHandle[i],vecMarketData[i].iMonthToStart,
vecMarketData[i].iMonthToStart + vecMarketData[i].iTermDuration,
fixingDays, calendar, convention,
endOfMonth, fraDayCounter));
vecRateHelper.push_back(fra_helper);
}
/*********************
** CURVE BUILDING **
*********************/
//.........这里部分代码省略.........
示例8: TARGET
//.........这里部分代码省略.........
depoFutSwapInstruments.push_back(s3y);
depoFutSwapInstruments.push_back(s5y);
depoFutSwapInstruments.push_back(s10y);
depoFutSwapInstruments.push_back(s15y);
boost::shared_ptr<YieldTermStructure> depoFutSwapTermStructure(
new PiecewiseYieldCurve<Discount,LogLinear>(
settlementDate, depoFutSwapInstruments,
termStructureDayCounter,
tolerance));
// A depo-FRA-swap curve
std::vector<boost::shared_ptr<RateHelper> > depoFRASwapInstruments;
depoFRASwapInstruments.push_back(d1w);
depoFRASwapInstruments.push_back(d1m);
depoFRASwapInstruments.push_back(d3m);
depoFRASwapInstruments.push_back(fra3x6);
depoFRASwapInstruments.push_back(fra6x9);
depoFRASwapInstruments.push_back(fra6x12);
depoFRASwapInstruments.push_back(s2y);
depoFRASwapInstruments.push_back(s3y);
depoFRASwapInstruments.push_back(s5y);
depoFRASwapInstruments.push_back(s10y);
depoFRASwapInstruments.push_back(s15y);
boost::shared_ptr<YieldTermStructure> depoFRASwapTermStructure(
new PiecewiseYieldCurve<Discount,LogLinear>(
settlementDate, depoFRASwapInstruments,
termStructureDayCounter,
tolerance));
// Term structures that will be used for pricing:
// the one used for discounting cash flows
RelinkableHandle<YieldTermStructure> discountingTermStructure;
// the one used for forward rate forecasting
RelinkableHandle<YieldTermStructure> forecastingTermStructure;
/*********************
* SWAPS TO BE PRICED *
**********************/
// constant nominal 1,000,000 Euro
Real nominal = 1000000.0;
// fixed leg
Frequency fixedLegFrequency = Annual;
BusinessDayConvention fixedLegConvention = Unadjusted;
BusinessDayConvention floatingLegConvention = ModifiedFollowing;
DayCounter fixedLegDayCounter = Thirty360(Thirty360::European);
Rate fixedRate = 0.04;
DayCounter floatingLegDayCounter = Actual360();
// floating leg
Frequency floatingLegFrequency = Semiannual;
boost::shared_ptr<IborIndex> euriborIndex(
new Euribor6M(forecastingTermStructure));
Spread spread = 0.0;
Integer lenghtInYears = 5;
VanillaSwap::Type swapType = VanillaSwap::Payer;
Date maturity = settlementDate + lenghtInYears*Years;
Schedule fixedSchedule(settlementDate, maturity,
Period(fixedLegFrequency),
calendar, fixedLegConvention,
fixedLegConvention,
示例9: BOOST_MESSAGE
void InflationTest::testYYTermStructure() {
BOOST_MESSAGE("Testing year-on-year inflation term structure...");
SavedSettings backup;
// try the YY UK
Calendar calendar = UnitedKingdom();
BusinessDayConvention bdc = ModifiedFollowing;
Date evaluationDate(13, August, 2007);
evaluationDate = calendar.adjust(evaluationDate);
Settings::instance().evaluationDate() = evaluationDate;
// fixing data
Date from(1, January, 2005);
Date to(13, August, 2007);
Schedule rpiSchedule = MakeSchedule().from(from).to(to)
.withTenor(1*Months)
.withCalendar(UnitedKingdom())
.withConvention(ModifiedFollowing);
Real fixData[] = { 189.9, 189.9, 189.6, 190.5, 191.6, 192.0,
192.2, 192.2, 192.6, 193.1, 193.3, 193.6,
194.1, 193.4, 194.2, 195.0, 196.5, 197.7,
198.5, 198.5, 199.2, 200.1, 200.4, 201.1,
202.7, 201.6, 203.1, 204.4, 205.4, 206.2,
207.3, -999.0, -999 };
RelinkableHandle<YoYInflationTermStructure> hy;
bool interp = false;
boost::shared_ptr<YYUKRPIr> iir(new YYUKRPIr(interp, hy));
for (Size i=0; i<rpiSchedule.size();i++) {
iir->addFixing(rpiSchedule[i], fixData[i]);
}
boost::shared_ptr<YieldTermStructure> nominalTS = nominalTermStructure();
// now build the YoY inflation curve
Datum yyData[] = {
{ Date(13, August, 2008), 2.95 },
{ Date(13, August, 2009), 2.95 },
{ Date(13, August, 2010), 2.93 },
{ Date(15, August, 2011), 2.955 },
{ Date(13, August, 2012), 2.945 },
{ Date(13, August, 2013), 2.985 },
{ Date(13, August, 2014), 3.01 },
{ Date(13, August, 2015), 3.035 },
{ Date(13, August, 2016), 3.055 }, // note that
{ Date(13, August, 2017), 3.075 }, // some dates will be on
{ Date(13, August, 2019), 3.105 }, // holidays but the payment
{ Date(15, August, 2022), 3.135 }, // calendar will roll them
{ Date(13, August, 2027), 3.155 },
{ Date(13, August, 2032), 3.145 },
{ Date(13, August, 2037), 3.145 }
};
Period observationLag = Period(2,Months);
DayCounter dc = Thirty360();
// now build the helpers ...
std::vector<boost::shared_ptr<BootstrapHelper<YoYInflationTermStructure> > > helpers =
makeHelpers<YoYInflationTermStructure,YearOnYearInflationSwapHelper,
YoYInflationIndex>(yyData, LENGTH(yyData), iir,
observationLag,
calendar, bdc, dc);
Rate baseYYRate = yyData[0].rate/100.0;
boost::shared_ptr<PiecewiseYoYInflationCurve<Linear> > pYYTS(
new PiecewiseYoYInflationCurve<Linear>(
evaluationDate, calendar, dc, observationLag,
iir->frequency(),iir->interpolated(), baseYYRate,
Handle<YieldTermStructure>(nominalTS), helpers));
pYYTS->recalculate();
// validation
// yoy swaps should reprice to zero
// yy rates should not equal yySwap rates
Real eps = 0.000001;
// usual swap engine
Handle<YieldTermStructure> hTS(nominalTS);
boost::shared_ptr<PricingEngine> sppe(new DiscountingSwapEngine(hTS));
// make sure that the index has the latest yoy term structure
hy.linkTo(pYYTS);
for (Size j = 1; j < LENGTH(yyData); j++) {
from = nominalTS->referenceDate();
to = yyData[j].date;
Schedule yoySchedule = MakeSchedule().from(from).to(to)
.withConvention(Unadjusted) // fixed leg gets calendar from
.withCalendar(calendar) // schedule
.withTenor(1*Years)
.backwards()
;
YearOnYearInflationSwap yyS2(YearOnYearInflationSwap::Payer,
1000000.0,
yoySchedule,//fixed schedule, but same as yoy
//.........这里部分代码省略.........
示例10: main
//.........这里部分代码省略.........
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< boost::shared_ptr<SimpleQuote> > quote;
for (Size i=0; i<numberOfBonds; i++) {
boost::shared_ptr<SimpleQuote> cp(new SimpleQuote(marketQuotes[i]));
quote.push_back(cp);
}
RelinkableHandle<Quote> quoteHandle[numberOfBonds];
for (Size i=0; i<numberOfBonds; i++) {
quoteHandle[i].linkTo(quote[i]);
}
// Definition of the rate helpers
std::vector<boost::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);
boost::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:
//
// boost::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.
示例11: TARGET
//.........这里部分代码省略.........
depoFutSwapInstruments.push_back(s3y);
depoFutSwapInstruments.push_back(s5y);
depoFutSwapInstruments.push_back(s10y);
depoFutSwapInstruments.push_back(s15y);
boost::shared_ptr<YieldTermStructure> depoFutSwapTermStructure(
new PiecewiseYieldCurve<Discount,LogLinear>(
settlementDate, depoFutSwapInstruments,
termStructureDayCounter,
tolerance));
// A depo-FRA-swap curve
std::vector<boost::shared_ptr<RateHelper> > depoFRASwapInstruments;
depoFRASwapInstruments.push_back(d1w);
depoFRASwapInstruments.push_back(d1m);
depoFRASwapInstruments.push_back(d3m);
depoFRASwapInstruments.push_back(fra3x6);
depoFRASwapInstruments.push_back(fra6x9);
depoFRASwapInstruments.push_back(fra6x12);
depoFRASwapInstruments.push_back(s2y);
depoFRASwapInstruments.push_back(s3y);
depoFRASwapInstruments.push_back(s5y);
depoFRASwapInstruments.push_back(s10y);
depoFRASwapInstruments.push_back(s15y);
boost::shared_ptr<YieldTermStructure> depoFRASwapTermStructure(
new PiecewiseYieldCurve<Discount,LogLinear>(
settlementDate, depoFRASwapInstruments,
termStructureDayCounter,
tolerance));
// Term structures that will be used for pricing:
// the one used for discounting cash flows
RelinkableHandle<YieldTermStructure> discountingTermStructure;
// the one used for forward rate forecasting
RelinkableHandle<YieldTermStructure> forecastingTermStructure;
/*********************
* SWAPS TO BE PRICED *
**********************/
// constant nominal 1,000,000 Euro
/////■ Real nominal = 1000000.0;
Real nominal = static_cast<Real>(ui->doubleSpinBox_Notional->value());
// fixed leg
/////■ Frequency fixedLegFrequency = Annual;
Frequency fixedLegFrequency = Annual;
/////■ BusinessDayConvention fixedLegConvention = Unadjusted;
BusinessDayConvention fixedLegConvention = Unadjusted;
/////■ DayCounter fixedLegDayCounter = Thirty360(Thirty360::European);
DayCounter fixedLegDayCounter = Thirty360(Thirty360::European);
/////■ Rate fixedRate = 0.04;
Rate fixedRate = static_cast<Real>((ui->doubleSpinBox_fixedRate->value())*0.01);
// floating leg
/////■ Frequency floatingLegFrequency = Semiannual;
Frequency floatingLegFrequency = Semiannual;
int comboBoxFloatingLegFrequency = ui->comboBox_FloatingLegFrequency->currentIndex();
switch(comboBoxFloatingLegFrequency) {
case 0: // Semiannual
floatingLegFrequency = Semiannual;
break;
case 1: // Annual
floatingLegFrequency = Annual;
示例12: main
int main(int, char* []) {
try {
boost::timer timer;
std::cout << std::endl;
Date repoSettlementDate(14,February,2000);;
Date repoDeliveryDate(15,August,2000);
Rate repoRate = 0.05;
DayCounter repoDayCountConvention = Actual360();
Integer repoSettlementDays = 0;
Compounding repoCompounding = Simple;
Frequency repoCompoundFreq = Annual;
// assume a ten year bond- this is irrelevant
Date bondIssueDate(15,September,1995);
Date bondDatedDate(15,September,1995);
Date bondMaturityDate(15,September,2005);
Real bondCoupon = 0.08;
Frequency bondCouponFrequency = Semiannual;
// unknown what calendar fincad is using
Calendar bondCalendar = NullCalendar();
DayCounter bondDayCountConvention = Thirty360(Thirty360::BondBasis);
// unknown what fincad is using. this may affect accrued calculation
Integer bondSettlementDays = 0;
BusinessDayConvention bondBusinessDayConvention = Unadjusted;
Real bondCleanPrice = 89.97693786;
Real bondRedemption = 100.0;
Real faceAmount = 100.0;
Settings::instance().evaluationDate() = repoSettlementDate;
RelinkableHandle<YieldTermStructure> bondCurve;
bondCurve.linkTo(boost::shared_ptr<YieldTermStructure>(
new FlatForward(repoSettlementDate,
.01, // dummy rate
bondDayCountConvention,
Compounded,
bondCouponFrequency)));
/*
boost::shared_ptr<FixedRateBond> bond(
new FixedRateBond(faceAmount,
bondIssueDate,
bondDatedDate,
bondMaturityDate,
bondSettlementDays,
std::vector<Rate>(1,bondCoupon),
bondCouponFrequency,
bondCalendar,
bondDayCountConvention,
bondBusinessDayConvention,
bondBusinessDayConvention,
bondRedemption,
bondCurve));
*/
Schedule bondSchedule(bondDatedDate, bondMaturityDate,
Period(bondCouponFrequency),
bondCalendar,bondBusinessDayConvention,
bondBusinessDayConvention,
DateGeneration::Backward,false);
boost::shared_ptr<FixedRateBond> bond(
new FixedRateBond(bondSettlementDays,
faceAmount,
bondSchedule,
std::vector<Rate>(1,bondCoupon),
bondDayCountConvention,
bondBusinessDayConvention,
bondRedemption,
bondIssueDate));
bond->setPricingEngine(boost::shared_ptr<PricingEngine>(
new DiscountingBondEngine(bondCurve)));
bondCurve.linkTo(boost::shared_ptr<YieldTermStructure> (
new FlatForward(repoSettlementDate,
bond->yield(bondCleanPrice,
bondDayCountConvention,
Compounded,
bondCouponFrequency),
bondDayCountConvention,
Compounded,
bondCouponFrequency)));
Position::Type fwdType = Position::Long;
double dummyStrike = 91.5745;
RelinkableHandle<YieldTermStructure> repoCurve;
repoCurve.linkTo(boost::shared_ptr<YieldTermStructure> (
new FlatForward(repoSettlementDate,
repoRate,
repoDayCountConvention,
repoCompounding,
repoCompoundFreq)));
FixedRateBondForward bondFwd(repoSettlementDate,
repoDeliveryDate,
//.........这里部分代码省略.........
示例13: BOOST_TEST_MESSAGE
void MCLongstaffSchwartzEngineTest::testAmericanMaxOption() {
// reference values taken from
// "Monte Carlo Methods in Financial Engineering",
// by Paul Glasserman, 2004 Springer Verlag, p. 462
BOOST_TEST_MESSAGE("Testing Monte-Carlo pricing of American max options...");
SavedSettings backup;
// most of the example taken from the EquityOption.cpp
const Option::Type type(Option::Call);
const Real strike = 100;
const Spread dividendYield = 0.10;
const Rate riskFreeRate = 0.05;
const Volatility volatility = 0.20;
const Date todaysDate(15, May, 1998);
const Date settlementDate(17, May, 1998);
Settings::instance().evaluationDate() = todaysDate;
const Date maturity(16, May, 2001);
const DayCounter dayCounter = Actual365Fixed();
boost::shared_ptr<Exercise> americanExercise(
new AmericanExercise(settlementDate, maturity));
// bootstrap the yield/dividend/vol curves
Handle<YieldTermStructure> flatTermStructure(
boost::shared_ptr<YieldTermStructure>(
new FlatForward(settlementDate, riskFreeRate, dayCounter)));
Handle<YieldTermStructure> flatDividendTS(
boost::shared_ptr<YieldTermStructure>(
new FlatForward(settlementDate, dividendYield, dayCounter)));
Handle<BlackVolTermStructure> flatVolTS(
boost::shared_ptr<BlackVolTermStructure>(new
BlackConstantVol(settlementDate, NullCalendar(),
volatility, dayCounter)));
boost::shared_ptr<StrikedTypePayoff> payoff(
new PlainVanillaPayoff(type, strike));
RelinkableHandle<Quote> underlyingH;
boost::shared_ptr<GeneralizedBlackScholesProcess> stochasticProcess(new
GeneralizedBlackScholesProcess(
underlyingH, flatDividendTS, flatTermStructure, flatVolTS));
const Size numberAssets = 2;
Matrix corr(numberAssets, numberAssets, 0.0);
std::vector<boost::shared_ptr<StochasticProcess1D> > v;
for (Size i=0; i<numberAssets; ++i) {
v.push_back(stochasticProcess);
corr[i][i] = 1.0;
}
boost::shared_ptr<StochasticProcessArray> process(
new StochasticProcessArray(v, corr));
VanillaOption americanMaxOption(payoff, americanExercise);
boost::shared_ptr<PricingEngine> mcengine(
new MCAmericanMaxEngine<PseudoRandom>(process, 25, Null<Size>(), false,
true, false, 4096,
Null<Real>(), Null<Size>(),
42, 1024));
americanMaxOption.setPricingEngine(mcengine);
const Real expected[] = {8.08, 13.90, 21.34};
for (Size i = 0; i < 3; ++i) {
const Real underlying = 90.0 + i*10.0;
underlyingH.linkTo(
boost::shared_ptr<Quote>(new SimpleQuote(underlying)));
const Real calculated = americanMaxOption.NPV();
const Real errorEstimate = americanMaxOption.errorEstimate();
if (std::fabs(calculated - expected[i]) > 2.34*errorEstimate) {
BOOST_ERROR("Failed to reproduce american option prices"
<< "\n expected: " << expected[i]
<< "\n calculated: " << calculated
<< " +/- " << errorEstimate);
}
}
}
示例14: BOOST_TEST_MESSAGE
void CdsOptionTest::testCached() {
BOOST_TEST_MESSAGE("Testing CDS-option value against cached values...");
SavedSettings backup;
Date cachedToday = Date(10,December,2007);
Settings::instance().evaluationDate() = cachedToday;
Calendar calendar = TARGET();
RelinkableHandle<YieldTermStructure> riskFree;
riskFree.linkTo(boost::shared_ptr<YieldTermStructure>(
new FlatForward(cachedToday,0.02,Actual360())));
Date expiry = calendar.advance(cachedToday,9,Months);
Date startDate = calendar.advance(expiry,1,Months);
Date maturity = calendar.advance(startDate,7,Years);
DayCounter dayCounter = Actual360();
BusinessDayConvention convention = ModifiedFollowing;
Real notional = 1000000.0;
Handle<Quote> hazardRate(boost::shared_ptr<Quote>(new SimpleQuote(0.001)));
Schedule schedule(startDate,maturity, Period(Quarterly),
calendar, convention, convention,
DateGeneration::Forward, false);
Real recoveryRate = 0.4;
Handle<DefaultProbabilityTermStructure> defaultProbability(
boost::shared_ptr<DefaultProbabilityTermStructure>(
new FlatHazardRate(0, calendar, hazardRate, dayCounter)));
boost::shared_ptr<PricingEngine> swapEngine(
new MidPointCdsEngine(defaultProbability, recoveryRate, riskFree));
CreditDefaultSwap swap(Protection::Seller, notional, 0.001, schedule,
convention, dayCounter);
swap.setPricingEngine(swapEngine);
Rate strike = swap.fairSpread();
Handle<Quote> cdsVol(boost::shared_ptr<Quote>(new SimpleQuote(0.20)));
boost::shared_ptr<CreditDefaultSwap> underlying(
new CreditDefaultSwap(Protection::Seller, notional, strike, schedule,
convention, dayCounter));
underlying->setPricingEngine(swapEngine);
boost::shared_ptr<Exercise> exercise(new EuropeanExercise(expiry));
CdsOption option1(underlying, exercise);
option1.setPricingEngine(boost::shared_ptr<PricingEngine>(
new BlackCdsOptionEngine(defaultProbability, recoveryRate,
riskFree, cdsVol)));
Real cachedValue = 270.976348;
if (std::fabs(option1.NPV() - cachedValue) > 1.0e-5)
BOOST_ERROR("failed to reproduce cached value:\n"
<< std::fixed << std::setprecision(6)
<< " calculated: " << option1.NPV() << "\n"
<< " expected: " << cachedValue);
underlying = boost::shared_ptr<CreditDefaultSwap>(
new CreditDefaultSwap(Protection::Buyer, notional, strike, schedule,
convention, dayCounter));
underlying->setPricingEngine(swapEngine);
CdsOption option2(underlying, exercise);
option2.setPricingEngine(boost::shared_ptr<PricingEngine>(
new BlackCdsOptionEngine(defaultProbability, recoveryRate,
riskFree, cdsVol)));
cachedValue = 270.976348;
if (std::fabs(option2.NPV() - cachedValue) > 1.0e-5)
BOOST_ERROR("failed to reproduce cached value:\n"
<< std::fixed << std::setprecision(6)
<< " calculated: " << option2.NPV() << "\n"
<< " expected: " << cachedValue);
}