internal override DoubleArray computedBucketedCs01(ResolvedCdsTrade trade, IList <ResolvedCdsTrade> bucketCds, CreditRatesProvider ratesProvider, ReferenceData refData)
        {
            checkCdsBucket(trade, bucketCds);
            ResolvedCds product       = trade.Product;
            Currency    currency      = product.Currency;
            StandardId  legalEntityId = product.LegalEntityId;
            LocalDate   valuationDate = ratesProvider.ValuationDate;

            int         nBucket          = bucketCds.Count;
            DoubleArray impSp            = impliedSpread(bucketCds, ratesProvider, refData);
            NodalCurve  creditCurveBase  = Calibrator.calibrate(bucketCds, impSp, DoubleArray.filled(nBucket), CurveName.of("baseImpliedCreditCurve"), valuationDate, ratesProvider.discountFactors(currency), ratesProvider.recoveryRates(legalEntityId), refData);
            IsdaCreditDiscountFactors df = IsdaCreditDiscountFactors.of(currency, valuationDate, creditCurveBase);
            CreditRatesProvider       ratesProviderBase = ratesProvider.toImmutableCreditRatesProvider().toBuilder().creditCurves(ImmutableMap.of(Pair.of(legalEntityId, currency), LegalEntitySurvivalProbabilities.of(legalEntityId, df))).build();

            double[][]         res     = new double[nBucket][];
            PointSensitivities pointPv = Pricer.presentValueOnSettleSensitivity(trade, ratesProviderBase, refData);
            DoubleArray        vLambda = ratesProviderBase.singleCreditCurveParameterSensitivity(pointPv, legalEntityId, currency).Sensitivity;

            for (int i = 0; i < nBucket; i++)
            {
                PointSensitivities pointSp = Pricer.parSpreadSensitivity(bucketCds[i], ratesProviderBase, refData);
                res[i] = ratesProviderBase.singleCreditCurveParameterSensitivity(pointSp, legalEntityId, currency).Sensitivity.toArray();
            }
            DoubleMatrix          jacT  = MATRIX_ALGEBRA.getTranspose(DoubleMatrix.ofUnsafe(res));
            LUDecompositionResult luRes = DECOMPOSITION.apply(jacT);
            DoubleArray           vS    = luRes.solve(vLambda);

            return(vS);
        }
Beispiel #2
0
        //-------------------------------------------------------------------------
        public override NodalCurve calibrate(IList <ResolvedCdsTrade> calibrationCDSs, DoubleArray premiums, DoubleArray pointsUpfront, CurveName name, LocalDate valuationDate, CreditDiscountFactors discountFactors, RecoveryRates recoveryRates, ReferenceData refData)
        {
            int n = calibrationCDSs.Count;

            double[] guess = new double[n];
            double[] t     = new double[n];
            double[] lgd   = new double[n];
            for (int i = 0; i < n; i++)
            {
                LocalDate endDate = calibrationCDSs[i].Product.ProtectionEndDate;
                t[i]     = discountFactors.relativeYearFraction(endDate);
                lgd[i]   = 1d - recoveryRates.recoveryRate(endDate);
                guess[i] = (premiums.get(i) + pointsUpfront.get(i) / t[i]) / lgd[i];
            }
            DoubleArray   times        = DoubleArray.ofUnsafe(t);
            CurveMetadata baseMetadata = DefaultCurveMetadata.builder().xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.ZERO_RATE).curveName(name).dayCount(discountFactors.DayCount).build();
            NodalCurve    creditCurve  = n == 1 ? ConstantNodalCurve.of(baseMetadata, t[0], guess[0]) : InterpolatedNodalCurve.of(baseMetadata, times, DoubleArray.ofUnsafe(guess), CurveInterpolators.PRODUCT_LINEAR, CurveExtrapolators.FLAT, CurveExtrapolators.PRODUCT_LINEAR);

            for (int i = 0; i < n; i++)
            {
                System.Func <double, double> func = getPriceFunction(i, calibrationCDSs[i], premiums.get(i), pointsUpfront.get(i), valuationDate, creditCurve, discountFactors, recoveryRates, refData);
                double[] bracket  = BRACKER.getBracketedPoints(func, 0.8 * guess[i], 1.25 * guess[i], 0.0, double.PositiveInfinity);
                double   zeroRate = bracket[0] > bracket[1] ? ROOTFINDER.getRoot(func, bracket[1], bracket[0]) : ROOTFINDER.getRoot(func, bracket[0], bracket[1]); //Negative guess handled
                creditCurve = creditCurve.withParameter(i, zeroRate);
            }

            return(creditCurve);
        }
            public override Builder set(string propertyName, object newValue)
            {
                switch (propertyName.GetHashCode())
                {
                case 100346066:         // index
                    this.index = (PriceIndex)newValue;
                    break;

                case 113107279:         // valuationDate
                    this.valuationDate = (LocalDate)newValue;
                    break;

                case 95027439:         // curve
                    this.curve = (NodalCurve)newValue;
                    break;

                case -843784602:         // fixings
                    this.fixings = (LocalDateDoubleTimeSeries)newValue;
                    break;

                default:
                    throw new NoSuchElementException("Unknown property: " + propertyName);
                }
                return(this);
            }
Beispiel #4
0
            public double rpv01(NodalCurve creditCurve, PriceType cleanOrDirty)
            {
                double pv = 0.0;

                for (int i = startPeriodIndex; i < nPayments; i++)
                {
                    CreditCouponPaymentPeriod coupon = cds.PaymentPeriods.get(i);
                    double yc = offsetAccEnd[i];
                    double q  = Math.Exp(-creditCurve.yValue(yc) * yc);
                    pv += coupon.YearFraction * paymentDF[i] * q;
                }

                if (cds.PaymentOnDefault.AccruedInterest)
                {
                    double accPV = 0.0;
                    for (int i = startPeriodIndex; i < nPayments; i++)
                    {
                        accPV += calculateSinglePeriodAccrualOnDefault(i, creditCurve);
                    }
                    pv += accPV;
                }
                pv /= valuationDF;
                if (cleanOrDirty == PriceType.CLEAN)
                {
                    pv -= accYearFraction;
                }
                return(pv);
            }
Beispiel #5
0
        internal override DoubleArray computedBucketedCs01(ResolvedCdsTrade trade, IList <ResolvedCdsTrade> bucketCds, CreditRatesProvider ratesProvider, ReferenceData refData)
        {
            checkCdsBucket(trade, bucketCds);
            ResolvedCds product       = trade.Product;
            Currency    currency      = product.Currency;
            StandardId  legalEntityId = product.LegalEntityId;
            LocalDate   valuationDate = ratesProvider.ValuationDate;
            ImmutableCreditRatesProvider immutableRatesProvider = ratesProvider.toImmutableCreditRatesProvider();

            int nBucket = bucketCds.Count;

            double[]    res                    = new double[nBucket];
            DoubleArray impSp                  = impliedSpread(bucketCds, ratesProvider, refData);
            NodalCurve  creditCurveBase        = Calibrator.calibrate(bucketCds, impSp, DoubleArray.filled(nBucket), CurveName.of("baseImpliedCreditCurve"), valuationDate, ratesProvider.discountFactors(currency), ratesProvider.recoveryRates(legalEntityId), refData);
            Pair <StandardId, Currency> lePair = Pair.of(legalEntityId, currency);

            IsdaCreditDiscountFactors df = IsdaCreditDiscountFactors.of(currency, valuationDate, creditCurveBase);
            CreditRatesProvider       ratesProviderBase = immutableRatesProvider.toBuilder().creditCurves(ImmutableMap.of(lePair, LegalEntitySurvivalProbabilities.of(legalEntityId, df))).build();
            double pvBase = Pricer.presentValueOnSettle(trade, ratesProviderBase, PriceType.DIRTY, refData).Amount;

            for (int i = 0; i < nBucket; ++i)
            {
                double[] bumpedSp = impSp.toArray();
                bumpedSp[i] += bumpAmount;
                NodalCurve creditCurveBump                  = Calibrator.calibrate(bucketCds, DoubleArray.ofUnsafe(bumpedSp), DoubleArray.filled(nBucket), CurveName.of("bumpedImpliedCreditCurve"), valuationDate, ratesProvider.discountFactors(currency), ratesProvider.recoveryRates(legalEntityId), refData);
                IsdaCreditDiscountFactors dfBump            = IsdaCreditDiscountFactors.of(currency, valuationDate, creditCurveBump);
                CreditRatesProvider       ratesProviderBump = immutableRatesProvider.toBuilder().creditCurves(ImmutableMap.of(lePair, LegalEntitySurvivalProbabilities.of(legalEntityId, dfBump))).build();
                double pvBumped = Pricer.presentValueOnSettle(trade, ratesProviderBump, PriceType.DIRTY, refData).Amount;
                res[i] = (pvBumped - pvBase) / bumpAmount;
            }
            return(DoubleArray.ofUnsafe(res));
        }
        //-------------------------------------------------------------------------
        // bumping a node point at nodeExpiry
        private double nodeSensitivity(BlackFxOptionFlatVolatilities provider, CurrencyPair pair, ZonedDateTime expiry, double strike, double forward, double nodeExpiry)
        {
            NodalCurve  curve   = (NodalCurve)provider.Curve;
            DoubleArray xValues = curve.XValues;
            DoubleArray yValues = curve.YValues;

            int nData = xValues.size();
            int index = -1;

            for (int i = 0; i < nData; ++i)
            {
                if (Math.Abs(xValues.get(i) - nodeExpiry) < TOLERANCE)
                {
                    index = i;
                }
            }
            NodalCurve curveUp = curve.withYValues(yValues.with(index, yValues.get(index) + EPS));
            NodalCurve curveDw = curve.withYValues(yValues.with(index, yValues.get(index) - EPS));
            BlackFxOptionFlatVolatilities provUp = BlackFxOptionFlatVolatilities.of(CURRENCY_PAIR, VAL_DATE_TIME, curveUp);
            BlackFxOptionFlatVolatilities provDw = BlackFxOptionFlatVolatilities.of(CURRENCY_PAIR, VAL_DATE_TIME, curveDw);
            double volUp = provUp.volatility(pair, expiry, strike, forward);
            double volDw = provDw.volatility(pair, expiry, strike, forward);

            return(0.5 * (volUp - volDw) / EPS);
        }
