ExponentialAndersonDarlingGapAnalysis.java

  1. package org.drip.sample.distancetest;

  2. import org.drip.measure.continuous.R1UnivariateExponential;
  3. import org.drip.numerical.common.FormatUtil;
  4. import org.drip.service.env.EnvManager;
  5. import org.drip.validation.distance.GapTestOutcome;
  6. import org.drip.validation.distance.GapTestSetting;
  7. import org.drip.validation.distance.GapLossWeightFunction;
  8. import org.drip.validation.evidence.Ensemble;
  9. import org.drip.validation.evidence.Sample;
  10. import org.drip.validation.evidence.TestStatisticEvaluator;
  11. import org.drip.validation.hypothesis.HistogramTestOutcome;
  12. import org.drip.validation.hypothesis.HistogramTestSetting;
  13. import org.drip.validation.hypothesis.ProbabilityIntegralTransformTest;
  14. import org.drip.validation.quantile.PlottingPositionGenerator;
  15. import org.drip.validation.quantile.PlottingPositionGeneratorHeuristic;

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

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

  88. /**
  89.  * <i>ExponentialAndersonDarlingGapAnalysis</i> demonstrates the Generation of the Sample Distance Metrics
  90.  * for Different Ensemble Hypotheses.
  91.  *
  92.  *  <br><br>
  93.  *  <ul>
  94.  *      <li>
  95.  *          <b>Reference Distribution  </b> - <i>Univariate Exponential</i>
  96.  *      </li>
  97.  *      <li>
  98.  *          <b>Gap Loss Function       </b> - <i>Anfuso, Karyampas, and Nawroth (2017)</i>
  99.  *      </li>
  100.  *      <li>
  101.  *          <b>Gap Loss Weight Function</b> - <i>Anderson and Darling</i>
  102.  *      </li>
  103.  *  </ul>
  104.  *
  105.  *  <br><br>
  106.  *  <ul>
  107.  *      <li>
  108.  *          Anfuso, F., D. Karyampas, and A. Nawroth (2017): A Sound Basel III Compliant Framework for
  109.  *              Back-testing Credit Exposure Models
  110.  *              https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2264620 <b>eSSRN</b>
  111.  *      </li>
  112.  *      <li>
  113.  *          Diebold, F. X., T. A. Gunther, and A. S. Tay (1998): Evaluating Density Forecasts with
  114.  *              Applications to Financial Risk Management, International Economic Review 39 (4) 863-883
  115.  *      </li>
  116.  *      <li>
  117.  *          Kenyon, C., and R. Stamm (2012): Discounting, LIBOR, CVA, and Funding: Interest Rate and Credit
  118.  *              Pricing, Palgrave Macmillan
  119.  *      </li>
  120.  *      <li>
  121.  *          Wikipedia (2018): Probability Integral Transform
  122.  *              https://en.wikipedia.org/wiki/Probability_integral_transform
  123.  *      </li>
  124.  *      <li>
  125.  *          Wikipedia (2019): p-value https://en.wikipedia.org/wiki/P-value
  126.  *      </li>
  127.  *  </ul>
  128.  *
  129.  *  <br><br>
  130.  *  <ul>
  131.  *      <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ComputationalCore.md">Computational Core Module</a></li>
  132.  *      <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ModelValidationAnalyticsLibrary.md">Model Validation Analytics Library</a></li>
  133.  *      <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/sample/README.md">DROP API Construction and Usage</a></li>
  134.  *      <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/sample/validation">Empirical Univariate Gap Distance Tests</a></li>
  135.  *  </ul>
  136.  * <br><br>
  137.  *
  138.  * @author Lakshmi Krishnamurthy
  139.  */

  140. public class ExponentialAndersonDarlingGapAnalysis
  141. {

  142.     private static final double UnivariateRandom (
  143.         final double lambda)
  144.         throws Exception
  145.     {
  146.         return new R1UnivariateExponential (lambda).random();
  147.     }

  148.     private static final Sample GenerateSample (
  149.         final double lambda,
  150.         final int drawCount)
  151.         throws Exception
  152.     {
  153.         double[] univariateRandomArray = new double[drawCount];

  154.         for (int drawIndex = 0; drawIndex < drawCount; ++drawIndex)
  155.         {
  156.             univariateRandomArray[drawIndex] = UnivariateRandom (lambda);
  157.         }

  158.         return new Sample (univariateRandomArray);
  159.     }

  160.     private static final Sample[] GenerateSampleArray (
  161.         final double lambda,
  162.         final int drawCount,
  163.         final int sampleCount)
  164.         throws Exception
  165.     {
  166.         Sample[] sampleArray = new Sample[sampleCount];

  167.         for (int sampleIndex = 0; sampleIndex < sampleCount; ++sampleIndex)
  168.         {
  169.             sampleArray[sampleIndex] = GenerateSample (
  170.                 lambda,
  171.                 drawCount
  172.             );
  173.         }

  174.         return sampleArray;
  175.     }

  176.     private static final Ensemble GenerateEnsemble (
  177.         final double lambda,
  178.         final int drawCount,
  179.         final int sampleCount)
  180.         throws Exception
  181.     {
  182.         return new Ensemble (
  183.             GenerateSampleArray (
  184.                 lambda,
  185.                 drawCount,
  186.                 sampleCount
  187.             ),
  188.             new TestStatisticEvaluator[]
  189.             {
  190.                 new TestStatisticEvaluator()
  191.                 {
  192.                     public double evaluate (
  193.                         final double[] drawArray)
  194.                         throws Exception
  195.                     {
  196.                         return 1.;
  197.                     }
  198.                 }
  199.             }
  200.         );
  201.     }

  202.     private static final GapTestOutcome DistanceTest (
  203.         final Sample sample,
  204.         final Ensemble ensemble,
  205.         final GapTestSetting gapTestSetting)
  206.         throws Exception
  207.     {
  208.         return new ProbabilityIntegralTransformTest (
  209.             ensemble.nativeProbabilityIntegralTransform()
  210.         ).distanceTest (
  211.             sample.nativeProbabilityIntegralTransform(),
  212.             gapTestSetting
  213.         );
  214.     }

  215.     private static final void DistanceTest (
  216.         final double hypothesisLambda,
  217.         final int drawCount,
  218.         final int sampleCount,
  219.         final Sample sample,
  220.         final GapTestSetting gapTestSetting,
  221.         final PlottingPositionGenerator plottingPositionGenerator)
  222.         throws Exception
  223.     {
  224.         Ensemble hypothesis = GenerateEnsemble (
  225.             hypothesisLambda,
  226.             drawCount,
  227.             sampleCount
  228.         );

  229.         GapTestOutcome gapTestOutcome = DistanceTest (
  230.             sample,
  231.             hypothesis,
  232.             gapTestSetting
  233.         );

  234.         HistogramTestOutcome histogram = new ProbabilityIntegralTransformTest (
  235.             gapTestOutcome.probabilityIntegralTransformWeighted()
  236.         ).histogramTest (
  237.             HistogramTestSetting.AnfusoKaryampasNawroth2017 (
  238.                 plottingPositionGenerator
  239.             )
  240.         );

  241.         double[] pValueIncrementalArray = histogram.pValueIncrementalArray();

  242.         double[] pValueCumulativeArray = histogram.pValueCumulativeArray();

  243.         double thresholdTestStatistic = histogram.thresholdTestStatistic();

  244.         double[] gapArray = histogram.testStatisticArray();

  245.         double distance = gapTestOutcome.distance();

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

  247.         System.out.println ("\t|         Exponential Anfuso Karyampas Nawroth Distance Test         ||");

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

  249.         System.out.println (
  250.             "\t|   Lambda => [" + FormatUtil.FormatDouble (hypothesisLambda, 1, 8, 1.) +
  251.             "]                                          ||"
  252.         );


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

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

  255.         System.out.println ("\t|        - Weighted Distance Metric                                  ||");

  256.         System.out.println ("\t|        - Cumulative p-Value                                        ||");

  257.         System.out.println ("\t|        - Incremental p-Value                                       ||");

  258.         System.out.println ("\t|        - Ensemble Weighted Distance                                ||");

  259.         System.out.println ("\t|        - p-Value Threshold Distance                                ||");

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

  261.         for (int histogramIndex = 0;
  262.             histogramIndex <= plottingPositionGenerator.orderStatisticCount() + 1;
  263.             ++histogramIndex)
  264.         {
  265.             System.out.println (
  266.                 "\t|" +
  267.                 FormatUtil.FormatDouble (gapArray[histogramIndex], 1, 8, 1.) + " | " +
  268.                 FormatUtil.FormatDouble (pValueCumulativeArray[histogramIndex], 1, 8, 1.) + " | " +
  269.                 FormatUtil.FormatDouble (pValueIncrementalArray[histogramIndex], 1, 8, 1.) + " | " +
  270.                 FormatUtil.FormatDouble (distance, 1, 8, 1.) + " | " +
  271.                 FormatUtil.FormatDouble (thresholdTestStatistic, 1, 8, 1.) + " ||"
  272.             );
  273.         }

  274.         System.out.println ("\t|--------------------------------------------------------------------||");
  275.     }

  276.     public static final void main (
  277.         final String[] argumentArray)
  278.         throws Exception
  279.     {
  280.         EnvManager.InitEnv ("");

  281.         int drawCount = 2000;
  282.         int sampleCount = 600;
  283.         double sampleLambda = 1.;
  284.         int orderStatisticsCount = 20;
  285.         double[] hypothesisLambdaArray =
  286.         {
  287.             0.20,
  288.             0.30,
  289.             0.40,
  290.             0.50,
  291.             0.60,
  292.             0.70,
  293.             0.80,
  294.             0.90,
  295.             1.00,
  296.             1.10,
  297.             1.20,
  298.             1.30,
  299.             1.40,
  300.             1.50,
  301.             1.60,
  302.             1.70,
  303.             1.80,
  304.             1.90,
  305.             2.00,
  306.             2.10,
  307.             2.20,
  308.             2.30,
  309.             2.40,
  310.             2.50
  311.         };

  312.         GapTestSetting gapTestSetting = GapTestSetting.RiskFactorLossTest (
  313.             GapLossWeightFunction.AndersonDarling()
  314.         );

  315.         Sample sample = GenerateSample (
  316.             sampleLambda,
  317.             drawCount
  318.         );

  319.         for (double hypothesisLambda : hypothesisLambdaArray)
  320.         {
  321.             DistanceTest (
  322.                 hypothesisLambda,
  323.                 drawCount,
  324.                 sampleCount,
  325.                 sample,
  326.                 gapTestSetting,
  327.                 PlottingPositionGeneratorHeuristic.NIST2013 (orderStatisticsCount)
  328.             );
  329.         }

  330.         EnvManager.TerminateEnv();
  331.     }
  332. }