PathSimulator.java

  1. package org.drip.xva.dynamics;

  2. /*
  3.  * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  4.  */

  5. /*!
  6.  * Copyright (C) 2020 Lakshmi Krishnamurthy
  7.  * Copyright (C) 2019 Lakshmi Krishnamurthy
  8.  * Copyright (C) 2018 Lakshmi Krishnamurthy
  9.  * Copyright (C) 2017 Lakshmi Krishnamurthy
  10.  *
  11.  *  This file is part of DROP, an open-source library targeting analytics/risk, transaction cost analytics,
  12.  *      asset liability management analytics, capital, exposure, and margin analytics, valuation adjustment
  13.  *      analytics, and portfolio construction analytics within and across fixed income, credit, commodity,
  14.  *      equity, FX, and structured products. It also includes auxiliary libraries for algorithm support,
  15.  *      numerical analysis, numerical optimization, spline builder, model validation, statistical learning,
  16.  *      and computational support.
  17.  *  
  18.  *      https://lakshmidrip.github.io/DROP/
  19.  *  
  20.  *  DROP is composed of three modules:
  21.  *  
  22.  *  - DROP Product Core - https://lakshmidrip.github.io/DROP-Product-Core/
  23.  *  - DROP Portfolio Core - https://lakshmidrip.github.io/DROP-Portfolio-Core/
  24.  *  - DROP Computational Core - https://lakshmidrip.github.io/DROP-Computational-Core/
  25.  *
  26.  *  DROP Product Core implements libraries for the following:
  27.  *  - Fixed Income Analytics
  28.  *  - Loan Analytics
  29.  *  - Transaction Cost Analytics
  30.  *
  31.  *  DROP Portfolio Core implements libraries for the following:
  32.  *  - Asset Allocation Analytics
  33.  *  - Asset Liability Management Analytics
  34.  *  - Capital Estimation Analytics
  35.  *  - Exposure Analytics
  36.  *  - Margin Analytics
  37.  *  - XVA Analytics
  38.  *
  39.  *  DROP Computational Core implements libraries for the following:
  40.  *  - Algorithm Support
  41.  *  - Computation Support
  42.  *  - Function Analysis
  43.  *  - Model Validation
  44.  *  - Numerical Analysis
  45.  *  - Numerical Optimizer
  46.  *  - Spline Builder
  47.  *  - Statistical Learning
  48.  *
  49.  *  Documentation for DROP is Spread Over:
  50.  *
  51.  *  - Main                     => https://lakshmidrip.github.io/DROP/
  52.  *  - Wiki                     => https://github.com/lakshmiDRIP/DROP/wiki
  53.  *  - GitHub                   => https://github.com/lakshmiDRIP/DROP
  54.  *  - Repo Layout Taxonomy     => https://github.com/lakshmiDRIP/DROP/blob/master/Taxonomy.md
  55.  *  - Javadoc                  => https://lakshmidrip.github.io/DROP/Javadoc/index.html
  56.  *  - Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal
  57.  *  - Release Versions         => https://lakshmidrip.github.io/DROP/version.html
  58.  *  - Community Credits        => https://lakshmidrip.github.io/DROP/credits.html
  59.  *  - Issues Catalog           => https://github.com/lakshmiDRIP/DROP/issues
  60.  *  - JUnit                    => https://lakshmidrip.github.io/DROP/junit/index.html
  61.  *  - Jacoco                   => https://lakshmidrip.github.io/DROP/jacoco/index.html
  62.  *
  63.  *  Licensed under the Apache License, Version 2.0 (the "License");
  64.  *      you may not use this file except in compliance with the License.
  65.  *  
  66.  *  You may obtain a copy of the License at
  67.  *      http://www.apache.org/licenses/LICENSE-2.0
  68.  *  
  69.  *  Unless required by applicable law or agreed to in writing, software
  70.  *      distributed under the License is distributed on an "AS IS" BASIS,
  71.  *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  72.  *  
  73.  *  See the License for the specific language governing permissions and
  74.  *      limitations under the License.
  75.  */

  76. /**
  77.  * <i>PathSimulator</i> drives the Simulation for various Latent States and Exposures. The References are:
  78.  *
  79.  *  <br><br>
  80.  *  <ul>
  81.  *      <li>
  82.  *          Albanese, C., and L. Andersen (2014): Accounting for OTC Derivatives: Funding Adjustments and the
  83.  *              Re-Hypothecation Option https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2482955
  84.  *              <b>eSSRN</b>
  85.  *      </li>
  86.  *      <li>
  87.  *          Burgard, C., and M. Kjaer (2014): PDE Representations of Derivatives with Bilateral Counter-party
  88.  *              Risk and Funding Costs <i>Journal of Credit Risk</i> <b>7 (3)</b> 1-19
  89.  *      </li>
  90.  *      <li>
  91.  *          Burgard, C., and M. Kjaer (2014): In the Balance <i>Risk</i> <b>24 (11)</b> 72-75
  92.  *      </li>
  93.  *      <li>
  94.  *          Burgard, C., and M. Kjaer (2017): Derivatives Funding, Netting, and Accounting
  95.  *              https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2534011 <b>eSSRN</b>
  96.  *      </li>
  97.  *      <li>
  98.  *          Piterbarg, V. (2010): Funding Beyond Discounting: Collateral Agreements and Derivatives Pricing
  99.  *              <i>Risk</i> <b>21 (2)</b> 97-102
  100.  *      </li>
  101.  *  </ul>
  102.  *
  103.  *  <br><br>
  104.  *  <ul>
  105.  *      <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/PortfolioCore.md">Portfolio Core Module</a></li>
  106.  *      <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/XVAAnalyticsLibrary.md">XVA Analytics Library</a></li>
  107.  *      <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/xva/README.md">Valuation Adjustments that account for Collateral, CC Credit/Debt and Funding Overhead</a></li>
  108.  *      <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/xva/dynamics/README.md">XVA Dynamics - Settings and Evolution</a></li>
  109.  *  </ul>
  110.  * <br><br>
  111.  *
  112.  * @author Lakshmi Krishnamurthy
  113.  */

  114. public class PathSimulator
  115. {
  116.     private int _iCount = -1;
  117.     private int _adjustmentDigestScheme = -1;
  118.     private org.drip.exposure.universe.MarketVertexGenerator _marketVertexGenerator = null;
  119.     private org.drip.exposure.holdings.PositionGroupContainer _positionGroupContainer = null;

  120.     private double[][] positionGroupValueArray (
  121.         final org.drip.exposure.universe.MarketPath marketPath)
  122.     {
  123.         org.drip.exposure.holdings.PositionGroup[] positionGroupArray =
  124.             _positionGroupContainer.positionGroupArray();

  125.         org.drip.analytics.date.JulianDate[] vertexDateArray = marketPath.anchorDates();

  126.         int vertexCount = vertexDateArray.length;
  127.         int positionGroupCount = positionGroupArray.length;
  128.         double[][] positionGroupValueArray = new double[positionGroupCount][vertexCount];

  129.         for (int positionGroupIndex = 0; positionGroupIndex < positionGroupCount; ++positionGroupIndex)
  130.         {
  131.             for (int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex)
  132.             {
  133.                 int forwardDate = vertexDateArray[vertexIndex].julian();

  134.                 try {
  135.                     positionGroupValueArray[positionGroupIndex][vertexIndex] =
  136.                         null == positionGroupArray[positionGroupIndex].positionGroupEstimator() ? 1. :
  137.                         positionGroupArray[positionGroupIndex].positionGroupEstimator().variationMarginEstimate (
  138.                             forwardDate,
  139.                             marketPath
  140.                         );
  141.                 }
  142.                 catch (java.lang.Exception e)
  143.                 {
  144.                     e.printStackTrace();

  145.                     return null;
  146.                 }
  147.             }
  148.         }

  149.         return positionGroupValueArray;
  150.     }

  151.     private boolean collateralGroupPathArray (
  152.         final org.drip.exposure.universe.MarketPath marketPath)
  153.     {
  154.         org.drip.xva.dynamics.PositionGroupTrajectory collateralGroup = null;

  155.         try
  156.         {
  157.             collateralGroup = new org.drip.xva.dynamics.PositionGroupTrajectory (
  158.                 _positionGroupContainer.positionGroupArray()[0].positionGroupSpecification().positionGroupSpecification(),
  159.                 marketPath,
  160.                 positionGroupValueArray (marketPath)
  161.             );
  162.         }
  163.         catch (java.lang.Exception e)
  164.         {
  165.             e.printStackTrace();

  166.             return false;
  167.         }

  168.         org.drip.xva.hypothecation.CollateralGroupVertex[][] collateralGroupVertexArray =
  169.             collateralGroup.positionGroupVertexArray();

  170.         if (null == collateralGroupVertexArray)
  171.         {
  172.             return false;
  173.         }

  174.         int positionGroupCount = collateralGroupVertexArray.length;

  175.         try
  176.         {
  177.             for (int positionGroupIndex = 0; positionGroupIndex < positionGroupCount; ++positionGroupIndex)
  178.             {
  179.                 if (!_positionGroupContainer.setCollateralGroupPath (
  180.                     positionGroupIndex,
  181.                     new org.drip.xva.netting.CollateralGroupPath (
  182.                         collateralGroupVertexArray[positionGroupIndex],
  183.                         marketPath
  184.                     )))
  185.                     return false;
  186.             }

  187.             return true;
  188.         }
  189.         catch (java.lang.Exception e)
  190.         {
  191.             e.printStackTrace();
  192.         }

  193.         return false;
  194.     }

  195.     /**
  196.      * Generate a PathSimulator Instance with the corresponding Position Group Value
  197.      *
  198.      * @param iPathCount Path Count
  199.      * @param marketVertexGenerator Market Vertex Generator
  200.      * @param positionGroupContainer Container of Position Groups
  201.      *
  202.      * @return The PathSimulator Instance
  203.      */

  204.     public static final PathSimulator UnitPositionGroupValue (
  205.         final int iPathCount,
  206.         final org.drip.exposure.universe.MarketVertexGenerator marketVertexGenerator,
  207.         final org.drip.exposure.holdings.PositionGroupContainer positionGroupContainer)
  208.     {
  209.         try
  210.         {
  211.             return new PathSimulator (
  212.                 iPathCount,
  213.                 marketVertexGenerator,
  214.                 org.drip.xva.settings.AdjustmentDigestScheme.ALBANESE_ANDERSEN_METRICS_POINTER,
  215.                 positionGroupContainer
  216.             );
  217.         }
  218.         catch (java.lang.Exception e)
  219.         {
  220.             e.printStackTrace();
  221.         }

  222.         return null;
  223.     }

  224.     /**
  225.      * PathSimulator Constructor
  226.      *
  227.      * @param iCount Path Count
  228.      * @param marketVertexGenerator Market Vertex Generator
  229.      * @param adjustmentDigestScheme Adjustment Digest Scheme
  230.      * @param positionGroupContainer Container of Position Groups
  231.      *
  232.      * @throws java.lang.Exception Thrown if the Inputs are Invalid
  233.      */

  234.     public PathSimulator (
  235.         final int iCount,
  236.         final org.drip.exposure.universe.MarketVertexGenerator marketVertexGenerator,
  237.         final int adjustmentDigestScheme,
  238.         final org.drip.exposure.holdings.PositionGroupContainer positionGroupContainer)
  239.         throws java.lang.Exception
  240.     {
  241.         if (0 >= (_iCount = iCount) ||
  242.             null == (_marketVertexGenerator = marketVertexGenerator) ||
  243.             null == (_positionGroupContainer = positionGroupContainer))
  244.         {
  245.             throw new java.lang.Exception ("PathSimulator Constructor => Invalid Inputs");
  246.         }

  247.         _adjustmentDigestScheme = adjustmentDigestScheme;
  248.     }

  249.     /**
  250.      * Retrieve the Path Count
  251.      *
  252.      * @return The Path Count
  253.      */

  254.     public int count()
  255.     {
  256.         return _iCount;
  257.     }

  258.     /**
  259.      * Retrieve the Market Vertex Generator
  260.      *
  261.      * @return The Market Vertex Generator
  262.      */

  263.     public org.drip.exposure.universe.MarketVertexGenerator marketVertexGenerator()
  264.     {
  265.         return _marketVertexGenerator;
  266.     }

  267.     /**
  268.      * Retrieve the Adjustment Digest Scheme
  269.      *
  270.      * @return The Adjustment Digest Scheme
  271.      */

  272.     public int adjustmentDigestScheme()
  273.     {
  274.         return _adjustmentDigestScheme;
  275.     }

  276.     /**
  277.      * Retrieve the Position Group Container
  278.      *
  279.      * @return Position Group Container
  280.      */

  281.     public org.drip.exposure.holdings.PositionGroupContainer positionGroupContainer()
  282.     {
  283.         return _positionGroupContainer;
  284.     }

  285.     /**
  286.      * Generate a Single Trajectory from the Specified Initial Market Vertex and the Evolver Sequence
  287.      *
  288.      * @param initialMarketVertex The Initial Market Vertex
  289.      * @param latentStateWeiner The Latent State Weiner Instance
  290.      *
  291.      * @return Single Trajectory Path Exposure Adjustment
  292.      */

  293.     public org.drip.xva.gross.PathExposureAdjustment singleTrajectory (
  294.         final org.drip.exposure.universe.MarketVertex initialMarketVertex,
  295.         final org.drip.exposure.universe.LatentStateWeiner latentStateWeiner)
  296.     {
  297.         try
  298.         {
  299.             org.drip.exposure.universe.MarketPath marketPath = new org.drip.exposure.universe.MarketPath (
  300.                 _marketVertexGenerator.marketVertex (
  301.                     initialMarketVertex,
  302.                     latentStateWeiner
  303.                 )
  304.             );

  305.             if (!collateralGroupPathArray (marketPath))
  306.             {
  307.                 return null;
  308.             }

  309.             org.drip.xva.netting.CollateralGroupPath[][] positionFundingGroupPath =
  310.                 _positionGroupContainer.fundingSegmentPaths();

  311.             org.drip.xva.netting.CollateralGroupPath[][] positionCreditDebtGroupPath =
  312.                 _positionGroupContainer.creditDebtSegmentPaths();

  313.             int positionFundingGroupCount = positionFundingGroupPath.length;
  314.             org.drip.xva.netting.FundingGroupPath[] fundingGroupPathArray = new
  315.                 org.drip.xva.strategy.AlbaneseAndersenFundingGroupPath[positionFundingGroupCount];

  316.             if (org.drip.xva.settings.AdjustmentDigestScheme.ALBANESE_ANDERSEN_METRICS_POINTER ==
  317.                 _adjustmentDigestScheme)
  318.             {
  319.                 int positionCreditDebtGroupCount = positionCreditDebtGroupPath.length;

  320.                 org.drip.xva.netting.CreditDebtGroupPath[] creditDebtGroupPathArray = new
  321.                     org.drip.xva.strategy.AlbaneseAndersenNettingGroupPath[positionCreditDebtGroupCount];

  322.                 for (int positionCreditDebtGroupIndex = 0; positionCreditDebtGroupIndex <
  323.                     positionCreditDebtGroupCount; ++positionCreditDebtGroupIndex)
  324.                 {
  325.                     creditDebtGroupPathArray[positionCreditDebtGroupIndex] =
  326.                         new org.drip.xva.strategy.AlbaneseAndersenNettingGroupPath (
  327.                             positionCreditDebtGroupPath[positionCreditDebtGroupIndex],
  328.                             marketPath
  329.                         );
  330.                 }

  331.                 for (int positionFundingGroupIndex = 0; positionFundingGroupIndex <
  332.                     positionFundingGroupCount; ++positionFundingGroupIndex)
  333.                 {
  334.                     fundingGroupPathArray[positionFundingGroupIndex] =
  335.                         new org.drip.xva.strategy.AlbaneseAndersenFundingGroupPath (
  336.                             creditDebtGroupPathArray,
  337.                             marketPath
  338.                         );
  339.                 }
  340.             }

  341.             return new org.drip.xva.gross.MonoPathExposureAdjustment (fundingGroupPathArray);
  342.         }
  343.         catch (java.lang.Exception e)
  344.         {
  345.             e.printStackTrace();
  346.         }

  347.         return null;
  348.     }

  349.     /**
  350.      * Simulate the Realized State/Entity Values and their Aggregates over the Paths
  351.      *
  352.      * @param latentStateLabelList Latent State Label List
  353.      * @param initialMarketVertex The Initial Market Vertex
  354.      * @param correlatedPathVertexDimension Path Vertex Dimension Generator
  355.      *
  356.      * @return The Exposure Adjustment Aggregator - Simulation Result
  357.      */

  358.     public org.drip.xva.gross.ExposureAdjustmentAggregator simulate (
  359.         final java.util.List<org.drip.state.identifier.LatentStateLabel> latentStateLabelList,
  360.         final org.drip.exposure.universe.MarketVertex initialMarketVertex,
  361.         final org.drip.measure.discrete.CorrelatedPathVertexDimension correlatedPathVertexDimension)
  362.     {
  363.         if (null == correlatedPathVertexDimension)
  364.         {
  365.             return null;
  366.         }

  367.         org.drip.xva.gross.PathExposureAdjustment[] pathExposureAdjustmentArray = new
  368.             org.drip.xva.gross.PathExposureAdjustment[_iCount];

  369.         for (int pathIndex = 0; pathIndex < _iCount; ++pathIndex)
  370.         {
  371.             if (null == (pathExposureAdjustmentArray[pathIndex] = singleTrajectory (
  372.                 initialMarketVertex,
  373.                 org.drip.exposure.universe.LatentStateWeiner.FromUnitRandom (
  374.                     latentStateLabelList,
  375.                     org.drip.numerical.linearalgebra.Matrix.Transpose
  376.                         (org.drip.numerical.linearalgebra.Matrix.Transpose
  377.                         (correlatedPathVertexDimension.straightPathVertexRd().flatform()))))))
  378.             {
  379.                 return null;
  380.             }
  381.         }

  382.         try
  383.         {
  384.             return new org.drip.xva.gross.ExposureAdjustmentAggregator (pathExposureAdjustmentArray);
  385.         }
  386.         catch (java.lang.Exception e)
  387.         {
  388.             e.printStackTrace();
  389.         }

  390.         return null;
  391.     }
  392. }