MultiFactorLIBORMonteCarlo.java

  1. package org.drip.sample.lmm;

  2. import java.util.List;

  3. import org.drip.analytics.date.JulianDate;
  4. import org.drip.analytics.definition.MarketSurface;
  5. import org.drip.analytics.support.CompositePeriodBuilder;
  6. import org.drip.dynamics.lmm.*;
  7. import org.drip.function.r1tor1.QuadraticRationalShapeControl;
  8. import org.drip.numerical.common.FormatUtil;
  9. import org.drip.param.creator.*;
  10. import org.drip.param.market.CurveSurfaceQuoteContainer;
  11. import org.drip.param.period.*;
  12. import org.drip.param.valuation.*;
  13. import org.drip.product.creator.SingleStreamComponentBuilder;
  14. import org.drip.product.rates.*;
  15. import org.drip.sequence.random.*;
  16. import org.drip.service.env.EnvManager;
  17. import org.drip.spline.basis.PolynomialFunctionSetParams;
  18. import org.drip.spline.grid.OverlappingStretchSpan;
  19. import org.drip.spline.params.*;
  20. import org.drip.spline.stretch.*;
  21. import org.drip.state.creator.*;
  22. import org.drip.state.curve.BasisSplineForwardRate;
  23. import org.drip.state.discount.*;
  24. import org.drip.state.estimator.LatentStateStretchBuilder;
  25. import org.drip.state.forward.ForwardCurve;
  26. import org.drip.state.identifier.*;
  27. import org.drip.state.inference.*;

  28. /*
  29.  * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  30.  */

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

  93. /**
  94.  * <i>MultiFactorLIBORMonteCarlo</i> demonstrates the Monte-Carlo Evolution Sequence of the LIBOR Forward
  95.  * Curve. The References are:
  96.  *  
  97.  * <br><br>
  98.  *  <ul>
  99.  *      <li>
  100.  *          Goldys, B., M. Musiela, and D. Sondermann (1994): Log-normality of Rates and Term Structure
  101.  *              Models, The University of New South Wales.
  102.  *      </li>
  103.  *      <li>
  104.  *          Musiela, M. (1994): Nominal Annual Rates and Log-normal Volatility Structure, The University of
  105.  *              New South Wales.
  106.  *      </li>
  107.  *      <li>
  108.  *          Brace, A., D. Gatarek, and M. Musiela (1997): The Market Model of Interest Rate Dynamics,
  109.  *              Mathematical Finance 7 (2), 127-155.
  110.  *      </li>
  111.  *  </ul>
  112.  *  
  113.  * <br><br>
  114.  *  <ul>
  115.  *      <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/AnalyticsCore.md">Analytics Core Module</a></li>
  116.  *      <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/FixedIncomeAnalyticsLibrary.md">Fixed Income Analytics Library</a></li>
  117.  *      <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/sample/README.md">Sample</a></li>
  118.  *      <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/sample/lmm/README.md">LIBOR Market (LMM-BGM Variant) Evolution</a></li>
  119.  *  </ul>
  120.  * <br><br>
  121.  *
  122.  * @author Lakshmi Krishnamurthy
  123.  */

  124. public class MultiFactorLIBORMonteCarlo {

  125.     /*
  126.      * Construct the Array of Deposit Instruments from the given set of parameters
  127.      *
  128.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  129.      */

  130.     private static final SingleStreamComponent[] DepositInstrumentsFromMaturityDays (
  131.         final JulianDate dtEffective,
  132.         final String strCurrency,
  133.         final int[] aiDay)
  134.         throws Exception
  135.     {
  136.         SingleStreamComponent[] aDeposit = new SingleStreamComponent[aiDay.length];

  137.         ComposableFloatingUnitSetting cfus = new ComposableFloatingUnitSetting (
  138.             "3M",
  139.             CompositePeriodBuilder.EDGE_DATE_SEQUENCE_SINGLE,
  140.             null,
  141.             ForwardLabel.Create (
  142.                 strCurrency,
  143.                 "3M"
  144.             ),
  145.             CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE,
  146.             0.
  147.         );

  148.         CompositePeriodSetting cps = new CompositePeriodSetting (
  149.             4,
  150.             "3M",
  151.             strCurrency,
  152.             null,
  153.             1.,
  154.             null,
  155.             null,
  156.             null,
  157.             null
  158.         );

  159.         CashSettleParams csp = new CashSettleParams (
  160.             0,
  161.             strCurrency,
  162.             0
  163.         );

  164.         for (int i = 0; i < aiDay.length; ++i) {
  165.             aDeposit[i] = new SingleStreamComponent (
  166.                 "DEPOSIT_" + aiDay[i],
  167.                 new Stream (
  168.                     CompositePeriodBuilder.FloatingCompositeUnit (
  169.                         CompositePeriodBuilder.EdgePair (
  170.                             dtEffective,
  171.                             dtEffective.addBusDays (
  172.                                 aiDay[i],
  173.                                 strCurrency
  174.                             )
  175.                         ),
  176.                         cps,
  177.                         cfus
  178.                     )
  179.                 ),
  180.                 csp
  181.             );

  182.             aDeposit[i].setPrimaryCode (aiDay[i] + "D");
  183.         }

  184.         return aDeposit;
  185.     }

  186.     /*
  187.      * Construct the Array of Swap Instruments from the given set of parameters
  188.      *
  189.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  190.      */

  191.     private static final FixFloatComponent[] SwapInstrumentsFromMaturityTenor (
  192.         final JulianDate dtEffective,
  193.         final String strCurrency,
  194.         final String[] astrMaturityTenor)
  195.         throws Exception
  196.     {
  197.         FixFloatComponent[] aIRS = new FixFloatComponent[astrMaturityTenor.length];

  198.         UnitCouponAccrualSetting ucasFixed = new UnitCouponAccrualSetting (
  199.             4,
  200.             "Act/360",
  201.             false,
  202.             "Act/360",
  203.             false,
  204.             strCurrency,
  205.             true,
  206.             CompositePeriodBuilder.ACCRUAL_COMPOUNDING_RULE_GEOMETRIC
  207.         );

  208.         ComposableFloatingUnitSetting cfusFloating = new ComposableFloatingUnitSetting (
  209.             "3M",
  210.             CompositePeriodBuilder.EDGE_DATE_SEQUENCE_REGULAR,
  211.             null,
  212.             ForwardLabel.Create (
  213.                 strCurrency,
  214.                 "3M"
  215.             ),
  216.             CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE,
  217.             0.
  218.         );

  219.         ComposableFixedUnitSetting cfusFixed = new ComposableFixedUnitSetting (
  220.             "3M",
  221.             CompositePeriodBuilder.EDGE_DATE_SEQUENCE_REGULAR,
  222.             null,
  223.             0.,
  224.             0.,
  225.             strCurrency
  226.         );

  227.         CompositePeriodSetting cpsFloating = new CompositePeriodSetting (
  228.             4,
  229.             "3M",
  230.             strCurrency,
  231.             null,
  232.             -1.,
  233.             null,
  234.             null,
  235.             null,
  236.             null
  237.         );

  238.         CompositePeriodSetting cpsFixed = new CompositePeriodSetting (
  239.             4,
  240.             "3M",
  241.             strCurrency,
  242.             null,
  243.             1.,
  244.             null,
  245.             null,
  246.             null,
  247.             null
  248.         );

  249.         CashSettleParams csp = new CashSettleParams (
  250.             0,
  251.             strCurrency,
  252.             0
  253.         );

  254.         for (int i = 0; i < astrMaturityTenor.length; ++i) {
  255.             List<Integer> lsFixedStreamEdgeDate = CompositePeriodBuilder.RegularEdgeDates (
  256.                 dtEffective,
  257.                 "3M",
  258.                 astrMaturityTenor[i],
  259.                 null
  260.             );

  261.             List<Integer> lsFloatingStreamEdgeDate = CompositePeriodBuilder.RegularEdgeDates (
  262.                 dtEffective,
  263.                 "3M",
  264.                 astrMaturityTenor[i],
  265.                 null
  266.             );

  267.             Stream floatingStream = new Stream (
  268.                 CompositePeriodBuilder.FloatingCompositeUnit (
  269.                     lsFloatingStreamEdgeDate,
  270.                     cpsFloating,
  271.                     cfusFloating
  272.                 )
  273.             );

  274.             Stream fixedStream = new Stream (
  275.                 CompositePeriodBuilder.FixedCompositeUnit (
  276.                     lsFixedStreamEdgeDate,
  277.                     cpsFixed,
  278.                     ucasFixed,
  279.                     cfusFixed
  280.                 )
  281.             );

  282.             FixFloatComponent irs = new FixFloatComponent (
  283.                 fixedStream,
  284.                 floatingStream,
  285.                 csp
  286.             );

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

  288.             aIRS[i] = irs;
  289.         }

  290.         return aIRS;
  291.     }

  292.     /*
  293.      * This sample demonstrates discount curve calibration and input instrument calibration quote recovery.
  294.      *  It shows the following:
  295.      *  - Construct the Array of Cash/Swap Instruments and their Quotes from the given set of parameters.
  296.      *  - Construct the Cash/Swap Instrument Set Stretch Builder.
  297.      *  - Set up the Linear Curve Calibrator using the following parameters:
  298.      *      - Cubic Exponential Mixture Basis Spline Set
  299.      *      - Ck = 2, Segment Curvature Penalty = 2
  300.      *      - Quadratic Rational Shape Controller
  301.      *      - Natural Boundary Setting
  302.      *  - Construct the Shape Preserving Discount Curve by applying the linear curve calibrator to the array
  303.      *      of Cash and Swap Stretches.
  304.      *  - Cross-Comparison of the Cash/Swap Calibration Instrument "Rate" metric across the different curve
  305.      *      construction methodologies.
  306.      *
  307.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  308.      */

  309.     private static final MergedDiscountForwardCurve OTCInstrumentCurve (
  310.         final JulianDate dtSpot,
  311.         final String strCurrency)
  312.         throws Exception
  313.     {
  314.         /*
  315.          * Construct the Array of Deposit Instruments and their Quotes from the given set of parameters
  316.          */

  317.         SingleStreamComponent[] aDepositComp = DepositInstrumentsFromMaturityDays (
  318.             dtSpot,
  319.             strCurrency,
  320.             new int[] {
  321.                 1, 2, 7, 14, 30, 60
  322.             }
  323.         );

  324.         double[] adblDepositQuote = new double[] {
  325.             0.0013, 0.0017, 0.0017, 0.0018, 0.0020, 0.0023
  326.         };

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

  330.         LatentStateStretchSpec depositStretch = LatentStateStretchBuilder.ForwardFundingStretchSpec (
  331.             "DEPOSIT",
  332.             aDepositComp,
  333.             "ForwardRate",
  334.             adblDepositQuote
  335.         );

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

  339.         SingleStreamComponent[] aEDFComp = SingleStreamComponentBuilder.ForwardRateFuturesPack (
  340.             dtSpot,
  341.             8,
  342.             strCurrency
  343.         );

  344.         double[] adblEDFQuote = new double[] {
  345.             0.0027, 0.0032, 0.0041, 0.0054, 0.0077, 0.0104, 0.0134, 0.0160
  346.         };

  347.         /*
  348.          * Construct the EDF Instrument Set Stretch Builder
  349.          */

  350.         LatentStateStretchSpec edfStretch = LatentStateStretchBuilder.ForwardFundingStretchSpec (
  351.             "EDF",
  352.             aEDFComp,
  353.             "ForwardRate",
  354.             adblEDFQuote
  355.         );

  356.         /*
  357.          * Construct the Array of Swap Instruments and their Quotes from the given set of parameters
  358.          */

  359.         FixFloatComponent[] aSwapComp = SwapInstrumentsFromMaturityTenor (
  360.             dtSpot,
  361.             strCurrency,
  362.             new java.lang.String[] {
  363.                 "4Y", "5Y", "6Y", "7Y", "8Y", "9Y", "10Y", "11Y", "12Y", "15Y", "20Y", "25Y", "30Y", "40Y", "50Y"
  364.             }
  365.         );

  366.         double[] adblSwapQuote = new double[] {
  367.             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
  368.         };

  369.         /*
  370.          * Construct the Swap Instrument Set Stretch Builder
  371.          */

  372.         LatentStateStretchSpec swapStretch = LatentStateStretchBuilder.ForwardFundingStretchSpec (
  373.             "SWAP",
  374.             aSwapComp,
  375.             "SwapRate",
  376.             adblSwapQuote
  377.         );

  378.         LatentStateStretchSpec[] aStretchSpec = new LatentStateStretchSpec[] {
  379.             depositStretch,
  380.             edfStretch,
  381.             swapStretch
  382.         };

  383.         /*
  384.          * Set up the Linear Curve Calibrator using the following parameters:
  385.          *  - Cubic Exponential Mixture Basis Spline Set
  386.          *  - Ck = 2, Segment Curvature Penalty = 2
  387.          *  - Quadratic Rational Shape Controller
  388.          *  - Natural Boundary Setting
  389.          */

  390.         LinearLatentStateCalibrator lcc = new LinearLatentStateCalibrator (
  391.             new SegmentCustomBuilderControl (
  392.                 MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
  393.                 new PolynomialFunctionSetParams (4),
  394.                 SegmentInelasticDesignControl.Create (
  395.                     2,
  396.                     2
  397.                 ),
  398.                 new ResponseScalingShapeControl (
  399.                     true,
  400.                     new QuadraticRationalShapeControl (0.)
  401.                 ),
  402.                 null
  403.             ),
  404.             BoundarySettings.NaturalStandard(),
  405.             MultiSegmentSequence.CALIBRATE,
  406.             null,
  407.             null
  408.         );

  409.         ValuationParams valParams = new ValuationParams (
  410.             dtSpot,
  411.             dtSpot,
  412.             strCurrency
  413.         );

  414.         /*
  415.          * Construct the Shape Preserving Discount Curve by applying the linear curve calibrator to the array
  416.          *  of Deposit, Futures, and Swap Stretches.
  417.          */

  418.         MergedDiscountForwardCurve dc = ScenarioDiscountCurveBuilder.ShapePreservingDFBuild (
  419.             strCurrency,
  420.             lcc,
  421.             aStretchSpec,
  422.             valParams,
  423.             null,
  424.             null,
  425.             null,
  426.             1.
  427.         );

  428.         CurveSurfaceQuoteContainer csqs = MarketParamsBuilder.Create (
  429.             dc,
  430.             null,
  431.             null,
  432.             null,
  433.             null,
  434.             null,
  435.             null
  436.         );

  437.         /*
  438.          * Cross-Comparison of the Deposit Calibration Instrument "Rate" metric across the different curve
  439.          *  construction methodologies.
  440.          */

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

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

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

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

  448.         /*
  449.          * Cross-Comparison of the EDF Calibration Instrument "Rate" metric across the different curve
  450.          *  construction methodologies.
  451.          */

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

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

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

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

  459.         /*
  460.          * Cross-Comparison of the Swap Calibration Instrument "Rate" metric across the different curve
  461.          *  construction methodologies.
  462.          */

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

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

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

  466.         for (int i = 0; i < aSwapComp.length; ++i)
  467.             System.out.println ("\t[" + aSwapComp[i].maturityDate() + "] = " +
  468.                 FormatUtil.FormatDouble (aSwapComp[i].measureValue (valParams, null, csqs, null, "CalibSwapRate"), 1, 6, 1.)
  469.                     + " | " + FormatUtil.FormatDouble (adblSwapQuote[i], 1, 6, 1.) + " | " +
  470.                         FormatUtil.FormatDouble (aSwapComp[i].measureValue (valParams, null, csqs, null, "FairPremium"), 1, 6, 1.));

  471.         return dc;
  472.     }

  473.     private static final ForwardCurve LIBORSpan (
  474.         final MergedDiscountForwardCurve dc,
  475.         final ForwardLabel forwardLabel,
  476.         final SegmentCustomBuilderControl scbc,
  477.         final JulianDate dtView,
  478.         final int iNumForwardTenor)
  479.         throws Exception
  480.     {
  481.         int[] aiDate = new int[iNumForwardTenor + 1];
  482.         double[] adblLIBOR = new double[iNumForwardTenor + 1];
  483.         SegmentCustomBuilderControl[] aSCBC = new SegmentCustomBuilderControl[iNumForwardTenor];

  484.         JulianDate dtForward = dtView.subtractTenor (forwardLabel.tenor());

  485.         for (int i = 0; i <= iNumForwardTenor; ++i) {
  486.             if (iNumForwardTenor != i) aSCBC[i] = scbc;

  487.             aiDate[i] = dtForward.julian();

  488.             adblLIBOR[i] = dc.libor (dtForward, forwardLabel.tenor());

  489.             dtForward = dtForward.addTenor (forwardLabel.tenor());
  490.         }

  491.         return new BasisSplineForwardRate (
  492.             forwardLabel,
  493.             new OverlappingStretchSpan (
  494.                 MultiSegmentSequenceBuilder.CreateCalibratedStretchEstimator (
  495.                     "SPOT_QM_LIBOR",
  496.                     aiDate,
  497.                     adblLIBOR,
  498.                     aSCBC,
  499.                     null,
  500.                     BoundarySettings.NaturalStandard(),
  501.                     MultiSegmentSequence.CALIBRATE
  502.                 )
  503.             )
  504.         );
  505.     }

  506.     private static final MarketSurface FlatVolatilitySurface (
  507.         final JulianDate dtStart,
  508.         final String strCurrency,
  509.         final double dblFlatVol)
  510.         throws Exception
  511.     {
  512.         return ScenarioMarketSurfaceBuilder.CustomSplineWireSurface (
  513.             "VIEW_TARGET_VOLATILITY_SURFACE",
  514.             dtStart,
  515.             strCurrency,
  516.             new double[] {
  517.                 dtStart.julian(),
  518.                 dtStart.addYears (2).julian(),
  519.                 dtStart.addYears (4).julian(),
  520.                 dtStart.addYears (6).julian(),
  521.                 dtStart.addYears (8).julian(),
  522.                 dtStart.addYears (10).julian()
  523.             },
  524.             new double[] {
  525.                 dtStart.julian(),
  526.                 dtStart.addYears (2).julian(),
  527.                 dtStart.addYears (4).julian(),
  528.                 dtStart.addYears (6).julian(),
  529.                 dtStart.addYears (8).julian(),
  530.                 dtStart.addYears (10).julian()
  531.             },
  532.             new double[][] {
  533.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  534.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  535.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  536.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  537.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  538.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  539.             },
  540.             new SegmentCustomBuilderControl (
  541.                 MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
  542.                 new PolynomialFunctionSetParams (4),
  543.                 SegmentInelasticDesignControl.Create (
  544.                     2,
  545.                     2
  546.                 ),
  547.                 null,
  548.                 null
  549.             ),
  550.             new SegmentCustomBuilderControl (
  551.                 MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
  552.                 new PolynomialFunctionSetParams (4),
  553.                 SegmentInelasticDesignControl.Create (
  554.                     2,
  555.                     2
  556.                 ),
  557.                 null,
  558.                 null
  559.             )
  560.         );
  561.     }

  562.     private static final LognormalLIBORVolatility LLVInstance (
  563.         final int iSpotDate,
  564.         final ForwardLabel forwardLabel,
  565.         final MarketSurface[] aMS,
  566.         final double[][] aadblCorrelation,
  567.         final int iNumFactor)
  568.         throws Exception
  569.     {
  570.         UnivariateSequenceGenerator[] aUSG = new UnivariateSequenceGenerator[aMS.length];

  571.         for (int i = 0; i < aUSG.length; ++i)
  572.             aUSG[i] = new BoxMullerGaussian (
  573.                 0.,
  574.                 1.
  575.             );

  576.         return new LognormalLIBORVolatility (
  577.             iSpotDate,
  578.             forwardLabel,
  579.             aMS,
  580.             new PrincipalFactorSequenceGenerator (
  581.                 aUSG,
  582.                 aadblCorrelation,
  583.                 iNumFactor
  584.             )
  585.         );
  586.     }

  587.     public static final void main (
  588.         final String[] astrArgs)
  589.         throws Exception
  590.     {
  591.         EnvManager.InitEnv ("");

  592.         String strForwardTenor = "3M";
  593.         String strViewTenor = "1Y";
  594.         String strSimulationTenor = "1M";
  595.         String strCurrency = "USD";
  596.         double dblFlatVol1 = 0.35;
  597.         double dblFlatVol2 = 0.42;
  598.         double dblFlatVol3 = 0.27;
  599.         int iNumForwardTenor = 5;
  600.         int iNumFactor = 2;

  601.         double[][] aadblCorrelation = new double[][] {
  602.             {1.0, 0.1, 0.2},
  603.             {0.1, 1.0, 0.2},
  604.             {0.2, 0.1, 1.0}
  605.         };

  606.         SegmentCustomBuilderControl scbc = new SegmentCustomBuilderControl (
  607.             MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
  608.             new PolynomialFunctionSetParams (4),
  609.             SegmentInelasticDesignControl.Create (
  610.                 2,
  611.                 2
  612.             ),
  613.             new ResponseScalingShapeControl (
  614.                 true,
  615.                 new QuadraticRationalShapeControl (1.)
  616.             ),
  617.             null
  618.         );

  619.         JulianDate dtSpot = org.drip.analytics.date.DateUtil.Today();

  620.         MarketSurface[] aMS = new MarketSurface[] {
  621.             FlatVolatilitySurface (
  622.                 dtSpot,
  623.                 strCurrency,
  624.                 dblFlatVol1
  625.             ),
  626.             FlatVolatilitySurface (
  627.                 dtSpot,
  628.                 strCurrency,
  629.                 dblFlatVol2
  630.             ),
  631.             FlatVolatilitySurface (
  632.                 dtSpot,
  633.                 strCurrency,
  634.                 dblFlatVol3
  635.             )
  636.         };

  637.         FundingLabel fundingLabel = FundingLabel.Standard (
  638.             strCurrency
  639.         );

  640.         ForwardLabel forwardLabel = ForwardLabel.Create (
  641.             strCurrency,
  642.             strForwardTenor
  643.         );

  644.         MergedDiscountForwardCurve dc = OTCInstrumentCurve (
  645.             dtSpot,
  646.             strCurrency
  647.         );

  648.         JulianDate dtView = dtSpot.addTenor (strViewTenor);

  649.         ForwardCurve fc = LIBORSpan (
  650.             dc,
  651.             forwardLabel,
  652.             scbc,
  653.             dtView,
  654.             iNumForwardTenor
  655.         );

  656.         LognormalLIBORCurveEvolver llce = LognormalLIBORCurveEvolver.Create (
  657.             fundingLabel,
  658.             forwardLabel,
  659.             iNumForwardTenor,
  660.             scbc
  661.         );

  662.         BGMCurveUpdate bgmInitial = BGMCurveUpdate.Create (
  663.             fundingLabel,
  664.             forwardLabel,
  665.             dtSpot.julian(),
  666.             dtSpot.julian(),
  667.             fc,
  668.             null,
  669.             dc,
  670.             null,
  671.             null,
  672.             null,
  673.             null,
  674.             null,
  675.             LLVInstance (
  676.                 dtSpot.julian(),
  677.                 forwardLabel,
  678.                 aMS,
  679.                 aadblCorrelation,
  680.                 iNumFactor
  681.             )
  682.         );

  683.         double[][] aadblTenorLIBOR = llce.simulatePrincipalMetric (
  684.             dtSpot.julian(),
  685.             dtSpot.addTenor (strSimulationTenor).julian(),
  686.             1,
  687.             dtView.julian(),
  688.             bgmInitial,
  689.             2
  690.         );

  691.         String strBoundary = "\t|---";
  692.         String strTenorDump = "\t|              |";
  693.         JulianDate[] adtForward = new JulianDate[iNumForwardTenor + 1];

  694.         for (int iTenorDate = 0; iTenorDate <= iNumForwardTenor; ++iTenorDate) {
  695.             adtForward[iTenorDate] = 0 == iTenorDate ?
  696.                 dtView.addTenor (forwardLabel.tenor()) :
  697.                 adtForward[iTenorDate - 1].addTenor (forwardLabel.tenor());

  698.             strBoundary += "-----------------";
  699.             strTenorDump += "  " + adtForward[iTenorDate] + "  |";
  700.         }

  701.         System.out.println ("\n\n" +
  702.             strBoundary + "\n" +
  703.             strTenorDump + "\n" +
  704.             strBoundary
  705.         );

  706.         for (int iSimulationDate = 0; iSimulationDate < aadblTenorLIBOR.length; ++iSimulationDate) {
  707.             double[] adblCurveNode = aadblTenorLIBOR[iSimulationDate];

  708.             String strCurveNodeDump = "\t|  " + dtSpot.addDays (iSimulationDate + 1) + " =>";

  709.             for (int i = 0; i < aadblTenorLIBOR[i].length; ++i)
  710.                 strCurveNodeDump += "   " + FormatUtil.FormatDouble (adblCurveNode[i], 1, 3, 100.) +  "%    |";

  711.             System.out.println (strCurveNodeDump);
  712.         }

  713.         System.out.println (strBoundary);

  714.         EnvManager.TerminateEnv();
  715.     }
  716. }