Example #1
0
        public SwaptionHelper(Period maturity,
                              Period length,
                              Handle <Quote> volatility,
                              IborIndex index,
                              Period fixedLegTenor,
                              DayCounter fixedLegDayCounter,
                              DayCounter floatingLegDayCounter,
                              Handle <YieldTermStructure> termStructure,
                              bool calibrateVolatility /*= false*/)
            : base(volatility, termStructure, calibrateVolatility)
        {
            Calendar calendar   = index.fixingCalendar();
            Period   indexTenor = index.tenor();
            int      fixingDays = index.fixingDays();

            Date exerciseDate = calendar.advance(termStructure.link.referenceDate(),
                                                 maturity,
                                                 index.businessDayConvention());
            Date startDate = calendar.advance(exerciseDate,
                                              fixingDays, TimeUnit.Days,
                                              index.businessDayConvention());
            Date endDate = calendar.advance(startDate, length,
                                            index.businessDayConvention());

            Schedule fixedSchedule = new Schedule(startDate, endDate, fixedLegTenor, calendar,
                                                  index.businessDayConvention(),
                                                  index.businessDayConvention(),
                                                  DateGeneration.Rule.Forward, false);
            Schedule floatSchedule = new Schedule(startDate, endDate, index.tenor(), calendar,
                                                  index.businessDayConvention(),
                                                  index.businessDayConvention(),
                                                  DateGeneration.Rule.Forward, false);

            IPricingEngine swapEngine = new DiscountingSwapEngine(termStructure);

            VanillaSwap temp = new VanillaSwap(VanillaSwap.Type.Receiver, 1.0,
                                               fixedSchedule, 0.0, fixedLegDayCounter,
                                               floatSchedule, index, 0.0, floatingLegDayCounter);

            temp.setPricingEngine(swapEngine);
            exerciseRate_ = temp.fairRate();
            swap_         = new VanillaSwap(VanillaSwap.Type.Receiver, 1.0,
                                            fixedSchedule, exerciseRate_, fixedLegDayCounter,
                                            floatSchedule, index, 0.0, floatingLegDayCounter);
            swap_.setPricingEngine(swapEngine);

            Exercise exercise = new EuropeanExercise(exerciseDate);

            swaption_    = new Swaption(swap_, exercise);
            marketValue_ = blackPrice(volatility_.link.value());
        }
Example #2
0
        public SwaptionHelper(Period maturity,
            Period length,
            Handle<Quote> volatility,
            IborIndex index,
            Period fixedLegTenor,
            DayCounter fixedLegDayCounter,
            DayCounter floatingLegDayCounter,
            Handle<YieldTermStructure> termStructure,
            bool calibrateVolatility /*= false*/)
            : base(volatility,termStructure, calibrateVolatility)
        {
            Calendar calendar = index.fixingCalendar();
            Period indexTenor = index.tenor();
            int fixingDays = index.fixingDays();

            Date exerciseDate   = calendar.advance(termStructure.link.referenceDate(),
                                                maturity,
                                                index.businessDayConvention());
            Date startDate      = calendar.advance(exerciseDate,
                                                fixingDays, TimeUnit.Days,
                                                index.businessDayConvention());
            Date endDate        = calendar.advance(startDate, length,
                                                index.businessDayConvention());

            Schedule fixedSchedule=new Schedule(startDate, endDate, fixedLegTenor, calendar,
                                            index.businessDayConvention(),
                                            index.businessDayConvention(),
                                            DateGeneration.Rule.Forward, false);
            Schedule floatSchedule=new Schedule(startDate, endDate, index.tenor(), calendar,
                                            index.businessDayConvention(),
                                            index.businessDayConvention(),
                                            DateGeneration.Rule.Forward, false);

            IPricingEngine swapEngine=new DiscountingSwapEngine(termStructure);

            VanillaSwap temp=new VanillaSwap(VanillaSwap.Type.Receiver, 1.0,
                                        fixedSchedule, 0.0, fixedLegDayCounter,
                                        floatSchedule, index, 0.0, floatingLegDayCounter);
            temp.setPricingEngine(swapEngine);
            exerciseRate_ = temp.fairRate();
            swap_ = new VanillaSwap(VanillaSwap.Type.Receiver, 1.0,
                            fixedSchedule, exerciseRate_, fixedLegDayCounter,
                            floatSchedule, index, 0.0, floatingLegDayCounter);
            swap_.setPricingEngine(swapEngine);

            Exercise exercise=new EuropeanExercise(exerciseDate);
            swaption_ = new Swaption(swap_, exercise);
            marketValue_ = blackPrice(volatility_.link.value());
        }
Example #3
0
 public MakeCms(Period swapTenor,
                SwapIndex swapIndex,
                IborIndex iborIndex,
                double iborSpread   = 0.0,
                Period forwardStart = null,
                Date maturityDate   = null)
 {
     swapTenor_     = swapTenor;
     swapIndex_     = swapIndex;
     iborIndex_     = iborIndex;
     iborSpread_    = iborSpread;
     iborCap_       = null;
     iborFloor_     = null;
     useAtmSpread_  = false;
     forwardStart_  = forwardStart ?? new Period(0, TimeUnit.Days);
     cmsSpread_     = 0.0;
     cmsGearing_    = 1.0;
     cmsCap_        = null;
     cmsFloor_      = null;
     effectiveDate_ = null;
     cmsCalendar_   = swapIndex.fixingCalendar();
     floatCalendar_ = iborIndex.fixingCalendar();
     payCms_        = true;
     nominal_       = 1.0;
     maturityDate_  = maturityDate;
     cmsTenor_      = new Period(3, TimeUnit.Months);
     floatTenor_    = iborIndex.tenor();
     cmsConvention_ = BusinessDayConvention.ModifiedFollowing;
     cmsTerminationDateConvention_ = BusinessDayConvention.ModifiedFollowing;
     floatConvention_ = iborIndex.businessDayConvention();
     floatTerminationDateConvention_ = iborIndex.businessDayConvention();
     cmsRule_             = DateGeneration.Rule.Backward;
     floatRule_           = DateGeneration.Rule.Backward;
     cmsEndOfMonth_       = false;
     floatEndOfMonth_     = false;
     cmsFirstDate_        = null;
     cmsNextToLastDate_   = null;
     floatFirstDate_      = null;
     floatNextToLastDate_ = null;
     cmsDayCount_         = new Actual360();
     floatDayCount_       = iborIndex.dayCounter();
     engine_ = new DiscountingSwapEngine(swapIndex.forwardingTermStructure());
 }
Example #4
0
        public override void calculate()
        {
            if (!(arguments_.settlementType == Settlement.Type.Physical))
            {
                throw new ApplicationException("cash-settled swaptions not priced with Lfm engine");
            }

            double basisPoint = 1.0e-4;

            VanillaSwap    swap = arguments_.swap;
            IPricingEngine pe   = new DiscountingSwapEngine(discountCurve_);

            swap.setPricingEngine(pe);

            double correction = swap.spread *
                                Math.Abs(swap.floatingLegBPS() / swap.fixedLegBPS());
            double fixedRate = swap.fixedRate - correction;
            double fairRate  = swap.fairRate() - correction;

            SwaptionVolatilityMatrix volatility =
                model_.getSwaptionVolatilityMatrix();

            Date       referenceDate = volatility.referenceDate();
            DayCounter dayCounter    = volatility.dayCounter();

            double exercise = dayCounter.yearFraction(referenceDate,
                                                      arguments_.exercise.date(0));
            double swapLength =
                dayCounter.yearFraction(referenceDate,
                                        arguments_.fixedPayDates.Last())
                - dayCounter.yearFraction(referenceDate,
                                          arguments_.fixedResetDates[0]);

            Option.Type w = arguments_.type == VanillaSwap.Type.Payer ?
                            Option.Type.Call : Option.Type.Put;
            double vol = volatility.volatility(exercise, swapLength,
                                               fairRate, true);

            results_.value = (swap.fixedLegBPS() / basisPoint) *
                             Utils.blackFormula(w, fixedRate, fairRate, vol * Math.Sqrt(exercise));
        }
Example #5
0
        public override void calculate()
        {
            Utils.QL_REQUIRE(arguments_.settlementMethod != Settlement.Method.ParYieldCurve, () =>
                             "cash-settled (ParYieldCurve) swaptions not priced with Lfm engine");

            VanillaSwap    swap = arguments_.swap;
            IPricingEngine pe   = new DiscountingSwapEngine(discountCurve_);

            swap.setPricingEngine(pe);

            double correction = swap.spread *
                                Math.Abs(swap.floatingLegBPS() / swap.fixedLegBPS());
            double fixedRate = swap.fixedRate - correction;
            double fairRate  = swap.fairRate() - correction;

            SwaptionVolatilityMatrix volatility =
                model_.link.getSwaptionVolatilityMatrix();

            Date       referenceDate = volatility.referenceDate();
            DayCounter dayCounter    = volatility.dayCounter();

            double exercise = dayCounter.yearFraction(referenceDate,
                                                      arguments_.exercise.date(0));
            double swapLength =
                dayCounter.yearFraction(referenceDate,
                                        arguments_.fixedPayDates.Last())
                - dayCounter.yearFraction(referenceDate,
                                          arguments_.fixedResetDates[0]);

            Option.Type w = arguments_.type == VanillaSwap.Type.Payer ?
                            Option.Type.Call : Option.Type.Put;
            double vol = volatility.volatility(exercise, swapLength,
                                               fairRate, true);

            results_.value = (swap.fixedLegBPS() / Const.BASIS_POINT) *
                             Utils.blackFormula(w, fixedRate, fairRate, vol * Math.Sqrt(exercise));
        }
Example #6
0
        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());
        }
Example #7
0
        public OvernightIndexedSwap value()
        {
            Date startDate;

            if (effectiveDate_ != null)
            {
                startDate = effectiveDate_;
            }
            else
            {
                Date refDate = Settings.evaluationDate();
                // if the evaluation date is not a business day
                // then move to the next business day
                refDate = calendar_.adjust(refDate);
                Date spotDate = calendar_.advance(refDate, new Period(settlementDays_, TimeUnit.Days));
                startDate = spotDate + forwardStart_;
                if (forwardStart_.length() < 0)
                {
                    startDate = calendar_.adjust(startDate, BusinessDayConvention.Preceding);
                }
                else
                {
                    startDate = calendar_.adjust(startDate, BusinessDayConvention.Following);
                }
            }

            // OIS end of month default
            bool usedEndOfMonth =
                isDefaultEOM_ ? calendar_.isEndOfMonth(startDate) : endOfMonth_;

            Date endDate = terminationDate_;

            if (endDate == null)
            {
                if (usedEndOfMonth)
                {
                    endDate = calendar_.advance(startDate,
                                                swapTenor_,
                                                BusinessDayConvention.ModifiedFollowing,
                                                usedEndOfMonth);
                }
                else
                {
                    endDate = startDate + swapTenor_;
                }
            }



            Schedule schedule = new Schedule(startDate, endDate,
                                             new Period(paymentFrequency_),
                                             calendar_,
                                             BusinessDayConvention.ModifiedFollowing,
                                             BusinessDayConvention.ModifiedFollowing,
                                             rule_,
                                             usedEndOfMonth);

            double?usedFixedRate = fixedRate_;

            if (fixedRate_ == null)
            {
                OvernightIndexedSwap temp = new OvernightIndexedSwap(type_, nominal_,
                                                                     schedule,
                                                                     0.0, // fixed rate
                                                                     fixedDayCount_,
                                                                     overnightIndex_, overnightSpread_);
                if (engine_ == null)
                {
                    Handle <YieldTermStructure> disc = overnightIndex_.forwardingTermStructure();
                    Utils.QL_REQUIRE(!disc.empty(), () => "null term structure set to this instance of " +
                                     overnightIndex_.name());
                    bool           includeSettlementDateFlows = false;
                    IPricingEngine engine = new DiscountingSwapEngine(disc, includeSettlementDateFlows);
                    temp.setPricingEngine(engine);
                }
                else
                {
                    temp.setPricingEngine(engine_);
                }

                usedFixedRate = temp.fairRate();
            }

            OvernightIndexedSwap ois = new OvernightIndexedSwap(type_, nominal_,
                                                                schedule,
                                                                usedFixedRate.Value, fixedDayCount_,
                                                                overnightIndex_, overnightSpread_);

            if (engine_ == null)
            {
                Handle <YieldTermStructure> disc          = overnightIndex_.forwardingTermStructure();
                bool           includeSettlementDateFlows = false;
                IPricingEngine engine = new DiscountingSwapEngine(disc, includeSettlementDateFlows);
                ois.setPricingEngine(engine);
            }
            else
            {
                ois.setPricingEngine(engine_);
            }

            return(ois);
        }
Example #8
0
        protected override void performCalculations()
        {
            Calendar calendar   = index_.fixingCalendar();
            int      fixingDays = index_.fixingDays();

            Date exerciseDate = exerciseDate_;

            if (exerciseDate == null)
            {
                exerciseDate = calendar.advance(termStructure_.link.referenceDate(),
                                                maturity_,
                                                index_.businessDayConvention());
            }

            Date startDate = calendar.advance(exerciseDate,
                                              fixingDays, TimeUnit.Days,
                                              index_.businessDayConvention());

            Date endDate = endDate_;

            if (endDate == null)
            {
                endDate = calendar.advance(startDate, length_,
                                           index_.businessDayConvention());
            }

            Schedule fixedSchedule = new Schedule(startDate, endDate, fixedLegTenor_, calendar,
                                                  index_.businessDayConvention(),
                                                  index_.businessDayConvention(),
                                                  DateGeneration.Rule.Forward, false);
            Schedule floatSchedule = new Schedule(startDate, endDate, index_.tenor(), calendar,
                                                  index_.businessDayConvention(),
                                                  index_.businessDayConvention(),
                                                  DateGeneration.Rule.Forward, false);

            IPricingEngine swapEngine = new DiscountingSwapEngine(termStructure_, false);

            VanillaSwap.Type type = VanillaSwap.Type.Receiver;

            VanillaSwap temp = new VanillaSwap(VanillaSwap.Type.Receiver, nominal_,
                                               fixedSchedule, 0.0, fixedLegDayCounter_,
                                               floatSchedule, index_, 0.0, floatingLegDayCounter_);

            temp.setPricingEngine(swapEngine);
            double forward = temp.fairRate();

            if (!strike_.HasValue)
            {
                exerciseRate_ = forward;
            }
            else
            {
                exerciseRate_ = strike_.Value;
                type          = strike_ <= forward ? VanillaSwap.Type.Receiver : VanillaSwap.Type.Payer;
                // ensure that calibration instrument is out of the money
            }
            swap_ = new VanillaSwap(type, nominal_,
                                    fixedSchedule, exerciseRate_, fixedLegDayCounter_,
                                    floatSchedule, index_, 0.0, floatingLegDayCounter_);
            swap_.setPricingEngine(swapEngine);

            Exercise exercise = new EuropeanExercise(exerciseDate);

            swaption_ = new Swaption(swap_, exercise);

            base.performCalculations();
        }
        public void testDecomposition()
        {
            // Testing collared coupon against its decomposition...

             CommonVars vars= new CommonVars();

             double tolerance = 1e-10;
             double npvVanilla,npvCappedLeg,npvFlooredLeg,npvCollaredLeg,npvCap,npvFloor,npvCollar;
             double error;
             double floorstrike = 0.05;
             double capstrike = 0.10;
             InitializedList<double> caps = new InitializedList<double>(vars.length,capstrike);
             List<double> caps0 = new List<double>();
             InitializedList<double> floors = new InitializedList<double>(vars.length,floorstrike);
             List<double> floors0 = new List<double>();
             double gearing_p = 0.5;
             double spread_p = 0.002;
             double gearing_n = -1.5;
             double spread_n = 0.12;
             // fixed leg with zero rate
             List<CashFlow> fixedLeg  = vars.makeFixedLeg(vars.startDate,vars.length);
             // floating leg with gearing=1 and spread=0
             List<CashFlow> floatLeg  = vars.makeYoYLeg(vars.startDate,vars.length);
             // floating leg with positive gearing (gearing_p) and spread<>0
             List<CashFlow> floatLeg_p = vars.makeYoYLeg(vars.startDate,vars.length,gearing_p,spread_p);
             // floating leg with negative gearing (gearing_n) and spread<>0
             List<CashFlow> floatLeg_n = vars.makeYoYLeg(vars.startDate,vars.length,gearing_n,spread_n);
             // Swap with null fixed leg and floating leg with gearing=1 and spread=0
             Swap vanillaLeg = new Swap(fixedLeg,floatLeg);
             // Swap with null fixed leg and floating leg with positive gearing and spread<>0
             Swap vanillaLeg_p = new Swap(fixedLeg,floatLeg_p);
             // Swap with null fixed leg and floating leg with negative gearing and spread<>0
             Swap vanillaLeg_n = new Swap(fixedLeg,floatLeg_n);

             IPricingEngine engine = new DiscountingSwapEngine(vars.nominalTS);

             vanillaLeg.setPricingEngine(engine);    // here use the autoset feature
             vanillaLeg_p.setPricingEngine(engine);
             vanillaLeg_n.setPricingEngine(engine);

             // CAPPED coupon - Decomposition of payoff
             // Payoff = Nom * Min(rate,strike) * accrualperiod =
             // = Nom * [rate + Min(0,strike-rate)] * accrualperiod =
             // = Nom * rate * accrualperiod - Nom * Max(rate-strike,0) * accrualperiod =
             // = VanillaFloatingLeg - Call
             //

             int whichPricer = 0;

             // Case gearing = 1 and spread = 0
             List<CashFlow> cappedLeg = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,
                              caps,floors0,vars.volatility);
             Swap capLeg = new Swap(fixedLeg,cappedLeg);
             capLeg.setPricingEngine(engine);
             YoYInflationCap cap = new YoYInflationCap(floatLeg, new List<double>(){capstrike});
             cap.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer));
             npvVanilla = vanillaLeg.NPV();
             npvCappedLeg = capLeg.NPV();
             npvCap = cap.NPV();
             error = Math.Abs(npvCappedLeg - (npvVanilla-npvCap));
             if (error>tolerance)
             {
            Assert.Fail("\nYoY Capped Leg: gearing=1, spread=0%, strike=" + capstrike*100 +
                        "%\n" +
                        "  Capped Floating Leg NPV: " + npvCappedLeg + "\n" +
                        "  Floating Leg NPV - Cap NPV: " + (npvVanilla - npvCap) + "\n" +
                        "  Diff: " + error );
             }

             // gearing = 1 and spread = 0
             // FLOORED coupon - Decomposition of payoff
             // Payoff = Nom * Max(rate,strike) * accrualperiod =
             // = Nom * [rate + Max(0,strike-rate)] * accrualperiod =
             // = Nom * rate * accrualperiod + Nom * Max(strike-rate,0) * accrualperiod =
             // = VanillaFloatingLeg + Put
             //

             List<CashFlow> flooredLeg = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,
                              caps0,floors,vars.volatility);
             Swap floorLeg = new Swap(fixedLeg,flooredLeg);
             floorLeg.setPricingEngine(engine);
             YoYInflationFloor floor= new YoYInflationFloor(floatLeg, new List<double>(){floorstrike});
             floor.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer));
             npvFlooredLeg = floorLeg.NPV();
             npvFloor = floor.NPV();
             error = Math.Abs(npvFlooredLeg-(npvVanilla + npvFloor));
             if (error>tolerance)
             {
            Assert.Fail("YoY Floored Leg: gearing=1, spread=0%, strike=" + floorstrike *100 +
                        "%\n" +
                        "  Floored Floating Leg NPV: " + npvFlooredLeg + "\n" +
                        "  Floating Leg NPV + Floor NPV: " + (npvVanilla + npvFloor) + "\n" +
                        "  Diff: " + error );
             }

             // gearing = 1 and spread = 0
             // COLLARED coupon - Decomposition of payoff
             // Payoff = Nom * Min(strikem,Max(rate,strikeM)) * accrualperiod =
             // = VanillaFloatingLeg - Collar
             //

             List<CashFlow> collaredLeg = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,
                              caps,floors,vars.volatility);
             Swap collarLeg = new Swap(fixedLeg,collaredLeg);
             collarLeg.setPricingEngine(engine);
             YoYInflationCollar collar = new YoYInflationCollar(floatLeg,
                     new List<double>(){capstrike},
                     new List<double>(){floorstrike});
             collar.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer));
             npvCollaredLeg = collarLeg.NPV();
             npvCollar = collar.NPV();
             error = Math.Abs(npvCollaredLeg -(npvVanilla - npvCollar));
             if (error>tolerance)
             {
            Assert.Fail("\nYoY Collared Leg: gearing=1, spread=0%, strike=" +
                        floorstrike*100 + "% and " + capstrike*100 + "%\n" +
                        "  Collared Floating Leg NPV: " + npvCollaredLeg + "\n" +
                        "  Floating Leg NPV - Collar NPV: " + (npvVanilla - npvCollar) + "\n" +
                        "  Diff: " + error );
             }

             // gearing = a and spread = b
             // CAPPED coupon - Decomposition of payoff
             // Payoff
             // = Nom * Min(a*rate+b,strike) * accrualperiod =
             // = Nom * [a*rate+b + Min(0,strike-a*rate-b)] * accrualperiod =
             // = Nom * a*rate+b * accrualperiod + Nom * Min(strike-b-a*rate,0) * accrualperiod
             // --> If a>0 (assuming positive effective strike):
             // Payoff = VanillaFloatingLeg - Call(a*rate+b,strike)
             // --> If a<0 (assuming positive effective strike):
             // Payoff = VanillaFloatingLeg + Nom * Min(strike-b+|a|*rate+,0) * accrualperiod =
             // = VanillaFloatingLeg + Put(|a|*rate+b,strike)
             //

             // Positive gearing
             List<CashFlow> cappedLeg_p = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,caps,floors0,
                              vars.volatility,gearing_p,spread_p);
             Swap capLeg_p = new Swap(fixedLeg,cappedLeg_p);
             capLeg_p.setPricingEngine(engine);
             YoYInflationCap cap_p = new YoYInflationCap(floatLeg_p,new List<double>(){capstrike});
             cap_p.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer));
             npvVanilla = vanillaLeg_p.NPV();
             npvCappedLeg = capLeg_p.NPV();
             npvCap = cap_p.NPV();
             error = Math.Abs(npvCappedLeg - (npvVanilla-npvCap));
             if (error>tolerance)
             {
            Assert.Fail("\nYoY Capped Leg: gearing=" + gearing_p + ", " +
                        "spread= " + spread_p *100 +
                        "%, strike=" + capstrike*100  + "%, " +
                        "effective strike= " + (capstrike-spread_p)/gearing_p*100 +
                        "%\n" +
                        "  Capped Floating Leg NPV: " + npvCappedLeg + "\n" +
                        "  Vanilla Leg NPV: " + npvVanilla + "\n" +
                        "  Cap NPV: " + npvCap + "\n" +
                        "  Floating Leg NPV - Cap NPV: " + (npvVanilla - npvCap) + "\n" +
                        "  Diff: " + error );
             }

             // Negative gearing
             List<CashFlow> cappedLeg_n = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,caps,floors0,
                              vars.volatility,gearing_n,spread_n);
             Swap capLeg_n = new Swap(fixedLeg,cappedLeg_n);
             capLeg_n.setPricingEngine(engine);
             YoYInflationFloor floor_n = new YoYInflationFloor(floatLeg,new List<double>(){(capstrike-spread_n)/gearing_n});
             floor_n.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer));
             npvVanilla = vanillaLeg_n.NPV();
             npvCappedLeg = capLeg_n.NPV();
             npvFloor = floor_n.NPV();
             error = Math.Abs(npvCappedLeg - (npvVanilla+ gearing_n*npvFloor));
             if (error>tolerance)
             {
            Assert.Fail("\nYoY Capped Leg: gearing=" + gearing_n + ", " +
                        "spread= " + spread_n *100 +
                        "%, strike=" + capstrike*100  + "%, " +
                        "effective strike= " + ((capstrike-spread_n)/gearing_n*100) +
                        "%\n" +
                        "  Capped Floating Leg NPV: " + npvCappedLeg + "\n" +
                        "  npv Vanilla: " + npvVanilla + "\n" +
                        "  npvFloor: " + npvFloor + "\n" +
                        "  Floating Leg NPV - Cap NPV: " + (npvVanilla + gearing_n*npvFloor) + "\n" +
                        "  Diff: " + error );
             }

             // gearing = a and spread = b
             // FLOORED coupon - Decomposition of payoff
             // Payoff
             // = Nom * Max(a*rate+b,strike) * accrualperiod =
             // = Nom * [a*rate+b + Max(0,strike-a*rate-b)] * accrualperiod =
             // = Nom * a*rate+b * accrualperiod + Nom * Max(strike-b-a*rate,0) * accrualperiod
             // --> If a>0 (assuming positive effective strike):
             // Payoff = VanillaFloatingLeg + Put(a*rate+b,strike)
             // --> If a<0 (assuming positive effective strike):
             // Payoff = VanillaFloatingLeg + Nom * Max(strike-b+|a|*rate+,0) * accrualperiod =
             // = VanillaFloatingLeg - Call(|a|*rate+b,strike)
             //

             // Positive gearing
             List<CashFlow> flooredLeg_p1 = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,caps0,floors,
                              vars.volatility,gearing_p,spread_p);
             Swap floorLeg_p1 = new Swap(fixedLeg,flooredLeg_p1);
             floorLeg_p1.setPricingEngine(engine);
             YoYInflationFloor floor_p1 = new YoYInflationFloor(floatLeg_p,new List<double>(){floorstrike});
             floor_p1.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer));
             npvVanilla = vanillaLeg_p.NPV();
             npvFlooredLeg = floorLeg_p1.NPV();
             npvFloor = floor_p1.NPV();
             error = Math.Abs(npvFlooredLeg - (npvVanilla+npvFloor));
             if (error>tolerance)
             {
            Assert.Fail("\nYoY Floored Leg: gearing=" + gearing_p + ", "
                        + "spread= " + spread_p *100+ "%, strike=" + floorstrike *100 + "%, "
                        + "effective strike= " + (floorstrike-spread_p)/gearing_p*100
                        + "%\n" +
                        "  Floored Floating Leg NPV: "    + npvFlooredLeg
                        + "\n" +
                        "  Floating Leg NPV + Floor NPV: " + (npvVanilla + npvFloor)
                        + "\n" +
                        "  Diff: " + error );
             }
             // Negative gearing
             List<CashFlow> flooredLeg_n = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,caps0,floors,
                              vars.volatility,gearing_n,spread_n);
             Swap floorLeg_n = new Swap(fixedLeg,flooredLeg_n);
             floorLeg_n.setPricingEngine(engine);
             YoYInflationCap cap_n = new YoYInflationCap(floatLeg,new List<double>(){(floorstrike-spread_n)/gearing_n});
             cap_n.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer));
             npvVanilla = vanillaLeg_n.NPV();
             npvFlooredLeg = floorLeg_n.NPV();
             npvCap = cap_n.NPV();
             error = Math.Abs(npvFlooredLeg - (npvVanilla - gearing_n*npvCap));
             if (error>tolerance)
             {
            Assert.Fail("\nYoY Capped Leg: gearing=" + gearing_n + ", " +
                        "spread= " + spread_n *100 +
                        "%, strike=" + floorstrike*100  + "%, " +
                        "effective strike= " + (floorstrike-spread_n)/gearing_n*100 +
                        "%\n" +
                        "  Capped Floating Leg NPV: " + npvFlooredLeg + "\n" +
                        "  Floating Leg NPV - Cap NPV: " + (npvVanilla - gearing_n*npvCap) + "\n" +
                        "  Diff: " + error );
             }
             // gearing = a and spread = b
             // COLLARED coupon - Decomposition of payoff
             // Payoff = Nom * Min(caprate,Max(a*rate+b,floorrate)) * accrualperiod
             // --> If a>0 (assuming positive effective strike):
             // Payoff = VanillaFloatingLeg - Collar(a*rate+b, floorrate, caprate)
             // --> If a<0 (assuming positive effective strike):
             // Payoff = VanillaFloatingLeg + Collar(|a|*rate+b, caprate, floorrate)
             //
             // Positive gearing
             List<CashFlow> collaredLeg_p = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,caps,floors,
                              vars.volatility,gearing_p,spread_p);
             Swap collarLeg_p1 = new Swap(fixedLeg,collaredLeg_p);
             collarLeg_p1.setPricingEngine(engine);
             YoYInflationCollar collar_p = new YoYInflationCollar(floatLeg_p,
                        new List<double>(){capstrike},
                        new List<double>(){floorstrike});
             collar_p.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer));
             npvVanilla = vanillaLeg_p.NPV();
             npvCollaredLeg = collarLeg_p1.NPV();
             npvCollar = collar_p.NPV();
             error = Math.Abs(npvCollaredLeg - (npvVanilla - npvCollar));
             if (error>tolerance)
             {
            Assert.Fail("\nYoY Collared Leg: gearing=" + gearing_p + ", "
                        + "spread= " + spread_p*100 + "%, strike="
                        + floorstrike*100 + "% and " + capstrike*100
                        + "%, "
                        + "effective strike=" + (floorstrike-spread_p)/gearing_p*100
                        +  "% and " + (capstrike-spread_p)/gearing_p*100
                        + "%\n" +
                        "  Collared Floating Leg NPV: "    + npvCollaredLeg
                        + "\n" +
                        "  Floating Leg NPV - Collar NPV: " + (npvVanilla - npvCollar)
                        + "\n" +
                        "  Diff: " + error );
             }
             // Negative gearing
             List<CashFlow> collaredLeg_n = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,caps,floors,
                              vars.volatility,gearing_n,spread_n);
             Swap collarLeg_n1 = new Swap(fixedLeg,collaredLeg_n);
             collarLeg_n1.setPricingEngine(engine);
             YoYInflationCollar collar_n = new YoYInflationCollar(floatLeg,
                        new List<double>(){(floorstrike-spread_n)/gearing_n},
                        new List<double>(){(capstrike-spread_n)/gearing_n});
             collar_n.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer));
             npvVanilla = vanillaLeg_n.NPV();
             npvCollaredLeg = collarLeg_n1.NPV();
             npvCollar = collar_n.NPV();
             error = Math.Abs(npvCollaredLeg - (npvVanilla - gearing_n*npvCollar));
             if (error>tolerance)
             {
            Assert.Fail("\nYoY Collared Leg: gearing=" + gearing_n + ", "
                        + "spread= " + spread_n*100 + "%, strike="
                        + floorstrike*100 + "% and " + capstrike*100
                        + "%, "
                        + "effective strike=" + (floorstrike-spread_n)/gearing_n*100
                        +  "% and " + (capstrike-spread_n)/gearing_n*100
                        + "%\n" +
                        "  Collared Floating Leg NPV: "    + npvCollaredLeg
                        + "\n" +
                        "  Floating Leg NPV - Collar NPV: " + (npvVanilla - gearing_n*npvCollar)
                        + "\n" +
                        "  Diff: " + error );
             }
             // remove circular refernce
             vars.hy.linkTo(new YoYInflationTermStructure());
        }
