FixFloatMonteCarloEvolver.java

  1. package org.drip.sample.lmm;

  2. import java.util.*;

  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>FixFloatMonteCarloEvolver</i> demonstrates the steps associated with a LMM-Based Monte-Carlo pricing of
  95.  * a Standard Fix-Float Swap. 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 FixFloatMonteCarloEvolver {

  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 Swap Instrument 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 SwapInstrumentFromMaturityTenor (
  192.         final JulianDate dtEffective,
  193.         final String strCurrency,
  194.         final double dblFixedCoupon,
  195.         final String strMaturityTenor)
  196.         throws Exception
  197.     {
  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.             dblFixedCoupon,
  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.         List<Integer> lsFixedStreamEdgeDate = CompositePeriodBuilder.RegularEdgeDates (
  255.             dtEffective,
  256.             "3M",
  257.             strMaturityTenor,
  258.             null
  259.         );

  260.         List<Integer> lsFloatingStreamEdgeDate = CompositePeriodBuilder.RegularEdgeDates (
  261.             dtEffective,
  262.             "3M",
  263.             strMaturityTenor,
  264.             null
  265.         );

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

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

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

  286.         irs.setPrimaryCode ("IRS." + strMaturityTenor + "." + strCurrency);

  287.         return irs;
  288.     }

  289.     /*
  290.      * Construct the Array of Swap Instruments from the given set of parameters
  291.      *
  292.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  293.      */

  294.     private static final FixFloatComponent[] SwapInstrumentsFromMaturityTenor (
  295.         final JulianDate dtEffective,
  296.         final String strCurrency,
  297.         final String[] astrMaturityTenor)
  298.         throws Exception
  299.     {
  300.         FixFloatComponent[] aIRS = new FixFloatComponent[astrMaturityTenor.length];

  301.         for (int i = 0; i < astrMaturityTenor.length; ++i)
  302.             aIRS[i] = SwapInstrumentFromMaturityTenor (
  303.                 dtEffective,
  304.                 strCurrency,
  305.                 0.,
  306.                 astrMaturityTenor[i]
  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 MergedDiscountForwardCurve 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 java.lang.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\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.         /*
  467.          * Cross-Comparison of the EDF Calibration Instrument "Rate" metric across the different curve
  468.          *  construction methodologies.
  469.          */

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

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

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

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

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

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

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

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

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

  489.         return dc;
  490.     }

  491.     private static final ForwardCurve LIBORSpan (
  492.         final MergedDiscountForwardCurve dc,
  493.         final ForwardLabel forwardLabel,
  494.         final SegmentCustomBuilderControl scbc,
  495.         final JulianDate dtView,
  496.         final int iNumForwardTenor)
  497.         throws Exception
  498.     {
  499.         int[] aiDate = new int[iNumForwardTenor + 1];
  500.         double[] adblLIBOR = new double[iNumForwardTenor + 1];
  501.         SegmentCustomBuilderControl[] aSCBC = new SegmentCustomBuilderControl[iNumForwardTenor];

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

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

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

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

  507.             dtForward = dtForward.addTenor (forwardLabel.tenor());
  508.         }

  509.         return new BasisSplineForwardRate (
  510.             forwardLabel,
  511.             new OverlappingStretchSpan (
  512.                 MultiSegmentSequenceBuilder.CreateCalibratedStretchEstimator (
  513.                     "SPOT_QM_LIBOR",
  514.                     aiDate,
  515.                     adblLIBOR,
  516.                     aSCBC,
  517.                     null,
  518.                     BoundarySettings.NaturalStandard(),
  519.                     MultiSegmentSequence.CALIBRATE
  520.                 )
  521.             )
  522.         );
  523.     }

  524.     private static final MarketSurface FlatVolatilitySurface (
  525.         final JulianDate dtStart,
  526.         final String strCurrency,
  527.         final double dblFlatVol)
  528.         throws Exception
  529.     {
  530.         return ScenarioMarketSurfaceBuilder.CustomSplineWireSurface (
  531.             "VIEW_TARGET_VOLATILITY_SURFACE",
  532.             dtStart,
  533.             strCurrency,
  534.             new double[] {
  535.                 dtStart.julian(),
  536.                 dtStart.addYears (2).julian(),
  537.                 dtStart.addYears (4).julian(),
  538.                 dtStart.addYears (6).julian(),
  539.                 dtStart.addYears (8).julian(),
  540.                 dtStart.addYears (10).julian()
  541.             },
  542.             new double[] {
  543.                 dtStart.julian(),
  544.                 dtStart.addYears (2).julian(),
  545.                 dtStart.addYears (4).julian(),
  546.                 dtStart.addYears (6).julian(),
  547.                 dtStart.addYears (8).julian(),
  548.                 dtStart.addYears (10).julian()
  549.             },
  550.             new double[][] {
  551.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  552.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  553.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  554.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  555.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  556.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  557.             },
  558.             new SegmentCustomBuilderControl (
  559.                 MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
  560.                 new PolynomialFunctionSetParams (4),
  561.                 SegmentInelasticDesignControl.Create (
  562.                     2,
  563.                     2
  564.                 ),
  565.                 null,
  566.                 null
  567.             ),
  568.             new SegmentCustomBuilderControl (
  569.                 MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
  570.                 new PolynomialFunctionSetParams (4),
  571.                 SegmentInelasticDesignControl.Create (
  572.                     2,
  573.                     2
  574.                 ),
  575.                 null,
  576.                 null
  577.             )
  578.         );
  579.     }

  580.     private static final LognormalLIBORVolatility LLVInstance (
  581.         final int iSpotDate,
  582.         final ForwardLabel forwardLabel,
  583.         final MarketSurface[] aMS,
  584.         final double[][] aadblCorrelation,
  585.         final int iNumFactor)
  586.         throws Exception
  587.     {
  588.         UnivariateSequenceGenerator[] aUSG = new UnivariateSequenceGenerator[aMS.length];

  589.         for (int i = 0; i < aUSG.length; ++i)
  590.             aUSG[i] = new BoxMullerGaussian (
  591.                 0.,
  592.                 1.
  593.             );

  594.         return new LognormalLIBORVolatility (
  595.             iSpotDate,
  596.             forwardLabel,
  597.             aMS,
  598.             new PrincipalFactorSequenceGenerator (
  599.                 aUSG,
  600.                 aadblCorrelation,
  601.                 iNumFactor
  602.             )
  603.         );
  604.     }

  605.     public static final void main (
  606.         final String[] astrArgs)
  607.         throws Exception
  608.     {
  609.         EnvManager.InitEnv ("");

  610.         String strForwardTenor = "3M";
  611.         String strViewTenor = "6M";
  612.         String strSimulationTenor = "6M";
  613.         String strSwapTenor = "5Y";
  614.         String strCurrency = "USD";
  615.         double dblFlatVol1 = 0.35;
  616.         double dblFlatVol2 = 0.42;
  617.         double dblFlatVol3 = 0.27;
  618.         int iNumForwardTenor = 30;
  619.         int iNumFactor = 2;
  620.         int iNumRun = 100;

  621.         double[][] aadblCorrelation = new double[][] {
  622.             {1.0, 0.1, 0.2},
  623.             {0.1, 1.0, 0.2},
  624.             {0.2, 0.1, 1.0}
  625.         };

  626.         SegmentCustomBuilderControl scbc = new SegmentCustomBuilderControl (
  627.             MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
  628.             new PolynomialFunctionSetParams (4),
  629.             SegmentInelasticDesignControl.Create (
  630.                 2,
  631.                 2
  632.             ),
  633.             new ResponseScalingShapeControl (
  634.                 true,
  635.                 new QuadraticRationalShapeControl (1.)
  636.             ),
  637.             null
  638.         );

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

  640.         MarketSurface[] aMS = new MarketSurface[] {
  641.             FlatVolatilitySurface (
  642.                 dtSpot,
  643.                 strCurrency,
  644.                 dblFlatVol1
  645.             ),
  646.             FlatVolatilitySurface (
  647.                 dtSpot,
  648.                 strCurrency,
  649.                 dblFlatVol2
  650.             ),
  651.             FlatVolatilitySurface (
  652.                 dtSpot,
  653.                 strCurrency,
  654.                 dblFlatVol3
  655.             )
  656.         };

  657.         FundingLabel fundingLabel = FundingLabel.Standard (
  658.             strCurrency
  659.         );

  660.         ForwardLabel forwardLabel = ForwardLabel.Create (
  661.             strCurrency,
  662.             strForwardTenor
  663.         );

  664.         JulianDate dtView = dtSpot.addTenor (
  665.             strViewTenor
  666.         );

  667.         JulianDate dtSimulationEnd = dtSpot.addTenor (
  668.             strSimulationTenor
  669.         );

  670.         MergedDiscountForwardCurve dc = OTCInstrumentCurve (
  671.             dtSpot,
  672.             strCurrency
  673.         );

  674.         FixFloatComponent ffcFixFloat = SwapInstrumentFromMaturityTenor (
  675.             dtView,
  676.             strCurrency,
  677.             0.,
  678.             strSwapTenor
  679.         );

  680.         ValuationParams valParams = new ValuationParams (
  681.             dtSpot,
  682.             dtSpot,
  683.             strCurrency
  684.         );

  685.         ForwardCurve fc = LIBORSpan (
  686.             dc,
  687.             forwardLabel,
  688.             scbc,
  689.             dtView,
  690.             iNumForwardTenor
  691.         );

  692.         CurveSurfaceQuoteContainer csqs = MarketParamsBuilder.DiscountForward (
  693.             dc,
  694.             fc
  695.         );

  696.         double dblBaselineSwapRate = ffcFixFloat.value (
  697.             valParams,
  698.             null,
  699.             csqs,
  700.             null
  701.         ).get (
  702.             "FairPremium"
  703.         );

  704.         ffcFixFloat = SwapInstrumentFromMaturityTenor (
  705.             dtSpot,
  706.             strCurrency,
  707.             dblBaselineSwapRate,
  708.             strSwapTenor
  709.         );

  710.         LognormalLIBORCurveEvolver llce = LognormalLIBORCurveEvolver.Create (
  711.             fundingLabel,
  712.             forwardLabel,
  713.             iNumForwardTenor,
  714.             scbc
  715.         );

  716.         BGMCurveUpdate bgmInitial = BGMCurveUpdate.Create (
  717.             fundingLabel,
  718.             forwardLabel,
  719.             dtSpot.julian(),
  720.             dtSpot.julian(),
  721.             fc,
  722.             null,
  723.             dc,
  724.             null,
  725.             null,
  726.             null,
  727.             null,
  728.             null,
  729.             LLVInstance (
  730.                 dtSpot.julian(),
  731.                 forwardLabel,
  732.                 aMS,
  733.                 aadblCorrelation,
  734.                 iNumFactor
  735.             )
  736.         );

  737.         ForwardCurve[] aFCLIBOR = llce.simulateTerminalLatentState (
  738.             dtSpot.julian(),
  739.             dtSimulationEnd.julian(),
  740.             1,
  741.             dtView.julian(),
  742.             bgmInitial,
  743.             iNumRun
  744.         );

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

  746.         System.out.println ("\t||  SIML  |  BASE  |   PV  |  ITM  ||");

  747.         System.out.println ("\t||---------------------------------||");

  748.         int iNumITM = 0;
  749.         double dblOptionPayout = 0.;

  750.         for (int i = 0; i < iNumRun; ++i) {
  751.             Map<String, Double> mapScenOutput = ffcFixFloat.value (
  752.                 new ValuationParams (
  753.                     dtSimulationEnd,
  754.                     dtSimulationEnd,
  755.                     strCurrency
  756.                 ),
  757.                 null,
  758.                 MarketParamsBuilder.DiscountForward (
  759.                     dc,
  760.                     aFCLIBOR[i]
  761.                 ),
  762.                 null
  763.             );

  764.             double dblSimulatedPayout = mapScenOutput.get ("PV");

  765.             double dblSimulatedSwapRate = mapScenOutput.get ("FairPremium");

  766.             boolean bITM = dblSimulatedSwapRate < dblBaselineSwapRate;

  767.             if (bITM) {
  768.                 ++iNumITM;
  769.                 dblOptionPayout += dblSimulatedPayout;
  770.             }

  771.             System.out.println ("\t|| " +
  772.                 FormatUtil.FormatDouble (dblSimulatedSwapRate, 1, 2, 100.) + "% | " +
  773.                 FormatUtil.FormatDouble (dblBaselineSwapRate, 1, 2, 100.) + "% | " +
  774.                 FormatUtil.FormatDouble (dblSimulatedPayout, 1, 2, 1.) + " | " +
  775.                 (bITM ? " OUI  ||" : " NON  ||")
  776.             );
  777.         }

  778.         System.out.println ("\t||---------------------------------||");

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

  780.         System.out.println ("\t||  ITM Success Rate:" +
  781.             FormatUtil.FormatDouble (((double) iNumITM) / iNumRun, 2, 2, 100.) + "% ||"
  782.         );

  783.         System.out.println ("\t||  Option Payout   :" +
  784.             FormatUtil.FormatDouble (dblOptionPayout / iNumRun, 1, 4, 1.) + " ||"
  785.         );

  786.         System.out.println ("\t||  Option PV       :" +
  787.             FormatUtil.FormatDouble (dblOptionPayout * dc.df (dtSimulationEnd) / iNumRun, 1, 4, 1.) + " ||"
  788.         );

  789.         System.out.println ("\t||---------------------------||");

  790.         EnvManager.TerminateEnv();
  791.     }
  792. }