Beispiel #7
0
            public double protectionLeg(NodalCurve creditCurve)
            {
                double ht0 = creditCurve.yValue(proLegIntPoints[0]) * proLegIntPoints[0];
                double rt0 = proYieldCurveRT[0];
                double b0  = proDF[0] * Math.Exp(-ht0);
                double pv  = 0d;

                for (int i = 1; i < nProPoints; ++i)
                {
                    double ht1  = creditCurve.yValue(proLegIntPoints[i]) * proLegIntPoints[i];
                    double rt1  = proYieldCurveRT[i];
                    double b1   = proDF[i] * Math.Exp(-ht1);
                    double dht  = ht1 - ht0;
                    double drt  = rt1 - rt0;
                    double dhrt = dht + drt;
                    // this is equivalent to the ISDA code without explicitly calculating the time step - it also handles the limit
                    double dPV;
                    if (Math.Abs(dhrt) < 1e-5)
                    {
                        dPV = dht * b0 * epsilon(-dhrt);
                    }
                    else
                    {
                        dPV = (b0 - b1) * dht / dhrt;
                    }
                    pv += dPV;
                    ht0 = ht1;
                    rt0 = rt1;
                    b0  = b1;
                }
                pv *= lgdDF;   // multiply by LGD and adjust to valuation date
                return(pv);
            }
Beispiel #8
0
        //-------------------------------------------------------------------------
        public override CurrencyAmount parallelCs01(ResolvedCdsTrade trade, IList <ResolvedCdsTrade> bucketCds, CreditRatesProvider ratesProvider, ReferenceData refData)
        {
            checkCdsBucket(trade, bucketCds);
            ResolvedCds product       = trade.Product;
            Currency    currency      = product.Currency;
            StandardId  legalEntityId = product.LegalEntityId;
            LocalDate   valuationDate = ratesProvider.ValuationDate;
            ImmutableCreditRatesProvider immutableRatesProvider = ratesProvider.toImmutableCreditRatesProvider();

            int         nBucket                = bucketCds.Count;
            DoubleArray impSp                  = impliedSpread(bucketCds, ratesProvider, refData);
            NodalCurve  creditCurveBase        = Calibrator.calibrate(bucketCds, impSp, DoubleArray.filled(nBucket), CurveName.of("baseImpliedCreditCurve"), valuationDate, ratesProvider.discountFactors(currency), ratesProvider.recoveryRates(legalEntityId), refData);
            Pair <StandardId, Currency> lePair = Pair.of(legalEntityId, currency);

            IsdaCreditDiscountFactors df = IsdaCreditDiscountFactors.of(currency, valuationDate, creditCurveBase);
            CreditRatesProvider       ratesProviderBase = immutableRatesProvider.toBuilder().creditCurves(ImmutableMap.of(lePair, LegalEntitySurvivalProbabilities.of(legalEntityId, df))).build();
            CurrencyAmount            pvBase            = Pricer.presentValueOnSettle(trade, ratesProviderBase, PriceType.DIRTY, refData);

            DoubleArray bumpedSp                        = DoubleArray.of(nBucket, i => impSp.get(i) + bumpAmount);
            NodalCurve  creditCurveBump                 = Calibrator.calibrate(bucketCds, bumpedSp, DoubleArray.filled(nBucket), CurveName.of("bumpedImpliedCreditCurve"), valuationDate, ratesProvider.discountFactors(currency), ratesProvider.recoveryRates(legalEntityId), refData);
            IsdaCreditDiscountFactors dfBump            = IsdaCreditDiscountFactors.of(currency, valuationDate, creditCurveBump);
            CreditRatesProvider       ratesProviderBump = immutableRatesProvider.toBuilder().creditCurves(ImmutableMap.of(lePair, LegalEntitySurvivalProbabilities.of(legalEntityId, dfBump))).build();
            CurrencyAmount            pvBumped          = Pricer.presentValueOnSettle(trade, ratesProviderBump, PriceType.DIRTY, refData);

            return(CurrencyAmount.of(currency, (pvBumped.Amount - pvBase.Amount) / bumpAmount));
        }
Beispiel #9
0
        public virtual void test_consistency_singleName()
        {
            IsdaCreditCurveDefinition        curveDefinition     = IsdaCreditCurveDefinition.of(CURVE_NAME, EUR, VALUATION_DATE, ACT_365F, CURVE_NODES_PS, true, true);
            LegalEntitySurvivalProbabilities creditCurveComputed = CALIBRATOR.calibrate(curveDefinition, MARKET_DATA_PS, RATES_PROVIDER, REF_DATA);
            NodalCurve curveComputed = (NodalCurve)creditCurveComputed.SurvivalProbabilities.findData(CURVE_NAME).get();
            double     computedIndex = curveComputed.Metadata.getInfo(CurveInfoType.CDS_INDEX_FACTOR);

            assertEquals(computedIndex, 93.0 / 97.0, TOL);
            IsdaCompliantCreditCurveCalibrator cdsCalibrator = FastCreditCurveCalibrator.standard();
            IList <CdsIsdaCreditCurveNode>     cdsNodes      = new List <CdsIsdaCreditCurveNode>();

            for (int i = 0; i < CURVE_NODES_PS.size(); ++i)
            {
                cdsNodes.Add(CdsIsdaCreditCurveNode.ofParSpread(CURVE_NODES_PS.get(i).Template, CURVE_NODES_PS.get(i).ObservableId, CURVE_NODES_PS.get(i).CdsIndexId));
                ParameterMetadata metadata = curveComputed.getParameterMetadata(i);
                assertTrue(metadata is ResolvedTradeParameterMetadata);
                ResolvedTradeParameterMetadata tradeMetadata = (ResolvedTradeParameterMetadata)metadata;
                assertTrue(tradeMetadata.Trade is ResolvedCdsIndexTrade);
            }
            IsdaCreditCurveDefinition        cdsCurveDefinition  = IsdaCreditCurveDefinition.of(CURVE_NAME, EUR, VALUATION_DATE, ACT_365F, cdsNodes, true, false);
            LegalEntitySurvivalProbabilities creditCurveExpected = cdsCalibrator.calibrate(cdsCurveDefinition, MARKET_DATA_PS, RATES_PROVIDER, REF_DATA);
            NodalCurve curveExpected = (NodalCurve)creditCurveExpected.SurvivalProbabilities.findData(CURVE_NAME).get();

            assertTrue(DoubleArrayMath.fuzzyEquals(curveComputed.XValues.toArray(), curveExpected.XValues.toArray(), TOL));
            assertTrue(DoubleArrayMath.fuzzyEquals(curveComputed.YValues.toArray(), curveExpected.YValues.toArray(), TOL));
            assertEquals(curveComputed.Metadata.getInfo(CurveInfoType.JACOBIAN), curveExpected.Metadata.getInfo(CurveInfoType.JACOBIAN));
        }
Beispiel #10
0
        /// <summary>
        /// Creates an instance from year fraction and zero rate values.
        /// </summary>
        /// <param name="currency">  the currency </param>
        /// <param name="valuationDate">  the valuation date </param>
        /// <param name="curveName">  the curve name </param>
        /// <param name="yearFractions">  the year fractions </param>
        /// <param name="zeroRates">  the zero rates </param>
        /// <param name="dayCount">  the day count </param>
        /// <returns> the instance </returns>
        public static IsdaCreditDiscountFactors of(Currency currency, LocalDate valuationDate, CurveName curveName, DoubleArray yearFractions, DoubleArray zeroRates, DayCount dayCount)
        {
            ArgChecker.notNull(yearFractions, "yearFractions");
            ArgChecker.notNull(zeroRates, "zeroRates");
            DefaultCurveMetadata metadata = DefaultCurveMetadata.builder().xValueType(YEAR_FRACTION).yValueType(ZERO_RATE).curveName(curveName).dayCount(dayCount).build();
            NodalCurve           curve    = (yearFractions.size() == 1 && zeroRates.size() == 1) ? ConstantNodalCurve.of(metadata, yearFractions.get(0), zeroRates.get(0)) : InterpolatedNodalCurve.of(metadata, yearFractions, zeroRates, CurveInterpolators.PRODUCT_LINEAR, CurveExtrapolators.FLAT, CurveExtrapolators.PRODUCT_LINEAR);

            return(new IsdaCreditDiscountFactors(currency, valuationDate, curve));
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @ImmutableConstructor private SimplePriceIndexValues(com.opengamma.strata.basics.index.PriceIndex index, java.time.LocalDate valuationDate, com.opengamma.strata.market.curve.NodalCurve curve, com.opengamma.strata.collect.timeseries.LocalDateDoubleTimeSeries fixings)
        private SimplePriceIndexValues(PriceIndex index, LocalDate valuationDate, NodalCurve curve, LocalDateDoubleTimeSeries fixings)
        {
            ArgChecker.isFalse(fixings.Empty, "Fixings must not be empty");
            curve.Metadata.XValueType.checkEquals(ValueType.MONTHS, "Incorrect x-value type for price curve");
            curve.Metadata.YValueType.checkEquals(ValueType.PRICE_INDEX, "Incorrect y-value type for price curve");
            this.index         = ArgChecker.notNull(index, "index");
            this.valuationDate = ArgChecker.notNull(valuationDate, "valuationDate");
            this.fixings       = ArgChecker.notNull(fixings, "fixings");
            this.curve         = ArgChecker.notNull(curve, "curve");
        }
Beispiel #12
0
 public System.Func <double, double> getPointFunction(int index, NodalCurve creditCurve)
 {
     return((double?x) =>
     {
         NodalCurve cc = creditCurve.withParameter(index, x.Value);
         double rpv01 = this.rpv01(cc, PriceType.CLEAN);
         double pro = protectionLeg(cc);
         return pro - fracSpread * rpv01 - puf;
     });
 }
Beispiel #13
0
        //-------------------------------------------------------------------------
        // restricted constructor
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @ImmutableConstructor private InflationNodalCurve(NodalCurve curve, com.opengamma.strata.collect.array.DoubleArray seasonality, com.opengamma.strata.market.ShiftType adjustmentType)
        private InflationNodalCurve(NodalCurve curve, DoubleArray seasonality, ShiftType adjustmentType)
        {
            this.underlying  = curve;
            this.seasonality = seasonality;
            this.xFixing     = curve.XValues.get(0);
            this.yFixing     = curve.YValues.get(0);
            int i = seasonalityIndex(xFixing);

            ArgChecker.isTrue(adjustmentType.applyShift(yFixing, seasonality.get(i)) - yFixing < 1.0E-10, "Fixing value should be unadjusted");
            this.adjustmentType = adjustmentType;
        }
Beispiel #14
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @ImmutableConstructor private IsdaCreditDiscountFactors(com.opengamma.strata.basics.currency.Currency currency, java.time.LocalDate valuationDate, com.opengamma.strata.market.curve.NodalCurve curve)
        private IsdaCreditDiscountFactors(Currency currency, LocalDate valuationDate, NodalCurve curve)
        {
            ArgChecker.notNull(currency, "currency");
            ArgChecker.notNull(valuationDate, "valuationDate");
            ArgChecker.notNull(curve, "curve");
            DayCount dayCount = curve.Metadata.findInfo(DAY_COUNT).orElseThrow(() => new System.ArgumentException("Incorrect curve metadata, missing DayCount"));

            this.currency      = currency;
            this.valuationDate = valuationDate;
            this.curve         = curve;
            this.dayCount      = dayCount;
        }
        // compute the sum of the product of times and rates
        private double sumProduct(NodalCurve curveInt)
        {
            double      result      = 0.0;
            DoubleArray x           = curveInt.XValues;
            DoubleArray y           = curveInt.YValues;
            int         nbNodePoint = x.size();

            for (int i = 0; i < nbNodePoint; i++)
            {
                result += x.get(i) * y.get(i);
            }
            return(result);
        }
Beispiel #16
0
        public virtual void pricePufTest()
        {
            double              premium       = 150d * ONE_BP;
            Cds                 product       = Cds.of(BUY, LEGAL_ENTITY, GBP, 1.0e6, START_DATE, END_DATE, Frequency.P3M, DEFAULT_CALENDAR, premium);
            TradeInfo           info          = TradeInfo.builder().tradeDate(TODAY).settlementDate(product.SettlementDateOffset.adjust(TODAY, REF_DATA)).build();
            ResolvedCdsTrade    trade         = CdsTrade.builder().product(product).info(info).build().resolve(REF_DATA);
            NodalCurve          cc            = CALIB.calibrate(ImmutableList.of(trade), DoubleArray.of(0.0123), DoubleArray.of(0.0), CurveName.of("test"), TODAY, DSC_CURVE, REC_RATES, REF_DATA);
            CreditRatesProvider rates         = RATES_PROVIDER.toImmutableCreditRatesProvider().toBuilder().creditCurves(ImmutableMap.of(Pair.of(LEGAL_ENTITY, GBP), LegalEntitySurvivalProbabilities.of(LEGAL_ENTITY, IsdaCreditDiscountFactors.of(GBP, TODAY, cc)))).build();
            double              pointsUpFront = CONV.pointsUpfront(trade, rates, REF_DATA);
            double              cleanPrice    = CONV.cleanPrice(trade, rates, REF_DATA);
            double              cleanPriceRe  = CONV.cleanPriceFromPointsUpfront(pointsUpFront);

            assertEquals(cleanPrice, cleanPriceRe, TOL);
        }
        public virtual void parSpreadTest()
        {
            LocalDate   valuationDate    = LocalDate.of(2013, 2, 27);
            DoubleArray ycTime           = DoubleArray.ofUnsafe(new double[] { 0.09041095890410959, 0.1726027397260274, 0.26301369863013696, 0.5123287671232877, 0.7616438356164383, 1.010958904109589, 2.008219178082192, 3.008219178082192, 4.008219178082192, 5.008219178082192, 6.008219178082192, 7.013698630136987, 8.01095890410959, 9.01095890410959, 10.01095890410959, 12.01917808219178, 15.016438356164384, 20.01917808219178, 25.021917808219175, 30.027397260273972 });
            DoubleArray ycRate           = DoubleArray.ofUnsafe(new double[] { 0.0020651105531615476, 0.0024506037920717797, 0.0028872269869485313, 0.004599628230463427, 0.006160809466806469, 0.0075703969168129295, 0.003965128877560435, 0.005059104202201957, 0.0069669135253734825, 0.009361825469323602, 0.011916895611422482, 0.014311922779901886, 0.016519187063048578, 0.018512121993907647, 0.020289623737560873, 0.02329885162861984, 0.026399509889410745, 0.029087919732133784, 0.03037740056662963, 0.03110021763406523 });
            IsdaCreditDiscountFactors yc = IsdaCreditDiscountFactors.of(EUR, valuationDate, CurveName.of("yc_usd"), ycTime, ycRate, ACT_365F);

            double[] timeNodeExp   = new double[] { 0.5616438356164384, 1.0575342465753426, 2.0575342465753423, 3.0602739726027397, 4.06027397260274, 5.06027397260274, 6.06027397260274, 7.063013698630137, 8.063013698630137, 9.063013698630137, 10.063013698630137 };
            double[] rateNodeExp   = new double[] { 0.00876054089781935, 0.011037345646850688, 0.015955126945240167, 0.020617953392829177, 0.025787811343896218, 0.030329992053915133, 0.03313419899444371, 0.03528129159875671, 0.03675340516560903, 0.037946169956317416, 0.038951101800190346 };
            double[] rateNodeExpMf = new double[] { 0.008754510260229803, 0.011030502992814844, 0.01594817866773906, 0.02060947097554756, 0.025776720596175737, 0.030316032527460755, 0.03311839631615255, 0.03526404051997617, 0.03673513322394772, 0.03792689865945585, 0.03893107891569398 };
            ImmutableCreditRatesProvider ratesProvider = ImmutableCreditRatesProvider.builder().valuationDate(valuationDate).discountCurves(ImmutableMap.of(EUR, yc)).recoveryRateCurves(ImmutableMap.of(LEGAL_ENTITY, ConstantRecoveryRates.of(LEGAL_ENTITY, valuationDate, 0.25))).creditCurves(ImmutableMap.of()).build();
            LocalDate startDate = LocalDate.of(2012, 12, 20);

            LocalDate[] pillarDates = new LocalDate[] { LocalDate.of(2013, 9, 20), LocalDate.of(2014, 3, 20), LocalDate.of(2015, 3, 20), LocalDate.of(2016, 3, 20), LocalDate.of(2017, 3, 20), LocalDate.of(2018, 3, 20), LocalDate.of(2019, 3, 20), LocalDate.of(2020, 3, 20), LocalDate.of(2021, 3, 20), LocalDate.of(2022, 3, 20), LocalDate.of(2023, 3, 20) };
            int         nPillars    = pillarDates.Length;
            ImmutableMarketDataBuilder     builderCredit = ImmutableMarketData.builder(valuationDate);
            IList <CdsIsdaCreditCurveNode> nodes         = new List <CdsIsdaCreditCurveNode>(nPillars);

            double[] quotes = new double[] { 0.006485, 0.008163, 0.011763, 0.015136, 0.018787, 0.021905, 0.023797, 0.025211, 0.02617, 0.026928, 0.027549 };
            for (int i = 0; i < nPillars; ++i)
            {
                CdsConvention conv = ImmutableCdsConvention.of("conv", EUR, ACT_360, Frequency.P3M, BUS_ADJ, CDS_SETTLE_STD);
                CdsTemplate   temp = DatesCdsTemplate.of(startDate, pillarDates[i], conv);
                QuoteId       id   = QuoteId.of(StandardId.of("OG", pillarDates[i].ToString()));
                nodes.Add(CdsIsdaCreditCurveNode.ofParSpread(temp, id, LEGAL_ENTITY));
                builderCredit.addValue(id, quotes[i]);
            }
            ImmutableMarketData              marketData      = builderCredit.build();
            IsdaCreditCurveDefinition        curveDefinition = IsdaCreditCurveDefinition.of(CurveName.of("zz"), EUR, valuationDate, ACT_365F, nodes, true, true);
            LegalEntitySurvivalProbabilities cc = BUILDER_ISDA.calibrate(curveDefinition, marketData, ratesProvider, REF_DATA);
            NodalCurve resCurve = ((IsdaCreditDiscountFactors)cc.SurvivalProbabilities).Curve;

            for (int i = 0; i < nPillars; ++i)
            {
                ParameterMetadata param = resCurve.getParameterMetadata(i);
                assertTrue(param is ResolvedTradeParameterMetadata);
                ResolvedTradeParameterMetadata tradeParam = (ResolvedTradeParameterMetadata)param;
                assertTrue(tradeParam.Trade is ResolvedCdsTrade);
            }
            assertTrue(DoubleArrayMath.fuzzyEquals(resCurve.XValues.toArray(), timeNodeExp, TOL));
            assertTrue(DoubleArrayMath.fuzzyEquals(resCurve.YValues.toArray(), rateNodeExp, TOL));
            testJacobian(BUILDER_ISDA, cc, ratesProvider, nodes, quotes, 1d, EPS);
            LegalEntitySurvivalProbabilities ccMf = BUILDER_MARKIT.calibrate(curveDefinition, marketData, ratesProvider, REF_DATA);
            NodalCurve resCurveMf = ((IsdaCreditDiscountFactors)ccMf.SurvivalProbabilities).Curve;

            assertTrue(DoubleArrayMath.fuzzyEquals(resCurveMf.XValues.toArray(), timeNodeExp, TOL));
            assertTrue(DoubleArrayMath.fuzzyEquals(resCurveMf.YValues.toArray(), rateNodeExpMf, TOL));
            testJacobian(BUILDER_MARKIT, ccMf, ratesProvider, nodes, quotes, 1d, EPS);
        }
Beispiel #18
0
        private System.Func <double, double> getPriceFunction(int index, ResolvedCdsTrade cds, double flactionalSpread, double pointsUpfront, LocalDate valuationDate, NodalCurve creditCurve, CreditDiscountFactors discountFactors, RecoveryRates recoveryRates, ReferenceData refData)
        {
            ResolvedCds cdsProduct                 = cds.Product;
            Currency    currency                   = cdsProduct.Currency;
            StandardId  legalEntityId              = cdsProduct.LegalEntityId;
            Pair <StandardId, Currency>  pair      = Pair.of(legalEntityId, currency);
            ImmutableCreditRatesProvider ratesbase = ImmutableCreditRatesProvider.builder().valuationDate(valuationDate).discountCurves(ImmutableMap.of(currency, discountFactors)).recoveryRateCurves(ImmutableMap.of(legalEntityId, recoveryRates)).build();

            System.Func <double, double> func = (double?x) =>
            {
                NodalCurve tempCreditCurve         = creditCurve.withParameter(index, x.Value);
                ImmutableCreditRatesProvider rates = ratesbase.toBuilder().creditCurves(ImmutableMap.of(pair, LegalEntitySurvivalProbabilities.of(legalEntityId, IsdaCreditDiscountFactors.of(currency, valuationDate, tempCreditCurve)))).build();
                double price = TradePricer.price(cds, rates, flactionalSpread, PriceType.CLEAN, refData);
                return(price - pointsUpfront);
            };
            return(func);
        }
Beispiel #19
0
        public virtual void test_regression_single()
        {
            double[] expectedTimes = new double[] { 4.852054794520548 };
            double[] expectedRates = new double[] { 0.04666754810728295 };
            ImmutableList <CdsIndexIsdaCreditCurveNode> singleNode = CURVE_NODES.subList(1, 2);
            IsdaCreditCurveDefinition        curveDefinition       = IsdaCreditCurveDefinition.of(CURVE_NAME, EUR, VALUATION_DATE, ACT_365F, singleNode, true, false);
            LegalEntitySurvivalProbabilities creditCurve           = CALIBRATOR.calibrate(curveDefinition, MARKET_DATA, RATES_PROVIDER, REF_DATA);
            NodalCurve curve = (NodalCurve)creditCurve.SurvivalProbabilities.findData(CURVE_NAME).get();

            assertTrue(DoubleArrayMath.fuzzyEquals(curve.XValues.toArray(), expectedTimes, TOL));
            assertTrue(DoubleArrayMath.fuzzyEquals(curve.YValues.toArray(), expectedRates, TOL));
            assertTrue(curve.getParameterMetadata(0) is DatedParameterMetadata);
            double computedIndex = curve.Metadata.getInfo(CurveInfoType.CDS_INDEX_FACTOR);

            assertEquals(computedIndex, 93.0 / 97.0, TOL);
            testJacobian(creditCurve, RATES_PROVIDER, singleNode, PUF_QUOTES);
        }
Beispiel #20
0
        /// <summary>
        /// Converts points upfront to quoted spread.
        /// <para>
        /// Thus {@code quote} must be {@code CdsQuoteConvention.POINTS_UPFRONT}.
        /// </para>
        /// <para>
        /// The relevant discount curve and recovery rate curve must be stored in {@code ratesProvider}.
        /// The credit curve is internally calibrated to convert one quote type to the other quote type.
        ///
        /// </para>
        /// </summary>
        /// <param name="trade">  the trade </param>
        /// <param name="quote">  the quote </param>
        /// <param name="ratesProvider">  the rates provider </param>
        /// <param name="refData">  the reference data </param>
        /// <returns> the quote </returns>
        public virtual CdsQuote quotedSpreadFromPointsUpfront(ResolvedCdsTrade trade, CdsQuote quote, CreditRatesProvider ratesProvider, ReferenceData refData)
        {
            ArgChecker.notNull(trade, "trade");
            ArgChecker.notNull(quote, "quote");
            ArgChecker.notNull(ratesProvider, "ratesProvider");
            ArgChecker.notNull(refData, "refData");
            ArgChecker.isTrue(quote.QuoteConvention.Equals(CdsQuoteConvention.POINTS_UPFRONT), "quote must be points upfront");

            ResolvedCds         product          = trade.Product;
            Currency            currency         = product.Currency;
            StandardId          legalEntityId    = product.LegalEntityId;
            LocalDate           valuationDate    = ratesProvider.ValuationDate;
            NodalCurve          creditCurve      = calibrator.calibrate(ImmutableList.of(trade), DoubleArray.of(product.FixedRate), DoubleArray.of(quote.QuotedValue), CurveName.of("temp"), valuationDate, ratesProvider.discountFactors(currency), ratesProvider.recoveryRates(legalEntityId), refData);
            CreditRatesProvider ratesProviderNew = ratesProvider.toImmutableCreditRatesProvider().toBuilder().creditCurves(ImmutableMap.of(Pair.of(legalEntityId, currency), LegalEntitySurvivalProbabilities.of(legalEntityId, IsdaCreditDiscountFactors.of(currency, valuationDate, creditCurve)))).build();
            double sp = pricer.parSpread(trade, ratesProviderNew, refData);

            return(CdsQuote.of(CdsQuoteConvention.QUOTED_SPREAD, sp));
        }
Beispiel #21
0
        public virtual void test_regression()
        {
            double[] expectedTimes = new double[] { 2.852054794520548, 4.852054794520548, 6.854794520547945, 9.854794520547944 };
            double[] expectedRates = new double[] { 0.03240798261187516, 0.04858422754375164, 0.0616141083562273, 0.06235460926516589 };
            IsdaCreditCurveDefinition        curveDefinition = IsdaCreditCurveDefinition.of(CURVE_NAME, EUR, VALUATION_DATE, ACT_365F, CURVE_NODES, true, false);
            LegalEntitySurvivalProbabilities creditCurve     = CALIBRATOR.calibrate(curveDefinition, MARKET_DATA, RATES_PROVIDER, REF_DATA);
            NodalCurve curve = (NodalCurve)creditCurve.SurvivalProbabilities.findData(CURVE_NAME).get();

            assertTrue(DoubleArrayMath.fuzzyEquals(curve.XValues.toArray(), expectedTimes, TOL));
            assertTrue(DoubleArrayMath.fuzzyEquals(curve.YValues.toArray(), expectedRates, TOL));
            assertTrue(curve.getParameterMetadata(0) is DatedParameterMetadata);
            assertTrue(curve.getParameterMetadata(1) is DatedParameterMetadata);
            assertTrue(curve.getParameterMetadata(2) is DatedParameterMetadata);
            assertTrue(curve.getParameterMetadata(3) is DatedParameterMetadata);
            double computedIndex = curve.Metadata.getInfo(CurveInfoType.CDS_INDEX_FACTOR);

            assertEquals(computedIndex, 93.0 / 97.0, TOL);
            testJacobian(creditCurve, RATES_PROVIDER, CURVE_NODES, PUF_QUOTES);
        }
        public virtual void pufTest()
        {
            LocalDate   valuationDate    = LocalDate.of(2013, 4, 10);
            DoubleArray ycTime           = DoubleArray.ofUnsafe(new double[] { 0.09041095890410959, 0.1726027397260274, 0.2547945205479452, 0.5123287671232877, 0.7616438356164383, 1.010958904109589, 2.008219178082192, 3.008219178082192, 4.008219178082192, 5.008219178082192, 6.008219178082192, 7.013698630136987, 8.01095890410959, 9.01095890410959, 10.01095890410959, 12.01917808219178, 15.016438356164384, 20.01917808219178, 25.021917808219175, 30.027397260273972 });
            DoubleArray ycRate           = DoubleArray.ofUnsafe(new double[] { 0.0020205071813561414, 0.0024226927083852126, 0.00280147037504029, 0.004449041082144009, 0.005821804782808804, 0.007254879152733453, 0.00378133614924816, 0.004815163234294319, 0.006576302084547871, 0.00884241431837336, 0.011358805989279104, 0.013793391727035883, 0.016014197840890115, 0.01801564209277191, 0.019757164421290663, 0.022773295945438254, 0.025862337032619587, 0.02848646344754061, 0.029753383126110852, 0.03045277462637107 });
            IsdaCreditDiscountFactors yc = IsdaCreditDiscountFactors.of(EUR, valuationDate, CurveName.of("yc_usd"), ycTime, ycRate, ACT_365F);

            double[] timeNodeExp   = new double[] { 0.19452054794520549, 0.4465753424657534, 0.6958904109589041, 0.9424657534246575, 1.1945205479452055, 1.4465753424657535, 1.6958904109589041, 1.9424657534246574, 2.1945205479452055, 2.4465753424657533, 2.695890410958904, 2.9452054794520546, 3.197260273972603, 3.4493150684931506, 3.6986301369863015, 3.9452054794520546, 4.197260273972603, 4.449315068493151, 4.698630136986301, 4.945205479452055, 5.197260273972603, 5.449315068493151, 5.698630136986301, 5.945205479452055, 6.197260273972603, 6.449315068493151, 6.698630136986301, 6.947945205479452, 7.2, 7.4520547945205475, 7.701369863013698, 7.947945205479452, 8.2, 8.452054794520548, 8.7013698630137, 8.947945205479453, 9.2, 9.452054794520548, 9.7013698630137, 9.947945205479453, 10.2 };
            double[] rateNodeExp   = new double[] { 0.11219168510100914, 0.11085321179769615, 0.11753783265486063, 0.11806409789291543, 0.12007843111645247, 0.12273722191216528, 0.12541993298405366, 0.12773640093265545, 0.1290535220739981, 0.13294183149211675, 0.13659302947963856, 0.13988488561043758, 0.1429469312254705, 0.14606538453369572, 0.14916286828444447, 0.15219682906227, 0.1548315745851032, 0.158141193071526, 0.16163981714033765, 0.1650400193930357, 0.1682351993447916, 0.1683744003954113, 0.168657453080796, 0.16915067878510565, 0.1694852880010724, 0.16990705130936645, 0.1704456138969621, 0.17105852486248443, 0.1717088423125347, 0.1727906445582425, 0.17407566745397665, 0.17547300248653266, 0.17679395545074758, 0.17769841457372118, 0.1788064602071617, 0.18001498257267778, 0.18123747758791092, 0.18253661761388457, 0.18406319235262744, 0.18582983758830868, 0.18750386499176422 };
            double[] rateNodeExpMf = new double[] { 0.11107220823737506, 0.11011543264900588, 0.11685607164947402, 0.11742079953945683, 0.1194445192166302, 0.12220026187805585, 0.12494798294628297, 0.12731185688090763, 0.12860146674492023, 0.1325216904413876, 0.1362014254649678, 0.13951646788193767, 0.14254141853655264, 0.14567581048732742, 0.1487851622438674, 0.15182838855605538, 0.15442415754322128, 0.15774061191016645, 0.16124288871765308, 0.1646451035564102, 0.167796451103847, 0.16794456750248196, 0.16823438468063495, 0.1687328171292339, 0.16904360885724334, 0.16947020572961907, 0.17001201556723175, 0.17062724832190826, 0.17125190473373603, 0.17233319414449558, 0.17361785479583028, 0.1750136127341691, 0.17630530410589512, 0.17720871748506664, 0.17831270423353415, 0.17951604233911425, 0.18070939732103264, 0.18200162521943403, 0.18351891000003046, 0.1852740041292825, 0.18691086960422418 };
            ImmutableCreditRatesProvider ratesProvider = ImmutableCreditRatesProvider.builder().valuationDate(valuationDate).discountCurves(ImmutableMap.of(EUR, yc)).recoveryRateCurves(ImmutableMap.of(LEGAL_ENTITY, ConstantRecoveryRates.of(LEGAL_ENTITY, valuationDate, 0.4))).creditCurves(ImmutableMap.of()).build();
            LocalDate startDate = LocalDate.of(2013, 3, 20);

            LocalDate[] pillarDate = new LocalDate[] { LocalDate.of(2013, 6, 20), LocalDate.of(2013, 9, 20), LocalDate.of(2013, 12, 20), LocalDate.of(2014, 3, 20), LocalDate.of(2014, 6, 20), LocalDate.of(2014, 9, 20), LocalDate.of(2014, 12, 20), LocalDate.of(2015, 3, 20), LocalDate.of(2015, 6, 20), LocalDate.of(2015, 9, 20), LocalDate.of(2015, 12, 20), LocalDate.of(2016, 3, 20), LocalDate.of(2016, 6, 20), LocalDate.of(2016, 9, 20), LocalDate.of(2016, 12, 20), LocalDate.of(2017, 3, 20), LocalDate.of(2017, 6, 20), LocalDate.of(2017, 9, 20), LocalDate.of(2017, 12, 20), LocalDate.of(2018, 3, 20), LocalDate.of(2018, 6, 20), LocalDate.of(2018, 9, 20), LocalDate.of(2018, 12, 20), LocalDate.of(2019, 3, 20), LocalDate.of(2019, 6, 20), LocalDate.of(2019, 9, 20), LocalDate.of(2019, 12, 20), LocalDate.of(2020, 3, 20), LocalDate.of(2020, 6, 20), LocalDate.of(2020, 9, 20), LocalDate.of(2020, 12, 20), LocalDate.of(2021, 3, 20), LocalDate.of(2021, 6, 20), LocalDate.of(2021, 9, 20), LocalDate.of(2021, 12, 20), LocalDate.of(2022, 3, 20), LocalDate.of(2022, 6, 20), LocalDate.of(2022, 9, 20), LocalDate.of(2022, 12, 20), LocalDate.of(2023, 3, 20), LocalDate.of(2023, 6, 20) };
            int         nPillars   = pillarDate.Length;
            double      coupon     = 500d * ONE_BP;
            ImmutableMarketDataBuilder     builderCredit = ImmutableMarketData.builder(valuationDate);
            IList <CdsIsdaCreditCurveNode> nodes         = new List <CdsIsdaCreditCurveNode>(nPillars);

            double[] quotes = new double[] { 0.32, 0.69, 1.32, 1.79, 2.36, 3.01, 3.7, 4.39, 5.02, 5.93, 6.85, 7.76, 8.67, 9.6, 10.53, 11.45, 12.33, 13.29, 14.26, 15.2, 16.11, 16.62, 17.12, 17.62, 18.09, 18.55, 19, 19.44, 19.87, 20.33, 20.79, 21.24, 21.67, 22.04, 22.41, 22.77, 23.12, 23.46, 23.8, 24.14, 24.46 };
            for (int i = 0; i < nPillars; ++i)
            {
                CdsConvention conv = ImmutableCdsConvention.of("conv", EUR, ACT_360, Frequency.P3M, BUS_ADJ, CDS_SETTLE_STD);
                CdsTemplate   temp = DatesCdsTemplate.of(startDate, pillarDate[i], conv);
                QuoteId       id   = QuoteId.of(StandardId.of("OG", pillarDate[i].ToString()));
                nodes.Add(CdsIsdaCreditCurveNode.ofPointsUpfront(temp, id, LEGAL_ENTITY, coupon));
                builderCredit.addValue(id, quotes[i] * ONE_PC);
            }
            ImmutableMarketData              marketData      = builderCredit.build();
            IsdaCreditCurveDefinition        curveDefinition = IsdaCreditCurveDefinition.of(CurveName.of("cc"), EUR, valuationDate, ACT_365F, nodes, true, false);
            LegalEntitySurvivalProbabilities cc = BUILDER_ISDA.calibrate(curveDefinition, marketData, ratesProvider, REF_DATA);
            NodalCurve resCurve = ((IsdaCreditDiscountFactors)cc.SurvivalProbabilities).Curve;

            assertTrue(DoubleArrayMath.fuzzyEquals(resCurve.XValues.toArray(), timeNodeExp, TOL));
            assertTrue(DoubleArrayMath.fuzzyEquals(resCurve.YValues.toArray(), rateNodeExp, TOL));
            testJacobian(BUILDER_ISDA, cc, ratesProvider, nodes, quotes, ONE_PC, EPS);
            LegalEntitySurvivalProbabilities ccMf = BUILDER_MARKIT.calibrate(curveDefinition, marketData, ratesProvider, REF_DATA);
            NodalCurve resCurveMf = ((IsdaCreditDiscountFactors)ccMf.SurvivalProbabilities).Curve;

            assertTrue(DoubleArrayMath.fuzzyEquals(resCurveMf.XValues.toArray(), timeNodeExp, TOL));
            assertTrue(DoubleArrayMath.fuzzyEquals(resCurveMf.YValues.toArray(), rateNodeExpMf, TOL));
            testJacobian(BUILDER_MARKIT, ccMf, ratesProvider, nodes, quotes, ONE_PC, EPS);
        }
Beispiel #23
0
            public override Builder set(string propertyName, object newValue)
            {
                switch (propertyName.GetHashCode())
                {
                case -1770633379:         // underlying
                    this.underlying = (NodalCurve)newValue;
                    break;

                case -857898080:         // seasonality
                    this.seasonality = (DoubleArray)newValue;
                    break;

                case -1002343865:         // adjustmentType
                    this.adjustmentType = (ShiftType)newValue;
                    break;

                default:
                    throw new NoSuchElementException("Unknown property: " + propertyName);
                }
                return(this);
            }
Beispiel #24
0
        /// <summary>
        /// Obtains an instance from a curve without initial fixing point and month-on-month seasonal adjustment.
        /// <para>
        /// The total adjustment is computed by accumulation of the monthly adjustment, starting with no adjustment for the
        /// last fixing month.
        ///
        /// </para>
        /// </summary>
        /// <param name="curveWithoutFixing">  the curve without the fixing </param>
        /// <param name="valuationDate">  the valuation date of the curve </param>
        /// <param name="lastMonth">  the last month for which the fixing is known </param>
        /// <param name="lastFixingValue">  the value of the last fixing </param>
        /// <param name="seasonalityDefinition">  the seasonality definition, which is made of month-on-month adjustment
        ///   and the adjustment type </param>
        /// <returns> the seasonal curve instance </returns>
        public static InflationNodalCurve of(NodalCurve curveWithoutFixing, LocalDate valuationDate, YearMonth lastMonth, double lastFixingValue, SeasonalityDefinition seasonalityDefinition)
        {
            YearMonth valuationMonth = YearMonth.from(valuationDate);

            ArgChecker.isTrue(lastMonth.isBefore(valuationMonth), "Last fixing month must be before valuation date");
            double      nbMonth = valuationMonth.until(lastMonth, MONTHS);
            DoubleArray x       = curveWithoutFixing.XValues;

            ArgChecker.isTrue(nbMonth < x.get(0), "The first estimation month should be after the last known index fixing");
            NodalCurve extendedCurve = curveWithoutFixing.withNode(nbMonth, lastFixingValue, ParameterMetadata.empty());

            double[] seasonalityCompoundedArray = new double[12];
            int      lastMonthIndex             = lastMonth.Month.Value - 1;

            seasonalityCompoundedArray[(int)((nbMonth + 12 + 1) % 12)] = seasonalityDefinition.SeasonalityMonthOnMonth.get(lastMonthIndex % 12);
            for (int i = 1; i < 12; i++)
            {
                int j = (int)((nbMonth + 12 + 1 + i) % 12);
                seasonalityCompoundedArray[j] = seasonalityDefinition.AdjustmentType.applyShift(seasonalityCompoundedArray[(j - 1 + 12) % 12], seasonalityDefinition.SeasonalityMonthOnMonth.get((lastMonthIndex + i) % 12));
            }
            return(new InflationNodalCurve(extendedCurve, DoubleArray.ofUnsafe(seasonalityCompoundedArray), seasonalityDefinition.AdjustmentType));
        }
Beispiel #25
0
        /// <summary>
        /// The par spread quotes are converted to points upfronts or quoted spreads.
        /// <para>
        /// The relevant discount curve and recovery rate curve must be stored in {@code ratesProvider}.
        /// The credit curve is internally calibrated to par spread values.
        /// </para>
        /// <para>
        /// {@code trades} must be sorted in ascending order in maturity and coherent to {@code quotes}.
        /// </para>
        /// <para>
        /// The resultant quote is specified by {@code targetConvention}.
        ///
        /// </para>
        /// </summary>
        /// <param name="trades">  the trades </param>
        /// <param name="quotes">  the quotes </param>
        /// <param name="ratesProvider">  the rates provider </param>
        /// <param name="targetConvention">  the target convention </param>
        /// <param name="refData">  the reference data </param>
        /// <returns> the quotes </returns>
        public virtual IList <CdsQuote> quotesFromParSpread(IList <ResolvedCdsTrade> trades, IList <CdsQuote> quotes, CreditRatesProvider ratesProvider, CdsQuoteConvention targetConvention, ReferenceData refData)
        {
            ArgChecker.noNulls(trades, "trades");
            ArgChecker.noNulls(quotes, "quotes");
            ArgChecker.notNull(ratesProvider, "ratesProvider");
            ArgChecker.notNull(targetConvention, "targetConvention");
            ArgChecker.notNull(refData, "refData");

            int nNodes = trades.Count;

            ArgChecker.isTrue(quotes.Count == nNodes, "trades and quotes must be the same size");
            quotes.ForEach(q => ArgChecker.isTrue(q.QuoteConvention.Equals(CdsQuoteConvention.PAR_SPREAD), "quote must be par spread"));
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            IEnumerator <StandardId> legalEntities = trades.Select(t => t.Product.LegalEntityId).collect(Collectors.toSet()).GetEnumerator();
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            StandardId legalEntityId = legalEntities.next();

//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            ArgChecker.isFalse(legalEntities.hasNext(), "legal entity must be common to trades");
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            IEnumerator <Currency> currencies = trades.Select(t => t.Product.Currency).collect(Collectors.toSet()).GetEnumerator();
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            Currency currency = currencies.next();

//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            ArgChecker.isFalse(currencies.hasNext(), "currency must be common to trades");

            LocalDate             valuationDate    = ratesProvider.ValuationDate;
            CreditDiscountFactors discountFactors  = ratesProvider.discountFactors(currency);
            RecoveryRates         recoveryRates    = ratesProvider.recoveryRates(legalEntityId);
            NodalCurve            creditCurve      = calibrator.calibrate(trades, DoubleArray.of(nNodes, q => quotes[q].QuotedValue), DoubleArray.filled(nNodes), CurveName.of("temp"), valuationDate, discountFactors, recoveryRates, refData);
            CreditRatesProvider   ratesProviderNew = ratesProvider.toImmutableCreditRatesProvider().toBuilder().creditCurves(ImmutableMap.of(Pair.of(legalEntityId, currency), LegalEntitySurvivalProbabilities.of(legalEntityId, IsdaCreditDiscountFactors.of(currency, valuationDate, creditCurve)))).build();

            System.Func <ResolvedCdsTrade, CdsQuote> quoteValueFunction = createQuoteValueFunction(ratesProviderNew, targetConvention, refData);
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            ImmutableList <CdsQuote> result = trades.Select(c => quoteValueFunction(c)).collect(Collectors.collectingAndThen(Collectors.toList(), ImmutableList.copyOf));

            return(result);
        }
        private DoubleArray sensitivitySwap(BasicFixedLeg swap, NodalCurve curve, double swapRate)
        {
            int    nPayments = swap.NumPayments;
            double annuity   = 0d;
            UnitParameterSensitivities sensi = UnitParameterSensitivities.empty();

            for (int i = 0; i < nPayments - 1; i++)
            {
                double t  = swap.getPaymentTime(i);
                double df = Math.Exp(-curve.yValue(t) * t);
                annuity += swap.getYearFraction(i) * df;
                sensi    = sensi.combinedWith(curve.yValueParameterSensitivity(t).multipliedBy(-df * t * swap.getYearFraction(i) * swapRate));
            }
            int    lastIndex = nPayments - 1;
            double t         = swap.getPaymentTime(lastIndex);
            double df        = Math.Exp(-curve.yValue(t) * t);

            annuity += swap.getYearFraction(lastIndex) * df;
            sensi    = sensi.combinedWith(curve.yValueParameterSensitivity(t).multipliedBy(-df * t * (1d + swap.getYearFraction(lastIndex) * swapRate)));
            sensi    = sensi.multipliedBy(-1d / annuity);
            ArgChecker.isTrue(sensi.size() == 1);
            return(sensi.Sensitivities.get(0).Sensitivity);
        }
 private double[] getStandardQuoteForm(ResolvedCdsTrade calibrationCds, CdsQuote marketQuote, LocalDate valuationDate, CreditDiscountFactors discountFactors, RecoveryRates recoveryRates, bool computeJacobian, ReferenceData refData)
 {
     double[] res = new double[3];
     res[2] = 1d;
     if (marketQuote.QuoteConvention.Equals(CdsQuoteConvention.PAR_SPREAD))
     {
         res[0] = marketQuote.QuotedValue;
     }
     else if (marketQuote.QuoteConvention.Equals(CdsQuoteConvention.QUOTED_SPREAD))
     {
         double     qSpread                 = marketQuote.QuotedValue;
         CurveName  curveName               = CurveName.of("quoteConvertCurve");
         NodalCurve tempCreditCurve         = calibrate(ImmutableList.of(calibrationCds), DoubleArray.of(qSpread), DoubleArray.of(0d), curveName, valuationDate, discountFactors, recoveryRates, refData);
         Currency   currency                = calibrationCds.Product.Currency;
         StandardId legalEntityId           = calibrationCds.Product.LegalEntityId;
         ImmutableCreditRatesProvider rates = ImmutableCreditRatesProvider.builder().valuationDate(valuationDate).discountCurves(ImmutableMap.of(currency, discountFactors)).recoveryRateCurves(ImmutableMap.of(legalEntityId, recoveryRates)).creditCurves(ImmutableMap.of(Pair.of(legalEntityId, currency), LegalEntitySurvivalProbabilities.of(legalEntityId, IsdaCreditDiscountFactors.of(currency, valuationDate, tempCreditCurve)))).build();
         res[0] = calibrationCds.Product.FixedRate;
         res[1] = tradePricer.price(calibrationCds, rates, PriceType.CLEAN, refData);
         if (computeJacobian)
         {
             CurrencyParameterSensitivities pufSensi = rates.parameterSensitivity(tradePricer.priceSensitivity(calibrationCds, rates, refData));
             CurrencyParameterSensitivities spSensi  = rates.parameterSensitivity(tradePricer.parSpreadSensitivity(calibrationCds, rates, refData));
             res[2] = spSensi.getSensitivity(curveName, currency).Sensitivity.get(0) / pufSensi.getSensitivity(curveName, currency).Sensitivity.get(0);
         }
     }
     else if (marketQuote.QuoteConvention.Equals(CdsQuoteConvention.POINTS_UPFRONT))
     {
         res[0] = calibrationCds.Product.FixedRate;
         res[1] = marketQuote.QuotedValue;
     }
     else
     {
         throw new System.ArgumentException("Unknown CDSQuoteConvention type " + marketQuote.GetType());
     }
     return(res);
 }
Beispiel #28
0
        private readonly DayCount dayCount;   // cached, not a property

        //-------------------------------------------------------------------------
        /// <summary>
        /// Creates an instance from the underlying curve.
        /// </summary>
        /// <param name="currency">  the currency </param>
        /// <param name="valuationDate">  the valuation date </param>
        /// <param name="curve">  the underlying curve </param>
        /// <returns> the instance </returns>
        public static IsdaCreditDiscountFactors of(Currency currency, LocalDate valuationDate, NodalCurve curve)
        {
            curve.Metadata.XValueType.checkEquals(YEAR_FRACTION, "Incorrect x-value type for zero-rate discount curve");
            curve.Metadata.YValueType.checkEquals(ZERO_RATE, "Incorrect y-value type for zero-rate discount curve");
            if (curve is InterpolatedNodalCurve)
            {
                InterpolatedNodalCurve interpolatedCurve = (InterpolatedNodalCurve)curve;
                ArgChecker.isTrue(interpolatedCurve.Interpolator.Equals(CurveInterpolators.PRODUCT_LINEAR), "Interpolator must be PRODUCT_LINEAR");
                ArgChecker.isTrue(interpolatedCurve.ExtrapolatorLeft.Equals(CurveExtrapolators.FLAT), "Left extrapolator must be FLAT");
                ArgChecker.isTrue(interpolatedCurve.ExtrapolatorRight.Equals(CurveExtrapolators.PRODUCT_LINEAR), "Right extrapolator must be PRODUCT_LINEAR");
            }
            else
            {
                ArgChecker.isTrue(curve is ConstantNodalCurve, "the underlying curve must be InterpolatedNodalCurve or ConstantNodalCurve");
            }
            return(new IsdaCreditDiscountFactors(currency, valuationDate, curve));
        }
        //-------------------------------------------------------------------------
        /// <summary>
        /// Calibrates the ISDA compliant discount curve to the market data.
        /// <para>
        /// This creates the single discount curve for a specified currency.
        /// The curve nodes in {@code IsdaCreditCurveDefinition} should be term deposit or fixed-for-Ibor swap,
        /// and the number of nodes should be greater than 1.
        ///
        /// </para>
        /// </summary>
        /// <param name="curveDefinition">  the curve definition </param>
        /// <param name="marketData">  the market data </param>
        /// <param name="refData">  the reference data </param>
        /// <returns> the ISDA compliant discount curve </returns>
        public IsdaCreditDiscountFactors calibrate(IsdaCreditCurveDefinition curveDefinition, MarketData marketData, ReferenceData refData)
        {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.List<? extends com.opengamma.strata.market.curve.IsdaCreditCurveNode> curveNodes = curveDefinition.getCurveNodes();
            IList <IsdaCreditCurveNode> curveNodes = curveDefinition.CurveNodes;
            int nNodes = curveNodes.Count;

            ArgChecker.isTrue(nNodes > 1, "the number of curve nodes must be greater than 1");
            LocalDate curveSnapDate      = marketData.ValuationDate;
            LocalDate curveValuationDate = curveDefinition.CurveValuationDate;
            DayCount  curveDayCount      = curveDefinition.DayCount;

            BasicFixedLeg[] swapLeg = new BasicFixedLeg[nNodes];
            double[]        termDepositYearFraction = new double[nNodes];
            double[]        curveNodeTime           = new double[nNodes];
            double[]        rates = new double[nNodes];
            ImmutableList.Builder <ParameterMetadata> paramMetadata = ImmutableList.builder();
            int       nTermDeposit  = 0;
            LocalDate curveSpotDate = null;

            for (int i = 0; i < nNodes; i++)
            {
                LocalDate           cvDateTmp;
                IsdaCreditCurveNode node = curveNodes[i];
                rates[i] = marketData.getValue(node.ObservableId);
                LocalDate adjMatDate = node.date(curveSnapDate, refData);
                paramMetadata.add(node.metadata(adjMatDate));
                if (node is DepositIsdaCreditCurveNode)
                {
                    DepositIsdaCreditCurveNode termDeposit = (DepositIsdaCreditCurveNode)node;
                    cvDateTmp                  = termDeposit.SpotDateOffset.adjust(curveSnapDate, refData);
                    curveNodeTime[i]           = curveDayCount.relativeYearFraction(cvDateTmp, adjMatDate);
                    termDepositYearFraction[i] = termDeposit.DayCount.relativeYearFraction(cvDateTmp, adjMatDate);
                    ArgChecker.isTrue(nTermDeposit == i, "TermDepositCurveNode should not be after FixedIborSwapCurveNode");
                    ++nTermDeposit;
                }
                else if (node is SwapIsdaCreditCurveNode)
                {
                    SwapIsdaCreditCurveNode swap = (SwapIsdaCreditCurveNode)node;
                    cvDateTmp        = swap.SpotDateOffset.adjust(curveSnapDate, refData);
                    curveNodeTime[i] = curveDayCount.relativeYearFraction(cvDateTmp, adjMatDate);
                    BusinessDayAdjustment busAdj = swap.BusinessDayAdjustment;
                    swapLeg[i] = new BasicFixedLeg(this, cvDateTmp, cvDateTmp.plus(swap.Tenor), swap.PaymentFrequency.Period, swap.DayCount, curveDayCount, busAdj, refData);
                }
                else
                {
                    throw new System.ArgumentException("unsupported cuve node type");
                }
                if (i > 0)
                {
                    ArgChecker.isTrue(curveNodeTime[i] - curveNodeTime[i - 1] > 0, "curve nodes should be ascending in terms of tenor");
                    ArgChecker.isTrue(cvDateTmp.Equals(curveSpotDate), "spot lag should be common for all of the curve nodes");
                }
                else
                {
                    ArgChecker.isTrue(curveNodeTime[i] >= 0d, "the first node should be after curve spot date");
                    curveSpotDate = cvDateTmp;
                }
            }
            ImmutableList <ParameterMetadata> parameterMetadata = paramMetadata.build();

            double[] ratesMod = Arrays.copyOf(rates, nNodes);
            for (int i = 0; i < nTermDeposit; ++i)
            {
                double dfInv = 1d + ratesMod[i] * termDepositYearFraction[i];
                ratesMod[i] = Math.Log(dfInv) / curveNodeTime[i];
            }
            InterpolatedNodalCurve curve = curveDefinition.curve(DoubleArray.ofUnsafe(curveNodeTime), DoubleArray.ofUnsafe(ratesMod));

            for (int i = nTermDeposit; i < nNodes; ++i)
            {
                curve = fitSwap(i, swapLeg[i], curve, rates[i]);
            }

            Currency     currency = curveDefinition.Currency;
            DoubleMatrix sensi    = quoteValueSensitivity(nTermDeposit, termDepositYearFraction, swapLeg, ratesMod, curve, curveDefinition.ComputeJacobian);

            if (curveValuationDate.isEqual(curveSpotDate))
            {
                if (curveDefinition.ComputeJacobian)
                {
                    JacobianCalibrationMatrix jacobian = JacobianCalibrationMatrix.of(ImmutableList.of(CurveParameterSize.of(curveDefinition.Name, nNodes)), MATRIX_ALGEBRA.getInverse(sensi));
                    NodalCurve curveWithParamMetadata  = curve.withMetadata(curve.Metadata.withInfo(CurveInfoType.JACOBIAN, jacobian).withParameterMetadata(parameterMetadata));
                    return(IsdaCreditDiscountFactors.of(currency, curveValuationDate, curveWithParamMetadata));
                }
                NodalCurve curveWithParamMetadata = curve.withMetadata(curve.Metadata.withParameterMetadata(parameterMetadata));
                return(IsdaCreditDiscountFactors.of(currency, curveValuationDate, curveWithParamMetadata));
            }
            double offset = curveDayCount.relativeYearFraction(curveSpotDate, curveValuationDate);

            return(IsdaCreditDiscountFactors.of(currency, curveValuationDate, withShift(curve, parameterMetadata, sensi, curveDefinition.ComputeJacobian, offset)));
        }
Beispiel #30
0
        private readonly double yFixing;   // cached, not a property

        //-------------------------------------------------------------------------
        /// <summary>
        /// Obtains an instance of the curve.
        /// <para>
        /// The seasonal adjustment is the total adjustment for each month, starting with January.
        /// </para>
        /// <para>
        /// See <seealso cref="#of(NodalCurve, LocalDate, YearMonth, double, SeasonalityDefinition)"/> for
        /// month-on-month adjustments and the adjustment starting point, including locking the last fixing.
        ///
        /// </para>
        /// </summary>
        /// <param name="curve">  the curve with initial fixing </param>
        /// <param name="seasonality">  the total seasonal adjustment for each month, with the first element the January adjustment </param>
        /// <param name="adjustmentType">  the adjustment type </param>
        /// <returns> the seasonal curve instance </returns>
        public static InflationNodalCurve of(NodalCurve curve, DoubleArray seasonality, ShiftType adjustmentType)
        {
            return(new InflationNodalCurve(curve, seasonality, adjustmentType));
        }