ADCorrelationBacktesting7c.java

  1. package org.drip.sample.anfuso2017;

  2. import java.util.ArrayList;
  3. import java.util.List;

  4. import org.drip.numerical.common.FormatUtil;
  5. import org.drip.service.env.EnvManager;
  6. import org.drip.state.identifier.EntityEquityLabel;
  7. import org.drip.state.identifier.FXLabel;
  8. import org.drip.validation.distance.GapLossWeightFunction;
  9. import org.drip.validation.distance.GapTestOutcome;
  10. import org.drip.validation.distance.GapTestSetting;
  11. import org.drip.validation.evidence.Ensemble;
  12. import org.drip.validation.evidence.Sample;
  13. import org.drip.validation.evidence.TestStatisticEvaluator;
  14. import org.drip.validation.hypothesis.HistogramTestOutcome;
  15. import org.drip.validation.hypothesis.HistogramTestSetting;
  16. import org.drip.validation.hypothesis.ProbabilityIntegralTransformTest;
  17. import org.drip.validation.quantile.PlottingPositionGenerator;
  18. import org.drip.validation.quantile.PlottingPositionGeneratorHeuristic;
  19. import org.drip.validation.riskfactorjoint.NormalSampleCohort;
  20. import org.drip.validation.riskfactorsingle.DiscriminatoryPowerAnalyzer;

  21. /*
  22.  * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  23.  */

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

  93. /**
  94.  * <i>ADCorrelationBacktesting7c</i> demonstrates the Horizon Multi-Factor Gap PIT Quantiles set out in Table
  95.  * 7c of Anfuso, Karyampas, and Nawroth (2017).
  96.  *
  97.  *  <br><br>
  98.  *  <ul>
  99.  *      <li>
  100.  *          Anfuso, F., D. Karyampas, and A. Nawroth (2017): A Sound Basel III Compliant Framework for
  101.  *              Back-testing Credit Exposure Models
  102.  *              https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2264620 <b>eSSRN</b>
  103.  *      </li>
  104.  *      <li>
  105.  *          Diebold, F. X., T. A. Gunther, and A. S. Tay (1998): Evaluating Density Forecasts with
  106.  *              Applications to Financial Risk Management, International Economic Review 39 (4) 863-883
  107.  *      </li>
  108.  *      <li>
  109.  *          Kenyon, C., and R. Stamm (2012): Discounting, LIBOR, CVA, and Funding: Interest Rate and Credit
  110.  *              Pricing, Palgrave Macmillan
  111.  *      </li>
  112.  *      <li>
  113.  *          Wikipedia (2018): Probability Integral Transform
  114.  *              https://en.wikipedia.org/wiki/Probability_integral_transform
  115.  *      </li>
  116.  *      <li>
  117.  *          Wikipedia (2019): p-value https://en.wikipedia.org/wiki/P-value
  118.  *      </li>
  119.  *  </ul>
  120.  *
  121.  *  <br><br>
  122.  *  <ul>
  123.  *      <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ComputationalCore.md">Computational Core Module</a></li>
  124.  *      <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ModelValidationAnalyticsLibrary.md">Model Validation Analytics Library</a></li>
  125.  *      <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>
  126.  *      <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/sample/anfuso2017/README.md">Anfuso, Karyampas, and Nawroth (2013) Replications</a></li>
  127.  *  </ul>
  128.  * <br><br>
  129.  *
  130.  * @author Lakshmi Krishnamurthy
  131.  */

  132. public class ADCorrelationBacktesting7c
  133. {

  134.     private static final double[][] CorrelationMatrix (
  135.         final double correlation)
  136.     {
  137.         return new double[][]
  138.         {
  139.             {1.,          correlation},
  140.             {correlation, 1.         }
  141.         };
  142.     }

  143.     private static final void DistanceTest (
  144.         final GapTestOutcome gapTestOutcome,
  145.         final PlottingPositionGenerator plottingPositionGenerator)
  146.         throws Exception
  147.     {
  148.         HistogramTestOutcome histogram = new ProbabilityIntegralTransformTest (
  149.             gapTestOutcome.probabilityIntegralTransformWeighted()
  150.         ).histogramTest (
  151.             HistogramTestSetting.AnfusoKaryampasNawroth2017 (
  152.                 plottingPositionGenerator
  153.             )
  154.         );

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

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

  157.         double thresholdTestStatistic = histogram.thresholdTestStatistic();

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

  159.         double distance = gapTestOutcome.distance();

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

  161.         System.out.println ("\t|             Anderson Darling Correlation Distance Test             ||");

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

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

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

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

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

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

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

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

  170.         for (int histogramIndex = 0;
  171.             histogramIndex <= plottingPositionGenerator.orderStatisticCount() + 1;
  172.             ++histogramIndex)
  173.         {
  174.             System.out.println (
  175.                 "\t|" +
  176.                 FormatUtil.FormatDouble (gapArray[histogramIndex], 1, 8, 1.) + " | " +
  177.                 FormatUtil.FormatDouble (pValueCumulativeArray[histogramIndex], 1, 8, 1.) + " | " +
  178.                 FormatUtil.FormatDouble (pValueIncrementalArray[histogramIndex], 1, 8, 1.) + " | " +
  179.                 FormatUtil.FormatDouble (distance, 1, 8, 1.) + " | " +
  180.                 FormatUtil.FormatDouble (thresholdTestStatistic, 1, 8, 1.) + " ||"
  181.             );
  182.         }

  183.         System.out.println ("\t|--------------------------------------------------------------------||");
  184.     }

  185.     private static final Ensemble Hypothesis (
  186.         final List<String> labelList,
  187.         final double[] annualStateMeanArray,
  188.         final double[] annualStateVolatilityArray,
  189.         final double[][] correlationMatrix,
  190.         final int vertexCount,
  191.         final int sampleCount,
  192.         final double horizon,
  193.         final String label1,
  194.         final String label2)
  195.         throws Exception
  196.     {
  197.         Sample[] sampleArray = new Sample[sampleCount];

  198.         for (int sampleIndex = 0; sampleIndex < sampleCount; ++sampleIndex)
  199.         {
  200.             sampleArray[sampleIndex] = NormalSampleCohort.Correlated (
  201.                 labelList,
  202.                 annualStateMeanArray,
  203.                 annualStateVolatilityArray,
  204.                 correlationMatrix,
  205.                 vertexCount,
  206.                 horizon
  207.             ).reduce (
  208.                 label1,
  209.                 label2
  210.             );
  211.         }

  212.         return new Ensemble (
  213.             sampleArray,
  214.             new TestStatisticEvaluator[]
  215.             {
  216.                 new TestStatisticEvaluator()
  217.                 {
  218.                     public double evaluate (
  219.                         final double[] drawArray)
  220.                         throws Exception
  221.                     {
  222.                         return 1.;
  223.                     }
  224.                 }
  225.             }
  226.         );
  227.     }

  228.     public static final void main (
  229.         final String[] argumentArray)
  230.         throws Exception
  231.     {
  232.         EnvManager.InitEnv ("");

  233.         int sampleCount = 26;
  234.         int vertexCount = 390;
  235.         String currency = "USD";
  236.         double horizon = 12. / 12.;
  237.         double correlation = 0.50;
  238.         int orderStatisticsCount = 20;
  239.         String equityEntity = "SNP500";
  240.         String fxCurrencyPair = "CHF/USD";
  241.         double[] annualStateMeanArray =
  242.         {
  243.             0.06,
  244.             0.01
  245.         };
  246.         double[] annualStateVolatilityArray =
  247.         {
  248.             0.1,
  249.             0.1
  250.         };

  251.         List<String> labelList = new ArrayList<String>();

  252.         String snp500Label = EntityEquityLabel.Standard (
  253.             equityEntity,
  254.             currency
  255.         ).fullyQualifiedName();

  256.         String chfusdLabel = FXLabel.Standard (fxCurrencyPair).fullyQualifiedName();

  257.         labelList.add (snp500Label);

  258.         labelList.add (chfusdLabel);

  259.         Sample sample = NormalSampleCohort.Correlated (
  260.             labelList,
  261.             annualStateMeanArray,
  262.             annualStateVolatilityArray,
  263.             CorrelationMatrix (correlation),
  264.             vertexCount,
  265.             horizon
  266.         ).reduce (
  267.             snp500Label,
  268.             chfusdLabel
  269.         );

  270.         DiscriminatoryPowerAnalyzer discriminatoryPowerAnalysis = DiscriminatoryPowerAnalyzer.FromSample (
  271.             sample,
  272.             GapTestSetting.RiskFactorLossTest (
  273.                 GapLossWeightFunction.AndersonDarling()
  274.             )
  275.         );

  276.         Ensemble hypothesis = Hypothesis (
  277.             labelList,
  278.             annualStateMeanArray,
  279.             annualStateVolatilityArray,
  280.             CorrelationMatrix (correlation),
  281.             vertexCount,
  282.             sampleCount,
  283.             horizon,
  284.             snp500Label,
  285.             chfusdLabel
  286.         );

  287.         GapTestOutcome gapTestOutcome = discriminatoryPowerAnalysis.gapTest (hypothesis);

  288.         DistanceTest (
  289.             gapTestOutcome,
  290.             PlottingPositionGeneratorHeuristic.NIST2013 (orderStatisticsCount)
  291.         );

  292.         EnvManager.TerminateEnv();
  293.     }
  294. }