MultivariateMoments.java

  1. package org.drip.measure.statistics;

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

  77. /**
  78.  * <i>MultivariateMoments</i> generates and holds the Specified Multivariate Series Mean, Co-variance, and
  79.  * other selected Moments.
  80.  *
  81.  *  <br><br>
  82.  *  <ul>
  83.  *      <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ComputationalCore.md">Computational Core Module</a></li>
  84.  *      <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/NumericalAnalysisLibrary.md">Numerical Analysis Library</a></li>
  85.  *      <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/measure/README.md">R<sup>d</sup> Continuous/Discrete Probability Measures</a></li>
  86.  *      <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/measure/statistics/README.md">R<sup>1</sup> R<sup>d</sup> Thin Thick Moments</a></li>
  87.  *  </ul>
  88.  *
  89.  * @author Lakshmi Krishnamurthy
  90.  */

  91. public class MultivariateMoments {
  92.     private org.drip.analytics.support.CaseInsensitiveHashMap<java.lang.Double> _mapMean = new
  93.         org.drip.analytics.support.CaseInsensitiveHashMap<java.lang.Double>();

  94.     private org.drip.analytics.support.CaseInsensitiveHashMap<java.lang.Double> _mapCovariance = new
  95.         org.drip.analytics.support.CaseInsensitiveHashMap<java.lang.Double>();

  96.     /**
  97.      * Generate the MultivariateMetrics Instance from the Series Realizations provided
  98.      *
  99.      * @param astrVariateName Array of Variate Name Headers
  100.      * @param aadblVariate Array of Variate Realization Arrays
  101.      *
  102.      * @return The MultivariateMetrics Instance
  103.      */

  104.     public static final MultivariateMoments Standard (
  105.         final java.lang.String[] astrVariateName,
  106.         final double[][] aadblVariate)
  107.     {
  108.         if (null == astrVariateName || null == aadblVariate) return null;

  109.         int iNumVariate = astrVariateName.length;
  110.         double[] adblMean = new double[iNumVariate];

  111.         if (0 == iNumVariate || iNumVariate != aadblVariate.length) return null;

  112.         int iNumSample = aadblVariate[0].length;

  113.         if (0 == iNumSample) return null;

  114.         MultivariateMoments mvm = new MultivariateMoments();

  115.         for (int i = 0; i < iNumVariate; ++i) {
  116.             adblMean[i] = 0.;
  117.             double[] adblVariateSample = aadblVariate[i];

  118.             if (null == adblVariateSample || adblVariateSample.length != iNumSample) return null;

  119.             for (int k = 0; k < iNumSample; ++k) {
  120.                 if (!org.drip.numerical.common.NumberUtil.IsValid (adblVariateSample[k])) return null;

  121.                 adblMean[i] += adblVariateSample[k];
  122.             }

  123.             if (!mvm.addMean (astrVariateName[i], adblMean[i] /= iNumSample)) return null;
  124.         }

  125.         for (int i = 0; i < iNumVariate; ++i) {
  126.             for (int j = 0; j < iNumVariate; ++j) {
  127.                 double dblCovariance = 0.;

  128.                 for (int k = 0; k < iNumSample; ++k)
  129.                     dblCovariance += (aadblVariate[i][k] - adblMean[i]) * (aadblVariate[j][k] - adblMean[j]);

  130.                 if (!mvm.addCovariance (astrVariateName[i], astrVariateName[j], dblCovariance / iNumSample))
  131.                     return null;
  132.             }
  133.         }

  134.         return mvm;
  135.     }

  136.     /**
  137.      * Generate the MultivariateMetrics Instance from the Specified Mean and Co-variance Inputs
  138.      *
  139.      * @param astrVariateName Array of Variate Name Headers
  140.      * @param adblMean Array of Variate Means
  141.      * @param aadblCovariance Double Array of the Variate Co-variance
  142.      *
  143.      * @return The MultivariateMetrics Instance
  144.      */

  145.     public static final MultivariateMoments Standard (
  146.         final java.lang.String[] astrVariateName,
  147.         final double[] adblMean,
  148.         final double[][] aadblCovariance)
  149.     {
  150.         if (null == astrVariateName || null == adblMean || null == aadblCovariance) return null;

  151.         int iNumVariate = astrVariateName.length;

  152.         if (0 == iNumVariate || iNumVariate != adblMean.length || iNumVariate != aadblCovariance.length ||
  153.             null == aadblCovariance[0] || iNumVariate != aadblCovariance[0].length)
  154.             return null;

  155.         MultivariateMoments mvm = new MultivariateMoments();

  156.         for (int i = 0; i < iNumVariate; ++i) {
  157.             if (!mvm.addMean (astrVariateName[i], adblMean[i])) return null;
  158.         }

  159.         for (int i = 0; i < iNumVariate; ++i) {
  160.             for (int j = 0; j < iNumVariate; ++j) {
  161.                 if (!mvm.addCovariance (astrVariateName[i], astrVariateName[j], aadblCovariance[i][j]))
  162.                     return null;
  163.             }
  164.         }

  165.         return mvm;
  166.     }

  167.     protected MultivariateMoments()
  168.     {
  169.     }

  170.     /**
  171.      * Retrieve the Number of Variates in the Distribution
  172.      *
  173.      * @return The Number of Variates in the Distribution
  174.      */

  175.     public int numVariate()
  176.     {
  177.         return _mapMean.size();
  178.     }

  179.     /**
  180.      * Retrieve the Variates for which the Metrics are available
  181.      *
  182.      * @return The Set of Variates
  183.      */

  184.     public java.util.Set<java.lang.String> variateList()
  185.     {
  186.         return _mapMean.keySet();
  187.     }

  188.     /**
  189.      * Add the Mean for the Named Variate
  190.      *
  191.      * @param strVariateName The Named Variate
  192.      * @param dblMean The Variate Mean
  193.      *
  194.      * @return TRUE - The Variate Mean successfully added
  195.      */

  196.     public boolean addMean (
  197.         final java.lang.String strVariateName,
  198.         final double dblMean)
  199.     {
  200.         if (null == strVariateName || strVariateName.isEmpty() || !org.drip.numerical.common.NumberUtil.IsValid
  201.             (dblMean))
  202.             return false;

  203.         _mapMean.put (strVariateName, dblMean);

  204.         return true;
  205.     }

  206.     /**
  207.      * Retrieve the Mean of the Named Variate
  208.      *
  209.      * @param strVariateName The Named Variate
  210.      *
  211.      * @return Mean of the Named Variate
  212.      *
  213.      * @throws java.lang.Exception Thrown if the Named Variate Mean cannot be retrieved
  214.      */

  215.     public double mean (
  216.         final java.lang.String strVariateName)
  217.         throws java.lang.Exception
  218.     {
  219.         if (null == strVariateName || strVariateName.isEmpty() || !_mapMean.containsKey (strVariateName))
  220.             throw new java.lang.Exception ("MultivariateMetrics::mean => Invalid Inputs");

  221.         return _mapMean.get (strVariateName);
  222.     }

  223.     /**
  224.      * Add the Co-variance for the Named Variate Pair
  225.      *
  226.      * @param strVariate1Name The Named Variate #1
  227.      * @param strVariate2Name The Named Variate #2
  228.      * @param dblCovariance The Variate Mean
  229.      *
  230.      * @return TRUE - The Variate Pair Co-variance successfully added
  231.      */

  232.     public boolean addCovariance (
  233.         final java.lang.String strVariate1Name,
  234.         final java.lang.String strVariate2Name,
  235.         final double dblCovariance)
  236.     {
  237.         if (null == strVariate1Name || strVariate1Name.isEmpty() || null == strVariate2Name ||
  238.             strVariate2Name.isEmpty() || !org.drip.numerical.common.NumberUtil.IsValid (dblCovariance))
  239.             return false;

  240.         _mapCovariance.put (strVariate1Name + "@#" + strVariate2Name, dblCovariance);

  241.         _mapCovariance.put (strVariate2Name + "@#" + strVariate1Name, dblCovariance);

  242.         return true;
  243.     }

  244.     /**
  245.      * Retrieve the Variance of the Named Variate
  246.      *
  247.      * @param strVariateName The Named Variate
  248.      *
  249.      * @return Variance of the Named Variate
  250.      *
  251.      * @throws java.lang.Exception Thrown if the Named Variate Variance cannot be retrieved
  252.      */

  253.     public double variance (
  254.         final java.lang.String strVariateName)
  255.         throws java.lang.Exception
  256.     {
  257.         if (null == strVariateName || strVariateName.isEmpty())
  258.             throw new java.lang.Exception ("MultivariateMetrics::variance => Invalid Inputs");

  259.         java.lang.String strVarianceEntry = strVariateName + "@#" + strVariateName;

  260.         if (!_mapCovariance.containsKey (strVarianceEntry))
  261.             throw new java.lang.Exception ("MultivariateMetrics::variance => Invalid Inputs");

  262.         return _mapCovariance.get (strVarianceEntry);
  263.     }

  264.     /**
  265.      * Retrieve the Co-variance of the Named Variate Pair
  266.      *
  267.      * @param strVariate1Name The Named Variate #1
  268.      * @param strVariate2Name The Named Variate #2
  269.      *
  270.      * @return Co-variance of the Named Variate Pair
  271.      *
  272.      * @throws java.lang.Exception Thrown if the Named Variate Co-variance cannot be retrieved
  273.      */

  274.     public double covariance (
  275.         final java.lang.String strVariate1Name,
  276.         final java.lang.String strVariate2Name)
  277.         throws java.lang.Exception
  278.     {
  279.         if (null == strVariate1Name || strVariate1Name.isEmpty() || null == strVariate2Name ||
  280.             strVariate2Name.isEmpty())
  281.             throw new java.lang.Exception ("MultivariateMetrics::covariance => Invalid Inputs");

  282.         java.lang.String strCovarianceEntry = strVariate1Name + "@#" + strVariate2Name;

  283.         if (!_mapCovariance.containsKey (strCovarianceEntry))
  284.             throw new java.lang.Exception ("MultivariateMetrics::coariance => Invalid Inputs");

  285.         return _mapCovariance.get (strCovarianceEntry);
  286.     }

  287.     /**
  288.      * Retrieve the Correlation between the Named Variate Pair
  289.      *
  290.      * @param strVariate1Name The Named Variate #1
  291.      * @param strVariate2Name The Named Variate #2
  292.      *
  293.      * @return Correlation between the Named Variate Pair
  294.      *
  295.      * @throws java.lang.Exception Thrown if the Named Variate Correlation cannot be retrieved
  296.      */

  297.     public double correlation (
  298.         final java.lang.String strVariate1Name,
  299.         final java.lang.String strVariate2Name)
  300.         throws java.lang.Exception
  301.     {
  302.         return covariance (strVariate1Name, strVariate2Name) / java.lang.Math.sqrt (variance
  303.             (strVariate1Name) * variance (strVariate2Name));
  304.     }
  305. }