CDSComponent.java

  1. package org.drip.product.credit;

  2. /*
  3.  * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  4.  */

  5. /*!
  6.  * Copyright (C) 2020 Lakshmi Krishnamurthy
  7.  * Copyright (C) 2019 Lakshmi Krishnamurthy
  8.  * Copyright (C) 2018 Lakshmi Krishnamurthy
  9.  * Copyright (C) 2017 Lakshmi Krishnamurthy
  10.  * Copyright (C) 2016 Lakshmi Krishnamurthy
  11.  * Copyright (C) 2015 Lakshmi Krishnamurthy
  12.  * Copyright (C) 2014 Lakshmi Krishnamurthy
  13.  * Copyright (C) 2013 Lakshmi Krishnamurthy
  14.  * Copyright (C) 2012 Lakshmi Krishnamurthy
  15.  * Copyright (C) 2011 Lakshmi Krishnamurthy
  16.  *
  17.  *  This file is part of DROP, an open-source library targeting analytics/risk, transaction cost analytics,
  18.  *      asset liability management analytics, capital, exposure, and margin analytics, valuation adjustment
  19.  *      analytics, and portfolio construction analytics within and across fixed income, credit, commodity,
  20.  *      equity, FX, and structured products. It also includes auxiliary libraries for algorithm support,
  21.  *      numerical analysis, numerical optimization, spline builder, model validation, statistical learning,
  22.  *      and computational support.
  23.  *  
  24.  *      https://lakshmidrip.github.io/DROP/
  25.  *  
  26.  *  DROP is composed of three modules:
  27.  *  
  28.  *  - DROP Product Core - https://lakshmidrip.github.io/DROP-Product-Core/
  29.  *  - DROP Portfolio Core - https://lakshmidrip.github.io/DROP-Portfolio-Core/
  30.  *  - DROP Computational Core - https://lakshmidrip.github.io/DROP-Computational-Core/
  31.  *
  32.  *  DROP Product Core implements libraries for the following:
  33.  *  - Fixed Income Analytics
  34.  *  - Loan Analytics
  35.  *  - Transaction Cost Analytics
  36.  *
  37.  *  DROP Portfolio Core implements libraries for the following:
  38.  *  - Asset Allocation Analytics
  39.  *  - Asset Liability Management Analytics
  40.  *  - Capital Estimation Analytics
  41.  *  - Exposure Analytics
  42.  *  - Margin Analytics
  43.  *  - XVA Analytics
  44.  *
  45.  *  DROP Computational Core implements libraries for the following:
  46.  *  - Algorithm Support
  47.  *  - Computation Support
  48.  *  - Function Analysis
  49.  *  - Model Validation
  50.  *  - Numerical Analysis
  51.  *  - Numerical Optimizer
  52.  *  - Spline Builder
  53.  *  - Statistical Learning
  54.  *
  55.  *  Documentation for DROP is Spread Over:
  56.  *
  57.  *  - Main                     => https://lakshmidrip.github.io/DROP/
  58.  *  - Wiki                     => https://github.com/lakshmiDRIP/DROP/wiki
  59.  *  - GitHub                   => https://github.com/lakshmiDRIP/DROP
  60.  *  - Repo Layout Taxonomy     => https://github.com/lakshmiDRIP/DROP/blob/master/Taxonomy.md
  61.  *  - Javadoc                  => https://lakshmidrip.github.io/DROP/Javadoc/index.html
  62.  *  - Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal
  63.  *  - Release Versions         => https://lakshmidrip.github.io/DROP/version.html
  64.  *  - Community Credits        => https://lakshmidrip.github.io/DROP/credits.html
  65.  *  - Issues Catalog           => https://github.com/lakshmiDRIP/DROP/issues
  66.  *  - JUnit                    => https://lakshmidrip.github.io/DROP/junit/index.html
  67.  *  - Jacoco                   => https://lakshmidrip.github.io/DROP/jacoco/index.html
  68.  *
  69.  *  Licensed under the Apache License, Version 2.0 (the "License");
  70.  *      you may not use this file except in compliance with the License.
  71.  *  
  72.  *  You may obtain a copy of the License at
  73.  *      http://www.apache.org/licenses/LICENSE-2.0
  74.  *  
  75.  *  Unless required by applicable law or agreed to in writing, software
  76.  *      distributed under the License is distributed on an "AS IS" BASIS,
  77.  *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  78.  *  
  79.  *  See the License for the specific language governing permissions and
  80.  *      limitations under the License.
  81.  */

  82. /**
  83.  * <i>CDSComponent</i> implements the credit default swap product contract details. It exposes the following
  84.  *  functionality:
  85.  *
  86.  * <br><br>
  87.  * <ul>
  88.  *  <li>
  89.  *      Methods to extract effective date, maturity date, coupon, coupon day count, coupon frequency,
  90.  *      contingent credit, currency, basket notional, credit valuation parameters, and optionally the
  91.  *      outstanding notional schedule.
  92.  *  </li>
  93.  *  <li>
  94.  *      Methods to compute the Jacobians to/from quote-to-latent state/manifest measures
  95.  *  </li>
  96.  *  <li>
  97.  *      Serialization into and de-serialization out of byte arrays
  98.  *  </li>
  99.  *  <li>
  100.  *      CDS specific methods such as such loss metric/Jacobian estimation, quote flat spread calibration etc:
  101.  *  </li>
  102.  * </ul>
  103.  *
  104.  *  <br><br>
  105.  *  <ul>
  106.  *      <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ProductCore.md">Product Core Module</a></li>
  107.  *      <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/FixedIncomeAnalyticsLibrary.md">Fixed Income Analytics</a></li>
  108.  *      <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/product/README.md">Product Components/Baskets for Credit, FRA, FX, Govvie, Rates, and Option AssetClasses</a></li>
  109.  *      <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/product/credit/README.md">Credit Products - Components and Baskets</a></li>
  110.  *  </ul>
  111.  * <br><br>
  112.  *
  113.  * @author Lakshmi Krishnamurthy
  114.  *
  115.  */

  116. public class CDSComponent extends org.drip.product.definition.CreditDefaultSwap {
  117.     private double _dblNotional = 100.;
  118.     private java.lang.String _strCode = "";
  119.     private java.lang.String _strName = "";
  120.     private boolean _bApplyAccEOMAdj = false;
  121.     private boolean _bApplyCpnEOMAdj = false;
  122.     private java.lang.String _strCouponCurrency = "";
  123.     private double _dblCoupon = java.lang.Double.NaN;
  124.     private int _iMaturityDate = java.lang.Integer.MIN_VALUE;
  125.     private int _iEffectiveDate = java.lang.Integer.MIN_VALUE;
  126.     private org.drip.numerical.common.Array2D _notlSchedule = null;
  127.     private org.drip.product.params.CreditSetting _crValParams = null;
  128.     private org.drip.param.valuation.CashSettleParams _settleParams = null;
  129.     private java.util.List<org.drip.analytics.cashflow.CompositePeriod> _lsCouponPeriod = null;

  130.     private org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> measures (
  131.         final java.lang.String strMeasureSetPrefix,
  132.         final org.drip.param.valuation.ValuationParams valParams,
  133.         final org.drip.param.pricer.CreditPricerParams pricerParamsIn,
  134.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  135.         final org.drip.param.valuation.ValuationCustomizationParams vcp)
  136.     {
  137.         if (null == valParams || null == csqs) return null;

  138.         org.drip.state.credit.CreditCurve cc = csqs.creditState (creditLabel());

  139.         org.drip.state.discount.MergedDiscountForwardCurve dcFunding = csqs.fundingState (fundingLabel());

  140.         if (null == cc || null == dcFunding) return null;

  141.         org.drip.param.pricer.CreditPricerParams pricerParams = null != pricerParamsIn ? pricerParamsIn :
  142.             org.drip.param.pricer.CreditPricerParams.Standard();

  143.         long lStart = System.nanoTime();

  144.         int iAccrualDays = 0;
  145.         double dblLossPV = 0.;
  146.         double dblExpLoss = 0.;
  147.         double dblAccrued01 = 0.;
  148.         double dblDirtyDV01 = 0.;
  149.         double dblLossNoRecPV = 0.;
  150.         double dblExpLossNoRec = 0.;
  151.         boolean bFirstPeriod = true;
  152.         double dblCashPayDF = java.lang.Double.NaN;

  153.         int iValueDate = valParams.valueDate();

  154.         int iLossPayLag = _crValParams.lossPayLag();

  155.         try {
  156.             for (org.drip.analytics.cashflow.CompositePeriod period : _lsCouponPeriod) {
  157.                 int iPayDate = period.payDate();

  158.                 if (iPayDate < iValueDate) continue;

  159.                 int iEndDate = period.endDate();

  160.                 int iStartDate = period.startDate();

  161.                 double dblPeriodNotional = notional (iStartDate, iValueDate);

  162.                 if (bFirstPeriod) {
  163.                     bFirstPeriod = false;

  164.                     if (iStartDate < iValueDate) {
  165.                         iAccrualDays = iValueDate - iStartDate;

  166.                         dblAccrued01 = period.accrualDCF (iValueDate) * 0.01 * dblPeriodNotional;
  167.                     }
  168.                 }

  169.                 double dblSurvProb = pricerParams.survivalToPayDate() ? cc.survival (iPayDate) :
  170.                     cc.survival (iEndDate);

  171.                 dblDirtyDV01 += 0.01 * period.couponDCF() * dcFunding.df (iPayDate) * dblSurvProb *
  172.                     dblPeriodNotional;

  173.                 for (org.drip.analytics.cashflow.LossQuadratureMetrics lp : period.lossMetrics (this,
  174.                     valParams, pricerParams, iEndDate, csqs)) {
  175.                     if (null == lp) continue;

  176.                     int iSubPeriodEndDate = lp.endDate();

  177.                     int iSubPeriodStartDate = lp.startDate();

  178.                     double dblSubPeriodDF = dcFunding.effectiveDF (iSubPeriodStartDate + iLossPayLag,
  179.                         iSubPeriodEndDate + iLossPayLag);

  180.                     double dblSubPeriodNotional = notional (iSubPeriodStartDate, iSubPeriodEndDate);

  181.                     double dblSubPeriodSurvival = cc.survival (iSubPeriodStartDate) - cc.survival
  182.                         (iSubPeriodEndDate);

  183.                     double dblRecovery = _crValParams.useCurveRecovery() ? cc.effectiveRecovery
  184.                         (iSubPeriodStartDate, iSubPeriodEndDate) : _crValParams.recovery();

  185.                     double dblSubPeriodExpLoss = (1. - dblRecovery) * 100. * dblSubPeriodSurvival *
  186.                         dblSubPeriodNotional;
  187.                     double dblSubPeriodExpLossNoRec = 100. * dblSubPeriodSurvival * dblSubPeriodNotional;
  188.                     dblLossPV += dblSubPeriodExpLoss * dblSubPeriodDF;
  189.                     dblLossNoRecPV += dblSubPeriodExpLossNoRec * dblSubPeriodDF;
  190.                     dblExpLoss += dblSubPeriodExpLoss;
  191.                     dblExpLossNoRec += dblSubPeriodExpLossNoRec;

  192.                     dblDirtyDV01 += 0.01 * lp.accrualDCF() * dblSubPeriodSurvival * dblSubPeriodDF *
  193.                         dblSubPeriodNotional;
  194.                 }
  195.             }

  196.             dblCashPayDF = dcFunding.df (null == _settleParams ? valParams.cashPayDate() :
  197.                 _settleParams.cashSettleDate (iValueDate));
  198.         } catch (java.lang.Exception e) {
  199.             e.printStackTrace();

  200.             return null;
  201.         }

  202.         dblLossPV /= dblCashPayDF;
  203.         dblDirtyDV01 /= dblCashPayDF;
  204.         dblLossNoRecPV /= dblCashPayDF;
  205.         double dblNotlFactor = _dblNotional * 0.01;
  206.         double dblCleanDV01 = dblDirtyDV01 - dblAccrued01;
  207.         double dblCleanPV = dblCleanDV01 * 10000. * _dblCoupon - dblLossPV;
  208.         double dblDirtyPV = dblDirtyDV01 * 10000. * _dblCoupon - dblLossPV;

  209.         org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> mapResult = new
  210.             org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double>();

  211.         mapResult.put (strMeasureSetPrefix + "AccrualDays", 1. * iAccrualDays);

  212.         mapResult.put (strMeasureSetPrefix + "Accrued", dblAccrued01 * _dblCoupon * dblNotlFactor);

  213.         mapResult.put (strMeasureSetPrefix + "Accrued01", dblAccrued01 * dblNotlFactor);

  214.         mapResult.put (strMeasureSetPrefix + "CleanDV01", dblCleanDV01 * dblNotlFactor);

  215.         mapResult.put (strMeasureSetPrefix + "CleanPV", dblCleanPV * dblNotlFactor);

  216.         mapResult.put (strMeasureSetPrefix + "CleanCouponPV", dblCleanDV01 * _dblCoupon * dblNotlFactor);

  217.         mapResult.put (strMeasureSetPrefix + "DirtyCouponPV", dblDirtyDV01 * _dblCoupon * dblNotlFactor);

  218.         mapResult.put (strMeasureSetPrefix + "DirtyDV01", dblDirtyDV01 * dblNotlFactor);

  219.         mapResult.put (strMeasureSetPrefix + "DirtyPV", dblDirtyPV * dblNotlFactor);

  220.         mapResult.put (strMeasureSetPrefix + "DV01", dblDirtyDV01 * dblNotlFactor);

  221.         mapResult.put (strMeasureSetPrefix + "ExpLoss", dblExpLoss * dblNotlFactor);

  222.         mapResult.put (strMeasureSetPrefix + "ExpLossNoRec", dblExpLossNoRec * dblNotlFactor);

  223.         mapResult.put (strMeasureSetPrefix + "FairPremium", dblLossPV / dblCleanDV01);

  224.         mapResult.put (strMeasureSetPrefix + "LossNoRecPV", dblLossNoRecPV * dblNotlFactor);

  225.         mapResult.put (strMeasureSetPrefix + "LossPV", dblLossPV * dblNotlFactor);

  226.         mapResult.put (strMeasureSetPrefix + "ParSpread", dblLossPV / dblCleanDV01);

  227.         mapResult.put (strMeasureSetPrefix + "PV", dblDirtyPV * dblNotlFactor);

  228.         mapResult.put (strMeasureSetPrefix + "Upfront", dblCleanPV * dblNotlFactor);

  229.         try {
  230.             double dblValueNotional = notional (iValueDate);

  231.             mapResult.put (strMeasureSetPrefix + "CleanPrice", 100. * (1. + (dblCleanPV / _dblNotional /
  232.                 dblValueNotional)));

  233.             mapResult.put (strMeasureSetPrefix + "DirtyPrice", 100. * (1. + (dblDirtyPV / _dblNotional /
  234.                 dblValueNotional)));

  235.             mapResult.put (strMeasureSetPrefix + "LossOnInstantaneousDefault", _dblNotional * (1. -
  236.                 cc.recovery (iValueDate)));

  237.             mapResult.put (strMeasureSetPrefix + "Price", 100. * (1. + (dblCleanPV / _dblNotional /
  238.                 dblValueNotional)));
  239.         } catch (java.lang.Exception e) {
  240.             e.printStackTrace();
  241.         }

  242.         mapResult.put (strMeasureSetPrefix + "CalcTime", (System.nanoTime() - lStart) * 1.e-09);

  243.         return mapResult;
  244.     }

  245.     private org.drip.numerical.differentiation.WengertJacobian calcPeriodOnDefaultPVDFMicroJack (
  246.         final double dblFairPremium,
  247.         final org.drip.analytics.cashflow.CompositePeriod period,
  248.         final org.drip.param.valuation.ValuationParams valParams,
  249.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  250.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs)
  251.     {
  252.         org.drip.state.discount.MergedDiscountForwardCurve dcFunding = csqs.fundingState (fundingLabel());

  253.         int iNumParameters = 0;
  254.         org.drip.numerical.differentiation.WengertJacobian wjPeriodOnDefaultPVDF = null;

  255.         for (org.drip.analytics.cashflow.LossQuadratureMetrics lpcf : period.lossMetrics (this, valParams,
  256.             pricerParams, period.endDate(), csqs)) {
  257.             org.drip.numerical.differentiation.WengertJacobian wjPeriodPayDFDF = dcFunding.jackDDFDManifestMeasure
  258.                 ((lpcf.startDate() + lpcf.endDate()) / 2 + _crValParams.lossPayLag(), "Rate");

  259.             try {
  260.                 if (null == wjPeriodOnDefaultPVDF)
  261.                     wjPeriodOnDefaultPVDF = new org.drip.numerical.differentiation.WengertJacobian (1, iNumParameters =
  262.                         wjPeriodPayDFDF.numParameters());

  263.                 double dblPeriodIncrementalCashFlow = notional (lpcf.startDate(), lpcf.endDate()) *
  264.                     (dblFairPremium * lpcf.accrualDCF() - 1. + lpcf.effectiveRecovery()) *
  265.                         (lpcf.startSurvival() - lpcf.endSurvival());

  266.                 for (int k = 0; k < iNumParameters; ++k) {
  267.                     if (!wjPeriodOnDefaultPVDF.accumulatePartialFirstDerivative (0, k,
  268.                         wjPeriodPayDFDF.firstDerivative (0, k) * dblPeriodIncrementalCashFlow))
  269.                         return null;
  270.                 }
  271.             } catch (java.lang.Exception e) {
  272.                 e.printStackTrace();

  273.                 return null;
  274.             }
  275.         }

  276.         return wjPeriodOnDefaultPVDF;
  277.     }

  278.     private PeriodLossMicroJack calcPeriodLossMicroJack (
  279.         final org.drip.analytics.cashflow.CompositePeriod period,
  280.         final org.drip.param.valuation.ValuationParams valParams,
  281.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  282.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs)
  283.     {
  284.         org.drip.state.discount.MergedDiscountForwardCurve dcFunding = csqs.fundingState (fundingLabel());

  285.         PeriodLossMicroJack plmj = null;

  286.         for (org.drip.analytics.cashflow.LossQuadratureMetrics lpcf : period.lossMetrics (this, valParams,
  287.             pricerParams, period.endDate(), csqs)) {
  288.             double dblPeriodNotional = java.lang.Double.NaN;
  289.             double dblPeriodIncrementalLoss = java.lang.Double.NaN;
  290.             double dblPeriodIncrementalAccrual = java.lang.Double.NaN;
  291.             double dblPeriodIncrementalSurvival = java.lang.Double.NaN;

  292.             int iPeriodEffectiveDate = (lpcf.startDate() + lpcf.endDate()) / 2;

  293.             org.drip.numerical.differentiation.WengertJacobian wjPeriodPayDFDF = dcFunding.jackDDFDManifestMeasure
  294.                 (iPeriodEffectiveDate + _crValParams.lossPayLag(), "Rate");

  295.             try {
  296.                 dblPeriodNotional = notional (lpcf.startDate(), lpcf.endDate());

  297.                 dblPeriodIncrementalSurvival = lpcf.startSurvival() - lpcf.endSurvival();

  298.                 dblPeriodIncrementalLoss = dblPeriodNotional * (1. - lpcf.effectiveRecovery()) *
  299.                     dblPeriodIncrementalSurvival;

  300.                 dblPeriodIncrementalAccrual = dblPeriodNotional * lpcf.accrualDCF() *
  301.                     dblPeriodIncrementalSurvival;

  302.                 if (null == plmj) plmj = new PeriodLossMicroJack (wjPeriodPayDFDF.numParameters());

  303.                 plmj._dblAccrOnDef01 += dblPeriodIncrementalAccrual * dcFunding.df (iPeriodEffectiveDate +
  304.                     _crValParams.lossPayLag());
  305.             } catch (java.lang.Exception e) {
  306.                 e.printStackTrace();

  307.                 return null;
  308.             }

  309.             for (int k = 0; k < wjPeriodPayDFDF.numParameters(); ++k) {
  310.                 if (!plmj._wjLossPVMicroJack.accumulatePartialFirstDerivative (0, k, dblPeriodIncrementalLoss
  311.                     * wjPeriodPayDFDF.firstDerivative (0, k)))
  312.                     return null;

  313.                 if (!plmj._wjAccrOnDef01MicroJack.accumulatePartialFirstDerivative (0, k,
  314.                     dblPeriodIncrementalAccrual * wjPeriodPayDFDF.firstDerivative (0, k)))
  315.                     return null;
  316.             }
  317.         }

  318.         return plmj;
  319.     }

  320.     private org.drip.analytics.cashflow.CompositePeriod calcCurrentPeriod (
  321.         final int iDate)
  322.     {
  323.         org.drip.analytics.cashflow.CompositePeriod cpFirst = _lsCouponPeriod.get (0);

  324.         if (iDate <= cpFirst.startDate()) return cpFirst;

  325.         for (org.drip.analytics.cashflow.CompositePeriod period : _lsCouponPeriod) {
  326.             try {
  327.                 if (period.contains (iDate)) return period;
  328.             } catch (java.lang.Exception e) {
  329.                 e.printStackTrace();

  330.                 return null;
  331.             }
  332.         }

  333.         return null;
  334.     }

  335.     /**
  336.      * CDSComponent constructor: Most generic CDS creation functionality
  337.      *
  338.      * @param iEffectiveDate Effective Date
  339.      * @param iMaturityDate Maturity Date
  340.      * @param dblCoupon Coupon
  341.      * @param iFreq Frequency
  342.      * @param strCouponDC Coupon DC
  343.      * @param strAccrualDC Accrual DC
  344.      * @param strFloatingRateIndex Floating Rate Index
  345.      * @param bConvCDS Is CDS Conventional
  346.      * @param dapEffective Effective DAP
  347.      * @param dapMaturity Maturity DAP
  348.      * @param dapPeriodStart Period Start DAP
  349.      * @param dapPeriodEnd Period End DAP
  350.      * @param dapAccrualStart Accrual Start DAP
  351.      * @param dapAccrualEnd Accrual End DAP
  352.      * @param dapPay Pay DAP
  353.      * @param dapReset Reset DAP
  354.      * @param notlSchedule Notional Schedule
  355.      * @param dblNotional Notional Amount
  356.      * @param strCouponCurrency Coupon Currency
  357.      * @param crValParams Credit Valuation Parameters
  358.      * @param strCalendar Calendar
  359.      *
  360.      * @throws java.lang.Exception Thrown if Inputs are Invalid
  361.      */

  362.     public CDSComponent (
  363.         final int iEffectiveDate,
  364.         final int iMaturityDate,
  365.         final double dblCoupon,
  366.         final int iFreq,
  367.         final java.lang.String strCouponDC,
  368.         final java.lang.String strAccrualDC,
  369.         final java.lang.String strFloatingRateIndex,
  370.         final boolean bConvCDS,
  371.         final org.drip.analytics.daycount.DateAdjustParams dapEffective,
  372.         final org.drip.analytics.daycount.DateAdjustParams dapMaturity,
  373.         final org.drip.analytics.daycount.DateAdjustParams dapPeriodStart,
  374.         final org.drip.analytics.daycount.DateAdjustParams dapPeriodEnd,
  375.         final org.drip.analytics.daycount.DateAdjustParams dapAccrualStart,
  376.         final org.drip.analytics.daycount.DateAdjustParams dapAccrualEnd,
  377.         final org.drip.analytics.daycount.DateAdjustParams dapPay,
  378.         final org.drip.analytics.daycount.DateAdjustParams dapReset,
  379.         final org.drip.numerical.common.Array2D notlSchedule,
  380.         final double dblNotional,
  381.         final java.lang.String strCouponCurrency,
  382.         final org.drip.product.params.CreditSetting crValParams,
  383.         final java.lang.String strCalendar)
  384.         throws java.lang.Exception
  385.     {
  386.         if (null == strCouponCurrency || (_strCouponCurrency = strCouponCurrency).isEmpty() || null ==
  387.             crValParams || !org.drip.numerical.common.NumberUtil.IsValid (dblCoupon))
  388.             throw new java.lang.Exception ("CDSComponent ctr: Invalid params!");

  389.         _dblCoupon = dblCoupon;
  390.         _crValParams = crValParams;
  391.         java.lang.String strTenor = (12 / iFreq) + "M";

  392.         if (null == (_notlSchedule = notlSchedule))
  393.             _notlSchedule = org.drip.numerical.common.Array2D.BulletSchedule();

  394.         org.drip.param.period.UnitCouponAccrualSetting ucas = new
  395.             org.drip.param.period.UnitCouponAccrualSetting (iFreq, strCouponDC, _bApplyCpnEOMAdj,
  396.                 strAccrualDC, _bApplyAccEOMAdj, _strCouponCurrency, true,
  397.                     org.drip.analytics.support.CompositePeriodBuilder.ACCRUAL_COMPOUNDING_RULE_GEOMETRIC);

  398.         org.drip.param.period.ComposableFixedUnitSetting cfus = new
  399.             org.drip.param.period.ComposableFixedUnitSetting (strTenor,
  400.                 org.drip.analytics.support.CompositePeriodBuilder.EDGE_DATE_SEQUENCE_SINGLE, null, 0., 0.,
  401.                     _strCouponCurrency);

  402.         org.drip.param.period.CompositePeriodSetting cps = new org.drip.param.period.CompositePeriodSetting
  403.             (iFreq, strTenor, _strCouponCurrency, null, _dblNotional = dblNotional, null, _notlSchedule,
  404.                 null, null == _crValParams ? null : org.drip.state.identifier.EntityCDSLabel.Standard
  405.                     (_crValParams.creditCurveName(), _strCouponCurrency));

  406.         java.util.List<java.lang.Integer> lsStreamEdgeDate =
  407.             org.drip.analytics.support.CompositePeriodBuilder.BackwardEdgeDates (new
  408.                 org.drip.analytics.date.JulianDate (_iEffectiveDate = iEffectiveDate), new
  409.                     org.drip.analytics.date.JulianDate (_iMaturityDate = iMaturityDate), strTenor,
  410.                         dapAccrualEnd, org.drip.analytics.support.CompositePeriodBuilder.SHORT_STUB);

  411.         if (null == (_lsCouponPeriod = org.drip.analytics.support.CompositePeriodBuilder.FixedCompositeUnit
  412.             (lsStreamEdgeDate, cps, ucas, cfus)) || 0 == _lsCouponPeriod.size())
  413.             throw new java.lang.Exception ("CDSComponent ctr: Cannot make Coupon Period List!");
  414.     }

  415.     @Override public java.lang.String primaryCode()
  416.     {
  417.         return _strCode;
  418.     }

  419.     @Override public void setPrimaryCode (
  420.         final java.lang.String strCode)
  421.     {
  422.         _strCode = strCode;
  423.     }

  424.     public boolean setName (
  425.         final java.lang.String strName)
  426.     {
  427.         _strName = strName;
  428.         return true;
  429.     }

  430.     @Override public java.lang.String name()
  431.     {
  432.         if (null != _strName && !_strName.isEmpty()) return _strName;

  433.         return "CDS=" + org.drip.analytics.date.DateUtil.YYYYMMDD (_iMaturityDate);
  434.     }

  435.     @Override public org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.String> couponCurrency()
  436.     {
  437.         org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.String> mapCouponCurrency = new
  438.             org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.String>();

  439.         mapCouponCurrency.put (name(), _strCouponCurrency);

  440.         return mapCouponCurrency;
  441.     }

  442.     @Override public java.lang.String payCurrency()
  443.     {
  444.         return _strCouponCurrency;
  445.     }

  446.     @Override public java.lang.String principalCurrency()
  447.     {
  448.         return null;
  449.     }

  450.     @Override public double initialNotional()
  451.     {
  452.         return _dblNotional;
  453.     }

  454.     @Override public double notional (
  455.         final int iDate)
  456.         throws java.lang.Exception
  457.     {
  458.         if (null == _notlSchedule) throw new java.lang.Exception ("CDSComponent::notional => Bad date");

  459.         return _notlSchedule.y (iDate);
  460.     }

  461.     @Override public double notional (
  462.         final int iDate1,
  463.         final int iDate2)
  464.         throws java.lang.Exception
  465.     {
  466.         if (null == _notlSchedule) throw new java.lang.Exception ("CDSComponent::notional => Bad date");

  467.         return _notlSchedule.y (iDate1, iDate2);
  468.     }

  469.     @Override public double recovery (
  470.         final int iDate,
  471.         final org.drip.state.credit.CreditCurve cc)
  472.         throws java.lang.Exception
  473.     {
  474.         if (null == cc) throw new java.lang.Exception ("CDSComponent::recovery => Bad inputs");

  475.         return _crValParams.useCurveRecovery() ? cc.recovery (iDate) : _crValParams.recovery();
  476.     }

  477.     @Override public double recovery (
  478.         final int iDateStart,
  479.         final int iDateEnd,
  480.         final org.drip.state.credit.CreditCurve cc)
  481.         throws java.lang.Exception
  482.     {
  483.         if (null == cc) throw new java.lang.Exception ("CDSComponent::recovery: Bad inputs");

  484.         double dblRecovery = _crValParams.useCurveRecovery() ? cc.effectiveRecovery (iDateStart, iDateEnd) :
  485.             _crValParams.recovery();

  486.         return dblRecovery;
  487.     }

  488.     @Override public org.drip.product.params.CreditSetting creditValuationParams()
  489.     {
  490.         return _crValParams;
  491.     }

  492.     @Override public org.drip.analytics.output.CompositePeriodCouponMetrics couponMetrics (
  493.         final int iAccrualEndDate,
  494.         final org.drip.param.valuation.ValuationParams valParams,
  495.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs)
  496.     {
  497.         try {
  498.             org.drip.analytics.cashflow.CompositePeriod period = calcCurrentPeriod (iAccrualEndDate);

  499.             return null == period ? null : period.couponMetrics (iAccrualEndDate, csqs);
  500.         } catch (java.lang.Exception e) {
  501.             e.printStackTrace();
  502.         }

  503.         return null;
  504.     }

  505.     @Override public int freq()
  506.     {
  507.         return couponPeriods().get (0).freq();
  508.     }

  509.     @Override public org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> calibMeasures (
  510.         final org.drip.param.valuation.ValuationParams valParams,
  511.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  512.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  513.         final org.drip.param.valuation.ValuationCustomizationParams vcp)
  514.     {
  515.         return null;
  516.     }

  517.     @Override public org.drip.state.identifier.EntityCDSLabel creditLabel()
  518.     {
  519.         return null == _crValParams || null == _crValParams.creditCurveName() ||
  520.             _crValParams.creditCurveName().isEmpty() ? null : org.drip.state.identifier.EntityCDSLabel.Standard
  521.                 (_crValParams.creditCurveName(), _strCouponCurrency);
  522.     }

  523.     @Override public
  524.         org.drip.analytics.support.CaseInsensitiveTreeMap<org.drip.state.identifier.ForwardLabel>
  525.             forwardLabel()
  526.     {
  527.         return null;
  528.     }

  529.     @Override public
  530.         org.drip.analytics.support.CaseInsensitiveTreeMap<org.drip.state.identifier.OTCFixFloatLabel>
  531.             otcFixFloatLabel()
  532.     {
  533.         return null;
  534.     }

  535.     @Override public org.drip.state.identifier.FundingLabel fundingLabel()
  536.     {
  537.         return org.drip.state.identifier.FundingLabel.Standard (_strCouponCurrency);
  538.     }

  539.     @Override public org.drip.state.identifier.GovvieLabel govvieLabel()
  540.     {
  541.         return org.drip.state.identifier.GovvieLabel.Standard (payCurrency());
  542.     }

  543.     @Override public org.drip.analytics.support.CaseInsensitiveTreeMap<org.drip.state.identifier.FXLabel>
  544.         fxLabel()
  545.     {
  546.         return null;
  547.     }

  548.     @Override public
  549.         org.drip.analytics.support.CaseInsensitiveTreeMap<org.drip.state.identifier.VolatilityLabel>
  550.             volatilityLabel()
  551.     {
  552.         return null;
  553.     }

  554.     @Override public org.drip.analytics.date.JulianDate effectiveDate()
  555.     {
  556.         try {
  557.             return new org.drip.analytics.date.JulianDate (_iEffectiveDate);
  558.         } catch (java.lang.Exception e) {
  559.             e.printStackTrace();
  560.         }

  561.         return null;
  562.     }

  563.     @Override public org.drip.analytics.date.JulianDate maturityDate()
  564.     {
  565.         try {
  566.             return new org.drip.analytics.date.JulianDate (_iMaturityDate);
  567.         } catch (java.lang.Exception e) {
  568.             e.printStackTrace();
  569.         }

  570.         return null;
  571.     }

  572.     @Override public org.drip.analytics.date.JulianDate firstCouponDate()
  573.     {
  574.         try {
  575.             return new org.drip.analytics.date.JulianDate (_lsCouponPeriod.get (0).endDate());
  576.         } catch (java.lang.Exception e) {
  577.             e.printStackTrace();
  578.         }

  579.         return null;
  580.     }

  581.     @Override public java.util.List<org.drip.analytics.cashflow.CompositePeriod> couponPeriods()
  582.     {
  583.         return _lsCouponPeriod;
  584.     }

  585.     @Override public org.drip.param.valuation.CashSettleParams cashSettleParams()
  586.     {
  587.         return _settleParams;
  588.     }

  589.     @Override public java.util.List<org.drip.analytics.cashflow.LossQuadratureMetrics> lossFlow (
  590.         final org.drip.param.valuation.ValuationParams valParams,
  591.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  592.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs)
  593.     {
  594.         if (null == valParams || null == pricerParams) return null;

  595.         java.util.List<org.drip.analytics.cashflow.LossQuadratureMetrics> sLP = new
  596.             java.util.ArrayList<org.drip.analytics.cashflow.LossQuadratureMetrics>();

  597.         int iValueDate = valParams.valueDate();

  598.         for (org.drip.analytics.cashflow.CompositePeriod period : _lsCouponPeriod) {
  599.             int iPeriodEndDate = period.endDate();

  600.             if (null == period || iPeriodEndDate < iValueDate) continue;

  601.             java.util.List<org.drip.analytics.cashflow.LossQuadratureMetrics> sLPSub = period.lossMetrics
  602.                 (this, valParams, pricerParams, iPeriodEndDate, csqs);

  603.             if (null != sLPSub) sLP.addAll (sLPSub);
  604.         }

  605.         return sLP;
  606.     }

  607.     @Override public org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> value (
  608.         final org.drip.param.valuation.ValuationParams valParams,
  609.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  610.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  611.         final org.drip.param.valuation.ValuationCustomizationParams vcp)
  612.     {
  613.         org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> mapFairMeasures = measures ("",
  614.             valParams, pricerParams, csqs, vcp);

  615.         if (null == mapFairMeasures) return null;

  616.         org.drip.numerical.common.CollectionUtil.MergeWithMain (mapFairMeasures,
  617.             org.drip.numerical.common.CollectionUtil.PrefixKeys (mapFairMeasures, "Fair"));

  618.         org.drip.analytics.cashflow.ComposableUnitPeriod cupFirst = _lsCouponPeriod.get (0).periods().get
  619.             (0);

  620.         try {
  621.             mapFairMeasures.put ("CumulativeCouponAmount", _dblNotional * _dblCoupon *
  622.                 org.drip.analytics.daycount.Convention.YearFraction (_iEffectiveDate, valParams.valueDate(),
  623.                     cupFirst.couponDC(), _bApplyAccEOMAdj, null, cupFirst.calendar()));
  624.         } catch (java.lang.Exception e) {
  625.             e.printStackTrace();
  626.         }

  627.         java.lang.String strName = name();

  628.         org.drip.param.definition.ProductQuote cq = csqs.productQuote (strName);

  629.         if ((null != pricerParams && null != pricerParams.calibParams()) || null == mapFairMeasures || null
  630.             == cq)
  631.             return mapFairMeasures;

  632.         double dblCreditBasis = java.lang.Double.NaN;
  633.         double dblMarketMeasure = java.lang.Double.NaN;
  634.         org.drip.state.credit.CreditCurve ccMarket = null;

  635.         if (cq.containsQuote ("Price"))
  636.             mapFairMeasures.put ("MarketInputType=Price", dblMarketMeasure = cq.quote ("Price").value
  637.                 ("mid"));
  638.         else if (cq.containsQuote ("CleanPrice"))
  639.             mapFairMeasures.put ("MarketInputType=CleanPrice", dblMarketMeasure = cq.quote
  640.                 ("CleanPrice").value ("mid"));
  641.         else if (cq.containsQuote ("Upfront"))
  642.             mapFairMeasures.put ("MarketInputType=Upfront", dblMarketMeasure = cq.quote ("Upfront").value
  643.                 ("mid"));
  644.         else if (cq.containsQuote ("FairPremium"))
  645.             mapFairMeasures.put ("MarketInputType=FairPremium", dblMarketMeasure = cq.quote
  646.                 ("FairPremium").value ("mid"));
  647.         else if (cq.containsQuote ("PV"))
  648.             mapFairMeasures.put ("MarketInputType=PV", dblMarketMeasure = cq.quote ("PV").value ("mid"));
  649.         else if (cq.containsQuote ("CleanPV"))
  650.             mapFairMeasures.put ("MarketInputType=CleanPV", dblMarketMeasure = cq.quote ("CleanPV").value
  651.                 ("mid"));

  652.         try {
  653.             SpreadCalibOP scop = new SpreadCalibrator (this,
  654.                 SpreadCalibrator.CALIBRATION_TYPE_NODE_PARALLEL_BUMP).calibrateHazardFromPrice (valParams,
  655.                     new org.drip.param.pricer.CreditPricerParams (7,
  656.                         org.drip.param.definition.CalibrationParams.Standard(), false,
  657.                             org.drip.param.pricer.CreditPricerParams.PERIOD_DISCRETIZATION_DAY_STEP), csqs,
  658.                                 vcp, dblMarketMeasure);

  659.             if (null != scop) {
  660.                 ccMarket = scop._ccCalib;
  661.                 dblCreditBasis = scop._dblCalibResult;
  662.             }
  663.         } catch (java.lang.Exception e) {
  664.             e.printStackTrace();
  665.         }

  666.         if (org.drip.numerical.common.NumberUtil.IsValid (dblCreditBasis)) {
  667.             mapFairMeasures.put ("MarketCreditBasis", dblCreditBasis);

  668.             org.drip.state.credit.CreditCurve cc = csqs.creditState (creditLabel());

  669.             try {
  670.                 ccMarket = (org.drip.state.credit.CreditCurve) cc.customTweakManifestMeasure
  671.                     ("FairPremium", new org.drip.param.definition.ManifestMeasureTweak
  672.                         (org.drip.param.definition.ManifestMeasureTweak.FLAT, false, dblCreditBasis));
  673.             } catch (java.lang.Exception e) {
  674.                 e.printStackTrace();
  675.             }
  676.         }

  677.         org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> mapMeasures = mapFairMeasures;

  678.         if (null != ccMarket) {
  679.             org.drip.param.market.CurveSurfaceQuoteContainer csqsMarket =
  680.                 org.drip.param.creator.MarketParamsBuilder.Create (csqs.fundingState (fundingLabel()),
  681.                     csqs.govvieState (org.drip.state.identifier.GovvieLabel.Standard (payCurrency())),
  682.                         ccMarket, strName, csqs.productQuote (strName), csqs.quoteMap(), csqs.fixings());

  683.             if (null != csqsMarket) {
  684.                 org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> mapMarketMeasures =
  685.                     measures ("", valParams, pricerParams, csqsMarket, vcp);

  686.                 if (null != mapMarketMeasures) {
  687.                     org.drip.numerical.common.CollectionUtil.MergeWithMain (mapMarketMeasures,
  688.                         org.drip.numerical.common.CollectionUtil.PrefixKeys (mapMarketMeasures, "Market"));

  689.                     org.drip.numerical.common.CollectionUtil.MergeWithMain (mapMeasures, mapMarketMeasures);
  690.                 }
  691.             }
  692.         }

  693.         return mapMeasures;
  694.     }

  695.     @Override public java.util.Set<java.lang.String> measureNames()
  696.     {
  697.         java.util.Set<java.lang.String> setstrMeasureNames = new java.util.TreeSet<java.lang.String>();

  698.         setstrMeasureNames.add ("AccrualDays");

  699.         setstrMeasureNames.add ("Accrued");

  700.         setstrMeasureNames.add ("Accrued01");

  701.         setstrMeasureNames.add ("CleanCouponPV");

  702.         setstrMeasureNames.add ("CleanDV01");

  703.         setstrMeasureNames.add ("CleanPV");

  704.         setstrMeasureNames.add ("DirtyCouponPV");

  705.         setstrMeasureNames.add ("DirtyDV01");

  706.         setstrMeasureNames.add ("DirtyPV");

  707.         setstrMeasureNames.add ("DV01");

  708.         setstrMeasureNames.add ("ExpLoss");

  709.         setstrMeasureNames.add ("ExpLossNoRec");

  710.         setstrMeasureNames.add ("FairAccrualDays");

  711.         setstrMeasureNames.add ("FairAccrued");

  712.         setstrMeasureNames.add ("FairAccrued01");

  713.         setstrMeasureNames.add ("FairCleanDV01");

  714.         setstrMeasureNames.add ("FairCleanPV");

  715.         setstrMeasureNames.add ("FairDirtyDV01");

  716.         setstrMeasureNames.add ("FairDirtyPV");

  717.         setstrMeasureNames.add ("FairDV01");

  718.         setstrMeasureNames.add ("FairExpLoss");

  719.         setstrMeasureNames.add ("FairExpLossNoRec");

  720.         setstrMeasureNames.add ("FairFairPremium");

  721.         setstrMeasureNames.add ("FairLossNoRecPV");

  722.         setstrMeasureNames.add ("FairLossPV");

  723.         setstrMeasureNames.add ("FairParSpread");

  724.         setstrMeasureNames.add ("FairPremium");

  725.         setstrMeasureNames.add ("FairPremiumPV");

  726.         setstrMeasureNames.add ("FairPV");

  727.         setstrMeasureNames.add ("FairUpfront");

  728.         setstrMeasureNames.add ("LossNoRecPV");

  729.         setstrMeasureNames.add ("LossPV");

  730.         setstrMeasureNames.add ("MarketAccrualDays");

  731.         setstrMeasureNames.add ("MarketAccrued");

  732.         setstrMeasureNames.add ("MarketAccrued01");

  733.         setstrMeasureNames.add ("MarketCleanDV01");

  734.         setstrMeasureNames.add ("MarketCleanPV");

  735.         setstrMeasureNames.add ("MarketDirtyDV01");

  736.         setstrMeasureNames.add ("MarketDirtyPV");

  737.         setstrMeasureNames.add ("MarketDV01");

  738.         setstrMeasureNames.add ("MarketExpLoss");

  739.         setstrMeasureNames.add ("MarketExpLossNoRec");

  740.         setstrMeasureNames.add ("MarketFairPremium");

  741.         setstrMeasureNames.add ("MarketLossNoRecPV");

  742.         setstrMeasureNames.add ("MarketLossPV");

  743.         setstrMeasureNames.add ("MarketParSpread");

  744.         setstrMeasureNames.add ("MarketPremiumPV");

  745.         setstrMeasureNames.add ("MarketPV");

  746.         setstrMeasureNames.add ("MarketUpfront");

  747.         setstrMeasureNames.add ("ParSpread");

  748.         setstrMeasureNames.add ("PV");

  749.         setstrMeasureNames.add ("Upfront");

  750.         return setstrMeasureNames;
  751.     }

  752.     @Override public double pv (
  753.         final org.drip.param.valuation.ValuationParams valParams,
  754.         final org.drip.param.pricer.CreditPricerParams pricerParamsIn,
  755.         final org.drip.param.market.CurveSurfaceQuoteContainer csqc,
  756.         final org.drip.param.valuation.ValuationCustomizationParams vcp)
  757.         throws java.lang.Exception
  758.     {
  759.         if (null == valParams || null == csqc)
  760.             throw new java.lang.Exception ("CDSComponent::pv => Invalid Inputs");

  761.         org.drip.state.credit.CreditCurve cc = csqc.creditState (creditLabel());

  762.         org.drip.state.discount.MergedDiscountForwardCurve dcFunding = csqc.fundingState (fundingLabel());

  763.         if (null == cc || null == dcFunding)
  764.             throw new java.lang.Exception ("CDSComponent::pv => Invalid Inputs");

  765.         org.drip.param.pricer.CreditPricerParams pricerParams = null != pricerParamsIn ? pricerParamsIn :
  766.             org.drip.param.pricer.CreditPricerParams.Standard();

  767.         double dblLossPV = 0.;
  768.         double dblDirtyDV01 = 0.;

  769.         int iValueDate = valParams.valueDate();

  770.         for (org.drip.analytics.cashflow.CompositePeriod period : _lsCouponPeriod) {
  771.             int iPayDate = period.payDate();

  772.             if (iPayDate < iValueDate) continue;

  773.             int iEndDate = period.endDate();

  774.             int iStartDate = period.startDate();

  775.             int iLossPayLag = _crValParams.lossPayLag();

  776.             double dblPeriodNotional = notional (iStartDate, iValueDate);

  777.             dblDirtyDV01 += 0.01 * period.couponDCF() * dcFunding.df (iPayDate) *
  778.                 (pricerParams.survivalToPayDate() ? cc.survival (iPayDate) : cc.survival (iEndDate)) *
  779.                     dblPeriodNotional;

  780.             for (org.drip.analytics.cashflow.LossQuadratureMetrics lp : period.lossMetrics (this, valParams,
  781.                 pricerParams, iEndDate, csqc)) {
  782.                 if (null == lp) continue;

  783.                 int iSubPeriodEndDate = lp.endDate();

  784.                 int iSubPeriodStartDate = lp.startDate();

  785.                 double dblSubPeriodDF = dcFunding.effectiveDF (iSubPeriodStartDate + iLossPayLag,
  786.                     iSubPeriodEndDate + iLossPayLag);

  787.                 double dblSubPeriodNotional = notional (iSubPeriodStartDate, iSubPeriodEndDate);

  788.                 double dblSubPeriodSurvival = cc.survival (iSubPeriodStartDate) - cc.survival
  789.                     (iSubPeriodEndDate);

  790.                 double dblSubPeriodExpLoss = (1. - (_crValParams.useCurveRecovery() ? cc.effectiveRecovery
  791.                     (iSubPeriodStartDate, iSubPeriodEndDate) : _crValParams.recovery())) * 100. *
  792.                         dblSubPeriodSurvival * dblSubPeriodNotional;

  793.                 dblLossPV += dblSubPeriodExpLoss * dblSubPeriodDF;

  794.                 dblDirtyDV01 += 0.01 * lp.accrualDCF() * dblSubPeriodSurvival * dblSubPeriodDF *
  795.                     dblSubPeriodNotional;
  796.             }
  797.         }

  798.         return (dblDirtyDV01 * 10000. * _dblCoupon - dblLossPV) * _dblNotional * 0.01 / dcFunding.df (null ==
  799.             _settleParams ? valParams.cashPayDate() : _settleParams.cashSettleDate (iValueDate));
  800.     }

  801.     @Override public org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double>
  802.         valueFromQuotedSpread (
  803.             final org.drip.param.valuation.ValuationParams valParams,
  804.             final org.drip.param.pricer.CreditPricerParams pricerParams,
  805.             final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  806.             final org.drip.param.valuation.ValuationCustomizationParams vcp,
  807.             final double dblFixCoupon,
  808.             final double dblQuotedSpread)
  809.     {
  810.         if (null == valParams || !org.drip.numerical.common.NumberUtil.IsValid (dblFixCoupon) ||
  811.             !org.drip.numerical.common.NumberUtil.IsValid (dblQuotedSpread))
  812.             return null;

  813.         org.drip.product.definition.CalibratableComponent[] aComp = new
  814.             org.drip.product.definition.CalibratableComponent[] {this};
  815.         org.drip.state.credit.CreditCurve cc = null;
  816.         double[] adblRestorableCDSCoupon = new double[1];
  817.         adblRestorableCDSCoupon[0] = _dblCoupon;
  818.         _dblCoupon = dblFixCoupon;

  819.         if (null != csqs) {
  820.             org.drip.product.definition.CalibratableComponent[] aMktComp = null;

  821.             cc = csqs.creditState (creditLabel());

  822.             if (null != cc && null != (aMktComp = cc.calibComp())) {
  823.                 int iNumComp = aMktComp.length;

  824.                 if (0 != iNumComp) {
  825.                     aComp = aMktComp;
  826.                     adblRestorableCDSCoupon = new double[iNumComp];

  827.                     for (int i = 0; i < iNumComp; ++i) {
  828.                         if (null != aComp[i] && aComp[i] instanceof
  829.                             org.drip.product.definition.CreditDefaultSwap) {
  830.                             try {
  831.                                 org.drip.analytics.output.CompositePeriodCouponMetrics cpcm = couponMetrics
  832.                                     (valParams.valueDate(), valParams, csqs);

  833.                                 if (null == cpcm) return null;

  834.                                 adblRestorableCDSCoupon[i] = cpcm.rate();

  835.                                 ((org.drip.product.definition.CreditDefaultSwap) aComp[i]).resetCoupon
  836.                                     (dblFixCoupon);
  837.                             } catch (java.lang.Exception e) {
  838.                                 e.printStackTrace();

  839.                                 return null;
  840.                             }
  841.                         }
  842.                     }
  843.                 }
  844.             }
  845.         }

  846.         int iNumCalibComp = aComp.length;
  847.         double[] adblQS = new double[iNumCalibComp];
  848.         org.drip.state.credit.CreditCurve ccQS = null;
  849.         java.lang.String[] astrCalibMeasure = new java.lang.String[iNumCalibComp];

  850.         for (int i = 0; i < iNumCalibComp; ++i) {
  851.             adblQS[i] = dblQuotedSpread;
  852.             astrCalibMeasure[i] = "FairPremium";
  853.         }

  854.         org.drip.state.discount.MergedDiscountForwardCurve dcFunding = csqs.fundingState (fundingLabel());

  855.         try {
  856.             if (null == (ccQS = org.drip.state.creator.ScenarioCreditCurveBuilder.Custom
  857.                 (creditLabel().referenceEntity(), new org.drip.analytics.date.JulianDate
  858.                     (valParams.valueDate()), aComp, dcFunding, adblQS, astrCalibMeasure, null != cc ?
  859.                         cc.recovery (valParams.valueDate()) : 0.4, true)))
  860.                 return null;
  861.         } catch (java.lang.Exception e) {
  862.             e.printStackTrace();

  863.             return null;
  864.         }

  865.         org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> mapPV = value (valParams,
  866.             pricerParams, org.drip.param.creator.MarketParamsBuilder.Credit (dcFunding, ccQS), vcp);

  867.         for (int i = 0; i < iNumCalibComp; ++i) {
  868.             try {
  869.                 ((org.drip.product.definition.CreditDefaultSwap) aComp[i]).resetCoupon
  870.                     (adblRestorableCDSCoupon[i]);
  871.             } catch (java.lang.Exception e) {
  872.                 e.printStackTrace();

  873.                 return null;
  874.             }
  875.         }

  876.         return mapPV;
  877.     }

  878.     @Override public org.drip.numerical.differentiation.WengertJacobian jackDDirtyPVDManifestMeasure (
  879.         final org.drip.param.valuation.ValuationParams valParams,
  880.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  881.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  882.         final org.drip.param.valuation.ValuationCustomizationParams vcp)
  883.     {
  884.         if (null == valParams || null == csqs) return null;

  885.         int iValueDate = valParams.valueDate();

  886.         if (iValueDate >= _iMaturityDate) return null;

  887.         org.drip.state.credit.CreditCurve cc = csqs.creditState (creditLabel());

  888.         org.drip.state.discount.MergedDiscountForwardCurve dc = csqs.fundingState (fundingLabel());

  889.         if (null == cc || null == dc) return null;

  890.         org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> mapMeasures = value (valParams,
  891.             pricerParams, csqs, vcp);

  892.         if (null == mapMeasures) return null;

  893.         double dblPV = mapMeasures.get ("PV");

  894.         double dblFairPremium = mapMeasures.get ("FairPremium");

  895.         try {
  896.             org.drip.numerical.differentiation.WengertJacobian wjPVDFMicroJack = null;

  897.             for (org.drip.analytics.cashflow.CompositePeriod p : _lsCouponPeriod) {
  898.                 int iPeriodPayDate = p.payDate();

  899.                 if (iPeriodPayDate < iValueDate) continue;

  900.                 org.drip.numerical.differentiation.WengertJacobian wjPeriodPayDFDF = dc.jackDDFDManifestMeasure
  901.                     (iPeriodPayDate, "Rate");

  902.                 org.drip.numerical.differentiation.WengertJacobian wjPeriodOnDefaultPVMicroJack =
  903.                     calcPeriodOnDefaultPVDFMicroJack (dblFairPremium, p, valParams, pricerParams, csqs);

  904.                 if (null == wjPeriodPayDFDF | null == wjPeriodOnDefaultPVMicroJack) continue;

  905.                 if (null == wjPVDFMicroJack)
  906.                     wjPVDFMicroJack = new org.drip.numerical.differentiation.WengertJacobian (1,
  907.                         wjPeriodPayDFDF.numParameters());

  908.                 double dblPeriodCashFlow = dblFairPremium * notional (p.startDate(), p.endDate()) *
  909.                     p.couponDCF() * cc.survival (iPeriodPayDate);

  910.                 for (int k = 0; k < wjPeriodPayDFDF.numParameters(); ++k) {
  911.                     if (!wjPVDFMicroJack.accumulatePartialFirstDerivative (0, k, dblPeriodCashFlow *
  912.                         wjPeriodPayDFDF.firstDerivative (0, k) + wjPeriodOnDefaultPVMicroJack.firstDerivative
  913.                             (0, k)))
  914.                         return null;
  915.                 }
  916.             }

  917.             return adjustForCashSettle (valParams.cashPayDate(), dblPV, dc, wjPVDFMicroJack) ?
  918.                 wjPVDFMicroJack : null;
  919.         } catch (java.lang.Exception e) {
  920.             e.printStackTrace();
  921.         }

  922.         return null;
  923.     }

  924.     @Override public org.drip.numerical.differentiation.WengertJacobian manifestMeasureDFMicroJack (
  925.         final java.lang.String strManifestMeasure,
  926.         final org.drip.param.valuation.ValuationParams valParams,
  927.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  928.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  929.         final org.drip.param.valuation.ValuationCustomizationParams vcp)
  930.     {
  931.         if (null == valParams || null == strManifestMeasure || null == csqs) return null;

  932.         int iValueDate = valParams.valueDate();

  933.         if (iValueDate >= _iMaturityDate) return null;

  934.         org.drip.state.credit.CreditCurve cc = csqs.creditState (creditLabel());

  935.         org.drip.state.discount.MergedDiscountForwardCurve dcFunding = csqs.fundingState (fundingLabel());

  936.         if (null == cc || null == dcFunding) return null;

  937.         if ("Rate".equalsIgnoreCase (strManifestMeasure) || "FairPremium".equalsIgnoreCase
  938.             (strManifestMeasure) || "ParSpread".equalsIgnoreCase (strManifestMeasure)) {
  939.             org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> mapMeasures = value
  940.                 (valParams, pricerParams, csqs, vcp);

  941.             if (null == mapMeasures) return null;

  942.             double dblFairPremium = mapMeasures.get ("FairPremium");

  943.             try {
  944.                 double dblDV01 = 0.;
  945.                 org.drip.numerical.differentiation.WengertJacobian wjFairPremiumDFMicroJack = null;

  946.                 for (org.drip.analytics.cashflow.CompositePeriod p : _lsCouponPeriod) {
  947.                     int iPeriodPayDate = p.payDate();

  948.                     if (iPeriodPayDate < iValueDate) continue;

  949.                     int iPeriodEndDate = p.endDate();

  950.                     org.drip.numerical.differentiation.WengertJacobian wjPeriodPayDFDF =
  951.                         dcFunding.jackDDFDManifestMeasure (iPeriodEndDate, "Rate");

  952.                     PeriodLossMicroJack plmj = calcPeriodLossMicroJack (p, valParams, pricerParams, csqs);

  953.                     if (null == wjPeriodPayDFDF | null == plmj) continue;

  954.                     if (null == wjFairPremiumDFMicroJack)
  955.                         wjFairPremiumDFMicroJack = new org.drip.numerical.differentiation.WengertJacobian (1,
  956.                             wjPeriodPayDFDF.numParameters());

  957.                     double dblPeriodCoupon01 = notional (p.startDate(), iPeriodEndDate) * p.couponDCF() *
  958.                         cc.survival (iPeriodEndDate);

  959.                     dblDV01 += dblPeriodCoupon01 * dcFunding.df (iPeriodPayDate) + plmj._dblAccrOnDef01;

  960.                     for (int k = 0; k < wjPeriodPayDFDF.numParameters(); ++k) {
  961.                         double dblPeriodNetLossJack = plmj._wjLossPVMicroJack.firstDerivative (0, k) -
  962.                             dblFairPremium * (plmj._wjAccrOnDef01MicroJack.firstDerivative (0, k) +
  963.                                 dblPeriodCoupon01 * wjPeriodPayDFDF.firstDerivative (0, k));

  964.                         if (!wjFairPremiumDFMicroJack.accumulatePartialFirstDerivative (0, k,
  965.                             dblPeriodNetLossJack))
  966.                             return null;
  967.                     }
  968.                 }

  969.                 return wjFairPremiumDFMicroJack.scale (dblDV01) ? wjFairPremiumDFMicroJack : null;
  970.             } catch (java.lang.Exception e) {
  971.                 e.printStackTrace();
  972.             }
  973.         }

  974.         return null;
  975.     }

  976.     @Override public org.drip.product.calib.ProductQuoteSet calibQuoteSet (
  977.         final org.drip.state.representation.LatentStateSpecification[] aLSS)
  978.     {
  979.         return null;
  980.     }

  981.     @Override public org.drip.state.estimator.PredictorResponseWeightConstraint fundingPRWC (
  982.         final org.drip.param.valuation.ValuationParams valParams,
  983.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  984.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  985.         final org.drip.param.valuation.ValuationCustomizationParams vcp,
  986.         final org.drip.product.calib.ProductQuoteSet pqs)
  987.     {
  988.         return null;
  989.     }

  990.     @Override public org.drip.state.estimator.PredictorResponseWeightConstraint forwardPRWC (
  991.         final org.drip.param.valuation.ValuationParams valParams,
  992.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  993.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  994.         final org.drip.param.valuation.ValuationCustomizationParams vcp,
  995.         final org.drip.product.calib.ProductQuoteSet pqs)
  996.     {
  997.         return null;
  998.     }

  999.     @Override public org.drip.state.estimator.PredictorResponseWeightConstraint fundingForwardPRWC (
  1000.         final org.drip.param.valuation.ValuationParams valParams,
  1001.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  1002.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  1003.         final org.drip.param.valuation.ValuationCustomizationParams vcp,
  1004.         final org.drip.product.calib.ProductQuoteSet pqs)
  1005.     {
  1006.         return null;
  1007.     }

  1008.     @Override public org.drip.state.estimator.PredictorResponseWeightConstraint fxPRWC (
  1009.         final org.drip.param.valuation.ValuationParams valParams,
  1010.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  1011.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  1012.         final org.drip.param.valuation.ValuationCustomizationParams vcp,
  1013.         final org.drip.product.calib.ProductQuoteSet pqs)
  1014.     {
  1015.         return null;
  1016.     }

  1017.     @Override public org.drip.state.estimator.PredictorResponseWeightConstraint govviePRWC (
  1018.         final org.drip.param.valuation.ValuationParams valParams,
  1019.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  1020.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  1021.         final org.drip.param.valuation.ValuationCustomizationParams vcp,
  1022.         final org.drip.product.calib.ProductQuoteSet pqs)
  1023.     {
  1024.         return null;
  1025.     }

  1026.     @Override public org.drip.state.estimator.PredictorResponseWeightConstraint volatilityPRWC (
  1027.         final org.drip.param.valuation.ValuationParams valParams,
  1028.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  1029.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  1030.         final org.drip.param.valuation.ValuationCustomizationParams vcp,
  1031.         final org.drip.product.calib.ProductQuoteSet pqs)
  1032.     {
  1033.         return null;
  1034.     }

  1035.     /**
  1036.      * Reset the CDS's coupon
  1037.      *
  1038.      * @param dblCoupon The new Coupon
  1039.      *
  1040.      * @return The old Coupon
  1041.      *
  1042.      * @throws java.lang.Exception Thrown if the coupon cannot be reset
  1043.      */

  1044.     public double resetCoupon (
  1045.         final double dblCoupon)
  1046.         throws java.lang.Exception
  1047.     {
  1048.         double dblOldCoupon = _dblCoupon;

  1049.         if (!org.drip.numerical.common.NumberUtil.IsValid (_dblCoupon = dblCoupon))
  1050.             throw new java.lang.Exception ("CDSComponent::resetCoupon => Bad coupon Input!");

  1051.         return dblOldCoupon;
  1052.     }

  1053.     /**
  1054.      * Calibrate the CDS's flat spread from the calculated up-front points
  1055.      *
  1056.      * @param valParams ValuationParams
  1057.      * @param pricerParams PricerParams
  1058.      * @param csqs ComponentMarketParams
  1059.      *
  1060.      * @return Calibrated flat spread
  1061.      *
  1062.      * @throws java.lang.Exception Thrown if cannot calibrate
  1063.      */

  1064.     public double calibFlatSpread (
  1065.         final org.drip.param.valuation.ValuationParams valParams,
  1066.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  1067.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  1068.         final org.drip.param.valuation.ValuationCustomizationParams vcp)
  1069.         throws java.lang.Exception
  1070.     {
  1071.         SpreadCalibOP scop = new SpreadCalibrator (this,
  1072.             SpreadCalibrator.CALIBRATION_TYPE_FLAT_CURVE_NODES).calibrateHazardFromPrice (valParams,
  1073.                 pricerParams, csqs, vcp, measureValue (valParams, pricerParams, csqs, vcp, "Upfront"));

  1074.         if (null == scop)
  1075.             throw new java.lang.Exception ("CDSComponent::calibFlatSpread => Cannot calibrate flat spread!");

  1076.         return scop._dblCalibResult;
  1077.     }

  1078.     /**
  1079.      *  CDS spread calibration output
  1080.      *
  1081.      * @author Lakshmi Krishnamurthy
  1082.      */

  1083.     public class SpreadCalibOP {
  1084.         public double _dblCalibResult = java.lang.Double.NaN;
  1085.         public org.drip.state.credit.CreditCurve _ccCalib = null;

  1086.         public SpreadCalibOP (
  1087.             final double dblCalibResult,
  1088.             final org.drip.state.credit.CreditCurve ccCalib)
  1089.             throws java.lang.Exception
  1090.         {
  1091.             if (!org.drip.numerical.common.NumberUtil.IsValid (_dblCalibResult = dblCalibResult) || null ==
  1092.                 (_ccCalib = ccCalib))
  1093.                 throw new java.lang.Exception ("CDSComponent::SpreadCalibOP ctr => Invalid inputs!");
  1094.         }
  1095.     }

  1096.     /**
  1097.      *  Implementation of the CDS spread calibrator
  1098.      *
  1099.      * @author Lakshmi Krishnamurthy
  1100.      */

  1101.     public class SpreadCalibrator {
  1102.         private org.drip.product.definition.CreditDefaultSwap _cds = null;

  1103.         /*
  1104.          * Calibration Type
  1105.          */

  1106.         public static final int CALIBRATION_TYPE_FLAT_INSTRUMENT_NODE = 1;
  1107.         public static final int CALIBRATION_TYPE_FLAT_CURVE_NODES = 2;
  1108.         public static final int CALIBRATION_TYPE_NODE_PARALLEL_BUMP = 4;

  1109.         private int _iCalibType = CALIBRATION_TYPE_FLAT_CURVE_NODES;

  1110.         /**
  1111.          * Constructor: Construct the SpreadCalibrator from the CDS parent, and whether the calibration is
  1112.          *  off of a single node
  1113.          *
  1114.          * @param cds CDS parent
  1115.          * @param iCalibType Calibration type indicating whether the calibration is PARALLEL, FLAT SINGLE
  1116.          *      NODE, or FLAT TERM
  1117.          *
  1118.          * @throws java.lang.Exception Thrown if inputs are invalid
  1119.          */

  1120.         public SpreadCalibrator (
  1121.             final org.drip.product.definition.CreditDefaultSwap cds,
  1122.             final int iCalibType)
  1123.             throws java.lang.Exception
  1124.         {
  1125.             if (null == (_cds = cds) || (CALIBRATION_TYPE_FLAT_INSTRUMENT_NODE != (_iCalibType = iCalibType)
  1126.                 && CALIBRATION_TYPE_FLAT_CURVE_NODES != iCalibType && CALIBRATION_TYPE_NODE_PARALLEL_BUMP !=
  1127.                     iCalibType))
  1128.                 throw new java.lang.Exception ("CDSComponent::SpreadCalibrator ctr => Invalid inputs!");
  1129.         }

  1130.         /**
  1131.          * Calibrate the hazard rate from calibration price
  1132.          *
  1133.          * @param valParams ValuationParams
  1134.          * @param pricerParams PricerParams
  1135.          * @param csqs ComponentMarketParams
  1136.          * @param vcp Valuation Customization Parameters
  1137.          * @param dblPriceCalib Market price to be calibrated
  1138.          *
  1139.          * @return Calibrated hazard
  1140.          */

  1141.         public SpreadCalibOP calibrateHazardFromPrice (
  1142.             final org.drip.param.valuation.ValuationParams valParams,
  1143.             final org.drip.param.pricer.CreditPricerParams pricerParams,
  1144.             final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  1145.             final org.drip.param.valuation.ValuationCustomizationParams vcp,
  1146.             final double dblPriceCalib)
  1147.         {
  1148.             if (null == valParams || null == pricerParams || null == csqs ||
  1149.                 !org.drip.numerical.common.NumberUtil.IsValid (dblPriceCalib))
  1150.                 return null;

  1151.             final org.drip.state.credit.CreditCurve ccOld = csqs.creditState (creditLabel());

  1152.             org.drip.function.definition.R1ToR1 ofCDSPriceFromFlatSpread = new
  1153.                 org.drip.function.definition.R1ToR1 (null) {
  1154.                 @Override public double evaluate (
  1155.                     final double dblFlatSpread)
  1156.                     throws java.lang.Exception
  1157.                 {
  1158.                     if (CALIBRATION_TYPE_NODE_PARALLEL_BUMP != _iCalibType)
  1159.                         csqs.setCreditState (ccOld.flatCurve (dblFlatSpread,
  1160.                             CALIBRATION_TYPE_FLAT_CURVE_NODES == _iCalibType, java.lang.Double.NaN));
  1161.                     else
  1162.                         csqs.setCreditState ((org.drip.state.credit.CreditCurve)
  1163.                             ccOld.customTweakManifestMeasure ("FairPremium", new
  1164.                                 org.drip.param.definition.ManifestMeasureTweak
  1165.                                     (org.drip.param.definition.ManifestMeasureTweak.FLAT, false,
  1166.                                         dblFlatSpread)));

  1167.                     return _cds.measureValue (valParams, pricerParams, csqs, vcp, "Upfront") - dblPriceCalib;
  1168.                 }
  1169.             };

  1170.             try {
  1171.                 org.drip.function.r1tor1solver.FixedPointFinderOutput rfop = new
  1172.                     org.drip.function.r1tor1solver.FixedPointFinderBrent (0., ofCDSPriceFromFlatSpread,
  1173.                         true).findRoot();

  1174.                 if (null == rfop || !rfop.containsRoot() && !csqs.setCreditState (ccOld))
  1175.                     return new SpreadCalibOP (rfop.getRoot(), ccOld);
  1176.             } catch (java.lang.Exception e) {
  1177.                 e.printStackTrace();
  1178.             }

  1179.             return null;
  1180.         }
  1181.     }

  1182.     class PeriodLossMicroJack {
  1183.         double _dblAccrOnDef01 = 0.;
  1184.         org.drip.numerical.differentiation.WengertJacobian _wjLossPVMicroJack = null;
  1185.         org.drip.numerical.differentiation.WengertJacobian _wjAccrOnDef01MicroJack = null;

  1186.         PeriodLossMicroJack (
  1187.             final int iNumParameters)
  1188.             throws java.lang.Exception
  1189.         {
  1190.             _wjLossPVMicroJack = new org.drip.numerical.differentiation.WengertJacobian (1, iNumParameters);

  1191.             _wjAccrOnDef01MicroJack = new org.drip.numerical.differentiation.WengertJacobian (1, iNumParameters);
  1192.         }
  1193.     }
  1194. }