/// <summary>
        ///
        /// </summary>
        /// <param name="capFloorLeg"></param>
        /// <param name="fixingCalendar"></param>
        /// <param name="paymentCalendar"></param>
        /// <param name="spreadSchedule"></param>
        /// <param name="capOrFloorSchedule"></param>
        /// <param name="notionalSchedule"></param>
        /// <returns></returns>
        public static CapFloor GenerateDefinitionCashflows(IBusinessCalendar fixingCalendar,
                                                           IBusinessCalendar paymentCalendar,
                                                           CapFloorLegParametersRange_Old capFloorLeg,
                                                           Schedule spreadSchedule,
                                                           Schedule capOrFloorSchedule,
                                                           NonNegativeAmountSchedule notionalSchedule)

        {
            CapFloor capFloor = GenerateDefiniton(capFloorLeg, spreadSchedule, capOrFloorSchedule, notionalSchedule);

            if (null != spreadSchedule)
            {
                InterestRateStreamParametricDefinitionGenerator.SetSpreadSchedule(capFloor.capFloorStream, spreadSchedule);
            }
            if (null != notionalSchedule)
            {
                InterestRateStreamParametricDefinitionGenerator.SetNotionalSchedule(capFloor.capFloorStream, notionalSchedule);
            }
            if (null != capOrFloorSchedule)
            {
                if (capFloorLeg.CapOrFloor == CapFloorType.Cap)
                {
                    InterestRateStreamParametricDefinitionGenerator.SetCapRateSchedule(capFloor.capFloorStream, capOrFloorSchedule, true);
                }
                else
                {
                    InterestRateStreamParametricDefinitionGenerator.SetFloorRateSchedule(capFloor.capFloorStream, capOrFloorSchedule, true);
                }
            }
            capFloor.capFloorStream.cashflows = FixedAndFloatingRateStreamCashflowGenerator.GetCashflows(capFloor.capFloorStream, fixingCalendar, paymentCalendar);
            return(capFloor);
        }
        public static ValuationReport Generate(string valuationId, string baseParty,
                                               string tradeId, DateTime tradeDate,
                                               CapFloor capFloor, Market market, AssetValuation assetValuation)
        {
            var valuationReport = new ValuationReport
            {
                header = new NotificationMessageHeader
                {
                    messageId = new MessageId
                    {
                        Value
                            =
                                valuationId
                    }
                },
                market = market
            };
            //  Associate id with the valuation
            //
            var tradeValuationItem = new TradeValuationItem();

            valuationReport.tradeValuationItem = new[] { tradeValuationItem };
            var         trade       = new Trade();
            TradeHeader tradeHeader = CreateTradeHeader(tradeDate, tradeId);

            trade.tradeHeader = tradeHeader;
            XsdClassesFieldResolver.TradeSetCapFloor(trade, capFloor);
            tradeValuationItem.Items        = new object[] { trade };
            tradeValuationItem.valuationSet = new ValuationSet
            {
                baseParty      = PartyReferenceFactory.Create(baseParty),
                assetValuation = new[] { assetValuation }
            };
            return(valuationReport);
        }
Exemple #3
0
            public CapFloor makeCapFloor(CapFloorType type, List <CashFlow> leg, double capStrike,
                                         double floorStrike, double vol)
            {
                CapFloor result = null;

                switch (type)
                {
                case CapFloorType.Cap:
                    result = new Cap(leg, new InitializedList <double>(1, capStrike));
                    break;

                case CapFloorType.Floor:
                    result = new Floor(leg, new InitializedList <double>(1, floorStrike));
                    break;

                case CapFloorType.Collar:
                    result = new Collar(leg, new InitializedList <double>(1, capStrike),
                                        new InitializedList <double>(1, floorStrike));
                    break;

                default:
                    Utils.QL_FAIL("unknown cap/floor type");
                    break;
                }
                result.setPricingEngine(makeEngine(vol));
                return(result);
            }
Exemple #4
0
 public static InterestRateStream GetReceiverStream(CapFloor capFloor, string baseParty)
 {
     if (capFloor.capFloorStream.receiverPartyReference.href == baseParty)
     {
         return(capFloor.capFloorStream);
     }
     throw new System.Exception($"No receiver stream was found for the specified receiver : '{baseParty}'");
 }
Exemple #5
0
        /// <summary>
        /// </summary>
        /// <returns></returns>
        public static CapFloor Create(InterestRateStream stream)
        {
            var result = new CapFloor {
                capFloorStream = stream
            };

            return(result);
        }
