Exemple #1
0
        public void testFairRate()
        {
            Calendar calendar = new TARGET();

            Date settlementDate = new Date(10, Month.Mar, 2010);

            /*********************
             * LOAN TO BE PRICED *
             **********************/

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

            // Principal leg
            Frequency pricipalLegFrequency = Frequency.Annual;

            int lenghtInMonths = 3;

            Loan.Type loanType = Loan.Type.Payer;

            Date     maturity      = settlementDate + new Period(lenghtInMonths, TimeUnit.Years);
            Schedule fixedSchedule = new Schedule(settlementDate, maturity, new Period(fixedLegFrequency),
                                                  calendar, fixedLegConvention, fixedLegConvention, DateGeneration.Rule.Forward, false);
            Schedule principalSchedule = new Schedule(settlementDate, maturity, new Period(pricipalLegFrequency),
                                                      calendar, principalLegConvention, principalLegConvention, DateGeneration.Rule.Forward, false);
            Loan testLoan = new FixedLoan(loanType, nominal, fixedSchedule, fixedRate, fixedLegDayCounter,
                                          principalSchedule, principalLegConvention);
        }
Exemple #2
0
        public void testSingleInstrumentBootstrap()
        {
            //Testing single-instrument curve bootstrap...

            Calendar calendar = new TARGET();

            Date today = Settings.Instance.evaluationDate();

            int settlementDays = 0;

            double quote = 0.005;
            Period tenor = new Period(2, TimeUnit.Years);

            Frequency             frequency  = Frequency.Quarterly;
            BusinessDayConvention convention = BusinessDayConvention.Following;

            DateGeneration.Rule rule       = DateGeneration.Rule.TwentiethIMM;
            DayCounter          dayCounter = new Thirty360();
            double recoveryRate            = 0.4;

            RelinkableHandle <YieldTermStructure> discountCurve = new RelinkableHandle <YieldTermStructure>();

            discountCurve.linkTo(new FlatForward(today, 0.06, new Actual360()));

            List <CdsHelper> helpers = new List <CdsHelper>();

            helpers.Add(
                new SpreadCdsHelper(quote, tenor,
                                    settlementDays, calendar,
                                    frequency, convention, rule,
                                    dayCounter, recoveryRate,
                                    discountCurve));

            PiecewiseDefaultCurve <HazardRate, BackwardFlat> defaultCurve = new PiecewiseDefaultCurve <HazardRate, BackwardFlat>(today, helpers,
                                                                                                                                 dayCounter);

            defaultCurve.recalculate();
        }
Exemple #3
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Thirty360 obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Exemple #4
0
        static void Main(string[] args)
        {
            DateTime timer = DateTime.Now;

            ////////////////  DATES  //////////////////////////////////////////////
            Calendar calendar       = new TARGET();
            Date     todaysDate     = new Date(15, Month.January, 2017);
            Date     settlementDate = new Date(todaysDate);

            Settings.setEvaluationDate(todaysDate);
            DayCounter dayCounter = new Actual365Fixed();


            ////////////////  MARKET  //////////////////////////////////////////////
            double underlying    = 100.0;
            double dividendYield = 0.035;
            double riskFreeRate  = 0.01;
            double intensity     = 0.02;
            double volatility    = 0.20;

            Handle <YieldTermStructure> flatRfTermStructure = new Handle <YieldTermStructure>(new FlatForward(settlementDate, riskFreeRate, dayCounter));
            Handle <DefaultProbabilityTermStructure> flatHazardStructure = new Handle <DefaultProbabilityTermStructure>(new FlatHazardRate(settlementDate, intensity, dayCounter));

            Period     forwardStart         = new Period(1, TimeUnit.Days);
            DayCounter swFixedLegDayCounter = new Thirty360(Thirty360.Thirty360Convention.European);
            IborIndex  swFloatingLegIndex   = new Euribor6M();


            Handle <Quote> underlyingH = new Handle <Quote>(new SimpleQuote(underlying));
            Handle <YieldTermStructure>             flatDividendTS = new Handle <YieldTermStructure>(new FlatForward(settlementDate, dividendYield, dayCounter));
            Handle <BlackVolTermStructure>          flatVolTS      = new Handle <BlackVolTermStructure>(new BlackConstantVol(settlementDate, calendar, volatility, dayCounter));
            GeneralizedBlackScholesProcessTolerance bsmProcess     = new GeneralizedBlackScholesProcessTolerance(underlyingH, flatDividendTS, flatRfTermStructure, flatVolTS);


            Console.WriteLine("Underlying price = " + underlying);
            Console.WriteLine("Risk-free interest rate = {0:0.00%}", riskFreeRate);
            Console.WriteLine("Dividend yield = {0:0.00%}", dividendYield);
            Console.WriteLine("Volatility = {0:0.00%}", volatility);
            Console.Write("\n");

            ////////////////  SIMPLEX  //////////////////////////////////////////////

            /*
             * CostFunction corstFunction = new CostFunction();
             *
             * List<double> X = new InitializedList<double>();
             * X.Add(0.0);
             * Vector vectX = new Vector (X);
             *
             * List<double> Dir = new InitializedList<double>();
             * Dir.Add(1);
             * Vector vectDir = new Vector (Dir);
             *
             * Constraint constraint = new PositiveConstraint();
             * constraint
             * Vector initValues = new Vector();
             *
             * Problem myProb = new Problem(corstFunction, constraint, initValues);
             */

            ////////////////  SURFACE  //////////////////////////////////////////////

            /*
             * freeArbSVI testSurface = new freeArbSVI(strikesVol, timesVol, spotATP, flatTermStructure, flatDividendTS, blackVolMatrix,50);
             *
             * testSurface.matricesBuildingForwardMoneyness();
             * testSurface.matricesBuildingTotalVariance();
             * testSurface.matricesBuildingBSPrices();
             * testSurface.splincalculation();
             * testSurface.matricesBuildingA();
             * testSurface.matricesBuildingB();
             */

            //Console.WriteLine("value [0,0] = {0}", blackVolMatrix[1,1]);



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

            Console.Write("Press any key to continue ...");
            Console.ReadKey();
        }
Exemple #5
0
 public Thirty360(Thirty360.Convention c) : this(NQuantLibcPINVOKE.new_Thirty360__SWIG_0((int)c), true) {
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
 }
Exemple #6
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();
        }
Exemple #7
0
        public void testThirty360_EurobondBasis()
        {
            // Testing thirty/360 day counter (Eurobond Basis)
            // Source: ISDA 2006 Definitions 4.16 (g)
            // 30E/360 (or Eurobond Basis)
            // Based on ICMA (Rule 251) and FBF; this is the version of 30E/360 used by Excel

            DayCounter  dayCounter     = new Thirty360(Thirty360.Thirty360Convention.EurobondBasis);
            List <Date> testStartDates = new List <Date>();
            List <Date> testEndDates   = new List <Date>();
            int         calculated;

            // ISDA - Example 1: End dates do not involve the last day of February
            testStartDates.Add(new Date(20, Month.August, 2006));   testEndDates.Add(new Date(20, Month.February, 2007));
            testStartDates.Add(new Date(20, Month.February, 2007)); testEndDates.Add(new Date(20, Month.August, 2007));
            testStartDates.Add(new Date(20, Month.August, 2007));   testEndDates.Add(new Date(20, Month.February, 2008));
            testStartDates.Add(new Date(20, Month.February, 2008)); testEndDates.Add(new Date(20, Month.August, 2008));
            testStartDates.Add(new Date(20, Month.August, 2008));   testEndDates.Add(new Date(20, Month.February, 2009));
            testStartDates.Add(new Date(20, Month.February, 2009)); testEndDates.Add(new Date(20, Month.August, 2009));

            //// ISDA - Example 2: End dates include some end-February dates
            testStartDates.Add(new Date(28, Month.February, 2006)); testEndDates.Add(new Date(31, Month.August, 2006));
            testStartDates.Add(new Date(31, Month.August, 2006));   testEndDates.Add(new Date(28, Month.February, 2007));
            testStartDates.Add(new Date(28, Month.February, 2007)); testEndDates.Add(new Date(31, Month.August, 2007));
            testStartDates.Add(new Date(31, Month.August, 2007));   testEndDates.Add(new Date(29, Month.February, 2008));
            testStartDates.Add(new Date(29, Month.February, 2008)); testEndDates.Add(new Date(31, Month.August, 2008));
            testStartDates.Add(new Date(31, Month.August, 2008));   testEndDates.Add(new Date(28, Month.Feb, 2009));
            testStartDates.Add(new Date(28, Month.February, 2009)); testEndDates.Add(new Date(31, Month.August, 2009));
            testStartDates.Add(new Date(31, Month.August, 2009));   testEndDates.Add(new Date(28, Month.Feb, 2010));
            testStartDates.Add(new Date(28, Month.February, 2010)); testEndDates.Add(new Date(31, Month.August, 2010));
            testStartDates.Add(new Date(31, Month.August, 2010));   testEndDates.Add(new Date(28, Month.Feb, 2011));
            testStartDates.Add(new Date(28, Month.February, 2011)); testEndDates.Add(new Date(31, Month.August, 2011));
            testStartDates.Add(new Date(31, Month.August, 2011));   testEndDates.Add(new Date(29, Month.Feb, 2012));

            //// ISDA - Example 3: Miscellaneous calculations
            testStartDates.Add(new Date(31, Month.January, 2006));   testEndDates.Add(new Date(28, Month.February, 2006));
            testStartDates.Add(new Date(30, Month.January, 2006));   testEndDates.Add(new Date(28, Month.February, 2006));
            testStartDates.Add(new Date(28, Month.February, 2006));  testEndDates.Add(new Date(3, Month.March, 2006));
            testStartDates.Add(new Date(14, Month.February, 2006));  testEndDates.Add(new Date(28, Month.February, 2006));
            testStartDates.Add(new Date(30, Month.September, 2006)); testEndDates.Add(new Date(31, Month.October, 2006));
            testStartDates.Add(new Date(31, Month.October, 2006));   testEndDates.Add(new Date(28, Month.November, 2006));
            testStartDates.Add(new Date(31, Month.August, 2007));    testEndDates.Add(new Date(28, Month.February, 2008));
            testStartDates.Add(new Date(28, Month.February, 2008));  testEndDates.Add(new Date(28, Month.August, 2008));
            testStartDates.Add(new Date(28, Month.February, 2008));  testEndDates.Add(new Date(30, Month.August, 2008));
            testStartDates.Add(new Date(28, Month.February, 2008));  testEndDates.Add(new Date(31, Month.August, 2008));
            testStartDates.Add(new Date(26, Month.February, 2007));  testEndDates.Add(new Date(28, Month.February, 2008));
            testStartDates.Add(new Date(26, Month.February, 2007));  testEndDates.Add(new Date(29, Month.February, 2008));
            testStartDates.Add(new Date(29, Month.February, 2008));  testEndDates.Add(new Date(28, Month.February, 2009));
            testStartDates.Add(new Date(28, Month.February, 2008));  testEndDates.Add(new Date(30, Month.March, 2008));
            testStartDates.Add(new Date(28, Month.February, 2008));  testEndDates.Add(new Date(31, Month.March, 2008));

            int[] expected = { 180, 180, 180, 180, 180, 180,
                               182, 178, 182, 179, 181, 178,
                               182, 178, 182, 178, 182, 179,
                               28,   28,   5,  14,  30,  28,
                               178, 180, 182, 182, 362, 363,
                               359,  32, 32 };

            for (int i = 0; i < testStartDates.Count; i++)
            {
                calculated = dayCounter.dayCount(testStartDates[i], testEndDates[i]);
                if (calculated != expected[i])
                {
                    QAssert.Fail("from " + testStartDates[i]
                                 + " to " + testEndDates[i] + ":\n"
                                 + "    calculated: " + calculated + "\n"
                                 + "    expected:   " + expected[i]);
                }
            }
        }