Example #10
0
        public void testMarketASWSpread()
        {
            // Testing relationship between market asset swap and par asset swap...
             CommonVars vars = new CommonVars();

             Calendar bondCalendar = new TARGET();
             int settlementDays = 3;
             int fixingDays = 2;
             bool payFixedRate = true;
             bool parAssetSwap = true;
             bool mktAssetSwap = false;
             bool inArrears = false;

             // Fixed Underlying bond (Isin: DE0001135275 DBR 4 01/04/37)
             // maturity doesn't occur on a business day

             Schedule fixedBondSchedule1 = new Schedule(new Date(4,Month.January,2005),
                                    new Date(4,Month.January,2037),
                                    new Period(Frequency.Annual), bondCalendar,
                                    BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                    DateGeneration.Rule.Backward, false);
             Bond fixedBond1 = new FixedRateBond(settlementDays, vars.faceAmount, fixedBondSchedule1,
                           new List<double>{0.04},
                           new ActualActual(ActualActual.Convention.ISDA),BusinessDayConvention.Following,
                           100.0, new Date(4,Month.January,2005));

             IPricingEngine bondEngine = new DiscountingBondEngine(vars.termStructure);
             IPricingEngine swapEngine = new DiscountingSwapEngine(vars.termStructure);
             fixedBond1.setPricingEngine(bondEngine);

             double fixedBondMktPrice1 = 89.22 ; // market price observed on 7th June 2007
             double fixedBondMktFullPrice1=fixedBondMktPrice1+fixedBond1.accruedAmount();
             AssetSwap fixedBondParAssetSwap1 = new AssetSwap(payFixedRate,
                                          fixedBond1, fixedBondMktPrice1,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             fixedBondParAssetSwap1.setPricingEngine(swapEngine);
             double fixedBondParAssetSwapSpread1 = fixedBondParAssetSwap1.fairSpread();
             AssetSwap fixedBondMktAssetSwap1 = new AssetSwap(payFixedRate,
                                          fixedBond1, fixedBondMktPrice1,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          mktAssetSwap);
             fixedBondMktAssetSwap1.setPricingEngine(swapEngine);
             double fixedBondMktAssetSwapSpread1 = fixedBondMktAssetSwap1.fairSpread();

             double tolerance = 1.0e-13;
             double error1 = Math.Abs(fixedBondMktAssetSwapSpread1- 100*fixedBondParAssetSwapSpread1/fixedBondMktFullPrice1);

             if (error1>tolerance) {
            Assert.Fail("wrong asset swap spreads for fixed bond:" +
                        "\n  market ASW spread: " + fixedBondMktAssetSwapSpread1 +
                        "\n  par ASW spread:    " + fixedBondParAssetSwapSpread1 +
                        "\n  error:             " + error1 +
                        "\n  tolerance:         " + tolerance);
             }

             // Fixed Underlying bond (Isin: IT0006527060 IBRD 5 02/05/19)
             // maturity occurs on a business day

             Schedule fixedBondSchedule2 = new Schedule(new Date(5,Month.February,2005),
                                    new Date(5,Month.February,2019),
                                    new Period(Frequency.Annual), bondCalendar,
                                    BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                    DateGeneration.Rule.Backward, false);
             Bond fixedBond2 = new FixedRateBond(settlementDays, vars.faceAmount, fixedBondSchedule2,
                           new List<double>{ 0.05},
                           new Thirty360(Thirty360.Thirty360Convention.BondBasis), BusinessDayConvention.Following,
                           100.0, new Date(5,Month.February,2005));

             fixedBond2.setPricingEngine(bondEngine);

             double fixedBondMktPrice2 = 99.98 ; // market price observed on 7th June 2007
             double fixedBondMktFullPrice2=fixedBondMktPrice2+fixedBond2.accruedAmount();
             AssetSwap fixedBondParAssetSwap2 = new AssetSwap(payFixedRate,
                                          fixedBond2, fixedBondMktPrice2,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             fixedBondParAssetSwap2.setPricingEngine(swapEngine);
             double fixedBondParAssetSwapSpread2 = fixedBondParAssetSwap2.fairSpread();
             AssetSwap fixedBondMktAssetSwap2 = new AssetSwap(payFixedRate,
                                          fixedBond2, fixedBondMktPrice2,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          mktAssetSwap);
             fixedBondMktAssetSwap2.setPricingEngine(swapEngine);
             double fixedBondMktAssetSwapSpread2 = fixedBondMktAssetSwap2.fairSpread();
             double error2 = Math.Abs(fixedBondMktAssetSwapSpread2-
                     100*fixedBondParAssetSwapSpread2/fixedBondMktFullPrice2);

             if (error2>tolerance) {
            Assert.Fail("wrong asset swap spreads for fixed bond:" +
                        "\n  market ASW spread: " + fixedBondMktAssetSwapSpread2 +
                        "\n  par ASW spread:    " + fixedBondParAssetSwapSpread2 +
                        "\n  error:             " + error2 +
                        "\n  tolerance:         " + tolerance);
             }

             // FRN Underlying bond (Isin: IT0003543847 ISPIM 0 09/29/13)
             // maturity doesn't occur on a business day

             Schedule floatingBondSchedule1 = new Schedule( new Date(29,Month.September,2003),
                                       new Date(29,Month.September,2013),
                                       new Period(Frequency.Semiannual), bondCalendar,
                                       BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                       DateGeneration.Rule.Backward, false);

             Bond floatingBond1 = new FloatingRateBond(settlementDays, vars.faceAmount,
                              floatingBondSchedule1,
                              vars.iborIndex, new Actual360(),
                              BusinessDayConvention.Following, fixingDays,
                              new List<double>{1}, new List<double>{0.0056},
                              new List<double>(), new List<double>(),
                              inArrears,
                              100.0, new Date(29,Month.September,2003));

             floatingBond1.setPricingEngine(bondEngine);

             Utils.setCouponPricer(floatingBond1.cashflows(), vars.pricer);
             vars.iborIndex.addFixing(new Date(27,Month.March,2007), 0.0402);
             // market price observed on 7th June 2007
             double floatingBondMktPrice1 = 101.64 ;
             double floatingBondMktFullPrice1 = floatingBondMktPrice1+floatingBond1.accruedAmount();
             AssetSwap floatingBondParAssetSwap1 = new AssetSwap(payFixedRate,
                                             floatingBond1, floatingBondMktPrice1,
                                             vars.iborIndex, vars.spread,
                                             null,
                                             vars.iborIndex.dayCounter(),
                                             parAssetSwap);
             floatingBondParAssetSwap1.setPricingEngine(swapEngine);
             double floatingBondParAssetSwapSpread1 = floatingBondParAssetSwap1.fairSpread();
             AssetSwap floatingBondMktAssetSwap1= new AssetSwap(payFixedRate,
                                             floatingBond1, floatingBondMktPrice1,
                                             vars.iborIndex, vars.spread,
                                             null,
                                             vars.iborIndex.dayCounter(),
                                             mktAssetSwap);
             floatingBondMktAssetSwap1.setPricingEngine(swapEngine);
             double floatingBondMktAssetSwapSpread1 = floatingBondMktAssetSwap1.fairSpread();
             double error3 = Math.Abs(floatingBondMktAssetSwapSpread1-
                     100*floatingBondParAssetSwapSpread1/floatingBondMktFullPrice1);

             if (error3>tolerance) {
            Assert.Fail("wrong asset swap spreads for floating bond:" +
                        "\n  market ASW spread: " + floatingBondMktAssetSwapSpread1 +
                        "\n  par ASW spread:    " + floatingBondParAssetSwapSpread1 +
                        "\n  error:             " + error3 +
                        "\n  tolerance:         " + tolerance);
             }

             // FRN Underlying bond (Isin: XS0090566539 COE 0 09/24/18)
             // maturity occurs on a business day

             Schedule floatingBondSchedule2 = new Schedule( new Date(24,Month.September,2004),
                                       new Date(24,Month.September,2018),
                                       new Period(Frequency.Semiannual), bondCalendar,
                                       BusinessDayConvention.ModifiedFollowing, BusinessDayConvention.ModifiedFollowing,
                                       DateGeneration.Rule.Backward, false);
             Bond floatingBond2 = new FloatingRateBond(settlementDays, vars.faceAmount,
                              floatingBondSchedule2,
                              vars.iborIndex, new Actual360(),
                              BusinessDayConvention.ModifiedFollowing, fixingDays,
                              new List<double>{1}, new List<double>{0.0025},
                              new List<double>(), new List<double>(),
                              inArrears,
                              100.0, new Date(24,Month.September,2004));

             floatingBond2.setPricingEngine(bondEngine);

             Utils.setCouponPricer(floatingBond2.cashflows(), vars.pricer);
             vars.iborIndex.addFixing(new Date(22,Month.March,2007), 0.04013);
             // market price observed on 7th June 2007
             double floatingBondMktPrice2 = 101.248 ;
             double floatingBondMktFullPrice2 = floatingBondMktPrice2+floatingBond2.accruedAmount();
             AssetSwap floatingBondParAssetSwap2= new AssetSwap(payFixedRate,
                                             floatingBond2, floatingBondMktPrice2,
                                             vars.iborIndex, vars.spread,
                                             null,
                                             vars.iborIndex.dayCounter(),
                                             parAssetSwap);
             floatingBondParAssetSwap2.setPricingEngine(swapEngine);
             double floatingBondParAssetSwapSpread2 = floatingBondParAssetSwap2.fairSpread();
             AssetSwap floatingBondMktAssetSwap2 = new AssetSwap(payFixedRate,
                                             floatingBond2, floatingBondMktPrice2,
                                             vars.iborIndex, vars.spread,
                                             null,
                                             vars.iborIndex.dayCounter(),
                                             mktAssetSwap);
             floatingBondMktAssetSwap2.setPricingEngine(swapEngine);
             double floatingBondMktAssetSwapSpread2 = floatingBondMktAssetSwap2.fairSpread();
             double error4 = Math.Abs(floatingBondMktAssetSwapSpread2-
                     100*floatingBondParAssetSwapSpread2/floatingBondMktFullPrice2);

             if (error4>tolerance) {
            Assert.Fail("wrong asset swap spreads for floating bond:" +
                        "\n  market ASW spread: " + floatingBondMktAssetSwapSpread2 +
                        "\n  par ASW spread:    " + floatingBondParAssetSwapSpread2 +
                        "\n  error:             " + error4 +
                        "\n  tolerance:         " + tolerance);
             }

             // CMS Underlying bond (Isin: XS0228052402 CRDIT 0 8/22/20)
             // maturity doesn't occur on a business day

             Schedule cmsBondSchedule1 = new Schedule( new Date(22,Month.August,2005),
                                 new Date(22,Month.August,2020),
                                 new Period(Frequency.Annual), bondCalendar,
                                 BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                 DateGeneration.Rule.Backward, false);
             Bond cmsBond1 = new CmsRateBond(settlementDays, vars.faceAmount, cmsBondSchedule1,
                        vars.swapIndex, new Thirty360(),
                        BusinessDayConvention.Following, fixingDays,
                        new List<double>{1.0}, new List<double>{0.0},
                        new List<double>{0.055}, new List<double>{0.025},
                        inArrears,
                        100.0, new Date(22,Month.August,2005));

             cmsBond1.setPricingEngine(bondEngine);

             Utils.setCouponPricer(cmsBond1.cashflows(), vars.cmspricer);
             vars.swapIndex.addFixing(new Date(18,Month.August,2006), 0.04158);
             double cmsBondMktPrice1 = 88.45 ; // market price observed on 7th June 2007
             double cmsBondMktFullPrice1 = cmsBondMktPrice1+cmsBond1.accruedAmount();
             AssetSwap cmsBondParAssetSwap1 = new AssetSwap(payFixedRate,
                                       cmsBond1, cmsBondMktPrice1,
                                       vars.iborIndex, vars.spread,
                                       null,
                                       vars.iborIndex.dayCounter(),
                                       parAssetSwap);
             cmsBondParAssetSwap1.setPricingEngine(swapEngine);
             double cmsBondParAssetSwapSpread1 = cmsBondParAssetSwap1.fairSpread();
             AssetSwap cmsBondMktAssetSwap1 = new AssetSwap(payFixedRate,
                                       cmsBond1, cmsBondMktPrice1,
                                       vars.iborIndex, vars.spread,
                                       null,
                                       vars.iborIndex.dayCounter(),
                                       mktAssetSwap);
             cmsBondMktAssetSwap1.setPricingEngine(swapEngine);
             double cmsBondMktAssetSwapSpread1 = cmsBondMktAssetSwap1.fairSpread();
             double error5 = Math.Abs(cmsBondMktAssetSwapSpread1-
                     100*cmsBondParAssetSwapSpread1/cmsBondMktFullPrice1);

             if (error5>tolerance) {
            Assert.Fail("wrong asset swap spreads for cms bond:" +
                        "\n  market ASW spread: " + cmsBondMktAssetSwapSpread1 +
                        "\n  par ASW spread:    " + cmsBondParAssetSwapSpread1 +
                        "\n  error:             " + error5 +
                        "\n  tolerance:         " + tolerance);
             }

             // CMS Underlying bond (Isin: XS0218766664 ISPIM 0 5/6/15)
             // maturity occurs on a business day

             Schedule cmsBondSchedule2 = new Schedule(new Date(06,Month.May,2005),
                                 new Date(06,Month.May,2015),
                                 new Period(Frequency.Annual), bondCalendar,
                                 BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                 DateGeneration.Rule.Backward, false);
             Bond cmsBond2 = new CmsRateBond(settlementDays, vars.faceAmount, cmsBondSchedule2,
                        vars.swapIndex, new Thirty360(),
                        BusinessDayConvention.Following, fixingDays,
                        new List<double>{0.84}, new List<double>{0.0},
                        new List<double>(), new List<double>(),
                        inArrears,
                        100.0, new Date(06,Month.May,2005));

             cmsBond2.setPricingEngine(bondEngine);

             Utils.setCouponPricer(cmsBond2.cashflows(), vars.cmspricer);
             vars.swapIndex.addFixing(new Date(04,Month.May,2006), 0.04217);
             double cmsBondMktPrice2 = 94.08 ; // market price observed on 7th June 2007
             double cmsBondMktFullPrice2 = cmsBondMktPrice2+cmsBond2.accruedAmount();
             AssetSwap cmsBondParAssetSwap2 = new AssetSwap(payFixedRate,
                                       cmsBond2, cmsBondMktPrice2,
                                       vars.iborIndex, vars.spread,
                                       null,
                                       vars.iborIndex.dayCounter(),
                                       parAssetSwap);
             cmsBondParAssetSwap2.setPricingEngine(swapEngine);
             double cmsBondParAssetSwapSpread2 = cmsBondParAssetSwap2.fairSpread();
             AssetSwap cmsBondMktAssetSwap2 = new AssetSwap(payFixedRate,
                                       cmsBond2, cmsBondMktPrice2,
                                       vars.iborIndex, vars.spread,
                                       null,
                                       vars.iborIndex.dayCounter(),
                                       mktAssetSwap);
             cmsBondMktAssetSwap2.setPricingEngine(swapEngine);
             double cmsBondMktAssetSwapSpread2 = cmsBondMktAssetSwap2.fairSpread();
             double error6 = Math.Abs(cmsBondMktAssetSwapSpread2-
                     100*cmsBondParAssetSwapSpread2/cmsBondMktFullPrice2);

             if (error6>tolerance) {
            Assert.Fail("wrong asset swap spreads for cms bond:" +
                        "\n  market ASW spread: " + cmsBondMktAssetSwapSpread2 +
                        "\n  par ASW spread:    " + cmsBondParAssetSwapSpread2 +
                        "\n  error:             " + error6 +
                        "\n  tolerance:         " + tolerance);
             }

             // Zero Coupon bond (Isin: DE0004771662 IBRD 0 12/20/15)
             // maturity doesn't occur on a business day

             Bond zeroCpnBond1 = new ZeroCouponBond(settlementDays, bondCalendar, vars.faceAmount,
                          new  Date(20,Month.December,2015), BusinessDayConvention.Following,
                           100.0, new Date(19,Month.December,1985));

             zeroCpnBond1.setPricingEngine(bondEngine);

             // market price observed on 12th June 2007
             double zeroCpnBondMktPrice1 = 70.436 ;
             double zeroCpnBondMktFullPrice1 = zeroCpnBondMktPrice1+zeroCpnBond1.accruedAmount();
             AssetSwap zeroCpnBondParAssetSwap1 = new AssetSwap(payFixedRate,zeroCpnBond1,
                                          zeroCpnBondMktPrice1,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             zeroCpnBondParAssetSwap1.setPricingEngine(swapEngine);
             double zeroCpnBondParAssetSwapSpread1 = zeroCpnBondParAssetSwap1.fairSpread();
             AssetSwap zeroCpnBondMktAssetSwap1 = new AssetSwap(payFixedRate,zeroCpnBond1,
                                          zeroCpnBondMktPrice1,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          mktAssetSwap);
             zeroCpnBondMktAssetSwap1.setPricingEngine(swapEngine);
             double zeroCpnBondMktAssetSwapSpread1 = zeroCpnBondMktAssetSwap1.fairSpread();
             double error7 = Math.Abs(zeroCpnBondMktAssetSwapSpread1-
                     100*zeroCpnBondParAssetSwapSpread1/zeroCpnBondMktFullPrice1);

             if (error7>tolerance) {
            Assert.Fail("wrong asset swap spreads for zero cpn bond:" +
                        "\n  market ASW spread: " + zeroCpnBondMktAssetSwapSpread1 +
                        "\n  par ASW spread:    " + zeroCpnBondParAssetSwapSpread1 +
                        "\n  error:             " + error7 +
                        "\n  tolerance:         " + tolerance);
             }

             // Zero Coupon bond (Isin: IT0001200390 ISPIM 0 02/17/28)
             // maturity occurs on a business day

             Bond zeroCpnBond2 = new ZeroCouponBond(settlementDays, bondCalendar, vars.faceAmount,
                           new Date(17,Month.February,2028),
                           BusinessDayConvention.Following,
                           100.0, new Date(17,Month.February,1998));

             zeroCpnBond2.setPricingEngine(bondEngine);

             // Real zeroCpnBondPrice2 = zeroCpnBond2->cleanPrice();

             // market price observed on 12th June 2007
             double zeroCpnBondMktPrice2 = 35.160 ;
             double zeroCpnBondMktFullPrice2 = zeroCpnBondMktPrice2+zeroCpnBond2.accruedAmount();
             AssetSwap zeroCpnBondParAssetSwap2 = new AssetSwap(payFixedRate,zeroCpnBond2,
                                          zeroCpnBondMktPrice2,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             zeroCpnBondParAssetSwap2.setPricingEngine(swapEngine);
             double zeroCpnBondParAssetSwapSpread2 = zeroCpnBondParAssetSwap2.fairSpread();
             AssetSwap zeroCpnBondMktAssetSwap2 = new AssetSwap(payFixedRate,zeroCpnBond2,
                                          zeroCpnBondMktPrice2,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          mktAssetSwap);
             zeroCpnBondMktAssetSwap2.setPricingEngine(swapEngine);
             double zeroCpnBondMktAssetSwapSpread2 = zeroCpnBondMktAssetSwap2.fairSpread();
             double error8 = Math.Abs(zeroCpnBondMktAssetSwapSpread2-
                     100*zeroCpnBondParAssetSwapSpread2/zeroCpnBondMktFullPrice2);

             if (error8>tolerance) {
            Assert.Fail("wrong asset swap spreads for zero cpn bond:" +
                        "\n  market ASW spread: " + zeroCpnBondMktAssetSwapSpread2 +
                        "\n  par ASW spread:    " + zeroCpnBondParAssetSwapSpread2 +
                        "\n  error:             " + error8 +
                        "\n  tolerance:         " + tolerance);
             }
        }
Example #11
0
        public void testConsistency()
        {
            // Testing consistency between fair price and fair spread...");
             CommonVars vars = new CommonVars();

             Calendar bondCalendar = new TARGET();
             int settlementDays = 3;

             // Fixed Underlying bond (Isin: DE0001135275 DBR 4 01/04/37)
             // maturity doesn't occur on a business day

             Schedule bondSchedule = new Schedule(new Date(4, Month.January, 2005),
                                              new Date(4, Month.January, 2037),
                                              new Period(Frequency.Annual), bondCalendar,
                                              BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                              DateGeneration.Rule.Backward, false);
             Bond bond = new FixedRateBond(settlementDays, vars.faceAmount,
                                       bondSchedule, new List<double>() { 0.04 },
                                       new ActualActual(ActualActual.Convention.ISDA),
                                       BusinessDayConvention.Following,
                                       100.0, new Date(4, Month.January, 2005));

             bool payFixedRate = true;
             double bondPrice = 95.0;

             bool isPar = true;

             AssetSwap parAssetSwap = new AssetSwap(payFixedRate, bond, bondPrice, vars.iborIndex, vars.spread,
                                                null, vars.iborIndex.dayCounter(), isPar);

             IPricingEngine swapEngine = new DiscountingSwapEngine(vars.termStructure, true, bond.settlementDate(),
                                                               Settings.evaluationDate());

             parAssetSwap.setPricingEngine(swapEngine);
             double fairCleanPrice = parAssetSwap.fairCleanPrice();
             double fairSpread = parAssetSwap.fairSpread();

             double tolerance = 1.0e-13;

             AssetSwap assetSwap2 = new AssetSwap(payFixedRate, bond, fairCleanPrice, vars.iborIndex, vars.spread,
                                              null, vars.iborIndex.dayCounter(), isPar);

             assetSwap2.setPricingEngine(swapEngine);
             if (Math.Abs(assetSwap2.NPV()) > tolerance)
             {
            Assert.Fail("npar asset swap fair clean price doesn't zero the NPV: " +
                        "\n  clean price:      " + bondPrice +
                        "\n  fair clean price: " + fairCleanPrice +
                        "\n  NPV:              " + assetSwap2.NPV() +
                        "\n  tolerance:        " + tolerance);
             }
             if (Math.Abs(assetSwap2.fairCleanPrice() - fairCleanPrice) > tolerance)
             {
            Assert.Fail("\npar asset swap fair clean price doesn't equal input clean price at zero NPV: " +
                       "\n  input clean price: " + fairCleanPrice +
                       "\n  fair clean price:  " + assetSwap2.fairCleanPrice() +
                       "\n  NPV:               " + assetSwap2.NPV() +
                       "\n  tolerance:         " + tolerance);
             }
             if (Math.Abs(assetSwap2.fairSpread() - vars.spread) > tolerance)
             {
            Assert.Fail("\npar asset swap fair spread doesn't equal input spread at zero NPV: " +
                       "\n  input spread: " + vars.spread +
                       "\n  fair spread:  " + assetSwap2.fairSpread() +
                       "\n  NPV:          " + assetSwap2.NPV() +
                       "\n  tolerance:    " + tolerance);
             }

             AssetSwap assetSwap3 = new AssetSwap(payFixedRate, bond, bondPrice, vars.iborIndex, fairSpread,
                                              null, vars.iborIndex.dayCounter(), isPar);

             assetSwap3.setPricingEngine(swapEngine);
             if (Math.Abs(assetSwap3.NPV()) > tolerance)
             {
            Assert.Fail("\npar asset swap fair spread doesn't zero the NPV: " +
                       "\n  spread:      " + vars.spread +
                       "\n  fair spread: " + fairSpread +
                       "\n  NPV:         " + assetSwap3.NPV() +
                       "\n  tolerance:   " + tolerance);
             }
             if (Math.Abs(assetSwap3.fairCleanPrice() - bondPrice) > tolerance)
             {
            Assert.Fail("\npar asset swap fair clean price doesn't equal input clean price at zero NPV: " +
                       "\n  input clean price: " + bondPrice +
                       "\n  fair clean price:  " + assetSwap3.fairCleanPrice() +
                       "\n  NPV:               " + assetSwap3.NPV() +
                       "\n  tolerance:         " + tolerance);
             }
             if (Math.Abs(assetSwap3.fairSpread() - fairSpread) > tolerance)
             {
            Assert.Fail("\npar asset swap fair spread doesn't equal input spread at  zero NPV: " +
                       "\n  input spread: " + fairSpread +
                       "\n  fair spread:  " + assetSwap3.fairSpread() +
                       "\n  NPV:          " + assetSwap3.NPV() +
                       "\n  tolerance:    " + tolerance);
             }

             // let's change the npv date
             swapEngine = new DiscountingSwapEngine(vars.termStructure, true, bond.settlementDate(), bond.settlementDate());

             parAssetSwap.setPricingEngine(swapEngine);
             // fair clean price and fair spread should not change
             if (Math.Abs(parAssetSwap.fairCleanPrice() - fairCleanPrice) > tolerance)
             {
            Assert.Fail("\npar asset swap fair clean price changed with NpvDate:" +
                       "\n expected clean price: " + fairCleanPrice +
                       "\n fair clean price:     " + parAssetSwap.fairCleanPrice() +
                       "\n tolerance:            " + tolerance);
             }
             if (Math.Abs(parAssetSwap.fairSpread() - fairSpread) > tolerance)
             {
            Assert.Fail("\npar asset swap fair spread changed with NpvDate:" +
                       "\n  expected spread: " + fairSpread +
                       "\n  fair spread:     " + parAssetSwap.fairSpread() +
                       "\n  tolerance:       " + tolerance);
             }

             assetSwap2 = new AssetSwap(payFixedRate, bond, fairCleanPrice, vars.iborIndex, vars.spread,
                                    null, vars.iborIndex.dayCounter(), isPar);
             assetSwap2.setPricingEngine(swapEngine);
             if (Math.Abs(assetSwap2.NPV()) > tolerance)
             {
            Assert.Fail("\npar asset swap fair clean price doesn't zero the NPV: " +
                       "\n  clean price:      " + bondPrice +
                       "\n  fair clean price: " + fairCleanPrice +
                       "\n  NPV:              " + assetSwap2.NPV() +
                       "\n  tolerance:        " + tolerance);
             }
             if (Math.Abs(assetSwap2.fairCleanPrice() - fairCleanPrice) > tolerance)
             {
            Assert.Fail("\npar asset swap fair clean price doesn't equal input clean price at zero NPV: " +
                       "\n  input clean price: " + fairCleanPrice +
                       "\n  fair clean price:  " + assetSwap2.fairCleanPrice() +
                       "\n  NPV:               " + assetSwap2.NPV() +
                       "\n  tolerance:         " + tolerance);
             }
             if (Math.Abs(assetSwap2.fairSpread() - vars.spread) > tolerance)
             {
            Assert.Fail("\npar asset swap fair spread doesn't equal input spread at zero NPV: " +
                       "\n  input spread: " + vars.spread +
                       "\n  fair spread:  " + assetSwap2.fairSpread() +
                       "\n  NPV:          " + assetSwap2.NPV() +
                       "\n  tolerance:    " + tolerance);
             }

             assetSwap3 = new AssetSwap(payFixedRate, bond, bondPrice, vars.iborIndex, fairSpread,
                                    null, vars.iborIndex.dayCounter(), isPar);
             assetSwap3.setPricingEngine(swapEngine);
             if (Math.Abs(assetSwap3.NPV()) > tolerance)
             {
            Assert.Fail("\npar asset swap fair spread doesn't zero the NPV: " +
                       "\n  spread:      " + vars.spread +
                       "\n  fair spread: " + fairSpread +
                       "\n  NPV:         " + assetSwap3.NPV() +
                       "\n  tolerance:   " + tolerance);
             }
             if (Math.Abs(assetSwap3.fairCleanPrice() - bondPrice) > tolerance)
             {
            Assert.Fail("\npar asset swap fair clean price doesn't equal input clean price at zero NPV: " +
                       "\n  input clean price: " + bondPrice +
                       "\n  fair clean price:  " + assetSwap3.fairCleanPrice() +
                       "\n  NPV:               " + assetSwap3.NPV() +
                       "\n  tolerance:         " + tolerance);
             }
             if (Math.Abs(assetSwap3.fairSpread() - fairSpread) > tolerance)
             {
            Assert.Fail("\npar asset swap fair spread doesn't equal input spread at zero NPV: " +
                       "\n  input spread: " + fairSpread +
                       "\n  fair spread:  " + assetSwap3.fairSpread() +
                       "\n  NPV:          " + assetSwap3.NPV() +
                       "\n  tolerance:    " + tolerance);

             }

             // now market asset swap
             isPar = false;
             AssetSwap mktAssetSwap = new AssetSwap(payFixedRate, bond, bondPrice, vars.iborIndex, vars.spread,
                                                null, vars.iborIndex.dayCounter(), isPar);

             swapEngine = new DiscountingSwapEngine(vars.termStructure, true, bond.settlementDate(),
                                                Settings.evaluationDate());

             mktAssetSwap.setPricingEngine(swapEngine);
             fairCleanPrice = mktAssetSwap.fairCleanPrice();
             fairSpread = mktAssetSwap.fairSpread();

             AssetSwap assetSwap4 = new AssetSwap(payFixedRate, bond, fairCleanPrice, vars.iborIndex, vars.spread,
                                              null, vars.iborIndex.dayCounter(), isPar);
             assetSwap4.setPricingEngine(swapEngine);
             if (Math.Abs(assetSwap4.NPV()) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair clean price doesn't zero the NPV: " +
                       "\n  clean price:      " + bondPrice +
                       "\n  fair clean price: " + fairCleanPrice +
                       "\n  NPV:              " + assetSwap4.NPV() +
                       "\n  tolerance:        " + tolerance);
             }
             if (Math.Abs(assetSwap4.fairCleanPrice() - fairCleanPrice) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair clean price doesn't equal input clean price at zero NPV: " +
                       "\n  input clean price: " + fairCleanPrice +
                       "\n  fair clean price:  " + assetSwap4.fairCleanPrice() +
                       "\n  NPV:               " + assetSwap4.NPV() +
                       "\n  tolerance:         " + tolerance);
             }
             if (Math.Abs(assetSwap4.fairSpread() - vars.spread) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair spread doesn't equal input spread at zero NPV: " +
                       "\n  input spread: " + vars.spread +
                       "\n  fair spread:  " + assetSwap4.fairSpread() +
                       "\n  NPV:          " + assetSwap4.NPV() +
                       "\n  tolerance:    " + tolerance);
             }

             AssetSwap assetSwap5 = new AssetSwap(payFixedRate, bond, bondPrice, vars.iborIndex, fairSpread,
                                              null, vars.iborIndex.dayCounter(), isPar);
             assetSwap5.setPricingEngine(swapEngine);
             if (Math.Abs(assetSwap5.NPV()) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair spread doesn't zero the NPV: " +
                       "\n  spread:      " + vars.spread +
                       "\n  fair spread: " + fairSpread +
                       "\n  NPV:         " + assetSwap5.NPV() +
                       "\n  tolerance:   " + tolerance);
             }
             if (Math.Abs(assetSwap5.fairCleanPrice() - bondPrice) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair clean price doesn't equal input clean price at zero NPV: " +
                       "\n  input clean price: " + bondPrice +
                       "\n  fair clean price:  " + assetSwap5.fairCleanPrice() +
                       "\n  NPV:               " + assetSwap5.NPV() +
                       "\n  tolerance:         " + tolerance);
             }
             if (Math.Abs(assetSwap5.fairSpread() - fairSpread) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair spread doesn't equal input spread at zero NPV: " +
                       "\n  input spread: " + fairSpread +
                       "\n  fair spread:  " + assetSwap5.fairSpread() +
                       "\n  NPV:          " + assetSwap5.NPV() +
                       "\n  tolerance:    " + tolerance);
             }

             // let's change the npv date
             swapEngine = new DiscountingSwapEngine(vars.termStructure, true, bond.settlementDate(), bond.settlementDate());
             mktAssetSwap.setPricingEngine(swapEngine);

             // fair clean price and fair spread should not change
             if (Math.Abs(mktAssetSwap.fairCleanPrice() - fairCleanPrice) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair clean price changed with NpvDate:" +
                       "\n  expected clean price: " + fairCleanPrice +
                       "\n  fair clean price:  " + mktAssetSwap.fairCleanPrice() +
                       "\n  tolerance:         " + tolerance);
             }
             if (Math.Abs(mktAssetSwap.fairSpread() - fairSpread) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair spread changed with NpvDate:" +
                       "\n  expected spread: " + fairSpread +
                       "\n  fair spread:  " + mktAssetSwap.fairSpread() +
                       "\n  tolerance:    " + tolerance);
             }

             assetSwap4 = new AssetSwap(payFixedRate, bond, fairCleanPrice, vars.iborIndex, vars.spread,
                                    null, vars.iborIndex.dayCounter(), isPar);
             assetSwap4.setPricingEngine(swapEngine);
             if (Math.Abs(assetSwap4.NPV()) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair clean price doesn't zero the NPV: " +
                       "\n  clean price:      " + bondPrice +
                       "\n  fair clean price: " + fairCleanPrice +
                       "\n  NPV:              " + assetSwap4.NPV() +
                       "\n  tolerance:        " + tolerance);
             }
             if (Math.Abs(assetSwap4.fairCleanPrice() - fairCleanPrice) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair clean price doesn't equal input clean price at zero NPV: " +
                       "\n  input clean price: " + fairCleanPrice +
                       "\n  fair clean price:  " + assetSwap4.fairCleanPrice() +
                       "\n  NPV:               " + assetSwap4.NPV() +
                       "\n  tolerance:         " + tolerance);
             }
             if (Math.Abs(assetSwap4.fairSpread() - vars.spread) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair spread doesn't equal input spread at zero NPV: " +
                       "\n  input spread: " + vars.spread +
                       "\n  fair spread:  " + assetSwap4.fairSpread() +
                       "\n  NPV:          " + assetSwap4.NPV() +
                       "\n  tolerance:    " + tolerance);
             }

             assetSwap5 = new AssetSwap(payFixedRate, bond, bondPrice, vars.iborIndex, fairSpread,
                                    null, vars.iborIndex.dayCounter(), isPar);
             assetSwap5.setPricingEngine(swapEngine);
             if (Math.Abs(assetSwap5.NPV()) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair spread doesn't zero the NPV: " +
                       "\n  spread:      " + vars.spread +
                       "\n  fair spread: " + fairSpread +
                       "\n  NPV:         " + assetSwap5.NPV() +
                       "\n  tolerance:   " + tolerance);
             }
             if (Math.Abs(assetSwap5.fairCleanPrice() - bondPrice) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair clean price doesn't equal input clean price at zero NPV: " +
                       "\n  input clean price: " + bondPrice +
                       "\n  fair clean price:  " + assetSwap5.fairCleanPrice() +
                       "\n  NPV:               " + assetSwap5.NPV() +
                       "\n  tolerance:         " + tolerance);
             }
             if (Math.Abs(assetSwap5.fairSpread() - fairSpread) > tolerance)
             {
            Assert.Fail("\nmarket asset swap fair spread doesn't equal input spread at zero NPV: " +
                       "\n  input spread: " + fairSpread +
                       "\n  fair spread:  " + assetSwap5.fairSpread() +
                       "\n  NPV:          " + assetSwap5.NPV() +
                       "\n  tolerance:    " + tolerance);
             }
        }
