Example #1
0
        public void testDatesSameAsEndDateWithEomAdjustment()
        {
            // Testing that next-to-last date same as end date is removed...

            Schedule s = new MakeSchedule().from(new Date(28, Month.March, 2013))
                         .to(new Date(31, Month.March, 2015))
                         .withCalendar(new TARGET())
                         .withTenor(new Period(1, TimeUnit.Years))
                         .withConvention(BusinessDayConvention.Unadjusted)
                         .withTerminationDateConvention(BusinessDayConvention.Unadjusted)
                         .forwards()
                         .endOfMonth()
                         .value();

            List <Date> expected = new List <Date>(3);

            expected.Add(new Date(31, Month.March, 2013));
            expected.Add(new Date(31, Month.March, 2014));
            // March 31st 2015, coming from the EOM adjustment of March 28th,
            // should be discarded as the same as the end date.
            expected.Add(new Date(31, Month.March, 2015));

            check_dates(s, expected);

            // also, the last period should be regular.
            if (!s.isRegular(2))
            {
                QAssert.Fail("last period should be regular");
            }
        }
Example #2
0
        public void testDailySchedule()
        {
            // Testing schedule with daily frequency

            Date startDate = new Date(17, Month.January, 2012);

            Schedule s = new MakeSchedule().from(startDate).to(startDate + 7)
                         .withCalendar(new TARGET())
                         .withConvention(BusinessDayConvention.Preceding)
                         .withFrequency(Frequency.Daily).value();

            List <Date> expected = new List <Date>(6);

            // The schedule should skip Saturday 21st and Sunday 22rd.
            // Previously, it would adjust them to Friday 20th, resulting
            // in three copies of the same date.
            expected.Add(new Date(17, Month.January, 2012));
            expected.Add(new Date(18, Month.January, 2012));
            expected.Add(new Date(19, Month.January, 2012));
            expected.Add(new Date(20, Month.January, 2012));
            expected.Add(new Date(23, Month.January, 2012));
            expected.Add(new Date(24, Month.January, 2012));

            check_dates(s, expected);
        }
Example #3
0
        [InlineData(false, Frequency.Quarterly, "1999-05-31", "2000-04-30", "1999-08-31", "1999-11-30", "1999-11-30", "2000-04-30", (91.0 / (91.0 * 4)) + (61.0 / (90.0 * 4)))]      // example e: long final calculation period - not end of month
        public void testActualActualIsma(bool isEndOfMonth, Frequency frequency, string interestAccrualDateAsString, string maturityDateAsString, string firstCouponDateAsString, string penultimateCouponDateAsString, string d1AsString, string d2AsString, double expectedYearFraction)
        {
            // Example from ISDA Paper: The actual/actual day count fraction, paper for use with the ISDA Market Conventions Survey, 3rd June, 1999
            var interestAccrualDate   = new Date(DateTime.ParseExact(interestAccrualDateAsString, "yyyy-MM-dd", CultureInfo.InvariantCulture));
            var maturityDate          = new Date(DateTime.ParseExact(maturityDateAsString, "yyyy-MM-dd", CultureInfo.InvariantCulture));
            var firstCouponDate       = new Date(DateTime.ParseExact(firstCouponDateAsString, "yyyy-MM-dd", CultureInfo.InvariantCulture));
            var penultimateCouponDate = new Date(DateTime.ParseExact(penultimateCouponDateAsString, "yyyy-MM-dd", CultureInfo.InvariantCulture));

            var d1 = new Date(DateTime.ParseExact(d1AsString, "yyyy-MM-dd", CultureInfo.InvariantCulture));
            var d2 = new Date(DateTime.ParseExact(d2AsString, "yyyy-MM-dd", CultureInfo.InvariantCulture));

            var schedule = new MakeSchedule()
                           .from(interestAccrualDate)
                           .to(maturityDate)
                           .withFrequency(frequency)
                           .withFirstDate(firstCouponDate)
                           .withNextToLastDate(penultimateCouponDate)
                           .endOfMonth(isEndOfMonth)
                           .value();

            var dayCounter = new ActualActual(ActualActual.Convention.ISMA, schedule);

            var t = dayCounter.yearFraction(d1, d2);

            Assert.Equal(expectedYearFraction, t);
        }
Example #4
0
        public void testOption()
        {
            /* a zero-coupon convertible bond with no credit spread is
             * equivalent to a call option. */

            // Testing zero-coupon convertible bonds against vanilla option

            CommonVars vars = new CommonVars();

            Exercise euExercise = new EuropeanExercise(vars.maturityDate);

            vars.settlementDays = 0;

            int            timeSteps     = 2001;
            IPricingEngine engine        = new BinomialConvertibleEngine <CoxRossRubinstein>(vars.process, timeSteps);
            IPricingEngine vanillaEngine = new BinomialVanillaEngine <CoxRossRubinstein>(vars.process, timeSteps);

            vars.creditSpread.linkTo(new SimpleQuote(0.0));

            double            conversionStrike = vars.redemption / vars.conversionRatio;
            StrikedTypePayoff payoff           = new PlainVanillaPayoff(Option.Type.Call, conversionStrike);

            Schedule schedule = new MakeSchedule().from(vars.issueDate)
                                .to(vars.maturityDate)
                                .withFrequency(Frequency.Once)
                                .withCalendar(vars.calendar)
                                .backwards().value();

            ConvertibleZeroCouponBond euZero = new ConvertibleZeroCouponBond(euExercise, vars.conversionRatio,
                                                                             vars.no_dividends, vars.no_callability,
                                                                             vars.creditSpread,
                                                                             vars.issueDate, vars.settlementDays,
                                                                             vars.dayCounter, schedule,
                                                                             vars.redemption);

            euZero.setPricingEngine(engine);

            VanillaOption euOption = new VanillaOption(payoff, euExercise);

            euOption.setPricingEngine(vanillaEngine);

            double tolerance = 5.0e-2 * (vars.faceAmount / 100.0);

            double expected = vars.faceAmount / 100.0 *
                              (vars.redemption * vars.riskFreeRate.link.discount(vars.maturityDate)
                               + vars.conversionRatio * euOption.NPV());
            double error = Math.Abs(euZero.NPV() - expected);

            if (error > tolerance)
            {
                QAssert.Fail("failed to reproduce plain-option price:"
                             + "\n    calculated: " + euZero.NPV()
                             + "\n    expected:   " + expected
                             + "\n    error:      " + error
                             + "\n    tolerance:      " + tolerance);
            }
        }