Exemple #8
0
        static void Main(string[] args)
        {
            DateTime timer = DateTime.Now;

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

            Calendar calendar = new TARGET();

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

            int fixingDays = 3;
            int settlementDays = 3;

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

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

            // Building of the bonds discounting yield curve

            /*********************
             ***  RATE HELPERS ***
             *********************/

            // RateHelpers are built from the above quotes together with
            // other instrument dependant infos.  Quotes are passed in
            // relinkable handles which could be relinked to some other
            // data source later.

            // Common data

            // ZC rates for the short end
             double zc3mQuote=0.0096;
             double zc6mQuote=0.0145;
             double zc1yQuote=0.0194;

             Quote zc3mRate = new SimpleQuote(zc3mQuote);
             Quote zc6mRate = new SimpleQuote(zc6mQuote);
             Quote zc1yRate = new SimpleQuote(zc1yQuote);

             DayCounter zcBondsDayCounter = new Actual365Fixed();

             RateHelper zc3m = new DepositRateHelper(new Handle<Quote>(zc3mRate),
                                                          new Period(3, TimeUnit.Months), fixingDays,
                                                          calendar, BusinessDayConvention.ModifiedFollowing,
                                                          true, zcBondsDayCounter);
             RateHelper zc6m = new DepositRateHelper(new Handle<Quote>(zc6mRate),
                                                          new Period(6, TimeUnit.Months), fixingDays,
                                                          calendar, BusinessDayConvention.ModifiedFollowing,
                                                          true, zcBondsDayCounter);
             RateHelper zc1y = new DepositRateHelper(new Handle<Quote>(zc1yRate),
                                                          new Period(1, TimeUnit.Years), fixingDays,
                                                          calendar, BusinessDayConvention.ModifiedFollowing,
                                                          true, zcBondsDayCounter);

            // setup bonds
            double redemption = 100.0;

            const int numberOfBonds = 5;

            Date[] issueDates = {
                    new Date (15, Month.March, 2005),
                    new Date (15, Month.June, 2005),
                    new Date (30, Month.June, 2006),
                    new Date (15, Month.November, 2002),
                    new Date (15, Month.May, 1987)
            };

            Date[] maturities = {
                    new Date (31, Month.August, 2010),
                    new Date (31, Month.August, 2011),
                    new Date (31, Month.August, 2013),
                    new Date (15, Month.August, 2018),
                    new Date (15, Month.May, 2038)
            };

            double[] couponRates = {
                    0.02375,
                    0.04625,
                    0.03125,
                    0.04000,
                    0.04500
            };

            double[] marketQuotes = {
                    100.390625,
                    106.21875,
                    100.59375,
                    101.6875,
                    102.140625
            };

            List<SimpleQuote> quote = new List<SimpleQuote>();
            for (int i=0; i<numberOfBonds; i++) {
                SimpleQuote cp = new SimpleQuote(marketQuotes[i]);
                quote.Add(cp);
            }

            List<RelinkableHandle<Quote>> quoteHandle = new InitializedList<RelinkableHandle<Quote>>(numberOfBonds);
            for (int i=0; i<numberOfBonds; i++) {
                quoteHandle[i].linkTo(quote[i]);
            }

            // Definition of the rate helpers
            List<FixedRateBondHelper> bondsHelpers = new List<FixedRateBondHelper>();
            for (int i=0; i<numberOfBonds; i++) {

                Schedule schedule = new Schedule(issueDates[i], maturities[i], new Period(Frequency.Semiannual),
                                                 new UnitedStates(UnitedStates.Market.GovernmentBond),
                                                 BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                                 DateGeneration.Rule.Backward, false);

                FixedRateBondHelper bondHelper = new FixedRateBondHelper(quoteHandle[i],
                                                                         settlementDays,
                                                                         100.0,
                                                                         schedule,
                                                                         new List<double>() { couponRates[i] },
                                                                         new ActualActual(ActualActual.Convention.Bond),
                                                                         BusinessDayConvention.Unadjusted,
                                                                         redemption,
                                                                         issueDates[i]);

                bondsHelpers.Add(bondHelper);
            }

            /*********************
             **  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-bond curve
             List<RateHelper> bondInstruments = new List<RateHelper>();

             // Adding the ZC bonds to the curve for the short end
             bondInstruments.Add(zc3m);
             bondInstruments.Add(zc6m);
             bondInstruments.Add(zc1y);

             // Adding the Fixed rate bonds to the curve for the long end
             for (int i=0; i<numberOfBonds; i++) {
                 bondInstruments.Add(bondsHelpers[i]);
             }

             YieldTermStructure bondDiscountingTermStructure = new PiecewiseYieldCurve<Discount,LogLinear>(
                                                                     settlementDate, bondInstruments,
                                                                     termStructureDayCounter,
                                                                     new List<Handle<Quote>>(),
                                                                     new List<Date>(),
                                                                     tolerance);

             // Building of the Libor forecasting curve
             // deposits
             double d1wQuote=0.043375;
             double d1mQuote=0.031875;
             double d3mQuote=0.0320375;
             double d6mQuote=0.03385;
             double d9mQuote=0.0338125;
             double d1yQuote=0.0335125;
             // swaps
             double s2yQuote=0.0295;
             double s3yQuote=0.0323;
             double s5yQuote=0.0359;
             double s10yQuote=0.0412;
             double s15yQuote=0.0433;

             /********************
              ***    QUOTES    ***
              ********************/

             // SimpleQuote stores a value which can be manually changed;
             // other Quote subclasses could read the value from a database
             // or some kind of data feed.

             // 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);
             // 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 swaps
             Frequency swFixedLegFrequency =Frequency.Annual;
             BusinessDayConvention swFixedLegConvention = BusinessDayConvention.Unadjusted;
             DayCounter swFixedLegDayCounter = new Thirty360(Thirty360.Thirty360Convention.European);
             IborIndex swFloatingLegIndex = new Euribor6M();

             Period forwardStart = new Period(1, TimeUnit.Days);

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

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

             // Any DayCounter would be fine.
             // ActualActual::ISDA ensures that 30 years is 30.0

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

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

             /*********************
              * BONDS TO BE PRICED *
              **********************/

             // Common data
             double faceAmount = 100;

             // Pricing engine
             IPricingEngine bondEngine = new DiscountingBondEngine(discountingTermStructure);

             // Zero coupon bond
             ZeroCouponBond zeroCouponBond = new ZeroCouponBond(
                     settlementDays,
                     new UnitedStates(UnitedStates.Market.GovernmentBond),
                     faceAmount,
                     new Date(15, Month.August,2013),
                     BusinessDayConvention.Following,
                     116.92,
                     new Date(15, Month.August,2003));

             zeroCouponBond.setPricingEngine(bondEngine);

             // Fixed 4.5% US Treasury Note
             Schedule fixedBondSchedule = new Schedule(new Date(15, Month.May, 2007),
                     new Date(15,Month.May,2017), new Period(Frequency.Semiannual),
                     new UnitedStates(UnitedStates.Market.GovernmentBond),
                     BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted, DateGeneration.Rule.Backward, false);

             FixedRateBond fixedRateBond = new FixedRateBond(
                     settlementDays,
                     faceAmount,
                     fixedBondSchedule,
                     new List<double>() { 0.045 },
                     new ActualActual(ActualActual.Convention.Bond),
                     BusinessDayConvention.ModifiedFollowing,
                     100.0, new Date(15, Month.May, 2007));

             fixedRateBond.setPricingEngine(bondEngine);

             // Floating rate bond (3M USD Libor + 0.1%)
             // Should and will be priced on another curve later...

             RelinkableHandle<YieldTermStructure> liborTermStructure = new RelinkableHandle<YieldTermStructure>();
             IborIndex libor3m = new USDLibor(new Period(3, TimeUnit.Months), liborTermStructure);
             libor3m.addFixing(new Date(17, Month.July, 2008),0.0278625);

             Schedule floatingBondSchedule = new Schedule(new Date(21, Month.October, 2005),
                     new Date(21, Month.October, 2010), new Period(Frequency.Quarterly),
                     new UnitedStates(UnitedStates.Market.NYSE),
                     BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted, DateGeneration.Rule.Backward, true);

             FloatingRateBond floatingRateBond = new FloatingRateBond(
                     settlementDays,
                     faceAmount,
                     floatingBondSchedule,
                     libor3m,
                     new Actual360(),
                     BusinessDayConvention.ModifiedFollowing,
                     2,
                     // Gearings
                     new List<double>() { 1.0 },
                     // Spreads
                     new List<double>() { 0.001 },
                     // Caps
                     new List<double>(),
                     // Floors
                     new List<double>(),
                     // Fixing in arrears
                     true,
                     100.0,
                     new Date(21, Month.October, 2005));

             floatingRateBond.setPricingEngine(bondEngine);

             // Coupon pricers
             IborCouponPricer pricer = new BlackIborCouponPricer();

             // optionLet volatilities
             double volatility = 0.0;
             Handle<OptionletVolatilityStructure> vol;
             vol = new Handle<OptionletVolatilityStructure>(
                                new ConstantOptionletVolatility(
                                     settlementDays,
                                     calendar,
                                     BusinessDayConvention.ModifiedFollowing,
                                     volatility,
                                     new Actual365Fixed()));

             pricer.setCapletVolatility(vol);
             Utils.setCouponPricer(floatingRateBond.cashflows(),pricer);

             // Yield curve bootstrapping
             forecastingTermStructure.linkTo(depoSwapTermStructure);
             discountingTermStructure.linkTo(bondDiscountingTermStructure);

             // We are using the depo & swap curve to estimate the future Libor rates
             liborTermStructure.linkTo(depoSwapTermStructure);

             /***************
              * BOND PRICING *
              ****************/

             // write column headings
             int[] widths = { 18, 10, 10, 10 };

            Console.WriteLine("{0,18}{1,10}{2,10}{3,10}", "", "ZC", "Fixed", "Floating");

            string separator = " | ";
            int width = widths[0]
                                 + widths[1]
                                          + widths[2]
                                                   + widths[3];
            string rule = "".PadLeft(width, '-'), dblrule = "".PadLeft(width, '=');
            string tab = "".PadLeft(8, ' ');

            Console.WriteLine(rule);

            Console.WriteLine("Net present value".PadLeft(widths[0]) + "{0,10:n2}{1,10:n2}{2,10:n2}",
                                zeroCouponBond.NPV(),
                                fixedRateBond.NPV(),
                                floatingRateBond.NPV());

            Console.WriteLine("Clean price".PadLeft(widths[0]) + "{0,10:n2}{1,10:n2}{2,10:n2}",
                                zeroCouponBond.cleanPrice(),
                                fixedRateBond.cleanPrice(),
                                floatingRateBond.cleanPrice());

            Console.WriteLine("Dirty price".PadLeft(widths[0]) + "{0,10:n2}{1,10:n2}{2,10:n2}",
                                zeroCouponBond.dirtyPrice(),
                                fixedRateBond.dirtyPrice(),
                                floatingRateBond.dirtyPrice());

            Console.WriteLine("Accrued coupon".PadLeft(widths[0]) + "{0,10:n2}{1,10:n2}{2,10:n2}",
                                zeroCouponBond.accruedAmount(),
                                fixedRateBond.accruedAmount(),
                                floatingRateBond.accruedAmount());

            Console.WriteLine("Previous coupon".PadLeft(widths[0]) + "{0,10:0.00%}{1,10:0.00%}{2,10:0.00%}",
                                "N/A",
                                fixedRateBond.previousCoupon(),
                                floatingRateBond.previousCoupon());

            Console.WriteLine("Next coupon".PadLeft(widths[0]) + "{0,10:0.00%}{1,10:0.00%}{2,10:0.00%}",
                              "N/A",
                              fixedRateBond.nextCoupon(),
                              floatingRateBond.nextCoupon());

            Console.WriteLine("Yield".PadLeft(widths[0]) + "{0,10:0.00%}{1,10:0.00%}{2,10:0.00%}",
                              zeroCouponBond.yield(new Actual360(), Compounding.Compounded, Frequency.Annual),
                              fixedRateBond.yield(new Actual360(), Compounding.Compounded, Frequency.Annual),
                              floatingRateBond.yield(new Actual360(), Compounding.Compounded, Frequency.Annual));

            Console.WriteLine();

            // Other computations
            Console.WriteLine("Sample indirect computations (for the floating rate bond): ");
            Console.WriteLine(rule);

            Console.WriteLine("Yield to Clean Price: {0:n2}",
                floatingRateBond.cleanPrice(floatingRateBond.yield(new Actual360(), Compounding.Compounded, Frequency.Annual),
                                                                   new Actual360(), Compounding.Compounded, Frequency.Annual,
                                                                   settlementDate));

            Console.WriteLine("Clean Price to Yield: {0:0.00%}",
                floatingRateBond.yield(floatingRateBond.cleanPrice(),new Actual360(), Compounding.Compounded, Frequency.Annual,
                                       settlementDate));

            /* "Yield to Price"
               "Price to Yield" */

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

            Console.Write("Press any key to continue ...");
            Console.ReadKey();
        }
Exemple #9
0
        public void testCachedMarketValue()
        {
            // Testing credit-default swap against cached market values...

            using (SavedSettings backup = new SavedSettings())
            {
                Settings.setEvaluationDate(new Date(9, Month.June, 2006));
                Date     evalDate = Settings.evaluationDate();
                Calendar calendar = new UnitedStates();

                List <Date> discountDates = new List <Date>();
                discountDates.Add(evalDate);
                discountDates.Add(calendar.advance(evalDate, 1, TimeUnit.Weeks, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 1, TimeUnit.Months, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 2, TimeUnit.Months, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 3, TimeUnit.Months, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 6, TimeUnit.Months, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 12, TimeUnit.Months, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 2, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 3, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 4, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 5, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 6, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 7, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 8, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 9, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 10, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 15, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));

                List <double> dfs = new List <double>();
                dfs.Add(1.0);
                dfs.Add(0.9990151375768731);
                dfs.Add(0.99570502636871183);
                dfs.Add(0.99118260474528685);
                dfs.Add(0.98661167950906203);
                dfs.Add(0.9732592953359388);
                dfs.Add(0.94724424481038083);
                dfs.Add(0.89844996737120875);
                dfs.Add(0.85216647839921411);
                dfs.Add(0.80775477692556874);
                dfs.Add(0.76517289234200347);
                dfs.Add(0.72401019553182933);
                dfs.Add(0.68503909569219212);
                dfs.Add(0.64797499814013748);
                dfs.Add(0.61263171936255534);
                dfs.Add(0.5791942350748791);
                dfs.Add(0.43518868769953606);

                DayCounter curveDayCounter = new Actual360();

                RelinkableHandle <YieldTermStructure> discountCurve = new RelinkableHandle <YieldTermStructure>();
                discountCurve.linkTo(new InterpolatedDiscountCurve <LogLinear>(discountDates, dfs, curveDayCounter, null, null, null, new LogLinear()));

                DayCounter  dayCounter = new Thirty360();
                List <Date> dates      = new List <Date>();
                dates.Add(evalDate);
                dates.Add(calendar.advance(evalDate, 6, TimeUnit.Months, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 1, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 2, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 3, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 4, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 5, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 7, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 10, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));

                List <double> defaultProbabilities = new List <double>();
                defaultProbabilities.Add(0.0000);
                defaultProbabilities.Add(0.0047);
                defaultProbabilities.Add(0.0093);
                defaultProbabilities.Add(0.0286);
                defaultProbabilities.Add(0.0619);
                defaultProbabilities.Add(0.0953);
                defaultProbabilities.Add(0.1508);
                defaultProbabilities.Add(0.2288);
                defaultProbabilities.Add(0.3666);

                List <double> hazardRates = new List <double>();
                hazardRates.Add(0.0);
                for (int i = 1; i < dates.Count; ++i)
                {
                    double t1 = dayCounter.yearFraction(dates[0], dates[i - 1]);
                    double t2 = dayCounter.yearFraction(dates[0], dates[i]);
                    double S1 = 1.0 - defaultProbabilities[i - 1];
                    double S2 = 1.0 - defaultProbabilities[i];
                    hazardRates.Add(Math.Log(S1 / S2) / (t2 - t1));
                }

                RelinkableHandle <DefaultProbabilityTermStructure> piecewiseFlatHazardRate = new RelinkableHandle <DefaultProbabilityTermStructure>();
                piecewiseFlatHazardRate.linkTo(new InterpolatedHazardRateCurve <BackwardFlat>(dates, hazardRates, new Thirty360()));

                // Testing credit default swap

                // Build the schedule
                Date                  issueDate     = new Date(20, Month.March, 2006);
                Date                  maturity      = new Date(20, Month.June, 2013);
                Frequency             cdsFrequency  = Frequency.Semiannual;
                BusinessDayConvention cdsConvention = BusinessDayConvention.ModifiedFollowing;

                Schedule schedule = new Schedule(issueDate, maturity, new Period(cdsFrequency), calendar,
                                                 cdsConvention, cdsConvention,
                                                 DateGeneration.Rule.Forward, false);

                // Build the CDS
                double     recoveryRate = 0.25;
                double     fixedRate    = 0.0224;
                DayCounter dayCount     = new Actual360();
                double     cdsNotional  = 100.0;

                CreditDefaultSwap cds = new CreditDefaultSwap(Protection.Side.Seller, cdsNotional, fixedRate,
                                                              schedule, cdsConvention, dayCount, true, true);
                cds.setPricingEngine(new MidPointCdsEngine(piecewiseFlatHazardRate, recoveryRate, discountCurve));

                double calculatedNpv      = cds.NPV();
                double calculatedFairRate = cds.fairSpread();

                double npv      = -1.364048777; // from Bloomberg we have 98.15598868 - 100.00;
                double fairRate = 0.0248429452; // from Bloomberg we have 0.0258378;

                double tolerance = 1e-9;

                if (Math.Abs(npv - calculatedNpv) > tolerance)
                {
                    Assert.Fail(
                        "Failed to reproduce the npv for the given credit-default swap\n"
                        + "    computed NPV:  " + calculatedNpv + "\n"
                        + "    Given NPV:     " + npv);
                }

                if (Math.Abs(fairRate - calculatedFairRate) > tolerance)
                {
                    Assert.Fail("Failed to reproduce the fair rate for the given credit-default swap\n"
                                + "    computed fair rate:  " + calculatedFairRate + "\n"
                                + "    Given fair rate:     " + fairRate);
                }
            }
        }
