CPGAUncollateralized.java

  1. package org.drip.sample.xvadigest;

  2. import org.drip.analytics.date.*;
  3. import org.drip.exposure.evolver.LatentStateVertexContainer;
  4. import org.drip.exposure.universe.*;
  5. import org.drip.measure.discrete.SequenceGenerator;
  6. import org.drip.measure.dynamics.DiffusionEvaluatorLinear;
  7. import org.drip.measure.process.DiffusionEvolver;
  8. import org.drip.measure.realization.*;
  9. import org.drip.measure.statistics.UnivariateDiscreteThin;
  10. import org.drip.numerical.common.FormatUtil;
  11. import org.drip.service.env.EnvManager;
  12. import org.drip.state.identifier.OTCFixFloatLabel;
  13. import org.drip.xva.gross.*;
  14. import org.drip.xva.netting.CollateralGroupPath;
  15. import org.drip.xva.strategy.*;
  16. import org.drip.xva.vertex.AlbaneseAndersen;

  17. /*
  18.  * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  19.  */

  20. /*!
  21.  * Copyright (C) 2018 Lakshmi Krishnamurthy
  22.  * Copyright (C) 2017 Lakshmi Krishnamurthy
  23.  *
  24.  *  This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
  25.  *      libraries targeting analysts and developers
  26.  *      https://lakshmidrip.github.io/DRIP/
  27.  *  
  28.  *  DRIP is composed of four main libraries:
  29.  *  
  30.  *  - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
  31.  *  - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
  32.  *  - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
  33.  *  - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
  34.  *
  35.  *  - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
  36.  *      Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
  37.  *      Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
  38.  *      Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
  39.  *      Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
  40.  *
  41.  *  - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
  42.  *      Incorporator, Holdings Constraint, and Transaction Costs.
  43.  *
  44.  *  - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
  45.  *
  46.  *  - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
  47.  *
  48.  *  Licensed under the Apache License, Version 2.0 (the "License");
  49.  *      you may not use this file except in compliance with the License.
  50.  *  
  51.  *  You may obtain a copy of the License at
  52.  *      http://www.apache.org/licenses/LICENSE-2.0
  53.  *  
  54.  *  Unless required by applicable law or agreed to in writing, software
  55.  *      distributed under the License is distributed on an "AS IS" BASIS,
  56.  *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  57.  *  
  58.  *  See the License for the specific language governing permissions and
  59.  *      limitations under the License.
  60.  */

  61. /**
  62.  * CPGAUncollateralized illustrates the Counter Party Aggregation over Netting Groups based Uncollateralized
  63.  *  Collateral Groups with several Fix-Float Swaps. The References are:
  64.  *  
  65.  *  - Burgard, C., and M. Kjaer (2014): PDE Representations of Derivatives with Bilateral Counter-party Risk
  66.  *      and Funding Costs, Journal of Credit Risk, 7 (3) 1-19.
  67.  *  
  68.  *  - Burgard, C., and M. Kjaer (2014): In the Balance, Risk, 24 (11) 72-75.
  69.  *  
  70.  *  - Gregory, J. (2009): Being Two-faced over Counter-party Credit Risk, Risk 20 (2) 86-90.
  71.  *  
  72.  *  - Li, B., and Y. Tang (2007): Quantitative Analysis, Derivatives Modeling, and Trading Strategies in the
  73.  *      Presence of Counter-party Credit Risk for the Fixed Income Market, World Scientific Publishing,
  74.  *      Singapore.
  75.  *
  76.  *  - Piterbarg, V. (2010): Funding Beyond Discounting: Collateral Agreements and Derivatives Pricing, Risk
  77.  *      21 (2) 97-102.
  78.  *
  79.  * @author Lakshmi Krishnamurthy
  80.  */

  81. public class CPGAUncollateralized {

  82.     private static final double[] ATMSwapRateOffsetRealization (
  83.         final DiffusionEvolver deATMSwapRateOffset,
  84.         final double dblATMSwapRateOffsetInitial,
  85.         final double dblTime,
  86.         final double dblTimeWidth,
  87.         final int iNumStep)
  88.         throws Exception
  89.     {
  90.         double[] adblATMSwapRateOffset = new double[iNumStep + 1];
  91.         adblATMSwapRateOffset[0] = dblATMSwapRateOffsetInitial;
  92.         double[] adblTimeWidth = new double[iNumStep];

  93.         for (int i = 0; i < iNumStep; ++i)
  94.             adblTimeWidth[i] = dblTimeWidth;

  95.         JumpDiffusionEdge[] aJDE = deATMSwapRateOffset.incrementSequence (
  96.             new JumpDiffusionVertex (
  97.                 dblTime,
  98.                 dblATMSwapRateOffsetInitial,
  99.                 0.,
  100.                 false
  101.             ),
  102.             JumpDiffusionEdgeUnit.Diffusion (
  103.                 adblTimeWidth,
  104.                 SequenceGenerator.Gaussian (iNumStep)
  105.             ),
  106.             dblTimeWidth
  107.         );

  108.         for (int j = 1; j <= iNumStep; ++j)
  109.             adblATMSwapRateOffset[j] = aJDE[j - 1].finish();

  110.         return adblATMSwapRateOffset;
  111.     }

  112.     private static final double[] SwapPortfolioValueRealization (
  113.         final DiffusionEvolver deATMSwapRate,
  114.         final double dblATMSwapRateStart,
  115.         final int iNumStep,
  116.         final double dblTime,
  117.         final double dblTimeWidth,
  118.         final int iNumSwap)
  119.         throws Exception
  120.     {
  121.         double[] adblSwapPortfolioValueRealization = new double[iNumStep + 1];

  122.         for (int i = 0; i < iNumStep; ++i)
  123.             adblSwapPortfolioValueRealization[i] = 0.;

  124.         for (int i = 0; i < iNumSwap; ++i) {
  125.             double[] adblATMSwapRateOffsetRealization = ATMSwapRateOffsetRealization (
  126.                 deATMSwapRate,
  127.                 dblATMSwapRateStart,
  128.                 dblTime,
  129.                 dblTimeWidth,
  130.                 iNumStep
  131.             );

  132.             for (int j = 0; j <= iNumStep; ++j)
  133.                 adblSwapPortfolioValueRealization[j] += dblTimeWidth * (iNumStep - j) * adblATMSwapRateOffsetRealization[j];
  134.         }

  135.         return adblSwapPortfolioValueRealization;
  136.     }

  137.     private static final double[][] SwapPortfolioValueRealization (
  138.         final DiffusionEvolver deATMSwapRate,
  139.         final double dblSwapPortfolioValueStart,
  140.         final int iNumStep,
  141.         final double dblTime,
  142.         final double dblTimeWidth,
  143.         final int iNumSwap,
  144.         final int iNumSimulation)
  145.         throws Exception
  146.     {
  147.         double[][] aadblSwapPortfolioValueRealization = new double[iNumSimulation][];

  148.         for (int i = 0; i < iNumSimulation; ++i)
  149.             aadblSwapPortfolioValueRealization[i] = SwapPortfolioValueRealization (
  150.                 deATMSwapRate,
  151.                 dblSwapPortfolioValueStart,
  152.                 iNumStep,
  153.                 dblTime,
  154.                 dblTimeWidth,
  155.                 iNumSwap
  156.             );

  157.         return aadblSwapPortfolioValueRealization;
  158.     }

  159.     private static final void UDTDump (
  160.         final String strHeader,
  161.         final JulianDate[] adtVertexNode,
  162.         final UnivariateDiscreteThin[] aUDT)
  163.         throws Exception
  164.     {
  165.         System.out.println ("\t|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|");

  166.         System.out.println (strHeader);

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

  168.         String strDump = "\t|       DATE      =>" ;

  169.         for (int i = 0; i < adtVertexNode.length; ++i)
  170.             strDump = strDump + " " + adtVertexNode[i] + "  |";

  171.         System.out.println (strDump);

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

  173.          strDump = "\t|     AVERAGE     =>";

  174.         for (int j = 0; j < aUDT.length; ++j)
  175.             strDump = strDump + "   " + FormatUtil.FormatDouble (aUDT[j].average(), 2, 4, 1.) + "   |";

  176.         System.out.println (strDump);

  177.         strDump = "\t|     MAXIMUM     =>";

  178.         for (int j = 0; j < aUDT.length; ++j)
  179.             strDump = strDump + "   " + FormatUtil.FormatDouble (aUDT[j].maximum(), 2, 4, 1.) + "   |";

  180.         System.out.println (strDump);

  181.         strDump = "\t|     MINIMUM     =>";

  182.         for (int j = 0; j < aUDT.length; ++j)
  183.             strDump = strDump + "   " + FormatUtil.FormatDouble (aUDT[j].minimum(), 2, 4, 1.) + "   |";

  184.         System.out.println (strDump);

  185.         strDump = "\t|      ERROR      =>";

  186.         for (int j = 0; j < aUDT.length; ++j)
  187.             strDump = strDump + "   " + FormatUtil.FormatDouble (aUDT[j].error(), 2, 4, 1.) + "   |";

  188.         System.out.println (strDump);

  189.         System.out.println ("\t|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|");
  190.     }

  191.     private static final void UDTDump (
  192.         final String strHeader,
  193.         final UnivariateDiscreteThin udt)
  194.         throws Exception
  195.     {
  196.         System.out.println (
  197.             strHeader +
  198.             FormatUtil.FormatDouble (udt.average(), 3, 2, 100.) + "% | " +
  199.             FormatUtil.FormatDouble (udt.maximum(), 3, 2, 100.) + "% | " +
  200.             FormatUtil.FormatDouble (udt.minimum(), 3, 2, 100.) + "% | " +
  201.             FormatUtil.FormatDouble (udt.error(), 3, 2, 100.) + "% ||"
  202.         );
  203.     }

  204.     public static final void main (
  205.         final String[] astrArgs)
  206.         throws Exception
  207.     {
  208.         EnvManager.InitEnv ("");

  209.         int iNumStep = 10;
  210.         int iNumSwap = 10;
  211.         double dblTime = 5.;
  212.         int iNumPath = 10000;
  213.         double dblATMSwapRateStart = 0.;
  214.         double dblATMSwapRateDrift = 0.;
  215.         double dblATMSwapRateVolatility = 0.25;
  216.         double dblOvernightNumeraireDrift = 0.01;
  217.         double dblCSADrift = 0.01;
  218.         double dblBankHazardRate = 0.015;
  219.         double dblBankRecoveryRate = 0.40;
  220.         double dblCounterPartyHazardRate = 0.030;
  221.         double dblCounterPartyRecoveryRate = 0.30;

  222.         JulianDate dtSpot = DateUtil.Today();

  223.         double dblTimeWidth = dblTime / iNumStep;
  224.         MarketVertex[] aMV = new MarketVertex[iNumStep + 1];
  225.         JulianDate[] adtVertex = new JulianDate[iNumStep + 1];
  226.         double[][] aadblCollateralBalance = new double[iNumPath][iNumStep + 1];
  227.         double dblBankFundingSpread = dblBankHazardRate / (1. - dblBankRecoveryRate);
  228.         MonoPathExposureAdjustment[] aMPEA = new MonoPathExposureAdjustment[iNumPath];
  229.         double dblCounterPartyFundingSpread = dblCounterPartyHazardRate / (1. - dblCounterPartyRecoveryRate);

  230.         double[][] aadblSwapPortfolioValueRealization = SwapPortfolioValueRealization (
  231.             new DiffusionEvolver (
  232.                 DiffusionEvaluatorLinear.Standard (
  233.                     dblATMSwapRateDrift,
  234.                     dblATMSwapRateVolatility
  235.                 )
  236.             ),
  237.             dblATMSwapRateStart,
  238.             iNumStep,
  239.             dblTime,
  240.             dblTimeWidth,
  241.             iNumSwap,
  242.             iNumPath
  243.         );

  244.         for (int i = 0; i <= iNumStep; ++i)
  245.         {
  246.             LatentStateVertexContainer latentStateVertexContainer = new LatentStateVertexContainer();

  247.             latentStateVertexContainer.add (
  248.                 OTCFixFloatLabel.Standard ("USD-3M-10Y"),
  249.                 Double.NaN
  250.             );

  251.             aMV[i] = MarketVertex.Nodal (
  252.                 adtVertex[i] = dtSpot.addMonths (6 * i),
  253.                 dblOvernightNumeraireDrift,
  254.                 Math.exp (-0.5 * dblOvernightNumeraireDrift * (iNumStep - i)),
  255.                 dblCSADrift,
  256.                 Math.exp (-0.5 * dblCSADrift * (iNumStep - i)),
  257.                 new MarketVertexEntity (
  258.                     Math.exp (-0.5 * dblBankHazardRate * i),
  259.                     dblBankHazardRate,
  260.                     dblBankRecoveryRate,
  261.                     dblBankFundingSpread,
  262.                     Math.exp (-0.5 * dblBankHazardRate * (1. - dblBankRecoveryRate) * (iNumStep - i)),
  263.                     Double.NaN,
  264.                     Double.NaN,
  265.                     Double.NaN
  266.                 ),
  267.                 new MarketVertexEntity (
  268.                     Math.exp (-0.5 * dblCounterPartyHazardRate * i),
  269.                     dblCounterPartyHazardRate,
  270.                     dblCounterPartyRecoveryRate,
  271.                     dblCounterPartyFundingSpread,
  272.                     Math.exp (-0.5 * dblCounterPartyHazardRate * (1. - dblCounterPartyRecoveryRate) * (iNumStep - i)),
  273.                     Double.NaN,
  274.                     Double.NaN,
  275.                     Double.NaN
  276.                 ),
  277.                 latentStateVertexContainer
  278.             );
  279.         }

  280.         MarketPath mp = MarketPath.FromMarketVertexArray (aMV);

  281.         for (int i = 0; i < iNumPath; ++i) {
  282.             AlbaneseAndersen[] aHGVR = new AlbaneseAndersen[iNumStep + 1];

  283.             for (int j = 0; j <= iNumStep; ++j) {
  284.                 aadblCollateralBalance[i][j] = 0.;

  285.                 aHGVR[j] = new AlbaneseAndersen (
  286.                     adtVertex[j],
  287.                     aadblSwapPortfolioValueRealization[i][j],
  288.                     0.,
  289.                     aadblCollateralBalance[i][j]
  290.                 );
  291.             }

  292.             CollateralGroupPath[] aHGP = new CollateralGroupPath[] {
  293.                 new CollateralGroupPath (
  294.                     aHGVR,
  295.                     mp
  296.                 )
  297.             };

  298.             aMPEA[i] = new MonoPathExposureAdjustment (
  299.                 new AlbaneseAndersenFundingGroupPath[] {
  300.                     new AlbaneseAndersenFundingGroupPath (
  301.                         new AlbaneseAndersenNettingGroupPath[] {
  302.                             new AlbaneseAndersenNettingGroupPath (
  303.                                 aHGP,
  304.                                 mp
  305.                             )
  306.                         },
  307.                         mp
  308.                     )
  309.                 }
  310.             );
  311.         }

  312.         ExposureAdjustmentAggregator eaa = new ExposureAdjustmentAggregator (aMPEA);

  313.         ExposureAdjustmentDigest ead = eaa.digest();

  314.         System.out.println();

  315.         UDTDump (
  316.             "\t|                                                                                COLLATERALIZED EXPOSURE                                                                                |",
  317.             eaa.vertexDates(),
  318.             ead.collateralizedExposure()
  319.         );

  320.         UDTDump (
  321.             "\t|                                                                               UNCOLLATERALIZED EXPOSURE                                                                               |",
  322.             eaa.vertexDates(),
  323.             ead.uncollateralizedExposure()
  324.         );

  325.         UDTDump (
  326.             "\t|                                                                                COLLATERALIZED EXPOSURE PV                                                                             |",
  327.             eaa.vertexDates(),
  328.             ead.collateralizedExposurePV()
  329.         );

  330.         UDTDump (
  331.             "\t|                                                                               UNCOLLATERALIZED EXPOSURE PV                                                                            |",
  332.             eaa.vertexDates(),
  333.             ead.uncollateralizedExposurePV()
  334.         );

  335.         UDTDump (
  336.             "\t|                                                                            COLLATERALIZED POSITIVE EXPOSURE PV                                                                        |",
  337.             eaa.vertexDates(),
  338.             ead.collateralizedPositiveExposure()
  339.         );

  340.         UDTDump (
  341.             "\t|                                                                           UNCOLLATERALIZED POSITIVE EXPOSURE PV                                                                       |",
  342.             eaa.vertexDates(),
  343.             ead.uncollateralizedPositiveExposure()
  344.         );

  345.         UDTDump (
  346.             "\t|                                                                            COLLATERALIZED NEGATIVE EXPOSURE PV                                                                        |",
  347.             eaa.vertexDates(),
  348.             ead.collateralizedNegativeExposure()
  349.         );

  350.         UDTDump (
  351.             "\t|                                                                           UNCOLLATERALIZED NEGATIVE EXPOSURE PV                                                                       |",
  352.             eaa.vertexDates(),
  353.             ead.uncollateralizedNegativeExposure()
  354.         );

  355.         System.out.println();

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

  357.         System.out.println ("\t||  UCVA CVA FTDCVA DVA FCA UNIVARIATE THIN STATISTICS ||");

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

  359.         System.out.println ("\t||    L -> R:                                          ||");

  360.         System.out.println ("\t||            - Path Average                           ||");

  361.         System.out.println ("\t||            - Path Maximum                           ||");

  362.         System.out.println ("\t||            - Path Minimum                           ||");

  363.         System.out.println ("\t||            - Monte Carlo Error                      ||");

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

  365.         UDTDump (
  366.             "\t||  UCVA  => ",
  367.             ead.ucva()
  368.         );

  369.         UDTDump (
  370.             "\t|| FTDCVA => ",
  371.             ead.ftdcva()
  372.         );

  373.         UDTDump (
  374.             "\t||   CVA  => ",
  375.             ead.cva()
  376.         );

  377.         UDTDump (
  378.             "\t||  CVACL => ",
  379.             ead.cvacl()
  380.         );

  381.         UDTDump (
  382.             "\t||   DVA  => ",
  383.             ead.dva()
  384.         );

  385.         UDTDump (
  386.             "\t||   FVA  => ",
  387.             ead.fva()
  388.         );

  389.         UDTDump (
  390.             "\t||   FDA  => ",
  391.             ead.fda()
  392.         );

  393.         UDTDump (
  394.             "\t||   FCA  => ",
  395.             ead.fca()
  396.         );

  397.         UDTDump (
  398.             "\t||   FBA  => ",
  399.             ead.fba()
  400.         );

  401.         UDTDump (
  402.             "\t||  SFVA  => ",
  403.             ead.sfva()
  404.         );

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

  406.         UDTDump (
  407.             "\t||  Total => ",
  408.             ead.totalVA()
  409.         );

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

  411.         System.out.println();

  412.         EnvManager.TerminateEnv();
  413.     }
  414. }