/// <summary> /// Assumes returns are normally distributed. /// <param name="returnArray">Historical returns from which VaR is to be calculated. The last value, with the highest index is assumed to be the most recent data point.</param> /// <param name="windowLength">Length of the VaR window. The number of historical returns that will be used to calculate the VaR.</param> /// <param name="confidenceLevel">VaR confidence level. 95% and 99% are typical values. If confidenceLevel is 95% then we expect 95% of days to be better (have a more positive return) than the VaR.</param> public static double NormalValueAtRisk(double[] returnArray, int windowLength, double confidenceLevel) { double[] da = new double[windowLength]; for (int i = 0; i < windowLength; i++) { da[i] = returnArray[returnArray.Length - windowLength + i]; } double mean = Moments.Mean(da); double standardDeviation = Moments.StandardDeviation(da); double var = Distributions.NormalCumulativeDistributionFunctionInverse(1 - confidenceLevel, mean, standardDeviation); return(-var); //By convention VaR is quoted as a positive value, even though it corresponds to a loss. }
/// <summary> /// Returns the incremental incremental VaR for the subportfolio relative to the portfolio. /// </summary> /// <param name="portfolioArray">Return array of portfolio. The last element (index = n-1), is the most recent.</param> /// <param name="subPortfolioArray">Return array of the sub-portfolio for which incremental VaR is being measured. The last element (index = n-1), is the most recent.</param> /// <param name="decayFactor">In most applications, the decay factor is between 0 and 1. Weigth on the last element in arrays is 1.0, the 2nd to last element d, 3rd to last d^2, ...</param> /// <param name="portfolioValutAtRisk">Value at risk of the portfolio.</param> /// <param name="length">Window length. Method uses the most recent n points, n = length.</param> public static double IncrementalValueAtRisk(double[] portfolioArray, double[] subPortfolioArray, double decayFactor, double portfolioValutAtRisk, int length) { double[] portfolioArrayLen = Tools.MostRecentValues(portfolioArray, length); double[] subPortfolioArrayLen = Tools.MostRecentValues(subPortfolioArray, length); double portfolioStandardDeviation = Moments.StandardDeviation(portfolioArray, decayFactor, length); if (Tools.ArrayAllEqual(subPortfolioArray)) { return(0.0); } double iStandardDeviation = Moments.IncrementalStandardDeviation(portfolioArrayLen, subPortfolioArrayLen, decayFactor); return((portfolioValutAtRisk / portfolioStandardDeviation) * iStandardDeviation); }