Exemple #10
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Tests yield. </summary>
        ///
        /// <param name="ms">   The milliseconds. </param>
        ///
        /// <returns>   True if the test passes, false if the test fails. </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        public bool testYield(QuantMicroService ms)
        {
            //"Testing consistency of bond price/yield calculation...");

            CommonVars vars = new CommonVars();

            double tolerance      = 1.0e-7;
            int    maxEvaluations = 100;

            int[] issueMonths    = new int[] { -24, -18, -12, -6, 0, 6, 12, 18, 24 };
            int[] lengths        = new int[] { 3, 5, 10, 15, 20 };
            int   settlementDays = 3;

            double[]              coupons           = new double[] { 0.02, 0.05, 0.08 };
            Frequency[]           frequencies       = new Frequency[] { Frequency.Semiannual, Frequency.Annual };
            DayCounter            bondDayCount      = new Thirty360();
            BusinessDayConvention accrualConvention = BusinessDayConvention.Unadjusted;
            BusinessDayConvention paymentConvention = BusinessDayConvention.ModifiedFollowing;
            double redemption = 100.0;

            double[]      yields      = new double[] { 0.03, 0.04, 0.05, 0.06, 0.07 };
            Compounding[] compounding = new Compounding[] { Compounding.Compounded, Compounding.Continuous };

            foreach (var t in issueMonths)
            {
                foreach (var t1 in lengths)
                {
                    foreach (var t2 in coupons)
                    {
                        foreach (var t3 in frequencies)
                        {
                            foreach (var t4 in compounding)
                            {
                                Date dated    = vars.calendar.advance(vars.today, t, TimeUnit.Months);
                                Date issue    = dated;
                                Date maturity = vars.calendar.advance(issue, t1, TimeUnit.Years);

                                Schedule sch = new Schedule(dated, maturity, new Period(t3), vars.calendar,
                                                            accrualConvention, accrualConvention, DateGeneration.Rule.Backward, false);

                                FixedRateBond bond = new FixedRateBond(settlementDays, vars.faceAmount, sch,
                                                                       new List <double>()
                                {
                                    t2
                                }, bondDayCount, paymentConvention, redemption, issue);

                                foreach (var t5 in yields)
                                {
                                    double price      = bond.cleanPrice(t5, bondDayCount, t4, t3);
                                    double calculated = bond.yield(price, bondDayCount, t4, t3, null,
                                                                   tolerance, maxEvaluations);

                                    double price2          = bond.cleanPrice(calculated, bondDayCount, t4, t3);
                                    BondsResponseMessage r = new BondsResponseMessage();
                                    r.message = (Math.Abs(price - price2) / price > tolerance) ?
                                                "yield recalculation failed:" : "";
                                    r.issue       = issue;
                                    r.maturity    = maturity;
                                    r.coupon      = t2;
                                    r.frequency   = (int)t3;
                                    r.yield       = t5;
                                    r.compounding = (t4 == Compounding.Compounded
                                        ? "compounded" : "continuous");
                                    r.price     = price;
                                    r.price2    = price2;
                                    r.calcYield = calculated;

                                    ms.PublishBondResponseMessage(r, "BondResponse");

                                    if (Math.Abs(t5 - calculated) > tolerance)
                                    {
                                        return(Math.Abs(price - price2) / price > tolerance);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(true);
        }
Exemple #11
0
        public void testRegression()
        {
            // Testing fixed-coupon convertible bond in known regression case

            Date today    = new Date(23, Month.December, 2008);
            Date tomorrow = today + 1;

            Settings.Instance.setEvaluationDate(tomorrow);

            Handle <Quote> u = new Handle <Quote>(new SimpleQuote(2.9084382818797443));

            List <Date>   dates    = new InitializedList <Date>(25);
            List <double> forwards = new InitializedList <double>(25);

            dates[0]  = new Date(29, Month.December, 2008);  forwards[0] = 0.0025999342800;
            dates[1]  = new Date(5, Month.January, 2009);   forwards[1] = 0.0025999342800;
            dates[2]  = new Date(29, Month.January, 2009);   forwards[2] = 0.0053123275500;
            dates[3]  = new Date(27, Month.February, 2009);  forwards[3] = 0.0197049598721;
            dates[4]  = new Date(30, Month.March, 2009);     forwards[4] = 0.0220524845296;
            dates[5]  = new Date(29, Month.June, 2009);      forwards[5] = 0.0217076395643;
            dates[6]  = new Date(29, Month.December, 2009);  forwards[6] = 0.0230349627478;
            dates[7]  = new Date(29, Month.December, 2010);  forwards[7] = 0.0087631647476;
            dates[8]  = new Date(29, Month.December, 2011);  forwards[8] = 0.0219084299499;
            dates[9]  = new Date(31, Month.December, 2012);  forwards[9] = 0.0244798766219;
            dates[10] = new Date(30, Month.December, 2013);  forwards[10] = 0.0267885498456;
            dates[11] = new Date(29, Month.December, 2014);  forwards[11] = 0.0266922867562;
            dates[12] = new Date(29, Month.December, 2015);  forwards[12] = 0.0271052126386;
            dates[13] = new Date(29, Month.December, 2016);  forwards[13] = 0.0268829891648;
            dates[14] = new Date(29, Month.December, 2017);  forwards[14] = 0.0264594744498;
            dates[15] = new Date(31, Month.December, 2018);  forwards[15] = 0.0273450367424;
            dates[16] = new Date(30, Month.December, 2019);  forwards[16] = 0.0294852614749;
            dates[17] = new Date(29, Month.December, 2020);  forwards[17] = 0.0285556119719;
            dates[18] = new Date(29, Month.December, 2021);  forwards[18] = 0.0305557764659;
            dates[19] = new Date(29, Month.December, 2022);  forwards[19] = 0.0292244738422;
            dates[20] = new Date(29, Month.December, 2023);  forwards[20] = 0.0263917004194;
            dates[21] = new Date(29, Month.December, 2028);  forwards[21] = 0.0239626970243;
            dates[22] = new Date(29, Month.December, 2033);  forwards[22] = 0.0216417108090;
            dates[23] = new Date(29, Month.December, 2038);  forwards[23] = 0.0228343838422;
            dates[24] = new Date(31, Month.December, 2199);  forwards[24] = 0.0228343838422;

            Handle <YieldTermStructure> r = new Handle <YieldTermStructure>(new InterpolatedForwardCurve <BackwardFlat>(dates, forwards, new Actual360()));

            Handle <BlackVolTermStructure> sigma = new Handle <BlackVolTermStructure>(new BlackConstantVol(tomorrow, new NullCalendar(), 21.685235548092248,
                                                                                                           new Thirty360(Thirty360.Thirty360Convention.BondBasis)));

            BlackProcess process = new BlackProcess(u, r, sigma);

            Handle <Quote> spread = new Handle <Quote>(new SimpleQuote(0.11498700678012874));

            Date     issueDate    = new Date(23, Month.July, 2008);
            Date     maturityDate = new Date(1, Month.August, 2013);
            Calendar calendar     = new UnitedStates();
            Schedule schedule     = new MakeSchedule().from(issueDate)
                                    .to(maturityDate)
                                    .withTenor(new Period(6, TimeUnit.Months))
                                    .withCalendar(calendar)
                                    .withConvention(BusinessDayConvention.Unadjusted).value();
            int                 settlementDays  = 3;
            Exercise            exercise        = new EuropeanExercise(maturityDate);
            double              conversionRatio = 100.0 / 20.3175;
            List <double>       coupons         = new InitializedList <double>(schedule.size() - 1, 0.05);
            DayCounter          dayCounter      = new Thirty360(Thirty360.Thirty360Convention.BondBasis);
            CallabilitySchedule no_callability  = new CallabilitySchedule();
            DividendSchedule    no_dividends    = new DividendSchedule();
            double              redemption      = 100.0;

            ConvertibleFixedCouponBond bond = new ConvertibleFixedCouponBond(exercise, conversionRatio,
                                                                             no_dividends, no_callability,
                                                                             spread, issueDate, settlementDays,
                                                                             coupons, dayCounter,
                                                                             schedule, redemption);

            bond.setPricingEngine(new BinomialConvertibleEngine <CoxRossRubinstein> (process, 600));

            try
            {
                double x = bond.NPV(); // should throw; if not, an INF was not detected.
                QAssert.Fail("INF result was not detected: " + x + " returned");
            }
            catch (Exception)
            {
                // as expected. Do nothing.

                // Note: we're expecting an Error we threw, not just any
                // exception.  If something else is thrown, then there's
                // another problem and the test must fail.
            }
        }
Exemple #12
0
        static void Main(string[] args)
        {
            /*
             * TODO:
             *  FIXES
             *      1. WAC vs Net Coupon (meanings are reversed, names are bad)
             *      2. CashFlows needs to be replaced with Expected CashFlows to get the correct price
             *  NEW IMPLEMENTATION
             *      1. Add delay
             *      2. Add SecType enum PT, PO, IO
             */

            Date referenceDate = new Date(16, 11, 2015);

            Settings.setEvaluationDate(referenceDate);
            int                   settlementDays    = 0;
            Calendar              calendar          = new TARGET();
            int                   origTerm          = 360;
            Frequency             sinkingFrequency  = Frequency.Monthly;
            DayCounter            accrualDayCounter = new Thirty360();
            BusinessDayConvention paymentConvention = BusinessDayConvention.Unadjusted;


            double wac          = 0.03875;
            int    wam          = 357;
            int    wala         = origTerm - wam;
            Date   factorDate   = new Date(1, 12, 2015);
            Date   issueDate    = calendar.advance(factorDate, -wala, TimeUnit.Months, BusinessDayConvention.Unadjusted);
            double factor       = 1.0;
            double currentFace  = 1000000;
            double originalFace = currentFace / factor;
            int    statedDelay  = 30; //54;
            double netCoupon    = 0.030;
            string secType      = "PT";
            Date   settleDate   = referenceDate;

            double yield_be = 0.0270;
            //double price;


            double speed = 0.08;

            IPrepayModel prepaymodel = new ConstantCPR(speed);
            //IPrepayModel prepaymodel = new PSACurve(factorDate, speed);

            MBSFixedRateBond mbs = new MBSFixedRateBond(
                settlementDays,
                calendar,
                currentFace,
                factorDate,
                new Period(wam, TimeUnit.Months),
                new Period(origTerm, TimeUnit.Months),
                sinkingFrequency,
                wac,
                netCoupon,
                accrualDayCounter,
                prepaymodel,
                paymentConvention,
                issueDate);

            YieldTermStructure discountCurve = new FlatForward(referenceDate, yield_be, new Thirty360(), Compounding.Compounded, Frequency.Semiannual);

            DiscountingBondEngine discountingBondEngine = new DiscountingBondEngine(new Handle <YieldTermStructure>(discountCurve));

            mbs.setPricingEngine(discountingBondEngine);

            // display results
            Console.WriteLine("WAC         : {0:F5}", wac);
            Console.WriteLine("WALA        : {0}", wala);
            Console.WriteLine("WAM         : {0}", wam);
            Console.WriteLine("Factor Date : {0}", factorDate.ToShortDateString());
            Console.WriteLine("Factor      : {0:F10}", factor);
            Console.WriteLine("Orig Face   : {0:N}", originalFace);
            Console.WriteLine("Curr Face   : {0:N}", currentFace);
            Console.WriteLine("Stated Delay: {0}", statedDelay);
            Console.WriteLine("Net Coupon  : {0:F3}", netCoupon);
            Console.WriteLine("Sec Type    : {0}", secType);
            Console.WriteLine("Settle Date : {0}", settleDate.ToShortDateString());
            Console.WriteLine("Model Type  : {0}", prepaymodel.GetType().ToString());
            Console.WriteLine("Model Speed : {0:F3}", speed);
            Console.WriteLine("Yield       : {0:F5}", yield_be);

            Console.WriteLine("Clean Price : {0:F6}", mbs.cleanPrice());
            Console.WriteLine("Dirty Price : {0:F6}", mbs.dirtyPrice());
            Console.WriteLine("Accrued     : {0:F6}", mbs.accruedAmount());

            // month, factor, pay date, ending prin, interest, reg principal, prepaid principal, total principal, net flow, cpr, smm, wala, wam, p&i payment, i payment, beg balance, days, discount, pv
            double ebal = currentFace;

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter("output.csv"))
            {
                DayCounter dc      = discountCurve.dayCounter();
                Date       refdate = discountCurve.referenceDate();



                sw.WriteLine("month,factor date,factor,pay date,ending principal,interest,regular principal,prepaid principal,total principal,net flow,cpr,smm,wala,wam,p&i payment,interest payment,beginning balance,days,discount,pv");
                for (int i = 0; i < wam; i++)
                {
                    double upmt = 0;
                    double ppmt = 0;
                    double ipmt = 0;
                    double bbal = ebal;

                    Date paydate = null;

                    for (int j = 0; j <= 2; j++)
                    {
                        int      k  = i * 3 + j;
                        CashFlow cf = mbs.expectedCashflows()[k];
                        if (cf.GetType() == typeof(VoluntaryPrepay))
                        {
                            upmt    = cf.amount();
                            paydate = cf.date();
                        }
                        if (cf.GetType() == typeof(AmortizingPayment))
                        {
                            ppmt = cf.amount();
                        }
                        if (cf.GetType() == typeof(FixedRateCoupon))
                        {
                            ipmt = cf.amount();
                        }
                    }
                    int    days = dc.dayCount(refdate, paydate);
                    double df   = discountCurve.discount(paydate);
                    ebal = bbal - upmt - ppmt;
                    double smm = upmt / (bbal - ppmt);

                    sw.Write("{0},", i + 1);                                                                              //month
                    sw.Write("{0},", calendar.advance(factorDate, i, TimeUnit.Months, BusinessDayConvention.Unadjusted)); //factor date
                    sw.Write("{0:F10},", factor * bbal / currentFace);                                                    //factor
                    sw.Write("{0},", paydate.ToShortDateString());                                                        //pay date
                    sw.Write("{0:F2},", ebal);                                                                            //ending principal
                    sw.Write("{0:F2},", ipmt);                                                                            //interest
                    sw.Write("{0:F2},", ppmt);                                                                            //regular principal
                    sw.Write("{0:F2},", upmt);                                                                            //prepaid principal
                    sw.Write("{0:F2},", ppmt + upmt);                                                                     //total principal
                    sw.Write("{0:F2},", ipmt + ppmt + upmt);                                                              //net flow
                    sw.Write("{0:F4},", 1 - Math.Pow(1 - smm, 12));                                                       //cpr
                    sw.Write("{0:F6},", smm);                                                                             //smm
                    sw.Write("{0},", wala + i);                                                                           //wala
                    sw.Write("{0},", wam - i);                                                                            //wam
                    sw.Write("{0},", i);                                                                                  //p&i payment
                    sw.Write("{0},", i);                                                                                  //interest payment
                    sw.Write("{0:F2},", bbal);                                                                            //beginning balance
                    sw.Write("{0},", days);                                                                               //days
                    sw.Write("{0:F8},", df);                                                                              //discount
                    sw.WriteLine("{0}", df * (ipmt + ppmt + upmt));                                                       //pv
                }
            }
        }
Exemple #13
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();
        }
Exemple #14
0
        static void Main(string[] args)
        {
            try
            {
                Option.Type type       = Option.Type.Put;
                double      underlying = 36.0;
                double      spreadRate = 0.005;

                double dividendYield = 0.02;
                double riskFreeRate  = 0.06;
                double volatility    = 0.2;

                int    settlementDays  = 3;
                int    length          = 5;
                double redemption      = 100.0;
                double conversionRatio = redemption / underlying; // at the money

                // set up dates/schedules
                Calendar calendar = new TARGET();
                Date     today    = calendar.adjust(Date.Today);

                Settings.setEvaluationDate(today);
                Date settlementDate = calendar.advance(today, settlementDays, TimeUnit.Days);
                Date exerciseDate   = calendar.advance(settlementDate, length, TimeUnit.Years);
                Date issueDate      = calendar.advance(exerciseDate, -length, TimeUnit.Years);

                BusinessDayConvention convention = BusinessDayConvention.ModifiedFollowing;

                Frequency frequency = Frequency.Annual;

                Schedule schedule = new Schedule(issueDate, exerciseDate,
                                                 new Period(frequency), calendar, convention, convention,
                                                 DateGeneration.Rule.Backward, false);

                DividendSchedule    dividends   = new DividendSchedule();
                CallabilitySchedule callability = new CallabilitySchedule();

                List <double> coupons      = new InitializedList <double>(1, 0.05);
                DayCounter    bondDayCount = new Thirty360();

                int[] callLength = { 2, 4 }; // Call dates, years 2,4.
                int[] putLength  = { 3 };    // Put dates year 3.

                double[] callPrices = { 101.5, 100.85 };
                double[] putPrices  = { 105.0 };

                // Load call schedules
                for (int i = 0; i < callLength.Length; i++)
                {
                    SoftCallability s = new SoftCallability(
                        new Callability.Price(callPrices[i], Callability.Price.Type.Clean), schedule.date(callLength[i]),
                        1.20);
                    callability.Add(s);
                }

                for (int j = 0; j < putLength.Length; j++)
                {
                    Callability s = new Callability(new Callability.Price(putPrices[j], Callability.Price.Type.Clean),
                                                    Callability.Type.Put, schedule.date(putLength[j]));
                    callability.Add(s);
                }

                // Assume dividends are paid every 6 months .
                for (Date d = today + new Period(6, TimeUnit.Months); d < exerciseDate; d += new Period(6, TimeUnit.Months))
                {
                    Dividend div = new FixedDividend(1.0, d);
                    dividends.Add(div);
                }

                DayCounter dayCounter = new Actual365Fixed();
                double     maturity   = dayCounter.yearFraction(settlementDate, exerciseDate);

                Console.WriteLine("option type = " + type);
                Console.WriteLine("Time to maturity = " + maturity);
                Console.WriteLine("Underlying price = " + underlying);
                Console.WriteLine("Risk-free interest rate = {0:0.0%}", riskFreeRate);
                Console.WriteLine("Dividend yield = {0:0.0%}%", dividendYield);
                Console.WriteLine("Volatility = {0:0.0%}%", volatility);
                Console.WriteLine("");


                // write column headings
                int[]  widths     = { 35, 14, 14 };
                int    totalWidth = widths[0] + widths[1] + widths[2];
                string rule       = new string('-', totalWidth);
                string dblrule    = new string('=', totalWidth);

                Console.WriteLine(dblrule);
                Console.WriteLine("Tsiveriotis-Fernandes method");
                Console.WriteLine(dblrule);
                Console.WriteLine("Tree Type                           European     American        ");
                Console.WriteLine(rule);


                Exercise exercise   = new EuropeanExercise(exerciseDate);
                Exercise amexercise = new AmericanExercise(settlementDate, exerciseDate);

                Handle <Quote> underlyingH = new Handle <Quote>(new SimpleQuote(underlying));
                Handle <YieldTermStructure> flatTermStructure =
                    new Handle <YieldTermStructure>(new FlatForward(settlementDate, riskFreeRate, dayCounter));
                Handle <YieldTermStructure> flatDividendTS =
                    new Handle <YieldTermStructure>(new FlatForward(settlementDate, dividendYield, dayCounter));
                Handle <BlackVolTermStructure> flatVolTS =
                    new Handle <BlackVolTermStructure>(new BlackConstantVol(settlementDate, calendar, volatility,
                                                                            dayCounter));

                BlackScholesMertonProcess stochasticProcess =
                    new BlackScholesMertonProcess(underlyingH, flatDividendTS, flatTermStructure, flatVolTS);

                int timeSteps = 801;

                Handle <Quote> creditSpread = new Handle <Quote>(new SimpleQuote(spreadRate));

                Quote rate = new SimpleQuote(riskFreeRate);

                Handle <YieldTermStructure> discountCurve =
                    new Handle <YieldTermStructure>(new FlatForward(today, new Handle <Quote>(rate), dayCounter));

                IPricingEngine engine = new BinomialConvertibleEngine <JarrowRudd>(stochasticProcess, timeSteps);

                ConvertibleFixedCouponBond europeanBond = new ConvertibleFixedCouponBond(exercise, conversionRatio,
                                                                                         dividends, callability, creditSpread, issueDate, settlementDays, coupons, bondDayCount, schedule,
                                                                                         redemption);

                europeanBond.setPricingEngine(engine);

                ConvertibleFixedCouponBond americanBond = new ConvertibleFixedCouponBond(amexercise, conversionRatio,
                                                                                         dividends, callability, creditSpread, issueDate, settlementDays, coupons, bondDayCount, schedule,
                                                                                         redemption);
                americanBond.setPricingEngine(engine);


                Console.WriteLine("Jarrow-Rudd                         {0:0.000000}   {1:0.000000}", europeanBond.NPV(), americanBond.NPV());

                americanBond.setPricingEngine(new BinomialConvertibleEngine <CoxRossRubinstein>(stochasticProcess, timeSteps));
                europeanBond.setPricingEngine(new BinomialConvertibleEngine <CoxRossRubinstein>(stochasticProcess, timeSteps));

                Console.WriteLine("CoxRossRubinstein                   {0:0.000000}   {1:0.000000}", europeanBond.NPV(), americanBond.NPV());

                americanBond.setPricingEngine(new BinomialConvertibleEngine <AdditiveEQPBinomialTree>(stochasticProcess, timeSteps));
                europeanBond.setPricingEngine(new BinomialConvertibleEngine <AdditiveEQPBinomialTree>(stochasticProcess, timeSteps));

                Console.WriteLine("AdditiveEQPBinomialTree             {0:0.000000}   {1:0.000000}", europeanBond.NPV(), americanBond.NPV());

                americanBond.setPricingEngine(new BinomialConvertibleEngine <Trigeorgis>(stochasticProcess, timeSteps));
                europeanBond.setPricingEngine(new BinomialConvertibleEngine <Trigeorgis>(stochasticProcess, timeSteps));

                Console.WriteLine("Trigeorgis                          {0:0.000000}   {1:0.000000}", europeanBond.NPV(), americanBond.NPV());

                americanBond.setPricingEngine(new BinomialConvertibleEngine <Tian>(stochasticProcess, timeSteps));
                europeanBond.setPricingEngine(new BinomialConvertibleEngine <Tian>(stochasticProcess, timeSteps));

                Console.WriteLine("Tian                                {0:0.000000}   {1:0.000000}", europeanBond.NPV(), americanBond.NPV());

                americanBond.setPricingEngine(new BinomialConvertibleEngine <LeisenReimer>(stochasticProcess, timeSteps));
                europeanBond.setPricingEngine(new BinomialConvertibleEngine <LeisenReimer>(stochasticProcess, timeSteps));

                Console.WriteLine("LeisenReimer                        {0:0.000000}   {1:0.000000}", europeanBond.NPV(), americanBond.NPV());

                americanBond.setPricingEngine(new BinomialConvertibleEngine <Joshi4>(stochasticProcess, timeSteps));
                europeanBond.setPricingEngine(new BinomialConvertibleEngine <Joshi4>(stochasticProcess, timeSteps));

                Console.WriteLine("Joshi4                              {0:0.000000}   {1:0.000000}", europeanBond.NPV(), americanBond.NPV());
                Console.WriteLine("===========================================================================");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.ReadKey();
        }
Exemple #15
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());
        }
Exemple #16
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());
        }
Exemple #17
0
        static void Main(string[] args)
        {
            DateTime timer = DateTime.Now;

            Date repoSettlementDate = new Date(14,Month.February,2000);;
            Date repoDeliveryDate = new Date(15,Month.August,2000);
            double repoRate = 0.05;
            DayCounter repoDayCountConvention = new Actual360();
            int repoSettlementDays = 0;
            Compounding repoCompounding = Compounding.Simple;
            Frequency repoCompoundFreq = Frequency.Annual;

            // assume a ten year bond- this is irrelevant
            Date bondIssueDate = new Date(15,Month.September,1995);
            Date bondDatedDate = new Date(15,Month.September,1995);
            Date bondMaturityDate = new Date(15,Month.September,2005);
            double bondCoupon = 0.08;
            Frequency bondCouponFrequency = Frequency.Semiannual;
            // unknown what calendar fincad is using
            Calendar bondCalendar = new NullCalendar();
            DayCounter bondDayCountConvention = new Thirty360(Thirty360.Thirty360Convention.BondBasis);
            // unknown what fincad is using. this may affect accrued calculation
            int bondSettlementDays = 0;
            BusinessDayConvention bondBusinessDayConvention = BusinessDayConvention.Unadjusted;
            double bondCleanPrice = 89.97693786;
            double bondRedemption = 100.0;
            double faceAmount = 100.0;

            Settings.setEvaluationDate(repoSettlementDate);

            RelinkableHandle<YieldTermStructure> bondCurve = new RelinkableHandle<YieldTermStructure>();
            bondCurve.linkTo(new FlatForward(repoSettlementDate,
                                               .01, // dummy rate
                                               bondDayCountConvention,
                                               Compounding.Compounded,
                                               bondCouponFrequency));

            /*
            boost::shared_ptr<FixedRateBond> bond(
                           new FixedRateBond(faceAmount,
                                             bondIssueDate,
                                             bondDatedDate,
                                             bondMaturityDate,
                                             bondSettlementDays,
                                             std::vector<Rate>(1,bondCoupon),
                                             bondCouponFrequency,
                                             bondCalendar,
                                             bondDayCountConvention,
                                             bondBusinessDayConvention,
                                             bondBusinessDayConvention,
                                             bondRedemption,
                                             bondCurve));
            */

            Schedule bondSchedule = new Schedule(bondDatedDate, bondMaturityDate,
                                  new Period(bondCouponFrequency),
                                  bondCalendar,bondBusinessDayConvention,
                                  bondBusinessDayConvention,
                                  DateGeneration.Rule.Backward,false);
            FixedRateBond bond = new FixedRateBond(bondSettlementDays,
                                             faceAmount,
                                             bondSchedule,
                                             new List<double>() { bondCoupon },
                                             bondDayCountConvention,
                                             bondBusinessDayConvention,
                                             bondRedemption,
                                             bondIssueDate);
            bond.setPricingEngine(new DiscountingBondEngine(bondCurve));

            bondCurve.linkTo(new FlatForward(repoSettlementDate,
                                       bond.yield(bondCleanPrice,
                                                   bondDayCountConvention,
                                                   Compounding.Compounded,
                                                   bondCouponFrequency),
                                       bondDayCountConvention,
                                       Compounding.Compounded,
                                       bondCouponFrequency));

            Position.Type fwdType = Position.Type.Long;
            double dummyStrike = 91.5745;

            RelinkableHandle<YieldTermStructure> repoCurve = new RelinkableHandle<YieldTermStructure>();
            repoCurve.linkTo(new FlatForward(repoSettlementDate,
                                               repoRate,
                                               repoDayCountConvention,
                                               repoCompounding,
                                               repoCompoundFreq));

            FixedRateBondForward bondFwd = new FixedRateBondForward(repoSettlementDate,
                                         repoDeliveryDate,
                                         fwdType,
                                         dummyStrike,
                                         repoSettlementDays,
                                         repoDayCountConvention,
                                         bondCalendar,
                                         bondBusinessDayConvention,
                                         bond,
                                         repoCurve,
                                         repoCurve);

            Console.WriteLine("Underlying bond clean price: " + bond.cleanPrice());
            Console.WriteLine("Underlying bond dirty price: " + bond.dirtyPrice());
            Console.WriteLine("Underlying bond accrued at settlement: "
                 + bond.accruedAmount(repoSettlementDate));
            Console.WriteLine("Underlying bond accrued at delivery:   "
                 + bond.accruedAmount(repoDeliveryDate));
            Console.WriteLine("Underlying bond spot income: "
                 + bondFwd.spotIncome(repoCurve));
            Console.WriteLine("Underlying bond fwd income:  "
                 + bondFwd.spotIncome(repoCurve)/
                    repoCurve.link.discount(repoDeliveryDate));
            Console.WriteLine("Repo strike: " + dummyStrike);
            Console.WriteLine("Repo NPV:    " + bondFwd.NPV());
            Console.WriteLine("Repo clean forward price: "
                 + bondFwd.cleanForwardPrice());
            Console.WriteLine("Repo dirty forward price: "
                 + bondFwd.forwardPrice());
            Console.WriteLine("Repo implied yield: "
                 + bondFwd.impliedYield(bond.dirtyPrice(),
                                         dummyStrike,
                                         repoSettlementDate,
                                         repoCompounding,
                                         repoDayCountConvention));
            Console.WriteLine("Market repo rate:   "
                 + repoCurve.link.zeroRate(repoDeliveryDate,
                                        repoDayCountConvention,
                                        repoCompounding,
                                        repoCompoundFreq));

            Console.WriteLine("\nCompare with example given at \n"
                 + "http://www.fincad.com/support/developerFunc/mathref/BFWD.htm");
            Console.WriteLine("Clean forward price = 88.2408");
            Console.WriteLine("\nIn that example, it is unknown what bond calendar they are\n"
                 + "using, as well as settlement Days. For that reason, I have\n"
                 + "made the simplest possible assumptions here: NullCalendar\n"
                 + "and 0 settlement days.\n");

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

              Console.Write("Press any key to continue ...");
              Console.ReadKey();
        }
Exemple #18
0
        static void Main(string[] args)
        {
            DateTime timer = DateTime.Now;

            Date        repoSettlementDate     = new Date(14, Month.February, 2000);;
            Date        repoDeliveryDate       = new Date(15, Month.August, 2000);
            double      repoRate               = 0.05;
            DayCounter  repoDayCountConvention = new Actual360();
            int         repoSettlementDays     = 0;
            Compounding repoCompounding        = Compounding.Simple;
            Frequency   repoCompoundFreq       = Frequency.Annual;

            // assume a ten year bond- this is irrelevant
            Date      bondIssueDate       = new Date(15, Month.September, 1995);
            Date      bondDatedDate       = new Date(15, Month.September, 1995);
            Date      bondMaturityDate    = new Date(15, Month.September, 2005);
            double    bondCoupon          = 0.08;
            Frequency bondCouponFrequency = Frequency.Semiannual;
            // unknown what calendar fincad is using
            Calendar   bondCalendar           = new NullCalendar();
            DayCounter bondDayCountConvention = new Thirty360(Thirty360.Thirty360Convention.BondBasis);
            // unknown what fincad is using. this may affect accrued calculation
            int bondSettlementDays = 0;
            BusinessDayConvention bondBusinessDayConvention = BusinessDayConvention.Unadjusted;
            double bondCleanPrice = 89.97693786;
            double bondRedemption = 100.0;
            double faceAmount     = 100.0;


            Settings.setEvaluationDate(repoSettlementDate);

            RelinkableHandle <YieldTermStructure> bondCurve = new RelinkableHandle <YieldTermStructure>();

            bondCurve.linkTo(new FlatForward(repoSettlementDate,
                                             .01,                                               // dummy rate
                                             bondDayCountConvention,
                                             Compounding.Compounded,
                                             bondCouponFrequency));

            /*
             * boost::shared_ptr<FixedRateBond> bond(
             *                         new FixedRateBond(faceAmount,
             *                                                               bondIssueDate,
             *                                                               bondDatedDate,
             *                                                               bondMaturityDate,
             *                                                               bondSettlementDays,
             *                                                               std::vector<Rate>(1,bondCoupon),
             *                                                               bondCouponFrequency,
             *                                                               bondCalendar,
             *                                                               bondDayCountConvention,
             *                                                               bondBusinessDayConvention,
             *                                                               bondBusinessDayConvention,
             *                                                               bondRedemption,
             *                                                               bondCurve));
             */

            Schedule bondSchedule = new Schedule(bondDatedDate, bondMaturityDate,
                                                 new Period(bondCouponFrequency),
                                                 bondCalendar, bondBusinessDayConvention,
                                                 bondBusinessDayConvention,
                                                 DateGeneration.Rule.Backward, false);
            FixedRateBond bond = new FixedRateBond(bondSettlementDays,
                                                   faceAmount,
                                                   bondSchedule,
                                                   new List <double>()
            {
                bondCoupon
            },
                                                   bondDayCountConvention,
                                                   bondBusinessDayConvention,
                                                   bondRedemption,
                                                   bondIssueDate);

            bond.setPricingEngine(new DiscountingBondEngine(bondCurve));

            bondCurve.linkTo(new FlatForward(repoSettlementDate,
                                             bond.yield(bondCleanPrice,
                                                        bondDayCountConvention,
                                                        Compounding.Compounded,
                                                        bondCouponFrequency),
                                             bondDayCountConvention,
                                             Compounding.Compounded,
                                             bondCouponFrequency));

            Position.Type fwdType     = Position.Type.Long;
            double        dummyStrike = 91.5745;

            RelinkableHandle <YieldTermStructure> repoCurve = new RelinkableHandle <YieldTermStructure>();

            repoCurve.linkTo(new FlatForward(repoSettlementDate,
                                             repoRate,
                                             repoDayCountConvention,
                                             repoCompounding,
                                             repoCompoundFreq));


            FixedRateBondForward bondFwd = new FixedRateBondForward(repoSettlementDate,
                                                                    repoDeliveryDate,
                                                                    fwdType,
                                                                    dummyStrike,
                                                                    repoSettlementDays,
                                                                    repoDayCountConvention,
                                                                    bondCalendar,
                                                                    bondBusinessDayConvention,
                                                                    bond,
                                                                    repoCurve,
                                                                    repoCurve);


            Console.WriteLine("Underlying bond clean price: " + bond.cleanPrice());
            Console.WriteLine("Underlying bond dirty price: " + bond.dirtyPrice());
            Console.WriteLine("Underlying bond accrued at settlement: "
                              + bond.accruedAmount(repoSettlementDate));
            Console.WriteLine("Underlying bond accrued at delivery:   "
                              + bond.accruedAmount(repoDeliveryDate));
            Console.WriteLine("Underlying bond spot income: "
                              + bondFwd.spotIncome(repoCurve));
            Console.WriteLine("Underlying bond fwd income:  "
                              + bondFwd.spotIncome(repoCurve) /
                              repoCurve.link.discount(repoDeliveryDate));
            Console.WriteLine("Repo strike: " + dummyStrike);
            Console.WriteLine("Repo NPV:    " + bondFwd.NPV());
            Console.WriteLine("Repo clean forward price: "
                              + bondFwd.cleanForwardPrice());
            Console.WriteLine("Repo dirty forward price: "
                              + bondFwd.forwardPrice());
            Console.WriteLine("Repo implied yield: "
                              + bondFwd.impliedYield(bond.dirtyPrice(),
                                                     dummyStrike,
                                                     repoSettlementDate,
                                                     repoCompounding,
                                                     repoDayCountConvention));
            Console.WriteLine("Market repo rate:   "
                              + repoCurve.link.zeroRate(repoDeliveryDate,
                                                        repoDayCountConvention,
                                                        repoCompounding,
                                                        repoCompoundFreq));

            Console.WriteLine("\nCompare with example given at \n"
                              + "http://www.fincad.com/support/developerFunc/mathref/BFWD.htm");
            Console.WriteLine("Clean forward price = 88.2408");
            Console.WriteLine("\nIn that example, it is unknown what bond calendar they are\n"
                              + "using, as well as settlement Days. For that reason, I have\n"
                              + "made the simplest possible assumptions here: NullCalendar\n"
                              + "and 0 settlement days.\n");


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

            Console.Write("Press any key to continue ...");
            Console.ReadKey();
        }
Exemple #19
0
        public void testYield()
        {
            //"Testing consistency of bond price/yield calculation...");

            CommonVars vars = new CommonVars();

            double tolerance      = 1.0e-7;
            int    maxEvaluations = 100;

            int[] issueMonths    = new int[] { -24, -18, -12, -6, 0, 6, 12, 18, 24 };
            int[] lengths        = new int[] { 3, 5, 10, 15, 20 };
            int   settlementDays = 3;

            double[]              coupons           = new double[] { 0.02, 0.05, 0.08 };
            Frequency[]           frequencies       = new Frequency[] { Frequency.Semiannual, Frequency.Annual };
            DayCounter            bondDayCount      = new Thirty360();
            BusinessDayConvention accrualConvention = BusinessDayConvention.Unadjusted;
            BusinessDayConvention paymentConvention = BusinessDayConvention.ModifiedFollowing;
            double redemption = 100.0;

            double[]      yields      = new double[] { 0.03, 0.04, 0.05, 0.06, 0.07 };
            Compounding[] compounding = new Compounding[] { Compounding.Compounded, Compounding.Continuous };

            for (int i = 0; i < issueMonths.Length; i++)
            {
                for (int j = 0; j < lengths.Length; j++)
                {
                    for (int k = 0; k < coupons.Length; k++)
                    {
                        for (int l = 0; l < frequencies.Length; l++)
                        {
                            for (int n = 0; n < compounding.Length; n++)
                            {
                                Date dated    = vars.calendar.advance(vars.today, issueMonths[i], TimeUnit.Months);
                                Date issue    = dated;
                                Date maturity = vars.calendar.advance(issue, lengths[j], TimeUnit.Years);

                                Schedule sch = new Schedule(dated, maturity, new Period(frequencies[l]), vars.calendar,
                                                            accrualConvention, accrualConvention, DateGeneration.Rule.Backward, false);

                                FixedRateBond bond = new FixedRateBond(settlementDays, vars.faceAmount, sch,
                                                                       new List <double>()
                                {
                                    coupons[k]
                                },
                                                                       bondDayCount, paymentConvention,
                                                                       redemption, issue);

                                for (int m = 0; m < yields.Length; m++)
                                {
                                    double price      = bond.cleanPrice(yields[m], bondDayCount, compounding[n], frequencies[l]);
                                    double calculated = bond.yield(price, bondDayCount, compounding[n], frequencies[l], null,
                                                                   tolerance, maxEvaluations);

                                    if (Math.Abs(yields[m] - calculated) > tolerance)
                                    {
                                        // the difference might not matter
                                        double price2 = bond.cleanPrice(calculated, bondDayCount, compounding[n], frequencies[l]);
                                        if (Math.Abs(price - price2) / price > tolerance)
                                        {
                                            Assert.Fail("yield recalculation failed:\n"
                                                        + "    issue:     " + issue + "\n"
                                                        + "    maturity:  " + maturity + "\n"
                                                        + "    coupon:    " + coupons[k] + "\n"
                                                        + "    frequency: " + frequencies[l] + "\n\n"
                                                        + "    yield:  " + yields[m] + " "
                                                        + (compounding[n] == Compounding.Compounded ? "compounded" : "continuous") + "\n"
                                                        + "    price:  " + price + "\n"
                                                        + "    yield': " + calculated + "\n"
                                                        + "    price': " + price2);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #20
0
        static void Main(string[] args)
        {
            double nominal = 575000000;

            Date _marketDate;
            Date _settlementDate;
            Dictionary <string, double> _depositRates;
            Dictionary <string, double> _swapRates;
            List <RateHelper>           _rateHelpers;
            Calendar _calendar   = new TARGET();
            int      _fixingDays = 2;

            _marketDate = new Date(new DateTime(2015, 12, 17));
            Settings.setEvaluationDate(_marketDate);

            _depositRates = new Dictionary <string, double>();
            _depositRates.Add("1M", 0.0045);
            _depositRates.Add("3M", 0.0070);
            _depositRates.Add("6M", 0.0090);

            _swapRates = new Dictionary <string, double>();
            _swapRates.Add("1Y", 0.0080);
            _swapRates.Add("2Y", 0.0109);
            _swapRates.Add("3Y", 0.0134);
            _swapRates.Add("4Y", 0.0153);
            _swapRates.Add("5Y", 0.0169);
            _swapRates.Add("7Y", 0.0193);
            _swapRates.Add("10Y", 0.0218);
            _swapRates.Add("30Y", 0.0262);

            _rateHelpers = new List <RateHelper>();
            foreach (var v in _depositRates)
            {
                SimpleQuote sq = new SimpleQuote(v.Value);
                _rateHelpers.Add(new DepositRateHelper(new Handle <Quote>(sq), new Period(v.Key),
                                                       _fixingDays, _calendar, BusinessDayConvention.ModifiedFollowing, true, new Actual360()));
            }
            foreach (var v in _swapRates)
            {
                SimpleQuote sq = new SimpleQuote(v.Value);
                _rateHelpers.Add(new SwapRateHelper(new Handle <Quote>(sq), new Period(v.Key),
                                                    _calendar, Frequency.Semiannual, BusinessDayConvention.Unadjusted,
                                                    new Thirty360(Thirty360.Thirty360Convention.USA), new Euribor3M()));
            }

            _marketDate     = _calendar.adjust(_marketDate);
            _settlementDate = _calendar.advance(_marketDate, _fixingDays, TimeUnit.Days);

            YieldTermStructure yieldTermStructure = new PiecewiseYieldCurve <Discount, LogLinear>(
                _settlementDate, _rateHelpers, new ActualActual(ActualActual.Convention.ISDA));

            RelinkableHandle <YieldTermStructure> yieldTermStructureHandle = new RelinkableHandle <YieldTermStructure>();


            Frequency             fixedLegFrequency  = Frequency.Semiannual;
            BusinessDayConvention fixedLegConvention = BusinessDayConvention.ModifiedFollowing;
            DayCounter            fixedLegDayCounter = new Thirty360(Thirty360.Thirty360Convention.USA);
            double fixedRate = 0.0144;

            Frequency             floatLegFrequency  = Frequency.Quarterly;
            BusinessDayConvention floatLegConvention = BusinessDayConvention.ModifiedFollowing;
            DayCounter            floatLegDayCounter = new Actual360();
            IborIndex             iborIndex          = new Euribor3M(yieldTermStructureHandle);

            iborIndex.addFixing(new Date(18, Month.Aug, 2015), 0.0033285);
            iborIndex.addFixing(new Date(18, Month.Nov, 2015), 0.0036960);
            double floatSpread = 0.0;

            VanillaSwap.Type swapType = VanillaSwap.Type.Receiver;

            Date     maturity      = new Date(20, Month.Nov, 2018);
            Date     effective     = new Date(20, Month.Nov, 2013);
            Schedule fixedSchedule = new Schedule(effective, maturity, new Period(fixedLegFrequency), _calendar, fixedLegConvention, fixedLegConvention, DateGeneration.Rule.Forward, false);
            Schedule floatSchedule = new Schedule(effective, maturity, new Period(floatLegFrequency), _calendar, floatLegConvention, floatLegConvention, DateGeneration.Rule.Forward, false);

            VanillaSwap vanillaSwap = new VanillaSwap(swapType, nominal, fixedSchedule, fixedRate, fixedLegDayCounter, floatSchedule, iborIndex, floatSpread, floatLegDayCounter);

            InterestRate        interestRate = new InterestRate(fixedRate, fixedLegDayCounter, Compounding.Simple, fixedLegFrequency);
            List <InterestRate> coupons      = new List <InterestRate>();

            for (int i = 0; i < fixedSchedule.Count; i++)
            {
                coupons.Add(interestRate);
            }
            FixedRateBond    fixedBond = new FixedRateBond(_fixingDays, nominal, fixedSchedule, coupons, BusinessDayConvention.ModifiedFollowing);
            FloatingRateBond floatBond = new FloatingRateBond(_fixingDays, nominal, floatSchedule, iborIndex, floatLegDayCounter);

            IPricingEngine bondPricingEngine = new DiscountingBondEngine(yieldTermStructureHandle);

            fixedBond.setPricingEngine(bondPricingEngine);
            floatBond.setPricingEngine(bondPricingEngine);

            IPricingEngine swapPricingEngine = new DiscountingSwapEngine(yieldTermStructureHandle);

            vanillaSwap.setPricingEngine(swapPricingEngine);

            yieldTermStructureHandle.linkTo(yieldTermStructure);

            double swapNPV      = vanillaSwap.NPV();
            double swapFixedNPV = vanillaSwap.fixedLegNPV();
            double swapFloatNPV = vanillaSwap.floatingLegNPV();

            double bondFixedNPV = fixedBond.NPV();
            double bondFloatNPV = floatBond.NPV();

            int    w = (swapType == VanillaSwap.Type.Receiver ? 1 : -1);
            double asBondsMarketValue      = w * (bondFixedNPV - bondFloatNPV);
            double asBondsMarketValueNoAcc = w * (fixedBond.cleanPrice() - floatBond.cleanPrice()) / 100.0 * nominal;
            double asBondsAccruedInterest  = asBondsMarketValue - asBondsMarketValueNoAcc;

            Console.WriteLine("Vanilla Swap Maket Value      : {0:N}", swapNPV);
            Console.WriteLine("As Bonds Market Value         : {0:N}", asBondsMarketValue);
            Console.WriteLine("As Bonds Market Value (no acc): {0:N}", asBondsMarketValueNoAcc);
            Console.WriteLine("As Bonds Accrued Interest     : {0:N}", asBondsAccruedInterest);

            Date   rollDate      = new Date(1, Month.Nov, 2015);
            double bondFixedCash = 0;

            foreach (CashFlow cf in fixedBond.cashflows())
            {
                if (cf.date() > rollDate & cf.date() <= _marketDate)
                {
                    bondFixedCash += cf.amount();
                }
            }
            double bondFloatCash = 0;

            foreach (CashFlow cf in floatBond.cashflows())
            {
                if (cf.date() > rollDate & cf.date() <= _marketDate)
                {
                    bondFloatCash += cf.amount();
                }
            }
            double asBondsCash = w * (bondFixedCash - bondFloatCash);

            Console.WriteLine("As Bonds Settled Cash         : {0:N}", asBondsCash);
        }
Exemple #21
0
        private static void Main()
        {
            DateTime startTime = DateTime.Now;

            var todaysDate = new DateTime(2002, 2, 15);

            Settings.instance().setEvaluationDate(todaysDate);

            Calendar calendar       = new TARGET();
            var      settlementDate = new Date(19, Month.February, 2002);

            // flat yield term structure impling 1x5 swap at 5%
            Quote flatRate        = new SimpleQuote(0.04875825);
            var   myTermStructure = new FlatForward(settlementDate, new QuoteHandle(flatRate), new Actual365Fixed());
            var   rhTermStructure = new RelinkableYieldTermStructureHandle();

            rhTermStructure.linkTo(myTermStructure);

            // Define the ATM/OTM/ITM swaps
            var fixedLegTenor = new Period(1, TimeUnit.Years);
            const BusinessDayConvention fixedLegConvention    = BusinessDayConvention.Unadjusted;
            const BusinessDayConvention floatingLegConvention = BusinessDayConvention.ModifiedFollowing;
            DayCounter   fixedLegDayCounter = new Thirty360(Thirty360.Convention.European);
            var          floatingLegTenor   = new Period(6, TimeUnit.Months);
            const 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);
            var  fixedSchedule = new Schedule(startDate, maturity, fixedLegTenor, calendar, fixedLegConvention, fixedLegConvention, DateGeneration.Rule.Forward, false);
            var  floatSchedule = new Schedule(startDate, maturity, floatingLegTenor, calendar, floatingLegConvention, floatingLegConvention, DateGeneration.Rule.Forward, false);
            var  swap          = new VanillaSwap(VanillaSwap.Type.Payer, 1000.0,
                                                 fixedSchedule, dummyFixedRate, fixedLegDayCounter,
                                                 floatSchedule, indexSixMonths, 0.0, indexSixMonths.dayCounter());
            var swapEngine = new DiscountingSwapEngine(rhTermStructure);

            swap.setPricingEngine(swapEngine);
            double fixedAtmRate = swap.fairRate();
            double fixedOtmRate = fixedAtmRate * 1.2;
            double fixedItmRate = fixedAtmRate * 0.8;

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

            atmSwap.setPricingEngine(swapEngine);
            otmSwap.setPricingEngine(swapEngine);
            itmSwap.setPricingEngine(swapEngine);

            // defining the swaptions to be used in model calibration
            var swaptionMaturities = new PeriodVector
            {
                new Period(1, TimeUnit.Years),
                new Period(2, TimeUnit.Years),
                new Period(3, TimeUnit.Years),
                new Period(4, TimeUnit.Years),
                new Period(5, TimeUnit.Years)
            };

            var swaptions = new CalibrationHelperVector();

            // List of times that have to be included in the timegrid
            var times = new DoubleVector();

            for (int i = 0; i < NUM_ROWS; i++)
            {
                int   j      = NUM_COLS - i - 1; // 1x5, 2x4, 3x3, 4x2, 5x1
                int   k      = i * NUM_COLS + j;
                Quote vol    = new SimpleQuote(SWAPTION_VOLS[k]);
                var   helper = new SwaptionHelper(swaptionMaturities[i], new Period(SWAP_LENGHTS[j], TimeUnit.Years),
                                                  new QuoteHandle(vol),
                                                  indexSixMonths, indexSixMonths.tenor(),
                                                  indexSixMonths.dayCounter(),
                                                  indexSixMonths.dayCounter(),
                                                  rhTermStructure);
                swaptions.Add(helper);
                times.AddRange(helper.times());
            }

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

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

            // model calibrations
            Console.WriteLine("Hull-White (analytic formulae) calibration");
            foreach (CalibrationHelper calibrationHelper in swaptions)
            {
                NQuantLibc.as_black_helper(calibrationHelper).setPricingEngine(new JamshidianSwaptionEngine(modelHw));
            }
            CalibrateModel(modelHw, swaptions, 0.05);

            Console.WriteLine("Hull-White (numerical) calibration");
            foreach (CalibrationHelper calibrationHelper in swaptions)
            {
                NQuantLibc.as_black_helper(calibrationHelper).setPricingEngine(new TreeSwaptionEngine(modelHw2, grid));
            }
            CalibrateModel(modelHw2, swaptions, 0.05);

            Console.WriteLine("Black-Karasinski (numerical) calibration");
            foreach (CalibrationHelper calibrationHelper in swaptions)
            {
                NQuantLibc.as_black_helper(calibrationHelper).setPricingEngine(new TreeSwaptionEngine(modelBk, grid));
            }
            CalibrateModel(modelBk, swaptions, 0.05);

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

            var bermudanDates = new DateVector();
            var schedule      = new Schedule(startDate, maturity,
                                             new Period(3, TimeUnit.Months), calendar,
                                             BusinessDayConvention.Following,
                                             BusinessDayConvention.Following,
                                             DateGeneration.Rule.Forward, false);

            for (uint i = 0; i < schedule.size(); i++)
            {
                bermudanDates.Add(schedule.date(i));
            }
            Exercise bermudaExercise = new BermudanExercise(bermudanDates);

            var bermudanSwaption = new Swaption(atmSwap, bermudaExercise);

            bermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelHw, 50));
            Console.WriteLine("HW: " + bermudanSwaption.NPV());

            bermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelHw2, 50));
            Console.WriteLine("HW (num): " + bermudanSwaption.NPV());

            bermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelBk, 50));
            Console.WriteLine("BK (num): " + bermudanSwaption.NPV());

            DateTime endTime = DateTime.Now;
            TimeSpan delta   = endTime - startTime;

            Console.WriteLine();
            Console.WriteLine("Run completed in {0} s", delta.TotalSeconds);
            Console.WriteLine();
        }
Exemple #22
0
        static void Main(string[] args)
        {
            try
            {
                var timer = new System.Diagnostics.Stopwatch();
                timer.Start();

                #region MARKET DATA

                var calendar = new TARGET();

                var settlementDate = new Date(18, Month.September, 2008);
                // must be a business day
                settlementDate = calendar.adjust(settlementDate);

                int  fixingDays     = 3;
                uint settlementDays = 3;

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

                Console.WriteLine("Today: {0} {1} {2} {3}", todaysDate.weekday(), todaysDate.dayOfMonth(), todaysDate.month(), todaysDate.year());
                Console.WriteLine("Settlement date: {0} {1} {2} {3}", settlementDate.weekday(), settlementDate.dayOfMonth(), settlementDate.month(), settlementDate.year());

                // Building of the bonds discounting yield curve

                #endregion

                #region RATE HELPERS

                // RateHelpers are built from the above quotes together with
                // other instrument dependant infos.  Quotes are passed in
                // relinkable handles which could be relinked to some other
                // data source later.

                // Common data

                // ZC rates for the short end
                double zc3mQuote = 0.0096;
                double zc6mQuote = 0.0145;
                double zc1yQuote = 0.0194;

                var zc3mRate = new SimpleQuote(zc3mQuote);
                var zc6mRate = new SimpleQuote(zc6mQuote);
                var zc1yRate = new SimpleQuote(zc1yQuote);

                var zcBondsDayCounter = new Actual365Fixed();

                var zc3m = new DepositRateHelper(new QuoteHandle(zc3mRate),
                                                 new Period(3, TimeUnit.Months),
                                                 (uint)fixingDays,
                                                 calendar,
                                                 BusinessDayConvention.ModifiedFollowing,
                                                 true,
                                                 zcBondsDayCounter);

                var zc6m = new DepositRateHelper(new QuoteHandle(zc6mRate),
                                                 new Period(6, TimeUnit.Months),
                                                 (uint)fixingDays,
                                                 calendar,
                                                 BusinessDayConvention.ModifiedFollowing,
                                                 true,
                                                 zcBondsDayCounter);

                var zc1y = new DepositRateHelper(new QuoteHandle(zc1yRate),
                                                 new Period(1, TimeUnit.Years),
                                                 (uint)fixingDays,
                                                 calendar,
                                                 BusinessDayConvention.ModifiedFollowing,
                                                 true,
                                                 zcBondsDayCounter);

                // setup bonds
                double redemption = 100.0;

                const uint numberOfBonds = 5;

                var issueDates = new Date[] { new Date(15, Month.March, 2005),
                                              new Date(15, Month.June, 2005),
                                              new Date(30, Month.June, 2006),
                                              new Date(15, Month.November, 2002),
                                              new Date(15, Month.May, 1987) };

                var maturities = new Date[] { new Date(31, Month.August, 2010),
                                              new Date(31, Month.August, 2011),
                                              new Date(31, Month.August, 2013),
                                              new Date(15, Month.August, 2018),
                                              new Date(15, Month.May, 2038) };

                var couponRates = new double[] { 0.02375,
                                                 0.04625,
                                                 0.03125,
                                                 0.04000,
                                                 0.04500 };

                var marketQuotes = new double[] { 100.390625,
                                                  106.21875,
                                                  100.59375,
                                                  101.6875,
                                                  102.140625 };

                var quote = new QuoteVector((int)numberOfBonds);
                for (uint i = 0; i < numberOfBonds; i++)
                {
                    var cp = new SimpleQuote(marketQuotes[i]);
                    quote.Add(cp);
                }

                var quoteHandle = new RelinkableQuoteHandleVector((int)numberOfBonds);
                for (int i = 0; i < (int)numberOfBonds; i++)
                {
                    quoteHandle.Add(new RelinkableQuoteHandle());
                    quoteHandle[i].linkTo(quote[i]);
                }

                // Definition of the rate helpers
                var bondsHelpers = new RateHelperVector((int)numberOfBonds);
                for (int i = 0; i < (int)numberOfBonds; i++)
                {
                    var schedule = new Schedule(issueDates[i],
                                                maturities[i],
                                                new Period(Frequency.Semiannual),
                                                new UnitedStates(UnitedStates.Market.GovernmentBond),
                                                BusinessDayConvention.Unadjusted,
                                                BusinessDayConvention.Unadjusted,
                                                DateGeneration.Rule.Backward,
                                                false);

                    var bondHelper = new FixedRateBondHelper(quoteHandle[i],
                                                             settlementDays,
                                                             100.0,
                                                             schedule,
                                                             new DoubleVector(1)
                    {
                        couponRates[i]
                    },
                                                             new ActualActual(ActualActual.Convention.Bond),
                                                             BusinessDayConvention.Unadjusted,
                                                             redemption,
                                                             issueDates[i]);

                    bondsHelpers.Add(bondHelper);
                }

                #endregion

                #region CURVE BUILDING

                // Any DayCounter would be fine.
                // ActualActual::ISDA ensures that 30 years is 30.0
                var termStructureDayCounter = new ActualActual(ActualActual.Convention.ISDA);
                //double tolerance = 1.0e-15;

                // A depo-bond curve
                var bondInstruments = new RateHelperVector();

                // Adding the ZC bonds to the curve for the short end
                bondInstruments.Add(zc3m);
                bondInstruments.Add(zc6m);
                bondInstruments.Add(zc1y);

                // Adding the Fixed rate bonds to the curve for the long end
                for (int i = 0; i < numberOfBonds; i++)
                {
                    bondInstruments.Add(bondsHelpers[3]);
                }

                var bondDiscountingTermStructure = new PiecewiseFlatForward(settlementDate,
                                                                            bondInstruments,
                                                                            termStructureDayCounter);

                // Building of the Libor forecasting curve
                // deposits
                double d1wQuote = 0.043375;
                double d1mQuote = 0.031875;
                double d3mQuote = 0.0320375;
                double d6mQuote = 0.03385;
                double d9mQuote = 0.0338125;
                double d1yQuote = 0.0335125;
                // swaps
                double s2yQuote  = 0.0295;
                double s3yQuote  = 0.0323;
                double s5yQuote  = 0.0359;
                double s10yQuote = 0.0412;
                double s15yQuote = 0.0433;

                #endregion

                #region 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
                var d1wRate = new SimpleQuote(d1wQuote);
                var d1mRate = new SimpleQuote(d1mQuote);
                var d3mRate = new SimpleQuote(d3mQuote);
                var d6mRate = new SimpleQuote(d6mQuote);
                var d9mRate = new SimpleQuote(d9mQuote);
                var d1yRate = new SimpleQuote(d1yQuote);
                // swaps
                var s2yRate  = new SimpleQuote(s2yQuote);
                var s3yRate  = new SimpleQuote(s3yQuote);
                var s5yRate  = new SimpleQuote(s5yQuote);
                var s10yRate = new SimpleQuote(s10yQuote);
                var s15yRate = new SimpleQuote(s15yQuote);

                #endregion

                #region 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
                var depositDayCounter = new Actual360();

                var d1w = new DepositRateHelper(new QuoteHandle(d1wRate),
                                                new Period(1, TimeUnit.Weeks),
                                                (uint)fixingDays,
                                                calendar,
                                                BusinessDayConvention.ModifiedFollowing,
                                                true,
                                                depositDayCounter);

                var d1m = new DepositRateHelper(new QuoteHandle(d1mRate),
                                                new Period(1, TimeUnit.Months),
                                                (uint)fixingDays,
                                                calendar,
                                                BusinessDayConvention.ModifiedFollowing,
                                                true,
                                                depositDayCounter);

                var d3m = new DepositRateHelper(new QuoteHandle(d3mRate),
                                                new Period(3, TimeUnit.Months),
                                                (uint)fixingDays,
                                                calendar,
                                                BusinessDayConvention.ModifiedFollowing,
                                                true,
                                                depositDayCounter);

                var d6m = new DepositRateHelper(new QuoteHandle(d6mRate),
                                                new Period(6, TimeUnit.Months),
                                                (uint)fixingDays,
                                                calendar,
                                                BusinessDayConvention.ModifiedFollowing,
                                                true,
                                                depositDayCounter);

                var d9m = new DepositRateHelper(new QuoteHandle(d9mRate),
                                                new Period(9, TimeUnit.Months),
                                                (uint)fixingDays,
                                                calendar,
                                                BusinessDayConvention.ModifiedFollowing,
                                                true,
                                                depositDayCounter);

                var d1y = new DepositRateHelper(new QuoteHandle(d1yRate),
                                                new Period(1, TimeUnit.Years),
                                                (uint)fixingDays,
                                                calendar,
                                                BusinessDayConvention.ModifiedFollowing,
                                                true,
                                                depositDayCounter);

                // setup swaps
                var swFixedLegFrequency  = Frequency.Annual;
                var swFixedLegConvention = BusinessDayConvention.Unadjusted;
                var swFixedLegDayCounter = new Thirty360(Thirty360.Convention.European);
                var swFloatingLegIndex   = new Euribor6M();

                var forwardStart = new Period(1, TimeUnit.Days);

                var s2y = new SwapRateHelper(new QuoteHandle(s2yRate),
                                             new Period(2, TimeUnit.Years),
                                             calendar,
                                             swFixedLegFrequency,
                                             swFixedLegConvention,
                                             swFixedLegDayCounter,
                                             swFloatingLegIndex,
                                             new QuoteHandle(),
                                             forwardStart);

                var s3y = new SwapRateHelper(new QuoteHandle(s3yRate),
                                             new Period(3, TimeUnit.Years),
                                             calendar,
                                             swFixedLegFrequency,
                                             swFixedLegConvention,
                                             swFixedLegDayCounter,
                                             swFloatingLegIndex,
                                             new QuoteHandle(),
                                             forwardStart);

                var s5y = new SwapRateHelper(new QuoteHandle(s5yRate),
                                             new Period(5, TimeUnit.Years),
                                             calendar,
                                             swFixedLegFrequency,
                                             swFixedLegConvention,
                                             swFixedLegDayCounter,
                                             swFloatingLegIndex,
                                             new QuoteHandle(),
                                             forwardStart);

                var s10y = new SwapRateHelper(new QuoteHandle(s10yRate),
                                              new Period(10, TimeUnit.Years),
                                              calendar,
                                              swFixedLegFrequency,
                                              swFixedLegConvention,
                                              swFixedLegDayCounter,
                                              swFloatingLegIndex,
                                              new QuoteHandle(),
                                              forwardStart);

                var s15y = new SwapRateHelper(new QuoteHandle(s15yRate),
                                              new Period(15, TimeUnit.Years),
                                              calendar,
                                              swFixedLegFrequency,
                                              swFixedLegConvention,
                                              swFixedLegDayCounter,
                                              swFloatingLegIndex,
                                              new QuoteHandle(),
                                              forwardStart);

                #endregion

                #region CURVE BUILDING

                // Any DayCounter would be fine.
                // ActualActual::ISDA ensures that 30 years is 30.0

                // A depo-swap curve
                var depoSwapInstruments = new RateHelperVector();
                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);

                var depoSwapTermStructure = new PiecewiseFlatForward(settlementDate,
                                                                     depoSwapInstruments,
                                                                     termStructureDayCounter);

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

                #endregion

                #region BONDS TO BE PRICED

                // Common data
                double faceAmount = 100;

                // Pricing engine
                var bondEngine = new DiscountingBondEngine(new YieldTermStructureHandle(bondDiscountingTermStructure));

                // Zero coupon bond
                var zeroCouponBond = new ZeroCouponBond(settlementDays,
                                                        new UnitedStates(UnitedStates.Market.GovernmentBond),
                                                        faceAmount,
                                                        new Date(15, Month.August, 2013),
                                                        BusinessDayConvention.Following,
                                                        116.92,
                                                        new Date(15, Month.August, 2003));

                zeroCouponBond.setPricingEngine(bondEngine);

                // Fixed 4.5% US Treasury Note
                var fixedBondSchedule = new Schedule(new Date(15, Month.May, 2007),
                                                     new Date(15, Month.May, 2017),
                                                     new Period(Frequency.Semiannual),
                                                     new UnitedStates(UnitedStates.Market.GovernmentBond),
                                                     BusinessDayConvention.Unadjusted,
                                                     BusinessDayConvention.Unadjusted,
                                                     DateGeneration.Rule.Backward,
                                                     false);

                var fixedRateBond = new FixedRateBond((int)settlementDays,
                                                      faceAmount,
                                                      fixedBondSchedule,
                                                      new DoubleVector(1)
                {
                    0.045
                },
                                                      new ActualActual(ActualActual.Convention.Bond),
                                                      BusinessDayConvention.ModifiedFollowing,
                                                      100.0,
                                                      new Date(15, Month.May, 2007));

                fixedRateBond.setPricingEngine(bondEngine);

                // Floating rate bond (3M USD Libor + 0.1%)
                // Should and will be priced on another curve later...

                var liborTermStructure = new RelinkableYieldTermStructureHandle();
                var libor3m            = new USDLibor(new Period(3, TimeUnit.Months),
                                                      liborTermStructure);
                libor3m.addFixing(new Date(17, Month.July, 2008), 0.0278625);

                var floatingBondSchedule = new Schedule(new Date(21, Month.October, 2005),
                                                        new Date(21, Month.October, 2010),
                                                        new Period(Frequency.Quarterly),
                                                        new UnitedStates(UnitedStates.Market.NYSE),
                                                        BusinessDayConvention.Unadjusted,
                                                        BusinessDayConvention.Unadjusted,
                                                        DateGeneration.Rule.Backward,
                                                        true);

                var floatingRateBond = new FloatingRateBond(settlementDays,
                                                            faceAmount,
                                                            floatingBondSchedule,
                                                            libor3m,
                                                            new Actual360(),
                                                            BusinessDayConvention.ModifiedFollowing,
                                                            2,
                                                            // Gearings
                                                            new DoubleVector(1)
                {
                    1.0
                },
                                                            // Spreads
                                                            new DoubleVector(1)
                {
                    0.001
                },
                                                            // Caps
                                                            new DoubleVector(),
                                                            // Floors
                                                            new DoubleVector(),
                                                            // Fixing in arrears
                                                            true,
                                                            100.0,
                                                            new Date(21, Month.October, 2005));

                floatingRateBond.setPricingEngine(bondEngine);

                // Coupon pricers
                var pricer = new BlackIborCouponPricer();

                // optionLet volatilities
                double volatility = 0.0;
                var    vol        = new OptionletVolatilityStructureHandle(new ConstantOptionletVolatility(settlementDays,
                                                                                                           calendar,
                                                                                                           BusinessDayConvention.ModifiedFollowing,
                                                                                                           volatility,
                                                                                                           new Actual365Fixed()));

                pricer.setCapletVolatility(vol);
                NQuantLibc.setCouponPricer(floatingRateBond.cashflows(), pricer);

                // Yield curve bootstrapping
                //forecastingTermStructure.linkTo(depoSwapTermStructure);
                discountingTermStructure.linkTo(bondDiscountingTermStructure);

                // We are using the depo & swap curve to estimate the future Libor rates
                liborTermStructure.linkTo(depoSwapTermStructure);

                #endregion

                #region BOND PRICING

                Console.WriteLine();

                // write column headings
                int[] widths = new int[] { 0, 28, 38, 48 };

                Console.CursorLeft = widths[0]; Console.Write("                 ");
                Console.CursorLeft = widths[1]; Console.Write("ZC");
                Console.CursorLeft = widths[2]; Console.Write("Fixed");
                Console.CursorLeft = widths[3]; Console.WriteLine("Floating");

                //string separator = " | ";
                int    width   = widths[3];
                string rule    = new string('-', width);
                string dblrule = new string('=', width);
                string tab     = new string(' ', 8);

                Console.WriteLine(rule);

                Console.CursorLeft = widths[0]; Console.Write("Net present value");
                Console.CursorLeft = widths[1]; Console.Write(zeroCouponBond.NPV().ToString("000.00"));
                Console.CursorLeft = widths[2]; Console.Write(fixedRateBond.NPV().ToString("000.00"));
                Console.CursorLeft = widths[3]; Console.WriteLine(floatingRateBond.NPV().ToString("000.00"));

                Console.CursorLeft = widths[0]; Console.Write("Clean price");
                Console.CursorLeft = widths[1]; Console.Write(zeroCouponBond.cleanPrice().ToString("000.00"));
                Console.CursorLeft = widths[2]; Console.Write(fixedRateBond.cleanPrice().ToString("000.00"));
                Console.CursorLeft = widths[3]; Console.WriteLine(floatingRateBond.cleanPrice().ToString("000.00"));

                Console.CursorLeft = widths[0]; Console.Write("Dirty price");
                Console.CursorLeft = widths[1]; Console.Write(zeroCouponBond.dirtyPrice().ToString("000.00"));
                Console.CursorLeft = widths[2]; Console.Write(fixedRateBond.dirtyPrice().ToString("000.00"));
                Console.CursorLeft = widths[3]; Console.WriteLine(floatingRateBond.dirtyPrice().ToString("000.00"));

                Console.CursorLeft = widths[0]; Console.Write("Accrued coupon");
                Console.CursorLeft = widths[1]; Console.Write(zeroCouponBond.accruedAmount().ToString("000.00"));
                Console.CursorLeft = widths[2]; Console.Write(fixedRateBond.accruedAmount().ToString("000.00"));
                Console.CursorLeft = widths[3]; Console.WriteLine(floatingRateBond.accruedAmount().ToString("000.00"));

                Console.CursorLeft = widths[0]; Console.Write("Previous coupon");
                Console.CursorLeft = widths[1]; Console.Write("N/A");
                Console.CursorLeft = widths[2]; Console.Write(fixedRateBond.previousCouponRate().ToString("000.00"));
                Console.CursorLeft = widths[3]; Console.WriteLine(floatingRateBond.previousCouponRate().ToString("000.00"));

                Console.CursorLeft = widths[0]; Console.Write("Next coupon");
                Console.CursorLeft = widths[1]; Console.Write("N/A");
                Console.CursorLeft = widths[2]; Console.Write(fixedRateBond.nextCouponRate().ToString("000.00"));
                Console.CursorLeft = widths[3]; Console.WriteLine(floatingRateBond.nextCouponRate().ToString("000.00"));

                Console.CursorLeft = widths[0]; Console.Write("Yield");
                Console.CursorLeft = widths[1]; Console.Write(zeroCouponBond.yield(new Actual360(), Compounding.Compounded, Frequency.Annual).ToString("000.00"));
                Console.CursorLeft = widths[2]; Console.Write(fixedRateBond.yield(new Actual360(), Compounding.Compounded, Frequency.Annual).ToString("000.00"));
                Console.CursorLeft = widths[3]; Console.WriteLine(floatingRateBond.yield(new Actual360(), Compounding.Compounded, Frequency.Annual).ToString("000.00"));

                double yield = fixedRateBond.yield(new Actual360(), Compounding.Compounded, Frequency.Annual);
                Console.CursorLeft = widths[2]; Console.Write(BondFunctions.duration(fixedRateBond, new InterestRate(yield, fixedRateBond.dayCounter(), Compounding.Compounded, Frequency.Annual), Duration.Type.Modified));

                Console.WriteLine();

                // Other computations
                Console.WriteLine("Sample indirect computations (for the floating rate bond): ");
                Console.WriteLine(rule);

                Console.WriteLine("Yield to Clean Price: {0}", floatingRateBond.cleanPrice(floatingRateBond.yield(new Actual360(), Compounding.Compounded, Frequency.Annual), new Actual360(), Compounding.Compounded, Frequency.Annual, settlementDate).ToString("000.00"));

                Console.WriteLine("Clean Price to Yield: {0}", floatingRateBond.yield(floatingRateBond.cleanPrice(), new Actual360(), Compounding.Compounded, Frequency.Annual, settlementDate).ToString("000.00"));

                /* "Yield to Price"
                *  "Price to Yield" */

                double milliseconds = timer.ElapsedMilliseconds;
                Console.WriteLine();
                Console.WriteLine("Run completed in " + milliseconds + "ms");

                #endregion
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                Console.Read();
            }
        }
Exemple #23
0
        public VanillaSwap 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 = 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);
        }
Exemple #24
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();
        }
