MultiFactorCurveDynamics.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.Span;
  19. import org.drip.spline.params.*;
  20. import org.drip.spline.stretch.*;
  21. import org.drip.state.creator.*;
  22. import org.drip.state.discount.*;
  23. import org.drip.state.estimator.LatentStateStretchBuilder;
  24. import org.drip.state.forward.ForwardCurve;
  25. import org.drip.state.identifier.*;
  26. import org.drip.state.inference.*;

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

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

  92. /**
  93.  * <i>MultiFactorCurveDynamics</i> demonstrates the Construction and Usage of the Curve LIBOR State Evolver,
  94.  * and the eventual Evolution of the related Discount/Forward Latent State Quantification Metrics. The
  95.  * 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 MultiFactorCurveDynamics {

  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 MarketSurface FlatVolatilitySurface (
  474.         final JulianDate dtStart,
  475.         final String strCurrency,
  476.         final double dblFlatVol)
  477.         throws Exception
  478.     {
  479.         return ScenarioMarketSurfaceBuilder.CustomSplineWireSurface (
  480.             "VIEW_TARGET_VOLATILITY_SURFACE",
  481.             dtStart,
  482.             strCurrency,
  483.             new double[] {
  484.                 dtStart.julian(),
  485.                 dtStart.addYears (2).julian(),
  486.                 dtStart.addYears (4).julian(),
  487.                 dtStart.addYears (6).julian(),
  488.                 dtStart.addYears (8).julian(),
  489.                 dtStart.addYears (10).julian()
  490.             },
  491.             new double[] {
  492.                 dtStart.julian(),
  493.                 dtStart.addYears (2).julian(),
  494.                 dtStart.addYears (4).julian(),
  495.                 dtStart.addYears (6).julian(),
  496.                 dtStart.addYears (8).julian(),
  497.                 dtStart.addYears (10).julian()
  498.             },
  499.             new double[][] {
  500.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  501.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  502.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  503.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  504.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  505.                 {dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol, dblFlatVol},
  506.             },
  507.             new SegmentCustomBuilderControl (
  508.                 MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
  509.                 new PolynomialFunctionSetParams (4),
  510.                 SegmentInelasticDesignControl.Create (
  511.                     2,
  512.                     2
  513.                 ),
  514.                 null,
  515.                 null
  516.             ),
  517.             new SegmentCustomBuilderControl (
  518.                 MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
  519.                 new PolynomialFunctionSetParams (4),
  520.                 SegmentInelasticDesignControl.Create (
  521.                     2,
  522.                     2
  523.                 ),
  524.                 null,
  525.                 null
  526.             )
  527.         );
  528.     }

  529.     private static final LognormalLIBORVolatility LLVInstance (
  530.         final int iSpotDate,
  531.         final ForwardLabel forwardLabel,
  532.         final MarketSurface[] aMS,
  533.         final double[][] aadblCorrelation,
  534.         final int iNumFactor)
  535.         throws Exception
  536.     {
  537.         UnivariateSequenceGenerator[] aUSG = new UnivariateSequenceGenerator[aMS.length];

  538.         for (int i = 0; i < aUSG.length; ++i)
  539.             aUSG[i] = new BoxMullerGaussian (
  540.                 0.,
  541.                 1.
  542.             );

  543.         return new LognormalLIBORVolatility (
  544.             iSpotDate,
  545.             forwardLabel,
  546.             aMS,
  547.             new PrincipalFactorSequenceGenerator (
  548.                 aUSG,
  549.                 aadblCorrelation,
  550.                 iNumFactor
  551.             )
  552.         );
  553.     }

  554.     public static final void main (
  555.         final String[] astrArgs)
  556.         throws Exception
  557.     {
  558.         EnvManager.InitEnv ("");

  559.         String strTenor = "3M";
  560.         String strCurrency = "USD";
  561.         double dblFlatVol1 = 0.35;
  562.         double dblFlatVol2 = 0.42;
  563.         double dblFlatVol3 = 0.27;
  564.         double dblFlatForwardRate = 0.02;
  565.         int iNumRun = 1;

  566.         int[] aiNumFactor = {
  567.             1, 2, 3
  568.         };

  569.         double[][] aadblCorrelation = new double[][] {
  570.             {1.0, 0.1, 0.2},
  571.             {0.1, 1.0, 0.2},
  572.             {0.2, 0.1, 1.0}
  573.         };

  574.         ForwardLabel forwardLabel = ForwardLabel.Create (
  575.             strCurrency,
  576.             strTenor
  577.         );

  578.         FundingLabel fundingLabel = FundingLabel.Standard (
  579.             strCurrency
  580.         );

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

  582.         MarketSurface[] aMS = new MarketSurface[] {
  583.             FlatVolatilitySurface (
  584.                 dtSpot,
  585.                 strCurrency,
  586.                 dblFlatVol1
  587.             ),
  588.             FlatVolatilitySurface (
  589.                 dtSpot,
  590.                 strCurrency,
  591.                 dblFlatVol2
  592.             ),
  593.             FlatVolatilitySurface (
  594.                 dtSpot,
  595.                 strCurrency,
  596.                 dblFlatVol3
  597.             )
  598.         };

  599.         ForwardCurve fc = ScenarioForwardCurveBuilder.FlatForwardForwardCurve (
  600.             dtSpot,
  601.             forwardLabel,
  602.             dblFlatForwardRate
  603.         );

  604.         MergedDiscountForwardCurve dc = OTCInstrumentCurve (
  605.             dtSpot,
  606.             strCurrency
  607.         );

  608.         int iSpotDate = dtSpot.julian();

  609.         JulianDate dtView = dtSpot.addTenor ("1Y");

  610.         int iViewDate = dtView.julian();

  611.         int iNumForwardTenor = 5;
  612.         int iViewTimeIncrement = 1;
  613.         String strBoundary = "\t|";
  614.         String strTenorDump = "\t|";
  615.         JulianDate[] adtIndex = new JulianDate[iNumForwardTenor + 1];
  616.         JulianDate[] adtForward = new JulianDate[iNumForwardTenor + 1];

  617.         for (int iTenorDate = 0; iTenorDate <= iNumForwardTenor; ++iTenorDate) {
  618.             adtIndex[iTenorDate] = 0 == iTenorDate ? dtView : adtIndex[iTenorDate - 1].addTenor (forwardLabel.tenor());

  619.             adtForward[iTenorDate] = 0 == iTenorDate ?
  620.                 dtView.addTenor (forwardLabel.tenor()) :
  621.                 adtForward[iTenorDate - 1].addTenor (forwardLabel.tenor());

  622.             strBoundary += "---------------";
  623.             strTenorDump += "  " + adtForward[iTenorDate] + "  |";
  624.         }

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

  638.          for (int iNumFactor : aiNumFactor) {
  639.             LognormalLIBORCurveEvolver llce = LognormalLIBORCurveEvolver.Create (
  640.                 fundingLabel,
  641.                 forwardLabel,
  642.                 iNumForwardTenor,
  643.                 scbc
  644.             );

  645.             BGMCurveUpdate bgmcu = BGMCurveUpdate.Create (
  646.                 fundingLabel,
  647.                 forwardLabel,
  648.                 iSpotDate,
  649.                 iSpotDate,
  650.                 fc,
  651.                 null,
  652.                 dc,
  653.                 null,
  654.                 null,
  655.                 null,
  656.                 null,
  657.                 null,
  658.                 LLVInstance (
  659.                     dtSpot.julian(),
  660.                     forwardLabel,
  661.                     aMS,
  662.                     aadblCorrelation,
  663.                     iNumFactor
  664.                 )
  665.             );

  666.             for (int iRun = 0; iRun < iNumRun; ++iRun) {
  667.                 String strLIBORDump = "\t|";
  668.                 String strDiscountFactorDump = "\t|";
  669.                 String strLIBORIncrementDump = "\t|";
  670.                 String strSpotRateIncrementDump = "\t|";
  671.                 String strNominalAnnualForwardDump = "\t|";
  672.                 String strEffectiveAnnualForwardDump = "\t|";
  673.                 String strDiscountFactorIncrementDump = "\t|";
  674.                 String strContinuousForwardIncrementDump = "\t|";

  675.                 BGMCurveUpdate bgmUpdate = llce.evolve (
  676.                     iSpotDate,
  677.                     iViewDate,
  678.                     iViewTimeIncrement,
  679.                     bgmcu
  680.                 );

  681.                 ForwardCurve fcLIBOR = bgmUpdate.forwardCurve();

  682.                 MergedDiscountForwardCurve dcDiscountFactor = bgmUpdate.discountCurve();

  683.                 Span spanLIBORIncrement = bgmUpdate.forwardCurveIncrement();

  684.                 Span spanDFIncrement = bgmUpdate.discountCurveIncrement();

  685.                 Span spanContinuousForwardIncrement = bgmUpdate.continuousForwardRateIncrement();

  686.                 Span spanSpotRateIncrement = bgmUpdate.spotRateIncrement();

  687.                 Span spanEffectiveAnnualForward = bgmUpdate.instantaneousEffectiveForwardRate();

  688.                 Span spanNominalAnnualForward = bgmUpdate.instantaneousNominalForwardRate();

  689.                 for (int iTenorDate = 0; iTenorDate <= iNumForwardTenor; ++iTenorDate) {
  690.                     strLIBORDump += "    " +
  691.                         FormatUtil.FormatDouble (fcLIBOR.forward (adtForward[iTenorDate]), 1, 2, 100.) +
  692.                         "%    |";

  693.                     strDiscountFactorDump += "   " +
  694.                         FormatUtil.FormatDouble (dcDiscountFactor.df (adtIndex[iTenorDate]), 1, 4, 1.) +
  695.                         "    |";

  696.                     strLIBORIncrementDump += "     " +
  697.                         FormatUtil.FormatDouble (spanLIBORIncrement.calcResponseValue (adtIndex[iTenorDate].julian()), 2, 0, 10000.) +
  698.                         "      |";

  699.                     strDiscountFactorIncrementDump += "     " +
  700.                         FormatUtil.FormatDouble (spanDFIncrement.calcResponseValue (adtIndex[iTenorDate].julian()), 2, 0, 100.) +
  701.                         "      |";

  702.                     strContinuousForwardIncrementDump += "     " +
  703.                         FormatUtil.FormatDouble (spanContinuousForwardIncrement.calcResponseValue (adtIndex[iTenorDate].julian()), 2, 0, 10000.) +
  704.                         "      |";

  705.                     strSpotRateIncrementDump += "     " +
  706.                         FormatUtil.FormatDouble (spanSpotRateIncrement.calcResponseValue (adtIndex[iTenorDate].julian()), 2, 0, 10000.) +
  707.                         "      |";

  708.                     strEffectiveAnnualForwardDump += "    " +
  709.                         FormatUtil.FormatDouble (spanEffectiveAnnualForward.calcResponseValue (adtIndex[iTenorDate].julian()), 1, 2, 100.) +
  710.                         "%    |";

  711.                     strNominalAnnualForwardDump += "    " +
  712.                         FormatUtil.FormatDouble (spanNominalAnnualForward.calcResponseValue (adtIndex[iTenorDate].julian()), 1, 2, 100.) +
  713.                         "%    |";
  714.                 }

  715.                 System.out.println ("\n\n" +
  716.                     strBoundary + "\n" +
  717.                     strTenorDump + "\n" +
  718.                     strBoundary + "\n" +
  719.                     strLIBORDump + "\n" +
  720.                     strDiscountFactorDump + "\n" +
  721.                     strLIBORIncrementDump + "\n" +
  722.                     strDiscountFactorIncrementDump + "\n" +
  723.                     strContinuousForwardIncrementDump + "\n" +
  724.                     strSpotRateIncrementDump + "\n" +
  725.                     strEffectiveAnnualForwardDump + "\n" +
  726.                     strNominalAnnualForwardDump + "\n" +
  727.                     strBoundary
  728.                 );
  729.             }
  730.         }

  731.         EnvManager.TerminateEnv();
  732.     }
  733. }