CustomFundingCurveBuilder.java

  1. package org.drip.sample.funding;

  2. import java.util.List;

  3. import org.drip.analytics.date.*;
  4. import org.drip.analytics.support.*;
  5. import org.drip.function.r1tor1.QuadraticRationalShapeControl;
  6. import org.drip.numerical.common.FormatUtil;
  7. import org.drip.param.creator.*;
  8. import org.drip.param.market.CurveSurfaceQuoteContainer;
  9. import org.drip.param.period.*;
  10. import org.drip.param.valuation.*;
  11. import org.drip.product.creator.*;
  12. import org.drip.product.rates.*;
  13. import org.drip.service.env.EnvManager;
  14. import org.drip.spline.basis.PolynomialFunctionSetParams;
  15. import org.drip.spline.params.*;
  16. import org.drip.spline.stretch.*;
  17. import org.drip.state.creator.ScenarioDiscountCurveBuilder;
  18. import org.drip.state.discount.*;
  19. import org.drip.state.estimator.LatentStateStretchBuilder;
  20. import org.drip.state.identifier.*;
  21. import org.drip.state.inference.*;

  22. /*
  23.  * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  24.  */

  25. /*!
  26.  * Copyright (C) 2019 Lakshmi Krishnamurthy
  27.  * Copyright (C) 2018 Lakshmi Krishnamurthy
  28.  * Copyright (C) 2017 Lakshmi Krishnamurthy
  29.  * Copyright (C) 2016 Lakshmi Krishnamurthy
  30.  * Copyright (C) 2015 Lakshmi Krishnamurthy
  31.  * Copyright (C) 2014 Lakshmi Krishnamurthy
  32.  *
  33.  *  This file is part of DROP, an open-source library targeting risk, transaction costs, exposure, margin
  34.  *      calculations, valuation adjustment, and portfolio construction within and across fixed income,
  35.  *      credit, commodity, equity, FX, and structured products.
  36.  *  
  37.  *      https://lakshmidrip.github.io/DROP/
  38.  *  
  39.  *  DROP is composed of three modules:
  40.  *  
  41.  *  - DROP Analytics Core - https://lakshmidrip.github.io/DROP-Analytics-Core/
  42.  *  - DROP Portfolio Core - https://lakshmidrip.github.io/DROP-Portfolio-Core/
  43.  *  - DROP Numerical Core - https://lakshmidrip.github.io/DROP-Numerical-Core/
  44.  *
  45.  *  DROP Analytics Core implements libraries for the following:
  46.  *  - Fixed Income Analytics
  47.  *  - Asset Backed Analytics
  48.  *  - XVA Analytics
  49.  *  - Exposure and Margin Analytics
  50.  *
  51.  *  DROP Portfolio Core implements libraries for the following:
  52.  *  - Asset Allocation Analytics
  53.  *  - Transaction Cost Analytics
  54.  *
  55.  *  DROP Numerical Core implements libraries for the following:
  56.  *  - Statistical Learning
  57.  *  - Numerical Optimizer
  58.  *  - Spline Builder
  59.  *  - Algorithm Support
  60.  *
  61.  *  Documentation for DROP is Spread Over:
  62.  *
  63.  *  - Main                     => https://lakshmidrip.github.io/DROP/
  64.  *  - Wiki                     => https://github.com/lakshmiDRIP/DROP/wiki
  65.  *  - GitHub                   => https://github.com/lakshmiDRIP/DROP
  66.  *  - Repo Layout Taxonomy     => https://github.com/lakshmiDRIP/DROP/blob/master/Taxonomy.md
  67.  *  - Javadoc                  => https://lakshmidrip.github.io/DROP/Javadoc/index.html
  68.  *  - Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal
  69.  *  - Release Versions         => https://lakshmidrip.github.io/DROP/version.html
  70.  *  - Community Credits        => https://lakshmidrip.github.io/DROP/credits.html
  71.  *  - Issues Catalog           => https://github.com/lakshmiDRIP/DROP/issues
  72.  *  - JUnit                    => https://lakshmidrip.github.io/DROP/junit/index.html
  73.  *  - Jacoco                   => https://lakshmidrip.github.io/DROP/jacoco/index.html
  74.  *
  75.  *  Licensed under the Apache License, Version 2.0 (the "License");
  76.  *      you may not use this file except in compliance with the License.
  77.  *  
  78.  *  You may obtain a copy of the License at
  79.  *      http://www.apache.org/licenses/LICENSE-2.0
  80.  *  
  81.  *  Unless required by applicable law or agreed to in writing, software
  82.  *      distributed under the License is distributed on an "AS IS" BASIS,
  83.  *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  84.  *  
  85.  *  See the License for the specific language governing permissions and
  86.  *      limitations under the License.
  87.  */

  88. /**
  89.  * <i>CustomFundingCurveBuilder</i> funding curve calibration and input instrument calibration quote
  90.  * recovery. It shows the following:
  91.  *  
  92.  * <br><br>
  93.  *  <ul>
  94.  *      <li>
  95.  *          Construct the Array of Deposit/Swap Instruments and their Quotes from the given set of
  96.  *              parameters.
  97.  *      </li>
  98.  *      <li>
  99.  *          Construct the Deposit/Swap Instrument Set Stretch Builder.
  100.  *      </li>
  101.  *      <li>
  102.  *          <ul>
  103.  *              <li>
  104.  *                  Set up the Linear Curve Calibrator using the following parameters:
  105.  *              </li>
  106.  *              <li>
  107.  *                  Cubic Exponential Mixture Basis Spline Set
  108.  *              </li>
  109.  *              <li>
  110.  *                  C<sub>k</sub> = 2
  111.  *                  Segment Curvature Penalty = 2
  112.  *              </li>
  113.  *              <li>
  114.  *                  Quadratic Rational Shape Controller
  115.  *              </li>
  116.  *              <li>
  117.  *                  Natural Boundary Setting
  118.  *              </li>
  119.  *          </ul>
  120.  *      </li>
  121.  *      <li>
  122.  *          Construct the Shape Preserving Discount Curve by applying the linear curve calibrator to the
  123.  *              array of Cash and Swap Stretches.
  124.  *      </li>
  125.  *      <li>
  126.  *          Cross-Comparison of the Cash/Swap Calibration Instrument "Rate" metric across the different curve
  127.  *              construction methodologies.
  128.  *      </li>
  129.  *  </ul>
  130.  *  
  131.  * <br><br>
  132.  *  <ul>
  133.  *      <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/AnalyticsCore.md">Analytics Core Module</a></li>
  134.  *      <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/FixedIncomeAnalyticsLibrary.md">Fixed Income Analytics Library</a></li>
  135.  *      <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/sample/README.md">Sample</a></li>
  136.  *      <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/sample/funding/README.md">Funding Curve Builder</a></li>
  137.  *  </ul>
  138.  * <br><br>
  139.  *
  140.  * @author Lakshmi Krishnamurthy
  141.  */

  142. public class CustomFundingCurveBuilder {

  143.     /*
  144.      * Construct the Array of Deposit Instruments from the given set of parameters
  145.      *
  146.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  147.      */

  148.     private static final SingleStreamComponent[] DepositInstrumentsFromMaturityDays (
  149.         final JulianDate dtEffective,
  150.         final String strCurrency,
  151.         final int[] aiDay)
  152.         throws Exception
  153.     {
  154.         SingleStreamComponent[] aDeposit = new SingleStreamComponent[aiDay.length];

  155.         ComposableFloatingUnitSetting cfus = new ComposableFloatingUnitSetting (
  156.             "3M",
  157.             CompositePeriodBuilder.EDGE_DATE_SEQUENCE_SINGLE,
  158.             null,
  159.             ForwardLabel.Create (
  160.                 strCurrency,
  161.                 "3M"
  162.             ),
  163.             CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE,
  164.             0.
  165.         );

  166.         CompositePeriodSetting cps = new CompositePeriodSetting (
  167.             4,
  168.             "3M",
  169.             strCurrency,
  170.             null,
  171.             1.,
  172.             null,
  173.             null,
  174.             null,
  175.             null
  176.         );

  177.         CashSettleParams csp = new CashSettleParams (
  178.             0,
  179.             strCurrency,
  180.             0
  181.         );

  182.         for (int i = 0; i < aiDay.length; ++i) {
  183.             aDeposit[i] = new SingleStreamComponent (
  184.                 "DEPOSIT_" + aiDay[i],
  185.                 new Stream (
  186.                     CompositePeriodBuilder.FloatingCompositeUnit (
  187.                         CompositePeriodBuilder.EdgePair (
  188.                             dtEffective,
  189.                             dtEffective.addBusDays (
  190.                                 aiDay[i],
  191.                                 strCurrency
  192.                             )
  193.                         ),
  194.                         cps,
  195.                         cfus
  196.                     )
  197.                 ),
  198.                 csp
  199.             );

  200.             aDeposit[i].setPrimaryCode (aiDay[i] + "D");
  201.         }

  202.         return aDeposit;
  203.     }

  204.     /*
  205.      * Construct the Array of Swap Instruments from the given set of parameters
  206.      *
  207.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  208.      */

  209.     private static final FixFloatComponent[] SwapInstrumentsFromMaturityTenor (
  210.         final JulianDate dtEffective,
  211.         final String strCurrency,
  212.         final String[] astrMaturityTenor)
  213.         throws Exception
  214.     {
  215.         FixFloatComponent[] aIRS = new FixFloatComponent[astrMaturityTenor.length];

  216.         UnitCouponAccrualSetting ucasFixed = new UnitCouponAccrualSetting (
  217.             2,
  218.             "Act/360",
  219.             false,
  220.             "Act/360",
  221.             false,
  222.             strCurrency,
  223.             true,
  224.             CompositePeriodBuilder.ACCRUAL_COMPOUNDING_RULE_GEOMETRIC
  225.         );

  226.         ComposableFloatingUnitSetting cfusFloating = new ComposableFloatingUnitSetting (
  227.             "6M",
  228.             CompositePeriodBuilder.EDGE_DATE_SEQUENCE_REGULAR,
  229.             null,
  230.             ForwardLabel.Create (
  231.                 strCurrency,
  232.                 "6M"
  233.             ),
  234.             CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE,
  235.             0.
  236.         );

  237.         ComposableFixedUnitSetting cfusFixed = new ComposableFixedUnitSetting (
  238.             "6M",
  239.             CompositePeriodBuilder.EDGE_DATE_SEQUENCE_REGULAR,
  240.             null,
  241.             0.,
  242.             0.,
  243.             strCurrency
  244.         );

  245.         CompositePeriodSetting cpsFloating = new CompositePeriodSetting (
  246.             2,
  247.             "6M",
  248.             strCurrency,
  249.             null,
  250.             -1.,
  251.             null,
  252.             null,
  253.             null,
  254.             null
  255.         );

  256.         CompositePeriodSetting cpsFixed = new CompositePeriodSetting (
  257.             2,
  258.             "6M",
  259.             strCurrency,
  260.             null,
  261.             1.,
  262.             null,
  263.             null,
  264.             null,
  265.             null
  266.         );

  267.         CashSettleParams csp = new CashSettleParams (
  268.             0,
  269.             strCurrency,
  270.             0
  271.         );

  272.         for (int i = 0; i < astrMaturityTenor.length; ++i) {
  273.             List<Integer> lsFixedStreamEdgeDate = CompositePeriodBuilder.RegularEdgeDates (
  274.                 dtEffective,
  275.                 "6M",
  276.                 astrMaturityTenor[i],
  277.                 null
  278.             );

  279.             List<Integer> lsFloatingStreamEdgeDate = CompositePeriodBuilder.RegularEdgeDates (
  280.                 dtEffective,
  281.                 "6M",
  282.                 astrMaturityTenor[i],
  283.                 null
  284.             );

  285.             Stream floatingStream = new Stream (
  286.                 CompositePeriodBuilder.FloatingCompositeUnit (
  287.                     lsFloatingStreamEdgeDate,
  288.                     cpsFloating,
  289.                     cfusFloating
  290.                 )
  291.             );

  292.             Stream fixedStream = new Stream (
  293.                 CompositePeriodBuilder.FixedCompositeUnit (
  294.                     lsFixedStreamEdgeDate,
  295.                     cpsFixed,
  296.                     ucasFixed,
  297.                     cfusFixed
  298.                 )
  299.             );

  300.             FixFloatComponent irs = new FixFloatComponent (
  301.                 fixedStream,
  302.                 floatingStream,
  303.                 csp
  304.             );

  305.             irs.setPrimaryCode ("IRS." + astrMaturityTenor[i] + "." + strCurrency);

  306.             aIRS[i] = irs;
  307.         }

  308.         return aIRS;
  309.     }

  310.     /*
  311.      * This sample demonstrates discount curve calibration and input instrument calibration quote recovery.
  312.      *  It shows the following:
  313.      *  - Construct the Array of Cash/Swap Instruments and their Quotes from the given set of parameters.
  314.      *  - Construct the Cash/Swap Instrument Set Stretch Builder.
  315.      *  - Set up the Linear Curve Calibrator using the following parameters:
  316.      *      - Cubic Exponential Mixture Basis Spline Set
  317.      *      - Ck = 2, Segment Curvature Penalty = 2
  318.      *      - Quadratic Rational Shape Controller
  319.      *      - Natural Boundary Setting
  320.      *  - Construct the Shape Preserving Discount Curve by applying the linear curve calibrator to the array
  321.      *      of Cash and Swap Stretches.
  322.      *  - Cross-Comparison of the Cash/Swap Calibration Instrument "Rate" metric across the different curve
  323.      *      construction methodologies.
  324.      *
  325.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  326.      */

  327.     private static final void OTCInstrumentCurve (
  328.         final JulianDate dtSpot,
  329.         final String strCurrency)
  330.         throws Exception
  331.     {
  332.         /*
  333.          * Construct the Array of Deposit Instruments and their Quotes from the given set of parameters
  334.          */

  335.         SingleStreamComponent[] aDepositComp = DepositInstrumentsFromMaturityDays (
  336.             dtSpot,
  337.             strCurrency,
  338.             new int[] {
  339.                 1, 2, 7, 14, 30, 60
  340.             }
  341.         );

  342.         double[] adblDepositQuote = new double[] {
  343.             0.0013, 0.0017, 0.0017, 0.0018, 0.0020, 0.0023
  344.         };

  345.         /*
  346.          * Construct the Deposit Instrument Set Stretch Builder
  347.          */

  348.         LatentStateStretchSpec depositStretch = LatentStateStretchBuilder.ForwardFundingStretchSpec (
  349.             "DEPOSIT",
  350.             aDepositComp,
  351.             "ForwardRate",
  352.             adblDepositQuote
  353.         );

  354.         /*
  355.          * Construct the Array of EDF Instruments and their Quotes from the given set of parameters
  356.          */

  357.         SingleStreamComponent[] aEDFComp = SingleStreamComponentBuilder.ForwardRateFuturesPack (
  358.             dtSpot,
  359.             8,
  360.             strCurrency
  361.         );

  362.         double[] adblEDFQuote = new double[] {
  363.             0.0027, 0.0032, 0.0041, 0.0054, 0.0077, 0.0104, 0.0134, 0.0160
  364.         };

  365.         /*
  366.          * Construct the EDF Instrument Set Stretch Builder
  367.          */

  368.         LatentStateStretchSpec edfStretch = LatentStateStretchBuilder.ForwardFundingStretchSpec (
  369.             "EDF",
  370.             aEDFComp,
  371.             "ForwardRate",
  372.             adblEDFQuote
  373.         );

  374.         /*
  375.          * Construct the Array of Swap Instruments and their Quotes from the given set of parameters
  376.          */

  377.         FixFloatComponent[] aSwapComp = SwapInstrumentsFromMaturityTenor (
  378.             dtSpot,
  379.             strCurrency,
  380.             new String[] {
  381.                 "4Y", "5Y", "6Y", "7Y", "8Y", "9Y", "10Y", "11Y", "12Y", "15Y", "20Y", "25Y", "30Y", "40Y", "50Y"
  382.             }
  383.         );

  384.         double[] adblSwapQuote = new double[] {
  385.             0.0166, 0.0206, 0.0241, 0.0269, 0.0292, 0.0311, 0.0326, 0.0340, 0.0351, 0.0375, 0.0393, 0.0402, 0.0407, 0.0409, 0.0409
  386.         };

  387.         /*
  388.          * Construct the Swap Instrument Set Stretch Builder
  389.          */

  390.         LatentStateStretchSpec swapStretch = LatentStateStretchBuilder.ForwardFundingStretchSpec (
  391.             "SWAP",
  392.             aSwapComp,
  393.             "SwapRate",
  394.             adblSwapQuote
  395.         );

  396.         LatentStateStretchSpec[] aStretchSpec = new LatentStateStretchSpec[] {
  397.             depositStretch,
  398.             edfStretch,
  399.             swapStretch
  400.         };

  401.         /*
  402.          * Set up the Linear Curve Calibrator using the following parameters:
  403.          *  - Cubic Exponential Mixture Basis Spline Set
  404.          *  - Ck = 2, Segment Curvature Penalty = 2
  405.          *  - Quadratic Rational Shape Controller
  406.          *  - Natural Boundary Setting
  407.          */

  408.         LinearLatentStateCalibrator lcc = new LinearLatentStateCalibrator (
  409.             new SegmentCustomBuilderControl (
  410.                 MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
  411.                 new PolynomialFunctionSetParams (4),
  412.                 SegmentInelasticDesignControl.Create (
  413.                     2,
  414.                     2
  415.                 ),
  416.                 new ResponseScalingShapeControl (
  417.                     true,
  418.                     new QuadraticRationalShapeControl (0.)
  419.                 ),
  420.                 null
  421.             ),
  422.             BoundarySettings.NaturalStandard(),
  423.             MultiSegmentSequence.CALIBRATE,
  424.             null,
  425.             null
  426.         );

  427.         ValuationParams valParams = new ValuationParams (
  428.             dtSpot,
  429.             dtSpot,
  430.             strCurrency
  431.         );

  432.         /*
  433.          * Construct the Shape Preserving Discount Curve by applying the linear curve calibrator to the array
  434.          *  of Deposit, Futures, and Swap Stretches.
  435.          */

  436.         MergedDiscountForwardCurve dc = ScenarioDiscountCurveBuilder.ShapePreservingDFBuild (
  437.             strCurrency,
  438.             lcc,
  439.             aStretchSpec,
  440.             valParams,
  441.             null,
  442.             null,
  443.             null,
  444.             1.
  445.         );

  446.         CurveSurfaceQuoteContainer csqs = MarketParamsBuilder.Create (
  447.             dc,
  448.             null,
  449.             null,
  450.             null,
  451.             null,
  452.             null,
  453.             null
  454.         );

  455.         /*
  456.          * Cross-Comparison of the Deposit Calibration Instrument "Rate" metric across the different curve
  457.          *  construction methodologies.
  458.          */

  459.         System.out.println ("\n\n\t----------------------------------------------------------------");

  460.         System.out.println ("\t     DEPOSIT INSTRUMENTS CALIBRATION RECOVERY");

  461.         System.out.println ("\t----------------------------------------------------------------");

  462.         for (int i = 0; i < aDepositComp.length; ++i)
  463.             System.out.println ("\t[" + aDepositComp[i].maturityDate() + "] = " +
  464.                 FormatUtil.FormatDouble (aDepositComp[i].measureValue (valParams, null, csqs,
  465.                     null, "Rate"), 1, 6, 1.) + " | " + FormatUtil.FormatDouble (adblDepositQuote[i], 1, 6, 1.));

  466.         System.out.println ("\t----------------------------------------------------------------");

  467.         /*
  468.          * Cross-Comparison of the EDF Calibration Instrument "Rate" metric across the different curve
  469.          *  construction methodologies.
  470.          */

  471.         System.out.println ("\n\t----------------------------------------------------------------");

  472.         System.out.println ("\t     EDF INSTRUMENTS CALIBRATION RECOVERY");

  473.         System.out.println ("\t----------------------------------------------------------------");

  474.         for (int i = 0; i < aEDFComp.length; ++i)
  475.             System.out.println ("\t[" + aEDFComp[i].maturityDate() + "] = " +
  476.                 FormatUtil.FormatDouble (aEDFComp[i].measureValue (valParams, null, csqs, null, "Rate"), 1, 6, 1.)
  477.                     + " | " + FormatUtil.FormatDouble (adblEDFQuote[i], 1, 6, 1.));

  478.         System.out.println ("\t----------------------------------------------------------------");

  479.         /*
  480.          * Cross-Comparison of the Swap Calibration Instrument "Rate" metric across the different curve
  481.          *  construction methodologies.
  482.          */

  483.         System.out.println ("\n\t----------------------------------------------------------------");

  484.         System.out.println ("\t     SWAP INSTRUMENTS CALIBRATION RECOVERY");

  485.         System.out.println ("\t----------------------------------------------------------------");

  486.         for (int i = 0; i < aSwapComp.length; ++i)
  487.             System.out.println ("\t[" + aSwapComp[i].maturityDate() + "] = " +
  488.                 FormatUtil.FormatDouble (aSwapComp[i].measureValue (valParams, null, csqs, null, "CalibSwapRate"), 1, 6, 1.)
  489.                     + " | " + FormatUtil.FormatDouble (adblSwapQuote[i], 1, 6, 1.) + " | " +
  490.                         FormatUtil.FormatDouble (aSwapComp[i].measureValue (valParams, null, csqs, null, "FairPremium"), 1, 6, 1.));

  491.         System.out.println ("\t----------------------------------------------------------------");
  492.     }

  493.     public static final void main (
  494.         final String[] astrArgs)
  495.         throws Exception
  496.     {
  497.         /*
  498.          * Initialize the Credit Analytics Library
  499.          */

  500.         EnvManager.InitEnv ("");

  501.         JulianDate dtToday = DateUtil.Today().addTenor ("0D");

  502.         String strCurrency = "USD";

  503.         OTCInstrumentCurve (
  504.             dtToday,
  505.             strCurrency
  506.         );

  507.         EnvManager.TerminateEnv();
  508.     }
  509. }