Example #12
0
        public VanillaSwap value()
        {
            Date startDate;

            if (effectiveDate_ != null)
            {
                startDate = effectiveDate_;
            }
            else
            {
                //int fixingDays = iborIndex_.fixingDays();
                Date refDate = Settings.evaluationDate();
                // if the evaluation date is not a business day
                // then move to the next business day
                refDate = floatCalendar_.adjust(refDate);
                Date spotDate = floatCalendar_.advance(refDate, new Period(settlementDays_, TimeUnit.Days));
                startDate = spotDate + forwardStart_;
                if (forwardStart_.length() < 0)
                {
                    startDate = floatCalendar_.adjust(startDate, BusinessDayConvention.Preceding);
                }
                else
                {
                    startDate = floatCalendar_.adjust(startDate, BusinessDayConvention.Following);
                }
            }

            Date endDate = terminationDate_;

            if (endDate == null)
            {
                if (floatEndOfMonth_)
                {
                    endDate = floatCalendar_.advance(startDate,
                                                     swapTenor_,
                                                     BusinessDayConvention.ModifiedFollowing,
                                                     floatEndOfMonth_);
                }
                else
                {
                    endDate = startDate + swapTenor_;
                }
            }

            Currency curr       = iborIndex_.currency();
            Period   fixedTenor = null;

            if (fixedTenor_ != null)
            {
                fixedTenor = fixedTenor_;
            }
            else
            {
                if ((curr == new EURCurrency()) ||
                    (curr == new USDCurrency()) ||
                    (curr == new CHFCurrency()) ||
                    (curr == new SEKCurrency()) ||
                    (curr == new GBPCurrency() && swapTenor_ <= new Period(1, TimeUnit.Years)))
                {
                    fixedTenor = new Period(1, TimeUnit.Years);
                }
                else if ((curr == new GBPCurrency() && swapTenor_ > new Period(1, TimeUnit.Years) ||
                          (curr == new JPYCurrency()) ||
                          (curr == new AUDCurrency() && swapTenor_ >= new Period(4, TimeUnit.Years))))
                {
                    fixedTenor = new Period(6, TimeUnit.Months);
                }
                else if ((curr == new HKDCurrency() ||
                          (curr == new AUDCurrency() && swapTenor_ < new Period(4, TimeUnit.Years))))
                {
                    fixedTenor = new Period(3, TimeUnit.Months);
                }
                else
                {
                    Utils.QL_FAIL("unknown fixed leg default tenor for " + curr);
                }
            }

            Schedule fixedSchedule = new Schedule(startDate, endDate,
                                                  fixedTenor, fixedCalendar_,
                                                  fixedConvention_, fixedTerminationDateConvention_,
                                                  fixedRule_, fixedEndOfMonth_,
                                                  fixedFirstDate_, fixedNextToLastDate_);

            Schedule floatSchedule = new Schedule(startDate, endDate,
                                                  floatTenor_, floatCalendar_,
                                                  floatConvention_, floatTerminationDateConvention_,
                                                  floatRule_, floatEndOfMonth_,
                                                  floatFirstDate_, floatNextToLastDate_);

            DayCounter fixedDayCount = null;

            if (fixedDayCount_ != null)
            {
                fixedDayCount = fixedDayCount_;
            }
            else
            {
                if (curr == new USDCurrency())
                {
                    fixedDayCount = new Actual360();
                }
                else if (curr == new EURCurrency() || curr == new CHFCurrency() || curr == new SEKCurrency())
                {
                    fixedDayCount = new Thirty360(Thirty360.Thirty360Convention.BondBasis);
                }
                else if (curr == new GBPCurrency() || curr == new JPYCurrency() || curr == new AUDCurrency() ||
                         curr == new HKDCurrency())
                {
                    fixedDayCount = new Actual365Fixed();
                }
                else
                {
                    Utils.QL_FAIL("unknown fixed leg day counter for " + curr);
                }
            }

            double?usedFixedRate = fixedRate_;

            if (fixedRate_ == null)
            {
                VanillaSwap temp = new VanillaSwap(type_, nominal_, fixedSchedule, 0.0, fixedDayCount,
                                                   floatSchedule, iborIndex_, floatSpread_, floatDayCount_);

                if (engine_ == null)
                {
                    Handle <YieldTermStructure> disc = iborIndex_.forwardingTermStructure();
                    Utils.QL_REQUIRE(!disc.empty(), () =>
                                     "null term structure set to this instance of " + iborIndex_.name());
                    bool           includeSettlementDateFlows = false;
                    IPricingEngine engine = new DiscountingSwapEngine(disc, includeSettlementDateFlows);
                    temp.setPricingEngine(engine);
                }
                else
                {
                    temp.setPricingEngine(engine_);
                }

                usedFixedRate = temp.fairRate();
            }

            VanillaSwap swap = new VanillaSwap(type_, nominal_, fixedSchedule, usedFixedRate.Value, fixedDayCount,
                                               floatSchedule, iborIndex_, floatSpread_, floatDayCount_);

            if (engine_ == null)
            {
                Handle <YieldTermStructure> disc          = iborIndex_.forwardingTermStructure();
                bool           includeSettlementDateFlows = false;
                IPricingEngine engine = new DiscountingSwapEngine(disc, includeSettlementDateFlows);
                swap.setPricingEngine(engine);
            }
            else
            {
                swap.setPricingEngine(engine_);
            }

            return(swap);
        }