Exemple #25
0
        static void Main(string[] args)
        {
            DateTime startTime = DateTime.Now;

            Date     todaysDate     = new Date(15, Month.February, 2002);
            Calendar calendar       = new TARGET();
            Date     settlementDate = new Date(19, Month.February, 2002);

            Settings.instance().setEvaluationDate(todaysDate);

            // flat yield term structure impling 1x5 swap at 5%
            Quote       flatRate        = new SimpleQuote(0.04875825);
            FlatForward myTermStructure = new FlatForward(
                settlementDate,
                new QuoteHandle(flatRate),
                new Actual365Fixed());
            RelinkableYieldTermStructureHandle rhTermStructure =
                new RelinkableYieldTermStructureHandle();

            rhTermStructure.linkTo(myTermStructure);

            // Define the ATM/OTM/ITM swaps
            Period fixedLegTenor = new Period(1, TimeUnit.Years);
            BusinessDayConvention fixedLegConvention =
                BusinessDayConvention.Unadjusted;
            BusinessDayConvention floatingLegConvention =
                BusinessDayConvention.ModifiedFollowing;
            DayCounter fixedLegDayCounter =
                new Thirty360(Thirty360.Convention.European);
            Period    floatingLegTenor = new Period(6, TimeUnit.Months);
            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,
                                                  fixedLegTenor, calendar, fixedLegConvention, fixedLegConvention,
                                                  DateGeneration.Rule.Forward, false);
            Schedule floatSchedule = new Schedule(startDate, maturity,
                                                  floatingLegTenor, calendar, floatingLegConvention,
                                                  floatingLegConvention, DateGeneration.Rule.Forward, false);
            VanillaSwap swap = new VanillaSwap(
                VanillaSwap.Type.Payer, 1000.0,
                fixedSchedule, dummyFixedRate, fixedLegDayCounter,
                floatSchedule, indexSixMonths, 0.0,
                indexSixMonths.dayCounter());
            DiscountingSwapEngine swapEngine =
                new DiscountingSwapEngine(rhTermStructure);

            swap.setPricingEngine(swapEngine);
            double fixedATMRate = swap.fairRate();
            double fixedOTMRate = fixedATMRate * 1.2;
            double fixedITMRate = fixedATMRate * 0.8;

            VanillaSwap atmSwap = new VanillaSwap(
                VanillaSwap.Type.Payer, 1000.0,
                fixedSchedule, fixedATMRate, fixedLegDayCounter,
                floatSchedule, indexSixMonths, 0.0,
                indexSixMonths.dayCounter());
            VanillaSwap otmSwap = new VanillaSwap(
                VanillaSwap.Type.Payer, 1000.0,
                fixedSchedule, fixedOTMRate, fixedLegDayCounter,
                floatSchedule, indexSixMonths, 0.0,
                indexSixMonths.dayCounter());
            VanillaSwap itmSwap = new VanillaSwap(
                VanillaSwap.Type.Payer, 1000.0,
                fixedSchedule, fixedITMRate, fixedLegDayCounter,
                floatSchedule, indexSixMonths, 0.0,
                indexSixMonths.dayCounter());

            atmSwap.setPricingEngine(swapEngine);
            otmSwap.setPricingEngine(swapEngine);
            itmSwap.setPricingEngine(swapEngine);

            // defining the swaptions to be used in model calibration
            PeriodVector swaptionMaturities = new PeriodVector();

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

            CalibrationHelperVector swaptions = new CalibrationHelperVector();

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

            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]);
                SwaptionHelper helper = new SwaptionHelper(
                    swaptionMaturities[i],
                    new Period(swapLengths[j], TimeUnit.Years),
                    new QuoteHandle(vol),
                    indexSixMonths,
                    indexSixMonths.tenor(),
                    indexSixMonths.dayCounter(),
                    indexSixMonths.dayCounter(),
                    rhTermStructure);
                swaptions.Add(helper);
                times.AddRange(helper.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++)
