UniformCramersVonMisesGapAnalysis.java

  1. package org.drip.sample.distancetest;

  2. import org.drip.measure.continuous.R1UnivariateUniform;
  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>UniformCramersVonMisesGapAnalysis</i> demonstrates the Generation of the Sample Distance Metrics for
  90.  * Different Ensemble Hypotheses.
  91.  *
  92.  *  <br><br>
  93.  *  <ul>
  94.  *      <li>
  95.  *          <b>Reference Distribution  </b> - <i>Univariate Uniform</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>Cramers and von Mises</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 UniformCramersVonMisesGapAnalysis
  141. {

  142.     private static final double UnivariateRandom (
  143.         final double leftSupport,
  144.         final double rightSupport)
  145.         throws Exception
  146.     {
  147.         return new R1UnivariateUniform (
  148.             leftSupport,
  149.             rightSupport
  150.         ).random();
  151.     }

  152.     private static final Sample GenerateSample (
  153.         final double leftSupport,
  154.         final double rightSupport,
  155.         final int drawCount)
  156.         throws Exception
  157.     {
  158.         double[] univariateRandomArray = new double[drawCount];

  159.         for (int drawIndex = 0; drawIndex < drawCount; ++drawIndex)
  160.         {
  161.             univariateRandomArray[drawIndex] = UnivariateRandom (
  162.                 leftSupport,
  163.                 rightSupport
  164.             );
  165.         }

  166.         return new Sample (univariateRandomArray);
  167.     }

  168.     private static final Sample[] GenerateSampleArray (
  169.         final double leftSupport,
  170.         final double rightSupport,
  171.         final int drawCount,
  172.         final int sampleCount)
  173.         throws Exception
  174.     {
  175.         Sample[] sampleArray = new Sample[sampleCount];

  176.         for (int sampleIndex = 0; sampleIndex < sampleCount; ++sampleIndex)
  177.         {
  178.             sampleArray[sampleIndex] = GenerateSample (
  179.                 leftSupport,
  180.                 rightSupport,
  181.                 drawCount
  182.             );
  183.         }

  184.         return sampleArray;
  185.     }

  186.     private static final Ensemble GenerateEnsemble (
  187.         final double leftSupport,
  188.         final double rightSupport,
  189.         final int drawCount,
  190.         final int sampleCount)
  191.         throws Exception
  192.     {
  193.         return new Ensemble (
  194.             GenerateSampleArray (
  195.                 leftSupport,
  196.                 rightSupport,
  197.                 drawCount,
  198.                 sampleCount
  199.             ),
  200.             new TestStatisticEvaluator[]
  201.             {
  202.                 new TestStatisticEvaluator()
  203.                 {
  204.                     public double evaluate (
  205.                         final double[] drawArray)
  206.                         throws Exception
  207.                     {
  208.                         return 1.;
  209.                     }
  210.                 }
  211.             }
  212.         );
  213.     }

  214.     private static final GapTestOutcome DistanceTest (
  215.         final Sample sample,
  216.         final Ensemble ensemble,
  217.         final GapTestSetting gapTestSetting)
  218.         throws Exception
  219.     {
  220.         return new ProbabilityIntegralTransformTest (
  221.             ensemble.nativeProbabilityIntegralTransform()
  222.         ).distanceTest (
  223.             sample.nativeProbabilityIntegralTransform(),
  224.             gapTestSetting
  225.         );
  226.     }

  227.     private static final void DistanceTest (
  228.         final double hypothesisLeftSupport,
  229.         final double hypothesisRightSupport,
  230.         final int drawCount,
  231.         final int sampleCount,
  232.         final Sample sample,
  233.         final GapTestSetting gapTestSetting,
  234.         final PlottingPositionGenerator plottingPositionGenerator)
  235.         throws Exception
  236.     {
  237.         Ensemble hypothesis = GenerateEnsemble (
  238.             hypothesisLeftSupport,
  239.             hypothesisRightSupport,
  240.             drawCount,
  241.             sampleCount
  242.         );

  243.         GapTestOutcome gapTestOutcome = DistanceTest (
  244.             sample,
  245.             hypothesis,
  246.             gapTestSetting
  247.         );

  248.         HistogramTestOutcome histogram = new ProbabilityIntegralTransformTest (
  249.             gapTestOutcome.probabilityIntegralTransformWeighted()
  250.         ).histogramTest (
  251.             HistogramTestSetting.AnfusoKaryampasNawroth2017 (
  252.                 plottingPositionGenerator
  253.             )
  254.         );

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

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

  257.         double thresholdTestStatistic = histogram.thresholdTestStatistic();

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

  259.         double distance = gapTestOutcome.distance();

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

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

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

  263.         System.out.println (
  264.             "\t|    Left => [" + FormatUtil.FormatDouble (hypothesisLeftSupport, 1, 8, 1.) +
  265.             "]  |  Right => [" + FormatUtil.FormatDouble (hypothesisRightSupport, 1, 8, 1.) + "]                ||"
  266.         );

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

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

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

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

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

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

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

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

  275.         for (int histogramIndex = 0;
  276.             histogramIndex <= plottingPositionGenerator.orderStatisticCount() + 1;
  277.             ++histogramIndex)
  278.         {
  279.             System.out.println (
  280.                 "\t|" +
  281.                 FormatUtil.FormatDouble (gapArray[histogramIndex], 1, 8, 1.) + " | " +
  282.                 FormatUtil.FormatDouble (pValueCumulativeArray[histogramIndex], 1, 8, 1.) + " | " +
  283.                 FormatUtil.FormatDouble (pValueIncrementalArray[histogramIndex], 1, 8, 1.) + " | " +
  284.                 FormatUtil.FormatDouble (distance, 1, 8, 1.) + " | " +
  285.                 FormatUtil.FormatDouble (thresholdTestStatistic, 1, 8, 1.) + " ||"
  286.             );
  287.         }

  288.         System.out.println ("\t|--------------------------------------------------------------------||");
  289.     }

  290.     public static final void main (
  291.         final String[] argumentArray)
  292.         throws Exception
  293.     {
  294.         EnvManager.InitEnv ("");

  295.         int drawCount = 2000;
  296.         int sampleCount = 600;
  297.         double sampleLeftSupport = 0.;
  298.         double sampleRightSupport = 1.;
  299.         int orderStatisticsCount = 20;
  300.         double[] hypothesisLeftSupportArray = {
  301.             -0.50,
  302.             -0.25,
  303.              0.00,
  304.              0.25,
  305.              0.50
  306.         };
  307.         double[] hypothesisRightSupportArray = {
  308.             0.75,
  309.             1.00,
  310.             1.25,
  311.             1.50,
  312.             1.75
  313.         };

  314.         GapTestSetting gapTestSetting = GapTestSetting.RiskFactorLossTest (
  315.             GapLossWeightFunction.AndersonDarling()
  316.         );

  317.         PlottingPositionGenerator plottingPositionGenerator = PlottingPositionGeneratorHeuristic.NIST2013
  318.             (orderStatisticsCount);

  319.         Sample sample = GenerateSample (
  320.             sampleLeftSupport,
  321.             sampleRightSupport,
  322.             drawCount
  323.         );

  324.         for (double hypothesisLeftSupport : hypothesisLeftSupportArray)
  325.         {
  326.             for (double hypothesisRightSupport : hypothesisRightSupportArray)
  327.             {
  328.                 DistanceTest (
  329.                     hypothesisLeftSupport,
  330.                     hypothesisRightSupport,
  331.                     drawCount,
  332.                     sampleCount,
  333.                     sample,
  334.                     gapTestSetting,
  335.                     plottingPositionGenerator
  336.                 );
  337.             }
  338.         }

  339.         EnvManager.TerminateEnv();
  340.     }
  341. }