public DVPLI.EstimationResult Estimate(List <object> data, DVPLI.IEstimationSettings settings = null, DVPLI.IController controller = null, Dictionary <string, object> properties = null)
        {
            DVPLI.InterestRateMarketData irmd = data[0] as DVPLI.InterestRateMarketData;

            //Date today = new Date(15, Month.February, 2002);
            //Date settlement = new Date(19, Month.February, 2002);
            Settings.setEvaluationDate(irmd.Date);



            Handle <YieldTermStructure> termStructure = new Handle <YieldTermStructure>(new Utilities.ZeroRateFunction(irmd.Date, irmd.ZRMarketDates, irmd.ZRMarket));

            //termStructure.link
            HullWhite model = new HullWhite(termStructure);


            IborIndex index = new Euribor6M(termStructure);

            IPricingEngine engine = new JamshidianSwaptionEngine(model);

            List <CalibrationHelper> swaptions = new List <CalibrationHelper>();

            for (int i = 0; i < irmd.SwapDates.Length; i++)
            {
                for (int j = 0; j < irmd.SwapDuration.Length; j++)
                {
                    Quote             vol    = new SimpleQuote(irmd.SwaptionsVolatility[j, i]);
                    CalibrationHelper helper =
                        new SwaptionHelper(new Period((int)irmd.SwapDates[i], TimeUnit.Years),
                                           new Period((int)irmd.SwapDuration[j], TimeUnit.Years),
                                           new Handle <Quote>(vol),
                                           index,
                                           new Period(1, TimeUnit.Years),
                                           new Thirty360(),
                                           new Actual360(),
                                           termStructure,
                                           false);
                    helper.setPricingEngine(engine);
                    swaptions.Add(helper);
                }
            }

            // Set up the optimization problem
            LevenbergMarquardt optimizationMethod = new LevenbergMarquardt(1.0e-8, 1.0e-8, 1.0e-8);
            EndCriteria        endCriteria        = new EndCriteria(10000, 100, 1e-6, 1e-8, 1e-8);

            //Optimize
            model.calibrate(swaptions, optimizationMethod, endCriteria, new Constraint(), new List <double>());
            EndCriteria.Type ecType = model.endCriteria();


            Vector xMinCalculated = model.parameters();
            double yMinCalculated = model.value(xMinCalculated, swaptions);
            Vector xMinExpected   = new Vector(2);

            double yMinExpected = model.value(xMinExpected, swaptions);

            DVPLI.EstimationResult r = new DVPLI.EstimationResult(new string[] { "Alpha", "Sigma" }, new double[] { xMinCalculated[0], xMinCalculated[1] });
            return(r);
        }
        public void testCachedHullWhite()
        {
            //("Testing Hull-White calibration against cached values...");

            Date today      = new Date(15, Month.February, 2002);
            Date settlement = new Date(19, Month.February, 2002);

            Settings.setEvaluationDate(today);
            Handle <YieldTermStructure> termStructure =
                new Handle <YieldTermStructure>(Utilities.flatRate(settlement, 0.04875825, new Actual365Fixed()));
            //termStructure.link
            HullWhite model = new HullWhite(termStructure);

            CalibrationData[] data = { new CalibrationData(1, 5, 0.1148),
                                       new CalibrationData(2, 4, 0.1108),
                                       new CalibrationData(3, 3, 0.1070),
                                       new CalibrationData(4, 2, 0.1021),
                                       new CalibrationData(5, 1, 0.1000) };
            IborIndex         index = new Euribor6M(termStructure);

            IPricingEngine engine = new JamshidianSwaptionEngine(model);

            List <CalibrationHelper> swaptions = new List <CalibrationHelper>();

            for (int i = 0; i < data.Length; i++)
            {
                Quote             vol    = new SimpleQuote(data[i].volatility);
                CalibrationHelper helper =
                    new SwaptionHelper(new Period(data[i].start, TimeUnit.Years),
                                       new Period(data[i].length, TimeUnit.Years),
                                       new Handle <Quote>(vol),
                                       index,
                                       new Period(1, TimeUnit.Years),
                                       new Thirty360(),
                                       new Actual360(),
                                       termStructure,
                                       false);
                helper.setPricingEngine(engine);
                swaptions.Add(helper);
            }

            // Set up the optimization problem
            // Real simplexLambda = 0.1;
            // Simplex optimizationMethod(simplexLambda);
            LevenbergMarquardt optimizationMethod = new LevenbergMarquardt(1.0e-8, 1.0e-8, 1.0e-8);
            EndCriteria        endCriteria        = new EndCriteria(10000, 100, 1e-6, 1e-8, 1e-8);

            //Optimize
            model.calibrate(swaptions, optimizationMethod, endCriteria, new Constraint(), new List <double>());
            EndCriteria.Type ecType = model.endCriteria();

            // Check and print out results
            #if QL_USE_INDEXED_COUPON
            double cachedA = 0.0488199, cachedSigma = 0.00593579;
            #else
            double cachedA = 0.0488565, cachedSigma = 0.00593662;
            #endif
            double tolerance = 1.120e-5;
            //double tolerance = 1.0e-6;
            Vector xMinCalculated = model.parameters();
            double yMinCalculated = model.value(xMinCalculated, swaptions);
            Vector xMinExpected   = new Vector(2);
            xMinExpected[0] = cachedA;
            xMinExpected[1] = cachedSigma;
            double yMinExpected = model.value(xMinExpected, swaptions);
            if (Math.Abs(xMinCalculated[0] - cachedA) > tolerance ||
                Math.Abs(xMinCalculated[1] - cachedSigma) > tolerance)
            {
                Assert.Fail("Failed to reproduce cached calibration results:\n"
                            + "calculated: a = " + xMinCalculated[0] + ", "
                            + "sigma = " + xMinCalculated[1] + ", "
                            + "f(a) = " + yMinCalculated + ",\n"
                            + "expected:   a = " + xMinExpected[0] + ", "
                            + "sigma = " + xMinExpected[1] + ", "
                            + "f(a) = " + yMinExpected + ",\n"
                            + "difference: a = " + (xMinCalculated[0] - xMinExpected[0]) + ", "
                            + "sigma = " + (xMinCalculated[1] - xMinExpected[1]) + ", "
                            + "f(a) = " + (yMinCalculated - yMinExpected) + ",\n"
                            + "end criteria = " + ecType);
            }
        }
