InArrearsSwap.java

  1. package org.drip.sample.fixfloat;

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

  87. /**
  88.  * <i>InArrearsSwap</i> demonstrates the Construction and Valuation of a In-Arrears Swap.
  89.  *  
  90.  * <br><br>
  91.  *  <ul>
  92.  *      <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/AnalyticsCore.md">Analytics Core Module</a></li>
  93.  *      <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/FixedIncomeAnalyticsLibrary.md">Fixed Income Analytics Library</a></li>
  94.  *      <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/sample/README.md">Sample</a></li>
  95.  *      <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/sample/fixfloat/README.md">Fix Float Swap Analytics</a></li>
  96.  *  </ul>
  97.  * <br><br>
  98.  *
  99.  * @author Lakshmi Krishnamurthy
  100.  */

  101. public class InArrearsSwap {

  102.     /*
  103.      * Construct the Array of Deposit Instruments from the given set of parameters
  104.      *
  105.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  106.      */

  107.     private static final SingleStreamComponent[] DepositInstrumentsFromMaturityDays (
  108.         final JulianDate dtEffective,
  109.         final String strCurrency,
  110.         final int[] aiDay,
  111.         final int iRefPeriodType)
  112.         throws Exception
  113.     {
  114.         SingleStreamComponent[] aDeposit = new SingleStreamComponent[aiDay.length];

  115.         ComposableFloatingUnitSetting cfus = new ComposableFloatingUnitSetting (
  116.             "3M",
  117.             CompositePeriodBuilder.EDGE_DATE_SEQUENCE_SINGLE,
  118.             null,
  119.             ForwardLabel.Create (
  120.                 strCurrency,
  121.                 "3M"
  122.             ),
  123.             iRefPeriodType,
  124.             0.
  125.         );

  126.         CompositePeriodSetting cps = new CompositePeriodSetting (
  127.             4,
  128.             "3M",
  129.             strCurrency,
  130.             null,
  131.             1.,
  132.             null,
  133.             null,
  134.             null,
  135.             null
  136.         );

  137.         CashSettleParams csp = new CashSettleParams (
  138.             0,
  139.             strCurrency,
  140.             0
  141.         );

  142.         for (int i = 0; i < aiDay.length; ++i) {
  143.             aDeposit[i] = new SingleStreamComponent (
  144.                 "DEPOSIT_" + aiDay[i],
  145.                 new Stream (
  146.                     CompositePeriodBuilder.FloatingCompositeUnit (
  147.                         CompositePeriodBuilder.EdgePair (
  148.                             dtEffective,
  149.                             dtEffective.addBusDays (
  150.                                 aiDay[i],
  151.                                 strCurrency
  152.                             )
  153.                         ),
  154.                         cps,
  155.                         cfus
  156.                     )
  157.                 ),
  158.                 csp
  159.             );

  160.             aDeposit[i].setPrimaryCode (aiDay[i] + "D");
  161.         }

  162.         return aDeposit;
  163.     }

  164.     /*
  165.      * Construct the Array of Swap Instruments from the given set of parameters
  166.      *
  167.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  168.      */

  169.     private static final FixFloatComponent[] SwapInstrumentsFromMaturityTenor (
  170.         final JulianDate dtEffective,
  171.         final String strCurrency,
  172.         final String[] astrMaturityTenor,
  173.         final int iRefPeriodType)
  174.         throws Exception
  175.     {
  176.         FixFloatComponent[] aIRS = new FixFloatComponent[astrMaturityTenor.length];

  177.         UnitCouponAccrualSetting ucasFixed = new UnitCouponAccrualSetting (
  178.             2,
  179.             "Act/360",
  180.             false,
  181.             "Act/360",
  182.             false,
  183.             strCurrency,
  184.             true,
  185.             CompositePeriodBuilder.ACCRUAL_COMPOUNDING_RULE_GEOMETRIC
  186.         );

  187.         ComposableFloatingUnitSetting cfusFloating = new ComposableFloatingUnitSetting (
  188.             "6M",
  189.             CompositePeriodBuilder.EDGE_DATE_SEQUENCE_REGULAR,
  190.             null,
  191.             ForwardLabel.Create (
  192.                 strCurrency,
  193.                 "6M"
  194.             ),
  195.             iRefPeriodType,
  196.             0.
  197.         );

  198.         ComposableFixedUnitSetting cfusFixed = new ComposableFixedUnitSetting (
  199.             "6M",
  200.             CompositePeriodBuilder.EDGE_DATE_SEQUENCE_REGULAR,
  201.             null,
  202.             0.,
  203.             0.,
  204.             strCurrency
  205.         );

  206.         CompositePeriodSetting cpsFloating = new CompositePeriodSetting (
  207.             2,
  208.             "6M",
  209.             strCurrency,
  210.             null,
  211.             -1.,
  212.             null,
  213.             null,
  214.             null,
  215.             null
  216.         );

  217.         CompositePeriodSetting cpsFixed = new CompositePeriodSetting (
  218.             2,
  219.             "6M",
  220.             strCurrency,
  221.             null,
  222.             1.,
  223.             null,
  224.             null,
  225.             null,
  226.             null
  227.         );

  228.         CashSettleParams csp = new CashSettleParams (
  229.             0,
  230.             strCurrency,
  231.             0
  232.         );

  233.         for (int i = 0; i < astrMaturityTenor.length; ++i) {
  234.             List<Integer> lsFixedStreamEdgeDate = CompositePeriodBuilder.RegularEdgeDates (
  235.                 dtEffective,
  236.                 "6M",
  237.                 astrMaturityTenor[i],
  238.                 null
  239.             );

  240.             List<Integer> lsFloatingStreamEdgeDate = CompositePeriodBuilder.RegularEdgeDates (
  241.                 dtEffective,
  242.                 "6M",
  243.                 astrMaturityTenor[i],
  244.                 null
  245.             );

  246.             Stream floatingStream = new Stream (
  247.                 CompositePeriodBuilder.FloatingCompositeUnit (
  248.                     lsFloatingStreamEdgeDate,
  249.                     cpsFloating,
  250.                     cfusFloating
  251.                 )
  252.             );

  253.             Stream fixedStream = new Stream (
  254.                 CompositePeriodBuilder.FixedCompositeUnit (
  255.                     lsFixedStreamEdgeDate,
  256.                     cpsFixed,
  257.                     ucasFixed,
  258.                     cfusFixed
  259.                 )
  260.             );

  261.             FixFloatComponent irs = new FixFloatComponent (
  262.                 fixedStream,
  263.                 floatingStream,
  264.                 csp
  265.             );

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

  267.             aIRS[i] = irs;
  268.         }

  269.         return aIRS;
  270.     }

  271.     /*
  272.      * This sample demonstrates discount curve calibration and input instrument calibration quote recovery.
  273.      *  It shows the following:
  274.      *  - Construct the Array of Cash/Swap Instruments and their Quotes from the given set of parameters.
  275.      *  - Construct the Cash/Swap Instrument Set Stretch Builder.
  276.      *  - Set up the Linear Curve Calibrator using the following parameters:
  277.      *      - Cubic Exponential Mixture Basis Spline Set
  278.      *      - Ck = 2, Segment Curvature Penalty = 2
  279.      *      - Quadratic Rational Shape Controller
  280.      *      - Natural Boundary Setting
  281.      *  - Construct the Shape Preserving Discount Curve by applying the linear curve calibrator to the array
  282.      *      of Cash and Swap Stretches.
  283.      *  - Cross-Comparison of the Cash/Swap Calibration Instrument "Rate" metric across the different curve
  284.      *      construction methodologies.
  285.      *
  286.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  287.      */

  288.     private static final void CustomDiscountCurveBuilderSample (
  289.         final JulianDate dtSpot,
  290.         final String strCurrency)
  291.         throws Exception
  292.     {
  293.         /*
  294.          * Construct the Array of Deposit Instruments and their Quotes from the given set of parameters
  295.          */

  296.         SingleStreamComponent[] aDepositComp = DepositInstrumentsFromMaturityDays (
  297.             dtSpot,
  298.             strCurrency,
  299.             new int[] {
  300.                 1, 2, 7, 14, 30, 60
  301.             },
  302.             CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE
  303.         );

  304.         double[] adblDepositQuote = new double[] {
  305.             0.0013, 0.0017, 0.0017, 0.0018, 0.0020, 0.0023
  306.         };

  307.         /*
  308.          * Construct the Deposit Instrument Set Stretch Builder
  309.          */

  310.         LatentStateStretchSpec depositStretch = LatentStateStretchBuilder.ForwardFundingStretchSpec (
  311.             "DEPOSIT",
  312.             aDepositComp,
  313.             "ForwardRate",
  314.             adblDepositQuote
  315.         );

  316.         /*
  317.          * Construct the Array of EDF Instruments and their Quotes from the given set of parameters
  318.          */

  319.         SingleStreamComponent[] aEDFComp = SingleStreamComponentBuilder.ForwardRateFuturesPack (
  320.             dtSpot,
  321.             8,
  322.             strCurrency
  323.         );

  324.         double[] adblEDFQuote = new double[] {
  325.             0.0027, 0.0032, 0.0041, 0.0054, 0.0077, 0.0104, 0.0134, 0.0160
  326.         };

  327.         /*
  328.          * Construct the EDF Instrument Set Stretch Builder
  329.          */

  330.         LatentStateStretchSpec edfStretch = LatentStateStretchBuilder.ForwardFundingStretchSpec (
  331.             "EDF",
  332.             aEDFComp,
  333.             "ForwardRate",
  334.             adblEDFQuote
  335.         );

  336.         /*
  337.          * Construct the Array of Swap Instruments and their Quotes from the given set of parameters
  338.          */

  339.         FixFloatComponent[] aSwapInAdvance = SwapInstrumentsFromMaturityTenor (
  340.             dtSpot,
  341.             strCurrency,
  342.             new java.lang.String[] {
  343.                 "4Y", "5Y", "6Y", "7Y", "8Y", "9Y", "10Y", "11Y", "12Y", "15Y", "20Y", "25Y", "30Y", "40Y", "50Y"
  344.             },
  345.             CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE
  346.         );

  347.         /*
  348.          * Construct the Array of Swap Instruments and their Quotes from the given set of parameters
  349.          */

  350.         FixFloatComponent[] aSwapInArrears = SwapInstrumentsFromMaturityTenor (
  351.             dtSpot,
  352.             strCurrency,
  353.             new java.lang.String[] {
  354.                 "4Y", "5Y", "6Y", "7Y", "8Y", "9Y", "10Y", "11Y", "12Y", "15Y", "20Y", "25Y", "30Y", "40Y", "50Y"
  355.             },
  356.             CompositePeriodBuilder.REFERENCE_PERIOD_IN_ARREARS
  357.         );

  358.         double[] adblSwapQuote = new double[] {
  359.             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
  360.         };

  361.         /*
  362.          * Construct the Swap Instrument Set Stretch Builder
  363.          */

  364.         LatentStateStretchSpec swapStretch = LatentStateStretchBuilder.ForwardFundingStretchSpec (
  365.             "SWAP",
  366.             aSwapInAdvance,
  367.             "SwapRate",
  368.             adblSwapQuote
  369.         );

  370.         LatentStateStretchSpec[] aStretchSpec = new LatentStateStretchSpec[] {
  371.             depositStretch,
  372.             edfStretch,
  373.             swapStretch
  374.         };

  375.         /*
  376.          * Set up the Linear Curve Calibrator using the following parameters:
  377.          *  - Cubic Exponential Mixture Basis Spline Set
  378.          *  - Ck = 2, Segment Curvature Penalty = 2
  379.          *  - Quadratic Rational Shape Controller
  380.          *  - Natural Boundary Setting
  381.          */

  382.         LinearLatentStateCalibrator lcc = new LinearLatentStateCalibrator (
  383.             new SegmentCustomBuilderControl (
  384.                 MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
  385.                 new PolynomialFunctionSetParams (4),
  386.                 SegmentInelasticDesignControl.Create (
  387.                     2,
  388.                     2
  389.                 ),
  390.                 new ResponseScalingShapeControl (
  391.                     true,
  392.                     new QuadraticRationalShapeControl (0.)
  393.                 ),
  394.                 null
  395.             ),
  396.             BoundarySettings.NaturalStandard(),
  397.             MultiSegmentSequence.CALIBRATE,
  398.             null,
  399.             null
  400.         );

  401.         ValuationParams valParams = new ValuationParams (
  402.             dtSpot,
  403.             dtSpot,
  404.             strCurrency
  405.         );

  406.         /*
  407.          * Construct the Shape Preserving Discount Curve by applying the linear curve calibrator to the array
  408.          *  of Deposit, Futures, and Swap Stretches.
  409.          */

  410.         MergedDiscountForwardCurve dc = ScenarioDiscountCurveBuilder.ShapePreservingDFBuild (
  411.             strCurrency,
  412.             lcc,
  413.             aStretchSpec,
  414.             valParams,
  415.             null,
  416.             null,
  417.             null,
  418.             1.
  419.         );

  420.         CurveSurfaceQuoteContainer csqs = MarketParamsBuilder.Create (
  421.             dc,
  422.             null,
  423.             null,
  424.             null,
  425.             null,
  426.             null,
  427.             null
  428.         );

  429.         /*
  430.          * Cross-Comparison of the In-Advance/Arrears Swap "Rate" metric across the different curve
  431.          *  construction methodologies.
  432.          */

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

  434.         System.out.println ("\t     IN-ADVANCE/IN-ARREARS SWAP INSTRUMENTS METRIC COMPARISON");

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

  436.         System.out.println ("\t\tL -> R:");

  437.         System.out.println ("\t\t\t - Swap Maturity");

  438.         System.out.println ("\t\t\t - In Advance Calibration Quote");

  439.         System.out.println ("\t\t\t - In Advance Fair Premium");

  440.         System.out.println ("\t\t\t - In Advance Swap Rate");

  441.         System.out.println ("\t\t\t - In Arrears Swap Rate");

  442.         System.out.println ("\t\t\t - In Arrears Swap Rate Shift");

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

  444.         for (int i = 0; i < aSwapInAdvance.length; ++i) {
  445.             double dblInArrearsFairPremium = aSwapInArrears[i].measureValue (
  446.                 valParams,
  447.                 null,
  448.                 csqs,
  449.                 null,
  450.                 "FairPremium"
  451.             );

  452.             System.out.println ("\t[" + aSwapInAdvance[i].maturityDate() + "] = " +
  453.                 FormatUtil.FormatDouble (aSwapInAdvance[i].measureValue (valParams, null, csqs, null, "CalibSwapRate"), 1, 4, 100.) + "% | " +
  454.                 FormatUtil.FormatDouble (adblSwapQuote[i], 1, 4, 100.) + "% | " +
  455.                 FormatUtil.FormatDouble (aSwapInAdvance[i].measureValue (valParams, null, csqs, null, "FairPremium"), 1, 4, 100.) + "% | " +
  456.                 FormatUtil.FormatDouble (dblInArrearsFairPremium, 1, 4, 100.) + "% | " +
  457.                 FormatUtil.FormatDouble (dblInArrearsFairPremium - adblSwapQuote[i], 1, 0, 10000.)
  458.             );
  459.         }

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

  461.         System.out.println ("\t     IN-ADVANCE/IN-ARREARS SWAP INSTRUMENTS DV01 COMPARISON");

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

  463.         System.out.println ("\t\tL -> R:");

  464.         System.out.println ("\t\t\t - Swap Maturity");

  465.         System.out.println ("\t\t\t - In Advance Swap DV01");

  466.         System.out.println ("\t\t\t - In Arrears Swap DV01");

  467.         System.out.println ("\t\t\t - In Arrears Step Down Swap DV01 Shift");

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

  469.         for (int i = 0; i < aSwapInAdvance.length; ++i) {
  470.             double dblInAdvanceDV01 = aSwapInAdvance[i].measureValue (
  471.                 valParams,
  472.                 null,
  473.                 csqs,
  474.                 null,
  475.                 "FixedDV01"
  476.             );

  477.             double dblInArrearsDV01 = aSwapInArrears[i].measureValue (
  478.                 valParams,
  479.                 null,
  480.                 csqs,
  481.                 null,
  482.                 "FixedDV01"
  483.             );

  484.             System.out.println ("\t[" + aSwapInAdvance[i].maturityDate() + "] = " +
  485.                 FormatUtil.FormatDouble (dblInAdvanceDV01, 2, 1, 10000.) + " | " +
  486.                 FormatUtil.FormatDouble (dblInArrearsDV01, 2, 1, 10000.) + " | " +
  487.                 FormatUtil.FormatDouble (dblInArrearsDV01 - dblInAdvanceDV01, 1, 2, 10000.)
  488.             );
  489.         }

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

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

  499.         EnvManager.InitEnv ("");

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

  501.         String strCurrency = "USD";

  502.         CustomDiscountCurveBuilderSample (
  503.             dtToday,
  504.             strCurrency
  505.         );

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