//              NQuantLibc.as_black_helper(swaptions[i]).setPricingEngine(
//                  new G2SwaptionEngine( modelG2, 6.0, 16 ) );
//
//          calibrateModel( modelG2, swaptions, 0.05);
//          Console.WriteLine( "calibrated to:" );
//          Console.WriteLine( "a     = " + modelG2.parameters()[0] );
//          Console.WriteLine( "sigma = " + modelG2.parameters()[1] );
//          Console.WriteLine( "b     = " + modelG2.parameters()[2] );
//          Console.WriteLine( "eta   = " + modelG2.parameters()[3] );
//          Console.WriteLine( "rho   = " + modelG2.parameters()[4] );

            Console.WriteLine("Hull-White (analytic formulae) calibration");
            for (int i = 0; i < swaptions.Count; i++)
            {
                NQuantLibc.as_black_helper(swaptions[i]).setPricingEngine(
                    new JamshidianSwaptionEngine(modelHW));
            }

            calibrateModel(modelHW, swaptions, 0.05);
//          Console.WriteLine( "calibrated to:" );
//            Console.WriteLine( "a = " + modelHW.parameters()[0] );
//            Console.WriteLine( "sigma = " + modelHW.parameters()[1] );


            Console.WriteLine("Hull-White (numerical) calibration");
            for (int i = 0; i < swaptions.Count; i++)
            {
                NQuantLibc.as_black_helper(swaptions[i]).setPricingEngine(
                    new TreeSwaptionEngine(modelHW2, grid));
            }

            calibrateModel(modelHW2, swaptions, 0.05);