Exemple #3
0
        static void Main(string[] args)
        {
            DateTime timer = DateTime.Now;

            Date     todaysDate     = new Date(15, 2, 2002);
            Calendar calendar       = new TARGET();
            Date     settlementDate = new Date(19, 2, 2002);

            Settings.setEvaluationDate(todaysDate);

            // flat yield term structure impling 1x5 swap at 5%
            Quote flatRate = new SimpleQuote(0.04875825);
            Handle <YieldTermStructure> rhTermStructure = new Handle <YieldTermStructure>(
                new FlatForward(settlementDate, new Handle <Quote>(flatRate),
                                new Actual365Fixed()));

            // Define the ATM/OTM/ITM swaps
            Frequency             fixedLegFrequency     = Frequency.Annual;
            BusinessDayConvention fixedLegConvention    = BusinessDayConvention.Unadjusted;
            BusinessDayConvention floatingLegConvention = BusinessDayConvention.ModifiedFollowing;
            DayCounter            fixedLegDayCounter    = new Thirty360(Thirty360.Thirty360Convention.European);
            Frequency             floatingLegFrequency  = Frequency.Semiannual;

            VanillaSwap.Type type           = VanillaSwap.Type.Payer;
            double           dummyFixedRate = 0.03;
            IborIndex        indexSixMonths = new Euribor6M(rhTermStructure);

            Date startDate = calendar.advance(settlementDate, 1, TimeUnit.Years,
                                              floatingLegConvention);
            Date maturity = calendar.advance(startDate, 5, TimeUnit.Years,
                                             floatingLegConvention);
            Schedule fixedSchedule = new Schedule(startDate, maturity, new Period(fixedLegFrequency),
                                                  calendar, fixedLegConvention, fixedLegConvention,
                                                  DateGeneration.Rule.Forward, false);
            Schedule floatSchedule = new Schedule(startDate, maturity, new Period(floatingLegFrequency),
                                                  calendar, floatingLegConvention, floatingLegConvention,
                                                  DateGeneration.Rule.Forward, false);

            VanillaSwap swap = new VanillaSwap(
                type, 1000.0,
                fixedSchedule, dummyFixedRate, fixedLegDayCounter,
                floatSchedule, indexSixMonths, 0.0,
                indexSixMonths.dayCounter());

            swap.setPricingEngine(new DiscountingSwapEngine(rhTermStructure));
            double fixedAtmRate = swap.fairRate();
            double fixedOtmRate = fixedAtmRate * 1.2;
            double fixedItmRate = fixedAtmRate * 0.8;

            VanillaSwap atmSwap = new VanillaSwap(
                type, 1000.0,
                fixedSchedule, fixedAtmRate, fixedLegDayCounter,
                floatSchedule, indexSixMonths, 0.0,
                indexSixMonths.dayCounter());
            VanillaSwap otmSwap = new VanillaSwap(
                type, 1000.0,
                fixedSchedule, fixedOtmRate, fixedLegDayCounter,
                floatSchedule, indexSixMonths, 0.0,
                indexSixMonths.dayCounter());
            VanillaSwap itmSwap = new VanillaSwap(
                type, 1000.0,
                fixedSchedule, fixedItmRate, fixedLegDayCounter,
                floatSchedule, indexSixMonths, 0.0,
                indexSixMonths.dayCounter());

            // defining the swaptions to be used in model calibration
            List <Period> swaptionMaturities = new List <Period>(5);

            swaptionMaturities.Add(new Period(1, TimeUnit.Years));
            swaptionMaturities.Add(new Period(2, TimeUnit.Years));
            swaptionMaturities.Add(new Period(3, TimeUnit.Years));
            swaptionMaturities.Add(new Period(4, TimeUnit.Years));
            swaptionMaturities.Add(new Period(5, TimeUnit.Years));

            List <CalibrationHelper> swaptions = new List <CalibrationHelper>();

            // List of times that have to be included in the timegrid
            List <double> times = new List <double>();

            for (int i = 0; i < NumRows; i++)
            {
                int   j   = NumCols - i - 1; // 1x5, 2x4, 3x3, 4x2, 5x1
                int   k   = i * NumCols + j;
                Quote vol = new SimpleQuote(SwaptionVols[k]);
                swaptions.Add(new SwaptionHelper(swaptionMaturities[i],
                                                 new Period(SwapLenghts[j], TimeUnit.Years),
                                                 new Handle <Quote>(vol),
                                                 indexSixMonths,
                                                 indexSixMonths.tenor(),
                                                 indexSixMonths.dayCounter(),
                                                 indexSixMonths.dayCounter(),
                                                 rhTermStructure, false));
                swaptions.Last().addTimesTo(times);
            }

            // Building time-grid
            TimeGrid grid = new TimeGrid(times, 30);


            // defining the models
            G2              modelG2  = new G2(rhTermStructure);
            HullWhite       modelHw  = new HullWhite(rhTermStructure);
            HullWhite       modelHw2 = new HullWhite(rhTermStructure);
            BlackKarasinski modelBk  = new BlackKarasinski(rhTermStructure);


            // model calibrations

            Console.WriteLine("G2 (analytic formulae) calibration");
            for (int i = 0; i < swaptions.Count; i++)
            {
                swaptions[i].setPricingEngine(new G2SwaptionEngine(modelG2, 6.0, 16));
            }
            CalibrateModel(modelG2, swaptions);
            Console.WriteLine("calibrated to:\n" +
                              "a     = {0:0.000000}, " +
                              "sigma = {1:0.0000000}\n" +
                              "b     = {2:0.000000}, " +
                              "eta   = {3:0.0000000}\n" +
                              "rho   = {4:0.00000}\n",
                              modelG2.parameters()[0],
                              modelG2.parameters()[1],
                              modelG2.parameters()[2],
                              modelG2.parameters()[3],
                              modelG2.parameters()[4]);

            Console.WriteLine("Hull-White (analytic formulae) calibration");
            for (int i = 0; i < swaptions.Count; i++)
            {
                swaptions[i].setPricingEngine(new JamshidianSwaptionEngine(modelHw));
            }
            CalibrateModel(modelHw, swaptions);
            Console.WriteLine("calibrated to:\n" +
                              "a = {0:0.000000}, " +
                              "sigma = {1:0.0000000}\n",
                              modelHw.parameters()[0],
                              modelHw.parameters()[1]);

            Console.WriteLine("Hull-White (numerical) calibration");
            for (int i = 0; i < swaptions.Count(); i++)
            {
                swaptions[i].setPricingEngine(new TreeSwaptionEngine(modelHw2, grid));
            }
            CalibrateModel(modelHw2, swaptions);
            Console.WriteLine("calibrated to:\n" +
                              "a = {0:0.000000}, " +
                              "sigma = {1:0.0000000}\n",
                              modelHw2.parameters()[0],
                              modelHw2.parameters()[1]);

            Console.WriteLine("Black-Karasinski (numerical) calibration");
            for (int i = 0; i < swaptions.Count; i++)
            {
                swaptions[i].setPricingEngine(new TreeSwaptionEngine(modelBk, grid));
            }
            CalibrateModel(modelBk, swaptions);
            Console.WriteLine("calibrated to:\n" +
                              "a = {0:0.000000}, " +
                              "sigma = {1:0.00000}\n",
                              modelBk.parameters()[0],
                              modelBk.parameters()[1]);


            // ATM Bermudan swaption pricing
            Console.WriteLine("Payer bermudan swaption "
                              + "struck at {0:0.00000 %} (ATM)",
                              fixedAtmRate);

            List <Date>     bermudanDates = new List <Date>();
            List <CashFlow> leg           = swap.fixedLeg();

            for (int i = 0; i < leg.Count; i++)
            {
                Coupon coupon = (Coupon)leg[i];
                bermudanDates.Add(coupon.accrualStartDate());
            }

            Exercise bermudanExercise = new BermudanExercise(bermudanDates);

            Swaption bermudanSwaption = new Swaption(atmSwap, bermudanExercise);

            // Do the pricing for each model

            // G2 price the European swaption here, it should switch to bermudan
            bermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelG2, 50));
            Console.WriteLine("G2:       {0:0.00}", bermudanSwaption.NPV());

            bermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelHw, 50));
            Console.WriteLine("HW:       {0:0.000}", bermudanSwaption.NPV());

            bermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelHw2, 50));
            Console.WriteLine("HW (num): {0:0.000}", bermudanSwaption.NPV());

            bermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelBk, 50));
            Console.WriteLine("BK:       {0:0.000}", bermudanSwaption.NPV());


            // OTM Bermudan swaption pricing
            Console.WriteLine("Payer bermudan swaption "
                              + "struck at {0:0.00000 %} (OTM)",
                              fixedOtmRate);

            Swaption otmBermudanSwaption = new Swaption(otmSwap, bermudanExercise);

            // Do the pricing for each model
            otmBermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelG2, 50));
            Console.WriteLine("G2:       {0:0.0000}", otmBermudanSwaption.NPV());

            otmBermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelHw, 50));
            Console.WriteLine("HW:       {0:0.0000}", otmBermudanSwaption.NPV());

            otmBermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelHw2, 50));
            Console.WriteLine("HW (num): {0:0.000}", otmBermudanSwaption.NPV());

            otmBermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelBk, 50));
            Console.WriteLine("BK:       {0:0.0000}", otmBermudanSwaption.NPV());

            // ITM Bermudan swaption pricing
            Console.WriteLine("Payer bermudan swaption "
                              + "struck at {0:0.00000 %} (ITM)",
                              fixedItmRate);

            Swaption itmBermudanSwaption = new Swaption(itmSwap, bermudanExercise);

            // Do the pricing for each model
            itmBermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelG2, 50));
            Console.WriteLine("G2:       {0:0.000}", itmBermudanSwaption.NPV());

            itmBermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelHw, 50));
            Console.WriteLine("HW:       {0:0.000}", itmBermudanSwaption.NPV());

            itmBermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelHw2, 50));
            Console.WriteLine("HW (num): {0:0.000}", itmBermudanSwaption.NPV());

            itmBermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelBk, 50));
            Console.WriteLine("BK:       {0:0.000}", itmBermudanSwaption.NPV());


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

            Console.Write("Press any key to continue ...");
            Console.ReadKey();
        }