Example #13
0
        public void testZeroTermStructure()
        {
            // Testing zero inflation term structure...

            SavedSettings backup = new SavedSettings();

            // try the Zero UK
            Calendar calendar = new UnitedKingdom();
            BusinessDayConvention bdc = BusinessDayConvention.ModifiedFollowing;
            Date evaluationDate = new Date( 13, Month.August, 2007 );
            evaluationDate = calendar.adjust( evaluationDate );
            Settings.setEvaluationDate( evaluationDate );

            // fixing data
            Date from = new Date( 1, Month.January, 2005 );
            Date to = new Date( 13, Month.August, 2007 );
            Schedule rpiSchedule = new MakeSchedule().from( from ).to( to )
                                          .withTenor( new Period( 1, TimeUnit.Months ) )
                                          .withCalendar( new UnitedKingdom() )
                                          .withConvention( BusinessDayConvention.ModifiedFollowing )
                                          .value();

            double[] 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, 206.1,  -999.0 };

            RelinkableHandle<ZeroInflationTermStructure> hz = new RelinkableHandle<ZeroInflationTermStructure>();
            bool interp = false;
            UKRPI iiUKRPI = new UKRPI( interp, hz );
            for ( int i = 0; i < rpiSchedule.Count; i++ )
            {
                iiUKRPI.addFixing( rpiSchedule[i], fixData[i] );
            }

            ZeroInflationIndex ii = iiUKRPI as ZeroInflationIndex;
            YieldTermStructure nominalTS = nominalTermStructure();

            // now build the zero inflation curve

            Datum[] zcData = {
               new Datum( new Date(13, Month.August, 2008), 2.93 ),
               new Datum( new Date(13, Month.August, 2009), 2.95 ),
               new Datum( new Date(13, Month.August, 2010), 2.965 ),
               new Datum( new Date(15, Month.August, 2011), 2.98 ),
               new Datum( new Date(13, Month.August, 2012), 3.0 ),
               new Datum( new Date(13, Month.August, 2014), 3.06 ),
               new Datum( new Date(13, Month.August, 2017), 3.175 ),
               new Datum( new Date(13, Month.August, 2019), 3.243 ),
               new Datum( new Date(15, Month.August, 2022), 3.293 ),
               new Datum( new Date(14, Month.August, 2027), 3.338 ),
               new Datum( new Date(13, Month.August, 2032), 3.348 ),
               new Datum( new Date(15, Month.August, 2037), 3.348 ),
               new Datum( new Date(13, Month.August, 2047), 3.308 ),
               new Datum( new Date(13, Month.August, 2057), 3.228 )};

            Period observationLag = new Period( 2, TimeUnit.Months );
            DayCounter dc = new Thirty360();
            Frequency frequency = Frequency.Monthly;
            List<BootstrapHelper<ZeroInflationTermStructure>> helpers =
                makeHelpers( zcData, zcData.Length, ii,
                                                observationLag,
                                                calendar, bdc, dc );

            double baseZeroRate = zcData[0].rate / 100.0;
            PiecewiseZeroInflationCurve<Linear> pZITS = new PiecewiseZeroInflationCurve<Linear>(
                                evaluationDate, calendar, dc, observationLag,
                                frequency, ii.interpolated(), baseZeroRate,
                                new Handle<YieldTermStructure>( nominalTS ), helpers );
            pZITS.recalculate();

            // first check that the zero rates on the curve match the data
            // and that the helpers give the correct impled rates
            const double eps = 0.00000001;
            bool forceLinearInterpolation = false;
            for ( int i = 0; i < zcData.Length; i++ )
            {
                Assert.IsTrue( Math.Abs( zcData[i].rate / 100.0
                - pZITS.zeroRate( zcData[i].date, observationLag, forceLinearInterpolation ) ) < eps,
                "ZITS zeroRate != instrument "
                + pZITS.zeroRate( zcData[i].date, observationLag, forceLinearInterpolation )
                + " vs " + zcData[i].rate / 100.0
                + " interpolation: " + ii.interpolated()
                + " forceLinearInterpolation " + forceLinearInterpolation );

                Assert.IsTrue( Math.Abs( helpers[i].impliedQuote()
                - zcData[i].rate / 100.0 ) < eps,
                "ZITS implied quote != instrument "
                + helpers[i].impliedQuote()
                + " vs " + zcData[i].rate / 100.0 );
            }

            // now test the forecasting capability of the index.
            hz.linkTo( pZITS );
            from = hz.link.baseDate();
            to = hz.link.maxDate() - new Period( 1, TimeUnit.Months ); // a bit of margin for adjustments
            Schedule testIndex = new MakeSchedule().from( from ).to( to )
                                            .withTenor( new Period( 1, TimeUnit.Months ) )
                                            .withCalendar( new UnitedKingdom() )
                                            .withConvention( BusinessDayConvention.ModifiedFollowing ).value();

            // we are testing UKRPI which is not interpolated
            Date bd = hz.link.baseDate();
            double bf = ii.fixing( bd );
            for ( int i = 0; i < testIndex.Count; i++ )
            {
                Date d = testIndex[i];
                double z = hz.link.zeroRate( d, new Period( 0, TimeUnit.Days ) );
                double t = hz.link.dayCounter().yearFraction( bd, d );
                if ( !ii.interpolated() ) // because fixing constant over period
                    t = hz.link.dayCounter().yearFraction( bd,
                     Utils.inflationPeriod( d, ii.frequency() ).Key );
                double calc = bf * Math.Pow( 1 + z, t );
                if ( t <= 0 )
                    calc = ii.fixing( d, false ); // still historical
                if ( Math.Abs( calc - ii.fixing( d, true ) ) / 10000.0 > eps )
                    Assert.Fail( "ZC index does not forecast correctly for date " + d
                                + " from base date " + bd
                                + " with fixing " + bf
                                + ", correct:  " + calc
                                + ", fix: " + ii.fixing( d, true )
                                + ", t " + t );
            }

            //===========================================================================================
            // Test zero-inflation-indexed (i.e. cpi ratio) cashflow
            // just ordinary indexed cashflow with a zero inflation index

            Date baseDate = new Date( 1, Month.January, 2006 );
            Date fixDate = new Date( 1, Month.August, 2014 );
            Date payDate = new UnitedKingdom().adjust( fixDate + new Period( 3, TimeUnit.Months ), BusinessDayConvention.ModifiedFollowing );
            Index ind = ii as Index;
             Utils.QL_REQUIRE( ind != null, () => "dynamic_pointer_cast to Index from InflationIndex failed" );

            double notional = 1000000.0;//1m
            IndexedCashFlow iicf = new IndexedCashFlow( notional, ind, baseDate, fixDate, payDate );
            double correctIndexed = ii.fixing( iicf.fixingDate() ) / ii.fixing( iicf.baseDate() );
            double calculatedIndexed = iicf.amount() / iicf.notional();
            Assert.IsTrue( Math.Abs( correctIndexed - calculatedIndexed ) < eps,
                                  "IndexedCashFlow indexing wrong: " + calculatedIndexed + " vs correct = "
                                  + correctIndexed );

            //===========================================================================================
            // Test zero coupon swap

            // first make one ...

            ZeroInflationIndex zii = ii as ZeroInflationIndex;
             Utils.QL_REQUIRE( zii != null, () => "dynamic_pointer_cast to ZeroInflationIndex from UKRPI failed" );
            ZeroCouponInflationSwap nzcis =
                new ZeroCouponInflationSwap( ZeroCouponInflationSwap.Type.Payer,
                                                     1000000.0,
                                                     evaluationDate,
                                                     zcData[6].date,    // end date = maturity
                                                     calendar, bdc, dc, zcData[6].rate / 100.0, // fixed rate
                                                     zii, observationLag );

            // N.B. no coupon pricer because it is not a coupon, effect of inflation curve via
            //      inflation curve attached to the inflation index.
            Handle<YieldTermStructure> hTS = new Handle<YieldTermStructure>( nominalTS );
            IPricingEngine sppe = new DiscountingSwapEngine( hTS );
            nzcis.setPricingEngine( sppe );

            // ... and price it, should be zero
            Assert.IsTrue( Math.Abs( nzcis.NPV() ) < 0.00001, "ZCIS does not reprice to zero "
                              + nzcis.NPV()
                              + evaluationDate + " to " + zcData[6].date + " becoming " + nzcis.maturityDate()
                              + " rate " + zcData[6].rate
                              + " fixed leg " + nzcis.legNPV( 0 )
                              + " indexed-predicted inflated leg " + nzcis.legNPV( 1 )
                              + " discount " + nominalTS.discount( nzcis.maturityDate() ) );

            //===========================================================================================
            // Test multiplicative seasonality in price
            //

            //Seasonality factors NOT normalized
            //and UKRPI is not interpolated
            Date trueBaseDate = Utils.inflationPeriod( hz.link.baseDate(), ii.frequency() ).Value;
            Date seasonallityBaseDate = new Date( 31, Month.January, trueBaseDate.year() );
            List<double> seasonalityFactors = new List<double>( 12 );
            seasonalityFactors.Add( 1.003245 );
            seasonalityFactors.Add( 1.000000 );
            seasonalityFactors.Add( 0.999715 );
            seasonalityFactors.Add( 1.000495 );
            seasonalityFactors.Add( 1.000929 );
            seasonalityFactors.Add( 0.998687 );
            seasonalityFactors.Add( 0.995949 );
            seasonalityFactors.Add( 0.994682 );
            seasonalityFactors.Add( 0.995949 );
            seasonalityFactors.Add( 1.000519 );
            seasonalityFactors.Add( 1.003705 );
            seasonalityFactors.Add( 1.004186 );

            //Creating two different seasonality objects
            //
            MultiplicativePriceSeasonality seasonality_1 = new MultiplicativePriceSeasonality();
            InitializedList<double> seasonalityFactors_1 = new InitializedList<double>( 12, 1.0 );
            seasonality_1.set( seasonallityBaseDate, Frequency.Monthly, seasonalityFactors_1 );

            MultiplicativePriceSeasonality seasonality_real =
                new MultiplicativePriceSeasonality( seasonallityBaseDate, Frequency.Monthly, seasonalityFactors );
            //Testing seasonality correction when seasonality factors are = 1
            //
            double[] fixing = {
            ii.fixing(new Date(14,Month.January  ,2013),true),
            ii.fixing(new Date(14,Month.February ,2013),true),
            ii.fixing(new Date(14,Month.March    ,2013),true),
            ii.fixing(new Date(14,Month.April    ,2013),true),
            ii.fixing(new Date(14,Month.May      ,2013),true),
            ii.fixing(new Date(14,Month.June     ,2013),true),
            ii.fixing(new Date(14,Month.July     ,2013),true),
            ii.fixing(new Date(14,Month.August   ,2013),true),
            ii.fixing(new Date(14,Month.September,2013),true),
            ii.fixing(new Date(14,Month.October  ,2013),true),
            ii.fixing(new Date(14,Month.November ,2013),true),
            ii.fixing(new Date(14,Month.December ,2013),true)
             };

            hz.link.setSeasonality( seasonality_1 );
             Utils.QL_REQUIRE( hz.link.hasSeasonality(), () => "[44] incorrectly believes NO seasonality correction" );

            double[] seasonalityFixing_1 = {
            ii.fixing(new Date(14,Month.January  ,2013),true),
            ii.fixing(new Date(14,Month.February ,2013),true),
            ii.fixing(new Date(14,Month.March    ,2013),true),
            ii.fixing(new Date(14,Month.April    ,2013),true),
            ii.fixing(new Date(14,Month.May      ,2013),true),
            ii.fixing(new Date(14,Month.June     ,2013),true),
            ii.fixing(new Date(14,Month.July     ,2013),true),
            ii.fixing(new Date(14,Month.August   ,2013),true),
            ii.fixing(new Date(14,Month.September,2013),true),
            ii.fixing(new Date(14,Month.October  ,2013),true),
            ii.fixing(new Date(14,Month.November ,2013),true),
            ii.fixing(new Date(14,Month.December ,2013),true)
             };

            for ( int i = 0; i < 12; i++ )
            {
                if ( Math.Abs( fixing[i] - seasonalityFixing_1[i] ) > eps )
                {
                    Assert.Fail( "Seasonality doesn't work correctly when seasonality factors are set = 1" );
                }
            }

            //Testing seasonality correction when seasonality factors are different from 1
            //
            //0.998687 is the seasonality factor corresponding to June (the base CPI curve month)
            //
            double[] expectedFixing = {
            ii.fixing(new Date(14,Month.January  ,2013),true) * 1.003245/0.998687,
            ii.fixing(new Date(14,Month.February ,2013),true) * 1.000000/0.998687,
            ii.fixing(new Date(14,Month.March    ,2013),true) * 0.999715/0.998687,
            ii.fixing(new Date(14,Month.April    ,2013),true) * 1.000495/0.998687,
            ii.fixing(new Date(14,Month.May      ,2013),true) * 1.000929/0.998687,
            ii.fixing(new Date(14,Month.June     ,2013),true) * 0.998687/0.998687,
            ii.fixing(new Date(14,Month.July     ,2013),true) * 0.995949/0.998687,
            ii.fixing(new Date(14,Month.August   ,2013),true) * 0.994682/0.998687,
            ii.fixing(new Date(14,Month.September,2013),true) * 0.995949/0.998687,
            ii.fixing(new Date(14,Month.October  ,2013),true) * 1.000519/0.998687,
            ii.fixing(new Date(14,Month.November ,2013),true) * 1.003705/0.998687,
            ii.fixing(new Date(14,Month.December ,2013),true) * 1.004186/0.998687
             };

            hz.link.setSeasonality( seasonality_real );

            double[] seasonalityFixing_real = {
            ii.fixing(new Date(14,Month.January  ,2013),true),
            ii.fixing(new Date(14,Month.February ,2013),true),
            ii.fixing(new Date(14,Month.March    ,2013),true),
            ii.fixing(new Date(14,Month.April    ,2013),true),
            ii.fixing(new Date(14,Month.May      ,2013),true),
            ii.fixing(new Date(14,Month.June     ,2013),true),
            ii.fixing(new Date(14,Month.July     ,2013),true),
            ii.fixing(new Date(14,Month.August   ,2013),true),
            ii.fixing(new Date(14,Month.September,2013),true),
            ii.fixing(new Date(14,Month.October  ,2013),true),
            ii.fixing(new Date(14,Month.November ,2013),true),
            ii.fixing(new Date(14,Month.December ,2013),true)
             };

            for ( int i = 0; i < 12; i++ )
            {
                if ( Math.Abs( expectedFixing[i] - seasonalityFixing_real[i] ) > 0.01 )
                {
                    Assert.Fail( "Seasonality doesn't work correctly when considering seasonality factors != 1 "
                                    + expectedFixing[i] + " vs " + seasonalityFixing_real[i] );
                }
            }

            //Testing Unset function
            //
             Utils.QL_REQUIRE( hz.link.hasSeasonality(), () => "[4] incorrectly believes NO seasonality correction" );
            hz.link.setSeasonality();
             Utils.QL_REQUIRE( !hz.link.hasSeasonality(), () => "[5] incorrectly believes HAS seasonality correction" );

            double[] seasonalityFixing_unset = {
            ii.fixing(new Date(14,Month.January  ,2013),true),
            ii.fixing(new Date(14,Month.February ,2013),true),
            ii.fixing(new Date(14,Month.March    ,2013),true),
            ii.fixing(new Date(14,Month.April    ,2013),true),
            ii.fixing(new Date(14,Month.May      ,2013),true),
            ii.fixing(new Date(14,Month.June     ,2013),true),
            ii.fixing(new Date(14,Month.July     ,2013),true),
            ii.fixing(new Date(14,Month.August   ,2013),true),
            ii.fixing(new Date(14,Month.September,2013),true),
            ii.fixing(new Date(14,Month.October  ,2013),true),
            ii.fixing(new Date(14,Month.November ,2013),true),
            ii.fixing(new Date(14,Month.December ,2013),true)
             };

            for ( int i = 0; i < 12; i++ )
            {
                if ( Math.Abs( seasonalityFixing_unset[i] - seasonalityFixing_1[i] ) > eps )
                {
                    Assert.Fail( "UnsetSeasonality doesn't work correctly "
                                    + seasonalityFixing_unset[i] + " vs " + seasonalityFixing_1[i] );
                }
            }

            //==============================================================================
            // now do an INTERPOLATED index, i.e. repeat everything on a fake version of
            // UKRPI (to save making another term structure)

            bool interpYES = true;
            UKRPI iiUKRPIyes = new UKRPI( interpYES, hz );
            for ( int i = 0; i < fixData.Length; i++ )
            {
                iiUKRPIyes.addFixing( rpiSchedule[i], fixData[i] );
            }

            ZeroInflationIndex iiyes = iiUKRPIyes as ZeroInflationIndex;

            // now build the zero inflation curve
            // same data, bigger lag or it will be a self-contradiction
            Period observationLagyes = new Period( 3, TimeUnit.Months );
            List<BootstrapHelper<ZeroInflationTermStructure>> helpersyes =
                makeHelpers( zcData, zcData.Length,
                iiyes, observationLagyes, calendar, bdc, dc );

            PiecewiseZeroInflationCurve<Linear> pZITSyes =
                    new PiecewiseZeroInflationCurve<Linear>(
                    evaluationDate, calendar, dc, observationLagyes,
                    frequency, iiyes.interpolated(), baseZeroRate,
                    new Handle<YieldTermStructure>( nominalTS ), helpersyes );
            pZITSyes.recalculate();

            // first check that the zero rates on the curve match the data
            // and that the helpers give the correct impled rates
            forceLinearInterpolation = false;   // still
            for ( int i = 0; i < zcData.Length; i++ )
            {
                Assert.IsTrue( Math.Abs( zcData[i].rate / 100.0
                                - pZITSyes.zeroRate( zcData[i].date, observationLagyes, forceLinearInterpolation ) ) < eps,
                                "ZITS INTERPOLATED zeroRate != instrument "
                                + pZITSyes.zeroRate( zcData[i].date, observationLagyes, forceLinearInterpolation )
                                + " date " + zcData[i].date + " observationLagyes " + observationLagyes
                                + " vs " + zcData[i].rate / 100.0
                                + " interpolation: " + iiyes.interpolated()
                                + " forceLinearInterpolation " + forceLinearInterpolation );
                Assert.IsTrue( Math.Abs( helpersyes[i].impliedQuote()
                                    - zcData[i].rate / 100.0 ) < eps,
                                "ZITS INTERPOLATED implied quote != instrument "
                                + helpersyes[i].impliedQuote()
                                + " vs " + zcData[i].rate / 100.0 );
            }

            //======================================================================================
            // now test the forecasting capability of the index.
            hz.linkTo( pZITSyes );
            from = hz.link.baseDate() + new Period( 1, TimeUnit.Months ); // to avoid historical linear bit for rest of base month
            to = hz.link.maxDate() - new Period( 1, TimeUnit.Months ); // a bit of margin for adjustments
            testIndex = new MakeSchedule().from( from ).to( to )
            .withTenor( new Period( 1, TimeUnit.Months ) )
            .withCalendar( new UnitedKingdom() )
            .withConvention( BusinessDayConvention.ModifiedFollowing ).value();

            // we are testing UKRPI which is FAKE interpolated for testing here
            bd = hz.link.baseDate();
            bf = iiyes.fixing( bd );
            for ( int i = 0; i < testIndex.Count; i++ )
            {
                Date d = testIndex[i];
                double z = hz.link.zeroRate( d, new Period( 0, TimeUnit.Days ) );
                double t = hz.link.dayCounter().yearFraction( bd, d );
                double calc = bf * Math.Pow( 1 + z, t );
                if ( t <= 0 ) calc = iiyes.fixing( d ); // still historical
                if ( Math.Abs( calc - iiyes.fixing( d ) ) > eps )
                    Assert.Fail( "ZC INTERPOLATED index does not forecast correctly for date " + d
                                    + " from base date " + bd
                                    + " with fixing " + bf
                                    + ", correct:  " + calc
                                    + ", fix: " + iiyes.fixing( d )
                                    + ", t " + t
                                    + ", zero " + z );
            }

            //===========================================================================================
            // Test zero coupon swap

            ZeroInflationIndex ziiyes = iiyes as ZeroInflationIndex;
             Utils.QL_REQUIRE( ziiyes != null, () => "dynamic_pointer_cast to ZeroInflationIndex from UKRPI-I failed" );
            ZeroCouponInflationSwap nzcisyes = new ZeroCouponInflationSwap( ZeroCouponInflationSwap.Type.Payer,
                                                              1000000.0,
                                                              evaluationDate,
                                                              zcData[6].date,    // end date = maturity
                                                              calendar, bdc, dc, zcData[6].rate / 100.0, // fixed rate
                                                              ziiyes, observationLagyes );

            // N.B. no coupon pricer because it is not a coupon, effect of inflation curve via
            //      inflation curve attached to the inflation index.
            nzcisyes.setPricingEngine( sppe );

            // ... and price it, should be zero
            Assert.IsTrue( Math.Abs( nzcisyes.NPV() ) < 0.00001, "ZCIS-I does not reprice to zero "
                                    + nzcisyes.NPV()
                                    + evaluationDate + " to " + zcData[6].date + " becoming " + nzcisyes.maturityDate()
                                    + " rate " + zcData[6].rate
                                    + " fixed leg " + nzcisyes.legNPV( 0 )
                                    + " indexed-predicted inflated leg " + nzcisyes.legNPV( 1 )
                                    + " discount " + nominalTS.discount( nzcisyes.maturityDate() )
                                    );

            // remove circular refernce
            hz.linkTo( new ZeroInflationTermStructure() );
        }
Example #14
0
        public void testYYTermStructure()
        {
            // Testing year-on-year inflation term structure...

            SavedSettings backup = new SavedSettings();
            //IndexHistoryCleaner cleaner;

            // try the YY UK
            Calendar calendar = new UnitedKingdom();
            BusinessDayConvention bdc = BusinessDayConvention.ModifiedFollowing;
            Date evaluationDate = new Date(13, Month.August, 2007);
            evaluationDate = calendar.adjust(evaluationDate);
            Settings.setEvaluationDate(evaluationDate);

            // fixing data
            Date from = new Date(1, Month.January, 2005);
            Date to = new Date(13, Month.August, 2007);
            Schedule rpiSchedule = new MakeSchedule().from(from).to(to)
            .withTenor(new Period(1,TimeUnit.Months))
            .withCalendar(new UnitedKingdom())
            .withConvention(BusinessDayConvention.ModifiedFollowing).value();
            double[] 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 };

            RelinkableHandle<YoYInflationTermStructure> hy = new RelinkableHandle<YoYInflationTermStructure>();
            bool interp = false;
            YYUKRPIr iir = new YYUKRPIr(interp, hy);
            for (int i=0; i<fixData.Length; i++)
            {
                iir.addFixing(rpiSchedule[i], fixData[i]);
            }

            YieldTermStructure nominalTS = nominalTermStructure();

            // now build the YoY inflation curve
            Datum[] yyData = {
                new Datum( new Date(13, Month.August, 2008), 2.95 ),
                new Datum( new Date(13, Month.August, 2009), 2.95 ),
                new Datum( new Date(13, Month.August, 2010), 2.93 ),
                new Datum( new Date(15, Month.August, 2011), 2.955 ),
                new Datum( new Date(13, Month.August, 2012), 2.945 ),
                new Datum( new Date(13, Month.August, 2013), 2.985 ),
                new Datum( new Date(13, Month.August, 2014), 3.01 ),
                new Datum( new Date(13, Month.August, 2015), 3.035 ),
                new Datum( new Date(13, Month.August, 2016), 3.055 ),  // note that
                new Datum( new Date(13, Month.August, 2017), 3.075 ),  // some dates will be on
                new Datum( new Date(13, Month.August, 2019), 3.105 ),  // holidays but the payment
                new Datum( new Date(15, Month.August, 2022), 3.135 ),  // calendar will roll them
                new Datum( new Date(13, Month.August, 2027), 3.155 ),
                new Datum( new Date(13, Month.August, 2032), 3.145 ),
                new Datum( new Date(13, Month.August, 2037), 3.145 )
            };

            Period observationLag = new Period(2,TimeUnit.Months);
            DayCounter dc = new Thirty360();

            // now build the helpers ...
            List<BootstrapHelper<YoYInflationTermStructure>> helpers =
            makeHelpers (yyData, yyData.Length, iir,observationLag, calendar, bdc, dc);

            double baseYYRate = yyData[0].rate/100.0;
            PiecewiseYoYInflationCurve<Linear> pYYTS = new PiecewiseYoYInflationCurve<Linear>(
                            evaluationDate, calendar, dc, observationLag,
                            iir.frequency(),iir.interpolated(), baseYYRate,
                            new Handle<YieldTermStructure>(nominalTS), helpers);
            pYYTS.recalculate();

            // validation
            // yoy swaps should reprice to zero
            // yy rates should not equal yySwap rates
            double eps = 0.000001;
            // usual swap engine
            Handle<YieldTermStructure> hTS = new Handle<YieldTermStructure>(nominalTS);
            IPricingEngine sppe = new DiscountingSwapEngine(hTS);

            // make sure that the index has the latest yoy term structure
            hy.linkTo(pYYTS);

            for (int j = 1; j < yyData.Length; j++)
            {

                from = nominalTS.referenceDate();
                to = yyData[j].date;
                Schedule yoySchedule = new MakeSchedule().from(from).to(to)
                .withConvention(BusinessDayConvention.Unadjusted) // fixed leg gets calendar from
                .withCalendar(calendar)     // schedule
                .withTenor(new Period(1,TimeUnit.Years)).value(); // .back

                YearOnYearInflationSwap yyS2 = new YearOnYearInflationSwap(
                    YearOnYearInflationSwap.Type.Payer,
                    1000000.0,
                    yoySchedule,//fixed schedule, but same as yoy
                    yyData[j].rate/100.0,
                    dc,
                    yoySchedule,
                    iir,
                    observationLag,
                    0.0,        //spread on index
                    dc,
                    new UnitedKingdom());

                yyS2.setPricingEngine(sppe);

                Assert.IsTrue(Math.Abs(yyS2.NPV())<eps,"fresh yoy swap NPV!=0 from TS "
                            +"swap quote for pt " + j
                            + ", is " + yyData[j].rate/100.0
                            +" vs YoY rate "+ pYYTS.yoyRate(yyData[j].date-observationLag)
                            +" at quote date "+(yyData[j].date-observationLag)
                            +", NPV of a fresh yoy swap is " + yyS2.NPV()
                            +"\n      fair rate " + yyS2.fairRate()
                            +" payment "+yyS2.paymentConvention());
            }

            int jj=3;
            for (int k = 0; k < 14; k++)
            {
                from = nominalTS.referenceDate() - new Period(k,TimeUnit.Months);
                to = yyData[jj].date - new Period(k,TimeUnit.Months);
                Schedule yoySchedule = new MakeSchedule().from(from).to(to)
                .withConvention(BusinessDayConvention.Unadjusted) // fixed leg gets calendar from
                .withCalendar(calendar)     // schedule
                .withTenor(new Period(1,TimeUnit.Years))
                .value(); //backwards()

                YearOnYearInflationSwap yyS3 = new YearOnYearInflationSwap(
                    YearOnYearInflationSwap.Type.Payer,
                    1000000.0,
                    yoySchedule,//fixed schedule, but same as yoy
                    yyData[jj].rate/100.0,
                    dc,
                    yoySchedule,
                    iir,
                    observationLag,
                    0.0,        //spread on index
                    dc,
                    new UnitedKingdom());

                yyS3.setPricingEngine(sppe);

                Assert.IsTrue(Math.Abs(yyS3.NPV())< 20000.0,
                                            "unexpected size of aged YoY swap, aged "
                                            + k +" months: YY aged NPV = " + yyS3.NPV()
                                            +", legs "+ yyS3.legNPV(0) + " and " + yyS3.legNPV(1)
                                            );
            }
            // remove circular refernce
            hy.linkTo( new YoYInflationTermStructure());
        }
Example #15
0
        public void testFixing()
        {
            Date tradeDate = new Date( 17, Month.April, 2015 );
             Calendar calendar = new UnitedKingdom();
             Date settlementDate = calendar.advance( tradeDate, 2, TimeUnit.Days, BusinessDayConvention.Following );
             Date maturityDate = calendar.advance( settlementDate, 5, TimeUnit.Years, BusinessDayConvention.Following );

             Date valueDate = new Date( 20, Month.April, 2015 );
             Settings.setEvaluationDate( valueDate );

             List<Date> dates = new List<Date>();
             dates.Add( valueDate );
             dates.Add( valueDate + new Period( 1, TimeUnit.Years ) );
             dates.Add( valueDate + new Period( 2, TimeUnit.Years ) );
             dates.Add( valueDate + new Period( 5, TimeUnit.Years ) );
             dates.Add( valueDate + new Period( 10, TimeUnit.Years ) );
             dates.Add( valueDate + new Period( 20, TimeUnit.Years ) );

             List<double> rates = new List<double>();
             rates.Add( 0.01 );
             rates.Add( 0.01 );
             rates.Add( 0.01 );
             rates.Add( 0.01 );
             rates.Add( 0.01 );
             rates.Add( 0.01 );

             var discountCurveHandle = new RelinkableHandle<YieldTermStructure>();
             var forecastCurveHandle = new RelinkableHandle<YieldTermStructure>();
             GBPLibor index = new GBPLibor( new Period( 6, TimeUnit.Months ), forecastCurveHandle );
             InterpolatedZeroCurve<Linear> zeroCurve = new InterpolatedZeroCurve<Linear>( dates, rates, new Actual360(), new Linear() );
             var fixedSchedule = new Schedule( settlementDate, maturityDate, new Period( 1, TimeUnit.Years ), calendar, BusinessDayConvention.Following, BusinessDayConvention.Following, DateGeneration.Rule.Forward, false );
             var floatSchedule = new Schedule( settlementDate, maturityDate, index.tenor(), calendar, BusinessDayConvention.Following, BusinessDayConvention.Following, DateGeneration.Rule.Forward, false );
             VanillaSwap swap = new VanillaSwap( VanillaSwap.Type.Payer, 1000000, fixedSchedule, 0.01, new Actual360(), floatSchedule, index, 0, new Actual360() );
             discountCurveHandle.linkTo( zeroCurve );
             forecastCurveHandle.linkTo( zeroCurve );
             var swapEngine = new DiscountingSwapEngine( discountCurveHandle, false, null );
             swap.setPricingEngine( swapEngine );

             try
             {
            double npv = swap.NPV();
             }
             catch ( Exception ex )
             {
            Assert.Fail( ex.Message );
            Console.WriteLine( ex );
             }
        }