Exemple #6
0
        public static Money GetReceiveFutureValueOfAdditionalPayments(CapFloor capFloor, string baseParty)
        {
            var valueList = new List <MoneyBase>();

            if (null != capFloor.additionalPayment)
            {
                valueList.AddRange((from payment in capFloor.additionalPayment where baseParty == payment.receiverPartyReference.href select payment.paymentAmount));
            }
            return(MoneyHelper.Sum(valueList));
        }
Exemple #7
0
        public void testVega()
        {
            CommonVars vars = new CommonVars();

            int[]          lengths = { 1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 30 };
            double[]       vols    = { 0.01, 0.05, 0.10, 0.15, 0.20 };
            double[]       strikes = { 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 };
            CapFloorType[] types   = { CapFloorType.Cap, CapFloorType.Floor };

            Date   startDate = vars.termStructure.link.referenceDate();
            double shift     = 1e-8;
            double tolerance = 0.005;

            for (int i = 0; i < lengths.Length; i++)
            {
                for (int j = 0; j < vols.Length; j++)
                {
                    for (int k = 0; k < strikes.Length; k++)
                    {
                        for (int h = 0; h < types.Length; h++)
                        {
                            List <CashFlow> leg              = vars.makeLeg(startDate, lengths[i]);
                            CapFloor        capFloor         = vars.makeCapFloor(types[h], leg, strikes[k], vols[j]);
                            CapFloor        shiftedCapFloor2 = vars.makeCapFloor(types[h], leg, strikes[k], vols[j] + shift);
                            CapFloor        shiftedCapFloor1 = vars.makeCapFloor(types[h], leg, strikes[k], vols[j] - shift);

                            double value1 = shiftedCapFloor1.NPV();
                            double value2 = shiftedCapFloor2.NPV();

                            double numericalVega = (value2 - value1) / (2 * shift);


                            if (numericalVega > 1.0e-4)
                            {
                                double analyticalVega = (double)capFloor.result("vega");
                                double discrepancy    = Math.Abs(numericalVega - analyticalVega);
                                discrepancy /= numericalVega;
                                if (discrepancy > tolerance)
                                {
                                    QAssert.Fail(
                                        "failed to compute cap/floor vega:" +
                                        "\n   lengths:     " + new Period(lengths[j], TimeUnit.Years) +
                                        "\n   strike:      " + strikes[k] +
                                        "\n   types:       " + types[h] +
                                        "\n   calculated:  " + analyticalVega +
                                        "\n   expected:    " + numericalVega +
                                        "\n   discrepancy: " + discrepancy +
                                        "\n   tolerance:   " + tolerance);
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #8
0
        public static Money GetFutureValue(CapFloor capFloor, string baseParty)
        {
            var list = new List <Money>();
            InterestRateStream stream = capFloor.capFloorStream;
            Money futureValueOfStream = CashflowsHelper.GetForecastValue(stream.cashflows);

            list.AddRange(GetValue(stream.payerPartyReference.href, stream.receiverPartyReference.href, baseParty, futureValueOfStream));
            Money futureValueOfAdditionalPayments = GetValueOfAdditionalPayments(capFloor, baseParty);

            list.Add(futureValueOfAdditionalPayments);
            return(MoneyHelper.Sum(list));
        }
Exemple #9
0
        public static Money GetPresentValueOfAdditionalPayments(CapFloor capFloor, string baseParty)
        {
            var list = new List <Money>();

            if (null != capFloor.additionalPayment)
            {
                foreach (Payment payment in capFloor.additionalPayment)
                {
                    list.AddRange(GetValue(payment.payerPartyReference.href, payment.receiverPartyReference.href, baseParty, payment.presentValueAmount));
                }
            }
            return(MoneyHelper.Sum(list));
        }
        public static CapFloor GenerateDefiniton(CapFloorLegParametersRange_Old capFloorLeg,
                                                 Schedule spreadSchedule,
                                                 Schedule capOrFloorSchedule,
                                                 NonNegativeSchedule notionalSchedule)
        {
            InterestRateStream capFloorStream = InterestRateStreamParametricDefinitionGenerator.GenerateStreamDefinition(capFloorLeg);

            InterestRateStreamHelper.SetPayerAndReceiver(capFloorStream, capFloorLeg.Payer, capFloorLeg.Receiver);
            var capFloor = new CapFloor {
                capFloorStream = capFloorStream
            };

            return(capFloor);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="capFloorLeg"></param>
        /// <param name="nameSpace"></param>
        /// <param name="fixingCalendar"></param>
        /// <param name="paymentCalendar"></param>
        /// <param name="spreadSchedule"></param>
        /// <param name="capOrFloorSchedule"></param>
        /// <param name="notionalSchedule"></param>
        /// <returns></returns>
        public static CapFloor GenerateDefinitionCashflows(ILogger logger, ICoreCache cache,
                                                           string nameSpace,
                                                           IBusinessCalendar fixingCalendar,
                                                           IBusinessCalendar paymentCalendar,
                                                           CapFloorLegParametersRange capFloorLeg,
                                                           Schedule spreadSchedule,
                                                           Schedule capOrFloorSchedule,
                                                           NonNegativeAmountSchedule notionalSchedule)
        {
            if (paymentCalendar == null)
            {
                if (!string.IsNullOrEmpty(capFloorLeg.PaymentCalendar))
                {
                    var payCalendar = BusinessCentersHelper.Parse(capFloorLeg.PaymentCalendar);
                    paymentCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, payCalendar, nameSpace);
                }
            }
            if (fixingCalendar == null)
            {
                if (!string.IsNullOrEmpty(capFloorLeg.FixingCalendar))
                {
                    var fixCalendar = BusinessCentersHelper.Parse(capFloorLeg.FixingCalendar);
                    fixingCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, fixCalendar, nameSpace);
                }
            }
            CapFloor capFloor = GenerateDefiniton(capFloorLeg, spreadSchedule, capOrFloorSchedule, notionalSchedule);

            if (null != spreadSchedule)
            {
                InterestRateStreamParametricDefinitionGenerator.SetSpreadSchedule(capFloor.capFloorStream, spreadSchedule);
            }
            if (null != notionalSchedule)
            {
                InterestRateStreamParametricDefinitionGenerator.SetNotionalSchedule(capFloor.capFloorStream, notionalSchedule);
            }
            if (null != capOrFloorSchedule)
            {
                if (capFloorLeg.CapOrFloor == CapFloorType.Cap)
                {
                    InterestRateStreamParametricDefinitionGenerator.SetCapRateSchedule(capFloor.capFloorStream, capOrFloorSchedule, true);
                }
                else
                {
                    InterestRateStreamParametricDefinitionGenerator.SetFloorRateSchedule(capFloor.capFloorStream, capOrFloorSchedule, true);
                }
            }
            capFloor.capFloorStream.cashflows = FixedAndFloatingRateStreamCashflowGenerator.GetCashflows(capFloor.capFloorStream, fixingCalendar, paymentCalendar);
            return(capFloor);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="fixingCalendar"></param>
        /// <param name="paymentCalendar"></param>
        /// <param name="capFloorLeg"></param>
        /// <param name="spreadSchedule"></param>
        /// <param name="capOrFloorSchedule"></param>
        /// <param name="notionalSchedule"></param>
        /// <param name="marketEnvironment"></param>
        /// <param name="valuationDate"></param>
        /// <returns></returns>
        public static CapFloor GenerateDefinitionCashflowsAmounts(IBusinessCalendar fixingCalendar,
                                                                  IBusinessCalendar paymentCalendar,
                                                                  CapFloorLegParametersRange_Old capFloorLeg,
                                                                  Schedule spreadSchedule,
                                                                  Schedule capOrFloorSchedule,
                                                                  NonNegativeAmountSchedule notionalSchedule,
                                                                  ISwapLegEnvironment marketEnvironment,
                                                                  DateTime valuationDate)
        {
            CapFloor   capFloor = GenerateDefinitionCashflows(fixingCalendar, paymentCalendar, capFloorLeg, spreadSchedule, capOrFloorSchedule, notionalSchedule);
            IRateCurve payStreamDiscountingCurve = marketEnvironment.GetDiscountRateCurve();
            IRateCurve payStreamForecastCurve    = marketEnvironment.GetForecastRateCurve();

            FixedAndFloatingRateStreamCashflowGenerator.UpdateCashflowsAmounts(capFloor.capFloorStream, payStreamForecastCurve, payStreamDiscountingCurve, valuationDate);
            return(capFloor);
        }
Exemple #13
0
        public DiscretizedCapFloor(CapFloor.Arguments args,
            Date referenceDate,
            DayCounter dayCounter)
        {
            arguments_ = args;

              startTimes_= new InitializedList<double>(args.startDates.Count);
              for (int i = 0; i < startTimes_.Count; ++i)
              startTimes_[i] = dayCounter.yearFraction(referenceDate,
                                                       args.startDates[i]);

              endTimes_ = new InitializedList<double>(args.endDates.Count);
              for (int i = 0; i < endTimes_.Count; ++i)
              endTimes_[i] = dayCounter.yearFraction(referenceDate,
                                                     args.endDates[i]);
        }
 public static void UpdatePaymentsAmounts(IBusinessCalendar paymentCalendar,
                                          CapFloor capFloor,
                                          CapFloorLegParametersRange capFloorLeg,
                                          IRateCurve discountCurve,
                                          DateTime valuationDate)
 {
     foreach (Payment payment in capFloor.additionalPayment)
     {
         var date = AdjustedDateHelper.GetAdjustedDate(paymentCalendar, payment.paymentDate);
         if (date != null)
         {
             payment.discountFactor          = (decimal)discountCurve.GetDiscountFactor(valuationDate, (DateTime)date);
             payment.discountFactorSpecified = true;
             payment.presentValueAmount      = MoneyHelper.Mul(payment.paymentAmount, payment.discountFactor);
         }
     }
 }
Exemple #15
0
        public static Money GetPayFutureValue(CapFloor capFloor, string baseParty)
        {
            var list = new List <Money>();
            InterestRateStream stream = capFloor.capFloorStream;
            {
                Money presentValueOfStream = CashflowsHelper.GetForecastValue(stream.cashflows);

                if (baseParty == stream.payerPartyReference.href)
                {
                    list.Add(presentValueOfStream);
                }
            }
            Money payFutureValueOfAdditionalPayments = GetPayFutureValueOfAdditionalPayments(capFloor, baseParty);

            list.Add(payFutureValueOfAdditionalPayments);
            return(MoneyHelper.Sum(list));
        }
Exemple #16
0
 public static object CouponDataReport(CapFloor capFloor)
 {
     if (capFloor != null)
     {
         var coupons1 = capFloor.capFloorStream.cashflows.paymentCalculationPeriod.Length;
         var result   = new object[coupons1, 4];
         var index    = 0;
         foreach (var coupon1 in capFloor.capFloorStream.cashflows.paymentCalculationPeriod)
         {
             result[index, 0] = "CapFloor_Coupon_" + index;
             result[index, 1] = coupon1.adjustedPaymentDate;
             result[index, 2] = coupon1.discountFactor;
             result[index, 3] = coupon1.forecastPaymentAmount.amount;
             result[index, 4] = coupon1.forecastPaymentAmount.currency.Value;
             index++;
         }
         return(result);
     }
     return(null);
 }
Exemple #17
0
        public void testImpliedVolatility()
        {
            CommonVars vars = new CommonVars();

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

            CapFloorType[] types   = { CapFloorType.Cap, CapFloorType.Floor };
            double[]       strikes = { 0.02, 0.03, 0.04 };
            int[]          lengths = { 1, 5, 10 };

            // test data
            double[] rRates = { 0.02, 0.03, 0.04 };
            double[] vols   = { 0.01, 0.20, 0.30, 0.70, 0.90 };

            for (int k = 0; k < lengths.Length; k++)
            {
                List <CashFlow> leg = vars.makeLeg(vars.settlement, lengths[k]);

                for (int i = 0; i < types.Length; i++)
                {
                    for (int j = 0; j < strikes.Length; j++)
                    {
                        CapFloor capfloor = vars.makeCapFloor(types[i], leg, strikes[j], 0.0);

                        for (int n = 0; n < rRates.Length; n++)
                        {
                            for (int m = 0; m < vols.Length; m++)
                            {
                                double r = rRates[n];
                                double v = vols[m];
                                vars.termStructure.linkTo(Utilities.flatRate(vars.settlement, r, new Actual360()));
                                capfloor.setPricingEngine(vars.makeEngine(v));

                                double value   = capfloor.NPV();
                                double implVol = 0.0;

                                try {
                                    implVol = capfloor.impliedVolatility(value,
                                                                         vars.termStructure,
                                                                         0.10,
                                                                         tolerance,
                                                                         maxEvaluations);
                                } catch (Exception e) {
                                    // couldn't bracket?
                                    capfloor.setPricingEngine(vars.makeEngine(0.0));
                                    double value2 = capfloor.NPV();
                                    if (Math.Abs(value - value2) < tolerance)
                                    {
                                        // ok, just skip:
                                        continue;
                                    }

                                    // otherwise, report error
                                    QAssert.Fail("implied vol failure: " + typeToString(types[i]) +
                                                 "  strike:     " + strikes[j] +
                                                 "  risk-free:  " + r +
                                                 "  length:     " + lengths[k] + "Y" +
                                                 "  volatility: " + v + e.Message);
                                }
                                if (Math.Abs(implVol - v) > tolerance)
                                {
                                    // the difference might not matter
                                    capfloor.setPricingEngine(vars.makeEngine(implVol));
                                    double value2 = capfloor.NPV();
                                    if (Math.Abs(value - value2) > tolerance)
                                    {
                                        QAssert.Fail(
                                            typeToString(types[i]) + ":"
                                            + "    strike:           "
                                            + strikes[j] + "\n"
                                            + "    risk-free rate:   "
                                            + r + "\n"
                                            + "    length:         "
                                            + lengths[k] + " years\n\n"
                                            + "    original volatility: "
                                            + v + "\n"
                                            + "    price:               "
                                            + value + "\n"
                                            + "    implied volatility:  "
                                            + implVol + "\n"
                                            + "    corresponding price: " + value2);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #18
0
        public void testATMRate()
        {
            CommonVars vars = new CommonVars();

            int[]    lengths = { 1, 2, 3, 5, 7, 10, 15, 20 };
            double[] strikes = { 0.0, 0.03, 0.04, 0.05, 0.06, 0.07 };
            double[] vols    = { 0.01, 0.05, 0.10, 0.15, 0.20 };

            Date startDate = vars.termStructure.link.referenceDate();

            for (int i = 0; i < lengths.Length; i++)
            {
                List <CashFlow> leg      = vars.makeLeg(startDate, lengths[i]);
                Date            maturity = vars.calendar.advance(startDate, lengths[i], TimeUnit.Years, vars.convention);
                Schedule        schedule = new Schedule(startDate, maturity,
                                                        new Period(vars.frequency), vars.calendar,
                                                        vars.convention, vars.convention,
                                                        DateGeneration.Rule.Forward, false);

                for (int j = 0; j < strikes.Length; j++)
                {
                    for (int k = 0; k < vols.Length; k++)
                    {
                        CapFloor cap          = vars.makeCapFloor(CapFloorType.Cap, leg, strikes[j], vols[k]);
                        CapFloor floor        = vars.makeCapFloor(CapFloorType.Floor, leg, strikes[j], vols[k]);
                        double   capATMRate   = cap.atmRate(vars.termStructure);
                        double   floorATMRate = floor.atmRate(vars.termStructure);

                        if (!checkAbsError(floorATMRate, capATMRate, 1.0e-10))
                        {
                            QAssert.Fail(
                                "Cap ATM Rate and floor ATM Rate should be equal :\n"
                                + "   length:        " + lengths[i] + " years\n"
                                + "   volatility:    " + vols[k] + "\n"
                                + "   strike:        " + strikes[j] + "\n"
                                + "   cap ATM rate:  " + capATMRate + "\n"
                                + "   floor ATM rate:" + floorATMRate + "\n"
                                + "   relative Error:"
                                + Utilities.relativeError(capATMRate, floorATMRate, capATMRate) * 100 + "%");
                        }
                        VanillaSwap swap = new VanillaSwap(VanillaSwap.Type.Payer, vars.nominals[0],
                                                           schedule, floorATMRate,
                                                           vars.index.dayCounter(),
                                                           schedule, vars.index, 0.0,
                                                           vars.index.dayCounter());
                        swap.setPricingEngine((IPricingEngine)(
                                                  new DiscountingSwapEngine(vars.termStructure)));
                        double swapNPV = swap.NPV();
                        if (!checkAbsError(swapNPV, 0, 1.0e-10))
                        {
                            QAssert.Fail(
                                "the NPV of a Swap struck at ATM rate "
                                + "should be equal to 0:\n"
                                + "   length:        " + lengths[i] + " years\n"
                                + "   volatility:    " + vols[k] + "\n"
                                + "   ATM rate:      " + floorATMRate + "\n"
                                + "   swap NPV:      " + swapNPV);
                        }
                    }
                }
            }
        }
 public static void TradeSetCapFloor(Trade trade, CapFloor capFloor)
 {
     trade.Item            = capFloor;
     trade.ItemElementName = ItemChoiceType15.capFloor;
 }
Exemple #20
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(CapFloor obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
Exemple #21
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(CapFloor obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }