Пример #1
0
        /// <summary>
        /// Construct the inverse Jacobian matrix from the sensitivities of the trades market quotes to the curve parameters.
        /// <para>
        /// All the trades and sensitivities must be in the same currency. The data should be coherent with the
        /// market quote sensitivities passed in an order coherent with the list of curves.
        /// </para>
        /// <para>
        /// For each trade describing the market quotes, the sensitivity provided should be the sensitivity of that
        /// market quote to the curve parameters.
        ///
        /// </para>
        /// </summary>
        /// <param name="curveOrder">  the order in which the curves should be represented in the jacobian </param>
        /// <param name="marketQuoteSensitivities">  the market quotes sensitivity to the curve parameters </param>
        /// <returns> inverse jacobian matrix, which correspond to the sensitivity of the parameters to the market quotes </returns>
        public static DoubleMatrix jacobianFromMarketQuoteSensitivities(IList <CurveParameterSize> curveOrder, IList <CurrencyParameterSensitivities> marketQuoteSensitivities)
        {
            Currency     ccy            = marketQuoteSensitivities[0].Sensitivities.get(0).Currency;
            DoubleMatrix jacobianMatrix = DoubleMatrix.ofArrayObjects(marketQuoteSensitivities.Count, marketQuoteSensitivities.Count, i => row(curveOrder, marketQuoteSensitivities[i], ccy));

            return(MATRIX_ALGEBRA.getInverse(jacobianMatrix));
        }
        // jacobian direct, for the current group
        private static DoubleMatrix jacobianDirect(DoubleMatrix res, int nbTrades, int totalParamsGroup, int totalParamsPrevious)
        {
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] direct = new double[totalParamsGroup][totalParamsGroup];
            double[][] direct = RectangularArrays.ReturnRectangularDoubleArray(totalParamsGroup, totalParamsGroup);
            for (int i = 0; i < nbTrades; i++)
            {
                Array.Copy(res.rowArray(i), totalParamsPrevious, direct[i], 0, totalParamsGroup);
            }
            return(MATRIX_ALGEBRA.getInverse(DoubleMatrix.copyOf(direct)));
        }
        //-------------------------------------------------------------------------
        /// <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)));
        }
        internal virtual LegalEntitySurvivalProbabilities calibrate(IList <CdsIsdaCreditCurveNode> curveNodes, CurveName name, MarketData marketData, ImmutableCreditRatesProvider ratesProvider, DayCount definitionDayCount, Currency definitionCurrency, bool computeJacobian, bool storeTrade, ReferenceData refData)
        {
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            IEnumerator <StandardId> legalEntities = curveNodes.Select(CdsIsdaCreditCurveNode::getLegalEntityId).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 curve nodes");
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            IEnumerator <Currency> currencies = curveNodes.Select(n => n.Template.Convention.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 curve nodes");
            ArgChecker.isTrue(definitionCurrency.Equals(currency), "curve definition currency must be the same as the currency of CDS");
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            IEnumerator <CdsQuoteConvention> quoteConventions = curveNodes.Select(n => n.QuoteConvention).collect(Collectors.toSet()).GetEnumerator();
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            CdsQuoteConvention quoteConvention = quoteConventions.next();

//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            ArgChecker.isFalse(quoteConventions.hasNext(), "quote convention must be common to curve nodes");
            LocalDate valuationDate = marketData.ValuationDate;

            ArgChecker.isTrue(valuationDate.Equals(marketData.ValuationDate), "ratesProvider and marketDate must be based on the same valuation date");
            CreditDiscountFactors discountFactors = ratesProvider.discountFactors(currency);

            ArgChecker.isTrue(definitionDayCount.Equals(discountFactors.DayCount), "credit curve and discount curve must be based on the same day count convention");
            RecoveryRates recoveryRates = ratesProvider.recoveryRates(legalEntityId);

            int nNodes = curveNodes.Count;

            double[] coupons = new double[nNodes];
            double[] pufs    = new double[nNodes];
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] diag = new double[nNodes][nNodes];
            double[][] diag = RectangularArrays.ReturnRectangularDoubleArray(nNodes, nNodes);
            ImmutableList.Builder <ResolvedCdsTrade> tradesBuilder = ImmutableList.builder();
            for (int i = 0; i < nNodes; i++)
            {
                CdsCalibrationTrade tradeCalibration = curveNodes[i].trade(1d, marketData, refData);
                ResolvedCdsTrade    trade            = tradeCalibration.UnderlyingTrade.resolve(refData);
                tradesBuilder.add(trade);
                double[] temp = getStandardQuoteForm(trade, tradeCalibration.Quote, valuationDate, discountFactors, recoveryRates, computeJacobian, refData);
                coupons[i] = temp[0];
                pufs[i]    = temp[1];
                diag[i][i] = temp[2];
            }
            ImmutableList <ResolvedCdsTrade> trades = tradesBuilder.build();
            NodalCurve nodalCurve = calibrate(trades, DoubleArray.ofUnsafe(coupons), DoubleArray.ofUnsafe(pufs), name, valuationDate, discountFactors, recoveryRates, refData);

            if (computeJacobian)
            {
                LegalEntitySurvivalProbabilities            creditCurve      = LegalEntitySurvivalProbabilities.of(legalEntityId, IsdaCreditDiscountFactors.of(currency, valuationDate, nodalCurve));
                ImmutableCreditRatesProvider                ratesProviderNew = ratesProvider.toBuilder().creditCurves(ImmutableMap.of(Pair.of(legalEntityId, currency), creditCurve)).build();
                System.Func <ResolvedCdsTrade, DoubleArray> sensiFunc        = quoteConvention.Equals(CdsQuoteConvention.PAR_SPREAD) ? getParSpreadSensitivityFunction(ratesProviderNew, name, currency, refData) : getPointsUpfrontSensitivityFunction(ratesProviderNew, name, currency, refData);
                DoubleMatrix sensi = DoubleMatrix.ofArrayObjects(nNodes, nNodes, i => sensiFunc(trades.get(i)));
                sensi = (DoubleMatrix)MATRIX_ALGEBRA.multiply(DoubleMatrix.ofUnsafe(diag), sensi);
                JacobianCalibrationMatrix jacobian = JacobianCalibrationMatrix.of(ImmutableList.of(CurveParameterSize.of(name, nNodes)), MATRIX_ALGEBRA.getInverse(sensi));
                nodalCurve = nodalCurve.withMetadata(nodalCurve.Metadata.withInfo(CurveInfoType.JACOBIAN, jacobian));
            }

            ImmutableList <ParameterMetadata> parameterMetadata;

            if (storeTrade)
            {
                parameterMetadata = IntStream.range(0, nNodes).mapToObj(n => ResolvedTradeParameterMetadata.of(trades.get(n), curveNodes[n].Label)).collect(Guavate.toImmutableList());
            }
            else
            {
                parameterMetadata = IntStream.range(0, nNodes).mapToObj(n => curveNodes[n].metadata(trades.get(n).Product.ProtectionEndDate)).collect(Guavate.toImmutableList());
            }
            nodalCurve = nodalCurve.withMetadata(nodalCurve.Metadata.withParameterMetadata(parameterMetadata));

            return(LegalEntitySurvivalProbabilities.of(legalEntityId, IsdaCreditDiscountFactors.of(currency, valuationDate, nodalCurve)));
        }