Example #16
0
        public void testMASWWithGenericBond()
        {
            // Testing market asset swap against par asset swap with generic bond...

             CommonVars vars = new CommonVars();

             Calendar bondCalendar = new TARGET();
             int settlementDays = 3;
             int fixingDays = 2;
             bool payFixedRate = true;
             bool parAssetSwap = true;
             bool mktAssetSwap = false;
             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);
             IPricingEngine swapEngine = new DiscountingSwapEngine(vars.termStructure);
             fixedBond1.setPricingEngine(bondEngine);

             double fixedBondMktPrice1 = 89.22 ; // market price observed on 7th June 2007
             double fixedBondMktFullPrice1=fixedBondMktPrice1+fixedBond1.accruedAmount();
             AssetSwap fixedBondParAssetSwap1= new AssetSwap(payFixedRate,
                                          fixedBond1, fixedBondMktPrice1,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             fixedBondParAssetSwap1.setPricingEngine(swapEngine);
             double fixedBondParAssetSwapSpread1 = fixedBondParAssetSwap1.fairSpread();
             AssetSwap fixedBondMktAssetSwap1 = new AssetSwap(payFixedRate,
                                          fixedBond1, fixedBondMktPrice1,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          mktAssetSwap);
             fixedBondMktAssetSwap1.setPricingEngine(swapEngine);
             double fixedBondMktAssetSwapSpread1 = fixedBondMktAssetSwap1.fairSpread();

             double tolerance = 1.0e-13;
             double error1 =
            Math.Abs(fixedBondMktAssetSwapSpread1-
                     100*fixedBondParAssetSwapSpread1/fixedBondMktFullPrice1);

             if (error1>tolerance)
            Assert.Fail("wrong asset swap spreads for fixed bond:" +
                        "\n  market asset swap spread: " + fixedBondMktAssetSwapSpread1 +
                        "\n  par asset swap spread:    " + fixedBondParAssetSwapSpread1 +
                        "\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 fixedBondMktPrice2 = 99.98 ; // market price observed on 7th June 2007
             double fixedBondMktFullPrice2=fixedBondMktPrice2+fixedBond2.accruedAmount();
             AssetSwap fixedBondParAssetSwap2= new AssetSwap(payFixedRate,
                                          fixedBond2, fixedBondMktPrice2,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             fixedBondParAssetSwap2.setPricingEngine(swapEngine);
             double fixedBondParAssetSwapSpread2 = fixedBondParAssetSwap2.fairSpread();
             AssetSwap fixedBondMktAssetSwap2= new AssetSwap(payFixedRate,
                                          fixedBond2, fixedBondMktPrice2,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          mktAssetSwap);
             fixedBondMktAssetSwap2.setPricingEngine(swapEngine);
             double fixedBondMktAssetSwapSpread2 = fixedBondMktAssetSwap2.fairSpread();
             double error2 = Math.Abs(fixedBondMktAssetSwapSpread2-
                     100*fixedBondParAssetSwapSpread2/fixedBondMktFullPrice2);

             if (error2>tolerance)
            Assert.Fail("wrong asset swap spreads for fixed bond:" +
                        "\n  market asset swap spread: " + fixedBondMktAssetSwapSpread2 +
                        "\n  par asset swap spread:    " + fixedBondParAssetSwapSpread2 +
                        "\n  error:                    " + error2 +
                        "\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)
            .withNotionals(vars.faceAmount);
             Date floatingbondRedemption1 =
            bondCalendar.adjust(floatingBondMaturityDate1, BusinessDayConvention.Following);
             floatingBondLeg1.Add(new SimpleCashFlow(100.0, floatingbondRedemption1));
             Bond floatingBond1 = new Bond(settlementDays, bondCalendar, vars.faceAmount,  floatingBondMaturityDate1,
            floatingBondStartDate1, floatingBondLeg1);
             floatingBond1.setPricingEngine(bondEngine);

             Utils.setCouponPricer(floatingBond1.cashflows(), vars.pricer);
             vars.iborIndex.addFixing(new Date(27,Month.March,2007), 0.0402);
             // market price observed on 7th June 2007
             double floatingBondMktPrice1 = 101.64 ;
             double floatingBondMktFullPrice1 =
            floatingBondMktPrice1+floatingBond1.accruedAmount();
             AssetSwap floatingBondParAssetSwap1 = new AssetSwap(payFixedRate,
                                             floatingBond1, floatingBondMktPrice1,
                                             vars.iborIndex, vars.spread,
                                             null,
                                             vars.iborIndex.dayCounter(),
                                             parAssetSwap);
             floatingBondParAssetSwap1.setPricingEngine(swapEngine);
             double floatingBondParAssetSwapSpread1 =
            floatingBondParAssetSwap1.fairSpread();
             AssetSwap floatingBondMktAssetSwap1 = new AssetSwap(payFixedRate,
                                             floatingBond1, floatingBondMktPrice1,
                                             vars.iborIndex, vars.spread,
                                             null,
                                             vars.iborIndex.dayCounter(),
                                             mktAssetSwap);
             floatingBondMktAssetSwap1.setPricingEngine(swapEngine);
             double floatingBondMktAssetSwapSpread1 =
            floatingBondMktAssetSwap1.fairSpread();
             double error3 = Math.Abs(floatingBondMktAssetSwapSpread1-
                     100*floatingBondParAssetSwapSpread1/floatingBondMktFullPrice1);

             if (error3>tolerance)
            Assert.Fail("wrong asset swap spreads for floating bond:" +
                        "\n  market asset swap spread: " + floatingBondMktAssetSwapSpread1 +
                        "\n  par asset swap spread:    " + floatingBondParAssetSwapSpread1 +
                        "\n  error:                    " + error3 +
                        "\n  tolerance:                " + tolerance);

             // FRN Underlying bond (Isin: XS0090566539 COE 0 09/24/18)
             // maturity occurs on a business day

             Date floatingBondStartDate2 = new Date(24,Month.September,2004);
             Date floatingBondMaturityDate2 = new Date(24,Month.September,2018);
             Schedule floatingBondSchedule2 = new Schedule(floatingBondStartDate2,
                                       floatingBondMaturityDate2,
                                       new Period(Frequency.Semiannual), bondCalendar,
                                       BusinessDayConvention.ModifiedFollowing, BusinessDayConvention.ModifiedFollowing,
                                       DateGeneration.Rule.Backward, false);
             List<CashFlow> floatingBondLeg2 = new IborLeg(floatingBondSchedule2, vars.iborIndex)
            .withFixingDays(fixingDays)
            .withSpreads(0.0025)
            .inArrears(inArrears)
            .withPaymentDayCounter(new Actual360())
            .withPaymentAdjustment(BusinessDayConvention.ModifiedFollowing)
            .withNotionals(vars.faceAmount);
             Date floatingbondRedemption2 =
            bondCalendar.adjust(floatingBondMaturityDate2, BusinessDayConvention.ModifiedFollowing);
             floatingBondLeg2.Add(new
            SimpleCashFlow(100.0, floatingbondRedemption2));
             Bond floatingBond2 = new Bond(settlementDays, bondCalendar, vars.faceAmount, floatingBondMaturityDate2,
            floatingBondStartDate2, floatingBondLeg2);
             floatingBond2.setPricingEngine(bondEngine);

             Utils.setCouponPricer(floatingBond2.cashflows(), vars.pricer);
             vars.iborIndex.addFixing(new Date(22,Month.March,2007), 0.04013);
             // market price observed on 7th June 2007
             double floatingBondMktPrice2 = 101.248 ;
             double floatingBondMktFullPrice2 =
            floatingBondMktPrice2+floatingBond2.accruedAmount();
             AssetSwap floatingBondParAssetSwap2 = new AssetSwap(payFixedRate,
                                             floatingBond2, floatingBondMktPrice2,
                                             vars.iborIndex, vars.spread,
                                             null,
                                             vars.iborIndex.dayCounter(),
                                             parAssetSwap);
             floatingBondParAssetSwap2.setPricingEngine(swapEngine);
             double floatingBondParAssetSwapSpread2 = floatingBondParAssetSwap2.fairSpread();
             AssetSwap floatingBondMktAssetSwap2 = new AssetSwap(payFixedRate,
                                             floatingBond2, floatingBondMktPrice2,
                                             vars.iborIndex, vars.spread,
                                             null,
                                             vars.iborIndex.dayCounter(),
                                             mktAssetSwap);
             floatingBondMktAssetSwap2.setPricingEngine(swapEngine);
             double floatingBondMktAssetSwapSpread2 =
            floatingBondMktAssetSwap2.fairSpread();
             double error4 = Math.Abs(floatingBondMktAssetSwapSpread2-
                     100*floatingBondParAssetSwapSpread2/floatingBondMktFullPrice2);

             if (error4>tolerance)
            Assert.Fail("wrong asset swap spreads for floating bond:" +
                        "\n  market asset swap spread: " + floatingBondMktAssetSwapSpread2 +
                        "\n  par asset swap spread:    " + floatingBondParAssetSwapSpread2 +
                        "\n  error:                    " + error4 +
                        "\n  tolerance:                " + tolerance);

             // CMS Underlying bond (Isin: XS0228052402 CRDIT 0 8/22/20)
             // maturity doesn't occur on a business day

             Date cmsBondStartDate1 = new Date(22,Month.August,2005);
             Date cmsBondMaturityDate1 = new Date(22,Month.August,2020);
             Schedule cmsBondSchedule1= new Schedule(cmsBondStartDate1,
                                 cmsBondMaturityDate1,
                                 new Period(Frequency.Annual), bondCalendar,
                                 BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                 DateGeneration.Rule.Backward, false);
             List<CashFlow> cmsBondLeg1 = new CmsLeg(cmsBondSchedule1, vars.swapIndex)
            .withPaymentDayCounter(new Thirty360())
            .withFixingDays(fixingDays)
            .withCaps(0.055)
            .withFloors(0.025)
            .inArrears(inArrears)
            .withNotionals(vars.faceAmount);
             Date cmsbondRedemption1 = bondCalendar.adjust(cmsBondMaturityDate1, BusinessDayConvention.Following);
             cmsBondLeg1.Add(new SimpleCashFlow(100.0, cmsbondRedemption1));
             Bond cmsBond1 = new Bond(settlementDays, bondCalendar, vars.faceAmount, cmsBondMaturityDate1, cmsBondStartDate1,
            cmsBondLeg1);
             cmsBond1.setPricingEngine(bondEngine);

             Utils.setCouponPricer(cmsBond1.cashflows(), vars.cmspricer);
             vars.swapIndex.addFixing(new Date(18,Month.August,2006), 0.04158);
             double cmsBondMktPrice1 = 88.45 ; // market price observed on 7th June 2007
             double cmsBondMktFullPrice1 = cmsBondMktPrice1+cmsBond1.accruedAmount();
             AssetSwap cmsBondParAssetSwap1 = new AssetSwap(payFixedRate,
                                       cmsBond1, cmsBondMktPrice1,
                                       vars.iborIndex, vars.spread,
                                       null,
                                       vars.iborIndex.dayCounter(),
                                       parAssetSwap);
             cmsBondParAssetSwap1.setPricingEngine(swapEngine);
             double cmsBondParAssetSwapSpread1 = cmsBondParAssetSwap1.fairSpread();
             AssetSwap cmsBondMktAssetSwap1 = new AssetSwap(payFixedRate,
                                       cmsBond1, cmsBondMktPrice1,
                                       vars.iborIndex, vars.spread,
                                       null,
                                       vars.iborIndex.dayCounter(),
                                       mktAssetSwap);
             cmsBondMktAssetSwap1.setPricingEngine(swapEngine);
             double cmsBondMktAssetSwapSpread1 = cmsBondMktAssetSwap1.fairSpread();
             double error5 =
            Math.Abs(cmsBondMktAssetSwapSpread1-
                     100*cmsBondParAssetSwapSpread1/cmsBondMktFullPrice1);

             if (error5>tolerance)
            Assert.Fail("wrong asset swap spreads for cms bond:" +
                        "\n  market asset swap spread: " + cmsBondMktAssetSwapSpread1 +
                        "\n  par asset swap spread:    " + cmsBondParAssetSwapSpread1 +
                        "\n  error:                    " + error5 +
                        "\n  tolerance:                " + tolerance);

             // CMS Underlying bond (Isin: XS0218766664 ISPIM 0 5/6/15)
             // maturity occurs on a business day

             Date cmsBondStartDate2 = new Date(06,Month.May,2005);
             Date cmsBondMaturityDate2 = new Date(06,Month.May,2015);
             Schedule cmsBondSchedule2= new Schedule(cmsBondStartDate2,
                                 cmsBondMaturityDate2,
                                 new Period(Frequency.Annual), bondCalendar,
                                 BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                 DateGeneration.Rule.Backward, false);
             List<CashFlow> cmsBondLeg2 = new CmsLeg(cmsBondSchedule2, vars.swapIndex)
            .withPaymentDayCounter(new Thirty360())
            .withFixingDays(fixingDays)
            .withGearings(0.84)
            .inArrears(inArrears)
            .withNotionals(vars.faceAmount);
             Date cmsbondRedemption2 = bondCalendar.adjust(cmsBondMaturityDate2,  BusinessDayConvention.Following);
             cmsBondLeg2.Add(new SimpleCashFlow(100.0, cmsbondRedemption2));
             Bond cmsBond2 = new Bond(settlementDays, bondCalendar, vars.faceAmount,  cmsBondMaturityDate2, cmsBondStartDate2,
            cmsBondLeg2);
             cmsBond2.setPricingEngine(bondEngine);

             Utils.setCouponPricer(cmsBond2.cashflows(), vars.cmspricer);
             vars.swapIndex.addFixing(new Date(04,Month.May,2006), 0.04217);
             double cmsBondMktPrice2 = 94.08 ; // market price observed on 7th June 2007
             double cmsBondMktFullPrice2 = cmsBondMktPrice2+cmsBond2.accruedAmount();
             AssetSwap cmsBondParAssetSwap2 = new AssetSwap(payFixedRate,
                                       cmsBond2, cmsBondMktPrice2,
                                       vars.iborIndex, vars.spread,
                                       null,
                                       vars.iborIndex.dayCounter(),
                                       parAssetSwap);
             cmsBondParAssetSwap2.setPricingEngine(swapEngine);
             double cmsBondParAssetSwapSpread2 = cmsBondParAssetSwap2.fairSpread();
             AssetSwap cmsBondMktAssetSwap2 = new AssetSwap(payFixedRate,
                                       cmsBond2, cmsBondMktPrice2,
                                       vars.iborIndex, vars.spread,
                                       null,
                                       vars.iborIndex.dayCounter(),
                                       mktAssetSwap);
             cmsBondMktAssetSwap2.setPricingEngine(swapEngine);
             double cmsBondMktAssetSwapSpread2 = cmsBondMktAssetSwap2.fairSpread();
             double error6 =
            Math.Abs(cmsBondMktAssetSwapSpread2-
                     100*cmsBondParAssetSwapSpread2/cmsBondMktFullPrice2);

             if (error6>tolerance)
            Assert.Fail("wrong asset swap spreads for cms bond:" +
                        "\n  market asset swap spread: " + cmsBondMktAssetSwapSpread2 +
                        "\n  par asset swap spread:    " + cmsBondParAssetSwapSpread2 +
                        "\n  error:                    " + error6 +
                        "\n  tolerance:                " + tolerance);

             // Zero Coupon bond (Isin: DE0004771662 IBRD 0 12/20/15)
             // maturity doesn't occur on a business day

             Date zeroCpnBondStartDate1 = new Date(19,Month.December,1985);
             Date zeroCpnBondMaturityDate1 = new Date(20,Month.December,2015);
             Date zeroCpnBondRedemption1 = bondCalendar.adjust(zeroCpnBondMaturityDate1,
                                                         BusinessDayConvention.Following);
             List<CashFlow> zeroCpnBondLeg1 = new List<CashFlow>{new SimpleCashFlow(100.0, zeroCpnBondRedemption1)};
             Bond zeroCpnBond1 = new  Bond(settlementDays, bondCalendar, vars.faceAmount, zeroCpnBondMaturityDate1,
            zeroCpnBondStartDate1, zeroCpnBondLeg1);
             zeroCpnBond1.setPricingEngine(bondEngine);

             // market price observed on 12th June 2007
             double zeroCpnBondMktPrice1 = 70.436 ;
             double zeroCpnBondMktFullPrice1 =
            zeroCpnBondMktPrice1+zeroCpnBond1.accruedAmount();
             AssetSwap zeroCpnBondParAssetSwap1 = new AssetSwap(payFixedRate,zeroCpnBond1,
                                          zeroCpnBondMktPrice1,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             zeroCpnBondParAssetSwap1.setPricingEngine(swapEngine);
             double zeroCpnBondParAssetSwapSpread1 = zeroCpnBondParAssetSwap1.fairSpread();
             AssetSwap zeroCpnBondMktAssetSwap1 = new AssetSwap(payFixedRate,zeroCpnBond1,
                                          zeroCpnBondMktPrice1,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          mktAssetSwap);
             zeroCpnBondMktAssetSwap1.setPricingEngine(swapEngine);
             double zeroCpnBondMktAssetSwapSpread1 = zeroCpnBondMktAssetSwap1.fairSpread();
             double error7 =
            Math.Abs(zeroCpnBondMktAssetSwapSpread1-
                     100*zeroCpnBondParAssetSwapSpread1/zeroCpnBondMktFullPrice1);

             if (error7>tolerance)
            Assert.Fail("wrong asset swap spreads for zero cpn bond:" +
                        "\n  market asset swap spread: " + zeroCpnBondMktAssetSwapSpread1 +
                        "\n  par asset swap spread:    " + zeroCpnBondParAssetSwapSpread1 +
                        "\n  error:                    " + error7 +
                        "\n  tolerance:                " + tolerance);

             // Zero Coupon bond (Isin: IT0001200390 ISPIM 0 02/17/28)
             // maturity occurs on a business day

             Date zeroCpnBondStartDate2 = new Date(17,Month.February,1998);
             Date zeroCpnBondMaturityDate2 = new Date(17,Month.February,2028);
             Date zerocpbondRedemption2 = bondCalendar.adjust(zeroCpnBondMaturityDate2,
                                                         BusinessDayConvention.Following);
             List<CashFlow> zeroCpnBondLeg2 = new List<CashFlow>{new SimpleCashFlow(100.0, zerocpbondRedemption2)};
             Bond zeroCpnBond2 = new Bond(settlementDays, bondCalendar, vars.faceAmount,
                  zeroCpnBondMaturityDate2, zeroCpnBondStartDate2, zeroCpnBondLeg2);
             zeroCpnBond2.setPricingEngine(bondEngine);

             // double zeroCpnBondPrice2 = zeroCpnBond2.cleanPrice();
             // market price observed on 12th June 2007
             double zeroCpnBondMktPrice2 = 35.160 ;
             double zeroCpnBondMktFullPrice2 =
            zeroCpnBondMktPrice2+zeroCpnBond2.accruedAmount();
             AssetSwap zeroCpnBondParAssetSwap2 = new AssetSwap(payFixedRate,zeroCpnBond2,
                                          zeroCpnBondMktPrice2,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             zeroCpnBondParAssetSwap2.setPricingEngine(swapEngine);
             double zeroCpnBondParAssetSwapSpread2 = zeroCpnBondParAssetSwap2.fairSpread();
             AssetSwap zeroCpnBondMktAssetSwap2 = new AssetSwap(payFixedRate,zeroCpnBond2,
                                          zeroCpnBondMktPrice2,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          mktAssetSwap);
             zeroCpnBondMktAssetSwap2.setPricingEngine(swapEngine);
             double zeroCpnBondMktAssetSwapSpread2 = zeroCpnBondMktAssetSwap2.fairSpread();
             double error8 =
            Math.Abs(zeroCpnBondMktAssetSwapSpread2-
                     100*zeroCpnBondParAssetSwapSpread2/zeroCpnBondMktFullPrice2);

             if (error8>tolerance)
            Assert.Fail("wrong asset swap spreads for zero cpn bond:" +
                        "\n  market asset swap spread: " + zeroCpnBondMktAssetSwapSpread2 +
                        "\n  par asset swap spread:    " + zeroCpnBondParAssetSwapSpread2 +
                        "\n  error:                    " + error8 +
                        "\n  tolerance:                " + tolerance);
        }
Example #17
0
        public void testSpecializedBondVsGenericBondUsingAsw()
        {
            // Testing asset-swap prices and spreads for specialized bond against equivalent generic bond...
             CommonVars vars = new CommonVars();

             Calendar bondCalendar = new TARGET();
             int settlementDays = 3;
             int fixingDays = 2;
             bool payFixedRate = true;
             bool parAssetSwap = true;
             bool inArrears = false;

             // Fixed 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));
             // generic bond
             Bond fixedBond1 = new Bond(settlementDays, bondCalendar, vars.faceAmount,
                  fixedBondMaturityDate1, fixedBondStartDate1, fixedBondLeg1);
             IPricingEngine bondEngine = new DiscountingBondEngine(vars.termStructure);
             IPricingEngine swapEngine = new DiscountingSwapEngine(vars.termStructure);
             fixedBond1.setPricingEngine(bondEngine);

             // equivalent specialized fixed rate bond
             Bond fixedSpecializedBond1 = new FixedRateBond(settlementDays, vars.faceAmount, fixedBondSchedule1,
                           new List<double>{0.04},
                           new ActualActual(ActualActual.Convention.ISDA), BusinessDayConvention.Following,
                           100.0, new Date(4,Month.January,2005));
             fixedSpecializedBond1.setPricingEngine(bondEngine);

             double fixedBondPrice1 = fixedBond1.cleanPrice();
             double fixedSpecializedBondPrice1 = fixedSpecializedBond1.cleanPrice();
             AssetSwap fixedBondAssetSwap1 = new AssetSwap(payFixedRate,
                                       fixedBond1, fixedBondPrice1,
                                       vars.iborIndex, vars.nonnullspread,
                                       null,
                                       vars.iborIndex.dayCounter(),
                                       parAssetSwap);
             fixedBondAssetSwap1.setPricingEngine(swapEngine);
             AssetSwap fixedSpecializedBondAssetSwap1 = new AssetSwap(payFixedRate,
                                                fixedSpecializedBond1,
                                                fixedSpecializedBondPrice1,
                                                vars.iborIndex,
                                                vars.nonnullspread,
                                                null,
                                                vars.iborIndex.dayCounter(),
                                                parAssetSwap);
             fixedSpecializedBondAssetSwap1.setPricingEngine(swapEngine);
             double fixedBondAssetSwapPrice1 = fixedBondAssetSwap1.fairCleanPrice();
             double fixedSpecializedBondAssetSwapPrice1 =
            fixedSpecializedBondAssetSwap1.fairCleanPrice();
             double tolerance = 1.0e-13;
             double error1 =
            Math.Abs(fixedBondAssetSwapPrice1-fixedSpecializedBondAssetSwapPrice1);
             if (error1>tolerance) {
            Assert.Fail("wrong clean price for fixed bond:"
                        + "\n  generic  fixed rate bond's  clean price: "
                        + fixedBondAssetSwapPrice1
                        + "\n  equivalent specialized bond's clean price: "
                        + fixedSpecializedBondAssetSwapPrice1
                        + "\n  error:                 " + error1
                        + "\n  tolerance:             " + tolerance);
             }
             // market executable price as of 4th sept 2007
             double fixedBondMktPrice1= 91.832;
             AssetSwap fixedBondASW1 = new AssetSwap(payFixedRate,
                                 fixedBond1, fixedBondMktPrice1,
                                 vars.iborIndex, vars.spread,
                                 null,
                                 vars.iborIndex.dayCounter(),
                                 parAssetSwap);
             fixedBondASW1.setPricingEngine(swapEngine);
             AssetSwap fixedSpecializedBondASW1 = new AssetSwap(payFixedRate,
                                          fixedSpecializedBond1,
                                          fixedBondMktPrice1,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             fixedSpecializedBondASW1.setPricingEngine(swapEngine);
             double fixedBondASWSpread1 = fixedBondASW1.fairSpread();
             double fixedSpecializedBondASWSpread1 = fixedSpecializedBondASW1.fairSpread();
             double error2 = Math.Abs(fixedBondASWSpread1-fixedSpecializedBondASWSpread1);
             if (error2>tolerance) {
            Assert.Fail("wrong asw spread  for fixed bond:"
                        + "\n  generic  fixed rate bond's  asw spread: "
                        + fixedBondASWSpread1
                        + "\n  equivalent specialized bond's asw spread: "
                        + fixedSpecializedBondASWSpread1
                        + "\n  error:                 " + error2
                        + "\n  tolerance:             " + tolerance);
             }

             //Fixed 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));

             // generic bond
             Bond fixedBond2 = new Bond(settlementDays, bondCalendar, vars.faceAmount,
                  fixedBondMaturityDate2, fixedBondStartDate2, fixedBondLeg2);
             fixedBond2.setPricingEngine(bondEngine);

             // equivalent specialized fixed rate bond
             Bond fixedSpecializedBond2 = new FixedRateBond(settlementDays, vars.faceAmount, fixedBondSchedule2,
                           new List<double>{ 0.05},
                           new Thirty360(Thirty360.Thirty360Convention.BondBasis), BusinessDayConvention.Following,
                           100.0, new Date(5,Month.February,2005));
             fixedSpecializedBond2.setPricingEngine(bondEngine);

             double fixedBondPrice2 = fixedBond2.cleanPrice();
             double fixedSpecializedBondPrice2 = fixedSpecializedBond2.cleanPrice();
             AssetSwap fixedBondAssetSwap2 = new AssetSwap(payFixedRate,
                                       fixedBond2, fixedBondPrice2,
                                       vars.iborIndex, vars.nonnullspread,
                                       null,
                                       vars.iborIndex.dayCounter(),
                                       parAssetSwap);
             fixedBondAssetSwap2.setPricingEngine(swapEngine);
             AssetSwap fixedSpecializedBondAssetSwap2 = new AssetSwap(payFixedRate,
                                                fixedSpecializedBond2,
                                                fixedSpecializedBondPrice2,
                                                vars.iborIndex,
                                                vars.nonnullspread,
                                                null,
                                                vars.iborIndex.dayCounter(),
                                                parAssetSwap);
             fixedSpecializedBondAssetSwap2.setPricingEngine(swapEngine);
             double fixedBondAssetSwapPrice2 = fixedBondAssetSwap2.fairCleanPrice();
             double fixedSpecializedBondAssetSwapPrice2 = fixedSpecializedBondAssetSwap2.fairCleanPrice();

             double error3 = Math.Abs(fixedBondAssetSwapPrice2-fixedSpecializedBondAssetSwapPrice2);
             if (error3>tolerance) {
            Assert.Fail("wrong clean price for fixed bond:"
                        + "\n  generic  fixed rate bond's clean price: "
                        + fixedBondAssetSwapPrice2
                        + "\n  equivalent specialized  bond's clean price: "
                        + fixedSpecializedBondAssetSwapPrice2
                        + "\n  error:                 " + error3
                        + "\n  tolerance:             " + tolerance);
             }
             // market executable price as of 4th sept 2007
             double fixedBondMktPrice2= 102.178;
             AssetSwap fixedBondASW2 = new AssetSwap(payFixedRate,
                                 fixedBond2, fixedBondMktPrice2,
                                 vars.iborIndex, vars.spread,
                                 null,
                                 vars.iborIndex.dayCounter(),
                                 parAssetSwap);
             fixedBondASW2.setPricingEngine(swapEngine);
             AssetSwap fixedSpecializedBondASW2 = new AssetSwap(payFixedRate,
                                          fixedSpecializedBond2,
                                          fixedBondMktPrice2,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             fixedSpecializedBondASW2.setPricingEngine(swapEngine);
             double fixedBondASWSpread2 = fixedBondASW2.fairSpread();
             double fixedSpecializedBondASWSpread2 = fixedSpecializedBondASW2.fairSpread();
             double error4 = Math.Abs(fixedBondASWSpread2-fixedSpecializedBondASWSpread2);
             if (error4>tolerance) {
            Assert.Fail("wrong asw spread for fixed bond:"
                        + "\n  generic  fixed rate bond's  asw spread: "
                        + fixedBondASWSpread2
                        + "\n  equivalent specialized bond's asw spread: "
                        + fixedSpecializedBondASWSpread2
                        + "\n  error:                 " + error4
                        + "\n  tolerance:             " + tolerance);
             }

             //FRN 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)
            .withNotionals(vars.faceAmount);
             Date floatingbondRedemption1 = bondCalendar.adjust(floatingBondMaturityDate1, BusinessDayConvention.Following);
             floatingBondLeg1.Add(new SimpleCashFlow(100.0, floatingbondRedemption1));
             // generic bond
             Bond floatingBond1 = new Bond(settlementDays, bondCalendar, vars.faceAmount,
                  floatingBondMaturityDate1, floatingBondStartDate1, floatingBondLeg1);
             floatingBond1.setPricingEngine(bondEngine);

             // equivalent specialized floater
             Bond floatingSpecializedBond1 = new FloatingRateBond(settlementDays, vars.faceAmount,
                                 floatingBondSchedule1,
                                 vars.iborIndex, new Actual360(),
                                 BusinessDayConvention.Following, fixingDays,
                                 new List<double>{1},
                                 new List<double>{0.0056},
                                 new List<double>(), new List<double>(),
                                 inArrears,
                                 100.0, new Date(29,Month.September,2003));
             floatingSpecializedBond1.setPricingEngine(bondEngine);

             Utils.setCouponPricer(floatingBond1.cashflows(), vars.pricer);
             Utils.setCouponPricer(floatingSpecializedBond1.cashflows(), vars.pricer);
             vars.iborIndex.addFixing(new Date(27,Month.March,2007), 0.0402);
             double floatingBondPrice1 = floatingBond1.cleanPrice();
             double floatingSpecializedBondPrice1= floatingSpecializedBond1.cleanPrice();
             AssetSwap floatingBondAssetSwap1= new AssetSwap(payFixedRate,
                                          floatingBond1, floatingBondPrice1,
                                          vars.iborIndex, vars.nonnullspread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             floatingBondAssetSwap1.setPricingEngine(swapEngine);
             AssetSwap floatingSpecializedBondAssetSwap1= new AssetSwap(payFixedRate,
                                                   floatingSpecializedBond1,
                                                   floatingSpecializedBondPrice1,
                                                   vars.iborIndex,
                                                   vars.nonnullspread,
                                                   null,
                                                   vars.iborIndex.dayCounter(),
                                                   parAssetSwap);
             floatingSpecializedBondAssetSwap1.setPricingEngine(swapEngine);
             double floatingBondAssetSwapPrice1 = floatingBondAssetSwap1.fairCleanPrice();
             double floatingSpecializedBondAssetSwapPrice1 =
            floatingSpecializedBondAssetSwap1.fairCleanPrice();

             double error5 =
            Math.Abs(floatingBondAssetSwapPrice1-floatingSpecializedBondAssetSwapPrice1);
             if (error5>tolerance) {
            Assert.Fail("wrong clean price for frnbond:"
                        + "\n  generic frn rate bond's clean price: "
                        + floatingBondAssetSwapPrice1
                        + "\n  equivalent specialized  bond's price: "
                        + floatingSpecializedBondAssetSwapPrice1
                        + "\n  error:                 " + error5
                        + "\n  tolerance:             " + tolerance);
             }
             // market executable price as of 4th sept 2007
             double floatingBondMktPrice1= 101.33;
             AssetSwap floatingBondASW1= new AssetSwap(payFixedRate,
                                    floatingBond1, floatingBondMktPrice1,
                                    vars.iborIndex, vars.spread,
                                    null,
                                    vars.iborIndex.dayCounter(),
                                    parAssetSwap);
             floatingBondASW1.setPricingEngine(swapEngine);
             AssetSwap floatingSpecializedBondASW1= new AssetSwap(payFixedRate,
                                             floatingSpecializedBond1,
                                             floatingBondMktPrice1,
                                             vars.iborIndex, vars.spread,
                                             null,
                                             vars.iborIndex.dayCounter(),
                                             parAssetSwap);
             floatingSpecializedBondASW1.setPricingEngine(swapEngine);
             double floatingBondASWSpread1 = floatingBondASW1.fairSpread();
             double floatingSpecializedBondASWSpread1 =
            floatingSpecializedBondASW1.fairSpread();
             double error6 =
            Math.Abs(floatingBondASWSpread1-floatingSpecializedBondASWSpread1);
             if (error6>tolerance) {
            Assert.Fail("wrong asw spread for fixed bond:"
                        + "\n  generic  frn rate bond's  asw spread: "
                        + floatingBondASWSpread1
                        + "\n  equivalent specialized bond's asw spread: "
                        + floatingSpecializedBondASWSpread1
                        + "\n  error:                 " + error6
                        + "\n  tolerance:             " + tolerance);
             }
             //FRN bond (Isin: XS0090566539 COE 0 09/24/18)
             //maturity occurs on a business day
             Date floatingBondStartDate2 = new Date(24,Month.September,2004);
             Date floatingBondMaturityDate2 = new Date(24,Month.September,2018);
             Schedule floatingBondSchedule2= new Schedule(floatingBondStartDate2,
                                       floatingBondMaturityDate2,
                                       new Period(Frequency.Semiannual), bondCalendar,
                                       BusinessDayConvention.ModifiedFollowing, BusinessDayConvention.ModifiedFollowing,
                                       DateGeneration.Rule.Backward, false);
             List<CashFlow> floatingBondLeg2 = new IborLeg(floatingBondSchedule2, vars.iborIndex)
            .withPaymentDayCounter(new Actual360())
            .withFixingDays(fixingDays)
            .withSpreads(0.0025)
            .inArrears(inArrears)
            .withPaymentAdjustment(BusinessDayConvention.ModifiedFollowing)
            .withNotionals(vars.faceAmount);
             Date floatingbondRedemption2 = bondCalendar.adjust(floatingBondMaturityDate2, BusinessDayConvention.ModifiedFollowing);
             floatingBondLeg2.Add(new SimpleCashFlow(100.0, floatingbondRedemption2));
             // generic bond
             Bond floatingBond2 = new  Bond(settlementDays, bondCalendar, vars.faceAmount,
                  floatingBondMaturityDate2, floatingBondStartDate2,floatingBondLeg2);
             floatingBond2.setPricingEngine(bondEngine);

             // equivalent specialized floater
             Bond floatingSpecializedBond2 = new FloatingRateBond(settlementDays, vars.faceAmount,
                              floatingBondSchedule2,
                              vars.iborIndex, new Actual360(),
                              BusinessDayConvention.ModifiedFollowing, fixingDays,
                              new List<double>{1},
                              new List<double>{0.0025},
                              new List<double>(), new List<double>(),
                              inArrears,
                              100.0, new Date(24,Month.September,2004));
             floatingSpecializedBond2.setPricingEngine(bondEngine);

             Utils.setCouponPricer(floatingBond2.cashflows(), vars.pricer);
             Utils.setCouponPricer(floatingSpecializedBond2.cashflows(), vars.pricer);

             vars.iborIndex.addFixing(new Date(22,Month.March,2007), 0.04013);

             double floatingBondPrice2 = floatingBond2.cleanPrice();
             double floatingSpecializedBondPrice2= floatingSpecializedBond2.cleanPrice();
             AssetSwap floatingBondAssetSwap2= new AssetSwap(payFixedRate,
                                          floatingBond2, floatingBondPrice2,
                                          vars.iborIndex, vars.nonnullspread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             floatingBondAssetSwap2.setPricingEngine(swapEngine);
             AssetSwap floatingSpecializedBondAssetSwap2= new AssetSwap(payFixedRate,
                                                   floatingSpecializedBond2,
                                                   floatingSpecializedBondPrice2,
                                                   vars.iborIndex,
                                                   vars.nonnullspread,
                                                   null,
                                                   vars.iborIndex.dayCounter(),
                                                   parAssetSwap);
             floatingSpecializedBondAssetSwap2.setPricingEngine(swapEngine);
             double floatingBondAssetSwapPrice2 = floatingBondAssetSwap2.fairCleanPrice();
             double floatingSpecializedBondAssetSwapPrice2 =
            floatingSpecializedBondAssetSwap2.fairCleanPrice();
             double error7 =
            Math.Abs(floatingBondAssetSwapPrice2-floatingSpecializedBondAssetSwapPrice2);
             if (error7>tolerance) {
            Assert.Fail("wrong clean price for frnbond:"
                        + "\n  generic frn rate bond's clean price: "
                        + floatingBondAssetSwapPrice2
                        + "\n  equivalent specialized frn  bond's price: "
                        + floatingSpecializedBondAssetSwapPrice2
                        + "\n  error:                 " + error7
                        + "\n  tolerance:             " + tolerance);
             }
             // market executable price as of 4th sept 2007
             double floatingBondMktPrice2 = 101.26;
             AssetSwap floatingBondASW2= new AssetSwap(payFixedRate,
                                    floatingBond2, floatingBondMktPrice2,
                                    vars.iborIndex, vars.spread,
                                    null,
                                    vars.iborIndex.dayCounter(),
                                    parAssetSwap);
             floatingBondASW2.setPricingEngine(swapEngine);
             AssetSwap floatingSpecializedBondASW2= new AssetSwap(payFixedRate,
                                             floatingSpecializedBond2,
                                             floatingBondMktPrice2,
                                             vars.iborIndex, vars.spread,
                                             null,
                                             vars.iborIndex.dayCounter(),
                                             parAssetSwap);
             floatingSpecializedBondASW2.setPricingEngine(swapEngine);
             double floatingBondASWSpread2 = floatingBondASW2.fairSpread();
             double floatingSpecializedBondASWSpread2 =
            floatingSpecializedBondASW2.fairSpread();
             double error8 =
            Math.Abs(floatingBondASWSpread2-floatingSpecializedBondASWSpread2);
             if (error8>tolerance) {
            Assert.Fail("wrong asw spread for frn bond:"
                        + "\n  generic  frn rate bond's  asw spread: "
                        + floatingBondASWSpread2
                        + "\n  equivalent specialized bond's asw spread: "
                        + floatingSpecializedBondASWSpread2
                        + "\n  error:                 " + error8
                        + "\n  tolerance:             " + tolerance);
             }

             // CMS bond (Isin: XS0228052402 CRDIT 0 8/22/20)
             // maturity doesn't occur on a business day
             Date cmsBondStartDate1 = new Date(22,Month.August,2005);
             Date cmsBondMaturityDate1 = new Date(22,Month.August,2020);
             Schedule cmsBondSchedule1= new Schedule(cmsBondStartDate1,
                                 cmsBondMaturityDate1,
                                 new Period(Frequency.Annual), bondCalendar,
                                 BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                 DateGeneration.Rule.Backward, false);
             List<CashFlow> cmsBondLeg1 = new CmsLeg(cmsBondSchedule1, vars.swapIndex)
            .withPaymentDayCounter(new Thirty360())
            .withFixingDays(fixingDays)
            .withCaps(0.055)
            .withFloors(0.025)
            .inArrears(inArrears)
            .withNotionals(vars.faceAmount);
             Date cmsbondRedemption1 = bondCalendar.adjust(cmsBondMaturityDate1, BusinessDayConvention.Following);
             cmsBondLeg1.Add(new SimpleCashFlow(100.0, cmsbondRedemption1));
             // generic cms bond
             Bond cmsBond1 = new  Bond(settlementDays, bondCalendar, vars.faceAmount,
                  cmsBondMaturityDate1, cmsBondStartDate1, cmsBondLeg1);
             cmsBond1.setPricingEngine(bondEngine);

             // equivalent specialized cms bond
             Bond cmsSpecializedBond1 = new CmsRateBond(settlementDays, vars.faceAmount, cmsBondSchedule1,
                     vars.swapIndex, new Thirty360(),
                     BusinessDayConvention.Following, fixingDays,
                     new List<double>{1.0}, new List<double>{0.0},
                     new List<double>{0.055}, new List<double>{0.025},
                     inArrears,
                     100.0, new Date(22,Month.August,2005));
             cmsSpecializedBond1.setPricingEngine(bondEngine);

             Utils.setCouponPricer(cmsBond1.cashflows(), vars.cmspricer);
             Utils.setCouponPricer(cmsSpecializedBond1.cashflows(), vars.cmspricer);
             vars.swapIndex.addFixing(new Date(18,Month.August,2006), 0.04158);
             double cmsBondPrice1 = cmsBond1.cleanPrice();
             double cmsSpecializedBondPrice1 = cmsSpecializedBond1.cleanPrice();
             AssetSwap cmsBondAssetSwap1= new AssetSwap(payFixedRate,cmsBond1, cmsBondPrice1,
                                    vars.iborIndex, vars.nonnullspread,
                                    null,vars.iborIndex.dayCounter(),
                                    parAssetSwap);
             cmsBondAssetSwap1.setPricingEngine(swapEngine);
             AssetSwap cmsSpecializedBondAssetSwap1= new AssetSwap(payFixedRate,cmsSpecializedBond1,
                                                cmsSpecializedBondPrice1,
                                                vars.iborIndex,
                                                vars.nonnullspread,
                                                null,
                                                vars.iborIndex.dayCounter(),
                                                parAssetSwap);
             cmsSpecializedBondAssetSwap1.setPricingEngine(swapEngine);
             double cmsBondAssetSwapPrice1 = cmsBondAssetSwap1.fairCleanPrice();
             double cmsSpecializedBondAssetSwapPrice1 =
            cmsSpecializedBondAssetSwap1.fairCleanPrice();
             double error9 =
            Math.Abs(cmsBondAssetSwapPrice1-cmsSpecializedBondAssetSwapPrice1);
             if (error9>tolerance) {
            Assert.Fail("wrong clean price for cmsbond:"
                        + "\n  generic bond's clean price: "
                        + cmsBondAssetSwapPrice1
                        + "\n  equivalent specialized cms rate bond's price: "
                        + cmsSpecializedBondAssetSwapPrice1
                        + "\n  error:                 " + error9
                        + "\n  tolerance:             " + tolerance);
             }
             double cmsBondMktPrice1 = 87.02;// market executable price as of 4th sept 2007
             AssetSwap cmsBondASW1= new AssetSwap(payFixedRate,
                              cmsBond1, cmsBondMktPrice1,
                              vars.iborIndex, vars.spread,
                              null,
                              vars.iborIndex.dayCounter(),
                              parAssetSwap);
             cmsBondASW1.setPricingEngine(swapEngine);
             AssetSwap cmsSpecializedBondASW1= new AssetSwap(payFixedRate,
                                          cmsSpecializedBond1,
                                          cmsBondMktPrice1,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             cmsSpecializedBondASW1.setPricingEngine(swapEngine);
             double cmsBondASWSpread1 = cmsBondASW1.fairSpread();
             double cmsSpecializedBondASWSpread1 = cmsSpecializedBondASW1.fairSpread();
             double error10 = Math.Abs(cmsBondASWSpread1-cmsSpecializedBondASWSpread1);
             if (error10>tolerance) {
            Assert.Fail("wrong asw spread for cm bond:"
                        + "\n  generic cms rate bond's  asw spread: "
                        + cmsBondASWSpread1
                        + "\n  equivalent specialized bond's asw spread: "
                        + cmsSpecializedBondASWSpread1
                        + "\n  error:                 " + error10
                        + "\n  tolerance:             " + tolerance);
             }

             //CMS bond (Isin: XS0218766664 ISPIM 0 5/6/15)
             //maturity occurs on a business day
             Date cmsBondStartDate2 = new Date(06,Month.May,2005);
             Date cmsBondMaturityDate2 = new Date(06,Month.May,2015);
             Schedule cmsBondSchedule2= new Schedule(cmsBondStartDate2,
                                 cmsBondMaturityDate2,
                                 new Period(Frequency.Annual), bondCalendar,
                                 BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                 DateGeneration.Rule.Backward, false);
             List<CashFlow> cmsBondLeg2 = new CmsLeg(cmsBondSchedule2, vars.swapIndex)
            .withPaymentDayCounter(new Thirty360())
            .withFixingDays(fixingDays)
            .withGearings(0.84)
            .inArrears(inArrears)
            .withNotionals(vars.faceAmount);
             Date cmsbondRedemption2 = bondCalendar.adjust(cmsBondMaturityDate2,
                                                      BusinessDayConvention.Following);
             cmsBondLeg2.Add(new SimpleCashFlow(100.0, cmsbondRedemption2));
             // generic bond
             Bond cmsBond2 = new  Bond(settlementDays, bondCalendar, vars.faceAmount,
                  cmsBondMaturityDate2, cmsBondStartDate2, cmsBondLeg2);
             cmsBond2.setPricingEngine(bondEngine);

             // equivalent specialized cms bond
             Bond cmsSpecializedBond2 = new  CmsRateBond(settlementDays, vars.faceAmount, cmsBondSchedule2,
                     vars.swapIndex, new Thirty360(),
                     BusinessDayConvention.Following, fixingDays,
                     new List<double>{0.84}, new List<double>{0.0},
                     new List<double>(), new List<double>(),
                     inArrears,
                     100.0, new Date(06,Month.May,2005));
             cmsSpecializedBond2.setPricingEngine(bondEngine);

             Utils.setCouponPricer(cmsBond2.cashflows(), vars.cmspricer);
             Utils.setCouponPricer(cmsSpecializedBond2.cashflows(), vars.cmspricer);
             vars.swapIndex.addFixing(new Date(04,Month.May,2006), 0.04217);
             double cmsBondPrice2 = cmsBond2.cleanPrice();
             double cmsSpecializedBondPrice2 = cmsSpecializedBond2.cleanPrice();
             AssetSwap cmsBondAssetSwap2= new AssetSwap(payFixedRate,cmsBond2, cmsBondPrice2,
                                    vars.iborIndex, vars.nonnullspread,
                                    null,
                                    vars.iborIndex.dayCounter(),
                                    parAssetSwap);
             cmsBondAssetSwap2.setPricingEngine(swapEngine);
             AssetSwap cmsSpecializedBondAssetSwap2= new AssetSwap(payFixedRate,cmsSpecializedBond2,
                                                cmsSpecializedBondPrice2,
                                                vars.iborIndex,
                                                vars.nonnullspread,
                                                null,
                                                vars.iborIndex.dayCounter(),
                                                parAssetSwap);
             cmsSpecializedBondAssetSwap2.setPricingEngine(swapEngine);
             double cmsBondAssetSwapPrice2 = cmsBondAssetSwap2.fairCleanPrice();
             double cmsSpecializedBondAssetSwapPrice2 =
            cmsSpecializedBondAssetSwap2.fairCleanPrice();
             double error11 =
            Math.Abs(cmsBondAssetSwapPrice2-cmsSpecializedBondAssetSwapPrice2);
             if (error11>tolerance) {
            Assert.Fail("wrong clean price for cmsbond:"
                        + "\n  generic  bond's clean price: "
                        + cmsBondAssetSwapPrice2
                        + "\n  equivalent specialized cms rate bond's price: "
                        + cmsSpecializedBondAssetSwapPrice2
                        + "\n  error:                 " + error11
                        + "\n  tolerance:             " + tolerance);
             }
             double cmsBondMktPrice2 = 94.35;// market executable price as of 4th sept 2007
             AssetSwap cmsBondASW2= new AssetSwap(payFixedRate,
                              cmsBond2, cmsBondMktPrice2,
                              vars.iborIndex, vars.spread,
                              null,
                              vars.iborIndex.dayCounter(),
                              parAssetSwap);
             cmsBondASW2.setPricingEngine(swapEngine);
             AssetSwap cmsSpecializedBondASW2= new AssetSwap(payFixedRate,
                                          cmsSpecializedBond2,
                                          cmsBondMktPrice2,
                                          vars.iborIndex, vars.spread,
                                          null,
                                          vars.iborIndex.dayCounter(),
                                          parAssetSwap);
             cmsSpecializedBondASW2.setPricingEngine(swapEngine);
             double cmsBondASWSpread2 = cmsBondASW2.fairSpread();
             double cmsSpecializedBondASWSpread2 = cmsSpecializedBondASW2.fairSpread();
             double error12 = Math.Abs(cmsBondASWSpread2-cmsSpecializedBondASWSpread2);
             if (error12>tolerance) {
            Assert.Fail("wrong asw spread for cm bond:"
                        + "\n  generic cms rate bond's  asw spread: "
                        + cmsBondASWSpread2
                        + "\n  equivalent specialized bond's asw spread: "
                        + cmsSpecializedBondASWSpread2
                        + "\n  error:                 " + error12
                        + "\n  tolerance:             " + tolerance);
             }

              //  Zero-Coupon bond (Isin: DE0004771662 IBRD 0 12/20/15)
              //  maturity doesn't occur on a business day
             Date zeroCpnBondStartDate1 = new Date(19,Month.December,1985);
             Date zeroCpnBondMaturityDate1 = new Date(20,Month.December,2015);
             Date zeroCpnBondRedemption1 = bondCalendar.adjust(zeroCpnBondMaturityDate1,
                                                         BusinessDayConvention.Following);
             List<CashFlow> zeroCpnBondLeg1 = new List<CashFlow>{new SimpleCashFlow(100.0, zeroCpnBondRedemption1)};
             // generic bond
             Bond zeroCpnBond1 = new Bond(settlementDays, bondCalendar, vars.faceAmount,
                  zeroCpnBondMaturityDate1, zeroCpnBondStartDate1, zeroCpnBondLeg1);
             zeroCpnBond1.setPricingEngine(bondEngine);

             // specialized zerocpn bond
             Bond zeroCpnSpecializedBond1= new ZeroCouponBond(settlementDays, bondCalendar, vars.faceAmount,
                     new Date(20,Month.December,2015),
                     BusinessDayConvention.Following,
                     100.0, new Date(19,Month.December,1985));
             zeroCpnSpecializedBond1.setPricingEngine(bondEngine);

             double zeroCpnBondPrice1 = zeroCpnBond1.cleanPrice();
             double zeroCpnSpecializedBondPrice1 = zeroCpnSpecializedBond1.cleanPrice();
             AssetSwap zeroCpnBondAssetSwap1= new AssetSwap(payFixedRate,zeroCpnBond1,
                                       zeroCpnBondPrice1,
                                       vars.iborIndex, vars.nonnullspread,
                                       null,
                                       vars.iborIndex.dayCounter(),
                                       parAssetSwap);
             zeroCpnBondAssetSwap1.setPricingEngine(swapEngine);
             AssetSwap zeroCpnSpecializedBondAssetSwap1= new AssetSwap(payFixedRate,
                                                   zeroCpnSpecializedBond1,
                                                   zeroCpnSpecializedBondPrice1,
                                                   vars.iborIndex,
                                                   vars.nonnullspread,
                                                   null,
                                                   vars.iborIndex.dayCounter(),
                                                   parAssetSwap);
             zeroCpnSpecializedBondAssetSwap1.setPricingEngine(swapEngine);
             double zeroCpnBondAssetSwapPrice1 = zeroCpnBondAssetSwap1.fairCleanPrice();
             double zeroCpnSpecializedBondAssetSwapPrice1 =
            zeroCpnSpecializedBondAssetSwap1.fairCleanPrice();
             double error13 =
            Math.Abs(zeroCpnBondAssetSwapPrice1-zeroCpnSpecializedBondAssetSwapPrice1);
             if (error13>tolerance) {
            Assert.Fail("wrong clean price for zerocpn bond:"
                        + "\n  generic zero cpn bond's clean price: "
                        + zeroCpnBondAssetSwapPrice1
                        + "\n  specialized equivalent bond's price: "
                        + zeroCpnSpecializedBondAssetSwapPrice1
                        + "\n  error:                 " + error13
                        + "\n  tolerance:             " + tolerance);
             }
             // market executable price as of 4th sept 2007
             double zeroCpnBondMktPrice1 = 72.277;
             AssetSwap zeroCpnBondASW1= new AssetSwap(payFixedRate,
                                 zeroCpnBond1,zeroCpnBondMktPrice1,
                                 vars.iborIndex, vars.spread,
                                 null,
                                 vars.iborIndex.dayCounter(),
                                 parAssetSwap);
             zeroCpnBondASW1.setPricingEngine(swapEngine);
             AssetSwap zeroCpnSpecializedBondASW1= new AssetSwap(payFixedRate,
                                             zeroCpnSpecializedBond1,
                                             zeroCpnBondMktPrice1,
                                             vars.iborIndex, vars.spread,
                                             null,
                                             vars.iborIndex.dayCounter(),
                                             parAssetSwap);
             zeroCpnSpecializedBondASW1.setPricingEngine(swapEngine);
             double zeroCpnBondASWSpread1 = zeroCpnBondASW1.fairSpread();
             double zeroCpnSpecializedBondASWSpread1 =
            zeroCpnSpecializedBondASW1.fairSpread();
             double error14 =
            Math.Abs(zeroCpnBondASWSpread1-zeroCpnSpecializedBondASWSpread1);
             if (error14>tolerance) {
            Assert.Fail("wrong asw spread for zeroCpn bond:"
                        + "\n  generic zeroCpn bond's  asw spread: "
                        + zeroCpnBondASWSpread1
                        + "\n  equivalent specialized bond's asw spread: "
                        + zeroCpnSpecializedBondASWSpread1
                        + "\n  error:                 " + error14
                        + "\n  tolerance:             " + tolerance);
             }

              //  Zero Coupon bond (Isin: IT0001200390 ISPIM 0 02/17/28)
              //  maturity doesn't occur on a business day
             Date zeroCpnBondStartDate2 = new Date(17,Month.February,1998);
             Date zeroCpnBondMaturityDate2 = new Date(17,Month.February,2028);
             Date zerocpbondRedemption2 = bondCalendar.adjust(zeroCpnBondMaturityDate2,
                                                         BusinessDayConvention.Following);
             List<CashFlow> zeroCpnBondLeg2 = new List<CashFlow>{new SimpleCashFlow(100.0, zerocpbondRedemption2)};
             // generic bond
             Bond zeroCpnBond2 = new Bond(settlementDays, bondCalendar, vars.faceAmount,
                  zeroCpnBondMaturityDate2, zeroCpnBondStartDate2, zeroCpnBondLeg2);
             zeroCpnBond2.setPricingEngine(bondEngine);

             // specialized zerocpn bond
             Bond zeroCpnSpecializedBond2 = new ZeroCouponBond(settlementDays, bondCalendar, vars.faceAmount,
                        new Date(17,Month.February,2028),
                        BusinessDayConvention.Following,
                        100.0, new Date(17,Month.February,1998));
             zeroCpnSpecializedBond2.setPricingEngine(bondEngine);

             double zeroCpnBondPrice2 = zeroCpnBond2.cleanPrice();
             double zeroCpnSpecializedBondPrice2 = zeroCpnSpecializedBond2.cleanPrice();

             AssetSwap zeroCpnBondAssetSwap2= new AssetSwap(payFixedRate,zeroCpnBond2,
                                       zeroCpnBondPrice2,
                                       vars.iborIndex, vars.nonnullspread,
                                       null,
                                       vars.iborIndex.dayCounter(),
                                       parAssetSwap);
             zeroCpnBondAssetSwap2.setPricingEngine(swapEngine);
             AssetSwap zeroCpnSpecializedBondAssetSwap2= new AssetSwap(payFixedRate,
                                                   zeroCpnSpecializedBond2,
                                                   zeroCpnSpecializedBondPrice2,
                                                   vars.iborIndex,
                                                   vars.nonnullspread,
                                                   null,
                                                   vars.iborIndex.dayCounter(),
                                                   parAssetSwap);
             zeroCpnSpecializedBondAssetSwap2.setPricingEngine(swapEngine);
             double zeroCpnBondAssetSwapPrice2 = zeroCpnBondAssetSwap2.fairCleanPrice();
             double zeroCpnSpecializedBondAssetSwapPrice2 =
                                    zeroCpnSpecializedBondAssetSwap2.fairCleanPrice();
             double error15 = Math.Abs(zeroCpnBondAssetSwapPrice2
                                 -zeroCpnSpecializedBondAssetSwapPrice2);
             if (error15>tolerance) {
            Assert.Fail("wrong clean price for zerocpn bond:"
                        + "\n  generic zero cpn bond's clean price: "
                        + zeroCpnBondAssetSwapPrice2
                        + "\n  equivalent specialized bond's price: "
                        + zeroCpnSpecializedBondAssetSwapPrice2
                        + "\n  error:                 " + error15
                        + "\n  tolerance:             " + tolerance);
             }
             // market executable price as of 4th sept 2007
             double zeroCpnBondMktPrice2 = 72.277;
             AssetSwap zeroCpnBondASW2= new AssetSwap(payFixedRate,
                                 zeroCpnBond2,zeroCpnBondMktPrice2,
                                 vars.iborIndex, vars.spread,
                                 null,
                                 vars.iborIndex.dayCounter(),
                                 parAssetSwap);
             zeroCpnBondASW2.setPricingEngine(swapEngine);
             AssetSwap zeroCpnSpecializedBondASW2= new AssetSwap(payFixedRate,
                                             zeroCpnSpecializedBond2,
                                             zeroCpnBondMktPrice2,
                                             vars.iborIndex, vars.spread,
                                             null,
                                             vars.iborIndex.dayCounter(),
                                             parAssetSwap);
             zeroCpnSpecializedBondASW2.setPricingEngine(swapEngine);
             double zeroCpnBondASWSpread2 = zeroCpnBondASW2.fairSpread();
             double zeroCpnSpecializedBondASWSpread2 =
            zeroCpnSpecializedBondASW2.fairSpread();
             double error16 =
            Math.Abs(zeroCpnBondASWSpread2-zeroCpnSpecializedBondASWSpread2);
             if (error16>tolerance) {
            Assert.Fail("wrong asw spread for zeroCpn bond:"
                        + "\n  generic zeroCpn bond's  asw spread: "
                        + zeroCpnBondASWSpread2
                        + "\n  equivalent specialized bond's asw spread: "
                        + zeroCpnSpecializedBondASWSpread2
                        + "\n  error:                 " + error16
                        + "\n  tolerance:             " + tolerance);
             }
        }
Example #18
0
 public MakeCms withDiscountingTermStructure(Handle <YieldTermStructure> discountingTermStructure)
 {
     engine_ = new DiscountingSwapEngine(discountingTermStructure);
     return(this);
 }
Example #19
0
        public void testImpliedValue()
        {
            // Testing implied bond value against asset-swap fair price with null spread
             CommonVars vars = new CommonVars();

             Calendar bondCalendar = new TARGET();
             int settlementDays = 3;
             int fixingDays = 2;
             bool payFixedRate = true;
             bool parAssetSwap = true;
             bool inArrears = false;

             // Fixed Underlying bond (Isin: DE0001135275 DBR 4 01/04/37)
             // maturity doesn't occur on a business day

             Schedule fixedBondSchedule1 = new Schedule( new Date(4,Month.January,2005),
                                                     new Date(4,Month.January,2037),
                                                     new Period(Frequency.Annual), bondCalendar,
                                                     BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                                     DateGeneration.Rule.Backward, false);
             Bond fixedBond1 = new FixedRateBond(settlementDays, vars.faceAmount,
                                                fixedBondSchedule1,
                                                new List<double>(){0.04},
                                                new ActualActual(ActualActual.Convention.ISDA),
                                                BusinessDayConvention.Following,
                                                100.0, new Date(4,Month.January,2005));

             IPricingEngine bondEngine = new DiscountingBondEngine(vars.termStructure);
             IPricingEngine swapEngine = new DiscountingSwapEngine(vars.termStructure);
             fixedBond1.setPricingEngine(bondEngine);

             double fixedBondPrice1 = fixedBond1.cleanPrice();
             AssetSwap fixedBondAssetSwap1 = new AssetSwap(payFixedRate, fixedBond1, fixedBondPrice1, vars.iborIndex, vars.spread,
                                                       null, vars.iborIndex.dayCounter(), parAssetSwap);
             fixedBondAssetSwap1.setPricingEngine(swapEngine);
             double fixedBondAssetSwapPrice1 = fixedBondAssetSwap1.fairCleanPrice();
             double tolerance = 1.0e-13;
             double error1 = Math.Abs(fixedBondAssetSwapPrice1-fixedBondPrice1);

             if (error1>tolerance) {
            Assert.Fail("wrong zero spread asset swap price for fixed bond:" +
                        "\n  bond's clean price:    " + fixedBondPrice1 +
                        "\n  asset swap fair price: " + fixedBondAssetSwapPrice1 +
                        "\n  error:                 " + error1 +
                        "\n  tolerance:             " + tolerance);
             }

             // Fixed Underlying bond (Isin: IT0006527060 IBRD 5 02/05/19)
             // maturity occurs on a business day

             Schedule fixedBondSchedule2 = new Schedule( new Date(5,Month.February,2005),
                                                     new Date(5,Month.February,2019),
                                                     new Period(Frequency.Annual), bondCalendar,
                                                     BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                                     DateGeneration.Rule.Backward, false);
             Bond fixedBond2 = new FixedRateBond(settlementDays, vars.faceAmount,
                                             fixedBondSchedule2,
                                             new List<double>(){0.05},
                                             new Thirty360(Thirty360.Thirty360Convention.BondBasis),
                                             BusinessDayConvention.Following,
                                             100.0, new Date(5,Month.February,2005));

             fixedBond2.setPricingEngine(bondEngine);

             double fixedBondPrice2 = fixedBond2.cleanPrice();
             AssetSwap fixedBondAssetSwap2 = new AssetSwap(payFixedRate, fixedBond2, fixedBondPrice2, vars.iborIndex, vars.spread,
                                                       null, vars.iborIndex.dayCounter(),  parAssetSwap);
             fixedBondAssetSwap2.setPricingEngine(swapEngine);
             double fixedBondAssetSwapPrice2 = fixedBondAssetSwap2.fairCleanPrice();
             double error2 = Math.Abs(fixedBondAssetSwapPrice2-fixedBondPrice2);

             if (error2>tolerance) {
            Assert.Fail("wrong zero spread asset swap price for fixed bond:" +
                        "\n  bond's clean price:    " + fixedBondPrice2 +
                        "\n  asset swap fair price: " + fixedBondAssetSwapPrice2 +
                        "\n  error:                 " + error2 +
                        "\n  tolerance:             " + tolerance);
             }

             // FRN Underlying bond (Isin: IT0003543847 ISPIM 0 09/29/13)
             // maturity doesn't occur on a business day

             Schedule floatingBondSchedule1 = new Schedule( new Date(29,Month.September,2003),
                                                        new Date(29,Month.September,2013),
                                                        new Period(Frequency.Semiannual), bondCalendar,
                                                        BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                                        DateGeneration.Rule.Backward, false);

             Bond floatingBond1 = new FloatingRateBond(settlementDays, vars.faceAmount,
                                                   floatingBondSchedule1,
                                                   vars.iborIndex, new Actual360(),
                                                   BusinessDayConvention.Following, fixingDays,
                                                   new List<double>(){1},
                                                   new List<double>(){0.0056},
                                                   new List<double>(),
                                                   new List<double>(),
                                                   inArrears,
                                                   100.0, new Date(29,Month.September,2003));

             floatingBond1.setPricingEngine(bondEngine);

             Utils.setCouponPricer(floatingBond1.cashflows(), vars.pricer);
             vars.iborIndex.addFixing(new Date(27,Month.March,2007), 0.0402);
             double floatingBondPrice1 = floatingBond1.cleanPrice();
             AssetSwap floatingBondAssetSwap1 = new AssetSwap(payFixedRate, floatingBond1, floatingBondPrice1, vars.iborIndex, vars.spread,
                                                          null, vars.iborIndex.dayCounter(), parAssetSwap);
             floatingBondAssetSwap1.setPricingEngine(swapEngine);
             double floatingBondAssetSwapPrice1 = floatingBondAssetSwap1.fairCleanPrice();
             double error3 = Math.Abs(floatingBondAssetSwapPrice1-floatingBondPrice1);

             if (error3>tolerance) {
            Assert.Fail("wrong zero spread asset swap price for floater:" +
                        "\n  bond's clean price:    " + floatingBondPrice1 +
                        "\n  asset swap fair price: " + floatingBondAssetSwapPrice1 +
                        "\n  error:                 " + error3 +
                        "\n  tolerance:             " + tolerance);
             }

             // FRN Underlying bond (Isin: XS0090566539 COE 0 09/24/18)
             // maturity occurs on a business day

             Schedule floatingBondSchedule2 = new Schedule( new Date(24,Month.September,2004),
                                                        new Date(24,Month.September,2018),
                                                        new Period(Frequency.Semiannual), bondCalendar,
                                                        BusinessDayConvention.ModifiedFollowing, BusinessDayConvention.ModifiedFollowing,
                                                        DateGeneration.Rule.Backward, false);
             Bond floatingBond2 = new FloatingRateBond( settlementDays, vars.faceAmount,
                                                    floatingBondSchedule2,
                                                    vars.iborIndex, new Actual360(),
                                                    BusinessDayConvention.ModifiedFollowing, fixingDays,
                                                    new List<double>(){1},
                                                    new List<double>(){0.0025},
                                                    new List<double>(),
                                                    new List<double>(),
                                                    inArrears,
                                                    100.0, new Date(24,Month.September,2004));

             floatingBond2.setPricingEngine(bondEngine);

             Utils.setCouponPricer(floatingBond2.cashflows(), vars.pricer);
             vars.iborIndex.addFixing( new Date(22,Month.March,2007), 0.04013);
             double currentCoupon=0.04013+0.0025;
             double floatingCurrentCoupon= floatingBond2.nextCouponRate();
             double error4= Math.Abs(floatingCurrentCoupon-currentCoupon);
             if (error4>tolerance) {
            Assert.Fail("wrong current coupon is returned for floater bond:" +
                        "\n  bond's calculated current coupon:      " +
                        currentCoupon +
                        "\n  current coupon asked to the bond: " +
                        floatingCurrentCoupon +
                        "\n  error:                 " + error4 +
                        "\n  tolerance:             " + tolerance);
             }

             double floatingBondPrice2 = floatingBond2.cleanPrice();
             AssetSwap floatingBondAssetSwap2 = new AssetSwap(payFixedRate,floatingBond2, floatingBondPrice2, vars.iborIndex, vars.spread,
                                                          null, vars.iborIndex.dayCounter(), parAssetSwap);
             floatingBondAssetSwap2.setPricingEngine(swapEngine);
             double floatingBondAssetSwapPrice2 = floatingBondAssetSwap2.fairCleanPrice();
             double error5 = Math.Abs(floatingBondAssetSwapPrice2-floatingBondPrice2);

             if (error5>tolerance) {
            Assert.Fail("wrong zero spread asset swap price for floater:" +
                        "\n  bond's clean price:    " + floatingBondPrice2 +
                        "\n  asset swap fair price: " + floatingBondAssetSwapPrice2 +
                        "\n  error:                 " + error5 +
                        "\n  tolerance:             " + tolerance);
             }

             // CMS Underlying bond (Isin: XS0228052402 CRDIT 0 8/22/20)
             // maturity doesn't occur on a business day

             Schedule cmsBondSchedule1 = new Schedule( new Date(22,Month.August,2005),
                                 new Date(22,Month.August,2020),
                                 new Period(Frequency.Annual), bondCalendar,
                                 BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                 DateGeneration.Rule.Backward, false);
             Bond cmsBond1 = new CmsRateBond(settlementDays, vars.faceAmount,
                                             cmsBondSchedule1,
                                             vars.swapIndex, new Thirty360(),
                                             BusinessDayConvention.Following, fixingDays,
                                             new List<double>(){1.0},
                                             new List<double>(){0.0},
                                             new List<double>(){0.055},
                                             new List<double>(){0.025},
                                             inArrears,
                                             100.0, new Date(22,Month.August,2005));

             cmsBond1.setPricingEngine(bondEngine);

             Utils.setCouponPricer(cmsBond1.cashflows(), vars.cmspricer);
             vars.swapIndex.addFixing( new Date(18,Month.August,2006), 0.04158);
             double cmsBondPrice1 = cmsBond1.cleanPrice();
             AssetSwap cmsBondAssetSwap1 = new AssetSwap(payFixedRate, cmsBond1, cmsBondPrice1, vars.iborIndex, vars.spread,
                                                     null,vars.iborIndex.dayCounter(), parAssetSwap);
             cmsBondAssetSwap1.setPricingEngine(swapEngine);
             double cmsBondAssetSwapPrice1 = cmsBondAssetSwap1.fairCleanPrice();
             double error6 = Math.Abs(cmsBondAssetSwapPrice1-cmsBondPrice1);

             if (error6>tolerance) {
            Assert.Fail("wrong zero spread asset swap price for cms bond:" +
                        "\n  bond's clean price:    " + cmsBondPrice1 +
                        "\n  asset swap fair price: " + cmsBondAssetSwapPrice1 +
                        "\n  error:                 " + error6 +
                        "\n  tolerance:             " + tolerance);
             }

             // CMS Underlying bond (Isin: XS0218766664 ISPIM 0 5/6/15)
             // maturity occurs on a business day

             Schedule cmsBondSchedule2 = new Schedule( new Date(06,Month.May,2005),
                                                   new Date(06,Month.May,2015),
                                                   new Period(Frequency.Annual), bondCalendar,
                                                   BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                                   DateGeneration.Rule.Backward, false);
            Bond cmsBond2 = new CmsRateBond(settlementDays, vars.faceAmount, cmsBondSchedule2,
                        vars.swapIndex, new Thirty360(),
                        BusinessDayConvention.Following, fixingDays,
                        new List<double>(){0.84}, new List<double>(){0.0},
                        new List<double>(), new List<double>(),
                        inArrears,
                        100.0, new Date(06,Month.May,2005));

             cmsBond2.setPricingEngine(bondEngine);

             Utils.setCouponPricer(cmsBond2.cashflows(), vars.cmspricer);
             vars.swapIndex.addFixing( new Date(04,Month.May,2006), 0.04217);
             double cmsBondPrice2 = cmsBond2.cleanPrice();
             AssetSwap cmsBondAssetSwap2 = new AssetSwap(payFixedRate,cmsBond2, cmsBondPrice2, vars.iborIndex, vars.spread,
                                                     null, vars.iborIndex.dayCounter(), parAssetSwap);
             cmsBondAssetSwap2.setPricingEngine(swapEngine);
             double cmsBondAssetSwapPrice2 = cmsBondAssetSwap2.fairCleanPrice();
             double error7 = Math.Abs(cmsBondAssetSwapPrice2-cmsBondPrice2);

             if (error7>tolerance) {
            Assert.Fail("wrong zero spread asset swap price for cms bond:" +
                        "\n  bond's clean price:    " + cmsBondPrice2 +
                        "\n  asset swap fair price: " + cmsBondAssetSwapPrice2 +
                        "\n  error:                 " + error7 +
                        "\n  tolerance:             " + tolerance);
             }

             // Zero Coupon bond (Isin: DE0004771662 IBRD 0 12/20/15)
             // maturity doesn't occur on a business day

             Bond zeroCpnBond1 = new ZeroCouponBond(settlementDays, bondCalendar, vars.faceAmount,
                                                new Date(20,Month.December,2015),
                                                BusinessDayConvention.Following,
                                                100.0, new Date(19,Month.December,1985));

             zeroCpnBond1.setPricingEngine(bondEngine);

             double zeroCpnBondPrice1 = zeroCpnBond1.cleanPrice();
             AssetSwap zeroCpnAssetSwap1 = new AssetSwap(payFixedRate,zeroCpnBond1, zeroCpnBondPrice1, vars.iborIndex, vars.spread,
                                                     null, vars.iborIndex.dayCounter(), parAssetSwap);
             zeroCpnAssetSwap1.setPricingEngine(swapEngine);
             double zeroCpnBondAssetSwapPrice1 = zeroCpnAssetSwap1.fairCleanPrice();
             double error8 = Math.Abs(cmsBondAssetSwapPrice1-cmsBondPrice1);

             if (error8>tolerance) {
            Assert.Fail("wrong zero spread asset swap price for zero cpn bond:" +
                        "\n  bond's clean price:    " + zeroCpnBondPrice1 +
                        "\n  asset swap fair price: " + zeroCpnBondAssetSwapPrice1 +
                        "\n  error:                 " + error8 +
                        "\n  tolerance:             " + tolerance);
             }

             // Zero Coupon bond (Isin: IT0001200390 ISPIM 0 02/17/28)
             // maturity occurs on a business day

             Bond zeroCpnBond2 = new ZeroCouponBond(settlementDays, bondCalendar, vars.faceAmount,
                           new Date(17,Month.February,2028),
                           BusinessDayConvention.Following,
                           100.0, new Date(17,Month.February,1998));

             zeroCpnBond2.setPricingEngine(bondEngine);

             double zeroCpnBondPrice2 = zeroCpnBond2.cleanPrice();
             AssetSwap zeroCpnAssetSwap2 = new AssetSwap(payFixedRate, zeroCpnBond2, zeroCpnBondPrice2,  vars.iborIndex, vars.spread,
                                                     null,vars.iborIndex.dayCounter(), parAssetSwap);
             zeroCpnAssetSwap2.setPricingEngine(swapEngine);
             double zeroCpnBondAssetSwapPrice2 = zeroCpnAssetSwap2.fairCleanPrice();
             double error9 = Math.Abs(cmsBondAssetSwapPrice2-cmsBondPrice2);

             if (error9>tolerance) {
            Assert.Fail("wrong zero spread asset swap price for zero cpn bond:" +
                        "\n  bond's clean price:      " + zeroCpnBondPrice2 +
                        "\n  asset swap fair price:   " + zeroCpnBondAssetSwapPrice2 +
                        "\n  error:                   " + error9 +
                        "\n  tolerance:               " + tolerance);
             }
        }
Example #20
0
        protected override void performCalculations()
        {
            Calendar calendar = index_.fixingCalendar();
            int fixingDays = index_.fixingDays();

            Date exerciseDate = exerciseDate_;
              if (exerciseDate == null)
                exerciseDate = calendar.advance(termStructure_.link.referenceDate(),
                                            maturity_,
                                            index_.businessDayConvention());

            Date startDate = calendar.advance(exerciseDate,
                                    fixingDays, TimeUnit.Days,
                                    index_.businessDayConvention());

            Date endDate = endDate_;
            if (endDate == null)
            endDate = calendar.advance(startDate, length_,
                                       index_.businessDayConvention());

            Schedule fixedSchedule = new Schedule(startDate, endDate, fixedLegTenor_, calendar,
                               index_.businessDayConvention(),
                               index_.businessDayConvention(),
                               DateGeneration.Rule.Forward, false);
            Schedule floatSchedule = new Schedule(startDate, endDate, index_.tenor(), calendar,
                               index_.businessDayConvention(),
                               index_.businessDayConvention(),
                               DateGeneration.Rule.Forward, false);

            IPricingEngine swapEngine = new DiscountingSwapEngine(termStructure_, false);

            VanillaSwap.Type type = VanillaSwap.Type.Receiver;

            VanillaSwap temp = new VanillaSwap(VanillaSwap.Type.Receiver, nominal_,
                            fixedSchedule, 0.0, fixedLegDayCounter_,
                            floatSchedule, index_, 0.0, floatingLegDayCounter_);
            temp.setPricingEngine(swapEngine);
            double forward = temp.fairRate();
            if(! strike_.HasValue)
              {
            exerciseRate_ = forward;
            }
            else
              {
            exerciseRate_ = strike_.Value;
            type = strike_ <= forward ? VanillaSwap.Type.Receiver : VanillaSwap.Type.Payer;
            // ensure that calibration instrument is out of the money
            }
            swap_ = new VanillaSwap(type, nominal_,
                            fixedSchedule, exerciseRate_, fixedLegDayCounter_,
                            floatSchedule, index_, 0.0, floatingLegDayCounter_);
            swap_.setPricingEngine(swapEngine);

            Exercise exercise = new EuropeanExercise(exerciseDate);

            swaption_ = new Swaption(swap_, exercise);

            base.performCalculations();
        }
Example #21
0
        static void Main(string[] args)
        {
            DateTime timer = DateTime.Now;

            /*********************
            ***  MARKET DATA  ***
            *********************/

            Calendar calendar = new TARGET();

            Date settlementDate = new Date(22, Month.September, 2004);
            // must be a business day
            settlementDate = calendar.adjust(settlementDate);

            int fixingDays = 2;
            Date todaysDate = calendar.advance(settlementDate, -fixingDays, TimeUnit.Days);
            // nothing to do with Date::todaysDate
            Settings.setEvaluationDate(todaysDate);

            todaysDate = Settings.evaluationDate();
            Console.WriteLine("Today: {0}, {1}", todaysDate.DayOfWeek, todaysDate);
            Console.WriteLine("Settlement date: {0}, {1}", settlementDate.DayOfWeek, settlementDate);

            // deposits
            double d1wQuote = 0.0382;
            double d1mQuote = 0.0372;
            double d3mQuote = 0.0363;
            double d6mQuote = 0.0353;
            double d9mQuote = 0.0348;
            double d1yQuote = 0.0345;
            // FRAs
            double fra3x6Quote = 0.037125;
            double fra6x9Quote = 0.037125;
            double fra6x12Quote = 0.037125;
            // futures
            double fut1Quote = 96.2875;
            double fut2Quote = 96.7875;
            double fut3Quote = 96.9875;
            double fut4Quote = 96.6875;
            double fut5Quote = 96.4875;
            double fut6Quote = 96.3875;
            double fut7Quote = 96.2875;
            double fut8Quote = 96.0875;
            // swaps
            double s2yQuote = 0.037125;
            double s3yQuote = 0.0398;
            double s5yQuote = 0.0443;
            double s10yQuote = 0.05165;
            double s15yQuote = 0.055175;

            /********************
            ***    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.

            // deposits
            Quote d1wRate = new SimpleQuote(d1wQuote);
            Quote d1mRate = new SimpleQuote(d1mQuote);
            Quote d3mRate = new SimpleQuote(d3mQuote);
            Quote d6mRate = new SimpleQuote(d6mQuote);
            Quote d9mRate = new SimpleQuote(d9mQuote);
            Quote d1yRate = new SimpleQuote(d1yQuote);
            // FRAs
            Quote fra3x6Rate = new SimpleQuote(fra3x6Quote);
            Quote fra6x9Rate = new SimpleQuote(fra6x9Quote);
            Quote fra6x12Rate = new SimpleQuote(fra6x12Quote);
            // futures
            Quote fut1Price = new SimpleQuote(fut1Quote);
            Quote fut2Price = new SimpleQuote(fut2Quote);
            Quote fut3Price = new SimpleQuote(fut3Quote);
            Quote fut4Price = new SimpleQuote(fut4Quote);
            Quote fut5Price = new SimpleQuote(fut5Quote);
            Quote fut6Price = new SimpleQuote(fut6Quote);
            Quote fut7Price = new SimpleQuote(fut7Quote);
            Quote fut8Price = new SimpleQuote(fut8Quote);
            // swaps
            Quote s2yRate = new SimpleQuote(s2yQuote);
            Quote s3yRate = new SimpleQuote(s3yQuote);
            Quote s5yRate = new SimpleQuote(s5yQuote);
            Quote s10yRate = new SimpleQuote(s10yQuote);
            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.

            // deposits
            DayCounter depositDayCounter = new Actual360();

            RateHelper d1w = new DepositRateHelper(new Handle<Quote>(d1wRate), new Period(1, TimeUnit.Weeks),
                fixingDays, calendar, BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);
            RateHelper d1m = new DepositRateHelper(new Handle<Quote>(d1mRate), new Period(1, TimeUnit.Months),
                fixingDays, calendar, BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);
            RateHelper d3m = new DepositRateHelper(new Handle<Quote>(d3mRate), new Period(3, TimeUnit.Months),
                fixingDays, calendar, BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);
            RateHelper d6m = new DepositRateHelper(new Handle<Quote>(d6mRate), new Period(6, TimeUnit.Months),
                fixingDays, calendar, BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);
            RateHelper d9m = new DepositRateHelper(new Handle<Quote>(d9mRate), new Period(9, TimeUnit.Months),
                fixingDays, calendar, BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);
            RateHelper d1y = new DepositRateHelper(new Handle<Quote>(d1yRate), new Period(1, TimeUnit.Years),
                fixingDays, calendar, BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);

            // setup FRAs
            RateHelper fra3x6 = new FraRateHelper(new Handle<Quote>(fra3x6Rate), 3, 6, fixingDays, calendar,
                        BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);
            RateHelper fra6x9 = new FraRateHelper(new Handle<Quote>(fra6x9Rate), 6, 9, fixingDays, calendar,
                        BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);
            RateHelper fra6x12 = new FraRateHelper(new Handle<Quote>(fra6x12Rate), 6, 12, fixingDays, calendar,
                        BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);

            // setup futures
            // Handle<Quote> convexityAdjustment = new Handle<Quote>(new SimpleQuote(0.0));
            int futMonths = 3;
            Date imm = IMM.nextDate(settlementDate);

            RateHelper fut1 = new FuturesRateHelper(new Handle<Quote>(fut1Price), imm, futMonths, calendar,
                    BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);

            imm = IMM.nextDate(imm + 1);
            RateHelper fut2 = new FuturesRateHelper(new Handle<Quote>(fut2Price), imm, futMonths, calendar,
                    BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);

            imm = IMM.nextDate(imm + 1);
            RateHelper fut3 = new FuturesRateHelper(new Handle<Quote>(fut3Price), imm, futMonths, calendar,
                    BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);

            imm = IMM.nextDate(imm + 1);
            RateHelper fut4 = new FuturesRateHelper(new Handle<Quote>(fut4Price), imm, futMonths, calendar,
                    BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);

            imm = IMM.nextDate(imm + 1);
            RateHelper fut5 = new FuturesRateHelper(new Handle<Quote>(fut5Price), imm, futMonths, calendar,
                    BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);

            imm = IMM.nextDate(imm + 1);
            RateHelper fut6 = new FuturesRateHelper(new Handle<Quote>(fut6Price), imm, futMonths, calendar,
                    BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);

            imm = IMM.nextDate(imm + 1);
            RateHelper fut7 = new FuturesRateHelper(new Handle<Quote>(fut7Price), imm, futMonths, calendar,
                    BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);

            imm = IMM.nextDate(imm + 1);
            RateHelper fut8 = new FuturesRateHelper(new Handle<Quote>(fut8Price), imm, futMonths, calendar,
                    BusinessDayConvention.ModifiedFollowing, true, depositDayCounter);

            // setup swaps
            Frequency swFixedLegFrequency = Frequency.Annual;
            BusinessDayConvention swFixedLegConvention = BusinessDayConvention.Unadjusted;
            DayCounter swFixedLegDayCounter = new Thirty360(Thirty360.Thirty360Convention.European);

            IborIndex swFloatingLegIndex = new Euribor6M();

            RateHelper s2y = new SwapRateHelper(new Handle<Quote>(s2yRate), new Period(2, TimeUnit.Years),
                calendar, swFixedLegFrequency, swFixedLegConvention, swFixedLegDayCounter, swFloatingLegIndex);
            RateHelper s3y = new SwapRateHelper(new Handle<Quote>(s3yRate), new Period(3, TimeUnit.Years),
                calendar, swFixedLegFrequency, swFixedLegConvention, swFixedLegDayCounter, swFloatingLegIndex);
            RateHelper s5y = new SwapRateHelper(new Handle<Quote>(s5yRate), new Period(5, TimeUnit.Years),
                calendar, swFixedLegFrequency, swFixedLegConvention, swFixedLegDayCounter, swFloatingLegIndex);
            RateHelper s10y = new SwapRateHelper(new Handle<Quote>(s10yRate), new Period(10, TimeUnit.Years),
                calendar, swFixedLegFrequency, swFixedLegConvention, swFixedLegDayCounter, swFloatingLegIndex);
            RateHelper s15y = new SwapRateHelper(new Handle<Quote>(s15yRate), new Period(15, TimeUnit.Years),
                calendar, swFixedLegFrequency, swFixedLegConvention, swFixedLegDayCounter, swFloatingLegIndex);

            /*********************
            **  CURVE BUILDING **
            *********************/

            // Any DayCounter would be fine.
            // ActualActual::ISDA ensures that 30 years is 30.0
            DayCounter termStructureDayCounter = new ActualActual(ActualActual.Convention.ISDA);

            double tolerance = 1.0e-15;

            // A depo-swap curve
            List<RateHelper> depoSwapInstruments = new List<RateHelper>();
            depoSwapInstruments.Add(d1w);
            depoSwapInstruments.Add(d1m);
            depoSwapInstruments.Add(d3m);
            depoSwapInstruments.Add(d6m);
            depoSwapInstruments.Add(d9m);
            depoSwapInstruments.Add(d1y);
            depoSwapInstruments.Add(s2y);
            depoSwapInstruments.Add(s3y);
            depoSwapInstruments.Add(s5y);
            depoSwapInstruments.Add(s10y);
            depoSwapInstruments.Add(s15y);
            YieldTermStructure depoSwapTermStructure = new PiecewiseYieldCurve<Discount,LogLinear>(
                        settlementDate, depoSwapInstruments, termStructureDayCounter, new List<Handle<Quote>>(), new List<Date>(), tolerance);

            // A depo-futures-swap curve
            List<RateHelper> depoFutSwapInstruments = new List<RateHelper>();
            depoFutSwapInstruments.Add(d1w);
            depoFutSwapInstruments.Add(d1m);
            depoFutSwapInstruments.Add(fut1);
            depoFutSwapInstruments.Add(fut2);
            depoFutSwapInstruments.Add(fut3);
            depoFutSwapInstruments.Add(fut4);
            depoFutSwapInstruments.Add(fut5);
            depoFutSwapInstruments.Add(fut6);
            depoFutSwapInstruments.Add(fut7);
            depoFutSwapInstruments.Add(fut8);
            depoFutSwapInstruments.Add(s3y);
            depoFutSwapInstruments.Add(s5y);
            depoFutSwapInstruments.Add(s10y);
            depoFutSwapInstruments.Add(s15y);
            YieldTermStructure depoFutSwapTermStructure = new PiecewiseYieldCurve<Discount,LogLinear>(
                    settlementDate, depoFutSwapInstruments, termStructureDayCounter, new List<Handle<Quote>>(), new List<Date>(), tolerance);

            // A depo-FRA-swap curve
            List<RateHelper> depoFRASwapInstruments = new List<RateHelper>();
            depoFRASwapInstruments.Add(d1w);
            depoFRASwapInstruments.Add(d1m);
            depoFRASwapInstruments.Add(d3m);
            depoFRASwapInstruments.Add(fra3x6);
            depoFRASwapInstruments.Add(fra6x9);
            depoFRASwapInstruments.Add(fra6x12);
            depoFRASwapInstruments.Add(s2y);
            depoFRASwapInstruments.Add(s3y);
            depoFRASwapInstruments.Add(s5y);
            depoFRASwapInstruments.Add(s10y);
            depoFRASwapInstruments.Add(s15y);
            YieldTermStructure depoFRASwapTermStructure = new PiecewiseYieldCurve<Discount,LogLinear>(
                    settlementDate, depoFRASwapInstruments, termStructureDayCounter, new List<Handle<Quote>>(), new List<Date>(), tolerance);

            // Term structures that will be used for pricing:
            // the one used for discounting cash flows
            RelinkableHandle<YieldTermStructure> discountingTermStructure = new RelinkableHandle<YieldTermStructure>();
            // the one used for forward rate forecasting
            RelinkableHandle<YieldTermStructure> forecastingTermStructure = new RelinkableHandle<YieldTermStructure>();

            /*********************
            * SWAPS TO BE PRICED *
            **********************/

            // constant nominal 1,000,000 Euro
            double nominal = 1000000.0;
            // fixed leg
            Frequency fixedLegFrequency = Frequency.Annual;
            BusinessDayConvention fixedLegConvention = BusinessDayConvention.Unadjusted;
            BusinessDayConvention floatingLegConvention = BusinessDayConvention.ModifiedFollowing;
            DayCounter fixedLegDayCounter = new Thirty360(Thirty360.Thirty360Convention.European);
            double fixedRate = 0.04;
            DayCounter floatingLegDayCounter = new Actual360();

            // floating leg
            Frequency floatingLegFrequency = Frequency.Semiannual;
            IborIndex euriborIndex = new Euribor6M(forecastingTermStructure);
            double spread = 0.0;

            int lenghtInYears = 5;
            VanillaSwap.Type swapType = VanillaSwap.Type.Payer;

            Date maturity = settlementDate + new Period(lenghtInYears, TimeUnit.Years);
            Schedule fixedSchedule = new Schedule(settlementDate, maturity, new Period(fixedLegFrequency),
                                     calendar, fixedLegConvention, fixedLegConvention, DateGeneration.Rule.Forward, false);
            Schedule floatSchedule = new Schedule(settlementDate, maturity, new Period(floatingLegFrequency),
                                     calendar, floatingLegConvention, floatingLegConvention, DateGeneration.Rule.Forward, false);
            VanillaSwap spot5YearSwap = new VanillaSwap(swapType, nominal, fixedSchedule, fixedRate, fixedLegDayCounter,
                                        floatSchedule, euriborIndex, spread, floatingLegDayCounter);

            Date fwdStart = calendar.advance(settlementDate, 1, TimeUnit.Years);
            Date fwdMaturity = fwdStart + new Period(lenghtInYears, TimeUnit.Years);
            Schedule fwdFixedSchedule = new Schedule(fwdStart, fwdMaturity, new Period(fixedLegFrequency),
                                        calendar, fixedLegConvention, fixedLegConvention, DateGeneration.Rule.Forward, false);
            Schedule fwdFloatSchedule = new Schedule(fwdStart, fwdMaturity, new Period(floatingLegFrequency),
                                        calendar, floatingLegConvention, floatingLegConvention, DateGeneration.Rule.Forward, false);
            VanillaSwap oneYearForward5YearSwap = new VanillaSwap(swapType, nominal, fwdFixedSchedule, fixedRate, fixedLegDayCounter,
                                        fwdFloatSchedule, euriborIndex, spread, floatingLegDayCounter);

            /***************
            * SWAP PRICING *
            ****************/

            // utilities for reporting
            List<string> headers = new List<string>();
            headers.Add("term structure");
            headers.Add("net present value");
            headers.Add("fair spread");
            headers.Add("fair fixed rate");
            string separator = " | ";
            int width = headers[0].Length + separator.Length
                       + headers[1].Length + separator.Length
                       + headers[2].Length + separator.Length
                       + headers[3].Length + separator.Length - 1;
            string rule = string.Format("").PadLeft(width, '-'), dblrule = string.Format("").PadLeft(width, '=');
            string tab = string.Format("").PadLeft(8, ' ');

            // calculations

            Console.WriteLine(dblrule);
            Console.WriteLine("5-year market swap-rate = {0:0.00%}", s5yRate.value());
            Console.WriteLine(dblrule);

            Console.WriteLine(tab + "5-years swap paying {0:0.00%}", fixedRate);
            Console.WriteLine(headers[0] + separator
                      + headers[1] + separator
                      + headers[2] + separator
                      + headers[3] + separator);
            Console.WriteLine(rule);

            double NPV;
            double fairRate;
            double fairSpread;

            IPricingEngine swapEngine = new DiscountingSwapEngine(discountingTermStructure);

            spot5YearSwap.setPricingEngine(swapEngine);
            oneYearForward5YearSwap.setPricingEngine(swapEngine);

            // Of course, you're not forced to really use different curves
            forecastingTermStructure.linkTo(depoSwapTermStructure);
            discountingTermStructure.linkTo(depoSwapTermStructure);

            NPV = spot5YearSwap.NPV();
            fairSpread = spot5YearSwap.fairSpread();
            fairRate = spot5YearSwap.fairRate();

            Console.Write("{0," + headers[0].Length + ":0.00}" + separator, "depo-swap");
            Console.Write("{0," + headers[1].Length + ":0.00}" + separator, NPV);
            Console.Write("{0," + headers[2].Length + ":0.00%}" + separator, fairSpread);
            Console.WriteLine("{0," + headers[3].Length + ":0.00%}" + separator, fairRate);

            // let's check that the 5 years swap has been correctly re-priced
            if (!(Math.Abs(fairRate-s5yQuote)<1e-8))
                throw new ApplicationException("5-years swap mispriced by " + Math.Abs(fairRate-s5yQuote));

            forecastingTermStructure.linkTo(depoFutSwapTermStructure);
            discountingTermStructure.linkTo(depoFutSwapTermStructure);

            NPV = spot5YearSwap.NPV();
            fairSpread = spot5YearSwap.fairSpread();
            fairRate = spot5YearSwap.fairRate();

            Console.Write("{0," + headers[0].Length + ":0.00}" + separator, "depo-fut-swap");
            Console.Write("{0," + headers[1].Length + ":0.00}" + separator, NPV);
            Console.Write("{0," + headers[2].Length + ":0.00%}" + separator, fairSpread);
            Console.WriteLine("{0," + headers[3].Length + ":0.00%}" + separator, fairRate);

            if (!(Math.Abs(fairRate-s5yQuote)<1e-8))
                throw new ApplicationException("5-years swap mispriced by " + Math.Abs(fairRate-s5yQuote));

            forecastingTermStructure.linkTo(depoFRASwapTermStructure);
            discountingTermStructure.linkTo(depoFRASwapTermStructure);

            NPV = spot5YearSwap.NPV();
            fairSpread = spot5YearSwap.fairSpread();
            fairRate = spot5YearSwap.fairRate();

            Console.Write("{0," + headers[0].Length + ":0.00}" + separator, "depo-FRA-swap");
            Console.Write("{0," + headers[1].Length + ":0.00}" + separator, NPV);
            Console.Write("{0," + headers[2].Length + ":0.00%}" + separator, fairSpread);
            Console.WriteLine("{0," + headers[3].Length + ":0.00%}" + separator, fairRate);

            if (!(Math.Abs(fairRate-s5yQuote)<1e-8))
                throw new ApplicationException("5-years swap mispriced by " + Math.Abs(fairRate-s5yQuote));

            Console.WriteLine(rule);

            // now let's price the 1Y forward 5Y swap
            Console.WriteLine(tab + "5-years, 1-year forward swap paying {0:0.00%}", fixedRate);
            Console.WriteLine(headers[0] + separator
                      + headers[1] + separator
                      + headers[2] + separator
                      + headers[3] + separator);
            Console.WriteLine(rule);

            forecastingTermStructure.linkTo(depoSwapTermStructure);
            discountingTermStructure.linkTo(depoSwapTermStructure);

            NPV = oneYearForward5YearSwap.NPV();
            fairSpread = oneYearForward5YearSwap.fairSpread();
            fairRate = oneYearForward5YearSwap.fairRate();

            Console.Write("{0," + headers[0].Length + ":0.00}" + separator, "depo-swap");
            Console.Write("{0," + headers[1].Length + ":0.00}" + separator, NPV);
            Console.Write("{0," + headers[2].Length + ":0.00%}" + separator, fairSpread);
            Console.WriteLine("{0," + headers[3].Length + ":0.00%}" + separator, fairRate);

            forecastingTermStructure.linkTo(depoFutSwapTermStructure);
            discountingTermStructure.linkTo(depoFutSwapTermStructure);

            NPV = oneYearForward5YearSwap.NPV();
            fairSpread = oneYearForward5YearSwap.fairSpread();
            fairRate = oneYearForward5YearSwap.fairRate();

            Console.Write("{0," + headers[0].Length + ":0.00}" + separator, "depo-fut-swap");
            Console.Write("{0," + headers[1].Length + ":0.00}" + separator, NPV);
            Console.Write("{0," + headers[2].Length + ":0.00%}" + separator, fairSpread);
            Console.WriteLine("{0," + headers[3].Length + ":0.00%}" + separator, fairRate);

            forecastingTermStructure.linkTo(depoFRASwapTermStructure);
            discountingTermStructure.linkTo(depoFRASwapTermStructure);

            NPV = oneYearForward5YearSwap.NPV();
            fairSpread = oneYearForward5YearSwap.fairSpread();
            fairRate = oneYearForward5YearSwap.fairRate();

            Console.Write("{0," + headers[0].Length + ":0.00}" + separator, "depo-FRA-swap");
            Console.Write("{0," + headers[1].Length + ":0.00}" + separator, NPV);
            Console.Write("{0," + headers[2].Length + ":0.00%}" + separator, fairSpread);
            Console.WriteLine("{0," + headers[3].Length + ":0.00%}" + separator, fairRate);

            // now let's say that the 5-years swap rate goes up to 4.60%.
            // A smarter market element--say, connected to a data source-- would
            // notice the change itself. Since we're using SimpleQuotes,
            // we'll have to change the value manually--which forces us to
            // downcast the handle and use the SimpleQuote
            // interface. In any case, the point here is that a change in the
            // value contained in the Quote triggers a new bootstrapping
            // of the curve and a repricing of the swap.

            SimpleQuote fiveYearsRate = s5yRate as SimpleQuote;
            fiveYearsRate.setValue(0.0460);

            Console.WriteLine(dblrule);
            Console.WriteLine("5-year market swap-rate = {0:0.00%}", s5yRate.value());
            Console.WriteLine(dblrule);

            Console.WriteLine(tab + "5-years swap paying {0:0.00%}", fixedRate);
            Console.WriteLine(headers[0] + separator
                      + headers[1] + separator
                      + headers[2] + separator
                      + headers[3] + separator);
            Console.WriteLine(rule);

            // now get the updated results
            forecastingTermStructure.linkTo(depoSwapTermStructure);
            discountingTermStructure.linkTo(depoSwapTermStructure);

            NPV = spot5YearSwap.NPV();
            fairSpread = spot5YearSwap.fairSpread();
            fairRate = spot5YearSwap.fairRate();

            Console.Write("{0," + headers[0].Length + ":0.00}" + separator, "depo-swap");
            Console.Write("{0," + headers[1].Length + ":0.00}" + separator, NPV);
            Console.Write("{0," + headers[2].Length + ":0.00%}" + separator, fairSpread);
            Console.WriteLine("{0," + headers[3].Length + ":0.00%}" + separator, fairRate);

            if (!(Math.Abs(fairRate-s5yRate.value())<1e-8))
                throw new ApplicationException("5-years swap mispriced by " + Math.Abs(fairRate-s5yRate.value()));

            forecastingTermStructure.linkTo(depoFutSwapTermStructure);
            discountingTermStructure.linkTo(depoFutSwapTermStructure);

            NPV = spot5YearSwap.NPV();
            fairSpread = spot5YearSwap.fairSpread();
            fairRate = spot5YearSwap.fairRate();

            Console.Write("{0," + headers[0].Length + ":0.00}" + separator, "depo-fut-swap");
            Console.Write("{0," + headers[1].Length + ":0.00}" + separator, NPV);
            Console.Write("{0," + headers[2].Length + ":0.00%}" + separator, fairSpread);
            Console.WriteLine("{0," + headers[3].Length + ":0.00%}" + separator, fairRate);

            if (!(Math.Abs(fairRate-s5yRate.value())<1e-8))
                throw new ApplicationException("5-years swap mispriced by " + Math.Abs(fairRate-s5yRate.value()));

            forecastingTermStructure.linkTo(depoFRASwapTermStructure);
            discountingTermStructure.linkTo(depoFRASwapTermStructure);

            NPV = spot5YearSwap.NPV();
            fairSpread = spot5YearSwap.fairSpread();
            fairRate = spot5YearSwap.fairRate();

            Console.Write("{0," + headers[0].Length + ":0.00}" + separator, "depo-FRA-swap");
            Console.Write("{0," + headers[1].Length + ":0.00}" + separator, NPV);
            Console.Write("{0," + headers[2].Length + ":0.00%}" + separator, fairSpread);
            Console.WriteLine("{0," + headers[3].Length + ":0.00%}" + separator, fairRate);

            if (!(Math.Abs(fairRate-s5yRate.value())<1e-8))
                throw new ApplicationException("5-years swap mispriced by " + Math.Abs(fairRate-s5yRate.value()));

            Console.WriteLine(rule);

            // the 1Y forward 5Y swap changes as well

            Console.WriteLine(tab + "5-years, 1-year forward swap paying {0:0.00%}", fixedRate);
            Console.WriteLine(headers[0] + separator
                      + headers[1] + separator
                      + headers[2] + separator
                      + headers[3] + separator);
            Console.WriteLine(rule);

            forecastingTermStructure.linkTo(depoSwapTermStructure);
            discountingTermStructure.linkTo(depoSwapTermStructure);

            NPV = oneYearForward5YearSwap.NPV();
            fairSpread = oneYearForward5YearSwap.fairSpread();
            fairRate = oneYearForward5YearSwap.fairRate();

            Console.Write("{0," + headers[0].Length + ":0.00}" + separator, "depo-swap");
            Console.Write("{0," + headers[1].Length + ":0.00}" + separator, NPV);
            Console.Write("{0," + headers[2].Length + ":0.00%}" + separator, fairSpread);
            Console.WriteLine("{0," + headers[3].Length + ":0.00%}" + separator, fairRate);

            forecastingTermStructure.linkTo(depoFutSwapTermStructure);
            discountingTermStructure.linkTo(depoFutSwapTermStructure);

            NPV = oneYearForward5YearSwap.NPV();
            fairSpread = oneYearForward5YearSwap.fairSpread();
            fairRate = oneYearForward5YearSwap.fairRate();

            Console.Write("{0," + headers[0].Length + ":0.00}" + separator, "depo-fut-swap");
            Console.Write("{0," + headers[1].Length + ":0.00}" + separator, NPV);
            Console.Write("{0," + headers[2].Length + ":0.00%}" + separator, fairSpread);
            Console.WriteLine("{0," + headers[3].Length + ":0.00%}" + separator, fairRate);

            forecastingTermStructure.linkTo(depoFRASwapTermStructure);
            discountingTermStructure.linkTo(depoFRASwapTermStructure);

            NPV = oneYearForward5YearSwap.NPV();
            fairSpread = oneYearForward5YearSwap.fairSpread();
            fairRate = oneYearForward5YearSwap.fairRate();

            Console.Write("{0," + headers[0].Length + ":0.00}" + separator, "depo-FRA-swap");
            Console.Write("{0," + headers[1].Length + ":0.00}" + separator, NPV);
            Console.Write("{0," + headers[2].Length + ":0.00%}" + separator, fairSpread);
            Console.WriteLine("{0," + headers[3].Length + ":0.00%}" + separator, fairRate);

            Console.WriteLine(" \nRun completed in {0}", DateTime.Now - timer);

            Console.Write("Press any key to continue ...");
            Console.ReadKey();
        }
Example #22
0
        public double calculateImpl(DateTime calcDate, FP_Parameter fp_parameter)
        {

            List<QLNet.CashFlow> ql_fixedCFList = new List<QLNet.CashFlow>();
            List<QLNet.CashFlow> ql_floatingCFList = new List<QLNet.CashFlow>();

            foreach (FP_CashFlow fixed_cf in this.FixedLegInfo_.FP_CashFlowList_)
                { ql_fixedCFList.Add(fixed_cf.build_ql_cf(fp_parameter)); }

            foreach (FP_CashFlow floating_cf in this.FloatingLegInfo_.FP_CashFlowList_)
                { ql_floatingCFList.Add(floating_cf.build_ql_cf(fp_parameter)); }

            Swap ql_swap = new Swap(ql_fixedCFList, ql_floatingCFList);

            //QLNet.DiscountingBasisSwapEngine

            Handle<YieldTermStructure> ql_discount_ts
                //= new QLNet.Handle<YieldTermStructure>(fp_parameter.DiscountCurveMap_["KRW"]);
                = new QLNet.Handle<YieldTermStructure>(fp_parameter.getDiscountCurve("KRW"));

            QLNet.DiscountingSwapEngine engine = new DiscountingSwapEngine(ql_discount_ts);

            ql_swap.setPricingEngine(engine);

            #region Result Price/Greek

            //clsHITM_FP_GREEKRESULT_TB clstb_greekresult = new clsHITM_FP_GREEKRESULT_TB();

            //clsHDAT_MARKETDATA_TB clstb_market = new clsHDAT_MARKETDATA_TB();

            //clstb_market.REF_DT = calcDate.ToString("yyyyMMdd");

            double swap_price = ql_swap.NPV();

            #region Comment

            //foreach (var item in index_cdList)
            //{
            //    clstb_market.INDEX_CD = item;

            //    clstb_market.SelectOwn();

            //    clstb_greekresult.FP_GREEKRESULT_ID = "";
            //    clstb_greekresult.CALC_DT = calcDate.ToString("yyyyMMdd");
            //    clstb_greekresult.INSTRUMENT_ID = this.SwapDAO_.INSTRUMENT_ID;
            //    clstb_greekresult.INSTRUMENT_TYP = 0;
            //    clstb_greekresult.UNDERLYING_ID = item;
            //    clstb_greekresult.UNDERLYING_VALUE = clstb_market.LAST;
            //    clstb_greekresult.SEQ = count;

            //    clstb_greekresult.DELTA = 0.0;
            //    clstb_greekresult.GAMMA = 0.0;
            //    clstb_greekresult.VEGA = 0.0;

            //    if (count == 1) { clstb_greekresult.CALC_PRICE = swap_price; }
            //    else  { clstb_greekresult.CALC_PRICE = 0.0; }

            //    clstb_greekresult.CALCULATED_FLAG = 1;
            //    clstb_greekresult.CALCULATED_TIME = DateTime.Now.ToString("HHmmss");

            //    clstb_greekresult.CALCULATE_TYP = 1; // 패러럴 쉬푸투 or 그냥 구한거 머 등등..

            //    clstb_greekresult.Insert();

            //    count += 1;
            //}
            #endregion

            #endregion

            for (int i = 0; i < this.FixedLegInfo_.FP_CashFlowList_.Count; i++)
            {
                this.FixedLegInfo_.FP_CashFlowList_[i].CashFlowAmount_ = ql_fixedCFList[i].amount();
                this.FixedLegInfo_.FP_CashFlowList_[i].DiscountFactor_
                    = ql_discount_ts.currentLink().discount(this.FixedLegInfo_.FP_CashFlowList_[i].PaymentDate_);

            }

            for (int j = 0; j < this.FloatingLegInfo_.FP_CashFlowList_.Count; j++)
            {
                this.FloatingLegInfo_.FP_CashFlowList_[j].CashFlowAmount_ = ql_floatingCFList[j].amount();
                this.FloatingLegInfo_.FP_CashFlowList_[j].DiscountFactor_
                    = ql_discount_ts.currentLink().discount(this.FloatingLegInfo_.FP_CashFlowList_[j].PaymentDate_);
            }

            return swap_price;

            //#endregion
        }