//        std::cout << "calibrated to:\n"
//                  << "a = " << modelHW2->params()[0] << ", "
//                  << "sigma = " << modelHW2->params()[1]
//                  << std::endl << std::endl;


            Console.WriteLine("Black-Karasinski (numerical) calibration");
            for (int i = 0; i < swaptions.Count; i++)
            {
                NQuantLibc.as_black_helper(swaptions[i]).setPricingEngine(
                    new TreeSwaptionEngine(modelBK, grid));
            }

            calibrateModel(modelBK, swaptions, 0.05);
//        std::cout << "calibrated to:\n"
//                  << "a = " << modelBK->params()[0] << ", "
//                  << "sigma = " << modelBK->params()[1]
//                  << std::endl << std::endl;

            // ATM Bermudan swaption pricing

            Console.WriteLine("Payer bermudan swaption struck at {0} (ATM)",
                              fixedATMRate);

            DateVector bermudanDates = new DateVector();
            Schedule   schedule      = new Schedule(startDate, maturity,
                                                    new Period(3, TimeUnit.Months), calendar,
                                                    BusinessDayConvention.Following,
                                                    BusinessDayConvention.Following,
                                                    DateGeneration.Rule.Forward, false);

            for (uint i = 0; i < schedule.size(); i++)
            {
                bermudanDates.Add(schedule.date(i));
            }
            Exercise bermudaExercise = new BermudanExercise(bermudanDates);

            Swaption bermudanSwaption =
                new Swaption(atmSwap, bermudaExercise);

            bermudanSwaption.setPricingEngine(
                new TreeSwaptionEngine(modelHW, 50));
            Console.WriteLine("HW: " + bermudanSwaption.NPV());

            bermudanSwaption.setPricingEngine(
                new TreeSwaptionEngine(modelHW2, 50));
            Console.WriteLine("HW (num): " + bermudanSwaption.NPV());

            bermudanSwaption.setPricingEngine(
                new TreeSwaptionEngine(modelBK, 50));
            Console.WriteLine("BK (num): " + bermudanSwaption.NPV());

            DateTime endTime = DateTime.Now;
            TimeSpan delta   = endTime - startTime;

            Console.WriteLine();
            Console.WriteLine("Run completed in {0} s", delta.TotalSeconds);
            Console.WriteLine();
        }