Example #5
0
        public MakeSchedule withTenor(Period arg0)
        {
            MakeSchedule ret = new MakeSchedule(NQuantLibcPINVOKE.MakeSchedule_withTenor(swigCPtr, Period.getCPtr(arg0)), false);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Example #6
0
        public MakeSchedule to(Date terminationDate)
        {
            MakeSchedule ret = new MakeSchedule(NQuantLibcPINVOKE.MakeSchedule_to(swigCPtr, Date.getCPtr(terminationDate)), false);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Example #7
0
        public MakeSchedule from(Date effectiveDate)
        {
            MakeSchedule ret = new MakeSchedule(NQuantLibcPINVOKE.MakeSchedule_from(swigCPtr, Date.getCPtr(effectiveDate)), false);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Example #8
0
        public MakeSchedule withNextToLastDate(Date d)
        {
            MakeSchedule ret = new MakeSchedule(NQuantLibcPINVOKE.MakeSchedule_withNextToLastDate(swigCPtr, Date.getCPtr(d)), false);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Example #9
0
        public MakeSchedule withFrequency(Frequency arg0)
        {
            MakeSchedule ret = new MakeSchedule(NQuantLibcPINVOKE.MakeSchedule_withFrequency(swigCPtr, (int)arg0), false);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Example #10
0
        public MakeSchedule withTerminationDateConvention(BusinessDayConvention arg0)
        {
            MakeSchedule ret = new MakeSchedule(NQuantLibcPINVOKE.MakeSchedule_withTerminationDateConvention(swigCPtr, (int)arg0), false);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Example #11
0
        public MakeSchedule backwards()
        {
            MakeSchedule ret = new MakeSchedule(NQuantLibcPINVOKE.MakeSchedule_backwards(swigCPtr), false);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Example #12
0
        public MakeSchedule endOfMonth()
        {
            MakeSchedule ret = new MakeSchedule(NQuantLibcPINVOKE.MakeSchedule_endOfMonth__SWIG_1(swigCPtr), false);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Example #13
0
        //@}

        protected override void initializeDates()
        {
            Date settlementDate = settlementCalendar_.advance(evaluationDate_, settlementDays_, TimeUnit.Days);
            Date maturityDate   = settlementDate + swapTenor_;

            Period   shortLegTenor    = shortIndex_.tenor();
            Schedule shortLegSchedule = new MakeSchedule()
                                        .from(settlementDate)
                                        .to(maturityDate)
                                        .withTenor(shortLegTenor)
                                        .withCalendar(settlementCalendar_)
                                        .withConvention(rollConvention_)
                                        .endOfMonth(eom_)
                                        .value();

            Period   longLegTenor    = longIndex_.tenor();
            Schedule longLegSchedule = new MakeSchedule()
                                       .from(settlementDate)
                                       .to(maturityDate)
                                       .withTenor(longLegTenor)
                                       .withCalendar(settlementCalendar_)
                                       .withConvention(rollConvention_)
                                       .endOfMonth(eom_)
                                       .value();

            double nominal        = 1.0;
            double shortLegSpread = 0.0;
            double longLegSpread  = 0.0;

            if (spreadOnShort_)
            {
                shortLegSpread = quote_.link.value();
            }
            else
            {
                longLegSpread = quote_.link.value();
            }

            /* Arbitrarily set the swap as paying the long index */
            swap_ = new BasisSwap(BasisSwap.Type.Payer, nominal,
                                  shortLegSchedule, shortIndex_, shortLegSpread, shortIndex_.dayCounter(),
                                  longLegSchedule, longIndex_, longLegSpread, longIndex_.dayCounter(),
                                  BusinessDayConvention.Following);

            IPricingEngine engine;

            engine = new DiscountingSwapEngine(discountHandle_, false, settlementDate, settlementDate);
            engine.reset();

            swap_.setPricingEngine(engine);

            earliestDate_ = swap_.startDate();
            latestDate_   = swap_.maturityDate();
            maturityDate_ = latestRelevantDate_ = swap_.maturityDate();
        }
Example #14
0
        //double fixedRate = 0.001;
        //double notional = 10000.0;
        //double recoveryRate = 0.4;

        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Calculates the cds. </summary>
        ///
        /// <param name="msg">          [in,out] The message. </param>
        /// <param name="fixedRate">    The fixed rate. </param>
        /// <param name="notional">     The notional. </param>
        /// <param name="recoveryRate"> The recovery rate. </param>
        ///
        /// <returns>   True if it succeeds, false if it fails. </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        public bool CalcCDS(ref CreditDefaultSwapRequestMessage msg, double fixedRate, double notional, double recoveryRate)
        {
            // Testing fair-spread calculation for credit-default swaps...
            using (SavedSettings backup = new SavedSettings())
            {
                // Initialize curves
                Calendar calendar = new TARGET();
                Date     today    = calendar.adjust(Date.Today);
                Settings.setEvaluationDate(today);

                Handle <Quote> hazardRate = new Handle <Quote>(new SimpleQuote(0.01234));
                RelinkableHandle <DefaultProbabilityTermStructure> probabilityCurve =
                    new RelinkableHandle <DefaultProbabilityTermStructure>();
                probabilityCurve.linkTo(new FlatHazardRate(0, calendar, hazardRate, new Actual360()));

                RelinkableHandle <YieldTermStructure> discountCurve =
                    new RelinkableHandle <YieldTermStructure>();
                discountCurve.linkTo(new FlatForward(today, 0.06, new Actual360()));

                // Build the schedule
                Date issueDate = calendar.advance(today, -1, TimeUnit.Years);
                Date maturity  = calendar.advance(issueDate, 10, TimeUnit.Years);
                BusinessDayConvention convention = BusinessDayConvention.Following;

                Schedule schedule = new MakeSchedule().from(issueDate)
                                    .to(maturity)
                                    .withFrequency(Frequency.Quarterly)
                                    .withCalendar(calendar)
                                    .withTerminationDateConvention(convention)
                                    .withRule(DateGeneration.Rule.TwentiethIMM).value();

                // Build the CDS
                DayCounter dayCount = new Actual360();

                IPricingEngine    engine = new MidPointCdsEngine(probabilityCurve, recoveryRate, discountCurve);
                CreditDefaultSwap cds    = new CreditDefaultSwap(Protection.Side.Seller, notional, fixedRate,
                                                                 schedule, convention, dayCount, true, true);
                cds.setPricingEngine(engine);
                double            fairRate = cds.fairSpread();
                CreditDefaultSwap fairCds  = new CreditDefaultSwap(Protection.Side.Seller, notional, fairRate,
                                                                   schedule, convention, dayCount, true, true);
                fairCds.setPricingEngine(engine);

                double fairNPV   = fairCds.NPV();
                double tolerance = 1e-10;

                msg.fairRate = fairRate;
                msg.fairNPV  = fairNPV;
                return(Math.Abs(fairNPV) <= tolerance);
            }
        }
Example #15
0
        public SubPeriodsCoupon(Date paymentDate, double nominal, Date startDate, Date endDate,
                                InterestRateIndex index, Type type, BusinessDayConvention convention,
                                double spread = 0.0, DayCounter dayCounter = null, bool includeSpread = false, double gearing = 1.0)
            : base(paymentDate, nominal, startDate, endDate, index.fixingDays(), index, gearing, spread, new Date(), new Date(), dayCounter, false)
        {
            _type          = type;
            _includeSpread = includeSpread;

            // Populate the value dates.
            Schedule sch = new MakeSchedule()
                           .from(startDate)
                           .to(endDate)
                           .withTenor(index.tenor())
                           .withCalendar(index.fixingCalendar())
                           .withConvention(convention)
                           .withTerminationDateConvention(convention)
                           .backwards().value();

            _valueDates = sch.dates();
            Utils.QL_REQUIRE(_valueDates.Count >= 2, () => "Degenerate schedule.");

            // Populate the fixing dates.
            _numPeriods = _valueDates.Count - 1;
            if (index.fixingDays() == 0)
            {
                _fixingDates = new List <Date> {
                    _valueDates.First(), _valueDates.Last() - 1
                };
            }
            else
            {
                _fixingDates.Resize(_numPeriods);
                for (int i = 0; i < _numPeriods; ++i)
                {
                    _fixingDates[i] = index.fixingDate(_valueDates[i]);
                }
            }

            // Populate the accrual periods.
            _accrualFractions.Resize(_numPeriods);
            for (int i = 0; i < _numPeriods; ++i)
            {
                _accrualFractions[i] = dayCounter.yearFraction(_valueDates[i], _valueDates[i + 1]);
            }
        }
Example #16
0
        public void testNullFixingDays()
        {
            // Testing ibor leg construction with null fixing days...
            Date     today    = Settings.Instance.evaluationDate();
            Schedule schedule = new
                                MakeSchedule()
                                .from(today - new Period(2, TimeUnit.Months)).to(today + new Period(4, TimeUnit.Months))
                                .withFrequency(Frequency.Semiannual)
                                .withCalendar(new TARGET())
                                .withConvention(BusinessDayConvention.Following)
                                .backwards().value();

            IborIndex       index = new USDLibor(new Period(6, TimeUnit.Months));
            List <CashFlow> leg   = new IborLeg(schedule, index)
                                    // this can happen with default values, and caused an
                                    // exception when the null was not managed properly
                                    .withFixingDays(null)
                                    .withNotionals(100.0);
        }
Example #17
0
        protected override void initializeDates()
        {
            // if the evaluation date is not a business day
            // then move to the next business day
            JointCalendar jc            = new JointCalendar(calendar_, iborIndex_.fixingCalendar());
            Date          referenceDate = jc.adjust(evaluationDate_);

            earliestDate_ = calendar_.advance(referenceDate, new Period(settlementDays_, TimeUnit.Days), BusinessDayConvention.Following);

            Date maturity = earliestDate_ + tenor_;

            // dummy BMA index with curve/swap arguments
            BMAIndex clonedIndex = new BMAIndex(termStructureHandle_);

            Schedule bmaSchedule = new MakeSchedule().from(earliestDate_).to(maturity)
                                   .withTenor(bmaPeriod_)
                                   .withCalendar(bmaIndex_.fixingCalendar())
                                   .withConvention(bmaConvention_)
                                   .backwards().value();

            Schedule liborSchedule = new MakeSchedule().from(earliestDate_).to(maturity)
                                     .withTenor(iborIndex_.tenor())
                                     .withCalendar(iborIndex_.fixingCalendar())
                                     .withConvention(iborIndex_.businessDayConvention())
                                     .endOfMonth(iborIndex_.endOfMonth())
                                     .backwards().value();

            swap_ = new BMASwap(BMASwap.Type.Payer,
                                100.0, liborSchedule, 0.75, // arbitrary
                                0.0, iborIndex_, iborIndex_.dayCounter(), bmaSchedule, clonedIndex, bmaDayCount_);

            swap_.setPricingEngine(new DiscountingSwapEngine(iborIndex_.forwardingTermStructure()));

            Date d             = calendar_.adjust(swap_.maturityDate(), BusinessDayConvention.Following);
            int  w             = d.weekday();
            Date nextWednesday = (w >= 4) ?
                                 d + new Period((11 - w), TimeUnit.Days) :
                                 d + new Period((4 - w), TimeUnit.Days);

            latestDate_ = clonedIndex.valueDate(clonedIndex.fixingCalendar().adjust(nextWednesday));
        }
Example #18
0
        public void testEndDateWithEomAdjustment()
        {
            // Testing end date for schedule with end-of-month adjustment

            Schedule s = new MakeSchedule().from(new Date(30, Month.September, 2009))
                         .to(new Date(15, Month.June, 2012))
                         .withCalendar(new Japan())
                         .withTenor(new Period(6, TimeUnit.Months))
                         .withConvention(BusinessDayConvention.Following)
                         .withTerminationDateConvention(BusinessDayConvention.Following)
                         .forwards()
                         .endOfMonth().value();

            List <Date> expected = new List <Date>();

            // The end date is adjusted, so it should also be moved to the end
            // of the month.
            expected.Add(new Date(30, Month.September, 2009));
            expected.Add(new Date(31, Month.March, 2010));
            expected.Add(new Date(30, Month.September, 2010));
            expected.Add(new Date(31, Month.March, 2011));
            expected.Add(new Date(30, Month.September, 2011));
            expected.Add(new Date(30, Month.March, 2012));
            expected.Add(new Date(29, Month.June, 2012));

            check_dates(s, expected);

            // now with unadjusted termination date...
            s = new MakeSchedule().from(new Date(30, Month.September, 2009))
                .to(new Date(15, Month.June, 2012))
                .withCalendar(new Japan())
                .withTenor(new Period(6, TimeUnit.Months))
                .withConvention(BusinessDayConvention.Following)
                .withTerminationDateConvention(BusinessDayConvention.Unadjusted)
                .forwards()
                .endOfMonth().value();
            // ...which should leave it alone.
            expected[6] = new Date(15, Month.June, 2012);

            check_dates(s, expected);
        }
Example #19
0
        public void testDoubleFirstDateWithEomAdjustment()
        {
            // Testing that the first date is not duplicated due to EOM convention when going backwards

            Schedule s = new MakeSchedule().from(new Date(22, Month.August, 1996))
                         .to(new Date(31, Month.August, 1997))
                         .withCalendar(new UnitedStates(UnitedStates.Market.GovernmentBond))
                         .withTenor(new Period(6, TimeUnit.Months))
                         .withConvention(BusinessDayConvention.Following)
                         .withTerminationDateConvention(BusinessDayConvention.Following)
                         .backwards()
                         .endOfMonth().value();

            List <Date> expected = new List <Date>();

            expected.Add(new Date(30, Month.August, 1996));
            expected.Add(new Date(28, Month.February, 1997));
            expected.Add(new Date(29, Month.August, 1997));

            check_dates(s, expected);
        }
Example #20
0
        public void testDatesPastEndDateWithEomAdjustment()
        {
            Schedule s = new MakeSchedule().from(new Date(28, Month.March, 2013))
                         .to(new Date(30, Month.March, 2015))
                         .withCalendar(new TARGET())
                         .withTenor(new Period(1, TimeUnit.Years))
                         .withConvention(BusinessDayConvention.Unadjusted)
                         .withTerminationDateConvention(BusinessDayConvention.Unadjusted)
                         .forwards()
                         .endOfMonth().value();

            List <Date> expected = new List <Date>();

            expected.Add(new Date(31, Month.March, 2013));
            expected.Add(new Date(31, Month.March, 2014));
            // March 31st 2015, coming from the EOM adjustment of March 28th,
            // should be discarded as past the end date.
            expected.Add(new Date(30, Month.March, 2015));

            check_dates(s, expected);
        }
Example #21
0
        public void testActualActualWithAnnualSchedule()
        {
            // Testing actual/actual with schedule "for undefined annual reference periods

            // Now do an annual schedule
            Calendar calendar = new UnitedStates();
            Schedule schedule = new MakeSchedule()
                                .from(new Date(10, Month.January, 2017))
                                .withFirstDate(new Date(31, Month.August, 2017))
                                .to(new Date(28, Month.February, 2026))
                                .withFrequency(Frequency.Annual)
                                .withCalendar(calendar)
                                .withConvention(BusinessDayConvention.Unadjusted)
                                .backwards().endOfMonth(false).value();

            Date referencePeriodStart = schedule.date(1);
            Date referencePeriodEnd   = schedule.date(2);

            Date       testDate   = schedule.date(1);
            DayCounter dayCounter = new ActualActual(ActualActual.Convention.ISMA, schedule);

            while (testDate < referencePeriodEnd)
            {
                double difference =
                    ISMAYearFractionWithReferenceDates(dayCounter,
                                                       testDate, referencePeriodEnd,
                                                       referencePeriodStart, referencePeriodEnd) -
                    dayCounter.yearFraction(testDate, referencePeriodEnd);
                if (Math.Abs(difference) > 1.0e-10)
                {
                    QAssert.Fail("Failed to correctly use the schedule " +
                                 "to find the reference period for Act/Act:\n"
                                 + testDate + " to " + referencePeriodEnd
                                 + "\n Ref: " + referencePeriodStart
                                 + " to " + referencePeriodEnd);
                }
                testDate = calendar.advance(testDate, 1, TimeUnit.Days);
            }
        }
Example #22
0
        public void testDefaultSettlementDate()
        {
            // Testing default evaluation date in cashflows methods...
            Date     today    = Settings.Instance.evaluationDate();
            Schedule schedule = new
                                MakeSchedule()
                                .from(today - new Period(2, TimeUnit.Months)).to(today + new Period(4, TimeUnit.Months))
                                .withFrequency(Frequency.Semiannual)
                                .withCalendar(new TARGET())
                                .withConvention(BusinessDayConvention.Unadjusted)
                                .backwards().value();

            List <CashFlow> leg = new FixedRateLeg(schedule)
                                  .withCouponRates(0.03, new Actual360())
                                  .withPaymentCalendar(new TARGET())
                                  .withNotionals(100.0)
                                  .withPaymentAdjustment(BusinessDayConvention.Following);

            double accruedPeriod = CashFlows.accruedPeriod(leg, false);

            if (accruedPeriod == 0.0)
            {
                QAssert.Fail("null accrued period with default settlement date");
            }

            int accruedDays = CashFlows.accruedDays(leg, false);

            if (accruedDays == 0)
            {
                QAssert.Fail("no accrued days with default settlement date");
            }

            double accruedAmount = CashFlows.accruedAmount(leg, false);

            if (accruedAmount == 0.0)
            {
                QAssert.Fail("null accrued amount with default settlement date");
            }
        }
Example #23
0
        public void testBackwardDatesWithEomAdjustment()
        {
            // Testing that the first date is not adjusted for EOM going backward when termination date convention is unadjusted

            Schedule s = new MakeSchedule().from(new Date(22, Month.August, 1996))
                         .to(new Date(31, Month.August, 1997))
                         .withCalendar(new UnitedStates(UnitedStates.Market.GovernmentBond))
                         .withTenor(new Period(6, TimeUnit.Months))
                         .withConvention(BusinessDayConvention.Unadjusted)
                         .withTerminationDateConvention(BusinessDayConvention.Unadjusted)
                         .backwards()
                         .endOfMonth().value();

            List <Date> expected = new List <Date>();

            expected.Add(new Date(22, Month.August, 1996));
            expected.Add(new Date(31, Month.August, 1996));
            expected.Add(new Date(28, Month.February, 1997));
            expected.Add(new Date(31, Month.August, 1997));

            check_dates(s, expected);
        }
Example #24
0
        public void testCDS2015Convention()
        {
            // Testing CDS2015 semi-annual rolling convention
            //From September 20th 2016 to March 19th 2017 of the next Year,
            //end date is December 20th 2021 for a 5 year Swap
            Schedule s1 = new  MakeSchedule().from(new Date(12, Month.December, 2016))
                          .to(new Date(12, Month.December, 2016) + new Period(5, TimeUnit.Years))
                          .withCalendar(new WeekendsOnly())
                          .withTenor(new Period(3, TimeUnit.Months))
                          .withConvention(BusinessDayConvention.ModifiedFollowing)
                          .withTerminationDateConvention(BusinessDayConvention.Unadjusted)
                          .withRule(DateGeneration.Rule.CDS2015).value();

            QAssert.IsTrue(s1.startDate() == new Date(20, Month.September, 2016));
            QAssert.IsTrue(s1.endDate() == new Date(20, Month.December, 2021));
            Schedule s2 = new MakeSchedule().from(new Date(1, Month.March, 2017))
                          .to(new Date(1, Month.March, 2017) + new Period(5, TimeUnit.Years))
                          .withCalendar(new WeekendsOnly())
                          .withTenor(new Period(3, TimeUnit.Months))
                          .withConvention(BusinessDayConvention.ModifiedFollowing)
                          .withTerminationDateConvention(BusinessDayConvention.Unadjusted)
                          .withRule(DateGeneration.Rule.CDS2015).value();

            QAssert.IsTrue(s2.startDate() == new Date(20, Month.December, 2016));
            QAssert.IsTrue(s2.endDate() == new Date(20, Month.December, 2021));
            //From March 20th 2017 to September 19th 2017
            //end date is June 20th 2022 for a 5 year Swap
            Schedule s3 = new MakeSchedule().from(new Date(20, Month.March, 2017))
                          .to(new Date(20, Month.March, 2017) + new Period(5, TimeUnit.Years))
                          .withCalendar(new WeekendsOnly())
                          .withTenor(new Period(3, TimeUnit.Months))
                          .withConvention(BusinessDayConvention.ModifiedFollowing)
                          .withTerminationDateConvention(BusinessDayConvention.Unadjusted)
                          .withRule(DateGeneration.Rule.CDS2015).value();

            QAssert.IsTrue(s3.startDate() == new Date(20, Month.March, 2017));
            QAssert.IsTrue(s3.endDate() == new Date(20, Month.June, 2022));
        }
Example #25
0
            // setup
            public CommonVars()
            {
                backup    = new SavedSettings();
                nominalUK = new RelinkableHandle <YieldTermStructure>();
                cpiUK     = new RelinkableHandle <ZeroInflationTermStructure>();
                hcpi      = new RelinkableHandle <ZeroInflationTermStructure>();
                zciisD    = new List <Date>();
                zciisR    = new List <double>();
                hii       = new RelinkableHandle <ZeroInflationIndex>();

                nominals = new InitializedList <double>(1, 1000000);
                // option variables
                frequency = Frequency.Annual;
                // usual setup
                volatility = 0.01;
                length     = 7;
                calendar   = new UnitedKingdom();
                convention = BusinessDayConvention.ModifiedFollowing;
                Date today = new Date(1, Month.June, 2010);

                evaluationDate = calendar.adjust(today);
                Settings.setEvaluationDate(evaluationDate);
                settlementDays = 0;
                fixingDays     = 0;
                settlement     = calendar.advance(today, settlementDays, TimeUnit.Days);
                startDate      = settlement;
                dcZCIIS        = new ActualActual();
                dcNominal      = new ActualActual();

                // uk rpi index
                //      fixing data
                Date     from        = new Date(1, Month.July, 2007);
                Date     to          = new Date(1, Month.June, 2010);
                Schedule rpiSchedule = new MakeSchedule().from(from).to(to)
                                       .withTenor(new Period(1, TimeUnit.Months))
                                       .withCalendar(new UnitedKingdom())
                                       .withConvention(BusinessDayConvention.ModifiedFollowing).value();

                double[] fixData =
                {
                    206.1, 207.3, 208.0, 208.9, 209.7, 210.9,
                    209.8, 211.4, 212.1, 214.0, 215.1, 216.8, //  2008
                    216.5, 217.2, 218.4, 217.7, 216.0, 212.9,
                    210.1, 211.4, 211.3, 211.5, 212.8, 213.4, //  2009
                    213.4, 214.4, 215.3, 216.0, 216.6, 218.0,
                    217.9, 219.2, 220.7, 222.8,  -999,  -999, //  2010
                    -999
                };

                // link from cpi index to cpi TS
                bool interp = false;// this MUST be false because the observation lag is only 2 months

                // for ZCIIS; but not for contract if the contract uses a bigger lag.
                ii = new UKRPI(interp, hcpi);
                for (int i = 0; i < rpiSchedule.Count; i++)
                {
                    ii.addFixing(rpiSchedule[i], fixData[i], true);// force overwrite in case multiple use
                }

                Datum[] nominalData =
                {
                    new Datum(new Date(2,  Month.June,      2010), 0.499997),
                    new Datum(new Date(3,  Month.June,      2010), 0.524992),
                    new Datum(new Date(8,  Month.June,      2010), 0.524974),
                    new Datum(new Date(15, Month.June,      2010), 0.549942),
                    new Datum(new Date(22, Month.June,      2010), 0.549913),
                    new Datum(new Date(1,  Month.July,      2010), 0.574864),
                    new Datum(new Date(2,  Month.August,    2010), 0.624668),
                    new Datum(new Date(1,  Month.September, 2010), 0.724338),
                    new Datum(new Date(16, Month.September, 2010), 0.769461),
                    new Datum(new Date(1,  Month.December,  2010), 0.997501),
                    //{ Date( 16, December, 2010), 0.838164 ),
                    new Datum(new Date(17, Month.March,     2011), 0.916996),
                    new Datum(new Date(16, Month.June,      2011), 0.984339),
                    new Datum(new Date(22, Month.September, 2011),  1.06085),
                    new Datum(new Date(22, Month.December,  2011), 1.141788),
                    new Datum(new Date(1,  Month.June,      2012), 1.504426),
                    new Datum(new Date(3,  Month.June,      2013),  1.92064),
                    new Datum(new Date(2,  Month.June,      2014), 2.290824),
                    new Datum(new Date(1,  Month.June,      2015), 2.614394),
                    new Datum(new Date(1,  Month.June,      2016), 2.887445),
                    new Datum(new Date(1,  Month.June,      2017), 3.122128),
                    new Datum(new Date(1,  Month.June,      2018), 3.322511),
                    new Datum(new Date(3,  Month.June,      2019), 3.483997),
                    new Datum(new Date(1,  Month.June,      2020), 3.616896),
                    new Datum(new Date(1,  Month.June,      2022),   3.8281),
                    new Datum(new Date(2,  Month.June,      2025),   4.0341),
                    new Datum(new Date(3,  Month.June,      2030), 4.070854),
                    new Datum(new Date(1,  Month.June,      2035), 4.023202),
                    new Datum(new Date(1,  Month.June,      2040), 3.954748),
                    new Datum(new Date(1,  Month.June,      2050), 3.870953),
                    new Datum(new Date(1,  Month.June,      2060),  3.85298),
                    new Datum(new Date(2,  Month.June,      2070), 3.757542),
                    new Datum(new Date(3,  Month.June,      2080), 3.651379)
                };
                int nominalDataLength = 33 - 1;

                List <Date>   nomD = new List <Date>();
                List <double> nomR = new List <double>();

                for (int i = 0; i < nominalDataLength; i++)
                {
                    nomD.Add(nominalData[i].date);
                    nomR.Add(nominalData[i].rate / 100.0);
                }
                YieldTermStructure nominalTS = new InterpolatedZeroCurve <Linear>(nomD, nomR, dcNominal);

                nominalUK.linkTo(nominalTS);

                // now build the zero inflation curve
                observationLag                   = new Period(2, TimeUnit.Months);
                contractObservationLag           = new Period(3, TimeUnit.Months);
                contractObservationInterpolation = InterpolationType.Flat;

                Datum[] zciisData =
                {
                    new Datum(new Date(1, Month.June, 2011), 3.087),
                    new Datum(new Date(1, Month.June, 2012),  3.12),
                    new Datum(new Date(1, Month.June, 2013), 3.059),
                    new Datum(new Date(1, Month.June, 2014),  3.11),
                    new Datum(new Date(1, Month.June, 2015),  3.15),
                    new Datum(new Date(1, Month.June, 2016), 3.207),
                    new Datum(new Date(1, Month.June, 2017), 3.253),
                    new Datum(new Date(1, Month.June, 2018), 3.288),
                    new Datum(new Date(1, Month.June, 2019), 3.314),
                    new Datum(new Date(1, Month.June, 2020), 3.401),
                    new Datum(new Date(1, Month.June, 2022), 3.458),
                    new Datum(new Date(1, Month.June, 2025),  3.52),
                    new Datum(new Date(1, Month.June, 2030), 3.655),
                    new Datum(new Date(1, Month.June, 2035), 3.668),
                    new Datum(new Date(1, Month.June, 2040), 3.695),
                    new Datum(new Date(1, Month.June, 2050), 3.634),
                    new Datum(new Date(1, Month.June, 2060), 3.629),
                };
                zciisDataLength = 17;
                for (int i = 0; i < zciisDataLength; i++)
                {
                    zciisD.Add(zciisData[i].date);
                    zciisR.Add(zciisData[i].rate);
                }

                // now build the helpers ...
                List <BootstrapHelper <ZeroInflationTermStructure> > helpers = makeHelpers(zciisData, zciisDataLength, ii,
                                                                                           observationLag, calendar, convention, dcZCIIS);

                // we can use historical or first ZCIIS for this
                // we know historical is WAY off market-implied, so use market implied flat.
                baseZeroRate = zciisData[0].rate / 100.0;
                PiecewiseZeroInflationCurve <Linear> pCPIts = new PiecewiseZeroInflationCurve <Linear>(
                    evaluationDate, calendar, dcZCIIS, observationLag, ii.frequency(), ii.interpolated(), baseZeroRate,
                    new Handle <YieldTermStructure>(nominalTS), helpers);

                pCPIts.recalculate();
                cpiUK.linkTo(pCPIts);
                hii.linkTo(ii);

                // make sure that the index has the latest zero inflation term structure
                hcpi.linkTo(pCPIts);

                // cpi CF price surf data
                Period[] cfMat = { new Period(3,  TimeUnit.Years),
                                   new Period(5,  TimeUnit.Years),
                                   new Period(7,  TimeUnit.Years),
                                   new Period(10, TimeUnit.Years),
                                   new Period(15, TimeUnit.Years),
                                   new Period(20, TimeUnit.Years),
                                   new Period(30, TimeUnit.Years) };
                double[] cStrike = { 3, 4, 5, 6 };
                double[] fStrike = { -1, 0, 1, 2 };
                int      ncStrikes = 4, nfStrikes = 4, ncfMaturities = 7;

                double[][] cPrice =
                {
                    new double[4] {
                        227.6, 100.27, 38.8, 14.94
                    },
                    new double[4] {
                        345.32, 127.9, 40.59, 14.11
                    },
                    new double[4] {
                        477.95, 170.19, 50.62, 16.88
                    },
                    new double[4] {
                        757.81, 303.95, 107.62, 43.61
                    },
                    new double[4] {
                        1140.73, 481.89, 168.4, 63.65
                    },
                    new double[4] {
                        1537.6, 607.72, 172.27, 54.87
                    },
                    new double[4] {
                        2211.67, 839.24, 184.75, 45.03
                    }
                };

                double[][] fPrice =
                {
                    new double[4] {
                        15.62, 28.38, 53.61, 104.6
                    },
                    new double[4] {
                        21.45, 36.73, 66.66, 129.6
                    },
                    new double[4] {
                        24.45, 42.08, 77.04, 152.24
                    },
                    new double[4] {
                        39.25, 63.52, 109.2, 203.44
                    },
                    new double[4] {
                        36.82, 63.62, 116.97, 232.73
                    },
                    new double[4] {
                        39.7, 67.47, 121.79, 238.56
                    },
                    new double[4] {
                        41.48, 73.9, 139.75, 286.75
                    }
                };

                // now load the data into vector and Matrix classes
                cStrikesUK     = new List <double>();
                fStrikesUK     = new List <double>();
                cfMaturitiesUK = new List <Period>();
                for (int i = 0; i < ncStrikes; i++)
                {
                    cStrikesUK.Add(cStrike[i]);
                }
                for (int i = 0; i < nfStrikes; i++)
                {
                    fStrikesUK.Add(fStrike[i]);
                }
                for (int i = 0; i < ncfMaturities; i++)
                {
                    cfMaturitiesUK.Add(cfMat[i]);
                }
                cPriceUK = new Matrix(ncStrikes, ncfMaturities);
                fPriceUK = new Matrix(nfStrikes, ncfMaturities);
                for (int i = 0; i < ncStrikes; i++)
                {
                    for (int j = 0; j < ncfMaturities; j++)
                    {
                        (cPriceUK)[i, j] = cPrice[j][i] / 10000.0;
                    }
                }
                for (int i = 0; i < nfStrikes; i++)
                {
                    for (int j = 0; j < ncfMaturities; j++)
                    {
                        (fPriceUK)[i, j] = fPrice[j][i] / 10000.0;
                    }
                }
            }
Example #26
0
            // setup
            public CommonVars()
            {
                // option variables
                nominals = new List <double>()
                {
                    1000000
                };
                frequency = Frequency.Annual;
                // usual setup
                volatility = 0.01;
                length     = 7;
                calendar   = new UnitedKingdom();
                convention = BusinessDayConvention.ModifiedFollowing;
                Date today = new Date(13, Month.August, 2007);

                evaluationDate = calendar.adjust(today);
                Settings.setEvaluationDate(evaluationDate);
                settlementDays = 0;
                fixingDays     = 0;
                settlement     = calendar.advance(today, settlementDays, TimeUnit.Days);
                startDate      = settlement;
                dc             = new Thirty360();

                // yoy index
                //      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, -999.0, -999 };
                // link from yoy index to yoy TS
                bool interp = false;

                iir = new YYUKRPIr(interp, hy);
                for (int i = 0; i < rpiSchedule.Count; i++)
                {
                    iir.addFixing(rpiSchedule[i], fixData[i]);
                }

                YieldTermStructure nominalFF = new FlatForward(evaluationDate, 0.05, new ActualActual());

                nominalTS.linkTo(nominalFF);

                // now build the YoY inflation curve
                Period observationLag = new Period(2, TimeUnit.Months);

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

                // now build the helpers ...
                List <BootstrapHelper <YoYInflationTermStructure> > helpers =
                    makeHelpers(yyData, yyData.Length, iir,
                                observationLag,
                                calendar, convention, 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();
                yoyTS = pYYTS as YoYInflationTermStructure;


                // make sure that the index has the latest yoy term structure
                hy.linkTo(pYYTS);
            }
Example #27
0
        public void testInstrumentEquality()
        {
            // Testing inflation capped/floored coupon against inflation capfloor instrument...

            CommonVars vars = new CommonVars();

            int[] lengths = { 1, 2, 3, 5, 7, 10, 15, 20 };
            // vol is low ...
            double[] strikes = { 0.01, 0.025, 0.029, 0.03, 0.031, 0.035, 0.07 };
            // yoy inflation vol is generally very low
            double[] vols = { 0.001, 0.005, 0.010, 0.015, 0.020 };

            // this is model independent
            // capped coupon = fwd - cap, and fwd = swap(0)
            // floored coupon = fwd + floor
            for (int whichPricer = 0; whichPricer < 3; whichPricer++)
            {
                for (int i = 0; i < lengths.Length; i++)
                {
                    for (int j = 0; j < strikes.Length; j++)
                    {
                        for (int k = 0; k < vols.Length; k++)
                        {
                            List <CashFlow> leg = vars.makeYoYLeg(vars.evaluationDate, lengths[i]);

                            Instrument cap = vars.makeYoYCapFloor(CapFloorType.Cap,
                                                                  leg, strikes[j], vols[k], whichPricer);

                            Instrument floor = vars.makeYoYCapFloor(CapFloorType.Floor,
                                                                    leg, strikes[j], vols[k], whichPricer);

                            Date     from        = vars.nominalTS.link.referenceDate();
                            Date     to          = from + new Period(lengths[i], TimeUnit.Years);
                            Schedule yoySchedule = new MakeSchedule().from(from).to(to)
                                                   .withTenor(new Period(1, TimeUnit.Years))
                                                   .withCalendar(new UnitedKingdom())
                                                   .withConvention(BusinessDayConvention.Unadjusted)
                                                   .backwards().value();

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

                            Handle <YieldTermStructure> hTS = new Handle <YieldTermStructure>(vars.nominalTS);
                            IPricingEngine sppe             = new DiscountingSwapEngine(hTS);
                            swap.setPricingEngine(sppe);

                            List <CashFlow> leg2 = vars.makeYoYCapFlooredLeg(whichPricer, from,
                                                                             lengths[i],
                                                                             new InitializedList <double>(lengths[i], strikes[j]), //cap
                                                                             new List <double>(),                                  //floor
                                                                             vols[k],
                                                                             1.0,                                                  // gearing
                                                                             0.0);                                                 // spread

                            List <CashFlow> leg3 = vars.makeYoYCapFlooredLeg(whichPricer, from,
                                                                             lengths[i],
                                                                             new List <double>(),                                  // cap
                                                                             new InitializedList <double>(lengths[i], strikes[j]), //floor
                                                                             vols[k],
                                                                             1.0,                                                  // gearing
                                                                             0.0);                                                 // spread

                            // N.B. nominals are 10e6
                            double capped = CashFlows.npv(leg2, vars.nominalTS, false);
                            if (Math.Abs(capped - (swap.NPV() - cap.NPV())) > 1.0e-6)
                            {
                                QAssert.Fail(
                                    "capped coupon != swap(0) - cap:\n"
                                    + "    length:      " + lengths[i] + " years\n"
                                    + "    volatility:  " + vols[k] + "\n"
                                    + "    strike:      " + strikes[j] + "\n"
                                    + "    cap value:   " + cap.NPV() + "\n"
                                    + "    swap value:  " + swap.NPV() + "\n"
                                    + "   capped coupon " + capped);
                            }


                            // N.B. nominals are 10e6
                            double floored = CashFlows.npv(leg3, vars.nominalTS, false);
                            if (Math.Abs(floored - (swap.NPV() + floor.NPV())) > 1.0e-6)
                            {
                                QAssert.Fail(
                                    "floored coupon != swap(0) + floor :\n"
                                    + "    length:      " + lengths[i] + " years\n"
                                    + "    volatility:  " + vols[k] + "\n"
                                    + "    strike:      " + strikes[j] + "\n"
                                    + "    floor value: " + floor.NPV() + "\n"
                                    + "    swap value:  " + swap.NPV() + "\n"
                                    + "  floored coupon " + floored);
                            }
                        }
                    }
                }
            }
            // remove circular refernce
            vars.hy.linkTo(null);
        }
Example #28
0
        public void testFairUpfront()
        {
            // Testing fair-upfront calculation for credit-default swaps...

            using (SavedSettings backup = new SavedSettings())
            {
                // Initialize curves
                Calendar calendar = new TARGET();
                Date     today    = calendar.adjust(Date.Today);
                Settings.setEvaluationDate(today);

                Handle <Quote> hazardRate = new Handle <Quote>(new SimpleQuote(0.01234));
                RelinkableHandle <DefaultProbabilityTermStructure> probabilityCurve =
                    new RelinkableHandle <DefaultProbabilityTermStructure>();
                probabilityCurve.linkTo(new FlatHazardRate(0, calendar, hazardRate, new Actual360()));

                RelinkableHandle <YieldTermStructure> discountCurve =
                    new RelinkableHandle <YieldTermStructure>();
                discountCurve.linkTo(new FlatForward(today, 0.06, new Actual360()));

                // Build the schedule
                Date issueDate = today;
                Date maturity  = calendar.advance(issueDate, 10, TimeUnit.Years);
                BusinessDayConvention convention = BusinessDayConvention.Following;

                Schedule schedule =
                    new MakeSchedule().from(issueDate)
                    .to(maturity)
                    .withFrequency(Frequency.Quarterly)
                    .withCalendar(calendar)
                    .withTerminationDateConvention(convention)
                    .withRule(DateGeneration.Rule.TwentiethIMM).value();

                // Build the CDS
                double     fixedRate    = 0.05;
                double     upfront      = 0.001;
                DayCounter dayCount     = new Actual360();
                double     notional     = 10000.0;
                double     recoveryRate = 0.4;

                IPricingEngine engine = new MidPointCdsEngine(probabilityCurve, recoveryRate, discountCurve, true);

                CreditDefaultSwap cds = new CreditDefaultSwap(Protection.Side.Seller, notional, upfront, fixedRate,
                                                              schedule, convention, dayCount, true, true);
                cds.setPricingEngine(engine);

                double fairUpfront = cds.fairUpfront();

                CreditDefaultSwap fairCds = new CreditDefaultSwap(Protection.Side.Seller, notional,
                                                                  fairUpfront, fixedRate, schedule, convention, dayCount, true, true);
                fairCds.setPricingEngine(engine);

                double fairNPV   = fairCds.NPV();
                double tolerance = 1e-10;

                if (Math.Abs(fairNPV) > tolerance)
                {
                    Assert.Fail(
                        "Failed to reproduce null NPV with calculated fair upfront\n"
                        + "    calculated upfront: " + fairUpfront + "\n"
                        + "    calculated NPV:     " + fairNPV);
                }

                // same with null upfront to begin with
                upfront = 0.0;
                CreditDefaultSwap cds2 = new CreditDefaultSwap(Protection.Side.Seller, notional, upfront, fixedRate,
                                                               schedule, convention, dayCount, true, true);
                cds2.setPricingEngine(engine);

                fairUpfront = cds2.fairUpfront();

                CreditDefaultSwap fairCds2 = new CreditDefaultSwap(Protection.Side.Seller, notional,
                                                                   fairUpfront, fixedRate, schedule, convention, dayCount, true, true);
                fairCds2.setPricingEngine(engine);

                fairNPV = fairCds2.NPV();

                if (Math.Abs(fairNPV) > tolerance)
                {
                    Assert.Fail(
                        "Failed to reproduce null NPV with calculated fair upfront\n"
                        + "    calculated upfront: " + fairUpfront + "\n"
                        + "    calculated NPV:     " + fairNPV);
                }
            }
        }
Example #29
0
        public void GenerateButton_Click(object sender, RoutedEventArgs e)
        {
            if (App.ISADMIN == false)
            {
                //If the user is not an admin, they are not allowed to create a schedule
                PermissionController pc = new PermissionController();
                Permission           p  = pc.getPermissions();
                if (p.GenerateSchedule == false)
                {
                    MessageBoxButton button = MessageBoxButton.OK;
                    MessageBoxImage  icon   = MessageBoxImage.Error;
                    System.Windows.MessageBox.Show("Sorry! You do not have permission to generate a schedule", "Error", button, icon);
                }
            }
            else
            {
                //Create a progress bar to track the progress of the schedule building
                System.Windows.Controls.ProgressBar pBar = new System.Windows.Controls.ProgressBar();
                pBar.Visibility = Visibility.Visible;

                ScheduleController sc = new ScheduleController();
                Schedule           t  = sc.getScheduleByDate(DateTime.Today);
                //Update the progress bar
                this.pBar.Value = 20;
                if (t.Id != null)
                {
                    MessageBoxImage  icon   = MessageBoxImage.Warning;
                    MessageBoxButton button = MessageBoxButton.YesNo;
                    MessageBoxResult result = System.Windows.MessageBox.Show("There was already a schedule made today. Would you like to overwrite it?", "Capstone Employee Scheduler", button, icon);
                    if (result == MessageBoxResult.No)
                    {
                        return;
                    }
                    else if (result == MessageBoxResult.Yes)
                    {
                        //If they choose to overwrite the schedule, delete the old one
                        this.pBar.Value = 30;
                        sc.deleteSchedule(t.Id);
                    }
                }
                //Update the progress bar
                this.pBar.Value = 40;

                //Create a new schedule with all the users and roles in the database
                Schedule       s     = new Schedule();
                MakeSchedule   ms    = new MakeSchedule();
                List <User>    users = new List <User>();
                UserController uc    = new UserController();
                this.pBar.Value = 50;
                //Get all the users without roles beforehand to speed up scheduling process
                users           = uc.getAllUsersWithRoleId();
                this.pBar.Value = 60;
                List <int> rolecounts = new List <int>();
                int        q;
                foreach (User u in users)
                {
                    q = u.Roles.Count();
                    rolecounts.Add(q);
                }
                this.pBar.Value = 70;

                /*  if (rolecounts.Contains(1))
                 * {
                 *    MessageBoxImage icon = MessageBoxImage.Warning;
                 *    MessageBoxButton button = MessageBoxButton.OK;
                 *    System.Windows.MessageBox.Show("One or more employees are only trained in one role. This may cause scheudling problems", "Capstone Employee Scheduler", button, icon);
                 * }
                 */
                this.pBar.Value = 80;
                ms.Generate(users, DateTime.Today);
                this.pBar.Value = 100;
                //Display the schedule once it is generated
                ScheduleWindow x = new ScheduleWindow(DateTime.Today);
                x.ShowDialog();
                //Reset the progress bar
                this.pBar.Value = 0;
            }
        }
Example #30
0
        private void FutureSchedules_Click(object sender, RoutedEventArgs e)
        {
            this.futureBar.Value = 0;
            //Create a progress bar to track the progress of the schedule building
            System.Windows.Forms.MessageBox.Show("Generating 7 schedules. This will take a while.");
            System.Windows.Controls.ProgressBar futureBar = new System.Windows.Controls.ProgressBar();
            futureBar.Visibility = Visibility.Visible;
            List <User>    users = new List <User>();
            UserController uc    = new UserController();

            //Get all the users with the role ids before loop to speed up scheduling process
            users = uc.getAllUsersWithRoleId();
            this.futureBar.Value = 50;

            //Create a new schedule 7 times
            for (int i = 0; i < 7; i++)
            {
                ScheduleController sc = new ScheduleController();
                //View the 7 future schedules to see if any schedules have already been made that interfere with the weeks worth of schedules being generated.
                Schedule t = sc.getScheduleByDate(DateTime.Today.AddDays(i));
                if (t.Id != null)
                {
                    //MessageBoxImage icon = MessageBoxImage.Warning;
                    //MessageBoxButton button = MessageBoxButton.YesNo;
                    ////Tells the user that the future schedules created will be overwritten
                    //MessageBoxResult result = System.Windows.MessageBox.Show("There was already a schedule made today. All schedules already created will be overwritten.", "Capstone Employee Scheduler", button, icon);
                    //if (result == MessageBoxResult.No)
                    //{
                    //    return;
                    //}
                    //else if (result == MessageBoxResult.Yes)
                    //{
                    //    //If they hit yes, delete the schedule
                    //    this.futureBar.Value = 30;
                    sc.deleteSchedule(t.Id);
                    //}
                }
                Schedule s = new Schedule();
                s.ScheduleDate = DateTime.Today.AddDays(i);
                MakeSchedule ms = new MakeSchedule();
                //Update progress bar

                /*List<int> rolecounts = new List<int>();
                 * int q;
                 * foreach (User u in users)
                 * {
                 *  q = u.Roles.Count();
                 *  rolecounts.Add(q);
                 * }
                 * this.futureBar.Value = 60;
                 * if (rolecounts.Contains(1))
                 * {
                 *  MessageBoxImage icon = MessageBoxImage.Warning;
                 *  MessageBoxButton button = MessageBoxButton.OK;
                 *  System.Windows.MessageBox.Show("One or more employees are only trained in one role. This may cause scheudling problems", "Capstone Employee Scheduler", button, icon);
                 * }
                 */
                ms.Generate(users, DateTime.Today.AddDays(i));
            }
            this.futureBar.Value = 100;
        }