本文整理汇总了C#中CommonVars类的典型用法代码示例。如果您正苦于以下问题:C# CommonVars类的具体用法?C# CommonVars怎么用?C# CommonVars使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CommonVars类属于命名空间,在下文中一共展示了CommonVars类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: testCachedValue
public void testCachedValue()
{
//"Testing swaption value against cached value...");
CommonVars vars = new CommonVars();
vars.today = new Date(13, 3, 2002);
vars.settlement = new Date(15, 3, 2002);
Settings.setEvaluationDate( vars.today);
vars.termStructure.linkTo(Utilities.flatRate(vars.settlement, 0.05, new Actual365Fixed()));
Date exerciseDate = vars.calendar.advance(vars.settlement, new Period(5,TimeUnit.Years));
Date startDate = vars.calendar.advance(exerciseDate,
vars.settlementDays,TimeUnit.Days);
VanillaSwap swap =
new MakeVanillaSwap(new Period(10,TimeUnit.Years), vars.index, 0.06)
.withEffectiveDate(startDate);
Swaption swaption =
vars.makeSwaption(swap, exerciseDate, 0.20);
//#if QL_USE_INDEXED_COUPON
double cachedNPV = 0.036418158579;
//#else
// double cachedNPV = 0.036421429684;
//#endif
// FLOATING_POINT_EXCEPTION
if (Math.Abs(swaption.NPV()-cachedNPV) > 1.0e-12)
Assert.Fail ("failed to reproduce cached swaption value:\n" +
//QL_FIXED + std::setprecision(12) +
"\ncalculated: " + swaption.NPV() +
"\nexpected: " + cachedNPV);
}
示例2: testCachedValue
public void testCachedValue()
{
// Testing Black yoy inflation cap/floor price against cached values...
CommonVars vars = new CommonVars();
int whichPricer = 0; // black
double K = 0.0295; // one centi-point is fair rate error i.e. < 1 cp
int j = 2;
List<CashFlow> leg = vars.makeYoYLeg(vars.evaluationDate,j);
Instrument cap = vars.makeYoYCapFloor(CapFloorType.Cap,leg, K, 0.01, whichPricer);
Instrument floor = vars.makeYoYCapFloor(CapFloorType.Floor,leg, K, 0.01, whichPricer);
// close to atm prices
double cachedCapNPVblack = 219.452;
double cachedFloorNPVblack = 314.641;
// N.B. notionals are 10e6.
Assert.IsTrue(Math.Abs(cap.NPV()-cachedCapNPVblack)<0.02,"yoy cap cached NPV wrong "
+cap.NPV()+" should be "+cachedCapNPVblack+" Black pricer"
+" diff was "+(Math.Abs(cap.NPV()-cachedCapNPVblack)));
Assert.IsTrue(Math.Abs(floor.NPV()-cachedFloorNPVblack)<0.02,"yoy floor cached NPV wrong "
+floor.NPV()+" should be "+cachedFloorNPVblack+" Black pricer"
+" diff was "+(Math.Abs(floor.NPV()-cachedFloorNPVblack)));
whichPricer = 1; // dd
cap = vars.makeYoYCapFloor(CapFloorType.Cap,leg, K, 0.01, whichPricer);
floor = vars.makeYoYCapFloor(CapFloorType.Floor,leg, K, 0.01, whichPricer);
// close to atm prices
double cachedCapNPVdd = 9114.61;
double cachedFloorNPVdd = 9209.8;
// N.B. notionals are 10e6.
Assert.IsTrue(Math.Abs(cap.NPV()-cachedCapNPVdd)<0.22,"yoy cap cached NPV wrong "
+cap.NPV()+" should be "+cachedCapNPVdd+" dd Black pricer"
+" diff was "+(Math.Abs(cap.NPV()-cachedCapNPVdd)));
Assert.IsTrue(Math.Abs(floor.NPV()-cachedFloorNPVdd)<0.22,"yoy floor cached NPV wrong "
+floor.NPV()+" should be "+cachedFloorNPVdd+" dd Black pricer"
+" diff was "+(Math.Abs(floor.NPV()-cachedFloorNPVdd)));
whichPricer = 2; // bachelier
cap = vars.makeYoYCapFloor(CapFloorType.Cap,leg, K, 0.01, whichPricer);
floor = vars.makeYoYCapFloor(CapFloorType.Floor,leg, K, 0.01, whichPricer);
// close to atm prices
double cachedCapNPVbac = 8852.4;
double cachedFloorNPVbac = 8947.59;
// N.B. notionals are 10e6.
Assert.IsTrue(Math.Abs(cap.NPV()-cachedCapNPVbac)<0.22,"yoy cap cached NPV wrong "
+cap.NPV()+" should be "+cachedCapNPVbac+" bac Black pricer"
+" diff was "+(Math.Abs(cap.NPV()-cachedCapNPVbac)));
Assert.IsTrue(Math.Abs(floor.NPV()-cachedFloorNPVbac)<0.22,"yoy floor cached NPV wrong "
+floor.NPV()+" should be "+cachedFloorNPVbac+" bac Black pricer"
+" diff was "+(Math.Abs(floor.NPV()-cachedFloorNPVbac)));
// remove circular refernce
vars.hy.linkTo(new YoYInflationTermStructure());
}
示例3: testFairRate
public void testFairRate()
{
//("Testing vanilla-swap calculation of fair fixed rate...");
CommonVars vars = new CommonVars();
int[] lengths = new int[] { 1, 2, 5, 10, 20 };
double[] spreads = new double[] { -0.001, -0.01, 0.0, 0.01, 0.001 };
for (int i = 0; i < lengths.Length; i++)
{
for (int j = 0; j < spreads.Length; j++)
{
VanillaSwap swap = vars.makeSwap(lengths[i], 0.0, spreads[j]);
swap = vars.makeSwap(lengths[i], swap.fairRate(), spreads[j]);
if (Math.Abs(swap.NPV()) > 1.0e-10)
{
Assert.Fail("recalculating with implied rate:\n"
+ " length: " + lengths[i] + " years\n"
+ " floating spread: "
+ spreads[j] + "\n"
+ " swap value: " + swap.NPV());
}
}
}
}
示例4: testFlatInterpolationLeft
public void testFlatInterpolationLeft()
{
// Testing flat interpolation before the first spreaded date...
CommonVars vars = new CommonVars();
List<Handle<Quote>> spreads = new List<Handle<Quote>>();
SimpleQuote spread1 = new SimpleQuote(0.02);
SimpleQuote spread2 = new SimpleQuote(0.03);
spreads.Add(new Handle<Quote>(spread1));
spreads.Add(new Handle<Quote>(spread2));
List<Date> spreadDates = new List<Date>();
spreadDates.Add(vars.calendar.advance(vars.today, 8, TimeUnit.Months));
spreadDates.Add(vars.calendar.advance(vars.today, 15, TimeUnit.Months));
Date interpolationDate = vars.calendar.advance(vars.today, 6, TimeUnit.Months);
ZeroYieldStructure spreadedTermStructure =
new PiecewiseZeroSpreadedTermStructure(
new Handle<YieldTermStructure>(vars.termStructure),
spreads, spreadDates);
double t = vars.dayCount.yearFraction(vars.today, interpolationDate);
double interpolatedZeroRate = spreadedTermStructure.zeroRate(t, vars.compounding).value();
double tolerance = 1e-9;
double expectedRate = vars.termStructure.zeroRate(t, vars.compounding).value() + spread1.value();
if (Math.Abs(interpolatedZeroRate - expectedRate) > tolerance)
Assert.Fail("unable to reproduce interpolated rate\n"
+ " calculated: " + interpolatedZeroRate + "\n"
+ " expected: " + expectedRate);
}
示例5: testATMRate
public void testATMRate()
{
CommonVars vars = new CommonVars();
int[] lengths = { 1, 2, 3, 5, 7, 10, 15, 20 };
double[] strikes = { 0.0, 0.03, 0.04, 0.05, 0.06, 0.07 };
double[] vols = { 0.01, 0.05, 0.10, 0.15, 0.20 };
Date startDate = vars.termStructure.link.referenceDate();
for (int i = 0; i < lengths.Length; i++) {
List<CashFlow> leg = vars.makeLeg(startDate, lengths[i]);
Date maturity = vars.calendar.advance(startDate, lengths[i], TimeUnit.Years, vars.convention);
Schedule schedule = new Schedule(startDate, maturity,
new Period(vars.frequency), vars.calendar,
vars.convention, vars.convention,
DateGeneration.Rule.Forward, false);
for (int j = 0; j < strikes.Length; j++) {
for (int k = 0; k < vols.Length; k++) {
CapFloor cap = vars.makeCapFloor(CapFloorType.Cap, leg, strikes[j], vols[k]);
CapFloor floor = vars.makeCapFloor(CapFloorType.Floor, leg, strikes[j], vols[k]);
double capATMRate = cap.atmRate(vars.termStructure);
double floorATMRate = floor.atmRate(vars.termStructure);
if (!checkAbsError(floorATMRate, capATMRate, 1.0e-10))
Assert.Fail(
"Cap ATM Rate and floor ATM Rate should be equal :\n"
+ " length: " + lengths[i] + " years\n"
+ " volatility: " + vols[k] + "\n"
+ " strike: " + strikes[j] + "\n"
+ " cap ATM rate: " + capATMRate + "\n"
+ " floor ATM rate:" + floorATMRate + "\n"
+ " relative Error:"
+ Utilities.relativeError(capATMRate, floorATMRate, capATMRate) * 100 + "%");
VanillaSwap swap = new VanillaSwap(VanillaSwap.Type.Payer, vars.nominals[0],
schedule, floorATMRate,
vars.index.dayCounter(),
schedule, vars.index, 0.0,
vars.index.dayCounter());
swap.setPricingEngine((IPricingEngine)(
new DiscountingSwapEngine(vars.termStructure)));
double swapNPV = swap.NPV();
if (!checkAbsError(swapNPV, 0, 1.0e-10))
Assert.Fail(
"the NPV of a Swap struck at ATM rate "
+ "should be equal to 0:\n"
+ " length: " + lengths[i] + " years\n"
+ " volatility: " + vols[k] + "\n"
+ " ATM rate: " + floorATMRate + "\n"
+ " swap NPV: " + swapNPV);
}
}
}
}
示例6: testSwaptionVolMatrixCoherence
public void testSwaptionVolMatrixCoherence()
{
//"Testing swaption volatility matrix...");
CommonVars vars = new CommonVars();
SwaptionVolatilityMatrix vol;
string description;
//floating reference date, floating market data
description = "floating reference date, floating market data";
vol = new SwaptionVolatilityMatrix(vars.conventions.calendar,
vars.conventions.optionBdc,
vars.atm.tenors.options,
vars.atm.tenors.swaps,
vars.atm.volsHandle,
vars.conventions.dayCounter);
vars.makeCoherenceTest(description, vol);
//fixed reference date, floating market data
description = "fixed reference date, floating market data";
vol = new SwaptionVolatilityMatrix(Settings.evaluationDate(),
vars.conventions.calendar,
vars.conventions.optionBdc,
vars.atm.tenors.options,
vars.atm.tenors.swaps,
vars.atm.volsHandle,
vars.conventions.dayCounter);
vars.makeCoherenceTest(description, vol);
// floating reference date, fixed market data
description = "floating reference date, fixed market data";
vol = new SwaptionVolatilityMatrix(vars.conventions.calendar,
vars.conventions.optionBdc,
vars.atm.tenors.options,
vars.atm.tenors.swaps,
vars.atm.volsHandle,
vars.conventions.dayCounter);
vars.makeCoherenceTest(description, vol);
// fixed reference date, fixed market data
description = "fixed reference date, fixed market data";
vol = new SwaptionVolatilityMatrix(Settings.evaluationDate(),
vars.conventions.calendar,
vars.conventions.optionBdc,
vars.atm.tenors.options,
vars.atm.tenors.swaps,
vars.atm.volsHandle,
vars.conventions.dayCounter);
vars.makeCoherenceTest(description, vol);
}
示例7: testFSpreadedObs
public void testFSpreadedObs()
{
// ("Testing observability of forward-spreaded term structure...");
CommonVars vars = new CommonVars();
SimpleQuote me = new SimpleQuote(0.01);
Handle<Quote> mh = new Handle<Quote>(me);
RelinkableHandle<YieldTermStructure> h = new RelinkableHandle<YieldTermStructure>(); //(vars.dummyTermStructure);
YieldTermStructure spreaded = new ForwardSpreadedTermStructure(h, mh);
Flag flag = new Flag();
spreaded.registerWith(flag.update);
h.linkTo(vars.termStructure);
if (!flag.isUp())
Console.WriteLine("Observer was not notified of term structure change");
flag.lower();
me.setValue(0.005);
if (!flag.isUp())
Console.WriteLine("Observer was not notified of spread change");
}
示例8: testBackwardFlatInterpolation
public void testBackwardFlatInterpolation()
{
// Testing backward flat interpolation between two dates...
CommonVars vars = new CommonVars();
List<Handle<Quote>> spreads = new List<Handle<Quote>>();
SimpleQuote spread1 = new SimpleQuote(0.02);
SimpleQuote spread2 = new SimpleQuote(0.03);
SimpleQuote spread3 = new SimpleQuote(0.04);
spreads.Add(new Handle<Quote>(spread1));
spreads.Add(new Handle<Quote>(spread2));
spreads.Add(new Handle<Quote>(spread3));
List<Date> spreadDates = new List<Date>();
spreadDates.Add(vars.calendar.advance(vars.today, 100, TimeUnit.Days));
spreadDates.Add(vars.calendar.advance(vars.today, 200, TimeUnit.Days));
spreadDates.Add(vars.calendar.advance(vars.today, 300, TimeUnit.Days));
Date interpolationDate = vars.calendar.advance(vars.today, 110, TimeUnit.Days);
ZeroYieldStructure spreadedTermStructure =
new InterpolatedPiecewiseZeroSpreadedTermStructure<BackwardFlat>(
new Handle<YieldTermStructure>(vars.termStructure),
spreads, spreadDates);
double t = vars.dayCount.yearFraction(vars.today, interpolationDate);
double interpolatedZeroRate = spreadedTermStructure.zeroRate(t, vars.compounding).value();
double tolerance = 1e-9;
double expectedRate = vars.termStructure.zeroRate(t, vars.compounding).value() +
spread2.value();
if (Math.Abs(interpolatedZeroRate - expectedRate) > tolerance)
Assert.Fail(
"unable to reproduce interpolated rate\n"
+ " calculated: " + interpolatedZeroRate + "\n"
+ " expected: " + expectedRate);
}
示例9: testFSpreaded
public void testFSpreaded()
{
//("Testing consistency of forward-spreaded term structure...");
CommonVars vars = new CommonVars();
double tolerance = 1.0e-10;
Quote me = new SimpleQuote(0.01);
Handle<Quote> mh = new Handle<Quote>(me);
YieldTermStructure spreaded = new ForwardSpreadedTermStructure(new Handle<YieldTermStructure>(vars.termStructure), mh);
Date testDate = vars.termStructure.referenceDate() + new Period(5, TimeUnit.Years);
DayCounter tsdc = vars.termStructure.dayCounter();
DayCounter sprdc = spreaded.dayCounter();
double forward = vars.termStructure.forwardRate(testDate, testDate, tsdc, Compounding.Continuous,
Frequency.NoFrequency).rate();
double spreadedForward = spreaded.forwardRate(testDate, testDate, sprdc, Compounding.Continuous,
Frequency.NoFrequency).rate();
if (Math.Abs(forward - (spreadedForward - me.value())) > tolerance)
Console.WriteLine("unable to reproduce forward from spreaded curve\n"
+ " calculated: "
+ (spreadedForward - me.value()) + "\n"
+ " expected: " + forward);
}
示例10: testCachedValue
public void testCachedValue()
{
//("Testing vanilla-swap calculation against cached value...");
CommonVars vars = new CommonVars();
vars.today = new Date(17, Month.June, 2002);
Settings.setEvaluationDate(vars.today);
vars.settlement = vars.calendar.advance(vars.today, vars.settlementDays, TimeUnit.Days);
vars.termStructure.linkTo(Utilities.flatRate(vars.settlement, 0.05, new Actual365Fixed()));
VanillaSwap swap = vars.makeSwap(10, 0.06, 0.001);
#if QL_USE_INDEXED_COUPON
double cachedNPV = -5.872342992212;
#else
double cachedNPV = -5.872863313209;
#endif
if (Math.Abs(swap.NPV() - cachedNPV) > 1.0e-11)
Assert.Fail("failed to reproduce cached swap value:\n"
+ " calculated: " + swap.NPV() + "\n"
+ " expected: " + cachedNPV);
}
示例11: testZSpreadWithGenericBond
public void testZSpreadWithGenericBond()
{
// Testing clean and dirty price with null Z-spread against theoretical prices...
CommonVars vars = new CommonVars();
Calendar bondCalendar = new TARGET();
int settlementDays = 3;
int fixingDays = 2;
bool inArrears = false;
// Fixed Underlying bond (Isin: DE0001135275 DBR 4 01/04/37)
// maturity doesn't occur on a business day
Date fixedBondStartDate1 = new Date(4,Month.January,2005);
Date fixedBondMaturityDate1 = new Date(4,Month.January,2037);
Schedule fixedBondSchedule1= new Schedule(fixedBondStartDate1,
fixedBondMaturityDate1,
new Period(Frequency.Annual), bondCalendar,
BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
DateGeneration.Rule.Backward, false);
List<CashFlow> fixedBondLeg1 = new FixedRateLeg(fixedBondSchedule1)
.withCouponRates(0.04, new ActualActual(ActualActual.Convention.ISDA))
.withNotionals(vars.faceAmount);
Date fixedbondRedemption1 = bondCalendar.adjust(fixedBondMaturityDate1,
BusinessDayConvention.Following);
fixedBondLeg1.Add(new SimpleCashFlow(100.0, fixedbondRedemption1));
Bond fixedBond1 = new Bond(settlementDays, bondCalendar, vars.faceAmount, fixedBondMaturityDate1, fixedBondStartDate1,
fixedBondLeg1);
IPricingEngine bondEngine = new DiscountingBondEngine(vars.termStructure);
fixedBond1.setPricingEngine(bondEngine);
double fixedBondImpliedValue1 = fixedBond1.cleanPrice();
Date fixedBondSettlementDate1= fixedBond1.settlementDate();
// standard market conventions:
// bond's frequency + coumpounding and daycounter of the YieldCurve
double fixedBondCleanPrice1 = BondFunctions.cleanPrice(fixedBond1, vars.termStructure, vars.spread,
new Actual365Fixed(), vars.compounding, Frequency.Annual, fixedBondSettlementDate1);
double tolerance = 1.0e-13;
double error1 = Math.Abs(fixedBondImpliedValue1-fixedBondCleanPrice1);
if (error1>tolerance) {
Assert.Fail("wrong clean price for fixed bond:"
+ "\n market asset swap spread: "
+ fixedBondImpliedValue1
+ "\n par asset swap spread: " + fixedBondCleanPrice1
+ "\n error: " + error1
+ "\n tolerance: " + tolerance);
}
// Fixed Underlying bond (Isin: IT0006527060 IBRD 5 02/05/19)
// maturity occurs on a business day
Date fixedBondStartDate2 = new Date(5,Month.February,2005);
Date fixedBondMaturityDate2 = new Date(5,Month.February,2019);
Schedule fixedBondSchedule2= new Schedule(fixedBondStartDate2,
fixedBondMaturityDate2,
new Period(Frequency.Annual), bondCalendar,
BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
DateGeneration.Rule.Backward, false);
List<CashFlow> fixedBondLeg2 = new FixedRateLeg(fixedBondSchedule2)
.withCouponRates(0.05, new Thirty360(Thirty360.Thirty360Convention.BondBasis))
.withNotionals(vars.faceAmount);
Date fixedbondRedemption2 = bondCalendar.adjust(fixedBondMaturityDate2, BusinessDayConvention.Following);
fixedBondLeg2.Add(new SimpleCashFlow(100.0, fixedbondRedemption2));
Bond fixedBond2 = new Bond(settlementDays, bondCalendar, vars.faceAmount,
fixedBondMaturityDate2, fixedBondStartDate2, fixedBondLeg2);
fixedBond2.setPricingEngine(bondEngine);
double fixedBondImpliedValue2 = fixedBond2.cleanPrice();
Date fixedBondSettlementDate2= fixedBond2.settlementDate();
// standard market conventions:
// bond's frequency + coumpounding and daycounter of the YieldCurve
double fixedBondCleanPrice2 = BondFunctions.cleanPrice(fixedBond2, vars.termStructure, vars.spread,
new Actual365Fixed(), vars.compounding, Frequency.Annual, fixedBondSettlementDate2);
double error3 = Math.Abs(fixedBondImpliedValue2-fixedBondCleanPrice2);
if (error3>tolerance) {
Assert.Fail("wrong clean price for fixed bond:"
+ "\n market asset swap spread: "
+ fixedBondImpliedValue2
+ "\n par asset swap spread: " + fixedBondCleanPrice2
+ "\n error: " + error3
+ "\n tolerance: " + tolerance);
}
// FRN Underlying bond (Isin: IT0003543847 ISPIM 0 09/29/13)
// maturity doesn't occur on a business day
Date floatingBondStartDate1 = new Date(29,Month.September,2003);
Date floatingBondMaturityDate1 = new Date(29,Month.September,2013);
Schedule floatingBondSchedule1= new Schedule(floatingBondStartDate1,
floatingBondMaturityDate1,
new Period(Frequency.Semiannual), bondCalendar,
BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
DateGeneration.Rule.Backward, false);
List<CashFlow> floatingBondLeg1 = new IborLeg(floatingBondSchedule1, vars.iborIndex)
.withPaymentDayCounter(new Actual360())
.withFixingDays(fixingDays)
.withSpreads(0.0056)
.inArrears(inArrears)
//.........这里部分代码省略.........
示例12: testParity
public void testParity()
{
// Testing yoy inflation cap/floor parity...
CommonVars vars = new CommonVars();
int[] lengths = { 1, 2, 3, 5, 7, 10, 15, 20 };
// vol is low ...
double[] strikes = { 0.0, 0.025, 0.029, 0.03, 0.031, 0.035, 0.07 };
// yoy inflation vol is generally very low
double[] vols = { 0.001, 0.005, 0.010, 0.015, 0.020 };
// cap-floor-swap parity is model-independent
for (int whichPricer = 0; whichPricer < 3; whichPricer++) {
for (int i=0; i<lengths.Length; i++) {
for (int j=0; j<strikes.Length; j++) {
for (int k=0; k<vols.Length; k++) {
List<CashFlow> leg = vars.makeYoYLeg(vars.evaluationDate,lengths[i]);
Instrument cap = vars.makeYoYCapFloor(CapFloorType.Cap,
leg, strikes[j], vols[k], whichPricer);
Instrument floor = vars.makeYoYCapFloor(CapFloorType.Floor,
leg, strikes[j], vols[k], whichPricer);
Date from = vars.nominalTS.link.referenceDate();
Date to = from+new Period(lengths[i],TimeUnit.Years);
Schedule yoySchedule = new MakeSchedule().from(from).to(to)
.withTenor(new Period(1,TimeUnit.Years))
.withConvention(BusinessDayConvention.Unadjusted)
.withCalendar(new UnitedKingdom()).backwards().value();
YearOnYearInflationSwap swap = new YearOnYearInflationSwap
(YearOnYearInflationSwap.Type.Payer,
1000000.0,
yoySchedule,//fixed schedule, but same as yoy
strikes[j],
vars.dc,
yoySchedule,
vars.iir,
vars.observationLag,
0.0, //spread on index
vars.dc,
new UnitedKingdom());
Handle<YieldTermStructure> hTS = new Handle<YieldTermStructure>(vars.nominalTS);
IPricingEngine sppe = new DiscountingSwapEngine(hTS);
swap.setPricingEngine(sppe);
// N.B. nominals are 10e6
if (Math.Abs((cap.NPV()-floor.NPV()) - swap.NPV()) > 1.0e-6) {
Assert.Fail(
"put/call parity violated:\n"
+ " length: " + lengths[i] + " years\n"
+ " volatility: " + vols[k] + "\n"
+ " strike: " + strikes[j] + "\n"
+ " cap value: " + cap.NPV() + "\n"
+ " floor value: " + floor.NPV() + "\n"
+ " swap value: " + swap.NPV());
}
}
}
}
}
// remove circular refernce
vars.hy.linkTo(new YoYInflationTermStructure());
}
示例13: testConsistency
public void testConsistency()
{
// Testing consistency between yoy inflation cap,floor and collar...
CommonVars vars = new CommonVars();
int[] lengths = { 1, 2, 3, 5, 7, 10, 15, 20 };
double[] cap_rates = { 0.01, 0.025, 0.029, 0.03, 0.031, 0.035, 0.07 };
double[] floor_rates = { 0.01, 0.025, 0.029, 0.03, 0.031, 0.035, 0.07 };
double[] vols = { 0.001, 0.005, 0.010, 0.015, 0.020 };
for (int whichPricer = 0; whichPricer < 3; whichPricer++)
{
for (int i=0; i<lengths.Length; i++)
{
for (int j=0; j<cap_rates.Length; j++)
{
for (int k=0; k<floor_rates.Length; k++)
{
for (int l=0; l<vols.Length; l++)
{
List<CashFlow> leg = vars.makeYoYLeg(vars.evaluationDate,lengths[i]);
YoYInflationCapFloor cap = vars.makeYoYCapFloor(CapFloorType.Cap,
leg, cap_rates[j], vols[l], whichPricer);
YoYInflationCapFloor floor = vars.makeYoYCapFloor(CapFloorType.Floor,
leg, floor_rates[k], vols[l], whichPricer);
YoYInflationCollar collar = new YoYInflationCollar(leg,new List<double>(){cap_rates[j]},
new List<double>(){floor_rates[k]});
collar.setPricingEngine(vars.makeEngine(vols[l], whichPricer));
if (Math.Abs((cap.NPV()-floor.NPV())-collar.NPV()) > 1e-6)
{
Assert.Fail(
"inconsistency between cap, floor and collar:\n"
+ " length: " + lengths[i] + " years\n"
+ " volatility: " + "\n"
+ " cap value: " + cap.NPV()
+ " at strike: " + "\n"
+ " floor value: " + floor.NPV()
+ " at strike: " + "\n"
+ " collar value: " + collar.NPV());
}
// test re-composition by optionlets, N.B. ONE per year
double capletsNPV = 0.0;
List<YoYInflationCapFloor> caplets = new List<YoYInflationCapFloor>();
for (int m=0; m<lengths[i]*1; m++)
{
caplets.Add(cap.optionlet(m));
caplets[m].setPricingEngine(vars.makeEngine(vols[l], whichPricer));
capletsNPV += caplets[m].NPV();
}
if (Math.Abs(cap.NPV() - capletsNPV) > 1e-6)
{
Assert.Fail(
"sum of caplet NPVs does not equal cap NPV:\n"
+ " length: " + lengths[i] + " years\n"
+ " volatility: " + "\n"
+ " cap value: " + cap.NPV()
+ " at strike: " + "\n"
+ " sum of caplets value: " + capletsNPV
+ " at strike (first): " + caplets[0].capRates()[0] + "\n"
);
}
double floorletsNPV = 0.0;
List<YoYInflationCapFloor> floorlets = new List<YoYInflationCapFloor>();
for (int m=0; m<lengths[i]*1; m++)
{
floorlets.Add(floor.optionlet(m));
floorlets[m].setPricingEngine(vars.makeEngine(vols[l], whichPricer));
floorletsNPV += floorlets[m].NPV();
}
if (Math.Abs(floor.NPV() - floorletsNPV) > 1e-6)
{
Assert.Fail(
"sum of floorlet NPVs does not equal floor NPV:\n"
+ " length: " + lengths[i] + " years\n"
+ " volatility: " + "\n"
+ " cap value: " + floor.NPV()
+ " at strike: " + floor_rates[j] + "\n"
+ " sum of floorlets value: " + floorletsNPV
+ " at strike (first): " + floorlets[0].floorRates()[0] + "\n"
);
}
double collarletsNPV = 0.0;
List<YoYInflationCapFloor> collarlets = new List<YoYInflationCapFloor>();
for (int m=0; m<lengths[i]*1; m++)
{
collarlets.Add(collar.optionlet(m));
collarlets[m].setPricingEngine(vars.makeEngine(vols[l], whichPricer));
collarletsNPV += collarlets[m].NPV();
}
//.........这里部分代码省略.........
示例14: testCachedZero
public void testCachedZero()
{
Console.WriteLine("Testing zero-coupon bond prices against cached values...");
CommonVars vars = new CommonVars();
Date today = new Date(22, Month.November, 2004);
Settings.setEvaluationDate(today);
int settlementDays = 1;
var discountCurve = new Handle<YieldTermStructure>(Utilities.flatRate(today, 0.03, new Actual360()));
double tolerance = 1.0e-6;
// plain
ZeroCouponBond bond1 = new ZeroCouponBond(settlementDays, new UnitedStates(UnitedStates.Market.GovernmentBond),
vars.faceAmount, new Date(30, Month.November, 2008), BusinessDayConvention.ModifiedFollowing,
100.0, new Date(30, Month.November, 2004));
IPricingEngine bondEngine = new DiscountingBondEngine(discountCurve);
bond1.setPricingEngine(bondEngine);
double cachedPrice1 = 88.551726;
double price = bond1.cleanPrice();
if (Math.Abs(price - cachedPrice1) > tolerance)
{
Console.WriteLine("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice1 + "\n"
+ " error: " + (price - cachedPrice1));
}
ZeroCouponBond bond2 = new ZeroCouponBond(settlementDays, new UnitedStates(UnitedStates.Market.GovernmentBond),
vars.faceAmount, new Date(30, Month.November, 2007), BusinessDayConvention.ModifiedFollowing,
100.0, new Date(30, Month.November, 2004));
bond2.setPricingEngine(bondEngine);
double cachedPrice2 = 91.278949;
price = bond2.cleanPrice();
if (Math.Abs(price - cachedPrice2) > tolerance)
{
Console.WriteLine("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice2 + "\n"
+ " error: " + (price - cachedPrice2));
}
ZeroCouponBond bond3 = new ZeroCouponBond(settlementDays, new UnitedStates(UnitedStates.Market.GovernmentBond),
vars.faceAmount, new Date(30, Month.November, 2006), BusinessDayConvention.ModifiedFollowing,
100.0, new Date(30, Month.November, 2004));
bond3.setPricingEngine(bondEngine);
double cachedPrice3 = 94.098006;
price = bond3.cleanPrice();
if (Math.Abs(price - cachedPrice3) > tolerance)
{
Console.WriteLine("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice3 + "\n"
+ " error: " + (price - cachedPrice3));
}
}
示例15: testCachedFloating
public void testCachedFloating()
{
// "Testing floating-rate bond prices against cached values...");
CommonVars vars = new CommonVars();
Date today = new Date(22, Month.November, 2004);
Settings.setEvaluationDate(today);
int settlementDays = 1;
var riskFreeRate = new Handle<YieldTermStructure>(Utilities.flatRate(today, 0.025, new Actual360()));
var discountCurve = new Handle<YieldTermStructure>(Utilities.flatRate(today, 0.03, new Actual360()));
IborIndex index = new USDLibor(new Period(6, TimeUnit.Months), riskFreeRate);
int fixingDays = 1;
double tolerance = 1.0e-6;
IborCouponPricer pricer = new BlackIborCouponPricer(new Handle<OptionletVolatilityStructure>());
// plain
Schedule sch = new Schedule(new Date(30, Month.November, 2004), new Date(30, Month.November, 2008),
new Period(Frequency.Semiannual), new UnitedStates(UnitedStates.Market.GovernmentBond),
BusinessDayConvention.ModifiedFollowing, BusinessDayConvention.ModifiedFollowing,
DateGeneration.Rule.Backward, false);
FloatingRateBond bond1 = new FloatingRateBond(settlementDays, vars.faceAmount, sch,
index, new ActualActual(ActualActual.Convention.ISMA),
BusinessDayConvention.ModifiedFollowing, fixingDays,
new List<double>(), new List<double>(),
new List<double>(), new List<double>(),
false,
100.0, new Date(30, Month.November, 2004));
IPricingEngine bondEngine = new DiscountingBondEngine(riskFreeRate);
bond1.setPricingEngine(bondEngine);
Utils.setCouponPricer(bond1.cashflows(), pricer);
#if QL_USE_INDEXED_COUPON
double cachedPrice1 = 99.874645;
#else
double cachedPrice1 = 99.874646;
#endif
double price = bond1.cleanPrice();
if (Math.Abs(price - cachedPrice1) > tolerance)
{
Assert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice1 + "\n"
+ " error: " + (price - cachedPrice1));
}
// different risk-free and discount curve
FloatingRateBond bond2 = new FloatingRateBond(settlementDays, vars.faceAmount, sch,
index, new ActualActual(ActualActual.Convention.ISMA),
BusinessDayConvention.ModifiedFollowing, fixingDays,
new List<double>(), new List<double>(),
new List<double>(), new List<double>(),
false,
100.0, new Date(30, Month.November, 2004));
IPricingEngine bondEngine2 = new DiscountingBondEngine(discountCurve);
bond2.setPricingEngine(bondEngine2);
Utils.setCouponPricer(bond2.cashflows(), pricer);
#if QL_USE_INDEXED_COUPON
double cachedPrice2 = 97.955904;
#else
double cachedPrice2 = 97.955904;
#endif
price = bond2.cleanPrice();
if (Math.Abs(price - cachedPrice2) > tolerance)
{
Assert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice2 + "\n"
+ " error: " + (price - cachedPrice2));
}
// varying spread
InitializedList<double> spreads = new InitializedList<double>(4);
spreads[0] = 0.001;
spreads[1] = 0.0012;
spreads[2] = 0.0014;
spreads[3] = 0.0016;
FloatingRateBond bond3 = new FloatingRateBond(settlementDays, vars.faceAmount, sch,
index, new ActualActual(ActualActual.Convention.ISMA),
BusinessDayConvention.ModifiedFollowing, fixingDays,
new List<double>(), spreads,
new List<double>(), new List<double>(),
false,
100.0, new Date(30, Month.November, 2004));
bond3.setPricingEngine(bondEngine2);
//.........这里部分代码省略.........