Exemple #26
0
        void testBootstrapFromSpread <T, I>()
            where T : ITraits <DefaultProbabilityTermStructure>, new()
            where I : class, IInterpolationFactory, new()
        {
            Calendar calendar = new TARGET();

            Date today = Settings.Instance.evaluationDate();

            int settlementDays = 1;

            List <double> quote = new List <double>();

            quote.Add(0.005);
            quote.Add(0.006);
            quote.Add(0.007);
            quote.Add(0.009);

            List <int> n = new List <int>();

            n.Add(1);
            n.Add(2);
            n.Add(3);
            n.Add(5);

            Frequency             frequency  = Frequency.Quarterly;
            BusinessDayConvention convention = BusinessDayConvention.Following;

            DateGeneration.Rule rule       = DateGeneration.Rule.TwentiethIMM;
            DayCounter          dayCounter = new Thirty360();
            double recoveryRate            = 0.4;

            RelinkableHandle <YieldTermStructure> discountCurve = new RelinkableHandle <YieldTermStructure>();

            discountCurve.linkTo(new FlatForward(today, 0.06, new Actual360()));

            List <CdsHelper> helpers = new List <CdsHelper>();

            for (int i = 0; i < n.Count; i++)
            {
                helpers.Add(
                    new SpreadCdsHelper(quote[i], new Period(n[i], TimeUnit.Years),
                                        settlementDays, calendar,
                                        frequency, convention, rule,
                                        dayCounter, recoveryRate,
                                        discountCurve));
            }

            RelinkableHandle <DefaultProbabilityTermStructure> piecewiseCurve = new RelinkableHandle <DefaultProbabilityTermStructure>();

            piecewiseCurve.linkTo(
                new PiecewiseDefaultCurve <T, I>(today, helpers,
                                                 new Thirty360()));

            double notional  = 1.0;
            double tolerance = 1.0e-6;

            // ensure apple-to-apple comparison
            SavedSettings backup = new SavedSettings();

            Settings.Instance.includeTodaysCashFlows = true;

            for (int i = 0; i < n.Count; i++)
            {
                Date protectionStart = today + settlementDays;
                Date startDate       = calendar.adjust(protectionStart, convention);
                Date endDate         = today + new Period(n[i], TimeUnit.Years);

                Schedule schedule = new Schedule(startDate, endDate, new Period(frequency), calendar,
                                                 convention, BusinessDayConvention.Unadjusted, rule, false);

                CreditDefaultSwap cds = new CreditDefaultSwap(CreditDefaultSwap.Protection.Side.Buyer, notional, quote[i],
                                                              schedule, convention, dayCounter,
                                                              true, true, protectionStart);
                cds.setPricingEngine(new MidPointCdsEngine(piecewiseCurve, recoveryRate,
                                                           discountCurve));

                // test
                double inputRate    = quote[i];
                double computedRate = cds.fairSpread();
                if (Math.Abs(inputRate - computedRate) > tolerance)
                {
                    QAssert.Fail(
                        "\nFailed to reproduce fair spread for " + n[i] +
                        "Y credit-default swaps\n"
                        + "    computed rate: " + computedRate.ToString() + "\n"
                        + "    input rate:    " + inputRate.ToString());
                }
            }
        }
Exemple #27
0
        public void testThirty360_BondBasis()
        {
            // Testing thirty/360 day counter (Bond Basis)
            // http://www.isda.org/c_and_a/docs/30-360-2006ISDADefs.xls
            // Source: 2006 ISDA Definitions, Sec. 4.16 (f)
            // 30/360 (or Bond Basis)

            DayCounter  dayCounter     = new Thirty360(Thirty360.Thirty360Convention.BondBasis);
            List <Date> testStartDates = new List <Date>();
            List <Date> testEndDates   = new List <Date>();
            int         calculated;

            // ISDA - Example 1: End dates do not involve the last day of February
            testStartDates.Add(new Date(20, Month.August, 2006));   testEndDates.Add(new Date(20, Month.February, 2007));
            testStartDates.Add(new Date(20, Month.February, 2007)); testEndDates.Add(new Date(20, Month.August, 2007));
            testStartDates.Add(new Date(20, Month.August, 2007));   testEndDates.Add(new Date(20, Month.February, 2008));
            testStartDates.Add(new Date(20, Month.February, 2008)); testEndDates.Add(new Date(20, Month.August, 2008));
            testStartDates.Add(new Date(20, Month.August, 2008));   testEndDates.Add(new Date(20, Month.February, 2009));
            testStartDates.Add(new Date(20, Month.February, 2009)); testEndDates.Add(new Date(20, Month.August, 2009));

            // ISDA - Example 2: End dates include some end-February dates
            testStartDates.Add(new Date(31, Month.August, 2006));   testEndDates.Add(new Date(28, Month.February, 2007));
            testStartDates.Add(new Date(28, Month.February, 2007)); testEndDates.Add(new Date(31, Month.August, 2007));
            testStartDates.Add(new Date(31, Month.August, 2007));   testEndDates.Add(new Date(29, Month.February, 2008));
            testStartDates.Add(new Date(29, Month.February, 2008)); testEndDates.Add(new Date(31, Month.August, 2008));
            testStartDates.Add(new Date(31, Month.August, 2008));   testEndDates.Add(new Date(28, Month.February, 2009));
            testStartDates.Add(new Date(28, Month.February, 2009)); testEndDates.Add(new Date(31, Month.August, 2009));

            //// ISDA - Example 3: Miscellaneous calculations
            testStartDates.Add(new Date(31, Month.January, 2006));   testEndDates.Add(new Date(28, Month.February, 2006));
            testStartDates.Add(new Date(30, Month.January, 2006));   testEndDates.Add(new Date(28, Month.February, 2006));
            testStartDates.Add(new Date(28, Month.February, 2006));  testEndDates.Add(new Date(3, Month.March, 2006));
            testStartDates.Add(new Date(14, Month.February, 2006));  testEndDates.Add(new Date(28, Month.February, 2006));
            testStartDates.Add(new Date(30, Month.September, 2006)); testEndDates.Add(new Date(31, Month.October, 2006));
            testStartDates.Add(new Date(31, Month.October, 2006));   testEndDates.Add(new Date(28, Month.November, 2006));
            testStartDates.Add(new Date(31, Month.August, 2007));    testEndDates.Add(new Date(28, Month.February, 2008));
            testStartDates.Add(new Date(28, Month.February, 2008));  testEndDates.Add(new Date(28, Month.August, 2008));
            testStartDates.Add(new Date(28, Month.February, 2008));  testEndDates.Add(new Date(30, Month.August, 2008));
            testStartDates.Add(new Date(28, Month.February, 2008));  testEndDates.Add(new Date(31, Month.August, 2008));
            testStartDates.Add(new Date(26, Month.February, 2007));  testEndDates.Add(new Date(28, Month.February, 2008));
            testStartDates.Add(new Date(26, Month.February, 2007));  testEndDates.Add(new Date(29, Month.February, 2008));
            testStartDates.Add(new Date(29, Month.February, 2008));  testEndDates.Add(new Date(28, Month.February, 2009));
            testStartDates.Add(new Date(28, Month.February, 2008));  testEndDates.Add(new Date(30, Month.March, 2008));
            testStartDates.Add(new Date(28, Month.February, 2008));  testEndDates.Add(new Date(31, Month.March, 2008));

            int[] expected = { 180, 180, 180, 180, 180, 180,
                               178, 183, 179, 182, 178, 183,
                               28,   28,   5,  14,  30,  28,
                               178, 180, 182, 183, 362, 363,
                               359,  32, 33 };

            for (int i = 0; i < testStartDates.Count; i++)
            {
                calculated = dayCounter.dayCount(testStartDates[i], testEndDates[i]);
                if (calculated != expected[i])
                {
                    QAssert.Fail("from " + testStartDates[i]
                                 + " to " + testEndDates[i] + ":\n"
                                 + "    calculated: " + calculated + "\n"
                                 + "    expected:   " + expected[i]);
                }
            }
        }
Exemple #28
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Thirty360 obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
Exemple #29
0
        static void Main(string[] args)
        {
            DateTime timer = DateTime.Now;

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

            Calendar calendar = new TARGET();

            Date settlementDate = new Date(18, Month.September, 2008);

            // must be a business day
            settlementDate = calendar.adjust(settlementDate);

            int fixingDays     = 3;
            int settlementDays = 3;

            Date todaysDate = calendar.advance(settlementDate, -fixingDays, TimeUnit.Days);

            // nothing to do with Date::todaysDate
            Settings.setEvaluationDate(todaysDate);

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


            // Building of the bonds discounting yield curve

            /*********************
            ***  RATE HELPERS ***
            *********************/

            // RateHelpers are built from the above quotes together with
            // other instrument dependant infos.  Quotes are passed in
            // relinkable handles which could be relinked to some other
            // data source later.

            // Common data

            // ZC rates for the short end
            double zc3mQuote = 0.0096;
            double zc6mQuote = 0.0145;
            double zc1yQuote = 0.0194;

            Quote zc3mRate = new SimpleQuote(zc3mQuote);
            Quote zc6mRate = new SimpleQuote(zc6mQuote);
            Quote zc1yRate = new SimpleQuote(zc1yQuote);

            DayCounter zcBondsDayCounter = new Actual365Fixed();

            RateHelper zc3m = new DepositRateHelper(new Handle <Quote>(zc3mRate),
                                                    new Period(3, TimeUnit.Months), fixingDays,
                                                    calendar, BusinessDayConvention.ModifiedFollowing,
                                                    true, zcBondsDayCounter);
            RateHelper zc6m = new DepositRateHelper(new Handle <Quote>(zc6mRate),
                                                    new Period(6, TimeUnit.Months), fixingDays,
                                                    calendar, BusinessDayConvention.ModifiedFollowing,
                                                    true, zcBondsDayCounter);
            RateHelper zc1y = new DepositRateHelper(new Handle <Quote>(zc1yRate),
                                                    new Period(1, TimeUnit.Years), fixingDays,
                                                    calendar, BusinessDayConvention.ModifiedFollowing,
                                                    true, zcBondsDayCounter);

            // setup bonds
            double redemption = 100.0;

            const int numberOfBonds = 5;

            Date[] issueDates =
            {
                new Date(15, Month.March,    2005),
                new Date(15, Month.June,     2005),
                new Date(30, Month.June,     2006),
                new Date(15, Month.November, 2002),
                new Date(15, Month.May, 1987)
            };

            Date[] maturities =
            {
                new Date(31, Month.August, 2010),
                new Date(31, Month.August, 2011),
                new Date(31, Month.August, 2013),
                new Date(15, Month.August, 2018),
                new Date(15, Month.May, 2038)
            };

            double[] couponRates =
            {
                0.02375,
                0.04625,
                0.03125,
                0.04000,
                0.04500
            };

            double[] marketQuotes =
            {
                100.390625,
                106.21875,
                100.59375,
                101.6875,
                102.140625
            };

            List <SimpleQuote> quote = new List <SimpleQuote>();

            for (int i = 0; i < numberOfBonds; i++)
            {
                SimpleQuote cp = new SimpleQuote(marketQuotes[i]);
                quote.Add(cp);
            }

            List <RelinkableHandle <Quote> > quoteHandle = new InitializedList <RelinkableHandle <Quote> >(numberOfBonds);

            for (int i = 0; i < numberOfBonds; i++)
            {
                quoteHandle[i].linkTo(quote[i]);
            }

            // Definition of the rate helpers
            List <FixedRateBondHelper> bondsHelpers = new List <FixedRateBondHelper>();

            for (int i = 0; i < numberOfBonds; i++)
            {
                Schedule schedule = new Schedule(issueDates[i], maturities[i], new Period(Frequency.Semiannual),
                                                 new UnitedStates(UnitedStates.Market.GovernmentBond),
                                                 BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
                                                 DateGeneration.Rule.Backward, false);

                FixedRateBondHelper bondHelper = new FixedRateBondHelper(quoteHandle[i],
                                                                         settlementDays,
                                                                         100.0,
                                                                         schedule,
                                                                         new List <double>()
                {
                    couponRates[i]
                },
                                                                         new ActualActual(ActualActual.Convention.Bond),
                                                                         BusinessDayConvention.Unadjusted,
                                                                         redemption,
                                                                         issueDates[i]);

                bondsHelpers.Add(bondHelper);
            }

            /*********************
            **  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-bond curve
            List <RateHelper> bondInstruments = new List <RateHelper>();

            // Adding the ZC bonds to the curve for the short end
            bondInstruments.Add(zc3m);
            bondInstruments.Add(zc6m);
            bondInstruments.Add(zc1y);

            // Adding the Fixed rate bonds to the curve for the long end
            for (int i = 0; i < numberOfBonds; i++)
            {
                bondInstruments.Add(bondsHelpers[i]);
            }

            YieldTermStructure bondDiscountingTermStructure = new PiecewiseYieldCurve <Discount, LogLinear>(
                settlementDate, bondInstruments,
                termStructureDayCounter,
                new List <Handle <Quote> >(),
                new List <Date>(),
                tolerance);

            // Building of the Libor forecasting curve
            // deposits
            double d1wQuote = 0.043375;
            double d1mQuote = 0.031875;
            double d3mQuote = 0.0320375;
            double d6mQuote = 0.03385;
            double d9mQuote = 0.0338125;
            double d1yQuote = 0.0335125;
            // swaps
            double s2yQuote  = 0.0295;
            double s3yQuote  = 0.0323;
            double s5yQuote  = 0.0359;
            double s10yQuote = 0.0412;
            double s15yQuote = 0.0433;


            /********************
            ***    QUOTES    ***
            ********************/

            // SimpleQuote stores a value which can be manually changed;
            // other Quote subclasses could read the value from a database
            // or some kind of data feed.

            // 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);
            // 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 swaps
            Frequency             swFixedLegFrequency  = Frequency.Annual;
            BusinessDayConvention swFixedLegConvention = BusinessDayConvention.Unadjusted;
            DayCounter            swFixedLegDayCounter = new Thirty360(Thirty360.Thirty360Convention.European);
            IborIndex             swFloatingLegIndex   = new Euribor6M();

            Period forwardStart = new Period(1, TimeUnit.Days);

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


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

            // Any DayCounter would be fine.
            // ActualActual::ISDA ensures that 30 years is 30.0

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

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

            /*********************
             * BONDS TO BE PRICED *
             **********************/

            // Common data
            double faceAmount = 100;

            // Pricing engine
            IPricingEngine bondEngine = new DiscountingBondEngine(discountingTermStructure);

            // Zero coupon bond
            ZeroCouponBond zeroCouponBond = new ZeroCouponBond(
                settlementDays,
                new UnitedStates(UnitedStates.Market.GovernmentBond),
                faceAmount,
                new Date(15, Month.August, 2013),
                BusinessDayConvention.Following,
                116.92,
                new Date(15, Month.August, 2003));

            zeroCouponBond.setPricingEngine(bondEngine);

            // Fixed 4.5% US Treasury Note
            Schedule fixedBondSchedule = new Schedule(new Date(15, Month.May, 2007),
                                                      new Date(15, Month.May, 2017), new Period(Frequency.Semiannual),
                                                      new UnitedStates(UnitedStates.Market.GovernmentBond),
                                                      BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted, DateGeneration.Rule.Backward, false);

            FixedRateBond fixedRateBond = new FixedRateBond(
                settlementDays,
                faceAmount,
                fixedBondSchedule,
                new List <double>()
            {
                0.045
            },
                new ActualActual(ActualActual.Convention.Bond),
                BusinessDayConvention.ModifiedFollowing,
                100.0, new Date(15, Month.May, 2007));

            fixedRateBond.setPricingEngine(bondEngine);

            // Floating rate bond (3M USD Libor + 0.1%)
            // Should and will be priced on another curve later...

            RelinkableHandle <YieldTermStructure> liborTermStructure = new RelinkableHandle <YieldTermStructure>();
            IborIndex libor3m = new USDLibor(new Period(3, TimeUnit.Months), liborTermStructure);

            libor3m.addFixing(new Date(17, Month.July, 2008), 0.0278625);

            Schedule floatingBondSchedule = new Schedule(new Date(21, Month.October, 2005),
                                                         new Date(21, Month.October, 2010), new Period(Frequency.Quarterly),
                                                         new UnitedStates(UnitedStates.Market.NYSE),
                                                         BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted, DateGeneration.Rule.Backward, true);

            FloatingRateBond floatingRateBond = new FloatingRateBond(
                settlementDays,
                faceAmount,
                floatingBondSchedule,
                libor3m,
                new Actual360(),
                BusinessDayConvention.ModifiedFollowing,
                2,
                // Gearings
                new List <double>()
            {
                1.0
            },
                // Spreads
                new List <double>()
            {
                0.001
            },
                // Caps
                new List <double?>(),
                // Floors
                new List <double?>(),
                // Fixing in arrears
                true,
                100.0,
                new Date(21, Month.October, 2005));

            floatingRateBond.setPricingEngine(bondEngine);

            // Coupon pricers
            IborCouponPricer pricer = new BlackIborCouponPricer();

            // optionLet volatilities
            double volatility = 0.0;
            Handle <OptionletVolatilityStructure> vol;

            vol = new Handle <OptionletVolatilityStructure>(
                new ConstantOptionletVolatility(
                    settlementDays,
                    calendar,
                    BusinessDayConvention.ModifiedFollowing,
                    volatility,
                    new Actual365Fixed()));

            pricer.setCapletVolatility(vol);
            Utils.setCouponPricer(floatingRateBond.cashflows(), pricer);

            // Yield curve bootstrapping
            forecastingTermStructure.linkTo(depoSwapTermStructure);
            discountingTermStructure.linkTo(bondDiscountingTermStructure);

            // We are using the depo & swap curve to estimate the future Libor rates
            liborTermStructure.linkTo(depoSwapTermStructure);

            /***************
             * BOND PRICING *
             ****************/

            // write column headings
            int[] widths = { 18, 10, 10, 10 };

            Console.WriteLine("{0,18}{1,10}{2,10}{3,10}", "", "ZC", "Fixed", "Floating");

            int width = widths[0]
                        + widths[1]
                        + widths[2]
                        + widths[3];
            string rule = "".PadLeft(width, '-'), dblrule = "".PadLeft(width, '=');
            string tab = "".PadLeft(8, ' ');

            Console.WriteLine(rule);

            Console.WriteLine("Net present value".PadLeft(widths[0]) + "{0,10:n2}{1,10:n2}{2,10:n2}",
                              zeroCouponBond.NPV(),
                              fixedRateBond.NPV(),
                              floatingRateBond.NPV());

            Console.WriteLine("Clean price".PadLeft(widths[0]) + "{0,10:n2}{1,10:n2}{2,10:n2}",
                              zeroCouponBond.cleanPrice(),
                              fixedRateBond.cleanPrice(),
                              floatingRateBond.cleanPrice());

            Console.WriteLine("Dirty price".PadLeft(widths[0]) + "{0,10:n2}{1,10:n2}{2,10:n2}",
                              zeroCouponBond.dirtyPrice(),
                              fixedRateBond.dirtyPrice(),
                              floatingRateBond.dirtyPrice());

            Console.WriteLine("Accrued coupon".PadLeft(widths[0]) + "{0,10:n2}{1,10:n2}{2,10:n2}",
                              zeroCouponBond.accruedAmount(),
                              fixedRateBond.accruedAmount(),
                              floatingRateBond.accruedAmount());

            Console.WriteLine("Previous coupon".PadLeft(widths[0]) + "{0,10:0.00%}{1,10:0.00%}{2,10:0.00%}",
                              "N/A",
                              fixedRateBond.previousCouponRate(),
                              floatingRateBond.previousCouponRate());

            Console.WriteLine("Next coupon".PadLeft(widths[0]) + "{0,10:0.00%}{1,10:0.00%}{2,10:0.00%}",
                              "N/A",
                              fixedRateBond.nextCouponRate(),
                              floatingRateBond.nextCouponRate());

            Console.WriteLine("Yield".PadLeft(widths[0]) + "{0,10:0.00%}{1,10:0.00%}{2,10:0.00%}",
                              zeroCouponBond.yield(new Actual360(), Compounding.Compounded, Frequency.Annual),
                              fixedRateBond.yield(new Actual360(), Compounding.Compounded, Frequency.Annual),
                              floatingRateBond.yield(new Actual360(), Compounding.Compounded, Frequency.Annual));

            Console.WriteLine();

            // Other computations
            Console.WriteLine("Sample indirect computations (for the floating rate bond): ");
            Console.WriteLine(rule);

            Console.WriteLine("Yield to Clean Price: {0:n2}",
                              floatingRateBond.cleanPrice(floatingRateBond.yield(new Actual360(), Compounding.Compounded, Frequency.Annual),
                                                          new Actual360(), Compounding.Compounded, Frequency.Annual,
                                                          settlementDate));

            Console.WriteLine("Clean Price to Yield: {0:0.00%}",
                              floatingRateBond.yield(floatingRateBond.cleanPrice(), new Actual360(), Compounding.Compounded, Frequency.Annual,
                                                     settlementDate));

            /* "Yield to Price"
            *  "Price to Yield" */

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

            Console.Write("Press any key to continue ...");
            Console.ReadKey();
        }
Exemple #30
0
        public void testYield()
        {
            //"Testing consistency of bond price/yield calculation...");

             CommonVars vars = new CommonVars();

             double tolerance = 1.0e-7;
             int maxEvaluations = 100;

             int[] issueMonths = new int[] { -24, -18, -12, -6, 0, 6, 12, 18, 24 };
             int[] lengths = new int[] { 3, 5, 10, 15, 20 };
             int settlementDays = 3;
             double[] coupons = new double[] { 0.02, 0.05, 0.08 };
             Frequency[] frequencies = new Frequency[] { Frequency.Semiannual, Frequency.Annual };
             DayCounter bondDayCount = new Thirty360();
             BusinessDayConvention accrualConvention = BusinessDayConvention.Unadjusted;
             BusinessDayConvention paymentConvention = BusinessDayConvention.ModifiedFollowing;
             double redemption = 100.0;

             double[] yields = new double[] { 0.03, 0.04, 0.05, 0.06, 0.07 };
             Compounding[] compounding = new Compounding[] { Compounding.Compounded, Compounding.Continuous };

             for (int i = 0; i < issueMonths.Length; i++)
             {
            for (int j = 0; j < lengths.Length; j++)
            {
               for (int k = 0; k < coupons.Length; k++)
               {
                  for (int l = 0; l < frequencies.Length; l++)
                  {
                     for (int n = 0; n < compounding.Length; n++)
                     {

                        Date dated = vars.calendar.advance(vars.today, issueMonths[i], TimeUnit.Months);
                        Date issue = dated;
                        Date maturity = vars.calendar.advance(issue, lengths[j], TimeUnit.Years);

                        Schedule sch = new Schedule(dated, maturity, new Period(frequencies[l]), vars.calendar,
                                                    accrualConvention, accrualConvention, DateGeneration.Rule.Backward, false);

                        FixedRateBond bond = new FixedRateBond(settlementDays, vars.faceAmount, sch,
                                                               new List<double>() { coupons[k] },
                                                               bondDayCount, paymentConvention,
                                                               redemption, issue);

                        for (int m = 0; m < yields.Length; m++)
                        {

                           double price = bond.cleanPrice(yields[m], bondDayCount, compounding[n], frequencies[l]);
                           double calculated = bond.yield(price, bondDayCount, compounding[n], frequencies[l], null,
                                                          tolerance, maxEvaluations);

                           if (Math.Abs(yields[m] - calculated) > tolerance)
                           {
                              // the difference might not matter
                              double price2 = bond.cleanPrice(calculated, bondDayCount, compounding[n], frequencies[l]);
                              if (Math.Abs(price - price2) / price > tolerance)
                              {
                                 Assert.Fail("yield recalculation failed:\n"
                                     + "    issue:     " + issue + "\n"
                                     + "    maturity:  " + maturity + "\n"
                                     + "    coupon:    " + coupons[k] + "\n"
                                     + "    frequency: " + frequencies[l] + "\n\n"
                                     + "    yield:  " + yields[m] + " "
                                     + (compounding[n] == Compounding.Compounded ? "compounded" : "continuous") + "\n"
                                     + "    price:  " + price + "\n"
                                     + "    yield': " + calculated + "\n"
                                     + "    price': " + price2);
                              }
                           }
                        }
                     }
                  }
               }
            }
             }
        }