From noreply at r-forge.r-project.org Mon Jun 1 23:12:22 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 1 Jun 2015 23:12:22 +0200 (CEST) Subject: [Returnanalytics-commits] r3659 - in pkg/Dowd: . R man Message-ID: <20150601211222.9B91E180535@r-forge.r-project.org> Author: dacharya Date: 2015-06-01 23:12:22 +0200 (Mon, 01 Jun 2015) New Revision: 3659 Added: pkg/Dowd/R/CdfOfSumUsingGumbelCopula.R pkg/Dowd/R/GumbelCopulaVaR.R pkg/Dowd/man/CdfOfSumUsingGumbelCopula.Rd pkg/Dowd/man/GumbelCopulaVaR.Rd Modified: pkg/Dowd/NAMESPACE pkg/Dowd/R/BootstrapVaR.R pkg/Dowd/R/BootstrapVaRConfInterval.R pkg/Dowd/R/BootstrapVaRFigure.R pkg/Dowd/R/HSVaR.R pkg/Dowd/man/BootstrapESFigure.Rd pkg/Dowd/man/BootstrapVaR.Rd pkg/Dowd/man/BootstrapVarConfInterval.Rd pkg/Dowd/man/HSVaR.Rd pkg/Dowd/readme.txt Log: GumbelCopulaVaR and CdfOfSumUsingGumbelCopula: source and documentation. Some error exists. HSVaR and dependent functions (BootstrapVaR, BootstrapVaRFigure) are functional. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-05-29 21:20:41 UTC (rev 3658) +++ pkg/Dowd/NAMESPACE 2015-06-01 21:12:22 UTC (rev 3659) @@ -7,9 +7,12 @@ export(BootstrapESConfInterval) export(BootstrapESFigure) export(BootstrapVaR) -export(BootstrapVarConfInterval) +export(BootstrapVaRConfInterval) +export(BootstrapVaRFigure) +export(CdfOfSumUsingGumbelCopula) export(ChristoffersenBacktestForIndependence) export(ChristoffersenBacktestForUnconditionalCoverage) +export(GumbelCopulaVaR) export(HSES) export(HSVaR) export(JarqueBeraBacktest) Modified: pkg/Dowd/R/BootstrapVaR.R =================================================================== --- pkg/Dowd/R/BootstrapVaR.R 2015-05-29 21:20:41 UTC (rev 3658) +++ pkg/Dowd/R/BootstrapVaR.R 2015-06-01 21:12:22 UTC (rev 3659) @@ -18,7 +18,7 @@ #' BootstrapES(a, 50, 0.95) #' #' @export -BootstrapVaR <- function(Ra, number.sample, cl){ +BootstrapVaR <- function(Ra, number.resamples, cl){ if (nargs() < 3){ error("Too few arguments") @@ -37,7 +37,7 @@ if (length(cl) != 1) { error("Confidence level must be a scalar") } - if (length(number.samples) != 1){ + if (length(number.resamples) != 1){ error("Number of resamples must be a scalar"); } Modified: pkg/Dowd/R/BootstrapVaRConfInterval.R =================================================================== --- pkg/Dowd/R/BootstrapVaRConfInterval.R 2015-05-29 21:20:41 UTC (rev 3658) +++ pkg/Dowd/R/BootstrapVaRConfInterval.R 2015-06-01 21:12:22 UTC (rev 3659) @@ -21,7 +21,7 @@ #' BootstrapVarConfInterval(Ra, 500, 0.95) #' #' @export -BootstrapVarConfInterval <- function(Ra, number.resamples, cl){ +BootstrapVaRConfInterval <- function(Ra, number.resamples, cl){ # Determine if there are three arguments if (nargs() < 3){ Modified: pkg/Dowd/R/BootstrapVaRFigure.R =================================================================== --- pkg/Dowd/R/BootstrapVaRFigure.R 2015-05-29 21:20:41 UTC (rev 3658) +++ pkg/Dowd/R/BootstrapVaRFigure.R 2015-06-01 21:12:22 UTC (rev 3659) @@ -20,7 +20,7 @@ #' BootstrapESFigure(Ra, 500, 0.95) #' #' @export -BootstrapESFigure <- function(Ra, number.resamples, cl){ +BootstrapVaRFigure <- function(Ra, number.resamples, cl){ # Determine if there are three arguments if (nargs() < 3){ @@ -67,6 +67,6 @@ # Histogram cl.for.label <- 100*cl - hist(VaR[1], 30, xlab="VaR", ylab="Frequency", main=paste("Bootstrapped Historical Simulation VaR at", cl, "% Confidence Level")) + hist(VaR, 30, xlab="VaR", ylab="Frequency", main=paste("Bootstrapped Historical Simulation VaR at", cl, "% Confidence Level")) } \ No newline at end of file Added: pkg/Dowd/R/CdfOfSumUsingGumbelCopula.R =================================================================== --- pkg/Dowd/R/CdfOfSumUsingGumbelCopula.R (rev 0) +++ pkg/Dowd/R/CdfOfSumUsingGumbelCopula.R 2015-06-01 21:12:22 UTC (rev 3659) @@ -0,0 +1,73 @@ +#' Derives prob ( X + Y < quantile) using Gumbel copula +#' +#' If X and Y are position P/Ls, then the VaR is equal to minus quantile. In +#' such cases, we insert the negative of the VaR as the quantile, and the +#' function gives us the value of 1 minus VaR confidence level. In other +#' words, if X and Y are position P/Ls, the quantile is the negative of the +#' VaR, and the output is 1 minus the VaR confidence level. +#' +#' @param quantile Portfolio quantile (or negative of Var, if X, Y are position P/Ls) +#' @param mu1 Mean of Profit/Loss on first position +#' @param mu2 Mean of Profit/Loss on second position +#' @param sigma1 Standard Deviation of Profit/Loss on first position +#' @param sigma2 Standard Deviation of Profit/Loss on second position +#' @param beta Gumber copula parameter (greater than 1) +#' @return Probability of X + Y being less than quantile +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering +#' News, 2004. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Prob ( X + Y < q ) using Gumbel Copula for X with mean 2.3 and std. .2 +#' # CdfOfSumUsingGumbelCopula(0.9, 2.3, 4.5, 1.2, 1.5, 1.2) +#' +#' @export +CdfOfSumUsingGumbelCopula <- function(quantile, mu1, mu2, sigma1, sigma2, beta){ + + if (beta <= 1) { + stop("Beta must be bigger than 1") + } + # Define w variable + w.min <- 0.001 + w.max <- 0.999 # Specify min and max of w + dw <- 0.001 # Specify incremental change in w + w <- seq(w.min, w.max, dw) # Define w-variable going from min to max in units of size dw + + # Obtain 'first' and 'second' sets of copula values corresponding to + # values of w (NB: The difference between the 'first' and 'second' goes + # into the calculation of the approximate copula differential) + first.copula <- double(length(w)) # initialize variables + second.copula <- double(length(w)) + approximate.copula.differential <- double(length(w)) + for (i in 1:length(w)) { + first.copula[i] <- GumbelCopula(w[i], + pnorm(quantile - qnorm(w[i], mu1, sigma1), mu2, sigma2), + beta) + } + for (i in 2:length(w)) { + first.copula[i] <- GumbelCopula(w[i] - dw, + pnorm(quantile - qnorm(w[i], mu1, sigma1), mu2, sigma2), + beta) + } + + # Obtain approximate copula differentials from the above + for (i in 2:length(w)){ + approximate.copula.differential[i] <- (first.copula[i]-second.copula[i])/dw + } + + y<- sum(approximate.copula.differential) * dw + +} + +GumbelCopula <- function(u, v, beta){ + # Derives value of Gumbel Copula + # u is value of first marginal for random variable X + # v is value of second marginal for random variable Y + # beta parameter for Gumbel Copula + y <- exp(-((-log(u))^beta + (-log(v))^beta))^(1/beta); + return(y) + +} \ No newline at end of file Added: pkg/Dowd/R/GumbelCopulaVaR.R =================================================================== --- pkg/Dowd/R/GumbelCopulaVaR.R (rev 0) +++ pkg/Dowd/R/GumbelCopulaVaR.R 2015-06-01 21:12:22 UTC (rev 3659) @@ -0,0 +1,68 @@ +#' Bivariate Gumbel Copule VaR +#' +#' Derives VaR using bivariate Gumbel or logistic copula with specified inputs +#' for normal marginals. +#' +#' @param mu1 Mean of Profit/Loss on first position +#' @param mu2 Mean of Profit/Loss on second position +#' @param sigma1 Standard Deviation of Profit/Loss on first position +#' @param sigma2 Standard Deviation of Profit/Loss on second position +#' @param beta Gumber copula parameter (greater than 1) +#' @param cl VaR onfidece level +#' @return Copula based VaR +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering +#' News, 2004. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # VaR using bivariate Gumbel for X and Y with given parameters: +#' GumbelCopulaVaR(2.3, 4.1, 1.2, 1.5, 1.2, .95) +#' +#' @export +GumbelCopulaVaR <- function(mu1, mu2, sigma1, sigma2, beta, cl){ + + if (beta <= 1) { + stop("Beta must be bigger than 1") + } + + p <- 1 - cl # p is tail probability or cdf + + # Compute portfolio mean and sigma (NB: These are used here to help compute + # initial bounds automatically) + portfolio.mu <- mu1 + mu2 + portfolio.variance <- sigma1^2+sigma2^2 + portfolio.sigma <- sqrt(portfolio.variance) + + # Specify bounds arbitrarily (NB: Would need to change manually if these were + # inappropriate) + L <- -portfolio.mu - 5 * portfolio.sigma + fL <- CdfOfSumUsingGumbelCopula(L, mu1, mu2, sigma1, sigma2, beta) - p + sign.fL <- sign(fL) + U <- -portfolio.mu + 5 * portfolio.sigma + fU <- CdfOfSumUsingGumbelCopula(U, mu1, mu2, sigma1, sigma2, beta) - p + sign.fU <- sign(fU) + if (sign.fL == sign.fU){ + stop("Assumed bounds do not include answer") + } + + # Bisection Algorithm + tol <- 0.0001 # Tolerance level (NM: change manually if desired) + while (U - L > tol){ + x <- (L + U) / 2 # Bisection carried out in terms of P/L quantiles or minus VaR + cum.prob <- CdfOfSumUsingGumbelCopula(x, mu1, mu2, sigma1, sigma2, beta) + fx <- cum.prob - p + if (sign(fx) == sign(fL)){ + L <- x + fL <- fx + } else { + U <- x + fU <- fx + } + } + y <- -x # VaR is negative of terminal x-value or P/L quantile + +} \ No newline at end of file Modified: pkg/Dowd/R/HSVaR.R =================================================================== --- pkg/Dowd/R/HSVaR.R 2015-05-29 21:20:41 UTC (rev 3658) +++ pkg/Dowd/R/HSVaR.R 2015-06-01 21:12:22 UTC (rev 3659) @@ -5,7 +5,7 @@ #' period implies by data frequency. #' #' @param Ra Vector corresponding to profit and loss distribution -#' @param Rb Vector corresponding to VaR confidence levels. +#' @param Rb Scalar corresponding to VaR confidence levels. #' @return Value at Risk of the portfolio #' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. @@ -25,7 +25,9 @@ #' @author Dinesh Acharya #' @examples #' -#' # To be added. +#' # To be added +#' a <- rnorm(1000) # Payoffs of random portfolio +#' HSVaR(a, .95) #' #' @export HSVaR <- function(Ra, Rb){ @@ -40,7 +42,6 @@ stop("Too many arguments") } - if (nargs() == 2) { profit.loss.data <- as.vector(Ra) cl <- as.vector(Rb) @@ -50,11 +51,10 @@ } # Check that inputs have correct dimensions - if (is.vector(Rb)) { + if (!is.vector(cl)) { stop("Confidence level must be a vector") } - # Check that inputs obey sign and value restrictions if (max(cl) >= 1) { stop("Confidence level must be less than 1.") @@ -68,7 +68,7 @@ # If index value is an integer, VaR follows immediately y <- double(length(i)) - if (index-round[index] == 0){ + if (index-round(index) == 0){ y[i] <- losses.data[index] } Modified: pkg/Dowd/man/BootstrapESFigure.Rd =================================================================== --- pkg/Dowd/man/BootstrapESFigure.Rd 2015-05-29 21:20:41 UTC (rev 3658) +++ pkg/Dowd/man/BootstrapESFigure.Rd 2015-06-01 21:12:22 UTC (rev 3659) @@ -1,12 +1,10 @@ % Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapESFigure.R, R/BootstrapVaRFigure.R +% Please edit documentation in R/BootstrapESFigure.R \name{BootstrapESFigure} \alias{BootstrapESFigure} \title{Plots figure of bootstrapped ES} \usage{ BootstrapESFigure(Ra, number.resamples, cl) - -BootstrapESFigure(Ra, number.resamples, cl) } \arguments{ \item{Ra}{Vector corresponding to profit and loss distribution} @@ -14,19 +12,10 @@ \item{cl}{Number corresponding to Expected Shortfall confidence level} \item{number.resample}{Number of samples to be taken in bootstrap procedure} - -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.sample}{Number of samples to be taken in bootstrap procedure} - -\item{cl}{Number corresponding to Value at Risk confidence level} } \description{ Plots figure for the bootstrapped ES, for confidence level and holding period implied by data frequency. - -Plots figure for the bootstrapped VaR, for confidence -level and holding period implied by data frequency. } \examples{ # To be modified with appropriate data. @@ -34,20 +23,11 @@ # confidence interval Ra <- rnorm(1000) BootstrapESFigure(Ra, 500, 0.95) -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped VaR for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapESFigure(Ra, 500, 0.95) } \author{ Dinesh Acharya - -Dinesh Acharya } \references{ Dowd, K. Measuring Market Risk, Wiley, 2007. - -Dowd, K. Measuring Market Risk, Wiley, 2007. } Modified: pkg/Dowd/man/BootstrapVaR.Rd =================================================================== --- pkg/Dowd/man/BootstrapVaR.Rd 2015-05-29 21:20:41 UTC (rev 3658) +++ pkg/Dowd/man/BootstrapVaR.Rd 2015-06-01 21:12:22 UTC (rev 3659) @@ -4,7 +4,7 @@ \alias{BootstrapVaR} \title{Bootstrapped VaR for specified confidence level} \usage{ -BootstrapVaR(Ra, number.sample, cl) +BootstrapVaR(Ra, number.resamples, cl) } \arguments{ \item{Ra}{Vector corresponding to profit and loss distribution} Modified: pkg/Dowd/man/BootstrapVarConfInterval.Rd =================================================================== --- pkg/Dowd/man/BootstrapVarConfInterval.Rd 2015-05-29 21:20:41 UTC (rev 3658) +++ pkg/Dowd/man/BootstrapVarConfInterval.Rd 2015-06-01 21:12:22 UTC (rev 3659) @@ -1,10 +1,10 @@ % Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/BootstrapVaRConfInterval.R -\name{BootstrapVarConfInterval} -\alias{BootstrapVarConfInterval} +\name{BootstrapVaRConfInterval} +\alias{BootstrapVaRConfInterval} \title{Bootstrapped VaR Confidence Interval} \usage{ -BootstrapVarConfInterval(Ra, number.resamples, cl) +BootstrapVaRConfInterval(Ra, number.resamples, cl) } \arguments{ \item{Ra}{Vector corresponding to profit and loss distribution} Added: pkg/Dowd/man/CdfOfSumUsingGumbelCopula.Rd =================================================================== --- pkg/Dowd/man/CdfOfSumUsingGumbelCopula.Rd (rev 0) +++ pkg/Dowd/man/CdfOfSumUsingGumbelCopula.Rd 2015-06-01 21:12:22 UTC (rev 3659) @@ -0,0 +1,45 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/CdfOfSumUsingGumbelCopula.R +\name{CdfOfSumUsingGumbelCopula} +\alias{CdfOfSumUsingGumbelCopula} +\title{Derives prob ( X + Y < quantile) using Gumbel copula} +\usage{ +CdfOfSumUsingGumbelCopula(quantile, mu1, mu2, sigma1, sigma2, beta) +} +\arguments{ +\item{quantile}{Portfolio quantile (or negative of Var, if X, Y are position P/Ls)} + +\item{mu1}{Mean of Profit/Loss on first position} + +\item{mu2}{Mean of Profit/Loss on second position} + +\item{sigma1}{Standard Deviation of Profit/Loss on first position} + +\item{sigma2}{Standard Deviation of Profit/Loss on second position} + +\item{beta}{Gumber copula parameter (greater than 1)} +} +\value{ +Probability of X + Y being less than quantile +} +\description{ +If X and Y are position P/Ls, then the VaR is equal to minus quantile. In +such cases, we insert the negative of the VaR as the quantile, and the +function gives us the value of 1 minus VaR confidence level. In other +words, if X and Y are position P/Ls, the quantile is the negative of the +VaR, and the output is 1 minus the VaR confidence level. +} +\examples{ +# Prob ( X + Y < q ) using Gumbel Copula for X with mean 2.3 and std. .2 + # CdfOfSumUsingGumbelCopula(0.9, 2.3, 4.5, 1.2, 1.5, 1.2) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering +News, 2004. +} + Added: pkg/Dowd/man/GumbelCopulaVaR.Rd =================================================================== --- pkg/Dowd/man/GumbelCopulaVaR.Rd (rev 0) +++ pkg/Dowd/man/GumbelCopulaVaR.Rd 2015-06-01 21:12:22 UTC (rev 3659) @@ -0,0 +1,42 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/GumbelCopulaVaR.R +\name{GumbelCopulaVaR} +\alias{GumbelCopulaVaR} +\title{Bivariate Gumbel Copule VaR} +\usage{ +GumbelCopulaVaR(mu1, mu2, sigma1, sigma2, beta, cl) +} +\arguments{ +\item{mu1}{Mean of Profit/Loss on first position} + +\item{mu2}{Mean of Profit/Loss on second position} + +\item{sigma1}{Standard Deviation of Profit/Loss on first position} + +\item{sigma2}{Standard Deviation of Profit/Loss on second position} + +\item{beta}{Gumber copula parameter (greater than 1)} + +\item{cl}{VaR onfidece level} +} +\value{ +Copula based VaR +} +\description{ +Derives VaR using bivariate Gumbel or logistic copula with specified inputs +for normal marginals. +} +\examples{ +# VaR using bivariate Gumbel for X and Y with given parameters: + GumbelCopulaVaR(2.3, 4.1, 1.2, 1.5, 1.2, .95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering +News, 2004. +} + Modified: pkg/Dowd/man/HSVaR.Rd =================================================================== --- pkg/Dowd/man/HSVaR.Rd 2015-05-29 21:20:41 UTC (rev 3658) +++ pkg/Dowd/man/HSVaR.Rd 2015-06-01 21:12:22 UTC (rev 3659) @@ -9,7 +9,7 @@ \arguments{ \item{Ra}{Vector corresponding to profit and loss distribution} -\item{Rb}{Vector corresponding to VaR confidence levels.} +\item{Rb}{Scalar corresponding to VaR confidence levels.} } \value{ Value at Risk of the portfolio @@ -20,7 +20,9 @@ period implies by data frequency. } \examples{ -# To be added. +# To be added + a <- rnorm(1000) # Payoffs of random portfolio + HSVaR(a, .95) } \author{ Dinesh Acharya Modified: pkg/Dowd/readme.txt =================================================================== --- pkg/Dowd/readme.txt 2015-05-29 21:20:41 UTC (rev 3658) +++ pkg/Dowd/readme.txt 2015-06-01 21:12:22 UTC (rev 3659) @@ -1,9 +1,12 @@ #*************************************************************** -# Bootstrap is almost complete. It is still to be tested/debugged. Tests still remaining. +# Some error is present in GumbelCopulaVaR and needs correction #*************************************************************** +# Bootstrap is functional (but HSVaR still does not accept matrix P/L +# and only still accepts vectors, its needs to be modified) +#*************************************************************** # Jarque-Bera Test: # It has to be checked Probability of null (H0) or (H1). -# (http://stats.stackexchange.com/questions/130368/why-do-i-get-this-p-value-doing-the-jarque-bera-test-in-r) +# #*************************************************************** # Christofferson Backtest for Independence: # VaR(excess_loss<=0)=[]; Does not make sense. It is still to be checked if it is as intended. From noreply at r-forge.r-project.org Tue Jun 2 20:34:16 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 2 Jun 2015 20:34:16 +0200 (CEST) Subject: [Returnanalytics-commits] r3660 - in pkg/Dowd: . R man Message-ID: <20150602183416.EEA4218796C@r-forge.r-project.org> Author: dacharya Date: 2015-06-02 20:34:16 +0200 (Tue, 02 Jun 2015) New Revision: 3660 Added: pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R pkg/Dowd/R/CdfOfSumUsingProductCopula.R pkg/Dowd/R/GaussianCopulaVaR.R pkg/Dowd/R/ProductCopulaVaR.R pkg/Dowd/man/BootstrapVaRFigure.Rd pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd pkg/Dowd/man/CdfOfSumUsingProductCopula.Rd pkg/Dowd/man/GaussianCopulaVaR.Rd pkg/Dowd/man/ProductCopulaVaR.Rd Modified: pkg/Dowd/NAMESPACE pkg/Dowd/R/CdfOfSumUsingGumbelCopula.R pkg/Dowd/man/CdfOfSumUsingGumbelCopula.Rd Log: GaussianCopulaVaR, ProductCopulaVaR: source and documentation. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-01 21:12:22 UTC (rev 3659) +++ pkg/Dowd/NAMESPACE 2015-06-02 18:34:16 UTC (rev 3660) @@ -9,9 +9,12 @@ export(BootstrapVaR) export(BootstrapVaRConfInterval) export(BootstrapVaRFigure) +export(CdfOfSumUsingGaussianCopula) export(CdfOfSumUsingGumbelCopula) +export(CdfOfSumUsingProductCopula) export(ChristoffersenBacktestForIndependence) export(ChristoffersenBacktestForUnconditionalCoverage) +export(GaussianCopulaVaR) export(GumbelCopulaVaR) export(HSES) export(HSVaR) @@ -19,3 +22,4 @@ export(KSTestStat) export(KuiperTestStat) export(LopezBacktest) +export(ProductCopulaVaR) Added: pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R =================================================================== --- pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R (rev 0) +++ pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R 2015-06-02 18:34:16 UTC (rev 3660) @@ -0,0 +1,97 @@ +#' Derives prob ( X + Y < quantile) using Gumbel copula +#' +#' If X and Y are position P/Ls, then the VaR is equal to minus quantile. In +#' such cases, we insert the negative of the VaR as the quantile, and the +#' function gives us the value of 1 minus VaR confidence level. In other +#' words, if X and Y are position P/Ls, the quantile is the negative of the +#' VaR, and the output is 1 minus the VaR confidence level. +#' +#' @param quantile Portfolio quantile (or negative of Var, if X, Y are position P/Ls) +#' @param mu1 Mean of Profit/Loss on first position +#' @param mu2 Mean of Profit/Loss on second position +#' @param sigma1 Standard Deviation of Profit/Loss on first position +#' @param sigma2 Standard Deviation of Profit/Loss on second position +#' @param rho Correlation between P/Ls on two positions +#' @param number.steps.in.copula The number of steps used in the copula approximation +#' @return Probability of X + Y being less than quantile +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering +#' News, 2004. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Prob ( X + Y < q ) using Gaussian Copula for X with mean 2.3 and std. .2 +#' # and Y with mean 4.5 and std. 1.5 with beta 1.2 at 0.9 quantile +#' CdfOfSumUsingGaussianCopula(0.9, 2.3, 4.5, 1.2, 1.5, 0.6, 100) +#' +#' @export +CdfOfSumUsingGaussianCopula <- function(quantile, mu1, mu2, sigma1, sigma2, rho, number.steps.in.copula){ + + # Define w variable + w.min <- 0.001 + w.max <- 0.999 # Specify min and max of w + dw <- 0.001 # Specify incremental change in w + w <- seq(w.min, w.max, dw) # Define w-variable going from min to max in units of size dw + + # Obtain 'first' and 'second' sets of copula values corresponding to + # values of w (NB: The difference between the 'first' and 'second' goes + # into the calculation of the approximate copula differential) + first.copula <- double(length(w)) # initialize variables + second.copula <- double(length(w)) + approximate.copula.differential <- double(length(w)) + for (i in 1:length(w)) { + first.copula[i] <- GaussianCopula(w[i], + pnorm(quantile - qnorm(w[i], mu1, sigma1), mu2, sigma2), + 0, number.steps.in.copula) + } + for (i in 2:length(w)) { + second.copula[i] <- GaussianCopula(w[i] - dw, + pnorm(quantile - qnorm(w[i], mu1, sigma1), mu2, sigma2), + 0, number.steps.in.copula) + } + + # Obtain approximate copula differentials from the above + for (i in 2:length(w)){ + approximate.copula.differential[i] <- (first.copula[i]-second.copula[i])/dw + } + + y<- sum(approximate.copula.differential) * dw + +} + +GaussianCopula <- function(u, v, rho, number.steps){ + # Derives value of Gaussian Copula + # u is value of first marginal for random variable X + # v is value of second marginal for random variable Y + # rho is correlation coefficient between X and Y + # number.steps is used for each of x and y + # NB: Applies to bivariate Gaussian copula only + + # Define x and y + # NB: These are hypothetical domains of the cdfs; without loss of generality + # we can take these to be standard normal percentiles; this is because we are + # only using these to determine double integrals with limits u and v + x.min <- -3 + x.max <- qnorm(u, 0, 1) + dx <- (x.max - x.min)/number.steps + x <- seq(x.min, x.max, dx) + y.min <- -3 + y.max <- qnorm(v, 0, 1) + dy <- (y.max - y.min)/number.steps + y <- seq(y.min, y.max, dy) + + # Obtain copula as approximate double sum, which appriximates the 'true' + # double integral + term <- double(length(x),length(y)) + for (i in 1:length(x)) { + for (j in 1:length(y)) { + term[i, j] <- exp(-(x[i]^2-2*rho*x[i]*y[j]+y[j]^2)/(2*(1-rho^2))) + } + } + + y <- sum(term) * dx * dy / (2 * pi * (1 - rho^2)^0.5) + + return(y) +} \ No newline at end of file Modified: pkg/Dowd/R/CdfOfSumUsingGumbelCopula.R =================================================================== --- pkg/Dowd/R/CdfOfSumUsingGumbelCopula.R 2015-06-01 21:12:22 UTC (rev 3659) +++ pkg/Dowd/R/CdfOfSumUsingGumbelCopula.R 2015-06-02 18:34:16 UTC (rev 3660) @@ -22,7 +22,8 @@ #' @examples #' #' # Prob ( X + Y < q ) using Gumbel Copula for X with mean 2.3 and std. .2 -#' # CdfOfSumUsingGumbelCopula(0.9, 2.3, 4.5, 1.2, 1.5, 1.2) +#' # and Y with mean 4.5 and std. 1.5 with beta 1.2 at 0.9 quantile +#' CdfOfSumUsingGumbelCopula(0.9, 2.3, 4.5, 1.2, 1.5, 1.2) #' #' @export CdfOfSumUsingGumbelCopula <- function(quantile, mu1, mu2, sigma1, sigma2, beta){ @@ -30,6 +31,7 @@ if (beta <= 1) { stop("Beta must be bigger than 1") } + # Define w variable w.min <- 0.001 w.max <- 0.999 # Specify min and max of w @@ -48,7 +50,7 @@ beta) } for (i in 2:length(w)) { - first.copula[i] <- GumbelCopula(w[i] - dw, + second.copula[i] <- GumbelCopula(w[i] - dw, pnorm(quantile - qnorm(w[i], mu1, sigma1), mu2, sigma2), beta) } @@ -67,7 +69,6 @@ # u is value of first marginal for random variable X # v is value of second marginal for random variable Y # beta parameter for Gumbel Copula - y <- exp(-((-log(u))^beta + (-log(v))^beta))^(1/beta); + y <- exp(-((-log(u))^beta + (-log(v))^beta))^(1/beta) return(y) - } \ No newline at end of file Added: pkg/Dowd/R/CdfOfSumUsingProductCopula.R =================================================================== --- pkg/Dowd/R/CdfOfSumUsingProductCopula.R (rev 0) +++ pkg/Dowd/R/CdfOfSumUsingProductCopula.R 2015-06-02 18:34:16 UTC (rev 3660) @@ -0,0 +1,67 @@ +#' Derives prob ( X + Y < quantile) using Product copula +#' +#' If X and Y are position P/Ls, then the VaR is equal to minus quantile. In +#' such cases, we insert the negative of the VaR as the quantile, and the +#' function gives us the value of 1 minus VaR confidence level. In other +#' words, if X and Y are position P/Ls, the quantile is the negative of the +#' VaR, and the output is 1 minus the VaR confidence level. +#' +#' @param quantile Portfolio quantile (or negative of Var, if X, Y are position P/Ls) +#' @param mu1 Mean of Profit/Loss on first position +#' @param mu2 Mean of Profit/Loss on second position +#' @param sigma1 Standard Deviation of Profit/Loss on first position +#' @param sigma2 Standard Deviation of Profit/Loss on second position +#' @return Probability of X + Y being less than quantile +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering +#' News, 2004. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Prob ( X + Y < q ) using Product Copula for X with mean 2.3 and std. .2 +#' # and Y with mean 4.5 and std. 1.5 with beta 1.2 at 0.9 quantile +#' CdfOfSumUsingProductCopula(0.9, 2.3, 4.5, 1.2, 1.5) +#' +#' @export +CdfOfSumUsingProductCopula <- function(quantile, mu1, mu2, sigma1, sigma2){ + + # Define w variable + w.min <- 0.001 + w.max <- 0.999 # Specify min and max of w + dw <- 0.001 # Specify incremental change in w + w <- seq(w.min, w.max, dw) # Define w-variable going from min to max in units of size dw + + # Obtain 'first' and 'second' sets of copula values corresponding to + # values of w (NB: The difference between the 'first' and 'second' goes + # into the calculation of the approximate copula differential) + first.copula <- double(length(w)) # initialize variables + second.copula <- double(length(w)) + approximate.copula.differential <- double(length(w)) + for (i in 1:length(w)) { + first.copula[i] <- ProductCopula(w[i], + pnorm(quantile - qnorm(w[i], mu1, sigma1), mu2, sigma2)) + } + for (i in 2:length(w)) { + second.copula[i] <- ProductCopula(w[i] - dw, + pnorm(quantile - qnorm(w[i], mu1, sigma1), mu2, sigma2)) + } + + # Obtain approximate copula differentials from the above + for (i in 2:length(w)){ + approximate.copula.differential[i] <- (first.copula[i]-second.copula[i])/dw + } + + y<- sum(approximate.copula.differential) * dw + +} + +ProductCopula <- function(u, v){ + # Derives value of Product Copula + # u is value of first marginal for random variable X + # v is value of second marginal for random variable Y + # beta parameter for Product Copula + y <- u * v + return(y) +} \ No newline at end of file Added: pkg/Dowd/R/GaussianCopulaVaR.R =================================================================== --- pkg/Dowd/R/GaussianCopulaVaR.R (rev 0) +++ pkg/Dowd/R/GaussianCopulaVaR.R 2015-06-02 18:34:16 UTC (rev 3660) @@ -0,0 +1,74 @@ +#' Bivariate Gaussian Copule VaR +#' +#' Derives VaR using bivariate Gaussian copula with specified inputs +#' for normal marginals. +#' +#' @param mu1 Mean of Profit/Loss on first position +#' @param mu2 Mean of Profit/Loss on second position +#' @param sigma1 Standard Deviation of Profit/Loss on first position +#' @param sigma2 Standard Deviation of Profit/Loss on second position +#' @param rho Correlation between Profit/Loss on two positions +#' @param number.steps.in.copula Number of steps used in the copula approximation +#' ( approximation being needed because Gaussian copula lacks a closed form solution) +#' @param cl VaR confidece level +#' @return Copula based VaR +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering +#' News, 2004. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # VaR using bivariate Gumbel for X and Y with given parameters: +#' GumbelCopulaVaR(2.3, 4.1, 1.2, 1.5, .6, .95) +#' +#' @export +GaussianCopulaVaR <- function(mu1, mu2, sigma1, sigma2, rho, + number.steps.in.copula, cl){ + + p <- 1 - cl # p is tail probability or cdf + + # For comparision, compute analytical normal VaR + portfolio.mu <- mu1 + mu2 + portfolio.variance <- sigma1^2 + 2 * rho * sigma1 * sigma2 + sigma2^2 + portfolio.sigma <- sqrt(portfolio.variance) + analytical.variance.covariance.VaR <- - portfolio.mu - portfolio.sigma * qnorm(p, 0, 1) + # Specify bounds arbitrarily (NB: Would need to change manually if these were + # inappropriate) + L <- -portfolio.mu - 5 * portfolio.sigma + fL <- CdfOfSumUsingGaussianCopula(L, mu1, mu2, sigma1, sigma2, + rho, number.steps.in.copula) - p + sign.fL <- sign(fL) + U <- -portfolio.mu + 5 * portfolio.sigma + fU <- CdfOfSumUsingGaussianCopula(U, mu1, mu2, sigma1, sigma2, + rho, number.steps.in.copula) - p + sign.fU <- sign(fU) + + if (sign.fL == sign.fU){ + stop("Assumed bounds do not include answer") + } + + # Bisection Algorithm + tol <- 0.0001 # Tolerance level (NM: change manually if desired) + while (U - L > tol){ + x <- (L + U) / 2 # Bisection carried out in terms of P/L quantiles or minus VaR + cum.prob <- CdfOfSumUsingGaussianCopula(x, mu1, mu2, sigma1, sigma2, rho, + number.steps.in.copula) + fx <- cum.prob - p + if (sign(fx) == sign(fL)){ + L <- x + fL <- fx + } else { + U <- x + fU <- fx + } + } + + y <- -x # VaR is negative of terminal x-value or P/L quantile + + cat("Analytical Variance Covariance Var: ", analytical.variance.covariance.VaR, "\n") + cat("Var using bivariate gaussian copula: ", y, "\n") + cat("Error in Copula VaR Estimate: ", analytical.variance.covariance.VaR-y) + return(y) +} \ No newline at end of file Added: pkg/Dowd/R/ProductCopulaVaR.R =================================================================== --- pkg/Dowd/R/ProductCopulaVaR.R (rev 0) +++ pkg/Dowd/R/ProductCopulaVaR.R 2015-06-02 18:34:16 UTC (rev 3660) @@ -0,0 +1,63 @@ +#' Bivariate Product Copule VaR +#' +#' Derives VaR using bivariate Product or logistic copula with specified inputs +#' for normal marginals. +#' +#' @param mu1 Mean of Profit/Loss on first position +#' @param mu2 Mean of Profit/Loss on second position +#' @param sigma1 Standard Deviation of Profit/Loss on first position +#' @param sigma2 Standard Deviation of Profit/Loss on second position +#' @param cl VaR onfidece level +#' @return Copula based VaR +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering +#' News, 2004. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # VaR using bivariate Product for X and Y with given parameters: +#' ProductCopulaVaR(2.3, 4.1, 1.2, 1.5, .95) +#' +#' @export +ProductCopulaVaR <- function(mu1, mu2, sigma1, sigma2, cl){ + + p <- 1 - cl # p is tail probability or cdf + + # Compute portfolio mean and sigma (NB: These are used here to help compute + # initial bounds automatically) + portfolio.mu <- mu1 + mu2 + portfolio.variance <- sigma1^2+sigma2^2 + portfolio.sigma <- sqrt(portfolio.variance) + + # Specify bounds arbitrarily (NB: Would need to change manually if these were + # inappropriate) + L <- -portfolio.mu - 5 * portfolio.sigma + fL <- CdfOfSumUsingProductCopula(L, mu1, mu2, sigma1, sigma2) - p + sign.fL <- sign(fL) + U <- -portfolio.mu + 5 * portfolio.sigma + fU <- CdfOfSumUsingProductCopula(U, mu1, mu2, sigma1, sigma2) - p + sign.fU <- sign(fU) + if (sign.fL == sign.fU){ + stop("Assumed bounds do not include answer") + } + + # Bisection Algorithm + tol <- 0.0001 # Tolerance level (NM: change manually if desired) + while (U - L > tol){ + x <- (L + U) / 2 # Bisection carried out in terms of P/L quantiles or minus VaR + cum.prob <- CdfOfSumUsingProductCopula(x, mu1, mu2, sigma1, sigma2, beta) + fx <- cum.prob - p + if (sign(fx) == sign(fL)){ + L <- x + fL <- fx + } else { + U <- x + fU <- fx + } + } + y <- -x # VaR is negative of terminal x-value or P/L quantile + +} \ No newline at end of file Added: pkg/Dowd/man/BootstrapVaRFigure.Rd =================================================================== --- pkg/Dowd/man/BootstrapVaRFigure.Rd (rev 0) +++ pkg/Dowd/man/BootstrapVaRFigure.Rd 2015-06-02 18:34:16 UTC (rev 3660) @@ -0,0 +1,33 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapVaRFigure.R +\name{BootstrapVaRFigure} +\alias{BootstrapVaRFigure} +\title{Plots figure of bootstrapped VaR} +\usage{ +BootstrapVaRFigure(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{cl}{Number corresponding to Value at Risk confidence level} + +\item{number.sample}{Number of samples to be taken in bootstrap procedure} +} +\description{ +Plots figure for the bootstrapped VaR, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped VaR for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapESFigure(Ra, 500, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Added: pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd =================================================================== --- pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd (rev 0) +++ pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd 2015-06-02 18:34:16 UTC (rev 3660) @@ -0,0 +1,49 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/CdfOfSumUsingGaussianCopula.R +\name{CdfOfSumUsingGaussianCopula} +\alias{CdfOfSumUsingGaussianCopula} +\title{Derives prob ( X + Y < quantile) using Gumbel copula} +\usage{ +CdfOfSumUsingGaussianCopula(quantile, mu1, mu2, sigma1, sigma2, rho, + number.steps.in.copula) +} +\arguments{ +\item{quantile}{Portfolio quantile (or negative of Var, if X, Y are position P/Ls)} + +\item{mu1}{Mean of Profit/Loss on first position} + +\item{mu2}{Mean of Profit/Loss on second position} + +\item{sigma1}{Standard Deviation of Profit/Loss on first position} + +\item{sigma2}{Standard Deviation of Profit/Loss on second position} + +\item{rho}{Correlation between P/Ls on two positions} + +\item{number.steps.in.copula}{The number of steps used in the copula approximation} +} +\value{ +Probability of X + Y being less than quantile +} +\description{ +If X and Y are position P/Ls, then the VaR is equal to minus quantile. In +such cases, we insert the negative of the VaR as the quantile, and the +function gives us the value of 1 minus VaR confidence level. In other +words, if X and Y are position P/Ls, the quantile is the negative of the +VaR, and the output is 1 minus the VaR confidence level. +} +\examples{ +# Prob ( X + Y < q ) using Gaussian Copula for X with mean 2.3 and std. .2 + # and Y with mean 4.5 and std. 1.5 with beta 1.2 at 0.9 quantile + CdfOfSumUsingGaussianCopula(0.9, 2.3, 4.5, 1.2, 1.5, 0.6, 100) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering +News, 2004. +} + Modified: pkg/Dowd/man/CdfOfSumUsingGumbelCopula.Rd =================================================================== --- pkg/Dowd/man/CdfOfSumUsingGumbelCopula.Rd 2015-06-01 21:12:22 UTC (rev 3659) +++ pkg/Dowd/man/CdfOfSumUsingGumbelCopula.Rd 2015-06-02 18:34:16 UTC (rev 3660) @@ -31,7 +31,8 @@ } \examples{ # Prob ( X + Y < q ) using Gumbel Copula for X with mean 2.3 and std. .2 - # CdfOfSumUsingGumbelCopula(0.9, 2.3, 4.5, 1.2, 1.5, 1.2) + # and Y with mean 4.5 and std. 1.5 with beta 1.2 at 0.9 quantile + CdfOfSumUsingGumbelCopula(0.9, 2.3, 4.5, 1.2, 1.5, 1.2) } \author{ Dinesh Acharya Added: pkg/Dowd/man/CdfOfSumUsingProductCopula.Rd =================================================================== --- pkg/Dowd/man/CdfOfSumUsingProductCopula.Rd (rev 0) +++ pkg/Dowd/man/CdfOfSumUsingProductCopula.Rd 2015-06-02 18:34:16 UTC (rev 3660) @@ -0,0 +1,44 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/CdfOfSumUsingProductCopula.R +\name{CdfOfSumUsingProductCopula} +\alias{CdfOfSumUsingProductCopula} +\title{Derives prob ( X + Y < quantile) using Product copula} +\usage{ +CdfOfSumUsingProductCopula(quantile, mu1, mu2, sigma1, sigma2) +} +\arguments{ +\item{quantile}{Portfolio quantile (or negative of Var, if X, Y are position P/Ls)} + +\item{mu1}{Mean of Profit/Loss on first position} + +\item{mu2}{Mean of Profit/Loss on second position} + +\item{sigma1}{Standard Deviation of Profit/Loss on first position} + +\item{sigma2}{Standard Deviation of Profit/Loss on second position} +} +\value{ +Probability of X + Y being less than quantile +} +\description{ +If X and Y are position P/Ls, then the VaR is equal to minus quantile. In +such cases, we insert the negative of the VaR as the quantile, and the +function gives us the value of 1 minus VaR confidence level. In other +words, if X and Y are position P/Ls, the quantile is the negative of the +VaR, and the output is 1 minus the VaR confidence level. +} +\examples{ +# Prob ( X + Y < q ) using Product Copula for X with mean 2.3 and std. .2 + # and Y with mean 4.5 and std. 1.5 with beta 1.2 at 0.9 quantile + CdfOfSumUsingProductCopula(0.9, 2.3, 4.5, 1.2, 1.5) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering +News, 2004. +} + Added: pkg/Dowd/man/GaussianCopulaVaR.Rd =================================================================== --- pkg/Dowd/man/GaussianCopulaVaR.Rd (rev 0) +++ pkg/Dowd/man/GaussianCopulaVaR.Rd 2015-06-02 18:34:16 UTC (rev 3660) @@ -0,0 +1,45 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/GaussianCopulaVaR.R +\name{GaussianCopulaVaR} +\alias{GaussianCopulaVaR} +\title{Bivariate Gaussian Copule VaR} +\usage{ +GaussianCopulaVaR(mu1, mu2, sigma1, sigma2, rho, number.steps.in.copula, cl) +} +\arguments{ +\item{mu1}{Mean of Profit/Loss on first position} + +\item{mu2}{Mean of Profit/Loss on second position} + +\item{sigma1}{Standard Deviation of Profit/Loss on first position} + +\item{sigma2}{Standard Deviation of Profit/Loss on second position} + +\item{rho}{Correlation between Profit/Loss on two positions} + +\item{number.steps.in.copula}{Number of steps used in the copula approximation +( approximation being needed because Gaussian copula lacks a closed form solution)} + +\item{cl}{VaR confidece level} +} +\value{ +Copula based VaR +} +\description{ +Derives VaR using bivariate Gaussian copula with specified inputs +for normal marginals. +} +\examples{ +# VaR using bivariate Gumbel for X and Y with given parameters: + GumbelCopulaVaR(2.3, 4.1, 1.2, 1.5, .6, .95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering +News, 2004. +} + Added: pkg/Dowd/man/ProductCopulaVaR.Rd =================================================================== --- pkg/Dowd/man/ProductCopulaVaR.Rd (rev 0) +++ pkg/Dowd/man/ProductCopulaVaR.Rd 2015-06-02 18:34:16 UTC (rev 3660) @@ -0,0 +1,40 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/ProductCopulaVaR.R +\name{ProductCopulaVaR} +\alias{ProductCopulaVaR} +\title{Bivariate Product Copule VaR} +\usage{ +ProductCopulaVaR(mu1, mu2, sigma1, sigma2, cl) +} +\arguments{ +\item{mu1}{Mean of Profit/Loss on first position} + +\item{mu2}{Mean of Profit/Loss on second position} + +\item{sigma1}{Standard Deviation of Profit/Loss on first position} + +\item{sigma2}{Standard Deviation of Profit/Loss on second position} + +\item{cl}{VaR onfidece level} +} +\value{ +Copula based VaR +} +\description{ +Derives VaR using bivariate Product or logistic copula with specified inputs +for normal marginals. +} +\examples{ +# VaR using bivariate Product for X and Y with given parameters: + ProductCopulaVaR(2.3, 4.1, 1.2, 1.5, .95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering +News, 2004. +} + From noreply at r-forge.r-project.org Thu Jun 4 02:09:54 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 4 Jun 2015 02:09:54 +0200 (CEST) Subject: [Returnanalytics-commits] r3661 - in pkg/Dowd: . R man Message-ID: <20150604000954.BC015183F26@r-forge.r-project.org> Author: dacharya Date: 2015-06-04 02:09:54 +0200 (Thu, 04 Jun 2015) New Revision: 3661 Added: pkg/Dowd/R/CornishFisherES.R pkg/Dowd/R/CornishFisherVaR.R pkg/Dowd/man/CornishFisherES.Rd pkg/Dowd/man/CornishFisherVaR.Rd Modified: pkg/Dowd/NAMESPACE Log: CornishFisherES and CornishFisherVaR: source and documentation. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-02 18:34:16 UTC (rev 3660) +++ pkg/Dowd/NAMESPACE 2015-06-04 00:09:54 UTC (rev 3661) @@ -14,6 +14,8 @@ export(CdfOfSumUsingProductCopula) export(ChristoffersenBacktestForIndependence) export(ChristoffersenBacktestForUnconditionalCoverage) +export(CornishFisherES) +export(CornishFisherVaR) export(GaussianCopulaVaR) export(GumbelCopulaVaR) export(HSES) Added: pkg/Dowd/R/CornishFisherES.R =================================================================== --- pkg/Dowd/R/CornishFisherES.R (rev 0) +++ pkg/Dowd/R/CornishFisherES.R 2015-06-04 00:09:54 UTC (rev 3661) @@ -0,0 +1,45 @@ +#' Corn-Fisher ES +#' +#' Function estimates the ES for near-normal P/L using the Cornish-Fisher +#' adjustment for non-normality, for specified confidence level. +#' +#' @param mu Mean of P/L distribution +#' @param sigma Variance of of P/L distribution +#' @param skew Skew of P/L distribution +#' @param kurtosis Kurtosis of P/L distribution +#' @param cl ES confidence level +#' @return Expected Shortfall +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Zangri, P. A VaR methodology for portfolios that include options. +#' RiskMetrics Monitor, First quarter, 1996, p. 4-12. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates Cornish-Fisher ES for given parameters +#' CornishFisherES(3.2, 5.6, 2, 3, .9) +#' +#' @export +CornishFisherES <- function(mu, sigma, skew, kurtosis, cl) { + # ES estimation + confidence.level <- cl + delta.cl <- (1 - confidence.level)/100 + cl <- double(99) + z <- double(99) + VaR <- double(99) + adjustment <- double(99) + cl[1] <- confidence.level + for (i in 1:98){ + cl [i] <- cl[1] + i * delta.cl + z[i] <- qnorm(1 - cl[i], 0, 1) + adjustment[i] <- (1/6) * (z[i]^2 - 1) * skew + + (1/24) * (z[i]^3 - 3 * z[i]) * (kurtosis - 3) - + (1/36) * (2 * z[i]^3 - 5 * z[i]) * skew^2 + VaR[i] <- - sigma * (z[i] + adjustment[i]) - mu + } + y <- mean(VaR) + return(y) + +} \ No newline at end of file Added: pkg/Dowd/R/CornishFisherVaR.R =================================================================== --- pkg/Dowd/R/CornishFisherVaR.R (rev 0) +++ pkg/Dowd/R/CornishFisherVaR.R 2015-06-04 00:09:54 UTC (rev 3661) @@ -0,0 +1,36 @@ +#' Corn-Fisher VaR +#' +#' Function estimates the VaR for near-normal P/L using the Cornish-Fisher +#' adjustment for non-normality, for specified confidence level. +#' +#' @param mu Mean of P/L distribution +#' @param sigma Variance of of P/L distribution +#' @param skew Skew of P/L distribution +#' @param kurtosis Kurtosis of P/L distribution +#' @param cl VaR confidence level +#' @return Value at Risk +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Zangri, P. A VaR methodology for portfolios that include options. +#' RiskMetrics Monitor, First quarter, 1996, p. 4-12. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates Cornish-Fisher VaR for given parameters +#' CornishFisherVaR(3.2, 5.6, 2, 3, .9) +#' +#' @export +CornishFisherVaR <- function(mu, sigma, skew, kurtosis, cl) { + # Normal variate + z <- qnorm(1 - cl, 0, 1) + # Deriving adjustment factor + adjustment <- (1/6) * (z^2 - 1) * skew + + (1/24) * (z^3 - 3 * z) * (kurtosis - 3) - + (1/36) * (2 * z^3 - 5 * z) * skew^2 + # VaR estimation + y <- - sigma * (z + adjustment) - mu + return(y) + +} \ No newline at end of file Added: pkg/Dowd/man/CornishFisherES.Rd =================================================================== --- pkg/Dowd/man/CornishFisherES.Rd (rev 0) +++ pkg/Dowd/man/CornishFisherES.Rd 2015-06-04 00:09:54 UTC (rev 3661) @@ -0,0 +1,40 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/CornishFisherES.R +\name{CornishFisherES} +\alias{CornishFisherES} +\title{Corn-Fisher ES} +\usage{ +CornishFisherES(mu, sigma, skew, kurtosis, cl) +} +\arguments{ +\item{mu}{Mean of P/L distribution} + +\item{sigma}{Variance of of P/L distribution} + +\item{skew}{Skew of P/L distribution} + +\item{kurtosis}{Kurtosis of P/L distribution} + +\item{cl}{ES confidence level} +} +\value{ +Expected Shortfall +} +\description{ +Function estimates the ES for near-normal P/L using the Cornish-Fisher +adjustment for non-normality, for specified confidence level. +} +\examples{ +# Estimates Cornish-Fisher ES for given parameters + CornishFisherES(3.2, 5.6, 2, 3, .9) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Zangri, P. A VaR methodology for portfolios that include options. +RiskMetrics Monitor, First quarter, 1996, p. 4-12. +} + Added: pkg/Dowd/man/CornishFisherVaR.Rd =================================================================== --- pkg/Dowd/man/CornishFisherVaR.Rd (rev 0) +++ pkg/Dowd/man/CornishFisherVaR.Rd 2015-06-04 00:09:54 UTC (rev 3661) @@ -0,0 +1,40 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/CornishFisherVaR.R +\name{CornishFisherVaR} +\alias{CornishFisherVaR} +\title{Corn-Fisher VaR} +\usage{ +CornishFisherVaR(mu, sigma, skew, kurtosis, cl) +} +\arguments{ +\item{mu}{Mean of P/L distribution} + +\item{sigma}{Variance of of P/L distribution} + +\item{skew}{Skew of P/L distribution} + +\item{kurtosis}{Kurtosis of P/L distribution} + +\item{cl}{VaR confidence level} +} +\value{ +Value at Risk +} +\description{ +Function estimates the VaR for near-normal P/L using the Cornish-Fisher +adjustment for non-normality, for specified confidence level. +} +\examples{ +# Estimates Cornish-Fisher VaR for given parameters + CornishFisherVaR(3.2, 5.6, 2, 3, .9) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Zangri, P. A VaR methodology for portfolios that include options. +RiskMetrics Monitor, First quarter, 1996, p. 4-12. +} + From noreply at r-forge.r-project.org Sun Jun 7 02:59:54 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 7 Jun 2015 02:59:54 +0200 (CEST) Subject: [Returnanalytics-commits] r3662 - in pkg/PerformanceAnalytics: . R Message-ID: <20150607005954.9AB9F1879E7@r-forge.r-project.org> Author: braverock Date: 2015-06-07 02:59:53 +0200 (Sun, 07 Jun 2015) New Revision: 3662 Modified: pkg/PerformanceAnalytics/DESCRIPTION pkg/PerformanceAnalytics/R/CAPM.dynamic.R pkg/PerformanceAnalytics/R/Return.Geltner.R pkg/PerformanceAnalytics/R/Return.calculate.R Log: - use lag.xts to work around shockingly bad dispatch behavior by dplyr reported by Roger Bos Modified: pkg/PerformanceAnalytics/DESCRIPTION =================================================================== --- pkg/PerformanceAnalytics/DESCRIPTION 2015-06-04 00:09:54 UTC (rev 3661) +++ pkg/PerformanceAnalytics/DESCRIPTION 2015-06-07 00:59:53 UTC (rev 3662) @@ -12,7 +12,7 @@ , person(given="Kyle",family="Balkissoon",role="ctb") , person(given="Diethelm",family="Wuertz",role="ctb") ) -Version: 1.4.3640 +Version: 1.4.3662 Date: $Date$ Description: Collection of econometric functions for performance and risk analysis. This package aims to aid Modified: pkg/PerformanceAnalytics/R/CAPM.dynamic.R =================================================================== --- pkg/PerformanceAnalytics/R/CAPM.dynamic.R 2015-06-04 00:09:54 UTC (rev 3661) +++ pkg/PerformanceAnalytics/R/CAPM.dynamic.R 2015-06-07 00:59:53 UTC (rev 3662) @@ -78,10 +78,10 @@ xRb = Return.excess(Rb, Rf)[1:(nrow(Rb) - 1)] z = Z - matrix(rep(mean(Z), nrow(Z)), nrow(Z), ncol(Z), byrow = TRUE) # Construct the matrix with information regressors (lagged values) - inform = lag(z) + inform = lag.xts(z) if (lags > 1){ for (i in 2:lags) { - inform = cbind(inform, lag(z, i)) + inform = cbind(inform, lag.xts(z, i)) } } z = inform[(lags + 1):nrow(z), ] Modified: pkg/PerformanceAnalytics/R/Return.Geltner.R =================================================================== --- pkg/PerformanceAnalytics/R/Return.Geltner.R 2015-06-04 00:09:54 UTC (rev 3661) +++ pkg/PerformanceAnalytics/R/Return.Geltner.R 2015-06-07 00:59:53 UTC (rev 3662) @@ -58,7 +58,7 @@ clean.geltner <- function(column.R) { # compute the lagged return series - lagR = lag(column.R, k=1) + lagR = lag.xts(column.R, k=1) # compute the first order autocorrelation f_acf = as.numeric(acf(as.numeric(column.R), plot = FALSE)[1][[1]]) # now calculate and return the Geltner series Modified: pkg/PerformanceAnalytics/R/Return.calculate.R =================================================================== --- pkg/PerformanceAnalytics/R/Return.calculate.R 2015-06-04 00:09:54 UTC (rev 3661) +++ pkg/PerformanceAnalytics/R/Return.calculate.R 2015-06-07 00:59:53 UTC (rev 3662) @@ -70,7 +70,7 @@ if(method=="simple" || method=='discrete'){ #Returns = pr/pr[-nrow(pr), ] - 1 - Returns = pr/lag(pr) - 1 + Returns = pr/lag.xts(pr) - 1 xtsAttributes(Returns) <- list(ret_type="discrete") } if(method=="compound" || method=='log') { From noreply at r-forge.r-project.org Mon Jun 8 23:51:12 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 8 Jun 2015 23:51:12 +0200 (CEST) Subject: [Returnanalytics-commits] r3663 - in pkg/Dowd: . R man Message-ID: <20150608215112.2BD4C186579@r-forge.r-project.org> Author: dacharya Date: 2015-06-08 23:51:11 +0200 (Mon, 08 Jun 2015) New Revision: 3663 Added: pkg/Dowd/R/HillEstimator.R pkg/Dowd/R/HillPlot.R pkg/Dowd/R/HillQuantileEstimator.R pkg/Dowd/R/PickandsEstimator.R pkg/Dowd/R/PickandsPlot.R pkg/Dowd/man/HillEstimator.Rd pkg/Dowd/man/HillPlot.Rd pkg/Dowd/man/HillQuantileEstimator.Rd pkg/Dowd/man/PickandsEstimator.Rd pkg/Dowd/man/PickandsPlot.Rd Modified: pkg/Dowd/NAMESPACE Log: HillPlot, HillEstimator, HillQuantileEstimator, PickandsPlot.R and PickandsEstimator: (source and documentation) Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-07 00:59:53 UTC (rev 3662) +++ pkg/Dowd/NAMESPACE 2015-06-08 21:51:11 UTC (rev 3663) @@ -20,8 +20,13 @@ export(GumbelCopulaVaR) export(HSES) export(HSVaR) +export(HillEstimator) +export(HillPlot) +export(HillQuantileEstimator) export(JarqueBeraBacktest) export(KSTestStat) export(KuiperTestStat) export(LopezBacktest) +export(PickandsEstimator) +export(PickandsPlot) export(ProductCopulaVaR) Added: pkg/Dowd/R/HillEstimator.R =================================================================== --- pkg/Dowd/R/HillEstimator.R (rev 0) +++ pkg/Dowd/R/HillEstimator.R 2015-06-08 21:51:11 UTC (rev 3663) @@ -0,0 +1,39 @@ +#' Hill Estimator +#' +#' Estimates the value of the Hill Estimator for a given specified data set and +#' chosen tail size. Notes: 1) We estimate Hill Estimator by looking at the +#' upper tail. 2) If the specified tail size is such that any included +#' observations are negative, the tail is truncated at the point before +#' observations become negative. 3) The tail size must be a scalar. +#' +#' @param Ra Data set +#' @param tail.size Number of observations to be used to estimate the Hill +#' estimator. +#' @param cl ES confidence level +#' @return Estimated value of Hill Estimator +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates Hill Estimator of +#' Ra <- rnorm(15) +#' HillEstimator(Ra, 10) +#' +#' @export +HillEstimator <- function(Ra, tail.size){ + + data <- as.vector(Ra) + n <- length(data) + i <- which(data <= 0) + i <- max(i) + k <- min(tail.size, n - i) + logsum <- 0 + for (i in 2:k){ + logsum <- logsum + log(data[n - 1]) + } + y <- logsum / (k - 1) - log(data[n - k - 1]) + return(y) + +} \ No newline at end of file Added: pkg/Dowd/R/HillPlot.R =================================================================== --- pkg/Dowd/R/HillPlot.R (rev 0) +++ pkg/Dowd/R/HillPlot.R 2015-06-08 21:51:11 UTC (rev 3663) @@ -0,0 +1,40 @@ +#' Hill Plot +#' +#' Displays a plot of the Hill Estimator against tail sample size. +#' +#' @param Ra The data set +#' @param maximum.tail.size maximum tail size and should be greater than a +#' quarter of the sample size. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Hill Estimator - Tail Sample Size Plot for random normal dataset +#' Ra <- rnorm(1000) +#' HillPlot(Ra, 180) +#' +#' @export +HillPlot <- function(Ra, maximum.tail.size){ + + data <- as.vector(Ra) + data <- sort(data) + n <- length(data) + i <- which(data <= 0) + i <- max(i) + max.k <- min(maximum.tail.size, n - i) + he <- double(max.k) + # Derivation of Hill Estimators and tail size series + for (k in 2:max.k){ + he[k] <- HillEstimator(data,k) + } + # Plot of Hill Estimator against tail size + j <- which(he != 0) + he <- he[j] + k <- 2:max.k + plot(k, he, type = "l", col="red", main = "Hill Estimator against Tail Size", + xlab="Number of observations in tail (k)", ylab = "Hill estimator") + +} \ No newline at end of file Added: pkg/Dowd/R/HillQuantileEstimator.R =================================================================== --- pkg/Dowd/R/HillQuantileEstimator.R (rev 0) +++ pkg/Dowd/R/HillQuantileEstimator.R 2015-06-08 21:51:11 UTC (rev 3663) @@ -0,0 +1,35 @@ +#' Hill Quantile Estimator +#' +#' Estimates value of Hill Quantile Estimator for a specified data set, tail +#' index, in-sample probability and confidence level. +#' +#' @param Ra A data set +#' @param tail.index Assumed tail index +#' @param in.sample.prob In-sample probability (used as basis for projection) +#' @param cl Confidence level +#' @return Value of Hill Quantile Estimator +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Next reference +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes estimates value of hill estimator for a specified data set +#' Ra <- rnorm(1000) +#' HillQuantileEstimator(Ra, 40, .5, .9) +#' +#' @export +HillQuantileEstimator <- function(Ra, tail.index, in.sample.prob, cl){ + + data <- as.vector(Ra) + data <- sort(data) + n <- length(data) + a <- in.sample.prob * n + k <- ((a>=0)*floor(a)+(a<0)*ceiling(a)) + p <- 1 - cl + y <- data[n - k] * (p * n / k) ^ (- tail.index) + return(y) + +} \ No newline at end of file Added: pkg/Dowd/R/PickandsEstimator.R =================================================================== --- pkg/Dowd/R/PickandsEstimator.R (rev 0) +++ pkg/Dowd/R/PickandsEstimator.R 2015-06-08 21:51:11 UTC (rev 3663) @@ -0,0 +1,34 @@ +#' Pickands Estimator +#' +#' Estimates the Value of Pickands Estimator for a specified data set +#' and chosen tail size. Notes: (1) We estimate the Pickands Estimator by +#' looking at the upper tail. (2) The tail size must be less than one quarter +#' of the total sample size. (3) The tail size must be a scalar. +#' +#' @param Ra A data set +#' @param tail.size Number of observations to be used to estimate the Pickands +#' estimator +#' @return Value of Pickands estimator +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes estimated Pickands estimator for randomly generated data. +#' Ra <- rnorm(1000) +#' PickandsEstimator(Ra, 40) +#' +#' @export +PickandsEstimator <- function (Ra, tail.size) { + + data <- as.vector(Ra) + data <- sort(data) + n <- length(data) + k <- tail.size + num <- data[n - k] - data[n - 2 * k] + den <- data[n - 2 * k] - data[n - 4 * k] + y <- log(num / den) / log(2) + return(y) + +} \ No newline at end of file Added: pkg/Dowd/R/PickandsPlot.R =================================================================== --- pkg/Dowd/R/PickandsPlot.R (rev 0) +++ pkg/Dowd/R/PickandsPlot.R 2015-06-08 21:51:11 UTC (rev 3663) @@ -0,0 +1,37 @@ +#' Pickand Estimator - Tail Sample Size Plot +#' +#' Displays a plot of the Pickands Estimator against Tail Sample Size. +#' +#' @param Ra The data set +#' @param maximum.tail.size maximum tail size and should be greater than a +#' quarter of the sample size. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Pickand - Sample Tail Size Plot for random standard normal data +#' Ra <- rnorm(1000) +#' PickandsPlot(Ra, 40) +#' +#' +#' @export +PickandsPlot <- function(Ra, maximum.tail.size){ + + data <- as.vector(Ra) + x <- sort(data) + n <- length(x) + # Derivation of Pickands estimators and tail size series + pe <- double(maximum.tail.size) + for(k in 2:maximum.tail.size){ + pe[k] <- PickandsEstimator(x, k) + } + # Plot of Pickands Estimator against tail size + k <- 1:maximum.tail.size + plot(k, pe, type="l", main = "Pickands Estimator against Tail Size", + xlab = "Number of observations in tail (k)", + ylab = "Pickands Estimator") + +} \ No newline at end of file Added: pkg/Dowd/man/HillEstimator.Rd =================================================================== --- pkg/Dowd/man/HillEstimator.Rd (rev 0) +++ pkg/Dowd/man/HillEstimator.Rd 2015-06-08 21:51:11 UTC (rev 3663) @@ -0,0 +1,38 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/HillEstimator.R +\name{HillEstimator} +\alias{HillEstimator} +\title{Hill Estimator} +\usage{ +HillEstimator(Ra, tail.size) +} +\arguments{ +\item{Ra}{Data set} + +\item{tail.size}{Number of observations to be used to estimate the Hill +estimator.} + +\item{cl}{ES confidence level} +} +\value{ +Estimated value of Hill Estimator +} +\description{ +Estimates the value of the Hill Estimator for a given specified data set and +chosen tail size. Notes: 1) We estimate Hill Estimator by looking at the +upper tail. 2) If the specified tail size is such that any included +observations are negative, the tail is truncated at the point before +observations become negative. 3) The tail size must be a scalar. +} +\examples{ +# Estimates Hill Estimator of + Ra <- rnorm(15) + HillEstimator(Ra, 10) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Added: pkg/Dowd/man/HillPlot.Rd =================================================================== --- pkg/Dowd/man/HillPlot.Rd (rev 0) +++ pkg/Dowd/man/HillPlot.Rd 2015-06-08 21:51:11 UTC (rev 3663) @@ -0,0 +1,29 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/HillPlot.R +\name{HillPlot} +\alias{HillPlot} +\title{Hill Plot} +\usage{ +HillPlot(Ra, maximum.tail.size) +} +\arguments{ +\item{Ra}{The data set} + +\item{maximum.tail.size}{maximum tail size and should be greater than a +quarter of the sample size.} +} +\description{ +Displays a plot of the Hill Estimator against tail sample size. +} +\examples{ +# Hill Estimator - Tail Sample Size Plot for random normal dataset + Ra <- rnorm(1000) + HillPlot(Ra, 180) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Added: pkg/Dowd/man/HillQuantileEstimator.Rd =================================================================== --- pkg/Dowd/man/HillQuantileEstimator.Rd (rev 0) +++ pkg/Dowd/man/HillQuantileEstimator.Rd 2015-06-08 21:51:11 UTC (rev 3663) @@ -0,0 +1,38 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/HillQuantileEstimator.R +\name{HillQuantileEstimator} +\alias{HillQuantileEstimator} +\title{Hill Quantile Estimator} +\usage{ +HillQuantileEstimator(Ra, tail.index, in.sample.prob, cl) +} +\arguments{ +\item{Ra}{A data set} + +\item{tail.index}{Assumed tail index} + +\item{in.sample.prob}{In-sample probability (used as basis for projection)} + +\item{cl}{Confidence level} +} +\value{ +Value of Hill Quantile Estimator +} +\description{ +Estimates value of Hill Quantile Estimator for a specified data set, tail +index, in-sample probability and confidence level. +} +\examples{ +# Computes estimates value of hill estimator for a specified data set + Ra <- rnorm(1000) + HillQuantileEstimator(Ra, 40, .5, .9) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Next reference +} + Added: pkg/Dowd/man/PickandsEstimator.Rd =================================================================== --- pkg/Dowd/man/PickandsEstimator.Rd (rev 0) +++ pkg/Dowd/man/PickandsEstimator.Rd 2015-06-08 21:51:11 UTC (rev 3663) @@ -0,0 +1,35 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/PickandsEstimator.R +\name{PickandsEstimator} +\alias{PickandsEstimator} +\title{Pickands Estimator} +\usage{ +PickandsEstimator(Ra, tail.size) +} +\arguments{ +\item{Ra}{A data set} + +\item{tail.size}{Number of observations to be used to estimate the Pickands +estimator} +} +\value{ +Value of Pickands estimator +} +\description{ +Estimates the Value of Pickands Estimator for a specified data set +and chosen tail size. Notes: (1) We estimate the Pickands Estimator by +looking at the upper tail. (2) The tail size must be less than one quarter +of the total sample size. (3) The tail size must be a scalar. +} +\examples{ +# Computes estimated Pickands estimator for randomly generated data. + Ra <- rnorm(1000) + PickandsEstimator(Ra, 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Added: pkg/Dowd/man/PickandsPlot.Rd =================================================================== --- pkg/Dowd/man/PickandsPlot.Rd (rev 0) +++ pkg/Dowd/man/PickandsPlot.Rd 2015-06-08 21:51:11 UTC (rev 3663) @@ -0,0 +1,29 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/PickandsPlot.R +\name{PickandsPlot} +\alias{PickandsPlot} +\title{Pickand Estimator - Tail Sample Size Plot} +\usage{ +PickandsPlot(Ra, maximum.tail.size) +} +\arguments{ +\item{Ra}{The data set} + +\item{maximum.tail.size}{maximum tail size and should be greater than a +quarter of the sample size.} +} +\description{ +Displays a plot of the Pickands Estimator against Tail Sample Size. +} +\examples{ +# Pickand - Sample Tail Size Plot for random standard normal data + Ra <- rnorm(1000) + PickandsPlot(Ra, 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jun 9 00:03:05 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 9 Jun 2015 00:03:05 +0200 (CEST) Subject: [Returnanalytics-commits] r3664 - pkg/Dowd/R Message-ID: <20150608220305.E792D186579@r-forge.r-project.org> Author: dacharya Date: 2015-06-09 00:03:05 +0200 (Tue, 09 Jun 2015) New Revision: 3664 Modified: pkg/Dowd/R/BootstrapVaRConfInterval.R Log: Small error correction in example. Modified: pkg/Dowd/R/BootstrapVaRConfInterval.R =================================================================== --- pkg/Dowd/R/BootstrapVaRConfInterval.R 2015-06-08 21:51:11 UTC (rev 3663) +++ pkg/Dowd/R/BootstrapVaRConfInterval.R 2015-06-08 22:03:05 UTC (rev 3664) @@ -18,7 +18,7 @@ #' # Estimates 90% confidence interval for bootstrapped Var for 95% #' # confidence interval #' Ra <- rnorm(1000) -#' BootstrapVarConfInterval(Ra, 500, 0.95) +#' BootstrapVaRConfInterval(Ra, 500, 0.95) #' #' @export BootstrapVaRConfInterval <- function(Ra, number.resamples, cl){ From noreply at r-forge.r-project.org Tue Jun 9 11:52:29 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 9 Jun 2015 11:52:29 +0200 (CEST) Subject: [Returnanalytics-commits] r3665 - pkg/Dowd/man Message-ID: <20150609095229.A794B187A59@r-forge.r-project.org> Author: dacharya Date: 2015-06-09 11:52:29 +0200 (Tue, 09 Jun 2015) New Revision: 3665 Added: pkg/Dowd/man/BootstrapVaRConfInterval.Rd Removed: pkg/Dowd/man/BootstrapVarConfInterval.Rd Log: Edit File Name for manual. Added: pkg/Dowd/man/BootstrapVaRConfInterval.Rd =================================================================== --- pkg/Dowd/man/BootstrapVaRConfInterval.Rd (rev 0) +++ pkg/Dowd/man/BootstrapVaRConfInterval.Rd 2015-06-09 09:52:29 UTC (rev 3665) @@ -0,0 +1,36 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapVaRConfInterval.R +\name{BootstrapVaRConfInterval} +\alias{BootstrapVaRConfInterval} +\title{Bootstrapped VaR Confidence Interval} +\usage{ +BootstrapVaRConfInterval(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{cl}{Number corresponding to Value at Risk confidence level} + +\item{number.sample}{Number of samples to be taken in bootstrap procedure} +} +\value{ +90% Confidence interval for bootstrapped VaR +} +\description{ +Estimates the 90% confidence interval for bootstrapped VaR, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped Var for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapVaRConfInterval(Ra, 500, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Deleted: pkg/Dowd/man/BootstrapVarConfInterval.Rd =================================================================== --- pkg/Dowd/man/BootstrapVarConfInterval.Rd 2015-06-08 22:03:05 UTC (rev 3664) +++ pkg/Dowd/man/BootstrapVarConfInterval.Rd 2015-06-09 09:52:29 UTC (rev 3665) @@ -1,36 +0,0 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapVaRConfInterval.R -\name{BootstrapVaRConfInterval} -\alias{BootstrapVaRConfInterval} -\title{Bootstrapped VaR Confidence Interval} -\usage{ -BootstrapVaRConfInterval(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{cl}{Number corresponding to Value at Risk confidence level} - -\item{number.sample}{Number of samples to be taken in bootstrap procedure} -} -\value{ -90% Confidence interval for bootstrapped VaR -} -\description{ -Estimates the 90% confidence interval for bootstrapped VaR, for confidence -level and holding period implied by data frequency. -} -\examples{ -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped Var for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapVarConfInterval(Ra, 500, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - From noreply at r-forge.r-project.org Tue Jun 9 23:12:48 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 9 Jun 2015 23:12:48 +0200 (CEST) Subject: [Returnanalytics-commits] r3666 - in pkg/Dowd: . R man Message-ID: <20150609211248.348AF186175@r-forge.r-project.org> Author: dacharya Date: 2015-06-09 23:12:47 +0200 (Tue, 09 Jun 2015) New Revision: 3666 Added: pkg/Dowd/R/MEFPlot.R pkg/Dowd/R/NormalQQPlot.R pkg/Dowd/man/MEFPlot.Rd pkg/Dowd/man/NormalQQPlot.Rd Modified: pkg/Dowd/NAMESPACE Log: MEFPlot and NormalQQPlot: source and documentation. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-09 09:52:29 UTC (rev 3665) +++ pkg/Dowd/NAMESPACE 2015-06-09 21:12:47 UTC (rev 3666) @@ -27,6 +27,8 @@ export(KSTestStat) export(KuiperTestStat) export(LopezBacktest) +export(MEFPlot) +export(NormalQQPlot) export(PickandsEstimator) export(PickandsPlot) export(ProductCopulaVaR) Added: pkg/Dowd/R/MEFPlot.R =================================================================== --- pkg/Dowd/R/MEFPlot.R (rev 0) +++ pkg/Dowd/R/MEFPlot.R 2015-06-09 21:12:47 UTC (rev 3666) @@ -0,0 +1,33 @@ +#' Mean Excess Function Plot +#' +#' Plots mean-excess function values of the data set. +#' +#' @param Ra Vector data +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots +#' Ra <- rnorm(1000) +#' MEFPlot(Ra) +#' +#' @export +MEFPlot <- function(Ra){ + data <- as.vector(Ra) + if (!is.vector(data)) { + stop("Input should be a vector data.") + } + u <- data + n <- length(u) + mef <- + for (i in 1:n - 1) { + data <- data[which(data > u[i])] + mef[i] <- mean(data) - u[i] + } + u <- u[!u==max(u)] + plot(u, mef, type = "l", xlab = "Threshold", ylab = "e(u)", + main = "Empirical Mean Excess Function") + +} \ No newline at end of file Added: pkg/Dowd/R/NormalQQPlot.R =================================================================== --- pkg/Dowd/R/NormalQQPlot.R (rev 0) +++ pkg/Dowd/R/NormalQQPlot.R 2015-06-09 21:12:47 UTC (rev 3666) @@ -0,0 +1,126 @@ +#' Normal Quantile Quantile Plot +#' +#' Produces an emperical QQ-Plot of the quantiles of the data set 'Ra' versus +#' the quantiles of a normal distribution. The purpose of the quantile-quantile plot is to determine whether the sample in 'Ra' is drawn from a normal (i.e., Gaussian) distribution. +#' +#' @param Ra Vector data set +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Description of example +#' Example +#' +#' @export +NormalQQPlot <- function(Ra){ + + x <- as.vector(Ra) + if (!is.vector(x)) { + stop("Input should be a vector.") + } + mu <- mean(x) + sigma <- sd(x) + y <- sort(x) + a <- PlotPos(y) + x <- a$pp + n <- a$n + x <- qnorm(x, mu, sigma) # This is theoretical normal quantile + xx <- x + yy <- y + + # Dowd's code has following details but since his code does not work for + # matrices with rows, columns > 1, it is not efficient to have it here. + # if(((dim(x)[1] == n) | (dim(x)[1] == 1 & dim(x)[2] == n)) & ~any(is.nan(x))){ + # xx <- sort(x) + # } else { + # xx <- quantile(x, pvec)[[1]] + # } + # + # if(((dim(y)[1] == n) | (dim(y)[1] == 1 & dim(y)[2] == n)) & ~any(is.nan(y))){ + # yy <- sort(y) + # } else { + # yy <- quantile(y, pvec)[[1]] + # } + xx <- sort(x) + yy <- sort(y) + + q1x <- quantile(x, .25)[[1]] + q3x <- quantile(x, .75)[[1]] + q1y <- quantile(y, .25)[[1]] + q3y <- quantile(y, .75)[[1]] + qx <- matrix(c(q1x,q3x), 2, length(q1x)) + qy <- matrix(c(q1y,q3y), 2, length(q1y)) + + dx <- q3x - q1x + dy <- q3y - q1y + slope <- dy/dx + centerx <- (q1x + q3x)/2 + centery <- (q1y + q3y)/2 + maxx <- max(x) + minx <- min(x) + maxy <- centery + slope * (maxx - centerx) + miny <- centery - slope * (centerx - minx) + + mx <- matrix(c(minx,maxx), 2, length(minx)) + my <- matrix(c(miny,maxy), 2, length(miny)) + + xmin <- min(xx, qx, mx) + xmax <- max(xx, qx, mx) + ymin <- min(yy, qy, my) + ymax <- max(yy, qy, my) + + plot(xx, yy, type = "p", pch=3, col="red", xlab = "Normal Quantiles", + ylab = "Quantiles of Input Sample", + main = "QQ Plot of Sample Data versus Normal", + xlim = c(xmin, xmax), ylim = c(ymin, ymax)) + par(new = TRUE) + plot(qx, qy, type = "l", col="blue", xlab = "Normal Quantiles", + ylab = "Quantiles of Input Sample", + main = "QQ Plot of Sample Data versus Normal", + xlim = c(xmin, xmax), ylim = c(ymin, ymax)) + par(new = TRUE) + plot(mx, my, type = "l", xlab = "Normal Quantiles", + ylab = "Quantiles of Input Sample", + main = "QQ Plot of Sample Data versus Normal", + xlim = c(xmin, xmax), ylim = c(ymin, ymax)) + +} + +# Helper Functions + +# Position PLot +PlotPos <- function(Ra){ + # + sx <- as.matrix(Ra) + if (!is.matrix(sx)) { + stop("Input should be a matrix.") + } + n <- dim(sx)[1] + m <- dim(sx)[2] + if (n == 1){ + sx <- t(sx) + n = m + m = 1 + } + nvec <- sum(!is.nan(sx)) + pp <- RepMat(as.matrix(1:n), 1, m) + pp <- (pp - .5)/ RepMat(nvec, n, 1) + pp[is.nan(sx)] <- NaN + + if (nargs() > 1){ + n <- max(nvec) + } + return(list("pp" = pp, "n" = n)) + +} + +# Implementation of repmat from matlab in R +RepMat <- function(X,m,n){ + X <- as.matrix(X) + mx <- dim(X)[1] + nx <- dim(X)[2] + a <- matrix(t(matrix(X, mx, nx * n)), mx * m, nx * n, byrow = T) + return(a) +} \ No newline at end of file Added: pkg/Dowd/man/MEFPlot.Rd =================================================================== --- pkg/Dowd/man/MEFPlot.Rd (rev 0) +++ pkg/Dowd/man/MEFPlot.Rd 2015-06-09 21:12:47 UTC (rev 3666) @@ -0,0 +1,26 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/MEFPlot.R +\name{MEFPlot} +\alias{MEFPlot} +\title{Mean Excess Function Plot} +\usage{ +MEFPlot(Ra) +} +\arguments{ +\item{Ra}{Vector data} +} +\description{ +Plots mean-excess function values of the data set. +} +\examples{ +# Plots + Ra <- rnorm(1000) + MEFPlot(Ra) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Added: pkg/Dowd/man/NormalQQPlot.Rd =================================================================== --- pkg/Dowd/man/NormalQQPlot.Rd (rev 0) +++ pkg/Dowd/man/NormalQQPlot.Rd 2015-06-09 21:12:47 UTC (rev 3666) @@ -0,0 +1,26 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalQQPlot.R +\name{NormalQQPlot} +\alias{NormalQQPlot} +\title{Normal Quantile Quantile Plot} +\usage{ +NormalQQPlot(Ra) +} +\arguments{ +\item{Ra}{Vector data set} +} +\description{ +Produces an emperical QQ-Plot of the quantiles of the data set 'Ra' versus +the quantiles of a normal distribution. The purpose of the quantile-quantile plot is to determine whether the sample in 'Ra' is drawn from a normal (i.e., Gaussian) distribution. +} +\examples{ +# Description of example + Example +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jun 9 23:16:46 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 9 Jun 2015 23:16:46 +0200 (CEST) Subject: [Returnanalytics-commits] r3667 - in pkg/Dowd: R man Message-ID: <20150609211646.55741186175@r-forge.r-project.org> Author: dacharya Date: 2015-06-09 23:16:46 +0200 (Tue, 09 Jun 2015) New Revision: 3667 Modified: pkg/Dowd/R/NormalQQPlot.R pkg/Dowd/man/NormalQQPlot.Rd Log: Example added for NormalQQPlot. Modified: pkg/Dowd/R/NormalQQPlot.R =================================================================== --- pkg/Dowd/R/NormalQQPlot.R 2015-06-09 21:12:47 UTC (rev 3666) +++ pkg/Dowd/R/NormalQQPlot.R 2015-06-09 21:16:46 UTC (rev 3667) @@ -10,8 +10,9 @@ #' @author Dinesh Acharya #' @examples #' -#' # Description of example -#' Example +#' # Normal QQ Plot for randomly generated standard normal data +#' Ra <- rnorm(100) +#' NormalQQPlot(Ra) #' #' @export NormalQQPlot <- function(Ra){ Modified: pkg/Dowd/man/NormalQQPlot.Rd =================================================================== --- pkg/Dowd/man/NormalQQPlot.Rd 2015-06-09 21:12:47 UTC (rev 3666) +++ pkg/Dowd/man/NormalQQPlot.Rd 2015-06-09 21:16:46 UTC (rev 3667) @@ -14,8 +14,9 @@ the quantiles of a normal distribution. The purpose of the quantile-quantile plot is to determine whether the sample in 'Ra' is drawn from a normal (i.e., Gaussian) distribution. } \examples{ -# Description of example - Example +# Normal QQ Plot for randomly generated standard normal data + Ra <- rnorm(100) + NormalQQPlot(Ra) } \author{ Dinesh Acharya From noreply at r-forge.r-project.org Wed Jun 10 15:06:29 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 10 Jun 2015 15:06:29 +0200 (CEST) Subject: [Returnanalytics-commits] r3668 - in pkg/Dowd: . R Message-ID: <20150610130630.056A918725F@r-forge.r-project.org> Author: peter_carl Date: 2015-06-10 15:06:29 +0200 (Wed, 10 Jun 2015) New Revision: 3668 Modified: pkg/Dowd/ pkg/Dowd/R/ADTestStat.R Log: - fixed comment that caused error during check Property changes on: pkg/Dowd ___________________________________________________________________ Added: svn:ignore + .Rproj.user .Rhistory .RData Modified: pkg/Dowd/R/ADTestStat.R =================================================================== --- pkg/Dowd/R/ADTestStat.R 2015-06-09 21:16:46 UTC (rev 3667) +++ pkg/Dowd/R/ADTestStat.R 2015-06-10 13:06:29 UTC (rev 3668) @@ -1,72 +1,72 @@ -#' Plots cumulative density for AD test and computes confidence -#' interval for AD test stat. -#' -#' Anderson-Darling(AD) test can be used to carry out distribution equality test and is -#' similar to Kolmogorov-Smirnov test. AD test statistic is defined as: -#' \deqn{A^2=n\int_{-\infty}^{\infty}\frac{[\hat{F}(x)-F(x)]^2}{F(x)[1-F(x)]}dF(x)} -#' which is equivalent to -#' \deqn{=-n-\frac{1}{n}\sum_{i=1}^n(2i-1)[\ln F(X_i)+\ln(1-F(X_{n+1-i}))]} -#' -#' @param number.trials -#' @param sample.size -#' @param confidence.interval -#' @return Confidence Interval for AD test statistic -#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. -#' -#' Anderson, T.W. and Darling, D.A. Asymptotic Theory of Certain Goodness of -#' Fit Criteria Based on Stochastic Processes, The Annals of Mathematical -#' Statistics, 23(2), 1952, p. 193-212. -#' -#' Kvam, P.H. and Vidakovic, B. Nonparametric Statistics with Applications to -#' Science and Engineering, Wiley, 2007. -#' -#' @author Dinesh Acharya -#' @examples -#' -#' # Probability that the VaR model is correct for 3 failures, 100 number -#' observations and 95% confidence level -#' ADTestStat(1000, 100, 0.95) -#' -#' @export -ADTestStat <- function(number.trials, sample.size, confidence.interval){ - - if (confidence.interval>1){ - stop("Confidence Interval should be less than 1.") - } - - m <- number.trials - n <- sample.size - - # Random Number Generation - data <- matrix(rnorm(m*n), m, n) - - # Initialize vectors - term <- double(n) - AD.test.stat <- double(m) - - # Compute AD test statistic - for (i in 1:m) { - trial.sample <- data[i, ] - ordered.trial.sample <- sort(trial.sample) - for (j in 1:n) { - term[j] <- (2*j-1)*(log(pnorm(ordered.trial.sample[j],0,1))- - log(1-pnorm(ordered.trial.sample[n+1-j],0,1))); - } - AD.test.stat[i] <- -n-mean(term) - } - AD.test.stat <- sort(AD.test.stat) - - # Obtain confidence interval - lower.bound.index <- round(m*(1-confidence.interval)/2) - upper.bound.index <- round(m* (confidence.interval+(1-confidence.interval)/2)) - confidence.interval.for.AD.test.stat <- c(AD.test.stat[lower.bound.index], - AD.test.stat[upper.bound.index]) - # Plot the graph - cdf <- seq(1/m, 1, 1/m) - plot(AD.test.stat, cdf, col="red", type="l", - main="Cumulative density for AD test statistic", - xlab="AD test statistic", ylab="Cumulative probability") - - return(confidence.interval.for.AD.test.stat) - -} +#' Plots cumulative density for AD test and computes confidence +#' interval for AD test stat. +#' +#' Anderson-Darling(AD) test can be used to carry out distribution equality test and is +#' similar to Kolmogorov-Smirnov test. AD test statistic is defined as: +#' \deqn{A^2=n\int_{-\infty}^{\infty}\frac{[\hat{F}(x)-F(x)]^2}{F(x)[1-F(x)]}dF(x)} +#' which is equivalent to +#' \deqn{=-n-\frac{1}{n}\sum_{i=1}^n(2i-1)[\ln F(X_i)+\ln(1-F(X_{n+1-i}))]} +#' +#' @param number.trials +#' @param sample.size +#' @param confidence.interval +#' @return Confidence Interval for AD test statistic +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Anderson, T.W. and Darling, D.A. Asymptotic Theory of Certain Goodness of +#' Fit Criteria Based on Stochastic Processes, The Annals of Mathematical +#' Statistics, 23(2), 1952, p. 193-212. +#' +#' Kvam, P.H. and Vidakovic, B. Nonparametric Statistics with Applications to +#' Science and Engineering, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Probability that the VaR model is correct for 3 failures, 100 number +#' # observations and 95% confidence level +#' ADTestStat(1000, 100, 0.95) +#' +#' @export +ADTestStat <- function(number.trials, sample.size, confidence.interval){ + + if (confidence.interval>1){ + stop("Confidence Interval should be less than 1.") + } + + m <- number.trials + n <- sample.size + + # Random Number Generation + data <- matrix(rnorm(m*n), m, n) + + # Initialize vectors + term <- double(n) + AD.test.stat <- double(m) + + # Compute AD test statistic + for (i in 1:m) { + trial.sample <- data[i, ] + ordered.trial.sample <- sort(trial.sample) + for (j in 1:n) { + term[j] <- (2*j-1)*(log(pnorm(ordered.trial.sample[j],0,1))- + log(1-pnorm(ordered.trial.sample[n+1-j],0,1))); + } + AD.test.stat[i] <- -n-mean(term) + } + AD.test.stat <- sort(AD.test.stat) + + # Obtain confidence interval + lower.bound.index <- round(m*(1-confidence.interval)/2) + upper.bound.index <- round(m* (confidence.interval+(1-confidence.interval)/2)) + confidence.interval.for.AD.test.stat <- c(AD.test.stat[lower.bound.index], + AD.test.stat[upper.bound.index]) + # Plot the graph + cdf <- seq(1/m, 1, 1/m) + plot(AD.test.stat, cdf, col="red", type="l", + main="Cumulative density for AD test statistic", + xlab="AD test statistic", ylab="Cumulative probability") + + return(confidence.interval.for.AD.test.stat) + +} From noreply at r-forge.r-project.org Wed Jun 10 20:40:36 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 10 Jun 2015 20:40:36 +0200 (CEST) Subject: [Returnanalytics-commits] r3669 - in pkg/Dowd: . R man Message-ID: <20150610184036.3C65E186ABA@r-forge.r-project.org> Author: dacharya Date: 2015-06-10 20:40:35 +0200 (Wed, 10 Jun 2015) New Revision: 3669 Added: pkg/Dowd/R/TQQPlot.R pkg/Dowd/man/TQQPlot.Rd Modified: pkg/Dowd/NAMESPACE Log: TQQPlot: Source and Documentation Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-10 13:06:29 UTC (rev 3668) +++ pkg/Dowd/NAMESPACE 2015-06-10 18:40:35 UTC (rev 3669) @@ -32,3 +32,4 @@ export(PickandsEstimator) export(PickandsPlot) export(ProductCopulaVaR) +export(TQQPlot) Added: pkg/Dowd/R/TQQPlot.R =================================================================== --- pkg/Dowd/R/TQQPlot.R (rev 0) +++ pkg/Dowd/R/TQQPlot.R 2015-06-10 18:40:35 UTC (rev 3669) @@ -0,0 +1,134 @@ +#' Student's T Quantile - Quantile Plot +#' +#' Creates emperical QQ-plot of the quantiles of the data set x versus of a t +#' distribution. The QQ-plot can be used to determine whether the sample in x is +#' drawn from a t distribution with specified number of degrees of freedom. +#' +#' @param Ra Sample data set +#' @param df Number of degrees of freedom of the t distribution +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # t-QQ Plot for randomly generated standard normal data +#' Ra <- rnorm(100) +#' TQQPlot(Ra, 20) +#' +#' @export +TQQPlot<- function(Ra, df){ + + x <- as.vector(Ra) + + if(!is.vector(Ra)){ + stop("The first argument should be a vector.") + } + + mu <- mean(x) + sigma <- sd(x) + y<- sort(x) + a <- PlotPos(y) + x <- a$pp + n <- a$n + x <- mu + sigma * qt(x, df) # This is theoretical t-quantile + xx <- x + yy <- y + + # Dowd's code has following details but since his code does not work for + # matrices with rows, columns > 1, it is not efficient to have it here. + # if(((dim(x)[1] == n) | (dim(x)[1] == 1 & dim(x)[2] == n)) & ~any(is.nan(x))){ + # xx <- sort(x) + # } else { + # xx <- quantile(x, pvec)[[1]] + # } + # + # if(((dim(y)[1] == n) | (dim(y)[1] == 1 & dim(y)[2] == n)) & ~any(is.nan(y))){ + # yy <- sort(y) + # } else { + # yy <- quantile(y, pvec)[[1]] + # } + xx <- sort(x) + yy <- sort(y) + + q1x <- quantile(x, .25)[[1]] + q3x <- quantile(x, .75)[[1]] + q1y <- quantile(y, .25)[[1]] + q3y <- quantile(y, .75)[[1]] + qx <- matrix(c(q1x,q3x), 2, length(q1x)) + qy <- matrix(c(q1y,q3y), 2, length(q1y)) + + dx <- q3x - q1x + dy <- q3y - q1y + slope <- dy/dx + centerx <- (q1x + q3x)/2 + centery <- (q1y + q3y)/2 + maxx <- max(x) + minx <- min(x) + maxy <- centery + slope * (maxx - centerx) + miny <- centery - slope * (centerx - minx) + + mx <- matrix(c(minx,maxx), 2, length(minx)) + my <- matrix(c(miny,maxy), 2, length(miny)) + + xmin <- min(xx, qx, mx) + xmax <- max(xx, qx, mx) + ymin <- min(yy, qy, my) + ymax <- max(yy, qy, my) + + plot(xx, yy, type = "p", pch=3, col="red", xlab = "t-Quantiles", + ylab = "Quantiles of Input Sample", + main = paste("QQ Plot of Sample Data versus Student-t with ", df, + "Degrees of freedom"), + xlim = c(xmin, xmax), ylim = c(ymin, ymax)) + par(new = TRUE) + plot(qx, qy, type = "l", col="blue", xlab = "t-Quantiles", + ylab = "Quantiles of Input Sample", + main = paste("QQ Plot of Sample Data versus Student-t with ", df, + "Degrees of freedom"), + xlim = c(xmin, xmax), ylim = c(ymin, ymax)) + par(new = TRUE) + plot(mx, my, type = "l", xlab = "t-Quantiles", + ylab = "Quantiles of Input Sample", + main = paste("QQ Plot of Sample Data versus Student-t with ", df, + "Degrees of freedom"), + xlim = c(xmin, xmax), ylim = c(ymin, ymax)) +} + +# Helper Functions + +# Position PLot +PlotPos <- function(Ra){ + # + sx <- as.matrix(Ra) + if (!is.matrix(sx)) { + stop("Input should be a matrix.") + } + n <- dim(sx)[1] + m <- dim(sx)[2] + if (n == 1){ + sx <- t(sx) + n = m + m = 1 + } + nvec <- sum(!is.nan(sx)) + pp <- RepMat(as.matrix(1:n), 1, m) + pp <- (pp - .5)/ RepMat(nvec, n, 1) + pp[is.nan(sx)] <- NaN + + if (nargs() > 1){ + n <- max(nvec) + } + return(list("pp" = pp, "n" = n)) + +} + +# Implementation of repmat from matlab in R +RepMat <- function(X,m,n){ + X <- as.matrix(X) + mx <- dim(X)[1] + nx <- dim(X)[2] + a <- matrix(t(matrix(X, mx, nx * n)), mx * m, nx * n, byrow = T) + return(a) +} \ No newline at end of file Added: pkg/Dowd/man/TQQPlot.Rd =================================================================== --- pkg/Dowd/man/TQQPlot.Rd (rev 0) +++ pkg/Dowd/man/TQQPlot.Rd 2015-06-10 18:40:35 UTC (rev 3669) @@ -0,0 +1,30 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/TQQPlot.R +\name{TQQPlot} +\alias{TQQPlot} +\title{Student's T Quantile - Quantile Plot} +\usage{ +TQQPlot(Ra, df) +} +\arguments{ +\item{Ra}{Sample data set} + +\item{df}{Number of degrees of freedom of the t distribution} +} +\description{ +Creates emperical QQ-plot of the quantiles of the data set x versus of a t +distribution. The QQ-plot can be used to determine whether the sample in x is +drawn from a t distribution with specified number of degrees of freedom. +} +\examples{ +# t-QQ Plot for randomly generated standard normal data + Ra <- rnorm(100) + TQQPlot(Ra, 20) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Wed Jun 10 23:08:25 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 10 Jun 2015 23:08:25 +0200 (CEST) Subject: [Returnanalytics-commits] r3670 - in pkg/Dowd: . R man Message-ID: <20150610210825.B7AE5187D29@r-forge.r-project.org> Author: dacharya Date: 2015-06-10 23:08:25 +0200 (Wed, 10 Jun 2015) New Revision: 3670 Added: pkg/Dowd/R/FrechetES.R pkg/Dowd/R/FrechetVaR.R pkg/Dowd/man/FrechetES.Rd pkg/Dowd/man/FrechetVaR.Rd Modified: pkg/Dowd/NAMESPACE pkg/Dowd/readme.txt Log: FrechetES and FrechetVaR: source and documentation Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-10 18:40:35 UTC (rev 3669) +++ pkg/Dowd/NAMESPACE 2015-06-10 21:08:25 UTC (rev 3670) @@ -16,6 +16,8 @@ export(ChristoffersenBacktestForUnconditionalCoverage) export(CornishFisherES) export(CornishFisherVaR) +export(FrechetES) +export(FrechetVaR) export(GaussianCopulaVaR) export(GumbelCopulaVaR) export(HSES) Added: pkg/Dowd/R/FrechetES.R =================================================================== --- pkg/Dowd/R/FrechetES.R (rev 0) +++ pkg/Dowd/R/FrechetES.R 2015-06-10 21:08:25 UTC (rev 3670) @@ -0,0 +1,97 @@ +#' Frechet Expected Shortfall +#' +#' Plots the ES of a portfolio against confidence level assuming extreme losses +#' are Frechet distributed, for specified confidence level and a given +#' holding period. +#' +#' Note that the long-right-hand tail is fitted to losses, not profits. +#' +#' +#' @param mu Location parameter for daily L/P +#' @param sigma Scale parameter for daily L/P +#' @param tail.index Tail index +#' @param n Block size from which maxima are drawn +#' @param cl Confidence level +#' @param hp Holding period +#' @return Value at Risk. If cl and hp are scalars, it returns scalar VaR. If cl +#' is vector and hp is a scalar, or viceversa, returns vector of VaRs. If both +#' cl and hp are vectors, returns a matrix of VaRs. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Embrechts, P., Kluppelberg, C. and Mikosch, T., Modelling Extremal Events for +#' Insurance and Finance. Springer, Berlin, 1997, p. 324. +#' +#' Reiss, R. D. and Thomas, M. Statistical Analysis of Extreme Values from +#' Insurance, Finance, Hydrology and Other Fields, Birkhaueser, Basel, 1997, +#' 15-18. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes VaR assuming Frechet Distribution for given parameters +#' FrechetVaR(3.5, 2.3, 1.6, 10, .95, 30) +#' +#' @export +FrechetES <- function(mu, sigma, tail.index, n, cl, hp){ + + # Check that inputs have correct dimensions + if (!length(mu) == 1) { + stop("mu must be a scalar") + } + if (!length(sigma) == 1) { + stop("sigma must be a scalar") + } + if (!length(tail.index) == 1) { + stop("tail.index must be a scalar") + } + if (!is.vector(cl)) { + stop("cl must be a vector or a scalar") + } + if (!is.vector(hp)) { + stop("hp must be a vector or a scalar") + } + + # Change cl and hp to row vector and column vectors respectively + cl <- t(as.matrix(cl)) + hp <- as.matrix(hp) + + # Check that parameters obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (min(tail.index) <= 0) { + stop("Tail index must be greater than 0") + } + if ( max(cl) >= 1){ + stop("Confidence level(s) must be less than 1") + } + if ( min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if ( min(cl) <= 0){ + stop("Holding period(s) must be greater than 0") + } + + # VaR estimation + VaR <- mu * matrix(1, 1, length(cl)) - (sigma / tail.index) * + (1 - ( - n * log(cl)) ^ ( - tail.index)) + + # ES Estimation + number.slices <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + term <- VaR + + delta.cl <- (1 - cl) / number.slices # Increment to confidence level as each slice is taken + for (i in 1:(number.slices-1)) { + cl <- cl0 + i * delta.cl # Revised cl + term <- term + mu * matrix(1, 1, length(cl)) - (sigma / tail.index) * + (1 - ( - n * log(cl)) ^ ( - tail.index)) + # NB Frechet term + } + + y <- term / (number.slices - 1) + + return(y) + +} \ No newline at end of file Added: pkg/Dowd/R/FrechetVaR.R =================================================================== --- pkg/Dowd/R/FrechetVaR.R (rev 0) +++ pkg/Dowd/R/FrechetVaR.R 2015-06-10 21:08:25 UTC (rev 3670) @@ -0,0 +1,81 @@ +#' Frechet Value at Risk +#' +#' Plots the VaR of a portfolio against confidence level assuming extreme losses +#' are Frechet distributed, for specified range of confidence level and a given +#' holding period. +#' +#' Note that the long-right-hand tail is fitted to losses, not profits. +#' +#' +#' @param mu Location parameter for daily L/P +#' @param sigma Scale parameter for daily L/P +#' @param tail.index Tail index +#' @param n Block size from which maxima are drawn +#' @param cl Confidence level +#' @param hp Holding period +#' @return Value at Risk. If cl and hp are scalars, it returns scalar VaR. If cl +#' is vector and hp is a scalar, or viceversa, returns vector of VaRs. If both +#' cl and hp are vectors, returns a matrix of VaRs. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Embrechts, P., Kluppelberg, C. and Mikosch, T., Modelling Extremal Events for +#' Insurance and Finance. Springer, Berlin, 1997, p. 324. +#' +#' Reiss, R. D. and Thomas, M. Statistical Analysis of Extreme Values from +#' Insurance, Finance, Hydrology and Other Fields, Birkhaueser, Basel, 1997, +#' 15-18. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes VaR assuming Frechet Distribution for given parameters +#' FrechetVaR(3.5, 2.3, 1.6, 10, .95, 30) +#' +#' @export +FrechetVaR <- function(mu, sigma, tail.index, n, cl, hp){ + + # Check that inputs have correct dimensions + if (!length(mu) == 1) { + stop("mu must be a scalar") + } + if (!length(sigma) == 1) { + stop("sigma must be a scalar") + } + if (!length(tail.index) == 1) { + stop("tail.index must be a scalar") + } + if (!is.vector(cl)) { + stop("cl must be a vector or a scalar") + } + if (!is.vector(hp)) { + stop("hp must be a vector or a scalar") + } + + # Change cl and hp to row vector and column vectors respectively + cl <- t(as.matrix(cl)) + hp <- as.matrix(hp) + + # Check that parameters obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (min(tail.index) <= 0) { + stop("Tail index must be greater than 0") + } + if ( max(cl) >= 1){ + stop("Confidence level(s) must be less than 1") + } + if ( min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if ( min(cl) <= 0){ + stop("Holding period(s) must be greater than 0") + } + # VaR estimation + y <- mu * matrix(1, 1, length(cl)) - (sigma / tail.index) * + (1 - ( - n * log(cl)) ^ ( - tail.index)) + + return(y) + +} \ No newline at end of file Added: pkg/Dowd/man/FrechetES.Rd =================================================================== --- pkg/Dowd/man/FrechetES.Rd (rev 0) +++ pkg/Dowd/man/FrechetES.Rd 2015-06-10 21:08:25 UTC (rev 3670) @@ -0,0 +1,52 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/FrechetES.R +\name{FrechetES} +\alias{FrechetES} +\title{Frechet Expected Shortfall} +\usage{ +FrechetES(mu, sigma, tail.index, n, cl, hp) +} +\arguments{ +\item{mu}{Location parameter for daily L/P} + +\item{sigma}{Scale parameter for daily L/P} + +\item{tail.index}{Tail index} + +\item{n}{Block size from which maxima are drawn} + +\item{cl}{Confidence level} + +\item{hp}{Holding period} +} +\value{ +Value at Risk. If cl and hp are scalars, it returns scalar VaR. If cl +is vector and hp is a scalar, or viceversa, returns vector of VaRs. If both +cl and hp are vectors, returns a matrix of VaRs. +} +\description{ +Plots the ES of a portfolio against confidence level assuming extreme losses +are Frechet distributed, for specified confidence level and a given +holding period. +} +\details{ +Note that the long-right-hand tail is fitted to losses, not profits. +} +\examples{ +# Computes VaR assuming Frechet Distribution for given parameters + FrechetVaR(3.5, 2.3, 1.6, 10, .95, 30) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Embrechts, P., Kluppelberg, C. and Mikosch, T., Modelling Extremal Events for +Insurance and Finance. Springer, Berlin, 1997, p. 324. + +Reiss, R. D. and Thomas, M. Statistical Analysis of Extreme Values from +Insurance, Finance, Hydrology and Other Fields, Birkhaueser, Basel, 1997, +15-18. +} + Added: pkg/Dowd/man/FrechetVaR.Rd =================================================================== --- pkg/Dowd/man/FrechetVaR.Rd (rev 0) +++ pkg/Dowd/man/FrechetVaR.Rd 2015-06-10 21:08:25 UTC (rev 3670) @@ -0,0 +1,52 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/FrechetVaR.R +\name{FrechetVaR} +\alias{FrechetVaR} +\title{Frechet Value at Risk} +\usage{ +FrechetVaR(mu, sigma, tail.index, n, cl, hp) +} +\arguments{ +\item{mu}{Location parameter for daily L/P} + +\item{sigma}{Scale parameter for daily L/P} + +\item{tail.index}{Tail index} + +\item{n}{Block size from which maxima are drawn} + +\item{cl}{Confidence level} + +\item{hp}{Holding period} +} +\value{ +Value at Risk. If cl and hp are scalars, it returns scalar VaR. If cl +is vector and hp is a scalar, or viceversa, returns vector of VaRs. If both +cl and hp are vectors, returns a matrix of VaRs. +} +\description{ +Plots the VaR of a portfolio against confidence level assuming extreme losses +are Frechet distributed, for specified range of confidence level and a given +holding period. +} +\details{ +Note that the long-right-hand tail is fitted to losses, not profits. +} +\examples{ +# Computes VaR assuming Frechet Distribution for given parameters + FrechetVaR(3.5, 2.3, 1.6, 10, .95, 30) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Embrechts, P., Kluppelberg, C. and Mikosch, T., Modelling Extremal Events for +Insurance and Finance. Springer, Berlin, 1997, p. 324. + +Reiss, R. D. and Thomas, M. Statistical Analysis of Extreme Values from +Insurance, Finance, Hydrology and Other Fields, Birkhaueser, Basel, 1997, +15-18. +} + Modified: pkg/Dowd/readme.txt =================================================================== --- pkg/Dowd/readme.txt 2015-06-10 18:40:35 UTC (rev 3669) +++ pkg/Dowd/readme.txt 2015-06-10 21:08:25 UTC (rev 3670) @@ -1,4 +1,11 @@ +# +# General Notes for Modification: #*************************************************************** +# FrechetVaR does not use hp and the remark about return value when it is vector is vaccuous. +#*************************************************************** +# In Normal/t QQ Plots, dowd code does not work for matrices but the code contains parts that +# work for matrices. some vectors like pvec are not defined anywhere in his code. +#*************************************************************** # Some error is present in GumbelCopulaVaR and needs correction #*************************************************************** # Bootstrap is functional (but HSVaR still does not accept matrix P/L @@ -6,7 +13,6 @@ #*************************************************************** # Jarque-Bera Test: # It has to be checked Probability of null (H0) or (H1). -# #*************************************************************** # Christofferson Backtest for Independence: # VaR(excess_loss<=0)=[]; Does not make sense. It is still to be checked if it is as intended. From noreply at r-forge.r-project.org Wed Jun 10 23:12:55 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 10 Jun 2015 23:12:55 +0200 (CEST) Subject: [Returnanalytics-commits] r3671 - in pkg/Dowd: R man Message-ID: <20150610211255.EDA15186C69@r-forge.r-project.org> Author: dacharya Date: 2015-06-10 23:12:55 +0200 (Wed, 10 Jun 2015) New Revision: 3671 Modified: pkg/Dowd/R/FrechetES.R pkg/Dowd/man/FrechetES.Rd Log: Corrected example in FrechetES. Modified: pkg/Dowd/R/FrechetES.R =================================================================== --- pkg/Dowd/R/FrechetES.R 2015-06-10 21:08:25 UTC (rev 3670) +++ pkg/Dowd/R/FrechetES.R 2015-06-10 21:12:55 UTC (rev 3671) @@ -29,8 +29,8 @@ #' @author Dinesh Acharya #' @examples #' -#' # Computes VaR assuming Frechet Distribution for given parameters -#' FrechetVaR(3.5, 2.3, 1.6, 10, .95, 30) +#' # Computes ES assuming Frechet Distribution for given parameters +#' FrechetES(3.5, 2.3, 1.6, 10, .95, 30) #' #' @export FrechetES <- function(mu, sigma, tail.index, n, cl, hp){ Modified: pkg/Dowd/man/FrechetES.Rd =================================================================== --- pkg/Dowd/man/FrechetES.Rd 2015-06-10 21:08:25 UTC (rev 3670) +++ pkg/Dowd/man/FrechetES.Rd 2015-06-10 21:12:55 UTC (rev 3671) @@ -33,8 +33,8 @@ Note that the long-right-hand tail is fitted to losses, not profits. } \examples{ -# Computes VaR assuming Frechet Distribution for given parameters - FrechetVaR(3.5, 2.3, 1.6, 10, .95, 30) +# Computes ES assuming Frechet Distribution for given parameters + FrechetES(3.5, 2.3, 1.6, 10, .95, 30) } \author{ Dinesh Acharya From noreply at r-forge.r-project.org Thu Jun 11 23:45:59 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 11 Jun 2015 23:45:59 +0200 (CEST) Subject: [Returnanalytics-commits] r3672 - in pkg/Dowd: . R man Message-ID: <20150611214559.CB5D51878A0@r-forge.r-project.org> Author: dacharya Date: 2015-06-11 23:45:59 +0200 (Thu, 11 Jun 2015) New Revision: 3672 Added: pkg/Dowd/R/FrechetESPlot2DCl.R pkg/Dowd/R/FrechetVaRPlot2DCl.R pkg/Dowd/man/FrechetESPlot2DCl.Rd pkg/Dowd/man/FrechetVaRPlot2DCl.Rd Modified: pkg/Dowd/NAMESPACE pkg/Dowd/R/FrechetES.R pkg/Dowd/R/FrechetVaR.R pkg/Dowd/man/FrechetES.Rd pkg/Dowd/man/FrechetVaR.Rd Log: FrechetESPlot2DCl and FrechetVaRPlot2DCl: source and documentation Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-10 21:12:55 UTC (rev 3671) +++ pkg/Dowd/NAMESPACE 2015-06-11 21:45:59 UTC (rev 3672) @@ -17,7 +17,9 @@ export(CornishFisherES) export(CornishFisherVaR) export(FrechetES) +export(FrechetESPlot2DCl) export(FrechetVaR) +export(FrechetVaRPlot2DCl) export(GaussianCopulaVaR) export(GumbelCopulaVaR) export(HSES) Modified: pkg/Dowd/R/FrechetES.R =================================================================== --- pkg/Dowd/R/FrechetES.R 2015-06-10 21:12:55 UTC (rev 3671) +++ pkg/Dowd/R/FrechetES.R 2015-06-11 21:45:59 UTC (rev 3672) @@ -1,6 +1,6 @@ #' Frechet Expected Shortfall #' -#' Plots the ES of a portfolio against confidence level assuming extreme losses +#' Estimates the ES of a portfolio assuming extreme losses #' are Frechet distributed, for specified confidence level and a given #' holding period. #' Added: pkg/Dowd/R/FrechetESPlot2DCl.R =================================================================== --- pkg/Dowd/R/FrechetESPlot2DCl.R (rev 0) +++ pkg/Dowd/R/FrechetESPlot2DCl.R 2015-06-11 21:45:59 UTC (rev 3672) @@ -0,0 +1,110 @@ +#' Plots Frechet Expected Shortfall against confidence level +#' +#' Plots the ES of a portfolio against confidence level assuming extreme losses +#' are Frechet distributed, for specified confidence level and a given +#' holding period. +#' +#' Note that the long-right-hand tail is fitted to losses, not profits. +#' +#' +#' @param mu Location parameter for daily L/P +#' @param sigma Scale parameter for daily L/P +#' @param tail.index Tail index +#' @param n Block size from which maxima are drawn +#' @param cl Confidence level and should be a vector +#' @param hp Holding period +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Embrechts, P., Kluppelberg, C. and Mikosch, T., Modelling Extremal Events for +#' Insurance and Finance. Springer, Berlin, 1997, p. 324. +#' +#' Reiss, R. D. and Thomas, M. Statistical Analysis of Extreme Values from +#' Insurance, Finance, Hydrology and Other Fields, Birkhaueser, Basel, 1997, +#' 15-18. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots ES against vector of cl assuming Frechet Distribution for given parameters +#' cl <- seq(0.9,0.99,0.01) +#' FrechetESPlot2DCl(3.5, 2.3, 1.6, 10, cl, 30) +#' +#' @export +FrechetESPlot2DCl <- function(mu, sigma, tail.index, n, cl, hp){ + + # Check that inputs have correct dimensions + if (!length(mu) == 1) { + stop("mu must be a scalar") + } + if (!length(sigma) == 1) { + stop("sigma must be a scalar") + } + if (!length(tail.index) == 1) { + stop("tail.index must be a scalar") + } + if (!is.vector(cl)) { + stop("cl must be a vector") + } + if (!length(hp) == 1) { + stop("hp must be a scalar") + } + + # Change cl to row vector + cl <- t(as.matrix(cl)) + + # Check that parameters obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (min(tail.index) <= 0) { + stop("Tail index must be greater than 0") + } + if ( max(cl) >= 1){ + stop("Confidence level(s) must be less than 1") + } + if ( min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if ( min(cl) <= 0){ + stop("Holding period(s) must be greater than 0") + } + + # VaR estimation + VaR <- mu * matrix(1, 1, length(cl)) - (sigma / tail.index) * + (1 - ( - n * log(cl)) ^ ( - tail.index)) + + # ES Estimation + number.slices <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + term <- VaR + + delta.cl <- (1 - cl) / number.slices # Increment to confidence level as each slice is taken + for (i in 1:(number.slices-1)) { + cl <- cl0 + i * delta.cl # Revised cl + term <- term + mu * matrix(1, 1, length(cl)) - (sigma / tail.index) * + (1 - ( - n * log(cl)) ^ ( - tail.index)) + # NB Frechet term + } + + es <- term / (number.slices - 1) + plot(cl0, es, type = "l", xlab = "Confidence level", ylab = "VaR", + main = "Frechet ES against confidence level") + + text(mean(cl0), + max(es) - .1*(max(es) - min(es)), + 'Input parameters') + text(mean(cl0), + max(es)-.2*(max(es)-min(es)), + paste('Location parameter for daily L/P = ', mu)) + text(mean(cl0), + max(es) - .3 * (max(es) - min(es)), + paste('Scale parameter for daily L/P = ', sigma)) + text(mean(cl0), + max(es) - .4 * (max(es) - min(es)), + paste('Tail index = ', tail.index)) + text(mean(cl0), + max(es) - .5 * (max(es) - min(es)), + paste('Holding period = ', hp, ' days')) + +} \ No newline at end of file Modified: pkg/Dowd/R/FrechetVaR.R =================================================================== --- pkg/Dowd/R/FrechetVaR.R 2015-06-10 21:12:55 UTC (rev 3671) +++ pkg/Dowd/R/FrechetVaR.R 2015-06-11 21:45:59 UTC (rev 3672) @@ -1,6 +1,6 @@ #' Frechet Value at Risk #' -#' Plots the VaR of a portfolio against confidence level assuming extreme losses +#' Estimates the VaR of a portfolio assuming extreme losses #' are Frechet distributed, for specified range of confidence level and a given #' holding period. #' Added: pkg/Dowd/R/FrechetVaRPlot2DCl.R =================================================================== --- pkg/Dowd/R/FrechetVaRPlot2DCl.R (rev 0) +++ pkg/Dowd/R/FrechetVaRPlot2DCl.R 2015-06-11 21:45:59 UTC (rev 3672) @@ -0,0 +1,93 @@ +#' Plots Frechet Value at Risk against Cl +#' +#' Plots the VaR of a portfolio against confidence level assuming extreme losses +#' are Frechet distributed, for specified range of confidence level and a given +#' holding period. +#' +#' Note that the long-right-hand tail is fitted to losses, not profits. +#' +#' +#' @param mu Location parameter for daily L/P +#' @param sigma Scale parameter for daily L/P +#' @param tail.index Tail index +#' @param n Block size from which maxima are drawn +#' @param cl Confidence level and should be a vector +#' @param hp Holding period and should be a scalar +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Embrechts, P., Kluppelberg, C. and Mikosch, T., Modelling Extremal Events for +#' Insurance and Finance. Springer, Berlin, 1997, p. 324. +#' +#' Reiss, R. D. and Thomas, M. Statistical Analysis of Extreme Values from +#' Insurance, Finance, Hydrology and Other Fields, Birkhaueser, Basel, 1997, +#' 15-18. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots VaR against vector of cl assuming Frechet Distribution for given parameters +#' cl <- seq(0.9, .99, .01) +#' FrechetVaRPlot2DCl(3.5, 2.3, 1.6, 10, cl, 30) +#' +#' @export +FrechetVaRPlot2DCl <- function(mu, sigma, tail.index, n, cl, hp){ + + # Check that inputs have correct dimensions + if (!length(mu) == 1) { + stop("mu must be a scalar") + } + if (!length(sigma) == 1) { + stop("sigma must be a scalar") + } + if (!length(tail.index) == 1) { + stop("tail.index must be a scalar") + } + if (!is.vector(cl)) { + stop("cl must be a vector or a scalar") + } + if (!is.vector(hp)) { + stop("hp must be a vector or a scalar") + } + + # Change cl to row vector + cl <- t(as.matrix(cl)) + + # Check that parameters obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (min(tail.index) <= 0) { + stop("Tail index must be greater than 0") + } + if ( max(cl) >= 1){ + stop("Confidence level(s) must be less than 1") + } + if ( min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if ( min(cl) <= 0){ + stop("Holding period(s) must be greater than 0") + } + # VaR estimation + VaR <- mu * matrix(1, 1, length(cl)) - (sigma / tail.index) * + (1 - ( - n * log(cl)) ^ ( - tail.index)) + # Plotting + plot(cl, VaR, type = "l", xlab = "Confidence level", ylab = "VaR", main = "Frechet VaR against confidence level") + text(mean(cl), + max(VaR) - .1*(max(VaR) - min(VaR)), + 'Input parameters') + text(mean(cl), + max(VaR)-.2*(max(VaR)-min(VaR)), + paste('Location parameter for daily L/P = ', mu)) + text(mean(cl), + max(VaR) - .3 * (max(VaR) - min(VaR)), + paste('Scale parameter for daily L/P = ', sigma)) + text(mean(cl), + max(VaR) - .4 * (max(VaR) - min(VaR)), + paste('Tail index = ', tail.index)) + text(mean(cl), + max(VaR) - .5 * (max(VaR) - min(VaR)), + paste('Holding period = ', hp, ' days')) + +} \ No newline at end of file Modified: pkg/Dowd/man/FrechetES.Rd =================================================================== --- pkg/Dowd/man/FrechetES.Rd 2015-06-10 21:12:55 UTC (rev 3671) +++ pkg/Dowd/man/FrechetES.Rd 2015-06-11 21:45:59 UTC (rev 3672) @@ -25,7 +25,7 @@ cl and hp are vectors, returns a matrix of VaRs. } \description{ -Plots the ES of a portfolio against confidence level assuming extreme losses +Estimates the ES of a portfolio assuming extreme losses are Frechet distributed, for specified confidence level and a given holding period. } Added: pkg/Dowd/man/FrechetESPlot2DCl.Rd =================================================================== --- pkg/Dowd/man/FrechetESPlot2DCl.Rd (rev 0) +++ pkg/Dowd/man/FrechetESPlot2DCl.Rd 2015-06-11 21:45:59 UTC (rev 3672) @@ -0,0 +1,48 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/FrechetESPlot2DCl.R +\name{FrechetESPlot2DCl} +\alias{FrechetESPlot2DCl} +\title{Plots Frechet Expected Shortfall against confidence level} +\usage{ +FrechetESPlot2DCl(mu, sigma, tail.index, n, cl, hp) +} +\arguments{ +\item{mu}{Location parameter for daily L/P} + +\item{sigma}{Scale parameter for daily L/P} + +\item{tail.index}{Tail index} + +\item{n}{Block size from which maxima are drawn} + +\item{cl}{Confidence level and should be a vector} + +\item{hp}{Holding period} +} +\description{ +Plots the ES of a portfolio against confidence level assuming extreme losses +are Frechet distributed, for specified confidence level and a given +holding period. +} +\details{ +Note that the long-right-hand tail is fitted to losses, not profits. +} +\examples{ +# Plots ES against vector of cl assuming Frechet Distribution for given parameters + cl <- seq(0.9,0.99,0.01) + FrechetESPlot2DCl(3.5, 2.3, 1.6, 10, cl, 30) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Embrechts, P., Kluppelberg, C. and Mikosch, T., Modelling Extremal Events for +Insurance and Finance. Springer, Berlin, 1997, p. 324. + +Reiss, R. D. and Thomas, M. Statistical Analysis of Extreme Values from +Insurance, Finance, Hydrology and Other Fields, Birkhaueser, Basel, 1997, +15-18. +} + Modified: pkg/Dowd/man/FrechetVaR.Rd =================================================================== --- pkg/Dowd/man/FrechetVaR.Rd 2015-06-10 21:12:55 UTC (rev 3671) +++ pkg/Dowd/man/FrechetVaR.Rd 2015-06-11 21:45:59 UTC (rev 3672) @@ -25,7 +25,7 @@ cl and hp are vectors, returns a matrix of VaRs. } \description{ -Plots the VaR of a portfolio against confidence level assuming extreme losses +Estimates the VaR of a portfolio assuming extreme losses are Frechet distributed, for specified range of confidence level and a given holding period. } Added: pkg/Dowd/man/FrechetVaRPlot2DCl.Rd =================================================================== --- pkg/Dowd/man/FrechetVaRPlot2DCl.Rd (rev 0) +++ pkg/Dowd/man/FrechetVaRPlot2DCl.Rd 2015-06-11 21:45:59 UTC (rev 3672) @@ -0,0 +1,48 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/FrechetVaRPlot2DCl.R +\name{FrechetVaRPlot2DCl} +\alias{FrechetVaRPlot2DCl} +\title{Plots Frechet Value at Risk against Cl} +\usage{ +FrechetVaRPlot2DCl(mu, sigma, tail.index, n, cl, hp) +} +\arguments{ +\item{mu}{Location parameter for daily L/P} + +\item{sigma}{Scale parameter for daily L/P} + +\item{tail.index}{Tail index} + +\item{n}{Block size from which maxima are drawn} + +\item{cl}{Confidence level and should be a vector} + +\item{hp}{Holding period and should be a scalar} +} +\description{ +Plots the VaR of a portfolio against confidence level assuming extreme losses +are Frechet distributed, for specified range of confidence level and a given +holding period. +} +\details{ +Note that the long-right-hand tail is fitted to losses, not profits. +} +\examples{ +# Plots VaR against vector of cl assuming Frechet Distribution for given parameters + cl <- seq(0.9, .99, .01) + FrechetVaRPlot2DCl(3.5, 2.3, 1.6, 10, cl, 30) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Embrechts, P., Kluppelberg, C. and Mikosch, T., Modelling Extremal Events for +Insurance and Finance. Springer, Berlin, 1997, p. 324. + +Reiss, R. D. and Thomas, M. Statistical Analysis of Extreme Values from +Insurance, Finance, Hydrology and Other Fields, Birkhaueser, Basel, 1997, +15-18. +} + From noreply at r-forge.r-project.org Fri Jun 12 18:43:18 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 12 Jun 2015 18:43:18 +0200 (CEST) Subject: [Returnanalytics-commits] r3673 - in pkg/Meucci: . R demo man Message-ID: <20150612164318.9A93E185852@r-forge.r-project.org> Author: xavierv Date: 2015-06-12 18:43:18 +0200 (Fri, 12 Jun 2015) New Revision: 3673 Modified: pkg/Meucci/NAMESPACE pkg/Meucci/R/CmaCopula.R pkg/Meucci/R/EntropyProg.R pkg/Meucci/R/PlotDistributions.R pkg/Meucci/R/Prior2Posterior.R pkg/Meucci/R/data.R pkg/Meucci/R/pHistPriorPosterior.R pkg/Meucci/demo/00Index pkg/Meucci/demo/AnalyticalvsNumerical.R pkg/Meucci/demo/HermiteGrid_demo.R pkg/Meucci/man/BlackLittermanFormula.Rd pkg/Meucci/man/BlackScholesCallPrice.Rd pkg/Meucci/man/CMAcombination.Rd pkg/Meucci/man/CMAseparation.Rd pkg/Meucci/man/Central2Raw.Rd pkg/Meucci/man/CentralAndStandardizedStatistics.Rd pkg/Meucci/man/ComputeCVaR.Rd pkg/Meucci/man/ComputeMVE.Rd pkg/Meucci/man/ComputeMoments.Rd pkg/Meucci/man/CondProbViews.Rd pkg/Meucci/man/ConvertChangeInYield2Price.Rd pkg/Meucci/man/ConvertCompoundedReturns2Price.Rd pkg/Meucci/man/Cumul2Raw.Rd pkg/Meucci/man/DetectOutliersViaMVE.Rd pkg/Meucci/man/DoubleDecay.Rd pkg/Meucci/man/EfficientFrontierPrices.Rd pkg/Meucci/man/EfficientFrontierReturns.Rd pkg/Meucci/man/EfficientFrontierReturnsBenchmark.Rd pkg/Meucci/man/EntropyProg.Rd pkg/Meucci/man/Equities.Rd pkg/Meucci/man/Fit2Moms.Rd pkg/Meucci/man/FitExpectationMaximization.Rd pkg/Meucci/man/FitMultivariateGarch.Rd pkg/Meucci/man/FitOU.Rd pkg/Meucci/man/FitOrnsteinUhlenbeck.Rd pkg/Meucci/man/GenFirstEigVect.Rd pkg/Meucci/man/GenPCBasis.Rd pkg/Meucci/man/GenerateLogNormalDistribution.Rd pkg/Meucci/man/GenerateUniformDrawsOnUnitSphere.Rd pkg/Meucci/man/HorizonPricing.Rd pkg/Meucci/man/InterExtrapolate.Rd pkg/Meucci/man/LeastInfoKernel.Rd pkg/Meucci/man/Log2Lin.Rd pkg/Meucci/man/LognormalCopulaPdf.Rd pkg/Meucci/man/LognormalMoments2Parameters.Rd pkg/Meucci/man/LognormalParam2Statistics.Rd pkg/Meucci/man/LongShortMeanCVaRFrontier.Rd pkg/Meucci/man/MaxEntropy.Rd pkg/Meucci/man/MaxRsqCS.Rd pkg/Meucci/man/MaxRsqTS.Rd pkg/Meucci/man/MeanTCEntropyFrontier.Rd pkg/Meucci/man/MleRecursionForStudentT.Rd pkg/Meucci/man/MvnRnd.Rd pkg/Meucci/man/NoisyObservations.Rd pkg/Meucci/man/NormalCopulaPdf.Rd pkg/Meucci/man/OUstep.Rd pkg/Meucci/man/OUstepEuler.Rd pkg/Meucci/man/PanicCopula.Rd pkg/Meucci/man/PartialConfidencePosterior.Rd pkg/Meucci/man/PerformIidAnalysis.Rd pkg/Meucci/man/PlotCompositionEfficientFrontier.Rd pkg/Meucci/man/PlotDistributions.Rd pkg/Meucci/man/PlotFrontier.Rd pkg/Meucci/man/PlotMarginalsNormalInverseWishart.Rd pkg/Meucci/man/PlotResults.Rd pkg/Meucci/man/PlotVolVsCompositionEfficientFrontier.Rd pkg/Meucci/man/Prior2Posterior.Rd pkg/Meucci/man/ProjectionStudentT.Rd pkg/Meucci/man/QuantileMixture.Rd pkg/Meucci/man/RIEfficientFrontier.Rd pkg/Meucci/man/RandNormalInverseWishart.Rd pkg/Meucci/man/Raw2Central.Rd pkg/Meucci/man/Raw2Cumul.Rd pkg/Meucci/man/RejectOutlier.Rd pkg/Meucci/man/SimulateJumpDiffusionMerton.Rd pkg/Meucci/man/StockSeries.Rd pkg/Meucci/man/StudentTCopulaPdf.Rd pkg/Meucci/man/SummStats.Rd pkg/Meucci/man/TimeSeries.Rd pkg/Meucci/man/Tweak.Rd pkg/Meucci/man/TwoDimEllipsoid.Rd pkg/Meucci/man/UsSwapRates.Rd pkg/Meucci/man/ViewCurveSlope.Rd pkg/Meucci/man/ViewImpliedVol.Rd pkg/Meucci/man/ViewRanking.Rd pkg/Meucci/man/ViewRealizedVol.Rd pkg/Meucci/man/bondAttribution.Rd pkg/Meucci/man/butterfliesAnalytics.Rd pkg/Meucci/man/covNRets.Rd pkg/Meucci/man/db.Rd pkg/Meucci/man/dbFFP.Rd pkg/Meucci/man/db_FX.Rd pkg/Meucci/man/derivatives.Rd pkg/Meucci/man/efficientFrontier.Rd pkg/Meucci/man/fILMR.Rd pkg/Meucci/man/factorsDistribution.Rd pkg/Meucci/man/fixedIncome.Rd pkg/Meucci/man/freaqEst.Rd pkg/Meucci/man/garch1f4.Rd pkg/Meucci/man/garch2f8.Rd pkg/Meucci/man/gaussHermiteMesh.Rd pkg/Meucci/man/hermitePolynomial.Rd pkg/Meucci/man/highYieldIndices.Rd pkg/Meucci/man/implVol.Rd pkg/Meucci/man/integrateSubIntervals.Rd pkg/Meucci/man/kernelbw.Rd pkg/Meucci/man/kernelcdf.Rd pkg/Meucci/man/kernelinv.Rd pkg/Meucci/man/kernelpdf.Rd pkg/Meucci/man/linearModel.Rd pkg/Meucci/man/linreturn.Rd pkg/Meucci/man/normalizeProb.Rd pkg/Meucci/man/pHist.Rd pkg/Meucci/man/pHistPriorPosterior.Rd pkg/Meucci/man/private_fun.Rd pkg/Meucci/man/returnsDistribution.Rd pkg/Meucci/man/robustBayesianPortfolioOptimization.Rd pkg/Meucci/man/sectorsSnP500.Rd pkg/Meucci/man/sectorsTS.Rd pkg/Meucci/man/securitiesIndustryClassification.Rd pkg/Meucci/man/securitiesTS.Rd pkg/Meucci/man/std.Rd pkg/Meucci/man/subIntervals.Rd pkg/Meucci/man/swap2y4y.Rd pkg/Meucci/man/swapParRates.Rd pkg/Meucci/man/swaps.Rd Log: Ported Torsion and Inverse Call papers, formatted AnalyticalvsNumerical and its dependencies Modified: pkg/Meucci/NAMESPACE =================================================================== --- pkg/Meucci/NAMESPACE 2015-06-11 21:45:59 UTC (rev 3672) +++ pkg/Meucci/NAMESPACE 2015-06-12 16:43:18 UTC (rev 3673) @@ -1,3 +1,5 @@ +# Generated by roxygen2 (4.1.1): do not edit by hand + export(BlackLittermanFormula) export(BlackScholesCallPrice) export(BlackScholesCallPutPrice) @@ -2,9 +4,9 @@ export(BlackScholesPutPrice) +export(CMAcombination) +export(CMAseparation) export(Central2Raw) export(CentralAndStandardizedStatistics) -export(CMAcombination) -export(CMAseparation) export(ComputeCVaR) +export(ComputeMVE) export(ComputeMoments) -export(ComputeMVE) export(CondProbViews) @@ -15,6 +17,7 @@ export(Cumul2Raw) export(DetectOutliersViaMVE) export(DoubleDecay) +export(EffectiveBets) export(EfficientFrontierPrices) export(EfficientFrontierReturns) export(EfficientFrontierReturnsBenchmark) @@ -23,16 +26,12 @@ export(FitExpectationMaximization) export(FitMultivariateGarch) export(FitOrnsteinUhlenbeck) -export(garch1f4) -export(garch2f8) export(GenerateLogNormalDistribution) export(GenerateUniformDrawsOnUnitSphere) -export(hermitePolynomial) export(HorizonPricing) -export(integrateSubIntervals) export(InterExtrapolate) +export(InverseCallTransformation) export(LeastInfoKernel) -export(linreturn) export(Log2Lin) export(LognormalCopulaPdf) export(LognormalMoments2Parameters) @@ -44,11 +43,9 @@ export(MvnRnd) export(NoisyObservations) export(NormalCopulaPdf) -export(normalizeProb) export(PanicCopula) export(PartialConfidencePosterior) export(PerformIidAnalysis) -export(pHistPriorPosterior) export(PlotCompositionEfficientFrontier) export(PlotDistributions) export(PlotFrontier) @@ -57,19 +54,27 @@ export(Prior2Posterior) export(ProjectionStudentT) export(QuantileMixture) +export(RIEfficientFrontier) export(RandNormalInverseWishart) export(Raw2Central) export(Raw2Cumul) export(RejectOutlier) -export(RIEfficientFrontier) -export(robustBayesianPortfolioOptimization) export(SimulateJumpDiffusionMerton) -export(std) export(StudentTCopulaPdf) -export(subIntervals) export(SummStats) +export(Torsion) export(Tweak) export(TwoDimEllipsoid) export(ViewCurveSlope) export(ViewImpliedVol) export(ViewRealizedVol) +export(garch1f4) +export(garch2f8) +export(hermitePolynomial) +export(integrateSubIntervals) +export(linreturn) +export(normalizeProb) +export(pHistPriorPosterior) +export(robustBayesianPortfolioOptimization) +export(std) +export(subIntervals) Modified: pkg/Meucci/R/CmaCopula.R =================================================================== --- pkg/Meucci/R/CmaCopula.R 2015-06-11 21:45:59 UTC (rev 3672) +++ pkg/Meucci/R/CmaCopula.R 2015-06-12 16:43:18 UTC (rev 3673) @@ -212,7 +212,7 @@ # Aeq %*% p_ # equals the expectations in beq # meanPriorReturnScenarios = apply( Aeq[ -1 , ] , 2 , mean ) # mean return for j'th prior scenario (distribution remains unaltered) # meanPriorReturnScenarios %*% p_ # expected portfolio return with new probabilities at each scenario - # breaks = pHist( meanPriorReturnScenarios , p_ , round( 10 * log(J)) , freq = FALSE )$Breaks + # breaks = PHist( meanPriorReturnScenarios , p_ , round( 10 * log(J)) , freq = FALSE )$Breaks # weighted.hist( meanPriorReturnScenarios, p_ , breaks , freq = FALSE ) # create weighted histogram. TODO: FIX. Cannot abline the expected portfolio return # bin <- cut( meanPriorReturnScenarios , breaks , include.lowest = TRUE) @@ -270,8 +270,8 @@ R_w = Y %*% w # Range is from -.18 to .18 meanReturn = mean( R_w ) - histOld = pHist( R_w , p , round( 10 * log(J)) , freq = FALSE ) # barplot with old probabilities - histNew = pHist( R_w , p_ , round( 10 * log(J)) , freq = FALSE ) # barplot with new probabilities + histOld = PHist( R_w , p , round( 10 * log(J)) , freq = FALSE ) # barplot with old probabilities + histNew = PHist( R_w , p_ , round( 10 * log(J)) , freq = FALSE ) # barplot with new probabilities print( histOld$Plot ) print( histNew$Plot ) # abline( v = mean( R_w ) , col = "blue" ) Modified: pkg/Meucci/R/EntropyProg.R =================================================================== --- pkg/Meucci/R/EntropyProg.R 2015-06-11 21:45:59 UTC (rev 3672) +++ pkg/Meucci/R/EntropyProg.R 2015-06-12 16:43:18 UTC (rev 3673) @@ -1,191 +1,306 @@ -#' Entropy pooling program for blending views on scenarios with a prior scenario-probability distribution +#' @title Compute posterior (=change of measure) with Entropy Pooling. #' -#' Entropy program will change the initial predictive distribution 'p' to a new set 'p_' that satisfies -#' specified moment conditions but changes other propoerties of the new distribution the least by -#' minimizing the relative entropy between the two distributions. Theoretical note: Relative Entropy (Kullback-Leibler information criterion KLIC) is an -#' asymmetric measure. +#' @description +#' Entropy Pooling program for blending views on scenarios with a +#' prior scenario-probability distribution. #' -#' We retrieve a new set of probabilities for the joint-scenarios using the Entropy pooling method -#' Of the many choices of 'p' that satisfy the views, we choose 'p' that minimize the entropy or distance of the new probability -#' distribution to the prior joint-scenario probabilities -#' We use Kullback-Leibler divergence or relative entropy dist(p,q): Sum across all scenarios [ p-t * ln( p-t / q-t ) ] -#' Therefore we define solution as p* = argmin (choice of p ) [ sum across all scenarios: p-t * ln( p-t / q-t) ], -#' such that 'p' satisfies views. The views modify the prior in a cohrent manner (minimizing distortion) -#' We forumulate the stress tests of the baseline scenarios as linear constraints on yet-to-be defined probabilities -#' Note that the numerical optimization acts on a very limited number of variables equal -#' to the number of views. It does not act directly on the very large number of variables -#' of interest, namely the probabilities of the Monte Carlo scenarios. This feature guarantees -#' the numerical feasability of entropy optimization -#' Note that new probabilities are generated in much the same way that the state-price density modifies -#' objective probabilities of pay-offs to risk-neutral probabilities in contingent-claims asset pricing +#' @details +#' The entropy program will change the initial predictive distribution 'p' to a +#' new set 'p_' that satisfies specified moment conditions but changes other +#' properties of the new distribution, the least by minimizing the relative +#' entropy between the two distributions. Theoretical note: Relative Entropy +#' (Kullback-Leibler information criterion KLIC) is an asymmetric measure. #' -#' Compute posterior (=change of measure) with Entropy Pooling, as described in +#' We retrieve a new set of probabilities for the joint-scenarios using the +#' Entropy pooling method of the many choices of 'p' that satisfy the views, +#' we choose a 'p' that minimize the entropy or distance of the new probability +#' distribution to the prior joint-scenario probabilities, we use the +#' Kullback-Leibler divergence or the relative entropy dist(p,q): Sum across all +#' scenarios [p-t * ln( p-t / q-t)]. Therefore we define solution as +#' p* = argmin (choice of p) [sum across all scenarios: p-t * ln( p-t / q-t)], +#' such that 'p' satisfies views. The views modify the prior in a coherent +#' manner (minimizing distortion). We formulate the stress tests of the baseline +#' scenarios as linear constraints on yet-to-be defined probabilities. #' -#' @param p a vector of initial probabilities based on prior (reference model, empirical distribution, etc.). Sum of 'p' must be 1 -#' @param Aeq matrix consisting of equality constraints (paired with argument 'beq'). Denoted as 'H' in the Meucci paper. (denoted as 'H' in the "Meucci - Flexible Views Theory & Practice" paper formlua 86 on page 22) -#' @param beq vector corresponding to the matrix of equality constraints (paired with argument 'Aeq'). Denoted as 'h' in the Meucci paper -#' @param A matrix consisting of inequality constraints (paired with argument 'b'). Denoted as 'F' in the Meucci paper -#' @param b vector consisting of inequality constraints (paired with matrix A). Denoted as 'f' in the Meucci paper +#' Note that the numerical optimization acts on a very limited number of +#' variables equal to the number of views. It does not act directly on the very +#' large number of variables of interest, namely the probabilities of the Monte +#' Carlo scenarios. This feature guarantees the numerical feasability of entropy +#' optimization. #' -#' ' \deqn{ \tilde{p} \equiv argmin_{Fx \leq f, Hx \equiv h} \big\{ \sum_1^J x_{j} \big(ln \big( x_{j} \big) - ln \big( p_{j} \big) \big) \big\} -#' \\ \ell \big(x, \lambda, \nu \big) \equiv x' \big(ln \big(x\big) - ln \big(p\big) \big) + \lambda' \big(Fx - f\big) + \nu' \big(Hx - h\big)} -#' @return a list with -#' p_ revised probabilities based on entropy pooling -#' optimizationPerformance a list with status of optimization, value, number of iterations and sum of probabilities. +#' Note that new probabilities are generated in much the same way that the +#' state-price density modifies objective probabilities of pay-offs to +#' risk-neutral probabilities in contingent-claims asset pricing. +#' +#' +#' @param p a vector of initial probabilities based on prior (reference +#' model, empirical distribution, etc.). Sum of 'p' must be 1 +#' @param Aeq matrix consisting of equality constraints (paired with +#' argument 'beq'). Denoted as 'H' in the Meucci paper. +#' (denoted as 'H' in the "Meucci - Flexible Views Theory & +#' Practice" paper formlua 86 on page 22) +#' +#' @param beq vector corresponding to the matrix of equality constraints +#' (paired with argument 'Aeq'). Denoted as 'h' in the paper +#' @param A matrix consisting of inequality constraints (paired with +#' argument 'b'). Denoted as 'F' in the Meucci paper +#' @param b vector consisting of inequality constraints (paired with +#' matrix A). Denoted as 'f' in the Meucci paper +#' +#' \deqn{ \tilde{p} \equiv argmin_{Fx \leq f, Hx \equiv h} \big\{ \sum_1^J +#' x_{j} \big(ln \big( x_{j} \big) - ln \big( p_{j} \big) \big) \big\} \\ +#' \ell \big(x, \lambda, \nu \big) \equiv x' \big(ln \big(x\big) - ln +#' \big(p\big) \big) + \lambda' \big(Fx - f\big) + \nu' \big(Hx - h\big)} +#' +#' @return p_ revised probabilities based on entropy +#' pooling +#' @return optimizationPerformance a list with status of optimization, +#' value, number of iterations and sum of +#' probabilities. +#' #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} +#' #' @references -#' A. Meucci - "Fully Flexible Views: Theory and Practice". See page 22 for illustration of numerical implementation -#' Symmys site containing original MATLAB source code \url{http://www.symmys.com} -#' NLOPT open-source optimization site containing background on algorithms \url{http://ab-initio.mit.edu/wiki/index.php/NLopt} +#' A. Meucci - "Fully Flexible Views: Theory and Practice". See page 22 for +#' illustration of numerical implementation +#' +#' Symmys site containing original MATLAB code \url{http://www.symmys.com} +#' +#' NLOPT open-source optimization site containing background on algorithms +#' \url{http://ab-initio.mit.edu/wiki/index.php/NLopt} +#' #' We use the information-theoretic estimator of Kitamur and Stutzer (1997). -#' Reversing 'p' and 'p_' leads to the empirical likelihood" estimator of Qin and Lawless (1994). -#' See Robertson et al, "Forecasting Using Relative Entropy" (2002) for more theory -#' @export -EntropyProg = function( p , A = NULL , b = NULL , Aeq , beq ) -{ - library( nloptr ) +#' +#' Reversing 'p' and 'p_' leads to the empirical likelihood" estimator of Qin +#' and Lawless (1994). +#' +#' See Robertson et al, "Forecasting Using Relative Entropy" (2002) for theory +#' +#' @export - if( !length(b) ) A = matrix( ,nrow = 0, ncol = 0) - if( !length(b) ) b = matrix( ,nrow = 0, ncol = 0) - # count the number of constraints - K_ = nrow( A ) # K_ is the number of inequality constraints in the matrix-vector pair A-b - K = nrow( Aeq ) # K is the number of equality views in the matrix-vector pair Aeq-beq - - # parameter checks - if ( K_ + K == 0 ) { stop( "at least one equality or inequality constraint must be specified")} - if ( ( ( .999999 < sum(p)) & (sum(p) < 1.00001) ) == FALSE ) { stop( "sum of probabilities from prior distribution must equal 1")} - if ( nrow(Aeq)!=nrow(beq) ) { stop( "number of inequality constraints in matrix Aeq must match number of elements in vector beq") } - if ( nrow(A)!=nrow(b) ) { stop( "number of equality constraints in matrix A must match number of elements in vector b") } - - # calculate derivatives of constraint matrices - A_ = t( A ) - b_ = t( b ) - Aeq_ = t( Aeq ) - beq_ = t( beq ) - - # starting guess for optimization search with length = to number of views - x0 = matrix( 0 , nrow = K_ + K , ncol = 1 ) - - if ( !K_ ) # equality constraints only - { - # define maximum likelihood, gradient, and hessian functions for unconstrained and constrained optimization - eval_f_list = function( v ) # cost function for unconstrained optimization (no inequality constraints) - { - x = exp( log(p) - 1 - Aeq_ %*% v ) - x = apply( cbind( x , 10^-32 ) , 1 , max ) # robustification - # L is the Lagrangian dual function (without inequality constraints). See formula 88 on p. 22 in "Meucci - Fully Flexible Views - Theory and Practice (2010)" - # t(x) is the derivative x' - # Aeq_ is the derivative of the Aeq matrix of equality constraints (denoted as 'H in the paper) - # beq_ is the transpose of the vector associated with Aeq equality constraints - # L= x' * ( log(x) - log(p) + Aeq_ * v ) - beq_ * v - # 1xJ * ( Jx1 - Jx1 + JxN+1 * N+1x1 ) - 1xN+1 * N+1x1 - L = t(x) %*% ( log(x) - log(p) + Aeq_ %*% v ) - beq_ %*% v - mL = -L # take negative values since we want to maximize - - # evaluate gradient - gradient = beq - Aeq %*% x - - # evaluate Hessian - # We comment this out for now -- to be used when we find an optimizer that can utilize the Hessian in addition to the gradient - # H = ( Aeq %*% (( x %*% ones(1,K) ) * Aeq_) ) # Hessian computed by Chen Qing, Lin Daimin, Meng Yanyan, Wang Weijun - - return( list( objective = mL , gradient = gradient ) ) - } - - # setup unconstrained optimization - start = Sys.time() - opts = list( algorithm = "NLOPT_LD_LBFGS" , xtol_rel = 1.0e-6 , - check_derivatives = TRUE , check_derivatives_print = "all" , print_level = 2 , maxeval = 1000 ) - optimResult = nloptr(x0 = x0, eval_f = eval_f_list , opts = opts ) - end = Sys.time() - print( c("Optimization completed in " , end - start )) ; rm( start ) ; rm( end ) - - if ( optimResult$status < 0 ) { print( c("Exit code " , optimResult$status ) ) ; stop( "Error: The optimizer did not converge" ) } - - # return results of optimization - v = optimResult$solution - p_ = exp( log(p) - 1 - Aeq_ %*% v ) - optimizationPerformance = list( converged = (optimResult$status > 0) , ml = optimResult$objective , iterations = optimResult$iterations , sumOfProbabilities = sum( p_ ) ) - }else # case inequality constraints are specified - { - # setup variables for constrained optimization - InqMat = -diag( 1 , K_ + K ) # -1 * Identity Matrix with dimension equal to number of constraints - InqMat = InqMat[ -c( K_+1:nrow( InqMat ) ) , ] # drop rows corresponding to equality constraints - InqVec = matrix( 0 , K_ , 1 ) - - # define maximum likelihood, gradient, and hessian functions for constrained optimization - InqConstraint = function( x ) { return( InqMat %*% x ) } # function used to evalute A %*% x <= 0 or A %*% x <= c(0,0) if there is more than one inequality constraint - - jacobian_constraint = function( x ) { return( InqMat ) } - # Jacobian of the constraints matrix. One row per constraint, one column per control parameter (x1,x2) - # Turns out the Jacobian of the constraints matrix is always equal to InqMat - - nestedfunC = function( lv ) - { - lv = as.matrix( lv ) - l = lv[ 1:K_ , , drop = FALSE ] # inequality Lagrange multiplier - v = lv[ (K_+1):length(lv) , , drop = FALSE ] # equality lagrange multiplier - x = exp( log(p) - 1 - A_ %*% l - Aeq_ %*% v ) - x = apply( cbind( x , 10^-32 ) , 1 , max ) - - # L is the cost function used for constrained optimization - # L is the Lagrangian dual function with inequality constraints and equality constraints - L = t(x) %*% ( log(x) - log(p) ) + t(l) %*% (A %*% x-b) + t(v) %*% (Aeq %*% x-beq) - objective = -L # take negative values since we want to maximize - - # calculate the gradient - gradient = rbind( b - A%*%x , beq - Aeq %*% x ) - - # compute the Hessian (commented out since no R optimizer supports use of Hessian) - # Hessian computed by Chen Qing, Lin Daimin, Meng Yanyan, Wang Weijun - #onesToK_ = array( rep( 1 , K_ ) ) ;onesToK = array( rep( 1 , K ) ) - #x = as.matrix( x ) - #H11 = A %*% ((x %*% onesToK_) * A_) ; H12 = A %*% ((x %*% onesToK) * Aeq_) - #H21 = Aeq %*% ((x %*% onesToK_) * A_) ; H22 = Aeq %*% ((x %*% onesToK) * Aeq_) - #H1 = cbind( H11 , H12 ) ; H2 = cbind( H21 , H22 ) ; H = rbind( H1 , H2 ) # Hessian for constrained optimization - return( list( objective = objective , gradient = gradient ) ) - } - - # find minimum of constrained multivariate function - start = Sys.time() - # Note: other candidates for constrained optimization in library nloptr: NLOPT_LD_SLSQP, NLOPT_LD_MMA, NLOPT_LN_AUGLAG, NLOPT_LD_AUGLAG_EQ - # See NLOPT open-source site for more details: http://ab-initio.mit.edu/wiki/index.php/NLopt - local_opts <- list( algorithm = "NLOPT_LD_SLSQP", xtol_rel = 1.0e-6 , - check_derivatives = TRUE , check_derivatives_print = "all" , - eval_f = nestedfunC , eval_g_ineq = InqConstraint , eval_jac_g_ineq = jacobian_constraint ) - optimResult = nloptr( x0 = x0 , eval_f = nestedfunC , eval_g_ineq = InqConstraint , eval_jac_g_ineq = jacobian_constraint , - opts = list( algorithm = "NLOPT_LD_AUGLAG" , local_opts = local_opts , - print_level = 2 , maxeval = 1000 , - check_derivatives = TRUE , check_derivatives_print = "all" , xtol_rel = 1.0e-6 ) ) - end = Sys.time() - print( c("Optimization completed in " , end - start )) ; rm( start ) ; rm( end ) - - if ( optimResult$status < 0 ) { print( c("Exit code " , optimResult$status ) ) ; stop( "Error: The optimizer did not converge" ) } - - # return results of optimization - lv = matrix( optimResult$solution , ncol = 1 ) - l = lv[ 1:K_ , , drop = FALSE ] # inequality Lagrange multipliers - v = lv[ (K_+1):nrow( lv ) , , drop = FALSE ] # equality Lagrange multipliers - p_ = exp( log(p) -1 - A_ %*% l - Aeq_ %*% v ) - optimizationPerformance = list( converged = (optimResult$status > 0) , ml = optimResult$objective , iterations = optimResult$iterations , sumOfProbabilities = sum( p_ ) ) +EntropyProg <- function(p, A = NULL, b = NULL, Aeq, beq) { + + if(!length(A)) + A <- matrix(,nrow = 0, ncol = 0) + if(!length(b)) + b <- matrix(,nrow = 0, ncol = 0) + + # count the number of constraints + # K_ is the number of inequality constraints in the matrix-vector pair A-b + K_ <- nrow(A) + # K is the number of equality views in the matrix-vector pair Aeq-beq + K <- nrow(Aeq) + + # parameter checks + if (K_ + K == 0) + stop("at least one equality or inequality constraint must be specified") + + if (((.999999 < sum(p)) & (sum(p) < 1.00001)) == FALSE) + stop("sum of probabilities from prior distribution must equal 1") + + if (nrow(Aeq) != nrow(beq)){ + stop("number of inequality constraints in matrix Aeq must match + number of elements in vector beq") + } + if (nrow(A) != nrow(b)) { + stop("number of equality constraints in matrix A must match number of + elements in vector b") + } + + # calculate derivatives of constraint matrices + A_ <- t(A) + Aeq_ <- t(Aeq) + beq_ <- t(beq) + + # starting guess for optimization search with length = to number of views + x0 <- matrix(0, nrow = K_ + K, ncol = 1) + + # equality constraints only + if (!K_) { + # define maximum likelihood, gradient, and hessian functions for + # unconstrained and constrained optimization + eval_f_list <- function(v) { + # cost function for unconstrained optimization + # (no inequality constraints) + # L: Lagrangian dual function (without inequality constraints) + # See formula 88 on p. 22 in "Meucci - Fully Flexible Views - + # Theory and Practice (2010)". + # t(x): the derivative x' + # Aeq_: the derivative of the Aeq matrix of equality constraints + # (denoted as 'H in the paper) + # beq_: transpose of the vector associated with Aeq equality + # constraints + # L= x' * (log(x) - log(p) + Aeq_ * v) - beq_ * v + # 1xJ * (Jx1 - Jx1 + JxN+1 * N+1x1) - 1xN+1 * N+1x1 + + x <- exp(log(p) - 1 - Aeq_ %*% v) + x <- apply(cbind(x, 10 ^ -32), 1, max) # robustification + L <- t(x) %*% (log(x) - log(p) + Aeq_ %*% v) - beq_ %*% v + mL <- -L # take negative values since we want to maximize + # evaluate gradient + gradient <- beq - Aeq %*% x + + # evaluate Hessian + # We comment this out for now -- to be used when we find an + # optimizer that can utilize the Hessian in addition to the gradient + # H = (Aeq %*% ((x %*% ones(1,K)) * Aeq_)) + # Hessian computed by Chen Qing, Lin Daimin, Meng Yanyan,Wang Weijun + + return(list(objective = mL, gradient = gradient)) } - - print( optimizationPerformance ) - - if ( sum( p_ ) < .999 ) { stop( "Sum or revised probabilities is less than 1!" ) } - if ( sum( p_ ) > 1.001 ) { stop( "Sum or revised probabilities is greater than 1!" ) } - - return ( list ( p_ = p_ , optimizationPerformance = optimizationPerformance ) ) + + # setup unconstrained optimization + start <- Sys.time() + opts <- list(algorithm = "NLOPT_LD_LBFGS", xtol_rel = 1.0e-6, + check_derivatives = TRUE, check_derivatives_print = "all", + print_level = 2, maxeval = 1000) + optimResult <- nloptr(x0 = x0, eval_f = eval_f_list, opts = opts) + end <- Sys.time() + print(c("Optimization completed in ", end - start)) + rm(start) + rm(end) + + if (optimResult$status < 0) { + print(c("Exit code ", optimResult$status)) + stop("Error: The optimizer did not converge") + } + + # return results of optimization + v <- optimResult$solution + p_ <- exp(log(p) - 1 - Aeq_ %*% v) + optimizationPerformance <- list(converged = (optimResult$status > 0), + ml = optimResult$objective, + iterations = optimResult$iterations, + sumOfProbabilities = sum(p_)) + } else { + #--- case inequality constraints are specified + + #-- setup variables for constrained optimization + + # -1 * Identity Matrix with dimension equal to number of constraints + InqMat <- -diag(1, K_ + K) + # drop rows corresponding to equality constraints + InqMat <- InqMat[-c(K_ + 1:nrow(InqMat)),] + InqVec <- matrix(0, K_, 1) + + #-- define maximum likelihood, gradient, and hessian functions for + # constrained optimization. + + # function used to evalute A %*% x <= 0 or A %*% x <= c(0,0) if there is + # more than one inequality constraint + InqConstraint <- function(x) { + return(InqMat %*% x) + } + + jacobian_constraint <- function(x) { + return(InqMat) + } + # Jacobian of the constraints matrix. One row per constraint, one column + # per control parameter (x1,x2) + # Turns out the Jacobian of the constraints matrix is always equal to + # InqMat + + nestedfunC <- function(lv) { + lv <- as.matrix(lv) + # inequality Lagrange multiplier + l <- lv[1:K_, , drop = FALSE] + # equality lagrange multiplier + v <- lv[(K_ + 1):length(lv), , drop = FALSE] + x <- exp(log(p) - 1 - A_ %*% l - Aeq_ %*% v) + x <- apply(cbind(x, 10 ^ -32), 1, max) + + # L is the cost function used for constrained optimization. + # L is the Lagrangian dual function with inequality constraints and + # equality constraints + L <- t(x) %*% (log(x) - log(p)) + t(l) %*% (A %*% x - b) + t(v) %*% + (Aeq %*% x - beq) + objective <- -L # take negative values since we want to maximize + + # calculate the gradient + gradient <- rbind(b - A %*% x, beq - Aeq %*% x) + + ##-- compute the Hessian (commented out since no R optimizer + ## supports use of Hessian) + ## Hessian by Chen Qing, Lin Daimin, Meng Yanyan, Wang Weijun + # onesToK_ = array(rep(1, K_)) + # onesToK = array(rep(1, K)) + # x = as.matrix(x) + # H11 = A %*% ((x %*% onesToK_) * A_) + # H12 = A %*% ((x %*% onesToK) * Aeq_) + # H21 = Aeq %*% ((x %*% onesToK_) * A_) + # H22 = Aeq %*% ((x %*% onesToK) * Aeq_) + # H1 = cbind(H11, H12) + # H2 = cbind(H21, H22) + ## H: Hessian for constrained optimization + # H = rbind(H1, H2) + + return(list(objective = objective, gradient = gradient)) + } + + # find minimum of constrained multivariate function + start <- Sys.time() + # Note: other candidates for constrained optimization in library nloptr: + # NLOPT_LD_SLSQP, NLOPT_LD_MMA, NLOPT_LN_AUGLAG, NLOPT_LD_AUGLAG_EQ + # See NLOPT open-source site for more details: + # http://ab-initio.mit.edu/wiki/index.php/NLopt + local_opts <- list(algorithm = "NLOPT_LD_SLSQP", xtol_rel = 1.0e-6, + check_derivatives = TRUE, + check_derivatives_print = "all", eval_f = nestedfunC, + eval_g_ineq = InqConstraint, + eval_jac_g_ineq = jacobian_constraint) + optimResult <- nloptr(x0 = x0, eval_f = nestedfunC, + eval_g_ineq = InqConstraint, + eval_jac_g_ineq = jacobian_constraint, + opts = list(algorithm = "NLOPT_LD_AUGLAG", + local_opts = local_opts, + print_level = 2, maxeval = 1000, + check_derivatives = TRUE, + check_derivatives_print = "all", + xtol_rel = 1.0e-6)) + end <- Sys.time() + print(c("Optimization completed in ", end - start)) + rm(start) + rm(end) + + if (optimResult$status < 0) { + print(c("Exit code ", optimResult$status)) + stop("Error: The optimizer did not converge") + } + + # return results of optimization + + lv <- matrix(optimResult$solution, ncol = 1) + # inequality Lagrange multipliers + l <- lv[1:K_, , drop = FALSE] + # equality Lagrange multipliers + v <- lv[(K_ + 1):nrow(lv), , drop = FALSE] + p_ <- exp(log(p) - 1 - A_ %*% l - Aeq_ %*% v) + optimizationPerformance <- list(converged = (optimResult$status > 0), + ml = optimResult$objective, + iterations = optimResult$iterations, + sumOfProbabilities = sum(p_)) + } + + print(optimizationPerformance) + + if (sum(p_) < .999) + stop("Sum or revised probabilities is less than 1!") + if (sum(p_) > 1.001) + stop("Sum or revised probabilities is greater than 1!") + + return (list (p_ = p_, optimizationPerformance = optimizationPerformance)) } #' Generates histogram #' -#' @param X a vector containing the data points -#' @param p a vector containing the probabilities for each of the data points in X +#' @param X vector containing the data points +#' @param p vector containing the probabilities for each of the data +#' points in X #' @param nBins expected number of Bins the data set is to be broken down into -#' @param freq a boolean variable to indicate whether the graphic is a representation of frequencies +#' @param freq boolean variable to indicate whether the graphic is a +#' representation of frequencies #' #' @return a list with #' f the frequency for each midpoint @@ -194,34 +309,32 @@ #' @references #' \url{http://www.symmys.com} #' See Meucci script pHist.m used for plotting -#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and Xavier Valls \email{flamejat@@gmail.com} +#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and Xavier Valls +#' \email{xaviervallspla@@gmail.com} -pHist = function( X , p , nBins, freq = FALSE ) -{ - if ( length( match.call() ) < 3 ) - { - J = dim( X )[ 1 ] - nBins = round( 10 * log(J) ) +PHist <- function(X, p, nBins, freq = FALSE) { + + if (length(match.call()) < 3) { + J <- dim(X)[1] + nBins <- round(10 * log(J)) } - - dist = hist( x = X , breaks = nBins , plot = FALSE ); - n = dist$counts - x = dist$breaks - D = x[2] - x[1] - - N = length(x) - np = zeros(N , 1) - - for (s in 1:N) - { - # The boolean Index is true is X is within the interval centered at x(s) and within a half-break distance - Index = ( X >= x[s] - D/2 ) & ( X <= x[s] + D/2 ) + + x <- hist(x = X, breaks = nBins, plot = FALSE)$breaks + D <- x[2] - x[1] + + N <- length(x) + np <- zeros(N, 1) + + for (s in 1:N) { + # The boolean Index is true is X is within the interval centered at x(s) and + # within a half-break distance + Index <- (X >= x[s] - D / 2) & (X <= x[s] + D / 2) # np = new probabilities? - np[ s ] = sum( p[ Index ] ) - f = np/D + np[s] <- sum(p[Index]) + f <- np / D } - - plot( x , f , type = "h", main = "Portfolio return distribution") - - return( list( f = f , x = x ) ) + + plot(x, f, type = "h", main = "Portfolio return distribution") + + return(list(f = f, x = x)) } Modified: pkg/Meucci/R/PlotDistributions.R =================================================================== --- pkg/Meucci/R/PlotDistributions.R 2015-06-11 21:45:59 UTC (rev 3672) +++ pkg/Meucci/R/PlotDistributions.R 2015-06-12 16:43:18 UTC (rev 3673) @@ -9,39 +9,36 @@ #' @param Sigma_ a vector containing the posterior standard deviations #' #' @references -#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158} +#' A. Meucci, "Fully Flexible Views: Theory and Practice" +#' \url{http://www.symmys.com/node/158} #' See Meucci script for "PlotDistributions.m" #' #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} #' @export -PlotDistributions = function( X , p , Mu , Sigma , p_ , Mu_ , Sigma_ ) -{ - J = nrow( X ) - N = ncol( X ) - - NBins = round( 10*log( J ) ) - - for ( n in 1:N ) - { +PlotDistributions <- function(X , p , Mu , Sigma , p_ , Mu_ , Sigma_) { + J <- nrow(X) + N <- ncol(X) + + NBins <- round(10 * log(J)) + + for (n in 1:N) { # set ranges - xl = min( X[ , n ] ) - xh = max( X[ , n ] ) - x = as.matrix( seq( from=xl, to=xh, by=(xh-xl) / 100 ) ) - + xl <- min(X[, n]) + xh <- max(X[, n]) + x <- as.matrix(seq(from = xl, to = xh, by = (xh - xl) / 100)) + # posterior numerical - # h3 = pHist(X[ ,n] , p_ , NBins ) - - # posterior analytical - y1 = dnorm( x , Mu_[n] , sqrt( Sigma_[n,n] ) ) - h4 = plot( x , y1, type='l', col='red', xlab='', ylab='' ) - + PHist(X[,n] , p_ , NBins) + + # posterior analytical + y1 <- dnorm(x , Mu_[n] , sqrt(Sigma_[n,n])) + lines(x , y1, type = "l", col = "red", xlab = "", ylab = "") [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3673 From noreply at r-forge.r-project.org Mon Jun 15 12:05:50 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 15 Jun 2015 12:05:50 +0200 (CEST) Subject: [Returnanalytics-commits] r3674 - in pkg/Dowd: . R man Message-ID: <20150615100550.297F3186EF6@r-forge.r-project.org> Author: dacharya Date: 2015-06-15 12:05:49 +0200 (Mon, 15 Jun 2015) New Revision: 3674 Added: pkg/Dowd/R/AdjustedNormalESHotspots.R pkg/Dowd/R/AdjustedNormalVaRHotspots.R pkg/Dowd/man/AdjustedNormalESHotspots.Rd pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd Modified: pkg/Dowd/NAMESPACE pkg/Dowd/R/FrechetVaRPlot2DCl.R pkg/Dowd/man/FrechetVaRPlot2DCl.Rd Log: AdjustedNormalESHotspots, AdjustedNormalVaRHotspots: source and documentation Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-12 16:43:18 UTC (rev 3673) +++ pkg/Dowd/NAMESPACE 2015-06-15 10:05:49 UTC (rev 3674) @@ -1,6 +1,8 @@ # Generated by roxygen2 (4.1.1): do not edit by hand export(ADTestStat) +export(AdjustedNormalESHotspots) +export(AdjustedNormalVaRHotspots) export(BinomialBacktest) export(BlancoIhleBacktest) export(BootstrapES) Added: pkg/Dowd/R/AdjustedNormalESHotspots.R =================================================================== --- pkg/Dowd/R/AdjustedNormalESHotspots.R (rev 0) +++ pkg/Dowd/R/AdjustedNormalESHotspots.R 2015-06-15 10:05:49 UTC (rev 3674) @@ -0,0 +1,114 @@ +#' @title Hotspots for ES adjusted by Cornish-Fisher correction +#' +#' @description Estimates the ES hotspots (or vector of incremental ESs) for a +#' portfolio with portfolio return adjusted for non-normality by Cornish-Fisher +#' corerction, for specified confidence level and holding period. +#' +#' @param vc.matrix Variance covariance matrix for returns +#' @param mu Vector of expected position returns +#' @param skew Return skew +#' @param kurtisos Return kurtosis +#' @param positions Vector of positions +#' @param cl Confidence level and is scalar +#' @param hp Holding period and is scalar +#' +#' @references Dowd, K. Measurh ing Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' +#' @examples +#' +#' # Hotspots for ES for randomly generated portfolio +#' vc.matrix <- matrix(rnorm(16),4,4) +#' return <- rnorm(4) +#' skew <- .5 +#' kurtosis <- 1.2 +#' positions <- c(5,2,6,10) +#' cl <- .95 +#' hp <- 280 +#' AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +#' +#' @export +AdjustedNormalESHotspots <- function(vc.matrix, mu, skew, kurtosis, positions, + cl, hp){ + + # Check that positions vector read as a scalar or row vector + positions <- as.matrix(positions) + if (dim(positions)[1] > dim(positions)[2]){ + positions <- t(positions) + } + + # Check that expected returns vector is read as a scalar or row vector + mu <- as.matrix(mu) + if (dim(mu)[1] > dim(mu)[2]){ + mu <- t(mu) + } + + # Check that dimensions are correct + if (max(dim(mu)) != max(dim(positions))){ + stop("Positions vector and expected returns vector must have same size") + } + if (max(dim(vc.matrix)) != max(dim(positions))){ + stop("Positions vector and expected returns vector must have same size") + } + + # Check that inputs obey sign and value restrictions + if (cl >= 1){ + stop("Confidence level must be less than 1") + } + if (cl <= 0){ + stop("Confidence level must be greater than 0"); + } + if (hp <= 0){ + stop("Holding period must be greater than 0"); + } + + # VaR and ES estimation + # Begin with portfolio ES + z <- qnorm(1 - cl, 0 ,1) + sigma <- positions %*% vc.matrix %*% t(positions)/(sum(positions)^2) # Initial + # standard deviation of portfolio returns + adjustment <- (1 / 6) * (z ^ 2 - 1) * skew + (1 / 24) * (z ^ 3 - 3 * z) * + (kurtosis - 3) - (1 / 36) * (2 * z ^ 3 - 5 * z) * skew ^ 2 + VaR <- - mu %*% t(positions) * hp - (z + adjustment) * sigma * + (sum(positions)^2) * sqrt(hp) # Initial VaR + n <- 1000 # Number of slives into which tail is divided + cl0 <- cl # Initial confidence level + term <- VaR + delta.cl <- (1 - cl) / n # Increment to confidence level + for (k in 1:(n - 1)) { + cl <- cl0 + k * delta.cl # Revised cl + z <- qnorm(1 - cl, 0, 1) + adjustment=(1 / 6) * (z ^ 2 - 1) * skew + (1 / 24) * (z ^ 3 - 3 * z) * + (kurtosis - 3) - (1 / 36) * (2 * z ^ 3 - 5 * z) * skew ^ 2 + term <- term - mu %*% t(positions) * hp - (z + adjustment) * sigma * + (sum(positions)^2) * sqrt(hp) + } + portfolio.ES <- term/n + + # Portfolio ES + es <- double(length(positions)) + ies <- double(length(positions)) + for (j in range(1: length(positions))) { + x <- positions + x[j] <- 0 + sigma <- x %*% vc.matrix %*% t(x) / (sum(x)^2) + term[j] <- - mu %*% t(x) * hp - qnorm(1-cl, 0, 1) * x %*% + vc.matrix %*% t(x) * sqrt(hp) + + for (k in 1:(n - 1)){ + cl <- cl0 + k * delta.cl # Revised cl + z <- qnorm(1-cl, 0, 1) + adjustment=(1 / 6) * (z ^ 2 - 1) * skew + (1 / 24) * (z ^ 3 - 3 * z) * + (kurtosis - 3) - (1 / 36) * (2 * z ^ 3 - 5 * z) * skew ^ 2 + term[j] <- term[j] - mu %*% t(positions) * hp - (z + adjustment) * + sigma * (sum(positions)^2) * sqrt(hp) + } + es[j] <- term[j]/n # ES on portfolio minus position j + ies [j] <- portfolio.ES - es[j] # Incremental ES + + } + y <- ies + return(ies) + +} Added: pkg/Dowd/R/AdjustedNormalVaRHotspots.R =================================================================== --- pkg/Dowd/R/AdjustedNormalVaRHotspots.R (rev 0) +++ pkg/Dowd/R/AdjustedNormalVaRHotspots.R 2015-06-15 10:05:49 UTC (rev 3674) @@ -0,0 +1,85 @@ +#' @title Hotspots for VaR adjusted by Cornish-Fisher correction +#' +#' @description Estimates the VaR hotspots (or vector of incremental VaRs) for a +#' portfolio with portfolio return adjusted for non-normality by Cornish-Fisher +#' corerction, for specified confidence level and holding period. +#' +#' @param vc.matrix Variance covariance matrix for returns +#' @param mu Vector of expected position returns +#' @param skew Return skew +#' @param kurtisos Return kurtosis +#' @param positions Vector of positions +#' @param cl Confidence level and is scalar +#' @param hp Holding period and is scalar +#' +#' @references Dowd, K. Measurh ing Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' +#' @examples +#' +#' # Hotspots for ES for randomly generated portfolio +#' vc.matrix <- matrix(rnorm(16),4,4) +#' return <- rnorm(4) +#' skew <- .5 +#' kurtosis <- 1.2 +#' positions <- c(5,2,6,10) +#' cl <- .95 +#' hp <- 280 +#' AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +#' +#' @export +AdjustedNormalVaRHotspots <- function(vc.matrix, mu, skew, kurtosis, positions, cl, hp){ + + # Check that positions vector read as a scalar or row vector + positions <- as.matrix(positions) + if (dim(positions)[1] > dim(positions)[2]){ + positions <- t(positions) + } + + # Check that expected returns vector is read as a scalar or row vector + mu <- as.matrix(mu) + if (dim(mu)[1] > dim(mu)[2]){ + mu <- t(mu) + } + + # Check that dimensions are correct + if (max(dim(mu)) != max(dim(positions))){ + stop("Positions vector and expected returns vector must have same size") + } + vc.matrix <- as.matrix(vc.matrix) + if (max(dim(vc.matrix)) != max(dim(positions))){ + stop("Positions vector and expected returns vector must have same size") + } + + # Check that inputs obey sign and value restrictions + if (cl >= 1){ + stop("Confidence level must be less than 1") + } + if (cl <= 0){ + stop("Confidence level must be greater than 0"); + } + if (hp <= 0){ + stop("Holding period must be greater than 0"); + } + + # VaR and ES estimation + z <- qnorm(1 - cl, 0 ,1) + sigma <- positions %*% vc.matrix %*% t(positions)/(sum(positions)^2) # Initial standard deviation of portfolio returns + adjustment <- (1 / 6) * (z ^ 2 - 1) * skew + (1 / 24) * (z ^ 3 - 3 * z) * (kurtosis - 3) - (1 / 36) * (2 * z ^ 3 - 5 * z) * skew ^ 2 + VaR <- - mu %*% t(positions) * hp - (z + adjustment) * sigma * (sum(positions)^2) * sqrt(hp) + + # VaR + x <- double(length(positions)) + sigma <- double(length(positions)) + iVaR <- double(length(positions)) + for (i in 1:length(positions)){ + x <- positions + x[i] <- 0 + sigma[i] <- x %*% vc.matrix %*% t(x)/sum(x)^2 # standard deviation of portfolio returns + iVaR[i] <- VaR + mu %*% t(x) %*% hp + (z + adjustment) * sigma[i] * (sum(x))^2 * sqrt(hp) # Incremental VaR + } + y <- iVaR + return(y) + +} \ No newline at end of file Modified: pkg/Dowd/R/FrechetVaRPlot2DCl.R =================================================================== --- pkg/Dowd/R/FrechetVaRPlot2DCl.R 2015-06-12 16:43:18 UTC (rev 3673) +++ pkg/Dowd/R/FrechetVaRPlot2DCl.R 2015-06-15 10:05:49 UTC (rev 3674) @@ -1,6 +1,6 @@ -#' Plots Frechet Value at Risk against Cl +#' @title Plots Frechet Value at Risk against Cl #' -#' Plots the VaR of a portfolio against confidence level assuming extreme losses +#' @description Plots the VaR of a portfolio against confidence level assuming extreme losses #' are Frechet distributed, for specified range of confidence level and a given #' holding period. #' @@ -14,7 +14,7 @@ #' @param cl Confidence level and should be a vector #' @param hp Holding period and should be a scalar #' -#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' @references Dowd, K. Measurh ing Market Risk, Wiley, 2007. #' #' Embrechts, P., Kluppelberg, C. and Mikosch, T., Modelling Extremal Events for #' Insurance and Finance. Springer, Berlin, 1997, p. 324. @@ -24,6 +24,7 @@ #' 15-18. #' #' @author Dinesh Acharya +#' #' @examples #' #' # Plots VaR against vector of cl assuming Frechet Distribution for given parameters Added: pkg/Dowd/man/AdjustedNormalESHotspots.Rd =================================================================== --- pkg/Dowd/man/AdjustedNormalESHotspots.Rd (rev 0) +++ pkg/Dowd/man/AdjustedNormalESHotspots.Rd 2015-06-15 10:05:49 UTC (rev 3674) @@ -0,0 +1,46 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AdjustedNormalESHotspots.R +\name{AdjustedNormalESHotspots} +\alias{AdjustedNormalESHotspots} +\title{Hotspots for ES adjusted by Cornish-Fisher correction} +\usage{ +AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Return skew} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar} + +\item{kurtisos}{Return kurtosis} +} +\description{ +Estimates the ES hotspots (or vector of incremental ESs) for a +portfolio with portfolio return adjusted for non-normality by Cornish-Fisher +corerction, for specified confidence level and holding period. +} +\examples{ +# Hotspots for ES for randomly generated portfolio + vc.matrix <- matrix(rnorm(16),4,4) + return <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,10) + cl <- .95 + hp <- 280 + AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measurh ing Market Risk, Wiley, 2007. +} + Added: pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd =================================================================== --- pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd (rev 0) +++ pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd 2015-06-15 10:05:49 UTC (rev 3674) @@ -0,0 +1,46 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AdjustedNormalVaRHotspots.R +\name{AdjustedNormalVaRHotspots} +\alias{AdjustedNormalVaRHotspots} +\title{Hotspots for VaR adjusted by Cornish-Fisher correction} +\usage{ +AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Return skew} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar} + +\item{kurtisos}{Return kurtosis} +} +\description{ +Estimates the VaR hotspots (or vector of incremental VaRs) for a +portfolio with portfolio return adjusted for non-normality by Cornish-Fisher +corerction, for specified confidence level and holding period. +} +\examples{ +# Hotspots for ES for randomly generated portfolio + vc.matrix <- matrix(rnorm(16),4,4) + return <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,10) + cl <- .95 + hp <- 280 + AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measurh ing Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/FrechetVaRPlot2DCl.Rd =================================================================== --- pkg/Dowd/man/FrechetVaRPlot2DCl.Rd 2015-06-12 16:43:18 UTC (rev 3673) +++ pkg/Dowd/man/FrechetVaRPlot2DCl.Rd 2015-06-15 10:05:49 UTC (rev 3674) @@ -23,8 +23,7 @@ Plots the VaR of a portfolio against confidence level assuming extreme losses are Frechet distributed, for specified range of confidence level and a given holding period. -} -\details{ + Note that the long-right-hand tail is fitted to losses, not profits. } \examples{ @@ -36,7 +35,7 @@ Dinesh Acharya } \references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. +Dowd, K. Measurh ing Market Risk, Wiley, 2007. Embrechts, P., Kluppelberg, C. and Mikosch, T., Modelling Extremal Events for Insurance and Finance. Springer, Berlin, 1997, p. 324. From noreply at r-forge.r-project.org Mon Jun 15 21:18:04 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 15 Jun 2015 21:18:04 +0200 (CEST) Subject: [Returnanalytics-commits] r3675 - in pkg/Dowd: . R man Message-ID: <20150615191804.555611879FF@r-forge.r-project.org> Author: dacharya Date: 2015-06-15 21:18:04 +0200 (Mon, 15 Jun 2015) New Revision: 3675 Added: pkg/Dowd/R/GParetoES.R pkg/Dowd/R/GParetoMEFPlot.R pkg/Dowd/man/GParetoES.Rd pkg/Dowd/man/GParetoMEFPlot.Rd Modified: pkg/Dowd/NAMESPACE Log: GParetoES and GParetoMEFPlot: source and documentation Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-15 10:05:49 UTC (rev 3674) +++ pkg/Dowd/NAMESPACE 2015-06-15 19:18:04 UTC (rev 3675) @@ -22,6 +22,8 @@ export(FrechetESPlot2DCl) export(FrechetVaR) export(FrechetVaRPlot2DCl) +export(GParetoES) +export(GParetoMEFPlot) export(GaussianCopulaVaR) export(GumbelCopulaVaR) export(HSES) Added: pkg/Dowd/R/GParetoES.R =================================================================== --- pkg/Dowd/R/GParetoES.R (rev 0) +++ pkg/Dowd/R/GParetoES.R 2015-06-15 19:18:04 UTC (rev 3675) @@ -0,0 +1,48 @@ +#' @title Expected Shortfall for Generalized Pareto +#' +#' @description Estimates the ES of a portfolio assuming losses are distributed as a generalised Pareto. +#' +#' @param Ra Vector of daily Profit/Loss data +#' @param beta Assumed scale parameter +#' @param zeta Assumed tail index +#' @param threshold.prob Threshold probability +#' @param cl VaR confidence level +#' +#' @return Expected Shortfall +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' McNeil, A., Extreme value theory for risk managers. Mimeo, ETHZ, 1999. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes ES assuming generalised Pareto for following parameters +#' Ra <- 5 * randn(100) +#' beta <- 1.2 +#' zeta <- 1.6 +#' threshold.prob <- .85 +#' cl <- .99 +#' GParetoES(Ra, beta, zeta, threshold.prob, cl) +#' +#' @export +GParetoES <- function(Ra, beta, zeta, threshold.prob, cl){ + + if ( max(cl) >= 1){ + stop("Confidence level(s) must be less than 1") + } + if ( min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + + x <- as.vector(Ra) + n <- length(x) + x <- sort(x) + Nu <- threshold.prob * n + Nu <- ((Nu >= 0) * floor(Nu) + (Nu < 0) * ceiling(Nu)) + u <- x[n - Nu] + y=(u + (beta / zeta) * ((((1 / threshold.prob) * (1 - cl))^(-zeta)) + - 1))/(1 - zeta)+(beta - zeta * u) / (1 - zeta); + return(y) + +} \ No newline at end of file Added: pkg/Dowd/R/GParetoMEFPlot.R =================================================================== --- pkg/Dowd/R/GParetoMEFPlot.R (rev 0) +++ pkg/Dowd/R/GParetoMEFPlot.R 2015-06-15 19:18:04 UTC (rev 3675) @@ -0,0 +1,50 @@ +#' @title Plot of Emperical and Generalised Pareto mean excess functions +#' +#' @description Plots of emperical mean excess function and Generalized mean excess function. +#' +#' @param Ra Vector of daily Profit/Loss data +#' @param mu Location parameter +#' @param beta Scale parameter +#' @param zeta Assumed tail index +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes ES assuming generalised Pareto for following parameters +#' Ra <- 5 * randn(100) +#' mu <- 1 +#' beta <- 1.2 +#' zeta <- 1.6 +#' GParetoMEFPlot(Ra, mu, beta, zeta) +#' +#' @export +GParetoMEFPlot <- function(Ra, mu, beta, zeta) { + x <- as.vector(Ra) + x <- sort(x) + u <- x + n <- length(u) + mef <- double(n - 1) + + for (i in 1:(n - 1)) { + x <- x[which(x > u[i])] + mef[i] <- mean(x) - u[i] + } + + u <- t(u) + u <- u[u!=max(u)] + gpmef <- (1 + zeta * (u - mu) / beta)/(1 - zeta); + # Plot + # Limits of axis + xlims <- c(min(u),max(u)) + ylims <- c(min(mef, gpmef), max(mef, gpmef)) + plot(u , mef, xlims, ylims, type = "l", xlab = "Threshold (u)", + col = 6, ylab = "e(u)") + par(new = TRUE) + plot(u , gpmef, xlims, ylims, type = "l", xlab = "Threshold (u)", + col = 3, ylab = "e(u)") + title("Emperical and Generalised Pareto Mean Excess Functions") + legend("topright", legend = c("Emperical MEF", "Generalized Pareto MEF"), text.col = c(6,3)) + +} \ No newline at end of file Added: pkg/Dowd/man/GParetoES.Rd =================================================================== --- pkg/Dowd/man/GParetoES.Rd (rev 0) +++ pkg/Dowd/man/GParetoES.Rd 2015-06-15 19:18:04 UTC (rev 3675) @@ -0,0 +1,43 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/GParetoES.R +\name{GParetoES} +\alias{GParetoES} +\title{Expected Shortfall for Generalized Pareto} +\usage{ +GParetoES(Ra, beta, zeta, threshold.prob, cl) +} +\arguments{ +\item{Ra}{Vector of daily Profit/Loss data} + +\item{beta}{Assumed scale parameter} + +\item{zeta}{Assumed tail index} + +\item{threshold.prob}{Threshold probability} + +\item{cl}{VaR confidence level} +} +\value{ +Expected Shortfall +} +\description{ +Estimates the ES of a portfolio assuming losses are distributed as a generalised Pareto. +} +\examples{ +# Computes ES assuming generalised Pareto for following parameters + Ra <- 5 * randn(100) + beta <- 1.2 + zeta <- 1.6 + threshold.prob <- .85 + cl <- .99 + GParetoES(Ra, beta, zeta, threshold.prob, cl) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +McNeil, A., Extreme value theory for risk managers. Mimeo, ETHZ, 1999. +} + Added: pkg/Dowd/man/GParetoMEFPlot.Rd =================================================================== --- pkg/Dowd/man/GParetoMEFPlot.Rd (rev 0) +++ pkg/Dowd/man/GParetoMEFPlot.Rd 2015-06-15 19:18:04 UTC (rev 3675) @@ -0,0 +1,35 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/GParetoMEFPlot.R +\name{GParetoMEFPlot} +\alias{GParetoMEFPlot} +\title{Plot of Emperical and Generalised Pareto mean excess functions} +\usage{ +GParetoMEFPlot(Ra, mu, beta, zeta) +} +\arguments{ +\item{Ra}{Vector of daily Profit/Loss data} + +\item{mu}{Location parameter} + +\item{beta}{Scale parameter} + +\item{zeta}{Assumed tail index} +} +\description{ +Plots of emperical mean excess function and Generalized mean excess function. +} +\examples{ +# Computes ES assuming generalised Pareto for following parameters + Ra <- 5 * randn(100) + mu <- 1 + beta <- 1.2 + zeta <- 1.6 + GParetoMEFPlot(Ra, mu, beta, zeta) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jun 16 16:22:15 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 16 Jun 2015 16:22:15 +0200 (CEST) Subject: [Returnanalytics-commits] r3676 - in pkg/Dowd: . R man Message-ID: <20150616142215.14D4C1879E7@r-forge.r-project.org> Author: dacharya Date: 2015-06-16 16:22:14 +0200 (Tue, 16 Jun 2015) New Revision: 3676 Added: pkg/Dowd/R/GParetoMultipleMEFPlot.R pkg/Dowd/R/GParetoVaR.R pkg/Dowd/R/GumbelES.R pkg/Dowd/R/GumbelESPlot2DCl.R pkg/Dowd/R/GumbelVaR.R pkg/Dowd/R/GumbelVaRPlot2DCl.R pkg/Dowd/man/GParetoMultipleMEFPlot.Rd pkg/Dowd/man/GParetoVaR.Rd pkg/Dowd/man/GumbelES.Rd pkg/Dowd/man/GumbelESPlot2DCl.Rd pkg/Dowd/man/GumbelVaR.Rd pkg/Dowd/man/GumbelVaRPlot2DCl.Rd Modified: pkg/Dowd/NAMESPACE pkg/Dowd/R/FrechetES.R pkg/Dowd/R/GParetoMEFPlot.R pkg/Dowd/man/FrechetES.Rd pkg/Dowd/man/GParetoMEFPlot.Rd Log: Gumbel Functions and remaining Gpareto functions: source and documentation. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-15 19:18:04 UTC (rev 3675) +++ pkg/Dowd/NAMESPACE 2015-06-16 14:22:14 UTC (rev 3676) @@ -24,8 +24,14 @@ export(FrechetVaRPlot2DCl) export(GParetoES) export(GParetoMEFPlot) +export(GParetoMultipleMEFPlot) +export(GParetoVaR) export(GaussianCopulaVaR) export(GumbelCopulaVaR) +export(GumbelES) +export(GumbelESPlot2DCl) +export(GumbelVaR) +export(GumbelVaRPlot2DCl) export(HSES) export(HSVaR) export(HillEstimator) Modified: pkg/Dowd/R/FrechetES.R =================================================================== --- pkg/Dowd/R/FrechetES.R 2015-06-15 19:18:04 UTC (rev 3675) +++ pkg/Dowd/R/FrechetES.R 2015-06-16 14:22:14 UTC (rev 3676) @@ -13,7 +13,7 @@ #' @param n Block size from which maxima are drawn #' @param cl Confidence level #' @param hp Holding period -#' @return Value at Risk. If cl and hp are scalars, it returns scalar VaR. If cl +#' @return Estimated ES. If cl and hp are scalars, it returns scalar VaR. If cl #' is vector and hp is a scalar, or viceversa, returns vector of VaRs. If both #' cl and hp are vectors, returns a matrix of VaRs. #' Modified: pkg/Dowd/R/GParetoMEFPlot.R =================================================================== --- pkg/Dowd/R/GParetoMEFPlot.R 2015-06-15 19:18:04 UTC (rev 3675) +++ pkg/Dowd/R/GParetoMEFPlot.R 2015-06-16 14:22:14 UTC (rev 3676) @@ -13,8 +13,8 @@ #' @examples #' #' # Computes ES assuming generalised Pareto for following parameters -#' Ra <- 5 * randn(100) -#' mu <- 1 +#' Ra <- 5 * rnorm(100) +#' mu <- 0 #' beta <- 1.2 #' zeta <- 1.6 #' GParetoMEFPlot(Ra, mu, beta, zeta) Added: pkg/Dowd/R/GParetoMultipleMEFPlot.R =================================================================== --- pkg/Dowd/R/GParetoMultipleMEFPlot.R (rev 0) +++ pkg/Dowd/R/GParetoMultipleMEFPlot.R 2015-06-16 14:22:14 UTC (rev 3676) @@ -0,0 +1,56 @@ +#' @title Plot of Emperical and 2 Generalised Pareto mean excess functions +#' +#' @description Plots of emperical mean excess function and two generalized pareto mean excess functions which differ in their tail-index value. +#' +#' @param Ra Vector of daily Profit/Loss data +#' @param mu Location parameter +#' @param beta Scale parameter +#' @param zeta1 Assumed tail index for first mean excess function +#' @param zeta2 Assumed tail index for second mean excess function +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes ES assuming generalised Pareto for following parameters +#' Ra <- 5 * rnorm(100) +#' mu <- 1 +#' beta <- 1.2 +#' zeta1 <- 1.6 +#' zeta2 <- 2.2 +#' GParetoMultipleMEFPlot(Ra, mu, beta, zeta1, zeta2) +#' +#' @export +GParetoMultipleMEFPlot <- function(Ra, mu, beta, zeta1, zeta2) { + x <- as.vector(Ra) + x <- sort(x) + u <- x + n <- length(u) + mef <- double(n - 1) + + for (i in 1:(n - 1)) { + x <- x[which(x > u[i])] + mef[i] <- mean(x) - u[i] + } + + u <- t(u) + u <- u[u!=max(u)] + gpmef1 <- (1 + zeta1 * (u - mu) / beta)/(1 - zeta1); + gpmef2 <- (1 + zeta2 * (u - mu) / beta)/(1 - zeta2); + # Plot + # Limits of axis + xlims <- c(min(u),max(u)) + ylims <- c(min(mef, gpmef1, gpmef2), max(mef, gpmef1, gpmef2)) + plot(u , mef, xlims, ylims, type = "l", xlab = "Threshold (u)", + col = 5, ylab = "e(u)") + par(new = TRUE) + plot(u , gpmef1, xlims, ylims, type = "l", xlab = "Threshold (u)", + col = 4, ylab = "e(u)") + par(new = TRUE) + plot(u , gpmef2, xlims, ylims, type = "l", xlab = "Threshold (u)", + col = 3, ylab = "e(u)") + title("Emperical and Two Generalised Pareto MEFs") + legend("topright", legend = c("Emperical MEF", "Generalized Pareto MEF1", "Generalized Pareto MEF1"), text.col = c(5,4,3)) + +} \ No newline at end of file Added: pkg/Dowd/R/GParetoVaR.R =================================================================== --- pkg/Dowd/R/GParetoVaR.R (rev 0) +++ pkg/Dowd/R/GParetoVaR.R 2015-06-16 14:22:14 UTC (rev 3676) @@ -0,0 +1,48 @@ +#' @title VaR for Generalized Pareto +#' +#' @description Estimates the Value at Risk of a portfolio assuming losses are +#' distributed as a generalised Pareto. +#' +#' @param Ra Vector of daily Profit/Loss data +#' @param beta Assumed scale parameter +#' @param zeta Assumed tail index +#' @param threshold.prob Threshold probability corresponding to threshold u and +#' x +#' @param cl VaR confidence level +#' +#' @return Expected Shortfall +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' McNeil, A., Extreme value theory for risk managers. Mimeo, ETHZ, 1999. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes ES assuming generalised Pareto for following parameters +#' Ra <- 5 * randn(100) +#' beta <- 1.2 +#' zeta <- 1.6 +#' threshold.prob <- .85 +#' cl <- .99 +#' GParetoVaR(Ra, beta, zeta, threshold.prob, cl) +#' +#' @export +GParetoVaR <- function(Ra, beta, zeta, threshold.prob, cl){ + + if ( max(cl) >= 1){ + stop("Confidence level(s) must be less than 1") + } + if ( min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + + x <- as.vector(Ra) + n <- length(x) + x <- sort(x) + Nu <- threshold.prob * n + Nu <- ((Nu >= 0) * floor(Nu) + (Nu < 0) * ceiling(Nu)) + u <- x[n - Nu] + y <- u+(beta/zeta)*((((1/threshold.prob)*(1-cl))^(-zeta))-1) + +} \ No newline at end of file Added: pkg/Dowd/R/GumbelES.R =================================================================== --- pkg/Dowd/R/GumbelES.R (rev 0) +++ pkg/Dowd/R/GumbelES.R 2015-06-16 14:22:14 UTC (rev 3676) @@ -0,0 +1,77 @@ +#' @title Gumbel ES +#' +#' @description Estimates the ES of a portfolio assuming extreme losses are +#' Gumbel distributed, for specified confidence level and holding period. +#' Note that the long-right-hand tail is fitted to losses, not profits. +#' +#' @param mu Location parameter for daily L/P +#' @param sigma Assumed scale parameter for daily L/P +#' @param n Assumed block size from which the maxima are drawn +#' @param cl VaR confidence level +#' @param hp VaR holding period +#' @return Estimated ES. If cl and hp are scalars, it returns scalar VaR. If cl +#' is vector and hp is a scalar, or viceversa, returns vector of VaRs. If both +#' cl and hp are vectors, returns a matrix of VaRs. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' National Institute of Standards and Technology, Dataplot Reference Manual. Volume 1: Commands. NIST: Washington, DC, 1997, p. 8-67. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Gumber ES Plot +#' GumbelES(0, 1.2, 100, c(.9,.88, .85, .8), 280) +#' +#' @export +GumbelES<- function(mu, sigma, n, cl, hp){ + + # Check that inputs have correct dimensions + if (!length(mu) == 1) { + stop("Mean must be a scalar") + } + if (!length(sigma) == 1) { + stop("Standard Deviation must be a scalar") + } + if (!is.vector(cl)) { + stop("cl must be a vector") + } + if (!length(hp) == 1) { + stop("hp must be a scalar") + } + + # To check that cl is read as a scalar or row vector and hp is read as a scalar of column vector as required + cl <- t(as.matrix(cl)) + hp <- as.matrix(hp) + + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (max(cl) >= 1) { + stop("Confidence levels must be less than 1") + } + if (min(cl) <= 0) { + stop("Confidence levels must be less than 1") + } + if (min(hp) <= 0) { + stop("Holding period must be greated than 0") + } + + # VaR Estimation + VaR <- mu * matrix(1, dim(cl)[1], dim(cl)[2]) - sigma * log(- n * log(cl)); # Gumberl VaR + + # ES Estimation + number.slices <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + term <- VaR + + delta.cl <- (1 - cl)/number.slices # Increment to confidence level as each slice is taken + for (i in 1:(number.slices - 1)) { + cl <- cl0 + i * delta.cl # Revised cl + term <- term + mu * matrix(1, dim(cl)[1], dim(cl)[2]) - sigma * log(-n * log(cl)) # NB Gumber term + } + y <- term / (number.slices - 1) + + return(y) +} \ No newline at end of file Added: pkg/Dowd/R/GumbelESPlot2DCl.R =================================================================== --- pkg/Dowd/R/GumbelESPlot2DCl.R (rev 0) +++ pkg/Dowd/R/GumbelESPlot2DCl.R 2015-06-16 14:22:14 UTC (rev 3676) @@ -0,0 +1,87 @@ +#' @title Gumbel VaR +#' +#' @description Estimates the EV VaR of a portfolio assuming extreme losses are Gumbel distributed, for specified confidence level and holding period. +#' +#' @param mu Location parameter for daily L/P +#' @param sigma Assumed scale parameter for daily L/P +#' @param n size from which the maxima are drawn +#' @param cl VaR confidence level +#' @param hp VaR holding period +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots ES against Cl +#' GumbelESPlot2DCl(0, 1.2, 100, c(.9,.88, .85, .8), 280) +#' +#' @export +GumbelESPlot2DCl<- function(mu, sigma, n, cl, hp){ + + # Check that inputs have correct dimensions + if (!length(mu) == 1) { + stop("Mean must be a scalar") + } + if (!length(sigma) == 1) { + stop("Standard Deviation must be a scalar") + } + if (!is.vector(cl)) { + stop("cl must be a vector") + } + if (!length(hp) == 1) { + stop("hp must be a scalar") + } + + # To check that cl is read as a row vector as required + cl <- t(as.matrix(cl)) + + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (max(cl) >= 1) { + stop("Confidence levels must be less than 1") + } + if (min(cl) <= 0) { + stop("Confidence levels must be less than 1") + } + if (min(hp) <= 0) { + stop("Holding period must be greated than 0") + } + + # VaR Estimation + VaR <- mu * matrix(1, dim(cl)[1], dim(cl)[2]) - sigma * log(- n * log(cl)); + + # ES Estimation + number.slices <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + term <- VaR + + delta.cl <- (1 - cl)/number.slices # Increment to confidence level as each slice is taken + for (i in 1:(number.slices - 1)) { + cl <- cl0 + i * delta.cl # Revised cl + term <- term + mu * matrix(1, dim(cl)[1], dim(cl)[2]) - sigma * log(-n * log(cl)) # NB Gumber term + } + v <- term / (number.slices - 1) + + # Plotting + plot(cl0, v, xlab = "Confidence Level", ylab = "ES", type = "l") + + text(mean(cl0), + max(v) - .1*(max(v) - min(v)), + 'Input parameters') + text(mean(cl0), + max(v)-.2*(max(v)-min(v)), + paste('Location parameter for daily L/P = ', mu)) + text(mean(cl0), + max(v) - .3 * (max(v) - min(v)), + paste('Scale parameter for daily L/P = ', sigma)) + text(mean(cl0), + max(v) - .4 * (max(v) - min(v)), + paste('Holding period = ', hp, ' days')) + + title("Gumbel ES against confidence level") + +} \ No newline at end of file Added: pkg/Dowd/R/GumbelVaR.R =================================================================== --- pkg/Dowd/R/GumbelVaR.R (rev 0) +++ pkg/Dowd/R/GumbelVaR.R 2015-06-16 14:22:14 UTC (rev 3676) @@ -0,0 +1,59 @@ +#' @title Gumbel VaR +#' +#' @description Estimates the EV VaR of a portfolio assuming extreme losses are Gumbel distributed, for specified confidence level and holding period. +#' +#' @param mu Location parameter for daily L/P +#' @param sigma Assumed scale parameter for daily L/P +#' @param n Size from which the maxima are drawn +#' @param cl VaR confidence level +#' @param hp VaR holding period +#' @return Estimated VaR +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Gumbel VaR +#' GumbelVaR(0, 1.2, 100, c(.9,.88, .85, .8), 280) +#' +#' @export +GumbelVaR<- function(mu, sigma, n, cl, hp){ + + # Check that inputs have correct dimensions + if (!length(mu) == 1) { + stop("Mean must be a scalar") + } + if (!length(sigma) == 1) { + stop("Standard Deviation must be a scalar") + } + if (!is.vector(cl)) { + stop("cl must be a vector") + } + if (!length(hp) == 1) { + stop("hp must be a scalar") + } + + # To check that cl is read as a row vector as required + cl <- t(as.matrix(cl)) + + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (max(cl) >= 1) { + stop("Confidence levels must be less than 1") + } + if (min(cl) <= 0) { + stop("Confidence levels must be less than 1") + } + if (min(hp) <= 0) { + stop("Holding period must be greated than 0") + } + + # VaR Estimation + y <- mu * matrix(1, dim(cl)[1], dim(cl)[2]) - sigma * log(- n * log(cl)); + + return(y) +} \ No newline at end of file Added: pkg/Dowd/R/GumbelVaRPlot2DCl.R =================================================================== --- pkg/Dowd/R/GumbelVaRPlot2DCl.R (rev 0) +++ pkg/Dowd/R/GumbelVaRPlot2DCl.R 2015-06-16 14:22:14 UTC (rev 3676) @@ -0,0 +1,74 @@ +#' @title Gumbel VaR +#' +#' @description Estimates the EV VaR of a portfolio assuming extreme losses are Gumbel distributed, for specified confidence level and holding period. +#' +#' @param mu Location parameter for daily L/P +#' @param sigma Assumed scale parameter for daily L/P +#' @param n size from which the maxima are drawn +#' @param cl VaR confidence level +#' @param hp VaR holding period +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots VaR against Cl +#' GumbelVaRPlot2DCl(0, 1.2, 100, c(.9,.88, .85, .8), 280) +#' +#' @export +GumbelVaRPlot2DCl<- function(mu, sigma, n, cl, hp){ + + # Check that inputs have correct dimensions + if (!length(mu) == 1) { + stop("Mean must be a scalar") + } + if (!length(sigma) == 1) { + stop("Standard Deviation must be a scalar") + } + if (!is.vector(cl)) { + stop("cl must be a vector") + } + if (!length(hp) == 1) { + stop("hp must be a scalar") + } + + # To check that cl is read as a row vector as required + cl <- t(as.matrix(cl)) + + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (max(cl) >= 1) { + stop("Confidence levels must be less than 1") + } + if (min(cl) <= 0) { + stop("Confidence levels must be less than 1") + } + if (min(hp) <= 0) { + stop("Holding period must be greated than 0") + } + + # VaR Estimation + VaR <- mu * matrix(1, dim(cl)[1], dim(cl)[2]) - sigma * log(- n * log(cl)); + + # Plotting + plot(cl, VaR, xlab = "Confidence Level", ylab = "VaR", type = "l") + text(mean(cl), + max(VaR) - .1*(max(VaR) - min(VaR)), + 'Input parameters') + text(mean(cl), + max(VaR)-.2*(max(VaR)-min(VaR)), + paste('Location parameter for daily L/P = ', mu)) + text(mean(cl), + max(VaR) - .3 * (max(VaR) - min(VaR)), + paste('Scale parameter for daily L/P = ', sigma)) + text(mean(cl), + max(VaR) - .4 * (max(VaR) - min(VaR)), + paste('Holding period = ', hp, ' days')) + + title("Gumbel VaR against confidence level") + +} \ No newline at end of file Modified: pkg/Dowd/man/FrechetES.Rd =================================================================== --- pkg/Dowd/man/FrechetES.Rd 2015-06-15 19:18:04 UTC (rev 3675) +++ pkg/Dowd/man/FrechetES.Rd 2015-06-16 14:22:14 UTC (rev 3676) @@ -20,7 +20,7 @@ \item{hp}{Holding period} } \value{ -Value at Risk. If cl and hp are scalars, it returns scalar VaR. If cl +Estimated ES. If cl and hp are scalars, it returns scalar VaR. If cl is vector and hp is a scalar, or viceversa, returns vector of VaRs. If both cl and hp are vectors, returns a matrix of VaRs. } Modified: pkg/Dowd/man/GParetoMEFPlot.Rd =================================================================== --- pkg/Dowd/man/GParetoMEFPlot.Rd 2015-06-15 19:18:04 UTC (rev 3675) +++ pkg/Dowd/man/GParetoMEFPlot.Rd 2015-06-16 14:22:14 UTC (rev 3676) @@ -20,8 +20,8 @@ } \examples{ # Computes ES assuming generalised Pareto for following parameters - Ra <- 5 * randn(100) - mu <- 1 + Ra <- 5 * rnorm(100) + mu <- 0 beta <- 1.2 zeta <- 1.6 GParetoMEFPlot(Ra, mu, beta, zeta) Added: pkg/Dowd/man/GParetoMultipleMEFPlot.Rd =================================================================== --- pkg/Dowd/man/GParetoMultipleMEFPlot.Rd (rev 0) +++ pkg/Dowd/man/GParetoMultipleMEFPlot.Rd 2015-06-16 14:22:14 UTC (rev 3676) @@ -0,0 +1,38 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/GParetoMultipleMEFPlot.R +\name{GParetoMultipleMEFPlot} +\alias{GParetoMultipleMEFPlot} +\title{Plot of Emperical and 2 Generalised Pareto mean excess functions} +\usage{ +GParetoMultipleMEFPlot(Ra, mu, beta, zeta1, zeta2) +} +\arguments{ +\item{Ra}{Vector of daily Profit/Loss data} + +\item{mu}{Location parameter} + +\item{beta}{Scale parameter} + +\item{zeta1}{Assumed tail index for first mean excess function} + +\item{zeta2}{Assumed tail index for second mean excess function} +} +\description{ +Plots of emperical mean excess function and two generalized pareto mean excess functions which differ in their tail-index value. +} +\examples{ +# Computes ES assuming generalised Pareto for following parameters + Ra <- 5 * rnorm(100) + mu <- 1 + beta <- 1.2 + zeta1 <- 1.6 + zeta2 <- 2.2 + GParetoMultipleMEFPlot(Ra, mu, beta, zeta1, zeta2) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Added: pkg/Dowd/man/GParetoVaR.Rd =================================================================== --- pkg/Dowd/man/GParetoVaR.Rd (rev 0) +++ pkg/Dowd/man/GParetoVaR.Rd 2015-06-16 14:22:14 UTC (rev 3676) @@ -0,0 +1,45 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/GParetoVaR.R +\name{GParetoVaR} +\alias{GParetoVaR} +\title{VaR for Generalized Pareto} +\usage{ +GParetoVaR(Ra, beta, zeta, threshold.prob, cl) +} +\arguments{ +\item{Ra}{Vector of daily Profit/Loss data} + +\item{beta}{Assumed scale parameter} + +\item{zeta}{Assumed tail index} + +\item{threshold.prob}{Threshold probability corresponding to threshold u and +x} + +\item{cl}{VaR confidence level} +} +\value{ +Expected Shortfall +} +\description{ +Estimates the Value at Risk of a portfolio assuming losses are +distributed as a generalised Pareto. +} +\examples{ +# Computes ES assuming generalised Pareto for following parameters + Ra <- 5 * randn(100) + beta <- 1.2 + zeta <- 1.6 + threshold.prob <- .85 + cl <- .99 + GParetoVaR(Ra, beta, zeta, threshold.prob, cl) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +McNeil, A., Extreme value theory for risk managers. Mimeo, ETHZ, 1999. +} + Added: pkg/Dowd/man/GumbelES.Rd =================================================================== --- pkg/Dowd/man/GumbelES.Rd (rev 0) +++ pkg/Dowd/man/GumbelES.Rd 2015-06-16 14:22:14 UTC (rev 3676) @@ -0,0 +1,42 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/GumbelES.R +\name{GumbelES} +\alias{GumbelES} +\title{Gumbel ES} +\usage{ +GumbelES(mu, sigma, n, cl, hp) +} +\arguments{ +\item{mu}{Location parameter for daily L/P} + +\item{sigma}{Assumed scale parameter for daily L/P} + +\item{n}{Assumed block size from which the maxima are drawn} + +\item{cl}{VaR confidence level} + +\item{hp}{VaR holding period} +} +\value{ +Estimated ES. If cl and hp are scalars, it returns scalar VaR. If cl +is vector and hp is a scalar, or viceversa, returns vector of VaRs. If both +cl and hp are vectors, returns a matrix of VaRs. +} +\description{ +Estimates the ES of a portfolio assuming extreme losses are +Gumbel distributed, for specified confidence level and holding period. +Note that the long-right-hand tail is fitted to losses, not profits. +} +\examples{ +# Gumber ES Plot + GumbelES(0, 1.2, 100, c(.9,.88, .85, .8), 280) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +National Institute of Standards and Technology, Dataplot Reference Manual. Volume 1: Commands. NIST: Washington, DC, 1997, p. 8-67. +} + Added: pkg/Dowd/man/GumbelESPlot2DCl.Rd =================================================================== --- pkg/Dowd/man/GumbelESPlot2DCl.Rd (rev 0) +++ pkg/Dowd/man/GumbelESPlot2DCl.Rd 2015-06-16 14:22:14 UTC (rev 3676) @@ -0,0 +1,33 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/GumbelESPlot2DCl.R +\name{GumbelESPlot2DCl} +\alias{GumbelESPlot2DCl} +\title{Gumbel VaR} +\usage{ +GumbelESPlot2DCl(mu, sigma, n, cl, hp) +} +\arguments{ +\item{mu}{Location parameter for daily L/P} + +\item{sigma}{Assumed scale parameter for daily L/P} + +\item{n}{size from which the maxima are drawn} + +\item{cl}{VaR confidence level} + +\item{hp}{VaR holding period} +} +\description{ +Estimates the EV VaR of a portfolio assuming extreme losses are Gumbel distributed, for specified confidence level and holding period. +} +\examples{ +# Plots ES against Cl + GumbelESPlot2DCl(0, 1.2, 100, c(.9,.88, .85, .8), 280) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Added: pkg/Dowd/man/GumbelVaR.Rd =================================================================== --- pkg/Dowd/man/GumbelVaR.Rd (rev 0) +++ pkg/Dowd/man/GumbelVaR.Rd 2015-06-16 14:22:14 UTC (rev 3676) @@ -0,0 +1,36 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/GumbelVaR.R +\name{GumbelVaR} +\alias{GumbelVaR} +\title{Gumbel VaR} +\usage{ +GumbelVaR(mu, sigma, n, cl, hp) +} +\arguments{ +\item{mu}{Location parameter for daily L/P} + +\item{sigma}{Assumed scale parameter for daily L/P} + +\item{n}{Size from which the maxima are drawn} + +\item{cl}{VaR confidence level} + +\item{hp}{VaR holding period} +} +\value{ +Estimated VaR +} +\description{ +Estimates the EV VaR of a portfolio assuming extreme losses are Gumbel distributed, for specified confidence level and holding period. +} +\examples{ +# Gumbel VaR + GumbelVaR(0, 1.2, 100, c(.9,.88, .85, .8), 280) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Added: pkg/Dowd/man/GumbelVaRPlot2DCl.Rd =================================================================== --- pkg/Dowd/man/GumbelVaRPlot2DCl.Rd (rev 0) +++ pkg/Dowd/man/GumbelVaRPlot2DCl.Rd 2015-06-16 14:22:14 UTC (rev 3676) @@ -0,0 +1,33 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/GumbelVaRPlot2DCl.R +\name{GumbelVaRPlot2DCl} +\alias{GumbelVaRPlot2DCl} +\title{Gumbel VaR} +\usage{ +GumbelVaRPlot2DCl(mu, sigma, n, cl, hp) +} +\arguments{ +\item{mu}{Location parameter for daily L/P} + +\item{sigma}{Assumed scale parameter for daily L/P} + +\item{n}{size from which the maxima are drawn} + +\item{cl}{VaR confidence level} + +\item{hp}{VaR holding period} +} +\description{ +Estimates the EV VaR of a portfolio assuming extreme losses are Gumbel distributed, for specified confidence level and holding period. +} +\examples{ +# Plots VaR against Cl + GumbelVaRPlot2DCl(0, 1.2, 100, c(.9,.88, .85, .8), 280) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jun 16 17:39:42 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 16 Jun 2015 17:39:42 +0200 (CEST) Subject: [Returnanalytics-commits] r3677 - in pkg/Meucci: . R demo man Message-ID: <20150616153942.E3C221853C2@r-forge.r-project.org> Author: xavierv Date: 2015-06-16 17:39:42 +0200 (Tue, 16 Jun 2015) New Revision: 3677 Modified: pkg/Meucci/DESCRIPTION pkg/Meucci/R/ButterflyTradingFunctions.R pkg/Meucci/R/EntropyProg.R pkg/Meucci/demo/ButterflyTrading.R pkg/Meucci/demo/Prior2Posterior.R pkg/Meucci/man/ComputeCVaR.Rd pkg/Meucci/man/HorizonPricing.Rd pkg/Meucci/man/LongShortMeanCVaRFrontier.Rd pkg/Meucci/man/ViewCurveSlope.Rd pkg/Meucci/man/ViewImpliedVol.Rd pkg/Meucci/man/ViewRealizedVol.Rd Log: Fixed and formatted AnalyticalvsNumerical and ButterflyTrading codes and its dependencies (including EntropyProg) Modified: pkg/Meucci/DESCRIPTION =================================================================== --- pkg/Meucci/DESCRIPTION 2015-06-16 14:22:14 UTC (rev 3676) +++ pkg/Meucci/DESCRIPTION 2015-06-16 15:39:42 UTC (rev 3677) @@ -37,8 +37,8 @@ quadprog, kernlab, nloptr, + limSolve, Suggests: - limSolve, Matrix, MASS, reshape2, Modified: pkg/Meucci/R/ButterflyTradingFunctions.R =================================================================== --- pkg/Meucci/R/ButterflyTradingFunctions.R 2015-06-16 14:22:14 UTC (rev 3676) +++ pkg/Meucci/R/ButterflyTradingFunctions.R 2015-06-16 15:39:42 UTC (rev 3677) @@ -1,19 +1,22 @@ # In order of appearance in the demo script ButterflyTrading.R -MapVol = function( sig , y , K , T ) -{ - # in real life a and b below should be calibrated to security-specific time series - - a = -0.00000000001 - b = 0.00000000001 - - s = sig + a/sqrt(T) * ( log(K) - log(y) ) + b/T*( log(K) - log(y) )^2 - - return( s ) +MapVol <- function(sig, y, K, T) { + # in real life a and b below should be calibrated to security-specific time + # series + + a <- -0.00000000001 + b <- 0.00000000001 + + s <- sig + a / sqrt(T) * (log(K) - log(y)) + b / T * (log(K) - log(y)) ^ 2 + + return(s) } -#' Compute the pricing in the horizon as it appears in A. Meucci, "Fully Flexible Views: Theory and Practice", -#' The Risk Magazine, October 2008, p 100-106. +#' @title Compute the pricing in the horizon. +#' +#' @description Compute the pricing in the horizon as it appears in A. Meucci, +#' "Fully Flexible Views: Theory and Practice", The Risk Magazine, October +#' 2008, p 100-106. #' #' @param Butterflies List of securities with some analytics computed. #' @param X Panel of joint factors realizations @@ -21,125 +24,153 @@ #' @return PnL Matrix of profit and loss scenarios #' #' @references -#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158} -#' See Meucci script for "ButterflyTrading/HorizonPricing.m" +#' A. Meucci, "Fully Flexible Views: Theory and Practice" +#' \url{http://www.symmys.com/node/158}, see Meucci script for +#' "ButterflyTrading/HorizonPricing.m" #' -#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and Xavier Valls \email{flamejat@@gmail.com} +#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and Xavier Valls +#' \email{xaviervallspla@@gmail.com} #' @export -HorizonPricing = function( Butterflies , X ) -{ - r = 0.04 # risk-free rate - tau = 1/252 # investment horizon - - # factors: 1. 'MSFT_close' 2. 'MSFT_vol_30' 3. 'MSFT_vol_91' 4. 'MSFT_vol_182' - # securities: 1. 'MSFT_vol_30' 2. 'MSFT_vol_91' 3. 'MSFT_vol_182' - +HorizonPricing <- function(Butterflies, X) { + r <- 0.04 # risk-free rate + tau <- 1 / 252 # investment horizon + + # factors: 1. 'MSFT_close' 2. 'MSFT_vol_30' + # 3. 'MSFT_vol_91' 4. 'MSFT_vol_182' + # securities: 1. 'MSFT_vol_30' 2. 'MSFT_vol_91' + # 3. 'MSFT_vol_182' + # create a new row called DlnY and Dsig - # create a new row called 'DlnY'. Assign the first row (vector) of X to this DlnY for the 1:3 securities - for ( s in 1:3 ) { Butterflies[[s]]$DlnY = X[ , 1 ] } - + # create a new row called 'DlnY'. Assign the first row (vector) of X to this + # DlnY for the 1:3 securities + for (s in 1:3) { + Butterflies[[s]]$DlnY <- X[, 1] + } + # assign the 2nd row of X to a new element called Dsig - Butterflies[[1]]$Dsig=X[ , 2 ] - Butterflies[[2]]$Dsig=X[ , 3 ] - Butterflies[[3]]$Dsig=X[ , 4 ] - - # factors: 5. 'YHOO_close' 6. 'YHOO_vol_30' 7. 'YHOO_vol_91' 8. 'YHOO_vol_182' - # securities: 4. 'YHOO_vol_30' 5. 'YHOO_vol_91' 6. 'YHOO_vol_182' - for ( s in 4:6 ) { Butterflies[[s]]$DlnY=X[ , 5 ] } - - Butterflies[[4]]$Dsig=X[ , 6 ] - Butterflies[[5]]$Dsig=X[ , 7 ] - Butterflies[[6]]$Dsig=X[ , 8 ] - - # factors: # 9. 'GOOG_close' 10. 'GOOG_vol_30' 11. 'GOOG_vol_91' 12. 'GOOG_vol_182' - # securities: 7. 'GOOG_vol_30' 8. 'GOOG_vol_91' 9. 'GOOG_vol_182' - for ( s in 7:9 ) { Butterflies[[s]]$DlnY=X[ , 9 ] } - - Butterflies[[7]]$Dsig=X[ , 10 ] - Butterflies[[8]]$Dsig=X[ , 11 ] - Butterflies[[9]]$Dsig=X[ , 12 ] - - PnL = matrix( NA , nrow = nrow(X) ) - - for ( s in 1:length(Butterflies) ) - { - Y = Butterflies[[s]]$Y_0 * exp(Butterflies[[s]]$DlnY) - ATMsig = apply( cbind( Butterflies[[s]]$sig_0 + Butterflies[[s]]$Dsig , 10^-6 ) , 1 , max ) - t = Butterflies[[s]]$T - tau - K = Butterflies[[s]]$K - sig = MapVol(ATMsig , Y , K , t ) - - ############# Ram's Code: Substituted with package's own functions ################################# + Butterflies[[1]]$Dsig <- X[, 2] + Butterflies[[2]]$Dsig <- X[, 3] + Butterflies[[3]]$Dsig <- X[, 4] + + # factors: 5. 'YHOO_close' 6. 'YHOO_vol_30' 7. 'YHOO_vol_91' + # 8. 'YHOO_vol_182' + # securities: 4. 'YHOO_vol_30' 5. 'YHOO_vol_91' 6. 'YHOO_vol_182' + for (s in 4:6) { + Butterflies[[s]]$DlnY <- X[, 5] + } + + Butterflies[[4]]$Dsig <- X[, 6] + Butterflies[[5]]$Dsig <- X[, 7] + Butterflies[[6]]$Dsig <- X[, 8] + + # factors: 9. 'GOOG_close' 10. 'GOOG_vol_30' 11. 'GOOG_vol_91' + # 12. 'GOOG_vol_182' + # securities: 7. 'GOOG_vol_30' 8. 'GOOG_vol_91' 9. 'GOOG_vol_182' + for (s in 7:9) { + Butterflies[[s]]$DlnY <- X[, 9] + } + + Butterflies[[7]]$Dsig <- X[, 10] + Butterflies[[8]]$Dsig <- X[, 11] + Butterflies[[9]]$Dsig <- X[, 12] + + PnL <- matrix(NA, nrow = nrow(X)) + + for (s in 1:length(Butterflies)) { + Y <- Butterflies[[s]]$Y_0 * exp(Butterflies[[s]]$DlnY) + ATMsig <- apply(cbind(Butterflies[[s]]$sig_0 + Butterflies[[s]]$Dsig, + 10 ^ -6), 1, max) + t <- Butterflies[[s]]$T - tau + K <- Butterflies[[s]]$K + sig <- MapVol(ATMsig, Y, K, t) + + ############# Ram's Code: Substituted with package's own functions ######### # - ## library(RQuantLib) # this function can only operate on one option at a time, so we use fOptions - ##C = EuropeanOption( type = "call" , underlying = Y , strike = K , dividendYield = 0 , riskFreeRate = r , maturity = t , volatility = sig )$value - ## P = EuropeanOption( type = "put" , underlying = Y , strike = K , dividendYield = 0 , riskFreeRate = r , maturity = t , volatility = sig )$value - + ## library(RQuantLib) # this function can only operate on one option at a + ## time, so we use fOptions + ## C = EuropeanOption(type = "call", underlying = Y, strike = K, + ## dividendYield = 0, riskFreeRate = r, maturity = t, + ## volatility = sig)$value + ## P = EuropeanOption(type = "put", underlying = Y, strike = K, + ## dividendYield = 0, riskFreeRate = r, maturity = t, + ## volatility = sig)$value ## use fOptions to value options - #library( fOptions ) - #C = GBSOption( TypeFlag = "c" , S = Y , X = K , r = r , b = 0 , Time = t , sigma = sig ) - #P = GBSOption( TypeFlag = "p" , S = Y , X = K , r = r , b = 0 , Time = t , sigma = sig ) - # - #################################################################################################### + #library(fOptions) + #C = GBSOption(TypeFlag = "c", S = Y, X = K, r = r, b = 0, Time = t, + # sigma = sig) + #P = GBSOption(TypeFlag = "p", S = Y, X = K, r = r, b = 0, Time = t, + # sigma = sig) + ############################################################################ - BS = BlackScholesCallPutPrice( Y, K, r, sig, t ) - - Butterflies[[s]]$P_T = BS$call + BS$put - PnL = cbind( PnL , Butterflies[[s]]$P_T ) + BS <- BlackScholesCallPutPrice(Y, K, r, sig, t) + Butterflies[[s]]$P_T <- BS$call + BS$put + PnL <- cbind(PnL, Butterflies[[s]]$P_T) } - PnL = PnL[ , -1 ] - - return( PnL ) + PnL <- PnL[, -1] + + return(PnL) } -ViewCurveSlopeTest = function( X , p ) -{ - J = nrow( X ) ; K = ncol( X ) - +ViewCurveSlopeTest <- function(X, p) { + J <- nrow(X) + # constrain probabilities to sum to one... - Aeq = matrix( 1, 1 , J ) - beq = matrix( 1 , nrow = 1 , ncol = 1 ) + Aeq <- matrix(1, 1, J) + beq <- matrix(1, nrow = 1, ncol = 1) browser() # ...constrain the expectation... - V = matrix( , nrow = nrow( X ) , ncol = 0 ) + V <- matrix(, nrow = nrow(X), ncol = 0) # Add 3 equality views - V = cbind( V , X[ , 14 ] - X[ , 13 ] ) # View 1: spread on treasuries - V = cbind( V , X[ , 14 ] - X[ , 13 ] ) # View 2: identical view (spread on treasuries) - V = cbind( V , X[ , 6 ] - X[ , 5 ] ) # View 3: difference in YHOO Vol - v = matrix( c( .0005 , 0 ) , nrow = ncol( V ) , ncol = 1 ) - - Aeq = rbind( Aeq , t(V) ) - - beq = rbind( beq , v ) - + V <- cbind(V, X[, 14] - X[, 13]) # View 1: spread on treasuries + V <- cbind(V, X[, 14] - X[, 13]) # View 2: identical view(spread on treasuries + V <- cbind(V, X[, 6] - X[, 5]) # View 3: difference in YHOO Vol + v <- matrix(c(.0005, 0), nrow = ncol(V), ncol = 1) + + Aeq <- rbind(Aeq, t(V)) + + beq <- rbind(beq, v) + # add an inequality view - # ...constrain the median... - V = abs( X[ , 1 ] ) # absolute value of the log of changes in MSFT close prices (definition of realized volatility) - V_Sort = sort( V , decreasing = FALSE ) # sorting of the abs value of log changes in prices from smallest to largest - I_Sort = order( V ) - - F = cumsum( p[ I_Sort ] ) # represents the cumulative sum of probabilities from ~0 to 1 - - I_Reference = max( matlab:::find( F <= 3/5 ) ) # finds the (max) index corresponding to element with value <= 3/5 along the empirical cumulative density function for the abs log-changes in price - V_Reference = V_Sort[ I_Reference ] # returns the corresponding abs log of change in price at the 3/5 of the cumulative density function + # ...constrain the median... + # absolute value of the log of changes in MSFT close prices (definition of + # realized volatility) + V <- abs(X[, 1]) + # sorting of the abs value of log changes in prices from smallest to largest + V_Sort <- sort(V, decreasing = FALSE) + I_Sort <- order(V) - I_Select = find( V <= V_Reference ) # finds all indices with value of abs log-change in price less than the reference value - a = zeros( 1 , J ) - a[ I_Select ] = 1 # select those cases where the abs log-change in price is less than the 3/5 of the empirical cumulative density... - - A = a - b = 0.5 # ... and assign the probability of these cases occuring as 50%. This moves the media of the distribution - + # represents the cumulative sum of probabilities from ~0 to 1 + F <- cumsum(p[I_Sort]) + + # finds the (max) index corresponding to element with value <= 3/5 along the + # empirical cumulative density function for the abs log-changes in price + I_Reference <- max(matlab:::find(F <= 3 / 5)) + # returns the corresponding abs log of change in price at the 3/5 of the cdf + V_Reference <- V_Sort[I_Reference] + + # finds all indices with value of abs log-change in price < reference value + I_Select <- find(V <= V_Reference) + a <- zeros(1, J) + # select those cases where the abs log-change in price is less than the 3/5 of + # the empirical cumulative density... + a[I_Select] <- 1 + + A <- a + # ... and assign the probability of these cases occuring as 50%. + # This moves the media of the distribution + b <- 0.5 + # ...compute posterior probabilities - p_ = EntropyProg( p , A , b , Aeq ,beq ) - return( p_ ) + p_ <- EntropyProg(p, A, b, Aeq,beq)$p_ + return(p_) } - -#' Process the inequality view, as it appears in A. Meucci, "Fully Flexible Views: Theory and Practice", -#' The Risk Magazine, October 2008, p 100-106. +#' @title Process the inequality view +#' @description Process the inequality view, as it appears in A. Meucci, "Fully +#' Flexible Views: Theory and Practice", The Risk Magazine, October 2008, +#' p 100-106. #' #' @param X : panel of joint factors realizations #' @param p : vector of probabilities @@ -147,40 +178,45 @@ #' @return p_ : vector of posterior probabilities #' #' @references -#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158} +#' A. Meucci, "Fully Flexible Views: Theory and Practice" +#' \url{http://www.symmys.com/node/158} +#' #' See Meucci script for "ButterflyTrading/ViewRealizedVol.m" #' -#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and Xavier Valls \email{flamejat@@gmail.com} +#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and +#' Xavier Valls \email{xaviervallspla@@gmail.com} +#' #' @export -ViewImpliedVol = function( X , p ) -{ - # View 1 (inequality view): bearish on on 2m-6m implied volaility spread for Google - - J = nrow( X ) ; - K = ncol( X ); - +ViewImpliedVol <- function(X, p) { + # View 1 (inequality view): bearish on on 2m-6m implied volaility spread + #for Google + + J <- nrow(X) + # constrain probabilities to sum to one... - Aeq = matrix( 1, 1 , J ) - beq = 1 - + Aeq <- matrix(1, 1, J) + beq <- c(1) + # ...constrain the expectation... - V = X[ , 12 ] - X[ , 11 ] # GOOG_vol_182 (6m implied vol) - GOOG_vol_91 (2m implied vol) - m = mean( V ) - s = std( V ) - - A = t( V ) - b = m - s - + # GOOG_vol_182 (6m implied vol) - GOOG_vol_91 (2m implied vol) + V <- X[, 12] - X[, 11] + m <- mean(V) + s <- std(V) + + A <- t(V) + b <- c(m - s) + # ...compute posterior probabilities - p_ = EntropyProg( p , A , b , Aeq , beq )$p_ - - return( p_ ) + p_ <- EntropyProg(p, A, b, Aeq, beq)$p_ + + return(p_) } -#' Process the relative inequality view on median, as it appears in A. Meucci, -#' "Fully Flexible Views: Theory and Practice", The Risk Magazine, October 2008, -#' p 100-106 +#' @title Process the relative inequality view on median +#' @description Process the relative inequality view on median, as it appears in +#' A. Meucci, "Fully Flexible Views: Theory and Practice", The Risk Magazine, +#' October 2008, p 100-106 #' #' @param X : panel of joint factors realizations #' @param p : vector of probabilities @@ -188,53 +224,69 @@ #' @return p_ : vector of posterior probabilities #' #' @references -#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158} +#' A. Meucci, "Fully Flexible Views: Theory and Practice" +#' \url{http://www.symmys.com/node/158} #' See Meucci script for "ButterflyTrading/ViewRealizedVol.m" #' -#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and Xavier Valls \email{flamejat@@gmail.com} +#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and Xavier Valls +#' \email{xaviervallspla@@gmail.com} #' @export -ViewRealizedVol = function( X , p ) -{ - # view 2 bullish on realized volatility of MSFT (i.e. absolute log-change in the underlying). - # This is the variable such that, if larger than a threshold, a long position in the butterfly turns into a profit (e.g. Rachev 2003) - # we issue a relative statement on the media comparing it with the third quintile implied by the reference market model - - library( matlab ) - J = nrow( X ) ; K = ncol( X ) - +ViewRealizedVol <- function(X, p) { + # view 2 bullish on realized volatility of MSFT (i.e. absolute log-change in + # the underlying). + # This is the variable such that, if larger than a threshold, a long position + # in the butterfly turns into a profit (e.g. Rachev 2003) + # we issue a relative statement on the media comparing it with the third + # quintile implied by the reference market model + + J <- nrow(X) + # constrain probabilities to sum to one... - Aeq = matrix( 1, 1 , J ) - beq = 1 - - # ...constrain the median... - V = abs( X[ , 1 ] ) # absolute value of the log of changes in MSFT close prices (definition of realized volatility) - - V_Sort = sort( V , decreasing = FALSE ) # sorting of the abs value of log changes in prices from smallest to largest - I_Sort = order( V ) - - F = cumsum( p[ I_Sort ] ) # represents the cumulative sum of probabilities from ~0 to 1 - - I_Reference = max( matlab:::find( F <= 3/5 ) ) # finds the (max) index corresponding to element with value <= 3/5 along the empirical cumulative density function for the abs log-changes in price - V_Reference = V_Sort[ I_Reference ] # returns the corresponding abs log of change in price at the 3/5 of the cumulative density function - - I_Select = find( V <= V_Reference ) # finds all indices with value of abs log-change in price less than the reference value - - a = zeros( 1 , J ) - a[ I_Select ] = 1 # select those cases where the abs log-change in price is less than the 3/5 of the empirical cumulative density... - - A = a - b = .5 # ... and assign the probability of these cases occuring as 50%. This moves the media of the distribution - + Aeq <- matrix(1, 1, J) + beq <- 1 + + # ...constrain the median... + # absolute value of the log of changes in MSFT close prices + # (definition of realized volatility) + V <- abs(X[, 1]) + # sorting of the abs value of log changes in prices from smallest to largest + V_Sort <- sort(V, decreasing = FALSE) + I_Sort <- order(V) + + # represents the cumulative sum of probabilities from ~0 to 1 + F <- cumsum(p[I_Sort]) + # finds the (max) index corresponding to element with value <= 3/5 along the + # empirical cumulative density function for the abs log-changes in price + I_Reference <- max(matlab:::find(F <= 3 / 5)) + # returns the corresponding abs log of change in price at the 3/5 of the + # cumulative density function + V_Reference <- V_Sort[I_Reference] + + # finds all indices with value of abs log-change in price < reference value + I_Select <- find(V <= V_Reference) + + a <- zeros(1, J) + # select those cases where the abs log-change in price is less than the 3/5 of + # the empirical cumulative density... + a[I_Select] <- 1 + + A <- a + # ... and assign the probability of these cases occuring as 50%. + # This moves the media of the distribution + b <- .5 + # ...compute posterior probabilities - p_ = EntropyProg( p , A , b , Aeq , beq )$p_ - - return( p_ ) + p_ <- EntropyProg(p, A, b, Aeq, beq)$p_ + + return(p_) } -#' Process views for the expectations and binding constraints as it appears in A. Meucci, -#' "Fully Flexible Views: Theory and Practice", The Risk Magazine, October 2008, -#' p 100-106 +#' @title Process views for the expectations and binding constraints +#' +#' @description Process views for the expectations and binding constraints as it +#' appears in A. Meucci, "Fully Flexible Views: Theory and Practice", The Risk +#' Magazine, October 2008, p 100-106. #' #' @param X : panel of joint factors realizations #' @param p : vector of probabilities @@ -242,42 +294,44 @@ #' @return p_ : vector of posterior probabilities #' #' @references -#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158} +#' A. Meucci, "Fully Flexible Views: Theory and Practice" +#' \url{http://www.symmys.com/node/158} +#' #' See Meucci script for "ButterflyTrading/ViewCurveSlope.m" #' -#' @author Xavier Valls \email{flamejat@@gmail.com} +#' @author Xavier Valls \email{xaviervallspla@@gmail.com} #' @export -ViewCurveSlope = function( X , p ) -{ - # view 3 - - J = nrow( X ); - K = ncol( X ); - +ViewCurveSlope <- function(X, p) { + # view 3 + J <- nrow(X) + # constrain probabilities to sum to one... - Aeq = matrix( 1, 1 , J ); - beq = 1; - + Aeq <- matrix(1, 1, J); + beq <- 1; + # ...constrain the expectation... - V = X[ , 14 ] - X[ , 13 ]; - v = 0.0005; - - Aeq = rbind( Aeq , t(V) ); - - beq = rbind( beq , v ); - - A = b = matrix( nrow = 0 , ncol = 0 ); - + V <- X[, 14] - X[, 13]; + v <- 0.0005; + + Aeq <- rbind(Aeq, t(V)); + + beq <- rbind(beq, v); + + A <- b <- matrix(nrow = 0, ncol = 0); + # ...compute posterior probabilities - p_ = EntropyProg( p , A , b , Aeq ,beq )$p_; + p_ <- EntropyProg(p, A, b, Aeq,beq)$p_; - return( p_ ); + return(p_); } -#' Computes the conditional value at risk as it appears in A. Meucci, "Fully Flexible Views: Theory and Practice", -#' The Risk Magazine, October 2008, p 100-106 -#' +#' @title Computes the conditional value at risk +#' +#' @description Computes the conditional value at risk as it appears in +#' A. Meucci, "Fully Flexible Views: Theory and Practice", The Risk Magazine, +#' October 2008, p 100-106. +#' #' @param Units panel of joint factors realizations #' @param Scenarios vector of probabilities #' @param Conf Confidence @@ -285,132 +339,150 @@ #' @return CVaR Conditional Value at Risk #' #' @references -#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158} +#' A. Meucci, "Fully Flexible Views: Theory and Practice" +#' \url{http://www.symmys.com/node/158} +#' #' See Meucci script for "ButterflyTrading/ComputeCVaR.m" #' #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} #' @export -ComputeCVaR = function( Units , Scenarios , Conf ) +ComputeCVaR <- function(Units, Scenarios, Conf) { - PnL = Scenarios %*% Units - Sort_PnL = PnL[ order( PnL , decreasing = FALSE ) ] - - J = length( PnL ) - Cut = round( J %*% ( 1 - Conf ) , 0 ) - - CVaR = -mean( Sort_PnL[ 1:Cut ] ) - - return( CVaR ) + PnL <- Scenarios %*% Units + Sort_PnL <- PnL[order(PnL, decreasing = FALSE)] + + J <- length(PnL) + Cut <- round(J %*% (1 - Conf), 0) + + CVaR <- -mean(Sort_PnL[1:Cut]) + + return(CVaR) } -#' Computes the long-short conditional value at risk frontier as it appears in A. Meucci, -#' "Fully Flexible Views: Theory and Practice", The Risk Magazine, October 2008, p 100-106 -#' +#' @title Computes the long-short conditional value at risk +#' +#' @description Computes the long-short conditional value at risk frontier as it +#' appears in A. Meucci, "Fully Flexible Views: Theory and Practice", The Risk +#' Magazine, October 2008, p 100-106. +#' #' @param PnL Profit and Loss scenarios #' @param Probs vector of probabilities #' @param Butterflies list of securities with some analytics computed. #' @param Options list of options #' #' @return Exp vector of expected returns for each asset -#' @return SDev vector of security volatilities along the efficient frontier +#' @return SDev vector of security volatilities along the efficient +#' frontier #' @return CVaR Conditional Value at Risk for each portfolio -#' @return Composition matrix of compositions (security weights) for each portfolio along the efficient frontier +#' @return Composition matrix of compositions (security weights) for each +#' portfolio along the efficient frontier #' #' @references -#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158} +#' A. Meucci, "Fully Flexible Views: Theory and Practice" +#' \url{http://www.symmys.com/node/158} +#' #' See Meucci script for "ButterflyTrading/LongShortMeanCVaRFrontier.m" #' -#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com}, Xavier Valls \email{flamejat@@gmail.com} +#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com}, +#' Xavier Valls \email{xaviervallspla@@gmail.com} #' @export -LongShortMeanCVaRFrontier = function( PnL , Probs , Butterflies , Options ) -{ - library( matlab ) - library( quadprog ) - library( limSolve ) - +LongShortMeanCVaRFrontier <- function(PnL, Probs, Butterflies, Options) { # setup constraints - J = nrow(PnL); N = ncol(PnL) - P_0s = matrix( , nrow = 1 , ncol = 0 ) - D_s = matrix( , nrow = 1 , ncol = 0 ) - emptyMatrix = matrix( nrow = 0 , ncol = 0 ) - - for ( n in 1:N ) - { - P_0s = cbind( P_0s , Butterflies[[n]]$P_0 ) # 1x9 matrix - D_s = cbind( D_s , Butterflies[[n]]$Delta ) # 1x9 matrix + N <- ncol(PnL) + P_0s <- matrix(, nrow = 1, ncol = 0) + D_s <- matrix(, nrow = 1, ncol = 0) + emptyMatrix <- matrix(nrow = 0, ncol = 0) + + for (n in 1:N) { + P_0s <- cbind(P_0s, Butterflies[[n]]$P_0) # 1x9 matrix + D_s <- cbind(D_s, Butterflies[[n]]$Delta) # 1x9 matrix } - - Constr = list() - Constr$Aeq = P_0s # linear coefficients in the constraints Aeq*X = beq (equality constraints) - Constr$beq = Options$Budget # the constant vector in the constraints Aeq*x = beq - - if ( Options$DeltaNeutral == TRUE ) - { - Constr$Aeq = rbind( Constr$Aeq , D_s ) # 2x9 matrix - Constr$beq = rbind( Constr$beq , 0 ) # 2x9 matrix + + Constr <- list() + # linear coefficients in the constraints Aeq*X = beq (equality constraints) + Constr$Aeq <- P_0s + # the constant vector in the constraints Aeq*x = beq + Constr$beq <- Options$Budget + + if (Options$DeltaNeutral == TRUE) { + Constr$Aeq <- rbind(Constr$Aeq, D_s) # 2x9 matrix + Constr$beq <- rbind(Constr$beq, 0) # 2x9 matrix } - - Constr$Aleq = rbind( diag( as.vector( P_0s ) ) , -diag( as.vector( P_0s ) ) ) # linear coefficients in the constraints A*x <= b. an 18x9 matrix - Constr$bleq = rbind( Options$Limit * matrix( 1,N,1) , Options$Limit * matrix( 1,N,1) ) # constant vector in the constraints A*x <= b. an 18x1 matrix - + +# linear coefficients in the constraints A*x <= b. an 18x9 matrix + Constr$Aleq <- rbind(diag(as.vector(P_0s)), -diag(as.vector(P_0s))) + # constant vector in the constraints A*x <= b. an 18x1 matrix + Constr$bleq <- rbind(Options$Limit * matrix(1,N,1), + Options$Limit * matrix(1,N,1)) + # determine expectation of minimum-variance portfolio - Exps = t(PnL) %*% Probs - Scnd_Mom = t(PnL) %*% (PnL * (Probs %*% matrix( 1,1,N) ) ) - Scnd_Mom = ( Scnd_Mom + t(Scnd_Mom) ) / 2 - Covs = Scnd_Mom - Exps %*% t(Exps) - - Amat = rbind( Constr$Aeq , Constr$Aleq ) # stack the equality constraints on top of the inequality constraints - bvec = rbind( Constr$beq , Constr$bleq ) # stack the equality constraints on top of the inequality constraints - - #if ( nrow(Covs) != length( zeros(N,1) ) ) stop("Dmat and dvec are incompatible!") - #if ( nrow(Covs) != nrow(Amat)) stop("Amat and dvec are incompatible!") - - MinSDev_Units = solve.QP( Dmat = Covs , dvec = -1 * zeros(N,1) , Amat = -1*t(Amat) , bvec = -1*bvec , meq = length( Constr$beq) ) # TODO: Check this - MinSDev_Exp = t( MinSDev_Units$solution ) %*% Exps - + Exps <- t(PnL) %*% Probs + Scnd_Mom <- t(PnL) %*% (PnL * (Probs %*% matrix(1,1,N))) + Scnd_Mom <- (Scnd_Mom + t(Scnd_Mom)) / 2 + Covs <- Scnd_Mom - Exps %*% t(Exps) + +# stack the equality constraints on top of the inequality constraints + Amat <- rbind(Constr$Aeq, Constr$Aleq) + bvec <- rbind(Constr$beq, Constr$bleq) + + #if (nrow(Covs) != length(zeros(N,1))) stop("Dmat and dvec are incompatible!") + #if (nrow(Covs) != nrow(Amat)) stop("Amat and dvec are incompatible!") + + MinSDev_Units <- solve.QP(Dmat = Covs, dvec = -1 * zeros(N,1), + Amat = -1 * t(Amat), bvec = -1 * bvec, + meq = length(Constr$beq)) # TODO: Check this + MinSDev_Exp <- t(MinSDev_Units$solution) %*% Exps + # determine expectation of maximum-expectation portfolio - - MaxExp_Units = linp( E = Constr$Aeq , F = Constr$beq , G = -1*Constr$Aleq , H = -1*Constr$bleq , Cost = -Exps , ispos = FALSE )$X - - MaxExp_Exp = t( MaxExp_Units ) %*% Exps - + + MaxExp_Units <- linp(E = Constr$Aeq, F = Constr$beq, G = -1 * Constr$Aleq, + H = -1 * Constr$bleq, Cost = -Exps, ispos = FALSE)$X + + MaxExp_Exp <- t(MaxExp_Units) %*% Exps + # slice efficient frontier in NumPortf equally thick horizontal sections - Grid = t( seq( from = Options$FrontierSpan[1] , to = Options$FrontierSpan[2] , length.out = Options$NumPortf ) ) - TargetExp = as.numeric( MinSDev_Exp ) + Grid * as.numeric( ( MaxExp_Exp - MinSDev_Exp ) ) - + Grid <- t(seq(from = Options$FrontierSpan[1], to = Options$FrontierSpan[2], + length.out = Options$NumPortf)) + TargetExp <- as.numeric(MinSDev_Exp) + Grid * as.numeric(MaxExp_Exp - + MinSDev_Exp) + # compute composition, expectation, s.dev. and CVaR of the efficient frontier - Composition = matrix( , ncol = N , nrow = 0 ) - Exp = matrix( , ncol = 1 , nrow = 0 ) - SDev = matrix( , ncol = 1 , nrow = 0 ) - CVaR = matrix( , ncol = 1 , nrow = 0 ) - - for (i in 1:Options$NumPortf ) - { - # determine least risky portfolio for given expectation - AEq = rbind( Constr$Aeq , t(Exps) ) # equality constraint: set expected return for each asset... - bEq = rbind( Constr$beq , TargetExp[i] ) - - Amat = rbind( AEq , Constr$Aleq ) # stack the equality constraints on top of the inequality constraints - bvec = rbind( bEq , Constr$bleq ) # ...and target portfolio return for i'th efficient portfolio - - # Why is FirstDegree "expected returns" set to 0? + Composition <- matrix(, ncol = N, nrow = 0) + Exp <- matrix(, ncol = 1, nrow = 0) + SDev <- matrix(, ncol = 1, nrow = 0) + CVaR <- matrix(, ncol = 1, nrow = 0) + + for (i in 1:Options$NumPortf) { + ## determine least risky portfolio for given expectation + # equality constraint: set expected return for each asset... + AEq <- rbind(Constr$Aeq, t(Exps)) + bEq <- rbind(Constr$beq, TargetExp[i]) + + # stack the equality constraints on top of the inequality constraints + Amat <- rbind(AEq, Constr$Aleq) + # ...and target portfolio return for i'th efficient portfolio + bvec <- rbind(bEq, Constr$bleq) + + # Why is FirstDegree "expected returns" set to 0? # Becasuse we capture the equality view in the equality constraints matrix - # In other words, we have a constraint that the Expected Returns by Asset %*% Weights = Target Return - Units = solve.QP( Dmat = Covs , dvec = -1*zeros(N,1) , Amat = -1*t(Amat) , bvec = -1*bvec , meq = length( bEq ) ) - + # In other words, we have a constraint that the Expected Returns by + # Asset %*% Weights = Target Return + Units <- solve.QP(Dmat = Covs, dvec = -1 * zeros(N,1), Amat = -1 * t(Amat), + bvec = -1 * bvec, meq = length(bEq)) + # store results - Composition = rbind( Composition , t( Units$solution ) ) - - Exp = rbind( Exp , t( Units$solution ) %*% Exps ) - SDev = rbind( SDev , sqrt( t( Units$solution ) %*% Covs %*% Units$solution ) ) - CVaR = rbind( CVaR , ComputeCVaR( Units$solution , PnL , Options$Quant ) ) - } - - colnames( Composition ) = c( "MSFT_vol_30" , "MSFT_vol_91" , "MSFT_vol_182" , - "YHOO_vol_30" , "YHOO_vol_91" , "YHOO_vol_182" , - "GOOG_vol_30" , "GOOG_vol_91" , "GOOG_vol_182" ) - - return( list( Exp = Exp , SDev = SDev , CVaR = CVaR , Composition = Composition ) ) + Composition <- rbind(Composition, t(Units$solution)) + + Exp <- rbind(Exp, t(Units$solution) %*% Exps) + SDev <- rbind(SDev, sqrt(t(Units$solution) %*% Covs %*% Units$solution)) + CVaR <- rbind(CVaR, ComputeCVaR(Units$solution, PnL, Options$Quant)) + } + + colnames(Composition) <- c("MSFT_vol_30", "MSFT_vol_91", "MSFT_vol_182", + "YHOO_vol_30", "YHOO_vol_91", "YHOO_vol_182", + "GOOG_vol_30", "GOOG_vol_91", "GOOG_vol_182") + + return(list(Exp = Exp, SDev = SDev, CVaR = CVaR, Composition = Composition)) } Modified: pkg/Meucci/R/EntropyProg.R =================================================================== --- pkg/Meucci/R/EntropyProg.R 2015-06-16 14:22:14 UTC (rev 3676) +++ pkg/Meucci/R/EntropyProg.R 2015-06-16 15:39:42 UTC (rev 3677) @@ -98,11 +98,11 @@ if (((.999999 < sum(p)) & (sum(p) < 1.00001)) == FALSE) stop("sum of probabilities from prior distribution must equal 1") - if (nrow(Aeq) != nrow(beq)){ + if (nrow(Aeq) != length(beq)){ stop("number of inequality constraints in matrix Aeq must match number of elements in vector beq") } - if (nrow(A) != nrow(b)) { + if (nrow(A) != length(b)) { stop("number of equality constraints in matrix A must match number of elements in vector b") } Modified: pkg/Meucci/demo/ButterflyTrading.R =================================================================== --- pkg/Meucci/demo/ButterflyTrading.R 2015-06-16 14:22:14 UTC (rev 3676) +++ pkg/Meucci/demo/ButterflyTrading.R 2015-06-16 15:39:42 UTC (rev 3677) @@ -1,101 +1,117 @@ -#' This script performs the butterfly-trading case study for the Entropy-Pooling approach by Attilio Meucci, -#' as it appears in A. Meucci, "Fully Flexible Views: Theory and Practice", The Risk Magazine, October 2008, -#' p 100-106 +#' This script performs the butterfly-trading case study for the Entropy-Pooling +#'' approach by Attilio Meucci, as it appears in A. Meucci, "Fully Flexible +#' Views: Theory and Practice", The Risk Magazine, October 2008, p 100-106 #' #' Most recent version of article and MATLAB code available at #' http://www.symmys.com/node/158 #' #' @references [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3677 From noreply at r-forge.r-project.org Thu Jun 18 01:16:50 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 18 Jun 2015 01:16:50 +0200 (CEST) Subject: [Returnanalytics-commits] r3678 - in pkg/Dowd: . R man Message-ID: <20150617231650.B69491833AE@r-forge.r-project.org> Author: dacharya Date: 2015-06-18 01:16:50 +0200 (Thu, 18 Jun 2015) New Revision: 3678 Added: pkg/Dowd/R/HSVaRDFPerc.R pkg/Dowd/man/HSVaRDFPerc.Rd Modified: pkg/Dowd/NAMESPACE pkg/Dowd/R/GumbelESPlot2DCl.R pkg/Dowd/R/GumbelVaRPlot2DCl.R pkg/Dowd/man/GumbelESPlot2DCl.Rd Log: HSVaRDFPerc : source and documentation Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-16 15:39:42 UTC (rev 3677) +++ pkg/Dowd/NAMESPACE 2015-06-17 23:16:50 UTC (rev 3678) @@ -34,6 +34,7 @@ export(GumbelVaRPlot2DCl) export(HSES) export(HSVaR) +export(HSVaRDFPerc) export(HillEstimator) export(HillPlot) export(HillQuantileEstimator) Modified: pkg/Dowd/R/GumbelESPlot2DCl.R =================================================================== --- pkg/Dowd/R/GumbelESPlot2DCl.R 2015-06-16 15:39:42 UTC (rev 3677) +++ pkg/Dowd/R/GumbelESPlot2DCl.R 2015-06-17 23:16:50 UTC (rev 3678) @@ -15,7 +15,7 @@ #' @examples #' #' # Plots ES against Cl -#' GumbelESPlot2DCl(0, 1.2, 100, c(.9,.88, .85, .8), 280) +#' GumbelESPlot2DCl(0, 1.2, 100, seq(0.8,0.99,0.02), 280) #' #' @export GumbelESPlot2DCl<- function(mu, sigma, n, cl, hp){ @@ -68,20 +68,10 @@ # Plotting plot(cl0, v, xlab = "Confidence Level", ylab = "ES", type = "l") - - text(mean(cl0), - max(v) - .1*(max(v) - min(v)), - 'Input parameters') - text(mean(cl0), - max(v)-.2*(max(v)-min(v)), - paste('Location parameter for daily L/P = ', mu)) - text(mean(cl0), - max(v) - .3 * (max(v) - min(v)), - paste('Scale parameter for daily L/P = ', sigma)) - text(mean(cl0), - max(v) - .4 * (max(v) - min(v)), - paste('Holding period = ', hp, ' days')) - + legend("topleft",c('Input parameters', + paste('Location parameter for daily L/P = ', mu), + paste('Scale parameter for daily L/P = ', sigma), + paste('Holding period = ', hp, ' days')), bty="n") title("Gumbel ES against confidence level") } \ No newline at end of file Modified: pkg/Dowd/R/GumbelVaRPlot2DCl.R =================================================================== --- pkg/Dowd/R/GumbelVaRPlot2DCl.R 2015-06-16 15:39:42 UTC (rev 3677) +++ pkg/Dowd/R/GumbelVaRPlot2DCl.R 2015-06-17 23:16:50 UTC (rev 3678) @@ -10,7 +10,6 @@ #' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' -#' #' @author Dinesh Acharya #' @examples #' @@ -56,19 +55,10 @@ # Plotting plot(cl, VaR, xlab = "Confidence Level", ylab = "VaR", type = "l") - text(mean(cl), - max(VaR) - .1*(max(VaR) - min(VaR)), - 'Input parameters') - text(mean(cl), - max(VaR)-.2*(max(VaR)-min(VaR)), - paste('Location parameter for daily L/P = ', mu)) - text(mean(cl), - max(VaR) - .3 * (max(VaR) - min(VaR)), - paste('Scale parameter for daily L/P = ', sigma)) - text(mean(cl), - max(VaR) - .4 * (max(VaR) - min(VaR)), - paste('Holding period = ', hp, ' days')) - + legend("topleft",c('Input parameters', + paste('Location parameter for daily L/P = ', mu), + paste('Scale parameter for daily L/P = ', sigma), + paste('Holding period = ', hp, ' days')), bty="n") title("Gumbel VaR against confidence level") } \ No newline at end of file Added: pkg/Dowd/R/HSVaRDFPerc.R =================================================================== --- pkg/Dowd/R/HSVaRDFPerc.R (rev 0) +++ pkg/Dowd/R/HSVaRDFPerc.R 2015-06-17 23:16:50 UTC (rev 3678) @@ -0,0 +1,80 @@ +#' @title Percentile of historical simulation VaR distribution function +#' +#' @description Estimates percentiles of historical simulation VaR distribution +#' function, using theory of order statistics, for specified confidence level. +#' +#' @param Ra Vector of daily P/L data +#' @param perc Desired percentile and is scalar +#' @param cl VaR confidence level and is scalar +#' @return Value of percentile of VaR distribution function +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates Percentiles for random standard normal returns and given perc +#' # and cl +#' Ra <- rnorm(100) +#' HSVaRDFPerc(Ra, .75, .95) +#' +#' @export +HSVaRDFPerc <- function(Ra, perc, cl){ + + # Determine if there are three arguments, and ensure that arguments are read as intended + if (nargs() < 3) { + stop("Too few arguments.") + } + if (nargs() > 3) { + stop("Too many arguments") + } + if (nargs() == 3) { + profit.loss <- as.vector(Ra) + data <- sort(profit.loss) + n <- length(data) + } + + # Check that inputs obey sign and value restrictions + if (n < 0) { + stop("Number of observations must be greater than zero.") + } + if (perc <= 0) { + stop("Chosen percentile must be positive.") + } + if (perc > 1) { + stop("Chosen percentile must not exceed 1") + } + if (cl >= 1) { + stop("Confidence level must be less than 1.") + } + if (cl <= 0) { + stop("Confidence level must positive.") + } + + # Derive order statistics and ensure it is an integer + w <- n * cl # Derive rth order statistics + r <- round(w) # Round r to nearest integer + + # Bisection routine + a <- 0 + fa <- -Inf + b <- 1 + fb <- Inf + eps <- .Machine$double.eps + while (b - a > eps * b) { + x <- (a + b) / 2 + fx <- 1 - pbinom(r - 1, n, x) - perc + if (sign(fx) == sign(fa)){ + a = x + fa = fx + } else { + b = x + fb = fx + } + } + i <- round(n * x) + y <- data[i] # Value of percentile of VaR distribution function + return(y) + +} \ No newline at end of file Modified: pkg/Dowd/man/GumbelESPlot2DCl.Rd =================================================================== --- pkg/Dowd/man/GumbelESPlot2DCl.Rd 2015-06-16 15:39:42 UTC (rev 3677) +++ pkg/Dowd/man/GumbelESPlot2DCl.Rd 2015-06-17 23:16:50 UTC (rev 3678) @@ -22,7 +22,7 @@ } \examples{ # Plots ES against Cl - GumbelESPlot2DCl(0, 1.2, 100, c(.9,.88, .85, .8), 280) + GumbelESPlot2DCl(0, 1.2, 100, seq(0.8,0.99,0.02), 280) } \author{ Dinesh Acharya Added: pkg/Dowd/man/HSVaRDFPerc.Rd =================================================================== --- pkg/Dowd/man/HSVaRDFPerc.Rd (rev 0) +++ pkg/Dowd/man/HSVaRDFPerc.Rd 2015-06-17 23:16:50 UTC (rev 3678) @@ -0,0 +1,35 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/HSVaRDFPerc.R +\name{HSVaRDFPerc} +\alias{HSVaRDFPerc} +\title{Percentile of historical simulation VaR distribution function} +\usage{ +HSVaRDFPerc(Ra, perc, cl) +} +\arguments{ +\item{Ra}{Vector of daily P/L data} + +\item{perc}{Desired percentile and is scalar} + +\item{cl}{VaR confidence level and is scalar} +} +\value{ +Value of percentile of VaR distribution function +} +\description{ +Estimates percentiles of historical simulation VaR distribution +function, using theory of order statistics, for specified confidence level. +} +\examples{ +# Estimates Percentiles for random standard normal returns and given perc + # and cl + Ra <- rnorm(100) + HSVaRDFPerc(Ra, .75, .95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Thu Jun 18 02:11:57 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 18 Jun 2015 02:11:57 +0200 (CEST) Subject: [Returnanalytics-commits] r3679 - in pkg/Dowd: . R man Message-ID: <20150618001157.7E22E186C0D@r-forge.r-project.org> Author: dacharya Date: 2015-06-18 02:11:57 +0200 (Thu, 18 Jun 2015) New Revision: 3679 Added: pkg/Dowd/R/HSVaRFigure.R pkg/Dowd/man/HSVaRFigure.Rd Modified: pkg/Dowd/NAMESPACE Log: HSVaRFigure: source and documentation Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-17 23:16:50 UTC (rev 3678) +++ pkg/Dowd/NAMESPACE 2015-06-18 00:11:57 UTC (rev 3679) @@ -35,6 +35,7 @@ export(HSES) export(HSVaR) export(HSVaRDFPerc) +export(HSVaRFigure) export(HillEstimator) export(HillPlot) export(HillQuantileEstimator) Added: pkg/Dowd/R/HSVaRFigure.R =================================================================== --- pkg/Dowd/R/HSVaRFigure.R (rev 0) +++ pkg/Dowd/R/HSVaRFigure.R 2015-06-18 00:11:57 UTC (rev 3679) @@ -0,0 +1,54 @@ +#' @title Figure of Historical SImulation VaR and histogram of L/P +#' +#' @description Plots figure showing the historical simulation VaR and histogram +#' of L/P for specified confidence level and holding period implied by data +#' frequency. +#' +#' @param Ra Vector of profit loss data +#' @param cl ES confidence level +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots figure showing VaR and histogram of P/L data +#' Ra <- rnorm(100) +#' HSVaRFigure(Ra, .95) +#' +#' @export +HSVaRFigure<- function(Ra, cl){ + # Determine if there are two arguments and ensure that arguments are read as intended + if (nargs() < 2) { + stop("Too few arguments") + } + if (nargs() > 2){ + stop("Too many arguments") + } + if (nargs() == 2){ + profit.loss <- as.vector(Ra) + n <- length(profit.loss) + } + + # Check that inputs have correct dimensions + if (length(cl) != 1) { + stop("Confidence level must be a scalar") + } + + if ( cl >= 1){ + stop("Confidence level must be less than 1") + } + + # VaR estimation + VaR <- HSVaR(profit.loss, cl) # HS VaR + # Histogram + n <- hist(profit.loss, main = "Historical Simulation VaR", col = 4, + xlab = "Loss(+) / Profit(-)", ylab = "Frequency") + v <- c(0, .625 * max(n$counts)) # Coordinates for VaR line + u <- VaR * matrix(1, length(v),1) # Coordinates for VaR line + lines(u, v, type = "l", col="blue") + cl.for.label <- 100 * cl + legend("topleft",c(paste('VaR at', cl.for.label, '% CL'), + paste('=', VaR)), bty="n", cex = 0.7) + +} \ No newline at end of file Added: pkg/Dowd/man/HSVaRFigure.Rd =================================================================== --- pkg/Dowd/man/HSVaRFigure.Rd (rev 0) +++ pkg/Dowd/man/HSVaRFigure.Rd 2015-06-18 00:11:57 UTC (rev 3679) @@ -0,0 +1,30 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/HSVaRFigure.R +\name{HSVaRFigure} +\alias{HSVaRFigure} +\title{Figure of Historical SImulation VaR and histogram of L/P} +\usage{ +HSVaRFigure(Ra, cl) +} +\arguments{ +\item{Ra}{Vector of profit loss data} + +\item{cl}{ES confidence level} +} +\description{ +Plots figure showing the historical simulation VaR and histogram + of L/P for specified confidence level and holding period implied by data + frequency. +} +\examples{ +# Plots figure showing VaR and histogram of P/L data + Ra <- rnorm(100) + HSVaRFigure(Ra, .95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Thu Jun 18 23:54:56 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 18 Jun 2015 23:54:56 +0200 (CEST) Subject: [Returnanalytics-commits] r3680 - in pkg/Dowd: . R man Message-ID: <20150618215456.CC3F5187AFD@r-forge.r-project.org> Author: dacharya Date: 2015-06-18 23:54:56 +0200 (Thu, 18 Jun 2015) New Revision: 3680 Added: pkg/Dowd/R/AdjustedVarianceCovarianceES.R pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd Modified: pkg/Dowd/NAMESPACE Log: AdjustedVarianceCovarianceES: source and documentation Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-18 00:11:57 UTC (rev 3679) +++ pkg/Dowd/NAMESPACE 2015-06-18 21:54:56 UTC (rev 3680) @@ -3,6 +3,7 @@ export(ADTestStat) export(AdjustedNormalESHotspots) export(AdjustedNormalVaRHotspots) +export(AdjustedVarianceCovarianceES) export(BinomialBacktest) export(BlancoIhleBacktest) export(BootstrapES) Added: pkg/Dowd/R/AdjustedVarianceCovarianceES.R =================================================================== --- pkg/Dowd/R/AdjustedVarianceCovarianceES.R (rev 0) +++ pkg/Dowd/R/AdjustedVarianceCovarianceES.R 2015-06-18 21:54:56 UTC (rev 3680) @@ -0,0 +1,125 @@ +#' @title Cornish-Fisher adjusted Variance-Covariance ES +#' +#' @description Function estimates the Variance-Covariance ES of a multi-asset +#' portfolio using the Cornish - Fisher adjustment for portfolio return +#' non-normality, for specified confidence level and holding period. +#' +#' @param vc.matrix Variance covariance matrix for returns +#' @param mu Vector of expected position returns +#' @param skew Return skew +#' @param kurtisos Return kurtosis +#' @param positions Vector of positions +#' @param cl Confidence level and is scalar +#' @param hp Holding period and is scalar +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' +#' @examples +#' +#' # Variance-covariance ES for randomly generated portfolio +#' vc.matrix <- matrix(rnorm(16), 4, 4) +#' skew <- .5 +#' kurtosis <- 1.2 +#' positions <- c(5, 2, 6, 10) +#' cl <- .95 +#' hp <- 280 +#' AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +#' +#' @export +AdjustedVarianceCovarianceES <- function(vc.matrix, mu, skew, kurtosis, + positions, cl, hp){ + + # Check that cl is read as a row vector + cl <- as.matrix(cl) + if (dim(cl)[1] > dim(cl)[2]) { + cl <- t(cl) + } + + # Check that hp is read as a column vector + hp <- as.matrix(hp) + if (dim(hp)[1] < dim(hp)[2]) { + hp <- t(hp) + } + + # Check that positions vector read as a scalar or row vector + positions <- as.matrix(positions) + if (dim(positions)[1] > dim(positions)[2]){ + positions <- t(positions) + } + + # Check that expected returns vector is read as a scalar or row vector + mu <- as.matrix(mu) + if (dim(mu)[1] > dim(mu)[2]){ + mu <- t(mu) + } + + # Check that dimensions are correct + if (max(dim(mu)) != max(dim(positions))){ + stop("Positions vector and expected returns vector must have same size") + } + if (max(dim(vc.matrix)) != max(dim(positions))){ + stop("Positions vector and expected returns vector must have same size") + } + + # Check that inputs obey sign and value restrictions + if (cl >= 1){ + stop("Confidence level must be less than 1") + } + if (cl <= 0){ + stop("Confidence level must be greater than 0"); + } + if (hp <= 0){ + stop("Holding period must be greater than 0"); + } + + # Portfolio return standard deviation + sigma <- positions %*% vc.matrix %*% t(positions)/(sum(positions)^2) # Initial + # standard deviation of portfolio returns + # VaR and ES estimation + z <- double(length(cl)) + adjustment <- z + VaR <- matrix(0, length(cl), length(hp)) + cl0 <- cl + term <- VaR + es <- VaR + delta.cl <- cl + for (i in 1:length(cl)) { + + # Cornish-Fisher adjustment + z[i] <- qnorm(1 - cl[i], 0 ,1) + adjustment[i] <- (1 / 6) * (z[i] ^ 2 - 1) * skew + (1 / 24) * + (z[i] ^ 3 - 3 * z[i]) * (kurtosis - 3) - (1 / 36) * + (2 * z[i] ^ 3 - 5 * z[i]) * skew ^ 2 + + for (j in 1:length(hp)){ + + VaR[i,j] <- - mu %*% t(positions) * hp[j] - (z[i] + adjustment[i]) * + sigma * (sum(positions)^2) * sqrt(hp[j]) # VaR + # ES Estimation + n <- 1000 # Number of slives into which tail is divided + cl0[i] <- cl[i] # Initial confidence level + term[i, j] <- VaR[i, j] + delta.cl[i] <- (1 - cl[i]) / n # Increment to confidence level as each + # slice is taken + + for (k in 1:(n - 1)) { + + cl[i] <- cl0[i] + k * delta.cl[i] # Revised cl + z[i] <- qnorm(1 - cl[i], 0, 1) + adjustment[i]=(1 / 6) * (z[i] ^ 2 - 1) * skew + (1 / 24) * + (z[i] ^ 3 - 3 * z[i]) * (kurtosis - 3) - (1 / 36) * + (2 * z[i] ^ 3 - 5 * z[i]) * skew ^ 2 + term[i, j] <- term[i, j] - mu %*% t(positions) * hp[j] - + (z[i] + adjustment) * sigma * (sum(positions)^2) * sqrt(hp[j]) + + } + es[i, j] <- term[i, j]/n + + } + } + y <- t(es) + return(es) + +} Added: pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd =================================================================== --- pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd (rev 0) +++ pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd 2015-06-18 21:54:56 UTC (rev 3680) @@ -0,0 +1,45 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AdjustedVarianceCovarianceES.R +\name{AdjustedVarianceCovarianceES} +\alias{AdjustedVarianceCovarianceES} +\title{Cornish-Fisher adjusted Variance-Covariance ES} +\usage{ +AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Return skew} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar} + +\item{kurtisos}{Return kurtosis} +} +\description{ +Function estimates the Variance-Covariance ES of a multi-asset +portfolio using the Cornish - Fisher adjustment for portfolio return +non-normality, for specified confidence level and holding period. +} +\examples{ +# Variance-covariance ES for randomly generated portfolio + vc.matrix <- matrix(rnorm(16), 4, 4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5, 2, 6, 10) + cl <- .95 + hp <- 280 + AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Fri Jun 19 00:35:27 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 19 Jun 2015 00:35:27 +0200 (CEST) Subject: [Returnanalytics-commits] r3681 - in pkg/Dowd: . R man Message-ID: <20150618223527.327A6187B00@r-forge.r-project.org> Author: dacharya Date: 2015-06-19 00:35:26 +0200 (Fri, 19 Jun 2015) New Revision: 3681 Added: pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd Modified: pkg/Dowd/NAMESPACE pkg/Dowd/R/AdjustedNormalESHotspots.R pkg/Dowd/R/AdjustedNormalVaRHotspots.R pkg/Dowd/man/AdjustedNormalESHotspots.Rd pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd Log: AdjustedVarianceCovarianceVaR: source and documentation Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-18 21:54:56 UTC (rev 3680) +++ pkg/Dowd/NAMESPACE 2015-06-18 22:35:26 UTC (rev 3681) @@ -4,6 +4,7 @@ export(AdjustedNormalESHotspots) export(AdjustedNormalVaRHotspots) export(AdjustedVarianceCovarianceES) +export(AdjustedVarianceCovarianceVaR) export(BinomialBacktest) export(BlancoIhleBacktest) export(BootstrapES) Modified: pkg/Dowd/R/AdjustedNormalESHotspots.R =================================================================== --- pkg/Dowd/R/AdjustedNormalESHotspots.R 2015-06-18 21:54:56 UTC (rev 3680) +++ pkg/Dowd/R/AdjustedNormalESHotspots.R 2015-06-18 22:35:26 UTC (rev 3681) @@ -20,7 +20,7 @@ #' #' # Hotspots for ES for randomly generated portfolio #' vc.matrix <- matrix(rnorm(16),4,4) -#' return <- rnorm(4) +#' mu <- rnorm(4) #' skew <- .5 #' kurtosis <- 1.2 #' positions <- c(5,2,6,10) Modified: pkg/Dowd/R/AdjustedNormalVaRHotspots.R =================================================================== --- pkg/Dowd/R/AdjustedNormalVaRHotspots.R 2015-06-18 21:54:56 UTC (rev 3680) +++ pkg/Dowd/R/AdjustedNormalVaRHotspots.R 2015-06-18 22:35:26 UTC (rev 3681) @@ -20,13 +20,13 @@ #' #' # Hotspots for ES for randomly generated portfolio #' vc.matrix <- matrix(rnorm(16),4,4) -#' return <- rnorm(4) +#' mu <- rnorm(4) #' skew <- .5 #' kurtosis <- 1.2 #' positions <- c(5,2,6,10) #' cl <- .95 #' hp <- 280 -#' AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +#' AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) #' #' @export AdjustedNormalVaRHotspots <- function(vc.matrix, mu, skew, kurtosis, positions, cl, hp){ Added: pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R =================================================================== --- pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R (rev 0) +++ pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R 2015-06-18 22:35:26 UTC (rev 3681) @@ -0,0 +1,94 @@ +#' @title Cornish-Fisher adjusted variance-covariance VaR +#' +#' @description Estimates the variance-covariance VaR of a multi-asset portfolio using the Cornish-Fisher adjustment for portfolio-return non-normality, for specified confidence level and holding period. +#' +#' @param vc.matrix Assumed variance covariance matrix for returns +#' @param mu Vector of expected position returns +#' @param skew Portfolio return skewness +#' @param kurtisos Portfolio return kurtosis +#' @param positions Vector of positions +#' @param cl Confidence level and is scalar or vector +#' @param hp Holding period and is scalar or vector +#' +#' @references Dowd, K. Measurh ing Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' +#' @examples +#' +#' # Variance-covariance for randomly generated portfolio +#' vc.matrix <- matrix(rnorm(16),4,4) +#' return <- rnorm(4) +#' skew <- .5 +#' kurtosis <- 1.2 +#' positions <- c(5,2,6,10) +#' cl <- .95 +#' hp <- 280 +#' AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +#' +#' @export +AdjustedVarianceCovarianceVaR <- function(vc.matrix, mu, skew, kurtosis, positions, cl, hp){ + + # Check that confidence level is read as a row vector + cl <- as.matrix(cl) + if (dim(cl)[1] > dim(cl)[2]){ + cl <- t(cl) + } + + # Check that hp is read as a column vector + hp <- as.matrix(hp) + if (dim(hp)[1] < dim(hp)[2]){ + hp <- t(hp) + } + + # Check that positions vector read as a scalar or row vector + positions <- as.matrix(positions) + if (dim(positions)[1] > dim(positions)[2]){ + positions <- t(positions) + } + + # Check that expected returns vector is read as a scalar or row vector + mu <- as.matrix(mu) + if (dim(mu)[1] > dim(mu)[2]){ + mu <- t(mu) + } + + # Check that dimensions are correct + if (max(dim(mu)) != max(dim(positions))){ + stop("Positions vector and expected returns vector must have same size") + } + vc.matrix <- as.matrix(vc.matrix) + if (max(dim(vc.matrix)) != max(dim(positions))){ + stop("Positions vector and expected returns vector must have same size") + } + + # Check that inputs obey sign and value restrictions + if (cl >= 1){ + stop("Confidence level must be less than 1") + } + if (cl <= 0){ + stop("Confidence level must be greater than 0"); + } + if (hp <= 0){ + stop("Holding period must be greater than 0"); + } + + # Portfolio return standard deviation + sigma <- positions %*% vc.matrix %*% t(positions)/(sum(positions)^2) # standard deviation of portfolio returns + # VaR estimation + z <- double(length(cl)) + adjustment <- z + VaR <- matrix(0, length(cl), length(hp)) + + for (i in 1:length(cl)) { + # Cornish-Fisher adjustment + z[i] <- qnorm(1 - cl[i], 0, 1) + adjustment[i] <- (1 / 6) * (z[i] ^ 2 - 1) * skew + (1 / 24) * (z[i] ^ 3 - 3 * z[i]) * (kurtosis - 3) - (1 / 36) * (2 * z[i] ^ 3 - 5 * z[i]) * skew ^ 2 + for (j in 1:length(hp)) { + VaR[i, j] <- - mu %*% t(positions) * hp[j] - (z[i] + adjustment[i]) * sigma * (sum(positions)^2) * sqrt(hp[j]) + } + } + y <- t(VaR) + return(y) + +} \ No newline at end of file Modified: pkg/Dowd/man/AdjustedNormalESHotspots.Rd =================================================================== --- pkg/Dowd/man/AdjustedNormalESHotspots.Rd 2015-06-18 21:54:56 UTC (rev 3680) +++ pkg/Dowd/man/AdjustedNormalESHotspots.Rd 2015-06-18 22:35:26 UTC (rev 3681) @@ -29,7 +29,7 @@ \examples{ # Hotspots for ES for randomly generated portfolio vc.matrix <- matrix(rnorm(16),4,4) - return <- rnorm(4) + mu <- rnorm(4) skew <- .5 kurtosis <- 1.2 positions <- c(5,2,6,10) Modified: pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd =================================================================== --- pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd 2015-06-18 21:54:56 UTC (rev 3680) +++ pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd 2015-06-18 22:35:26 UTC (rev 3681) @@ -29,13 +29,13 @@ \examples{ # Hotspots for ES for randomly generated portfolio vc.matrix <- matrix(rnorm(16),4,4) - return <- rnorm(4) + mu <- rnorm(4) skew <- .5 kurtosis <- 1.2 positions <- c(5,2,6,10) cl <- .95 hp <- 280 - AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) + AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) } \author{ Dinesh Acharya Added: pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd =================================================================== --- pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd (rev 0) +++ pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd 2015-06-18 22:35:26 UTC (rev 3681) @@ -0,0 +1,44 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AdjustedVarianceCovarianceVaR.R +\name{AdjustedVarianceCovarianceVaR} +\alias{AdjustedVarianceCovarianceVaR} +\title{Cornish-Fisher adjusted variance-covariance VaR} +\usage{ +AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Assumed variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Portfolio return skewness} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar or vector} + +\item{hp}{Holding period and is scalar or vector} + +\item{kurtisos}{Portfolio return kurtosis} +} +\description{ +Estimates the variance-covariance VaR of a multi-asset portfolio using the Cornish-Fisher adjustment for portfolio-return non-normality, for specified confidence level and holding period. +} +\examples{ +# Variance-covariance for randomly generated portfolio + vc.matrix <- matrix(rnorm(16),4,4) + return <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,10) + cl <- .95 + hp <- 280 + AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measurh ing Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Sat Jun 20 10:11:15 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sat, 20 Jun 2015 10:11:15 +0200 (CEST) Subject: [Returnanalytics-commits] r3682 - in pkg/Meucci: . R demo man Message-ID: <20150620081116.03503187008@r-forge.r-project.org> Author: xavierv Date: 2015-06-20 10:11:15 +0200 (Sat, 20 Jun 2015) New Revision: 3682 Modified: pkg/Meucci/NAMESPACE pkg/Meucci/R/DetectOutliersviaMVE.R pkg/Meucci/R/EntropyProg.R pkg/Meucci/R/FullyFlexibleBayesNets.R pkg/Meucci/R/HermiteGrid.R pkg/Meucci/R/data.R pkg/Meucci/demo/DetectOutliersviaMVE.R pkg/Meucci/demo/FullFlexProbs.R pkg/Meucci/demo/FullyFlexibleBayesNets.R pkg/Meucci/demo/FullyIntegratedLiquidityAndMarketRisk.R pkg/Meucci/demo/HermiteGrid_CVaR_Recursion.R pkg/Meucci/demo/HermiteGrid_CaseStudy.R pkg/Meucci/demo/HermiteGrid_demo.R pkg/Meucci/demo/RobustBayesianAllocation.R pkg/Meucci/man/ComputeMVE.Rd pkg/Meucci/man/ComputeMoments.Rd pkg/Meucci/man/CondProbViews.Rd pkg/Meucci/man/DetectOutliersViaMVE.Rd pkg/Meucci/man/Equities.Rd pkg/Meucci/man/NoisyObservations.Rd pkg/Meucci/man/RejectOutlier.Rd pkg/Meucci/man/StockSeries.Rd pkg/Meucci/man/TimeSeries.Rd pkg/Meucci/man/Tweak.Rd pkg/Meucci/man/UsSwapRates.Rd pkg/Meucci/man/bondAttribution.Rd pkg/Meucci/man/butterfliesAnalytics.Rd pkg/Meucci/man/covNRets.Rd pkg/Meucci/man/db.Rd pkg/Meucci/man/dbFFP.Rd pkg/Meucci/man/db_FX.Rd pkg/Meucci/man/derivatives.Rd pkg/Meucci/man/fILMR.Rd pkg/Meucci/man/factorsDistribution.Rd pkg/Meucci/man/fixedIncome.Rd pkg/Meucci/man/freaqEst.Rd pkg/Meucci/man/gaussHermiteMesh.Rd pkg/Meucci/man/hermitePolynomial.Rd pkg/Meucci/man/highYieldIndices.Rd pkg/Meucci/man/implVol.Rd pkg/Meucci/man/integrateSubIntervals.Rd pkg/Meucci/man/kernelbw.Rd pkg/Meucci/man/kernelcdf.Rd pkg/Meucci/man/kernelinv.Rd pkg/Meucci/man/kernelpdf.Rd pkg/Meucci/man/linearModel.Rd pkg/Meucci/man/normalizeProb.Rd pkg/Meucci/man/private_fun.Rd pkg/Meucci/man/returnsDistribution.Rd pkg/Meucci/man/sectorsSnP500.Rd pkg/Meucci/man/sectorsTS.Rd pkg/Meucci/man/securitiesIndustryClassification.Rd pkg/Meucci/man/securitiesTS.Rd pkg/Meucci/man/subIntervals.Rd pkg/Meucci/man/swap2y4y.Rd pkg/Meucci/man/swapParRates.Rd pkg/Meucci/man/swaps.Rd Log: - Formatted demo scripts and its functions up to HermiteGrid_demo Modified: pkg/Meucci/NAMESPACE =================================================================== --- pkg/Meucci/NAMESPACE 2015-06-18 22:35:26 UTC (rev 3681) +++ pkg/Meucci/NAMESPACE 2015-06-20 08:11:15 UTC (rev 3682) @@ -43,6 +43,7 @@ export(MvnRnd) export(NoisyObservations) export(NormalCopulaPdf) +export(PHist) export(PanicCopula) export(PartialConfidencePosterior) export(PerformIidAnalysis) Modified: pkg/Meucci/R/DetectOutliersviaMVE.R =================================================================== --- pkg/Meucci/R/DetectOutliersviaMVE.R 2015-06-18 22:35:26 UTC (rev 3681) +++ pkg/Meucci/R/DetectOutliersviaMVE.R 2015-06-20 08:11:15 UTC (rev 3682) @@ -1,16 +1,18 @@ -#' Finds the "worst" outlier in a multivariate time series +#' @title Finds the "worst" outlier in a multivariate time series #' -#' Finds the "worst" outlier in a multivariate time-series +#' @description Finds the "worst" outlier in a multivariate time series. +#' #' We aim at finding the the observation x_t such that if we remove it from the -#' set {x_1 ... x_t } the determinant of the resulting sample covariance is reduced the most -#' This means that by dropping that observation the location-dispersion ellipsoid defined -#' by the sample mean and covariance shrinks the most -#' See Sec. 4.6.1 of "Risk and Asset Allocation" - Springer (2005), by A. Meucci -#' for the theory and the routine implemented below +#' set {x_1 ... x_t } the determinant of the resulting sample covariance is +#' reduced the most. This means that by dropping that observation the +#' location-dispersion ellipsoid defined by the sample mean and covariance +#' shrinks the most. See Sec. 4.6.1 of "Risk and Asset Allocation" - Springer +#' (2005), by A. Meucci for the theory and the routine implemented below #' #' @param sample a vector containing the input dataset with outliers #' -#' @return rejected a numeric indicating which observation in the index to reject +#' @return rejected a numeric indicating which observation in the index to +#' reject #' #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} #' @@ -18,29 +20,35 @@ #' \url{http://www.symmys.com} #' See Meucci script for "RejectOutlier.m" #' @export -RejectOutlier = function( sample ) -{ - library( matlab ) - + +RejectOutlier <- function(sample) { + library(matlab) # parameter checks - if ( ncol( sample ) > nrow( sample ) ) { stop("The number of assets must be greater than number of observations (otherwise system is singular)") } - + if (ncol(sample) > nrow(sample)) { + stop("The number of assets must be greater than number of observations + (otherwise system is singular)") + } + # initialize parameters - T = nrow( sample ) - m = matrix( colMeans( sample ) , nrow = ncol( sample ) ) - U = sample - ones( T , 1 ) %*% t( m ) - + T <- nrow(sample) + m <- matrix(colMeans(sample), nrow = ncol(sample)) + U <- sample - ones(T, 1) %*% t(m) + # measure lambdas associated with each observation - lambdas = diag( U %*% solve( t(U) %*% U ) %*% t(U) ) # result is from Poston, Wegman, Priebe and Solka (1997) - # the various lambdas denote the t-th element of the diagonal of the information matrix + + # result is from Poston, Wegman, Priebe and Solka (1997) + lambdas <- diag(U %*% solve(t(U) %*% U) %*% t(U)) + # the various lambdas denote the t-th element of the diagonal of the + # information matrix # the farthest outlier corresponds to the highest value of lambda - a = max( lambdas ) - rejected = which.max( lambdas ) # identify the farthest outlier - - if ( max(lambdas > 1) == 1 ) { stop( "Lambdas cannot be greater than 1")} - if ( max(lambdas < 0) == 1 ) { stop( "Lambdas cannot be less than 0")} - - return( list( rejected = rejected , lambdas = lambdas ) ) + rejected <- which.max(lambdas) # identify the farthest outlier + + if (max(lambdas > 1) == 1) + stop("Lambdas cannot be greater than 1") + if (max(lambdas < 0) == 1) + stop("Lambdas cannot be less than 0") + + return(list(rejected = rejected, lambdas = lambdas)) } #' Compute the minimum volume ellipsoid for a given (multi-variate) time-series @@ -49,7 +57,7 @@ #' #' via the expectations-minimization algorithm #' -#' \deqn{ w_{t} = \frac{1}{T} , t = 1,...,T +#' \deqn{ w_{t} = \frac{1}{T}, t = 1,...,T #' \\ m \equiv \frac{1}{ \sum_{s=1}^T w_{s} } \sum_{t=1}^T w_{t} x_{t} #' \\ S \equiv \sum_{t=1}^T w_{t} \big(x_{t} - m\big) \big(x_{t} - m\big)' #' \\ Ma_{t}^{2} \equiv \big(x-m\big)' S^{-1} \big(x-m\big), t=1,...,T @@ -60,171 +68,199 @@ #' The location and scatter parameters that define the ellipsoid are #' multivariate high-breakdown estimators of location and scatter #' -#' @param data a matrix time-series of data. Each row is a observation (date). Each column is an asset -#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} +#' @param data a matrix time-series of data. Each row is a observation +#' (date). Each column is an asset +#' #' @return list a list with -#' MVE_Location a numeric with the location parameter of minimum volume ellipsoid -#' MVE_Dispersion a numeric with the covariance matrix of the minimum volume ellipsoid +#' MVE_Location a numeric with the location parameter of minimum volume +#' ellipsoid +#' MVE_Dispersion a numeric with the covariance matrix of the minimum +#' volume ellipsoid #' #' @references -#' \url{http://www.symmys.com/sites/default/files/Risk\%20and\%20Asset\%20Allocation\%20-\%20Springer\%20Quantitative\%20Finance\%20-\%20Estimation.pdf} #' See Sec. 4.6.1 of "Risk and Asset Allocation" - Springer (2005), by A. Meucci #' for the theory and the routine implemented below #' See Meucci script for "ComputeMVE.m" +#' +#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} +#' #' @export -#' -ComputeMVE = function ( data ) -{ - library( matlab ) - NumObservations = nrow( data ) - Ones = ones( NumObservations , 1 ) - det_S_New = 0 - + +ComputeMVE <- function (data) { + library(matlab) + NumObservations <- nrow(data) + Ones <- ones(NumObservations, 1) + det_S_New <- 0 + # step 0: initialize the relative weights - w = 1 / NumObservations * Ones - + w <- 1 / NumObservations * Ones + # step 1: compute the location parameter (m), and the scatter matrix (S) - m = matrix( colMeans( data ) , nrow = ncol( data ) ) - S = cov( data ) # notice the weights in the scatter matrix are not normalized - - keeploop = TRUE - while ( keeploop == TRUE ) - { - Mahalanobis = matrix( , ncol = 0 , nrow = 1 ) - for ( t in 1:NumObservations ) - { + m <- matrix(colMeans(data), nrow = ncol(data)) + S <- cov(data) # notice the weights in the scatter matrix are not normalized + + keeploop <- TRUE + while (keeploop == TRUE) { + Mahalanobis <- matrix(, ncol = 0, nrow = 1) + for (t in 1:NumObservations) { # cycle thru each observation... - x_t = t( data[ t , , drop = FALSE ] ) - + x_t <- t(data[t, , drop = FALSE]) + # ...and calculate the square Mahalanobis distances - Mahalanobis = cbind( Mahalanobis , t((x_t - m)) %*% solve(S) %*% ( x_t - m ) ) - } - # Step 3: update the weights if the Mahalanobis distance squared > 1 as follows... - update = matlab:::find(Mahalanobis > 1 ) - w[ update ] = w[ update ] * t( Mahalanobis[ update ] ) + Mahalanobis <- cbind(Mahalanobis, t((x_t - m)) %*% solve(S) %*% (x_t - m)) + } + # Step 3: update the weights if Mahalanobis distance squared > 1 as follows + update <- matlab:::find(Mahalanobis > 1) + w[update] <- w[update] * t(Mahalanobis[update]) # ... otherwise leave the weight unchanged - - # Step 4: If convergence is reached, stop and define mu and Sigma, otherwise go to Step 1 - m = t( data ) %*% w / sum (w ) - S = t(( data - Ones %*% t( m ) )) %*% diag( as.vector( w ) ) %*% ( data - Ones %*% t(m) ) - - det_S_Old = det_S_New - det_S_New = base:::det(S) - - exitFlag = ( ( det_S_Old / det_S_New ) < .99999 ) # loop exits when evaluates to FALSE - - if ( det_S_New == 0 ) { exitFlag = TRUE } - - if ( !is.logical( exitFlag ) ) { browser() } - - keeploop = ( exitFlag ) - } - - MVE_Location = m - MVE_Dispersion = S - - return( list( MVE_Location = MVE_Location , MVE_Dispersion = MVE_Dispersion ) ) + + # Step 4: If convergence is reached, stop and define mu and Sigma, + # otherwise go to Step 1 + m <- t(data) %*% w / sum (w) + S <- t((data - Ones %*% t(m))) %*% diag(as.vector(w)) %*% (data - + Ones %*% t(m)) + + det_S_Old <- det_S_New + det_S_New <- base:::det(S) + + # loop exits when evaluates to FALSE + exitFlag <- ((det_S_Old / det_S_New) < .99999) + + if (det_S_New == 0) + exitFlag <- TRUE + + if (!is.logical(exitFlag)) + browser() + + keeploop <- (exitFlag) + } + + MVE_Location <- m + MVE_Dispersion <- S + + return(list(MVE_Location = MVE_Location, MVE_Dispersion = MVE_Dispersion)) } -#' Use the minimum volume ellipsoid to detect outliers +#' @title Use the minimum volume ellipsoid to detect outliers #' -#' See Sec. 4.6.1 of "Risk and Asset Allocation" - Springer (2005), by A. Meucci -#' for the theory and the routine implemented below +#' @description Use the minimum volume ellipsoid to detect outliers. See Sec. +#' 4.6.1 of "Risk and Asset Allocation" - Springer (2005), by A. Meucci for the +#' theory and the routine implemented below. #' -#' @param corruptSample a matrix of returns with outlier data. Rows are observations, columns are assets. +#' @param corruptSample a matrix of returns with outlier data. Rows are +#' observations, columns are assets. #' #' @return a list containing: -#' plotdata a matrix of data used to plot minimum volume ellipsoid as a function of its length -#' cutofflist an ordering of observations with the highest Mahalanobis distance (i.e. ordering of outliers by their index )#' -#' numOutliers returns the number of outliers based on the slope of the minimum volume ellipsoid as a function of sample data +#' plotdata a matrix of data used to plot minimum volume ellipsoid as a +#' function of its length +#' cutofflist an ordering of observations with the highest Mahalanobis +#' distance (i.e. ordering of outliers by their index) +#' numOutliers returns the number of outliers based on the slope of the +#' minimum volume ellipsoid as a function of sample data #' #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} #' @references #' \url{http://www.symmys.com} #' See Meucci script for "S_HighBreakdownMVE.m" #' @export -DetectOutliersViaMVE = function( corruptSample ) -{ - library( matlab ) - + +DetectOutliersViaMVE <- function(corruptSample) { + # parameter checks - if ( ncol( corruptSample ) > nrow( corruptSample ) ) { stop("The number of assets must be greater than number of observations (otherwise system is singular)") } - + if (ncol(corruptSample) > nrow(corruptSample)) { + stop("The number of assets must be greater than number of observations + (otherwise system is singular)") + } + # initialize variables - T = nrow( corruptSample ) - index = seq( from = 1 , to = T , 1 ) - vol_MVE = sample_Length = matrix( , nrow = 1 , ncol = 0 ) - store = rep( list() , length = ceil( T / 2 ) ) - - lambdas = RejectOutlier( corruptSample )$lambdas - cutofflist = order( lambdas , decreasing = TRUE ) - + T <- nrow(corruptSample) + index <- seq(from = 1, to = T, 1) + vol_MVE <- sample_Length <- matrix(, nrow = 1, ncol = 0) + store <- rep(list(), length = ceil(T / 2)) + + lambdas <- RejectOutlier(corruptSample)$lambdas + cutofflist <- order(lambdas, decreasing = TRUE) + # compute high-breakdown estimates - for ( j in 1:ceil( T / 2 ) ) # stop when the number of data left is less than half the original sample, otherwise repeat - { - # step 1: compute MVE location and dispersion - MVE = ComputeMVE( corruptSample ) - + + # stop when the number of data left is less than half the original sample, + # otherwise repeat + for (j in 1:ceil(T / 2)) { + # step 1: compute MVE location and dispersion + MVE <- ComputeMVE(corruptSample) + # store results - store[[j]]$MVE_Location = MVE$MVE_Location - store[[j]]$MVE_Dispersion = MVE$MVE_Dispersion - - sample_Length = cbind( sample_Length , nrow( corruptSample ) ) - vol_MVE = cbind( vol_MVE , sqrt( det( MVE$MVE_Dispersion ) ) ) - - store[[j]]$index = index - - # step 2: find the farthest outlier among the data and remove the observation (one at a time) - rejected = RejectOutlier( corruptSample )$rejected - corruptSample = corruptSample[ -rejected , ] # drop outlier rows from sample - index = index[ -rejected ] + store[[j]]$MVE_Location <- MVE$MVE_Location + store[[j]]$MVE_Dispersion <- MVE$MVE_Dispersion + + sample_Length <- cbind(sample_Length, nrow(corruptSample)) + vol_MVE <- cbind(vol_MVE, sqrt(det(MVE$MVE_Dispersion))) + + store[[j]]$index <- index + + # step 2: find the farthest outlier among the data and remove the + # observation (one at a time) + rejected <- RejectOutlier(corruptSample)$rejected + corruptSample <- corruptSample[-rejected, ] # drop outlier rows from sample + index <- index[-rejected] } - - # plot volume of ellipsoid as function of sample length + + # plot volume of ellipsoid as function of sample length # shows an abrupt jump when the first outlier is added to the data - # The respective sample covariance is the minimum covariance determinant and the respective ellipsoid - plot( sample_Length , vol_MVE , type = "l" , main = "Outlier detection" , ylab = "volume of Min volume ellipsoid" , xlab = "sample length" ) - + # The respective sample covariance is the minimum covariance determinant and + # the respective ellipsoid + plot(sample_Length, vol_MVE, type = "l", main = "Outlier detection", + ylab = "volume of Min volume ellipsoid", xlab = "sample length") + # return the minimum volume ellipsoid at each sample length - result = rbind( sample_Length , vol_MVE ) - rownames( result ) = c("index" , "volumeMVE" ) - - # TODO: measure the slope of result$volumeMVE. When slope doubles that marks the first outlier - numOutliers = NULL - - return( list( plotdata = t( result ) , cutofflist = cutofflist , numOutliers = numOutliers ) ) + result <- rbind(sample_Length, vol_MVE) + rownames(result) = c("index", "volumeMVE") + + # TODO: measure the slope of result$volumeMVE. + # When slope doubles that marks the first outlier + numOutliers <- NULL + + return(list(plotdata = t(result), cutofflist = cutofflist, + numOutliers = numOutliers)) } -#' Generate observations from a two asset covariance matrix and add outliers +#' @title Generate observations from a covariance matrix and add outliers #' -#' Generate observations from a covariance matrix and add outliers +#' @description Generate observations from a two asset covariance matrix and add outliers #' -#' @param numGoodSamples number of observations drawn from the covariance matrix +#' @param numGoodSamples number of observations drawn from the +#' covariance matrix #' @param numOutliers number of outliers added to sample -#' @param covarianceMatrix the covariance matrix for the asset returns from which good samples will be drawn -#' @param shuffle a boolean suggesting whether order of the twos should be shuffled +#' @param covarianceMatrix the covariance matrix for the asset returns +#' from which good samples will be drawn +#' @param shuffle a boolean suggesting whether order of the twos +#' should be shuffled #' -#' @return sample a matrix of returns consisting of good and bad sample. Rows are observations, columns are the assets. +#' @return sample a matrix of returns consisting of good and bad sample. +#' Rows are observations, columns are the assets. #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} #' @export -NoisyObservations = function( numGoodSamples , numOutliers , covarianceMatrix , shuffle = FALSE ) -{ - mu = matrix( rep( 0 , nrow( covarianceMatrix ) ) ) - T = numGoodSamples - + +NoisyObservations <- function(numGoodSamples, numOutliers, covarianceMatrix, + shuffle = FALSE) { + mu <- matrix(rep(0, nrow(covarianceMatrix))) + T <- numGoodSamples + require("MASS") # "good" observations - library( MASS ) - sample = mvrnorm( n = T , mu = mu , Sigma = covarianceMatrix ) # draw T samples from mvrnorm distribution - + + # draw T samples from mvrnorm distribution + sample <- mvrnorm(n = T, mu = mu, Sigma = covarianceMatrix) # generate outliers - outliers = 10 * matrix( runif( numOutliers * nrow( covarianceMatrix ) ) , nrow = numOutliers , ncol = ncol( covarianceMatrix ) ) - + outliers <- 10 * matrix(runif(numOutliers * nrow(covarianceMatrix)), + nrow = numOutliers, ncol = ncol(covarianceMatrix)) + # add "bad" observation(s) - corruptSample = rbind ( sample , outliers ) - + corruptSample <- rbind (sample, outliers) + # shuffle rows - if ( shuffle == TRUE ) { corruptSample = corruptSample[ sample( nrow( corruptSample ) ) , ] } - - return( corruptSample = corruptSample ) + if (shuffle == TRUE) + corruptSample <- corruptSample[sample(nrow(corruptSample)), ] + + return(corruptSample = corruptSample) } Modified: pkg/Meucci/R/EntropyProg.R =================================================================== --- pkg/Meucci/R/EntropyProg.R 2015-06-18 22:35:26 UTC (rev 3681) +++ pkg/Meucci/R/EntropyProg.R 2015-06-20 08:11:15 UTC (rev 3682) @@ -311,6 +311,8 @@ #' See Meucci script pHist.m used for plotting #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and Xavier Valls #' \email{xaviervallspla@@gmail.com} +#' +#' @export PHist <- function(X, p, nBins, freq = FALSE) { Modified: pkg/Meucci/R/FullyFlexibleBayesNets.R =================================================================== --- pkg/Meucci/R/FullyFlexibleBayesNets.R 2015-06-18 22:35:26 UTC (rev 3681) +++ pkg/Meucci/R/FullyFlexibleBayesNets.R 2015-06-20 08:11:15 UTC (rev 3682) @@ -1,9 +1,10 @@ #' Input conditional views #' #' statement: View(k).Who (e.g. [1 3])= View(k).Equal (e.g. {[2 3] [1 3 5]}) -#' optional conditional statement: View(k).Cond_Who (e.g. [2])= View(k).Cond_Equal (e.g. {[1]}) -#' amount of stress is quantified as Prob(statement) <= View(k).v if View(k).sgn = 1; -#' Prob(statement) >= View(k).v if View(k).sgn = -1; +#' optional conditional statement: View(k).Cond_Who (e.g. [2]) = +#' View(k).Cond_Equal (e.g. {[1]}) +#' amount of stress quantified as Prob(statement)<=View(k).v if View(k).sgn = 1 +#' Prob(statement)>=View(k).v if View(k).sgn = -1 #' #' confidence in stress is quantified in View(k).c in (0,1) #' @@ -15,145 +16,169 @@ #' @return g TBD #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} #' @export -CondProbViews = function( View , X ) -{ - # initialize parameters - A = matrix( , nrow = 0 , ncol = nrow( X ) ) - b = g = matrix( , nrow = 0 , ncol = 1 ) - - # for each view... - for ( k in 1:length( View ) ) { - I_mrg = ( X[ , 1] < Inf ) - - for ( s in 1:length( View[[k]]$Who ) ) - { - Who = View[[k]]$Who[s] - Or_Targets = View[[k]]$Equal[[s]] - I_mrg_or = ( X[ , Who] > Inf ) - for ( i in 1:length( Or_Targets ) ) { I_mrg_or = I_mrg_or | ( X[ , Who ] == Or_Targets[i] ) } # element-wise logical OR - I_mrg = I_mrg & I_mrg_or # element-wise logical AND + +CondProbViews <- function(View, X) { + # initialize parameters + A <- matrix(, nrow = 0, ncol = nrow(X)) + b <- g <- matrix(, nrow = 0, ncol = 1) + + # for each view... + for (k in 1:length(View)) { + I_mrg <- (X[, 1] < Inf) + + for (s in 1:length(View[[k]]$Who)) { + Who <- View[[k]]$Who[s] + Or_Targets <- View[[k]]$Equal[[s]] + I_mrg_or <- (X[, Who] > Inf) + for (i in 1:length(Or_Targets)) { + I_mrg_or <- I_mrg_or | (X[, Who] == Or_Targets[i]) + } # element-wise logical OR + I_mrg <- I_mrg & I_mrg_or # element-wise logical AND } - - I_cnd = ( X[ , 1 ] < Inf ) - - if ( length( View[[k]]$Cond_Who ) != 0) # If length of Cond_Who is zero, skip - { - for ( s in 1:length( View[[k]]$Cond_Who ) ) - { - Who = View[[k]]$Cond_Who[s] - Or_Targets = View[[k]]$Cond_Equal[[s]] - I_cnd_or = ( X[ , Who ] > Inf ) - for ( i in 1:length( Or_Targets ) ) { I_cnd_or = I_cnd_or | X[ ,Who ] == Or_Targets[i] } - I_cnd = I_cnd & I_cnd_or + + I_cnd <- (X[, 1] < Inf) + # If length of Cond_Who is zero, skip + if (length(View[[k]]$Cond_Who) != 0) { + for (s in 1:length(View[[k]]$Cond_Who)) { + Who <- View[[k]]$Cond_Who[s] + Or_Targets <- View[[k]]$Cond_Equal[[s]] + I_cnd_or <- (X[, Who] > Inf) + for (i in 1:length(Or_Targets)) { + I_cnd_or <- I_cnd_or | X[,Who] == Or_Targets[i] + } + I_cnd <- I_cnd & I_cnd_or } } - - I_jnt=I_mrg & I_cnd - - if ( !isempty( View[[k]]$Cond_Who ) ) - { - New_A = View[[k]]$sgn %*% t( (I_jnt - View[[k]]$v * I_cnd) ) - New_b = 0 + + I_jnt <- I_mrg & I_cnd + + if (!isempty(View[[k]]$Cond_Who)) { + New_A <- View[[k]]$sgn %*% t((I_jnt - View[[k]]$v * I_cnd)) + New_b <- 0 } - else - { - New_A = View[[k]]$sgn %*% t( I_mrg ) - New_b = View[[k]]$sgn %*% View[[k]]$v + else { + New_A <- View[[k]]$sgn %*% t(I_mrg) + New_b <- View[[k]]$sgn %*% View[[k]]$v } - - A = rbind( A , New_A ) # constraint for the conditional expectations... - b = rbind( b , New_b ) - g = rbind( g , -log( 1 - View[[k]]$c ) ) + + A <- rbind(A, New_A) # constraint for the conditional expectations... + b <- rbind(b, New_b) + g <- rbind(g, -log(1 - View[[k]]$c)) } - return( list( A = A , b = b , g = g ) ) + return(list(A = A, b = b, g = g)) } #' tweak a matrix -#' @param A matrix A consisting of inequality constraints ( Ax <= b ) -#' @param b matrix b consisting of inequality constraint vector b ( Ax <= b ) -#' @param g TODO: TBD +#' @param A matrix A consisting of inequality constraints (Ax <= b) +#' @param b matrix b consisting of inequality constraint vector b (Ax <= b) +#' @param g TODO: TBD #' #' @return db #' @export #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} -Tweak = function( A , b , g ) -{ - library( matlab ) - library( limSolve ) - - K = nrow( A ) - J = ncol( A ) - - g_ = rbind( g , zeros( J , 1 ) ) - - Aeq_ = cbind( zeros( 1 , K ) , ones( 1 , J ) ) - beq_ = 1 - - lb_ = rbind( zeros( K , 1 ) , zeros( J , 1 ) ) - ub_ = rbind( Inf * ones( K , 1 ) , ones( J , 1 ) ) - - A_ = cbind( -eye( K ) , A ) - b_ = b - + +Tweak <- function(A, b, g) { + library(matlab) + library(limSolve) + + K <- nrow(A) + J <- ncol(A) + + g_ <- rbind(g, zeros(J, 1)) + + Aeq_ <- cbind(zeros(1, K), ones(1, J)) + beq_ <- 1 + + lb_ <- rbind(zeros(K, 1), zeros(J, 1)) + ub_ <- rbind(Inf * ones(K, 1), ones(J, 1)) + + A_ <- cbind(-eye(K), A) + b_ <- b + # add lower-bound and upper-bound constraints - A_ = rbind( A_ , -eye(ncol(A_)) ) - b_ = rbind( b_ , zeros( ncol(A_), 1) ) - - x0 = rep( 1/ncol( Aeq_ ) , ncol( Aeq_ ) ) - # db_ = linprog( g_ , A_ , b_ , Aeq_ ,beq_ , lb_ , ub_ ) # MATLAB version - # optimResult = linp( E = Aeq_ , # matrix containing coefficients of equality constraints Ex=F - # F = beq_ , # vector containing the right-hand side of equality constraints - # G = -1*A_ , # matrix containint coefficients of the inequality constraints GX >= H - # H = -1*b_ , # vector containing the right-hand side of the inequality constraints - # Cost = -1*g_ , # vector containing the coefficients of the cost function - # ispos = FALSE ) - - costFunction = function( x ) { matrix( x , nrow = 1 ) %*% matrix( -1*g_ , ncol = 1) } - gradient = function( x ) { -1*g_ } - optimResult = optim( par = x0 , - fn = costFunction , # CHECK - gr = gradient , + A_ <- rbind(A_, -eye(ncol(A_))) + b_ <- rbind(b_, zeros(ncol(A_), 1)) + + x0 <- rep(1/ncol(Aeq_), ncol(Aeq_)) + + # db_ = linprog(g_, A_, b_, Aeq_,beq_, lb_, ub_) # MATLAB version + # matrix containing coefficients of equality constraints Ex=F + # optimResult = linp(E = Aeq_, + # vector containing the right-hand side of equality constraints + # F = beq_, + # matrix containint coefficients of the inequality constraints GX >= H + # G = -1*A_, + # vector containing the right-hand side of the inequality constraints + # H = -1*b_, + # vector containing the coefficients of the cost function + # Cost = -1*g_, + # ispos = FALSE) + + costFunction <- function(x) { + matrix(x, nrow = 1) %*% matrix(-1*g_, ncol = 1) + } + gradient <- function(x) { + -1*g_ + } + optimResult <- optim(par = x0, + fn = costFunction, # CHECK + gr = gradient, method = "L-BFGS-B", - lower = lb_ , - upper = ub_ , - hessian = FALSE ) - - # library( linprog ) - # optimResult2 = solveLP( E = Aeq_ , # numeric matrix containing coefficients of equality constraints Ex=F - # F = beq_ , # numeric vector containing the right-hand side of equality constraints - # G = -1*A_ , # numeric matrix containint coefficients of the inequality constraints GX >= H - # H = -1*b_ , # numeric vector containing the right-hand side of the inequality constraints - # Cost = -g_ , # numeric vector containing the coefficients of the cost function - # ispos = FALSE ) - - db_ = optimResult$X - - db = db_[ 1:K ] - - return( db ) + lower = lb_, + upper = ub_, + hessian = FALSE) + + # library(linprog) + # optimResult2 = solveLP(E = Aeq_, + # vector containing the right-hand side of equality constraints + # F = beq_, + # matrix containint coefficients of the inequality constraints GX >= H + # G = -1*A_, + # vector containing the right-hand side of the inequality constraints + # H = -1*b_, + # vector containing the coefficients of the cost function + # Cost = -1*g_, + # ispos = FALSE) + + db_ <- optimResult$X + + db <- db_[1:K] + + return(db) } -#' Takes a matrix of joint-scenario probability distributions and generates expectations, standard devation, and correlation matrix for the assets +#' @title Takes a matrix of joint-scenario probability distributions and +#' generates expectations, standard devation, and correlation matrix +#' for the assets #' -#' Takes a matrix of joint-scenario probability distributions and generates expectations, standard devation, and correlation matrix for the assets +#' @description Takes a matrix of joint-scenario probability distributions and +#' generates expectations, standard devation, and correlation +#' matrix for the assets #' -#' @param X a matrix of joint-probability scenarios (rows are scenarios, columns are assets) -#' @param p a numeric vector containing the probabilities for each of the scenarios in the matrix X +#' @param X a matrix of joint-probability scenarios (rows are scenarios, +#' columns are assets) +#' @param p a numeric vector containing the probabilities for each of the +#' scenarios in the matrix X #' -#' @return means a numeric vector of the expectations (probability weighted) for each asset -#' @return sd a numeric vector of standard deviations corresponding to the assets in the covariance matrix -#' @return correlationMatrix the correlation matrix resulting from converting the covariance matrix to a correlation matrix +#' @return means a numeric vector of the expectations +#' (probability weighted) for each asset +#' @return sd a numeric vector of standard deviations +#' corresponding to the assets in the covariance +#' matrix +#' @return correlationMatrix the correlation matrix resulting from +#' converting the covariance matrix to a +#' correlation matrix #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} #' @export -ComputeMoments = function( X , p ) -{ - library( matlab ) - J = nrow( X ) ; N = ncol( X ) - m = t(X) %*% p - Sm = t(X) %*% (X * repmat( p , 1 , N ) ) # repmat : repeats/tiles a matrix - S = Sm - m %*% t(m) - C = cov2cor( S ) # the correlation matrix - s = sqrt( diag( S ) ) # the vector of standard deviations - return( list( means = m , sd = s , correlationMatrix = C ) ) + +ComputeMoments <- function(X, p) { + library(matlab) + N <- ncol(X) + m <- t(X) %*% p + Sm <- t(X) %*% (X * repmat(p, 1, N)) # repmat : repeats/tiles a matrix + S <- Sm - m %*% t(m) + C <- cov2cor(S) # the correlation matrix + s <- sqrt(diag(S)) # the vector of standard deviations + return(list(means = m, sd = s, correlationMatrix = C)) } Modified: pkg/Meucci/R/HermiteGrid.R =================================================================== --- pkg/Meucci/R/HermiteGrid.R 2015-06-18 22:35:26 UTC (rev 3681) +++ pkg/Meucci/R/HermiteGrid.R 2015-06-20 08:11:15 UTC (rev 3682) @@ -1,67 +1,74 @@ #' Generates the normalized probability for an input probability value #' -#' @param p a numeric value containing the probability value required to be normalized +#' @param p a numeric value containing the probability value +#' required to be normalized #' -#' @return normalizedp a numeric value containing the normalized probability value +#' @return normalizedp a numeric value containing the normalized probability +#' value #' #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} #' @export -normalizeProb = function( p ) -{ - tol = 1e-20 - tmp = p - tmp[ tmp < tol ] = tol - normalizedp = exp( log( tmp ) - log( sum( tmp ) ) ) - - return( normalizedp ) + +normalizeProb <- function(p) { + + tol <- 1e-20 + tmp <- p + tmp[tmp < tol] <- tol + normalizedp <- exp(log(tmp) - log(sum(tmp))) + + return(normalizedp) } #' Generate the intervals containing jth point of the grid. #' -#' @param x a vector containing the scenarios +#' @param x a vector containing the scenarios #' #' @return a list containing #' @return xLB a vector containing the lower bound of each interval #' @return xUB a vector containing the upper bound of each interval -#" -#' \deqn{ I_{j} \equiv \big[ x_{j} - \frac{x_{j} - x_{j-1} }{2}, x_{j} + \frac{x_{j+1} - x_{j}}{2} \big) } -#' @references +#' +#' \deqn{ I_{j} \equiv \big[x_{j} - \frac{x_{j} - x_{j-1} }{2}, x_{j} + +#' \frac{x_{j+1} - x_{j}}{2} \big) } +#' @references #' A. Meucci - "Fully Flexible Extreme Views" - See formula (17) #' \url{http://ssrn.com/abstract=1542083} #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} #' @export -subIntervals = function( x ) -{ - n = nrow( x ) - x = t(x) - xMesh = rep( NaN , n + 1) - xMesh[ 1 ] = x[ 1 ] - xMesh[ n + 1 ] = x[ n ] - xMesh[ 2:n ] = x[2:n] - 0.5 * ( x[ 2:n ] - x[ 1:n-1 ] ) # simple product - - # cadlag mesh - xUB = xMesh[ -1 ] - 2.2e-308 # right - xLB = xMesh[ -(n + 1) ] # left - - return( list( xLB = xLB , xUB = xUB ) ) + +subIntervals <- function(x) { + + n <- nrow(x) + x <- t(x) + xMesh <- rep(NaN, n + 1) + xMesh[1] <- x[1] + xMesh[n + 1] <- x[n] + xMesh[2:n] <- x[2:n] - 0.5 * (x[2:n] - x[1:n - 1]) # simple product + + # cadlag mesh + xUB <- xMesh[-1] - 2.2e-308 # right + xLB <- xMesh[-(n + 1)] # left + + return(list(xLB = xLB, xUB = xUB)) } -#' Integrate the subinterval for the given cumulative distribution function to get the equivalent probability +#' Integrate the subinterval for the given cumulative distribution function to +#' get the equivalent probability #' #' @param x a vector containing the data points #' @param cdf the cumulative distribution function #' -#' @return p a vector containing the cdf evaluated for each of the subintervals -#' +#' @return p a vector containing the cdf evaluated for each of +#' the subintervals #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} #' @export -integrateSubIntervals = function( x , cdf ) -{ - bounds = subIntervals( x ) - [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3682 From noreply at r-forge.r-project.org Sat Jun 20 12:44:55 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sat, 20 Jun 2015 12:44:55 +0200 (CEST) Subject: [Returnanalytics-commits] r3683 - in pkg/Dowd: . R man Message-ID: <20150620104455.BF7DC186999@r-forge.r-project.org> Author: dacharya Date: 2015-06-20 12:44:55 +0200 (Sat, 20 Jun 2015) New Revision: 3683 Modified: pkg/Dowd/NAMESPACE pkg/Dowd/R/ADTestStat.R pkg/Dowd/R/AdjustedNormalESHotspots.R pkg/Dowd/R/AdjustedNormalVaRHotspots.R pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R pkg/Dowd/R/BinomialBacktest.R pkg/Dowd/R/ChristoffersenBacktestForIndependence.R pkg/Dowd/R/FrechetVaRPlot2DCl.R pkg/Dowd/R/GParetoES.R pkg/Dowd/R/GParetoMEFPlot.R pkg/Dowd/R/GParetoMultipleMEFPlot.R pkg/Dowd/R/GumbelES.R pkg/Dowd/R/HSVaR.R pkg/Dowd/R/JarqueBeraBacktest.R pkg/Dowd/R/KSTestStat.R pkg/Dowd/R/KuiperTestStat.R pkg/Dowd/man/ADTestStat.Rd pkg/Dowd/man/AdjustedNormalESHotspots.Rd pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd pkg/Dowd/man/BinomialBacktest.Rd pkg/Dowd/man/FrechetVaRPlot2DCl.Rd pkg/Dowd/man/GumbelES.Rd pkg/Dowd/man/JarqueBeraBacktest.Rd pkg/Dowd/man/KSTestStat.Rd pkg/Dowd/man/KuiperTestStat.Rd Log: InsuranceVaR : source and document and other minor change in documentation in others. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/NAMESPACE 2015-06-20 10:44:55 UTC (rev 3683) @@ -41,6 +41,7 @@ export(HillEstimator) export(HillPlot) export(HillQuantileEstimator) +export(InsuranceVaR) export(JarqueBeraBacktest) export(KSTestStat) export(KuiperTestStat) Modified: pkg/Dowd/R/ADTestStat.R =================================================================== --- pkg/Dowd/R/ADTestStat.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/ADTestStat.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -7,9 +7,9 @@ #' which is equivalent to #' \deqn{=-n-\frac{1}{n}\sum_{i=1}^n(2i-1)[\ln F(X_i)+\ln(1-F(X_{n+1-i}))]} #' -#' @param number.trials -#' @param sample.size -#' @param confidence.interval +#' @param number.trials Number of trials +#' @param sample.size Sample size +#' @param confidence.interval Confidence Interval #' @return Confidence Interval for AD test statistic #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' Modified: pkg/Dowd/R/AdjustedNormalESHotspots.R =================================================================== --- pkg/Dowd/R/AdjustedNormalESHotspots.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/AdjustedNormalESHotspots.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -12,7 +12,7 @@ #' @param cl Confidence level and is scalar #' @param hp Holding period and is scalar #' -#' @references Dowd, K. Measurh ing Market Risk, Wiley, 2007. +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya #' Modified: pkg/Dowd/R/AdjustedNormalVaRHotspots.R =================================================================== --- pkg/Dowd/R/AdjustedNormalVaRHotspots.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/AdjustedNormalVaRHotspots.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -12,7 +12,7 @@ #' @param cl Confidence level and is scalar #' @param hp Holding period and is scalar #' -#' @references Dowd, K. Measurh ing Market Risk, Wiley, 2007. +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya #' Modified: pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R =================================================================== --- pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -10,7 +10,7 @@ #' @param cl Confidence level and is scalar or vector #' @param hp Holding period and is scalar or vector #' -#' @references Dowd, K. Measurh ing Market Risk, Wiley, 2007. +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya #' Modified: pkg/Dowd/R/BinomialBacktest.R =================================================================== --- pkg/Dowd/R/BinomialBacktest.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/BinomialBacktest.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -21,7 +21,7 @@ #' @examples #' #' # Probability that the VaR model is correct for 3 failures, 100 number -#' observations and 95% confidence level +#' # observations and 95% confidence level #' BinomialBacktest(55, 1000, 0.95) #' #' @export Modified: pkg/Dowd/R/ChristoffersenBacktestForIndependence.R =================================================================== --- pkg/Dowd/R/ChristoffersenBacktestForIndependence.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/ChristoffersenBacktestForIndependence.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -9,7 +9,6 @@ #' @return Probability that given the data set, the null hypothesis #' (i.e. independence) is correct. #' -#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' Christoffersen, P. Evaluating Interval Forecasts. International Economic Modified: pkg/Dowd/R/FrechetVaRPlot2DCl.R =================================================================== --- pkg/Dowd/R/FrechetVaRPlot2DCl.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/FrechetVaRPlot2DCl.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -1,12 +1,11 @@ -#' @title Plots Frechet Value at Risk against Cl +#' Plots Frechet Value at Risk against Cl #' -#' @description Plots the VaR of a portfolio against confidence level assuming extreme losses +#' Plots the VaR of a portfolio against confidence level assuming extreme losses #' are Frechet distributed, for specified range of confidence level and a given #' holding period. #' #' Note that the long-right-hand tail is fitted to losses, not profits. #' -#' #' @param mu Location parameter for daily L/P #' @param sigma Scale parameter for daily L/P #' @param tail.index Tail index Modified: pkg/Dowd/R/GParetoES.R =================================================================== --- pkg/Dowd/R/GParetoES.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/GParetoES.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -1,6 +1,6 @@ -#' @title Expected Shortfall for Generalized Pareto +#' Expected Shortfall for Generalized Pareto #' -#' @description Estimates the ES of a portfolio assuming losses are distributed as a generalised Pareto. +#' Estimates the ES of a portfolio assuming losses are distributed as a generalised Pareto. #' #' @param Ra Vector of daily Profit/Loss data #' @param beta Assumed scale parameter Modified: pkg/Dowd/R/GParetoMEFPlot.R =================================================================== --- pkg/Dowd/R/GParetoMEFPlot.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/GParetoMEFPlot.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -1,6 +1,6 @@ -#' @title Plot of Emperical and Generalised Pareto mean excess functions +#' Plot of Emperical and Generalised Pareto mean excess functions #' -#' @description Plots of emperical mean excess function and Generalized mean excess function. +#' Plots of emperical mean excess function and Generalized mean excess function. #' #' @param Ra Vector of daily Profit/Loss data #' @param mu Location parameter Modified: pkg/Dowd/R/GParetoMultipleMEFPlot.R =================================================================== --- pkg/Dowd/R/GParetoMultipleMEFPlot.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/GParetoMultipleMEFPlot.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -1,6 +1,6 @@ -#' @title Plot of Emperical and 2 Generalised Pareto mean excess functions +#' Plot of Emperical and 2 Generalised Pareto mean excess functions #' -#' @description Plots of emperical mean excess function and two generalized pareto mean excess functions which differ in their tail-index value. +#' Plots of emperical mean excess function and two generalized pareto mean excess functions which differ in their tail-index value. #' #' @param Ra Vector of daily Profit/Loss data #' @param mu Location parameter Modified: pkg/Dowd/R/GumbelES.R =================================================================== --- pkg/Dowd/R/GumbelES.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/GumbelES.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -15,7 +15,8 @@ #' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' -#' National Institute of Standards and Technology, Dataplot Reference Manual. Volume 1: Commands. NIST: Washington, DC, 1997, p. 8-67. +#' National Institute of Standards and Technology, Dataplot Reference Manual. +#' Volume 1: Commands. NIST: Washington, DC, 1997, p. 8-67. #' #' @author Dinesh Acharya #' @examples Modified: pkg/Dowd/R/HSVaR.R =================================================================== --- pkg/Dowd/R/HSVaR.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/HSVaR.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -94,7 +94,7 @@ if (upper.index!=lower.index){ # Weights attached to upper and lower VaRs lower.weight <- (upper.index-index)/(upper.index-lower.index) # weight on upper.var - + upper.weight <- (index-lower.index)/(upper.index-lower.index) # weight on upper_var # Finally, the weighted, VaR as a linear interpolation of upper and lower VaRs y <- lower.weight * lower.var + upper.weight * upper.var Modified: pkg/Dowd/R/JarqueBeraBacktest.R =================================================================== --- pkg/Dowd/R/JarqueBeraBacktest.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/JarqueBeraBacktest.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -21,7 +21,7 @@ #' @examples #' #' # JB test statistic for sample with 500 observations with sample -#' skewness and kurtosis of -0.075 and 2.888 +#' # skewness and kurtosis of -0.075 and 2.888 #' JarqueBeraBacktest(-0.075,2.888,500) #' #' @export Modified: pkg/Dowd/R/KSTestStat.R =================================================================== --- pkg/Dowd/R/KSTestStat.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/KSTestStat.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -19,7 +19,7 @@ #' @examples #' #' # Plots the cdf for KS Test statistic and returns KS confidence interval -#' for 100 trials with 1000 sample size and 0.95 confidence interval +#' # for 100 trials with 1000 sample size and 0.95 confidence interval #' KSTestStat(100, 1000, 0.95) #' #' @export Modified: pkg/Dowd/R/KuiperTestStat.R =================================================================== --- pkg/Dowd/R/KuiperTestStat.R 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/R/KuiperTestStat.R 2015-06-20 10:44:55 UTC (rev 3683) @@ -18,16 +18,19 @@ #' @examples #' #' # Plots the cdf for Kuiper Test statistic and returns Kuiper confidence -#' interval for 100 trials with 1000 sample size and 0.95 confidence -#' interval. +#' # interval for 100 trials with 1000 sample size and 0.95 confidence +#' # interval. #' KuiperTestStat(100, 1000, 0.95) #' #' @export KuiperTestStat <- function(number.trials, sample.size, confidence.interval){ - if (confidence.interval>1){ + if (confidence.interval >= 1) { stop("Confidence Interval should be less than 1.") } + if (confidence.interval <= 0) { + stop("Confidence Interval should be positive.") + } # Read back input parameters m <- number.trials Modified: pkg/Dowd/man/ADTestStat.Rd =================================================================== --- pkg/Dowd/man/ADTestStat.Rd 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/man/ADTestStat.Rd 2015-06-20 10:44:55 UTC (rev 3683) @@ -8,11 +8,11 @@ ADTestStat(number.trials, sample.size, confidence.interval) } \arguments{ -\item{number.trials}{} +\item{number.trials}{Number of trials} -\item{sample.size}{} +\item{sample.size}{Sample size} -\item{confidence.interval}{} +\item{confidence.interval}{Confidence Interval} } \value{ Confidence Interval for AD test statistic @@ -26,7 +26,7 @@ } \examples{ # Probability that the VaR model is correct for 3 failures, 100 number - observations and 95\% confidence level + # observations and 95\% confidence level ADTestStat(1000, 100, 0.95) } \author{ Modified: pkg/Dowd/man/AdjustedNormalESHotspots.Rd =================================================================== --- pkg/Dowd/man/AdjustedNormalESHotspots.Rd 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/man/AdjustedNormalESHotspots.Rd 2015-06-20 10:44:55 UTC (rev 3683) @@ -41,6 +41,6 @@ Dinesh Acharya } \references{ -Dowd, K. Measurh ing Market Risk, Wiley, 2007. +Dowd, K. Measuring Market Risk, Wiley, 2007. } Modified: pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd =================================================================== --- pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd 2015-06-20 10:44:55 UTC (rev 3683) @@ -41,6 +41,6 @@ Dinesh Acharya } \references{ -Dowd, K. Measurh ing Market Risk, Wiley, 2007. +Dowd, K. Measuring Market Risk, Wiley, 2007. } Modified: pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd =================================================================== --- pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd 2015-06-20 10:44:55 UTC (rev 3683) @@ -39,6 +39,6 @@ Dinesh Acharya } \references{ -Dowd, K. Measurh ing Market Risk, Wiley, 2007. +Dowd, K. Measuring Market Risk, Wiley, 2007. } Modified: pkg/Dowd/man/BinomialBacktest.Rd =================================================================== --- pkg/Dowd/man/BinomialBacktest.Rd 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/man/BinomialBacktest.Rd 2015-06-20 10:44:55 UTC (rev 3683) @@ -26,7 +26,7 @@ } \examples{ # Probability that the VaR model is correct for 3 failures, 100 number - observations and 95\% confidence level + # observations and 95\% confidence level BinomialBacktest(55, 1000, 0.95) } \author{ Modified: pkg/Dowd/man/FrechetVaRPlot2DCl.Rd =================================================================== --- pkg/Dowd/man/FrechetVaRPlot2DCl.Rd 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/man/FrechetVaRPlot2DCl.Rd 2015-06-20 10:44:55 UTC (rev 3683) @@ -23,7 +23,8 @@ Plots the VaR of a portfolio against confidence level assuming extreme losses are Frechet distributed, for specified range of confidence level and a given holding period. - +} +\details{ Note that the long-right-hand tail is fitted to losses, not profits. } \examples{ Modified: pkg/Dowd/man/GumbelES.Rd =================================================================== --- pkg/Dowd/man/GumbelES.Rd 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/man/GumbelES.Rd 2015-06-20 10:44:55 UTC (rev 3683) @@ -37,6 +37,7 @@ \references{ Dowd, K. Measuring Market Risk, Wiley, 2007. -National Institute of Standards and Technology, Dataplot Reference Manual. Volume 1: Commands. NIST: Washington, DC, 1997, p. 8-67. +National Institute of Standards and Technology, Dataplot Reference Manual. +Volume 1: Commands. NIST: Washington, DC, 1997, p. 8-67. } Modified: pkg/Dowd/man/JarqueBeraBacktest.Rd =================================================================== --- pkg/Dowd/man/JarqueBeraBacktest.Rd 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/man/JarqueBeraBacktest.Rd 2015-06-20 10:44:55 UTC (rev 3683) @@ -25,7 +25,7 @@ } \examples{ # JB test statistic for sample with 500 observations with sample - skewness and kurtosis of -0.075 and 2.888 + # skewness and kurtosis of -0.075 and 2.888 JarqueBeraBacktest(-0.075,2.888,500) } \author{ Modified: pkg/Dowd/man/KSTestStat.Rd =================================================================== --- pkg/Dowd/man/KSTestStat.Rd 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/man/KSTestStat.Rd 2015-06-20 10:44:55 UTC (rev 3683) @@ -24,7 +24,7 @@ } \examples{ # Plots the cdf for KS Test statistic and returns KS confidence interval - for 100 trials with 1000 sample size and 0.95 confidence interval + # for 100 trials with 1000 sample size and 0.95 confidence interval KSTestStat(100, 1000, 0.95) } \author{ Modified: pkg/Dowd/man/KuiperTestStat.Rd =================================================================== --- pkg/Dowd/man/KuiperTestStat.Rd 2015-06-20 08:11:15 UTC (rev 3682) +++ pkg/Dowd/man/KuiperTestStat.Rd 2015-06-20 10:44:55 UTC (rev 3683) @@ -25,8 +25,8 @@ } \examples{ # Plots the cdf for Kuiper Test statistic and returns Kuiper confidence - interval for 100 trials with 1000 sample size and 0.95 confidence - interval. + # interval for 100 trials with 1000 sample size and 0.95 confidence + # interval. KuiperTestStat(100, 1000, 0.95) } \author{ From noreply at r-forge.r-project.org Sat Jun 20 13:03:20 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sat, 20 Jun 2015 13:03:20 +0200 (CEST) Subject: [Returnanalytics-commits] r3684 - pkg/Dowd/R Message-ID: <20150620110320.709191839D0@r-forge.r-project.org> Author: dacharya Date: 2015-06-20 13:03:19 +0200 (Sat, 20 Jun 2015) New Revision: 3684 Modified: pkg/Dowd/R/ADTestStat.R pkg/Dowd/R/BinomialBacktest.R Log: Condition requirement for confidence level made more precise Modified: pkg/Dowd/R/ADTestStat.R =================================================================== --- pkg/Dowd/R/ADTestStat.R 2015-06-20 10:44:55 UTC (rev 3683) +++ pkg/Dowd/R/ADTestStat.R 2015-06-20 11:03:19 UTC (rev 3684) @@ -1,72 +1,75 @@ -#' Plots cumulative density for AD test and computes confidence -#' interval for AD test stat. -#' -#' Anderson-Darling(AD) test can be used to carry out distribution equality test and is -#' similar to Kolmogorov-Smirnov test. AD test statistic is defined as: -#' \deqn{A^2=n\int_{-\infty}^{\infty}\frac{[\hat{F}(x)-F(x)]^2}{F(x)[1-F(x)]}dF(x)} -#' which is equivalent to -#' \deqn{=-n-\frac{1}{n}\sum_{i=1}^n(2i-1)[\ln F(X_i)+\ln(1-F(X_{n+1-i}))]} -#' -#' @param number.trials Number of trials -#' @param sample.size Sample size -#' @param confidence.interval Confidence Interval -#' @return Confidence Interval for AD test statistic -#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. -#' -#' Anderson, T.W. and Darling, D.A. Asymptotic Theory of Certain Goodness of -#' Fit Criteria Based on Stochastic Processes, The Annals of Mathematical -#' Statistics, 23(2), 1952, p. 193-212. -#' -#' Kvam, P.H. and Vidakovic, B. Nonparametric Statistics with Applications to -#' Science and Engineering, Wiley, 2007. -#' -#' @author Dinesh Acharya -#' @examples -#' -#' # Probability that the VaR model is correct for 3 failures, 100 number -#' # observations and 95% confidence level -#' ADTestStat(1000, 100, 0.95) -#' -#' @export -ADTestStat <- function(number.trials, sample.size, confidence.interval){ - - if (confidence.interval>1){ - stop("Confidence Interval should be less than 1.") - } - - m <- number.trials - n <- sample.size - - # Random Number Generation - data <- matrix(rnorm(m*n), m, n) - - # Initialize vectors - term <- double(n) - AD.test.stat <- double(m) - - # Compute AD test statistic - for (i in 1:m) { - trial.sample <- data[i, ] - ordered.trial.sample <- sort(trial.sample) - for (j in 1:n) { - term[j] <- (2*j-1)*(log(pnorm(ordered.trial.sample[j],0,1))- - log(1-pnorm(ordered.trial.sample[n+1-j],0,1))); - } - AD.test.stat[i] <- -n-mean(term) - } - AD.test.stat <- sort(AD.test.stat) - - # Obtain confidence interval - lower.bound.index <- round(m*(1-confidence.interval)/2) - upper.bound.index <- round(m* (confidence.interval+(1-confidence.interval)/2)) - confidence.interval.for.AD.test.stat <- c(AD.test.stat[lower.bound.index], - AD.test.stat[upper.bound.index]) - # Plot the graph - cdf <- seq(1/m, 1, 1/m) - plot(AD.test.stat, cdf, col="red", type="l", - main="Cumulative density for AD test statistic", - xlab="AD test statistic", ylab="Cumulative probability") - - return(confidence.interval.for.AD.test.stat) - -} +#' Plots cumulative density for AD test and computes confidence +#' interval for AD test stat. +#' +#' Anderson-Darling(AD) test can be used to carry out distribution equality test and is +#' similar to Kolmogorov-Smirnov test. AD test statistic is defined as: +#' \deqn{A^2=n\int_{-\infty}^{\infty}\frac{[\hat{F}(x)-F(x)]^2}{F(x)[1-F(x)]}dF(x)} +#' which is equivalent to +#' \deqn{=-n-\frac{1}{n}\sum_{i=1}^n(2i-1)[\ln F(X_i)+\ln(1-F(X_{n+1-i}))]} +#' +#' @param number.trials Number of trials +#' @param sample.size Sample size +#' @param confidence.interval Confidence Interval +#' @return Confidence Interval for AD test statistic +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Anderson, T.W. and Darling, D.A. Asymptotic Theory of Certain Goodness of +#' Fit Criteria Based on Stochastic Processes, The Annals of Mathematical +#' Statistics, 23(2), 1952, p. 193-212. +#' +#' Kvam, P.H. and Vidakovic, B. Nonparametric Statistics with Applications to +#' Science and Engineering, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Probability that the VaR model is correct for 3 failures, 100 number +#' # observations and 95% confidence level +#' ADTestStat(1000, 100, 0.95) +#' +#' @export +ADTestStat <- function(number.trials, sample.size, confidence.interval){ + + if (confidence.interval >= 1){ + stop("Confidence Interval should be less than 1.") + } + if (confidence.interval <= 1){ + stop("Confidence Interval should be positive.") + } + + m <- number.trials + n <- sample.size + + # Random Number Generation + data <- matrix(rnorm(m*n), m, n) + + # Initialize vectors + term <- double(n) + AD.test.stat <- double(m) + + # Compute AD test statistic + for (i in 1:m) { + trial.sample <- data[i, ] + ordered.trial.sample <- sort(trial.sample) + for (j in 1:n) { + term[j] <- (2*j-1)*(log(pnorm(ordered.trial.sample[j],0,1))- + log(1-pnorm(ordered.trial.sample[n+1-j],0,1))); + } + AD.test.stat[i] <- -n-mean(term) + } + AD.test.stat <- sort(AD.test.stat) + + # Obtain confidence interval + lower.bound.index <- round(m*(1-confidence.interval)/2) + upper.bound.index <- round(m* (confidence.interval+(1-confidence.interval)/2)) + confidence.interval.for.AD.test.stat <- c(AD.test.stat[lower.bound.index], + AD.test.stat[upper.bound.index]) + # Plot the graph + cdf <- seq(1/m, 1, 1/m) + plot(AD.test.stat, cdf, col="red", type="l", + main="Cumulative density for AD test statistic", + xlab="AD test statistic", ylab="Cumulative probability") + + return(confidence.interval.for.AD.test.stat) + +} Modified: pkg/Dowd/R/BinomialBacktest.R =================================================================== --- pkg/Dowd/R/BinomialBacktest.R 2015-06-20 10:44:55 UTC (rev 3683) +++ pkg/Dowd/R/BinomialBacktest.R 2015-06-20 11:03:19 UTC (rev 3684) @@ -27,9 +27,8 @@ #' @export BinomialBacktest <- function (x, n, cl){ # Give warning if x>n or cl>100% - if(x > n | cl > 1){ - warning ("Incorrect parameter list. Make sure that x>n and cl<=100%") - return (NaN) + if(x > n | cl >= 1 | cl <= 0){ + stop ("Incorrect parameter list. Make sure that x>n and 0 Author: dacharya Date: 2015-06-22 13:13:17 +0200 (Mon, 22 Jun 2015) New Revision: 3685 Added: pkg/Dowd/README Log: File name made appropriate as per package structure. Added: pkg/Dowd/README =================================================================== --- pkg/Dowd/README (rev 0) +++ pkg/Dowd/README 2015-06-22 11:13:17 UTC (rev 3685) @@ -0,0 +1,28 @@ +# +# General Notes for Modification: +#*************************************************************** +# FrechetVaR does not use hp and the remark about return value when it is vector is vaccuous. +#*************************************************************** +# In Normal/t QQ Plots, dowd code does not work for matrices but the code contains parts that +# work for matrices. some vectors like pvec are not defined anywhere in his code. +#*************************************************************** +# Some error is present in GumbelCopulaVaR and needs correction +#*************************************************************** +# Bootstrap is functional (but HSVaR still does not accept matrix P/L +# and only still accepts vectors, its needs to be modified) +#*************************************************************** +# Jarque-Bera Test: +# It has to be checked Probability of null (H0) or (H1). +#*************************************************************** +# Christofferson Backtest for Independence: +# VaR(excess_loss<=0)=[]; Does not make sense. It is still to be checked if it is as intended. +# if(excess.loss[i-1]<=0) if condition incomplete statement. +#*************************************************************** +# Tests/Examples for profit.loss distribution and corresponding VaR and ETL +# still needs to be completed. Around 4 in Backtest do not have examples. +# It still has to be completed. +#*************************************************************** +# Lopez Backtest: +# In Christofferson , excess.loss is defined as -profit.loss-VaR +# But in Lopez Backtest, profit.loss-VaR is used. It has to be checked. +#*************************************************************** \ No newline at end of file From noreply at r-forge.r-project.org Mon Jun 22 14:06:40 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 14:06:40 +0200 (CEST) Subject: [Returnanalytics-commits] r3686 - pkg/Dowd Message-ID: <20150622120640.71B6E187709@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 14:06:40 +0200 (Mon, 22 Jun 2015) New Revision: 3686 Modified: pkg/Dowd/DESCRIPTION Log: License changed to GPL. Modified: pkg/Dowd/DESCRIPTION =================================================================== --- pkg/Dowd/DESCRIPTION 2015-06-22 11:13:17 UTC (rev 3685) +++ pkg/Dowd/DESCRIPTION 2015-06-22 12:06:40 UTC (rev 3686) @@ -11,4 +11,4 @@ bootstrap Suggests: PerformanceAnalytics, testthat -License: GNU Public License +License: GPL From noreply at r-forge.r-project.org Mon Jun 22 14:09:17 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 14:09:17 +0200 (CEST) Subject: [Returnanalytics-commits] r3687 - pkg/Dowd/R Message-ID: <20150622120917.BC03B18111F@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 14:09:17 +0200 (Mon, 22 Jun 2015) New Revision: 3687 Modified: pkg/Dowd/R/BootstrapES.R pkg/Dowd/R/BootstrapESConfInterval.R pkg/Dowd/R/BootstrapESFigure.R pkg/Dowd/R/BootstrapVaR.R pkg/Dowd/R/BootstrapVaRConfInterval.R pkg/Dowd/R/BootstrapVaRFigure.R Log: Unnecessary line library(bootstrap) removed. Modified: pkg/Dowd/R/BootstrapES.R =================================================================== --- pkg/Dowd/R/BootstrapES.R 2015-06-22 12:06:40 UTC (rev 3686) +++ pkg/Dowd/R/BootstrapES.R 2015-06-22 12:09:17 UTC (rev 3687) @@ -52,8 +52,6 @@ stop("Number of resamples must be at least 0") } - # Load bootstrap package - library(bootstrap) # ES estimation es <- bootstrap(losses.data, number.resamples, HSES, cl)$thetastar y <- mean(es) Modified: pkg/Dowd/R/BootstrapESConfInterval.R =================================================================== --- pkg/Dowd/R/BootstrapESConfInterval.R 2015-06-22 12:06:40 UTC (rev 3686) +++ pkg/Dowd/R/BootstrapESConfInterval.R 2015-06-22 12:09:17 UTC (rev 3687) @@ -55,9 +55,7 @@ if (number.resamples <= 0){ stop("Number of resamples must be at least 0") } - - library(bootstrap) - + # ES estimation es <- bootstrap(losses.data, number.resamples, HSES, cl)[1] y <- quantile(es, c(.05, .95)) Modified: pkg/Dowd/R/BootstrapESFigure.R =================================================================== --- pkg/Dowd/R/BootstrapESFigure.R 2015-06-22 12:06:40 UTC (rev 3686) +++ pkg/Dowd/R/BootstrapESFigure.R 2015-06-22 12:09:17 UTC (rev 3687) @@ -55,8 +55,6 @@ stop("Number of resamples must be at least 0") } - library(bootstrap) - # ES Estimation es <- bootstrap(losses.data, number.resamples, HSES, cl)$thetastar mean.es <- mean(es) Modified: pkg/Dowd/R/BootstrapVaR.R =================================================================== --- pkg/Dowd/R/BootstrapVaR.R 2015-06-22 12:06:40 UTC (rev 3686) +++ pkg/Dowd/R/BootstrapVaR.R 2015-06-22 12:09:17 UTC (rev 3687) @@ -52,8 +52,6 @@ stop("Number of resamples must be at least 0") } - # Load bootstrap package - library(bootstrap) # ES estimation VaR <- bootstrap(losses.data, number.resamples, HSVaR, cl)$thetastar y <- mean(VaR) Modified: pkg/Dowd/R/BootstrapVaRConfInterval.R =================================================================== --- pkg/Dowd/R/BootstrapVaRConfInterval.R 2015-06-22 12:06:40 UTC (rev 3686) +++ pkg/Dowd/R/BootstrapVaRConfInterval.R 2015-06-22 12:09:17 UTC (rev 3687) @@ -56,8 +56,6 @@ stop("Number of resamples must be at least 0") } - library(bootstrap) - # VaR estimation VaR <- bootstrap(losses.data, number.resamples, HSVaR, cl)$thetastar y <- quantile(VaR, c(.05, .95)) Modified: pkg/Dowd/R/BootstrapVaRFigure.R =================================================================== --- pkg/Dowd/R/BootstrapVaRFigure.R 2015-06-22 12:06:40 UTC (rev 3686) +++ pkg/Dowd/R/BootstrapVaRFigure.R 2015-06-22 12:09:17 UTC (rev 3687) @@ -55,8 +55,6 @@ stop("Number of resamples must be at least 0") } - library(bootstrap) - # ES Estimation VaR <- bootstrap(losses.data, number.resamples, HSVaR, cl)$thetastar mean.VaR <- mean(VaR) From noreply at r-forge.r-project.org Mon Jun 22 14:34:45 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 14:34:45 +0200 (CEST) Subject: [Returnanalytics-commits] r3688 - pkg/Dowd/R Message-ID: <20150622123445.30C9E18780E@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 14:34:44 +0200 (Mon, 22 Jun 2015) New Revision: 3688 Modified: pkg/Dowd/R/BootstrapES.R pkg/Dowd/R/BootstrapESConfInterval.R pkg/Dowd/R/BootstrapESFigure.R pkg/Dowd/R/BootstrapVaR.R pkg/Dowd/R/BootstrapVaRConfInterval.R pkg/Dowd/R/BootstrapVaRFigure.R Log: Import bootstrap added. Modified: pkg/Dowd/R/BootstrapES.R =================================================================== --- pkg/Dowd/R/BootstrapES.R 2015-06-22 12:09:17 UTC (rev 3687) +++ pkg/Dowd/R/BootstrapES.R 2015-06-22 12:34:44 UTC (rev 3688) @@ -1,59 +1,61 @@ -#' Bootstrapped ES for specified confidence level -#' -#' Estimates the bootstrapped ES for confidence level and holding period -#' implied by data frequency. -#' -#' @param Ra Vector corresponding to profit and loss distribution -#' @param number.resamples Number of samples to be taken in bootstrap procedure -#' @return cl Number corresponding to Expected Shortfall confidence level -#' -#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. -#' -#' -#' @author Dinesh Acharya -#' @examples -#' -#' # Estimates bootstrapped ES for given parameters -#' a <- rnorm(100) # generate a random profit/loss vector -#' BootstrapVaR(a, 50, 0.95) -#' -#' @export -BootstrapES <- function(Ra, number.resamples, cl){ - - if (nargs() < 3){ - error("Too few arguments") - } - if (nargs() > 3){ - error("Too many arguments") - } - - profit.loss.data <- as.vector(Ra) - # Preprocess data - unsorted.loss.data <- -profit.loss.data - losses.data <- sort(unsorted.loss.data) - n <- length(losses.data) - - # Check that inputs have correct dimensions - if (length(cl) != 1) { - error("Confidence level must be a scalar") - } - if (length(number.resamples) != 1){ - error("Number of resamples must be a scalar"); - } - - # Check that inputs obey sign and value restrictions - if (cl >= 1){ - stop("Confidence level must be less that 1") - } - if (cl <= 0){ - stop("Confidence level must be at least 0") - } - if (number.resamples <= 0){ - stop("Number of resamples must be at least 0") - } - - # ES estimation - es <- bootstrap(losses.data, number.resamples, HSES, cl)$thetastar - y <- mean(es) - return (y) +#' Bootstrapped ES for specified confidence level +#' +#' Estimates the bootstrapped ES for confidence level and holding period +#' implied by data frequency. +#' +#' @param Ra Vector corresponding to profit and loss distribution +#' @param number.resamples Number of samples to be taken in bootstrap procedure +#' @return cl Number corresponding to Expected Shortfall confidence level +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates bootstrapped ES for given parameters +#' a <- rnorm(100) # generate a random profit/loss vector +#' BootstrapVaR(a, 50, 0.95) +#' +#' @import bootstrap +#' +#' @export +BootstrapES <- function(Ra, number.resamples, cl){ + + if (nargs() < 3){ + error("Too few arguments") + } + if (nargs() > 3){ + error("Too many arguments") + } + + profit.loss.data <- as.vector(Ra) + # Preprocess data + unsorted.loss.data <- -profit.loss.data + losses.data <- sort(unsorted.loss.data) + n <- length(losses.data) + + # Check that inputs have correct dimensions + if (length(cl) != 1) { + error("Confidence level must be a scalar") + } + if (length(number.resamples) != 1){ + error("Number of resamples must be a scalar"); + } + + # Check that inputs obey sign and value restrictions + if (cl >= 1){ + stop("Confidence level must be less that 1") + } + if (cl <= 0){ + stop("Confidence level must be at least 0") + } + if (number.resamples <= 0){ + stop("Number of resamples must be at least 0") + } + + # ES estimation + es <- bootstrap(losses.data, number.resamples, HSES, cl)$thetastar + y <- mean(es) + return (y) } \ No newline at end of file Modified: pkg/Dowd/R/BootstrapESConfInterval.R =================================================================== --- pkg/Dowd/R/BootstrapESConfInterval.R 2015-06-22 12:09:17 UTC (rev 3687) +++ pkg/Dowd/R/BootstrapESConfInterval.R 2015-06-22 12:34:44 UTC (rev 3688) @@ -1,64 +1,66 @@ -#' Bootstrapped ES Confidence Interval -#' -#' Estimates the 90% confidence interval for bootstrapped ES, for confidence -#' level and holding period implied by data frequency. -#' -#' @param Ra Vector corresponding to profit and loss distribution -#' @param number.resample Number of samples to be taken in bootstrap procedure -#' @param cl Number corresponding to Expected Shortfall confidence level -#' @return 90% Confidence interval for bootstrapped ES -#' -#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. -#' -#' -#' @author Dinesh Acharya -#' @examples -#' -#' # To be modified with appropriate data. -#' # Estimates 90% confidence interval for bootstrapped ES for 95% -#' # confidence interval -#' Ra <- rnorm(1000) -#' BootstrapESConfInterval(Ra, 50, 0.95) -#' -#' @export -BootstrapESConfInterval <- function(Ra, number.resamples, cl){ - - # Determine if there are three arguments - if (nargs() < 3){ - stop("Too few arguments") - } - if (nargs() > 3){ - stop("Too many arguments") - } - - profit.loss.data <- as.vector(Ra) - - # Preprocess data - unsorted.loss.data <- -profit.loss.data # Derives L/P data from input P/L data - losses.data <- sort(unsorted.loss.data) # Puts losses in ascending order - n <- length(losses.data) - - # Check that inputs have correct dimensions - if (is.vector(cl) & (length(cl) != 1) ) { - error("Confidence level must be a scalar") - } - if (length(number.resamples) != 1) { - error("Number of resamples must be a scalar") - } - # Check that inputs obey sign and value restrictions - if (cl >= 1){ - stop("Confidence level must be less that 1") - } - if (cl <= 0){ - stop("Confidence level must be at least 0") - } - if (number.resamples <= 0){ - stop("Number of resamples must be at least 0") - } - - # ES estimation - es <- bootstrap(losses.data, number.resamples, HSES, cl)[1] - y <- quantile(es, c(.05, .95)) - return(y) - +#' Bootstrapped ES Confidence Interval +#' +#' Estimates the 90% confidence interval for bootstrapped ES, for confidence +#' level and holding period implied by data frequency. +#' +#' @param Ra Vector corresponding to profit and loss distribution +#' @param number.resample Number of samples to be taken in bootstrap procedure +#' @param cl Number corresponding to Expected Shortfall confidence level +#' @return 90% Confidence interval for bootstrapped ES +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # To be modified with appropriate data. +#' # Estimates 90% confidence interval for bootstrapped ES for 95% +#' # confidence interval +#' Ra <- rnorm(1000) +#' BootstrapESConfInterval(Ra, 50, 0.95) +#' +#' @import bootstrap +#' +#' @export +BootstrapESConfInterval <- function(Ra, number.resamples, cl){ + + # Determine if there are three arguments + if (nargs() < 3){ + stop("Too few arguments") + } + if (nargs() > 3){ + stop("Too many arguments") + } + + profit.loss.data <- as.vector(Ra) + + # Preprocess data + unsorted.loss.data <- -profit.loss.data # Derives L/P data from input P/L data + losses.data <- sort(unsorted.loss.data) # Puts losses in ascending order + n <- length(losses.data) + + # Check that inputs have correct dimensions + if (is.vector(cl) & (length(cl) != 1) ) { + error("Confidence level must be a scalar") + } + if (length(number.resamples) != 1) { + error("Number of resamples must be a scalar") + } + # Check that inputs obey sign and value restrictions + if (cl >= 1){ + stop("Confidence level must be less that 1") + } + if (cl <= 0){ + stop("Confidence level must be at least 0") + } + if (number.resamples <= 0){ + stop("Number of resamples must be at least 0") + } + + # ES estimation + es <- bootstrap(losses.data, number.resamples, HSES, cl)[1] + y <- quantile(es, c(.05, .95)) + return(y) + } \ No newline at end of file Modified: pkg/Dowd/R/BootstrapESFigure.R =================================================================== --- pkg/Dowd/R/BootstrapESFigure.R 2015-06-22 12:09:17 UTC (rev 3687) +++ pkg/Dowd/R/BootstrapESFigure.R 2015-06-22 12:34:44 UTC (rev 3688) @@ -1,70 +1,72 @@ -#' Plots figure of bootstrapped ES -#' -#' Plots figure for the bootstrapped ES, for confidence -#' level and holding period implied by data frequency. -#' -#' @param Ra Vector corresponding to profit and loss distribution -#' @param number.resample Number of samples to be taken in bootstrap procedure -#' @param cl Number corresponding to Expected Shortfall confidence level -#' -#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. -#' -#' -#' @author Dinesh Acharya -#' @examples -#' -#' # To be modified with appropriate data. -#' # Estimates 90% confidence interval for bootstrapped ES for 95% -#' # confidence interval -#' Ra <- rnorm(1000) -#' BootstrapESFigure(Ra, 500, 0.95) -#' -#' @export -BootstrapESFigure <- function(Ra, number.resamples, cl){ - - # Determine if there are three arguments - if (nargs() < 3){ - stop("Too few arguments") - } - if (nargs() > 3){ - stop("Too many arguments") - } - - profit.loss.data <- as.vector(Ra) - - # Preprocess data - unsorted.loss.data <- -profit.loss.data # Derives L/P data from input P/L data - losses.data <- sort(unsorted.loss.data) # Puts losses in ascending order - n <- length(losses.data) - - # Check that inputs have correct dimensions - if (is.vector(cl) & (length(cl) != 1) ) { - error("Confidence level must be a scalar") - } - if (length(number.resamples) != 1) { - error("Number of resamples must be a scalar") - } - # Check that inputs obey sign and value restrictions - if (cl >= 1){ - stop("Confidence level must be less that 1") - } - if (cl <= 0){ - stop("Confidence level must be at least 0") - } - if (number.resamples <= 0){ - stop("Number of resamples must be at least 0") - } - - # ES Estimation - es <- bootstrap(losses.data, number.resamples, HSES, cl)$thetastar - mean.es <- mean(es) - std.es <- sd(es) - min.es <- min(es) - max.es <- max(es) - ninety.five.perc.conf.interval <- quantile(es, c(.05, .95)) - - # Histogram - cl.for.label <- 100*cl - hist(es, 30, xlab="ES", ylab="Frequency", main=paste("Bootstrapped Historical Simulation ES at", cl, "% Confidence Level")) - +#' Plots figure of bootstrapped ES +#' +#' Plots figure for the bootstrapped ES, for confidence +#' level and holding period implied by data frequency. +#' +#' @param Ra Vector corresponding to profit and loss distribution +#' @param number.resample Number of samples to be taken in bootstrap procedure +#' @param cl Number corresponding to Expected Shortfall confidence level +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # To be modified with appropriate data. +#' # Estimates 90% confidence interval for bootstrapped ES for 95% +#' # confidence interval +#' Ra <- rnorm(1000) +#' BootstrapESFigure(Ra, 500, 0.95) +#' +#' @import bootstrap +#' +#' @export +BootstrapESFigure <- function(Ra, number.resamples, cl){ + + # Determine if there are three arguments + if (nargs() < 3){ + stop("Too few arguments") + } + if (nargs() > 3){ + stop("Too many arguments") + } + + profit.loss.data <- as.vector(Ra) + + # Preprocess data + unsorted.loss.data <- -profit.loss.data # Derives L/P data from input P/L data + losses.data <- sort(unsorted.loss.data) # Puts losses in ascending order + n <- length(losses.data) + + # Check that inputs have correct dimensions + if (is.vector(cl) & (length(cl) != 1) ) { + error("Confidence level must be a scalar") + } + if (length(number.resamples) != 1) { + error("Number of resamples must be a scalar") + } + # Check that inputs obey sign and value restrictions + if (cl >= 1){ + stop("Confidence level must be less that 1") + } + if (cl <= 0){ + stop("Confidence level must be at least 0") + } + if (number.resamples <= 0){ + stop("Number of resamples must be at least 0") + } + + # ES Estimation + es <- bootstrap(losses.data, number.resamples, HSES, cl)$thetastar + mean.es <- mean(es) + std.es <- sd(es) + min.es <- min(es) + max.es <- max(es) + ninety.five.perc.conf.interval <- quantile(es, c(.05, .95)) + + # Histogram + cl.for.label <- 100*cl + hist(es, 30, xlab="ES", ylab="Frequency", main=paste("Bootstrapped Historical Simulation ES at", cl, "% Confidence Level")) + } \ No newline at end of file Modified: pkg/Dowd/R/BootstrapVaR.R =================================================================== --- pkg/Dowd/R/BootstrapVaR.R 2015-06-22 12:09:17 UTC (rev 3687) +++ pkg/Dowd/R/BootstrapVaR.R 2015-06-22 12:34:44 UTC (rev 3688) @@ -17,6 +17,8 @@ #' a <- rnorm(100) # generate a random profit/loss vector #' BootstrapES(a, 50, 0.95) #' +#' @import bootstrap +#' #' @export BootstrapVaR <- function(Ra, number.resamples, cl){ Modified: pkg/Dowd/R/BootstrapVaRConfInterval.R =================================================================== --- pkg/Dowd/R/BootstrapVaRConfInterval.R 2015-06-22 12:09:17 UTC (rev 3687) +++ pkg/Dowd/R/BootstrapVaRConfInterval.R 2015-06-22 12:34:44 UTC (rev 3688) @@ -20,6 +20,8 @@ #' Ra <- rnorm(1000) #' BootstrapVaRConfInterval(Ra, 500, 0.95) #' +#' @import bootstrap +#' #' @export BootstrapVaRConfInterval <- function(Ra, number.resamples, cl){ Modified: pkg/Dowd/R/BootstrapVaRFigure.R =================================================================== --- pkg/Dowd/R/BootstrapVaRFigure.R 2015-06-22 12:09:17 UTC (rev 3687) +++ pkg/Dowd/R/BootstrapVaRFigure.R 2015-06-22 12:34:44 UTC (rev 3688) @@ -1,70 +1,71 @@ -#' Plots figure of bootstrapped VaR -#' -#' Plots figure for the bootstrapped VaR, for confidence -#' level and holding period implied by data frequency. -#' -#' @param Ra Vector corresponding to profit and loss distribution -#' @param number.sample Number of samples to be taken in bootstrap procedure -#' @param cl Number corresponding to Value at Risk confidence level -#' -#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. -#' -#' -#' @author Dinesh Acharya -#' @examples -#' -#' # To be modified with appropriate data. -#' # Estimates 90% confidence interval for bootstrapped VaR for 95% -#' # confidence interval -#' Ra <- rnorm(1000) -#' BootstrapESFigure(Ra, 500, 0.95) -#' -#' @export -BootstrapVaRFigure <- function(Ra, number.resamples, cl){ - - # Determine if there are three arguments - if (nargs() < 3){ - stop("Too few arguments") - } - if (nargs() > 3){ - stop("Too many arguments") - } - - profit.loss.data <- as.vector(Ra) - - # Preprocess data - unsorted.loss.data <- -profit.loss.data # Derives L/P data from input P/L data - losses.data <- sort(unsorted.loss.data) # Puts losses in ascending order - n <- length(losses.data) - - # Check that inputs have correct dimensions - if (is.vector(cl) & (length(cl) != 1) ) { - error("Confidence level must be a scalar") - } - if (length(number.resamples) != 1) { - error("Number of resamples must be a scalar") - } - # Check that inputs obey sign and value restrictions - if (cl >= 1){ - stop("Confidence level must be less that 1") - } - if (cl <= 0){ - stop("Confidence level must be at least 0") - } - if (number.resamples <= 0){ - stop("Number of resamples must be at least 0") - } - - # ES Estimation - VaR <- bootstrap(losses.data, number.resamples, HSVaR, cl)$thetastar - mean.VaR <- mean(VaR) - std.VaR <- sd(VaR) - min.VaR <- min(VaR) - max.VaR <- max(VaR) - ninety.five.perc.conf.interval <- quantile(VaR, c(.05, .95)) - - # Histogram - cl.for.label <- 100*cl - hist(VaR, 30, xlab="VaR", ylab="Frequency", main=paste("Bootstrapped Historical Simulation VaR at", cl, "% Confidence Level")) - +#' Plots figure of bootstrapped VaR +#' +#' Plots figure for the bootstrapped VaR, for confidence +#' level and holding period implied by data frequency. +#' +#' @param Ra Vector corresponding to profit and loss distribution +#' @param number.sample Number of samples to be taken in bootstrap procedure +#' @param cl Number corresponding to Value at Risk confidence level +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # To be modified with appropriate data. +#' # Estimates 90% confidence interval for bootstrapped VaR for 95% +#' # confidence interval +#' Ra <- rnorm(1000) +#' BootstrapESFigure(Ra, 500, 0.95) +#' +#' @import bootstrap +#' +#' @export +BootstrapVaRFigure <- function(Ra, number.resamples, cl){ + + # Determine if there are three arguments + if (nargs() < 3){ + stop("Too few arguments") + } + if (nargs() > 3){ + stop("Too many arguments") + } + + profit.loss.data <- as.vector(Ra) + + # Preprocess data + unsorted.loss.data <- -profit.loss.data # Derives L/P data from input P/L data + losses.data <- sort(unsorted.loss.data) # Puts losses in ascending order + n <- length(losses.data) + + # Check that inputs have correct dimensions + if (is.vector(cl) & (length(cl) != 1) ) { + error("Confidence level must be a scalar") + } + if (length(number.resamples) != 1) { + error("Number of resamples must be a scalar") + } + # Check that inputs obey sign and value restrictions + if (cl >= 1){ + stop("Confidence level must be less that 1") + } + if (cl <= 0){ + stop("Confidence level must be at least 0") + } + if (number.resamples <= 0){ + stop("Number of resamples must be at least 0") + } + + # ES Estimation + VaR <- bootstrap(losses.data, number.resamples, HSVaR, cl)$thetastar + mean.VaR <- mean(VaR) + std.VaR <- sd(VaR) + min.VaR <- min(VaR) + max.VaR <- max(VaR) + ninety.five.perc.conf.interval <- quantile(VaR, c(.05, .95)) + + # Histogram + cl.for.label <- 100*cl + hist(VaR, 30, xlab="VaR", ylab="Frequency", main=paste("Bootstrapped Historical Simulation VaR at", cl, "% Confidence Level")) + } \ No newline at end of file From noreply at r-forge.r-project.org Mon Jun 22 14:41:03 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 14:41:03 +0200 (CEST) Subject: [Returnanalytics-commits] r3689 - pkg/Dowd/R Message-ID: <20150622124103.C8838180936@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 14:41:03 +0200 (Mon, 22 Jun 2015) New Revision: 3689 Modified: pkg/Dowd/R/BootstrapES.R pkg/Dowd/R/BootstrapESConfInterval.R pkg/Dowd/R/BootstrapESFigure.R pkg/Dowd/R/BootstrapVaR.R pkg/Dowd/R/BootstrapVaRConfInterval.R pkg/Dowd/R/BootstrapVaRFigure.R Log: "error" of MATLAB code was changed to "stop" in R. Modified: pkg/Dowd/R/BootstrapES.R =================================================================== --- pkg/Dowd/R/BootstrapES.R 2015-06-22 12:34:44 UTC (rev 3688) +++ pkg/Dowd/R/BootstrapES.R 2015-06-22 12:41:03 UTC (rev 3689) @@ -23,10 +23,10 @@ BootstrapES <- function(Ra, number.resamples, cl){ if (nargs() < 3){ - error("Too few arguments") + stop("Too few arguments") } if (nargs() > 3){ - error("Too many arguments") + stop("Too many arguments") } profit.loss.data <- as.vector(Ra) @@ -37,10 +37,10 @@ # Check that inputs have correct dimensions if (length(cl) != 1) { - error("Confidence level must be a scalar") + stop("Confidence level must be a scalar") } if (length(number.resamples) != 1){ - error("Number of resamples must be a scalar"); + stop("Number of resamples must be a scalar"); } # Check that inputs obey sign and value restrictions Modified: pkg/Dowd/R/BootstrapESConfInterval.R =================================================================== --- pkg/Dowd/R/BootstrapESConfInterval.R 2015-06-22 12:34:44 UTC (rev 3688) +++ pkg/Dowd/R/BootstrapESConfInterval.R 2015-06-22 12:41:03 UTC (rev 3689) @@ -42,10 +42,10 @@ # Check that inputs have correct dimensions if (is.vector(cl) & (length(cl) != 1) ) { - error("Confidence level must be a scalar") + stop("Confidence level must be a scalar") } if (length(number.resamples) != 1) { - error("Number of resamples must be a scalar") + stop("Number of resamples must be a scalar") } # Check that inputs obey sign and value restrictions if (cl >= 1){ Modified: pkg/Dowd/R/BootstrapESFigure.R =================================================================== --- pkg/Dowd/R/BootstrapESFigure.R 2015-06-22 12:34:44 UTC (rev 3688) +++ pkg/Dowd/R/BootstrapESFigure.R 2015-06-22 12:41:03 UTC (rev 3689) @@ -41,10 +41,10 @@ # Check that inputs have correct dimensions if (is.vector(cl) & (length(cl) != 1) ) { - error("Confidence level must be a scalar") + stop("Confidence level must be a scalar") } if (length(number.resamples) != 1) { - error("Number of resamples must be a scalar") + stop("Number of resamples must be a scalar") } # Check that inputs obey sign and value restrictions if (cl >= 1){ Modified: pkg/Dowd/R/BootstrapVaR.R =================================================================== --- pkg/Dowd/R/BootstrapVaR.R 2015-06-22 12:34:44 UTC (rev 3688) +++ pkg/Dowd/R/BootstrapVaR.R 2015-06-22 12:41:03 UTC (rev 3689) @@ -23,10 +23,10 @@ BootstrapVaR <- function(Ra, number.resamples, cl){ if (nargs() < 3){ - error("Too few arguments") + stop("Too few arguments") } if (nargs() > 3){ - error("Too many arguments") + stop("Too many arguments") } profit.loss.data <- as.vector(Ra) @@ -37,10 +37,10 @@ # Check that inputs have correct dimensions if (length(cl) != 1) { - error("Confidence level must be a scalar") + stop("Confidence level must be a scalar") } if (length(number.resamples) != 1){ - error("Number of resamples must be a scalar"); + stop("Number of resamples must be a scalar"); } # Check that inputs obey sign and value restrictions Modified: pkg/Dowd/R/BootstrapVaRConfInterval.R =================================================================== --- pkg/Dowd/R/BootstrapVaRConfInterval.R 2015-06-22 12:34:44 UTC (rev 3688) +++ pkg/Dowd/R/BootstrapVaRConfInterval.R 2015-06-22 12:41:03 UTC (rev 3689) @@ -42,10 +42,10 @@ # Check that inputs have correct dimensions if (is.vector(cl) & (length(cl) != 1) ) { - error("Confidence level must be a scalar") + stop("Confidence level must be a scalar") } if (length(number.resamples) != 1) { - error("Number of resamples must be a scalar") + stop("Number of resamples must be a scalar") } # Check that inputs obey sign and value restrictions if (cl >= 1){ Modified: pkg/Dowd/R/BootstrapVaRFigure.R =================================================================== --- pkg/Dowd/R/BootstrapVaRFigure.R 2015-06-22 12:34:44 UTC (rev 3688) +++ pkg/Dowd/R/BootstrapVaRFigure.R 2015-06-22 12:41:03 UTC (rev 3689) @@ -40,10 +40,10 @@ # Check that inputs have correct dimensions if (is.vector(cl) & (length(cl) != 1) ) { - error("Confidence level must be a scalar") + stop("Confidence level must be a scalar") } if (length(number.resamples) != 1) { - error("Number of resamples must be a scalar") + stop("Number of resamples must be a scalar") } # Check that inputs obey sign and value restrictions if (cl >= 1){ From noreply at r-forge.r-project.org Mon Jun 22 14:42:12 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 14:42:12 +0200 (CEST) Subject: [Returnanalytics-commits] r3690 - pkg/Dowd Message-ID: <20150622124212.86BFE180936@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 14:42:12 +0200 (Mon, 22 Jun 2015) New Revision: 3690 Modified: pkg/Dowd/NAMESPACE Log: Import "bootstrap" added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-22 12:41:03 UTC (rev 3689) +++ pkg/Dowd/NAMESPACE 2015-06-22 12:42:12 UTC (rev 3690) @@ -1,54 +1,54 @@ -# Generated by roxygen2 (4.1.1): do not edit by hand - -export(ADTestStat) -export(AdjustedNormalESHotspots) -export(AdjustedNormalVaRHotspots) -export(AdjustedVarianceCovarianceES) -export(AdjustedVarianceCovarianceVaR) -export(BinomialBacktest) -export(BlancoIhleBacktest) -export(BootstrapES) -export(BootstrapESConfInterval) -export(BootstrapESFigure) -export(BootstrapVaR) -export(BootstrapVaRConfInterval) -export(BootstrapVaRFigure) -export(CdfOfSumUsingGaussianCopula) -export(CdfOfSumUsingGumbelCopula) -export(CdfOfSumUsingProductCopula) -export(ChristoffersenBacktestForIndependence) -export(ChristoffersenBacktestForUnconditionalCoverage) -export(CornishFisherES) -export(CornishFisherVaR) -export(FrechetES) -export(FrechetESPlot2DCl) -export(FrechetVaR) -export(FrechetVaRPlot2DCl) -export(GParetoES) -export(GParetoMEFPlot) -export(GParetoMultipleMEFPlot) -export(GParetoVaR) -export(GaussianCopulaVaR) -export(GumbelCopulaVaR) -export(GumbelES) -export(GumbelESPlot2DCl) -export(GumbelVaR) -export(GumbelVaRPlot2DCl) -export(HSES) -export(HSVaR) -export(HSVaRDFPerc) -export(HSVaRFigure) -export(HillEstimator) -export(HillPlot) -export(HillQuantileEstimator) -export(InsuranceVaR) -export(JarqueBeraBacktest) -export(KSTestStat) -export(KuiperTestStat) -export(LopezBacktest) -export(MEFPlot) -export(NormalQQPlot) -export(PickandsEstimator) -export(PickandsPlot) -export(ProductCopulaVaR) -export(TQQPlot) +# Generated by roxygen2 (4.1.0): do not edit by hand + +export(ADTestStat) +export(AdjustedNormalESHotspots) +export(AdjustedNormalVaRHotspots) +export(AdjustedVarianceCovarianceES) +export(AdjustedVarianceCovarianceVaR) +export(BinomialBacktest) +export(BlancoIhleBacktest) +export(BootstrapES) +export(BootstrapESConfInterval) +export(BootstrapESFigure) +export(BootstrapVaR) +export(BootstrapVaRConfInterval) +export(BootstrapVaRFigure) +export(CdfOfSumUsingGaussianCopula) +export(CdfOfSumUsingGumbelCopula) +export(CdfOfSumUsingProductCopula) +export(ChristoffersenBacktestForIndependence) +export(ChristoffersenBacktestForUnconditionalCoverage) +export(CornishFisherES) +export(CornishFisherVaR) +export(FrechetES) +export(FrechetESPlot2DCl) +export(FrechetVaR) +export(FrechetVaRPlot2DCl) +export(GParetoES) +export(GParetoMEFPlot) +export(GParetoMultipleMEFPlot) +export(GParetoVaR) +export(GaussianCopulaVaR) +export(GumbelCopulaVaR) +export(GumbelES) +export(GumbelESPlot2DCl) +export(GumbelVaR) +export(GumbelVaRPlot2DCl) +export(HSES) +export(HSVaR) +export(HSVaRDFPerc) +export(HSVaRFigure) +export(HillEstimator) +export(HillPlot) +export(HillQuantileEstimator) +export(JarqueBeraBacktest) +export(KSTestStat) +export(KuiperTestStat) +export(LopezBacktest) +export(MEFPlot) +export(NormalQQPlot) +export(PickandsEstimator) +export(PickandsPlot) +export(ProductCopulaVaR) +export(TQQPlot) +import(bootstrap) From noreply at r-forge.r-project.org Mon Jun 22 15:42:06 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 15:42:06 +0200 (CEST) Subject: [Returnanalytics-commits] r3691 - pkg/Dowd/R Message-ID: <20150622134206.62F06185F8B@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 15:42:06 +0200 (Mon, 22 Jun 2015) New Revision: 3691 Modified: pkg/Dowd/R/AdjustedNormalESHotspots.R Log: Error in "kurtosis" in documentation. Modified: pkg/Dowd/R/AdjustedNormalESHotspots.R =================================================================== --- pkg/Dowd/R/AdjustedNormalESHotspots.R 2015-06-22 12:42:12 UTC (rev 3690) +++ pkg/Dowd/R/AdjustedNormalESHotspots.R 2015-06-22 13:42:06 UTC (rev 3691) @@ -7,7 +7,7 @@ #' @param vc.matrix Variance covariance matrix for returns #' @param mu Vector of expected position returns #' @param skew Return skew -#' @param kurtisos Return kurtosis +#' @param kurtosis Return kurtosis #' @param positions Vector of positions #' @param cl Confidence level and is scalar #' @param hp Holding period and is scalar From noreply at r-forge.r-project.org Mon Jun 22 15:43:12 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 15:43:12 +0200 (CEST) Subject: [Returnanalytics-commits] r3692 - pkg/Dowd/R Message-ID: <20150622134312.8435F185F8B@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 15:43:12 +0200 (Mon, 22 Jun 2015) New Revision: 3692 Modified: pkg/Dowd/R/AdjustedNormalVaRHotspots.R Log: Typo in "kurtosis" in documentation corrected. Modified: pkg/Dowd/R/AdjustedNormalVaRHotspots.R =================================================================== --- pkg/Dowd/R/AdjustedNormalVaRHotspots.R 2015-06-22 13:42:06 UTC (rev 3691) +++ pkg/Dowd/R/AdjustedNormalVaRHotspots.R 2015-06-22 13:43:12 UTC (rev 3692) @@ -7,7 +7,7 @@ #' @param vc.matrix Variance covariance matrix for returns #' @param mu Vector of expected position returns #' @param skew Return skew -#' @param kurtisos Return kurtosis +#' @param kurtosis Return kurtosis #' @param positions Vector of positions #' @param cl Confidence level and is scalar #' @param hp Holding period and is scalar From noreply at r-forge.r-project.org Mon Jun 22 15:43:47 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 15:43:47 +0200 (CEST) Subject: [Returnanalytics-commits] r3693 - pkg/Dowd/R Message-ID: <20150622134347.CC61D185F8B@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 15:43:47 +0200 (Mon, 22 Jun 2015) New Revision: 3693 Modified: pkg/Dowd/R/AdjustedVarianceCovarianceES.R Log: Typo in "kurtosis" in documentation corrected. Modified: pkg/Dowd/R/AdjustedVarianceCovarianceES.R =================================================================== --- pkg/Dowd/R/AdjustedVarianceCovarianceES.R 2015-06-22 13:43:12 UTC (rev 3692) +++ pkg/Dowd/R/AdjustedVarianceCovarianceES.R 2015-06-22 13:43:47 UTC (rev 3693) @@ -7,7 +7,7 @@ #' @param vc.matrix Variance covariance matrix for returns #' @param mu Vector of expected position returns #' @param skew Return skew -#' @param kurtisos Return kurtosis +#' @param kurtosis Return kurtosis #' @param positions Vector of positions #' @param cl Confidence level and is scalar #' @param hp Holding period and is scalar From noreply at r-forge.r-project.org Mon Jun 22 15:44:03 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 15:44:03 +0200 (CEST) Subject: [Returnanalytics-commits] r3694 - pkg/Dowd/R Message-ID: <20150622134403.DA7D3185F8B@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 15:44:03 +0200 (Mon, 22 Jun 2015) New Revision: 3694 Modified: pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R Log: Typo in "kurtosis" in documentation corrected. Modified: pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R =================================================================== --- pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R 2015-06-22 13:43:47 UTC (rev 3693) +++ pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R 2015-06-22 13:44:03 UTC (rev 3694) @@ -5,7 +5,7 @@ #' @param vc.matrix Assumed variance covariance matrix for returns #' @param mu Vector of expected position returns #' @param skew Portfolio return skewness -#' @param kurtisos Portfolio return kurtosis +#' @param kurtosis Portfolio return kurtosis #' @param positions Vector of positions #' @param cl Confidence level and is scalar or vector #' @param hp Holding period and is scalar or vector From noreply at r-forge.r-project.org Mon Jun 22 15:44:34 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 15:44:34 +0200 (CEST) Subject: [Returnanalytics-commits] r3695 - pkg/Dowd/R Message-ID: <20150622134434.33352185F8B@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 15:44:33 +0200 (Mon, 22 Jun 2015) New Revision: 3695 Modified: pkg/Dowd/R/BootstrapES.R Log: Typo in parameters in documentation corrected. Modified: pkg/Dowd/R/BootstrapES.R =================================================================== --- pkg/Dowd/R/BootstrapES.R 2015-06-22 13:44:03 UTC (rev 3694) +++ pkg/Dowd/R/BootstrapES.R 2015-06-22 13:44:33 UTC (rev 3695) @@ -5,7 +5,8 @@ #' #' @param Ra Vector corresponding to profit and loss distribution #' @param number.resamples Number of samples to be taken in bootstrap procedure -#' @return cl Number corresponding to Expected Shortfall confidence level +#' @param cl Number corresponding to Expected Shortfall confidence level +#' @return Bootstrapped Expected Shortfall #' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' From noreply at r-forge.r-project.org Mon Jun 22 15:44:51 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 15:44:51 +0200 (CEST) Subject: [Returnanalytics-commits] r3696 - pkg/Dowd/R Message-ID: <20150622134451.79E29185F8B@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 15:44:51 +0200 (Mon, 22 Jun 2015) New Revision: 3696 Modified: pkg/Dowd/R/BootstrapESConfInterval.R Log: Typo in parameters in documentation corrected. Modified: pkg/Dowd/R/BootstrapESConfInterval.R =================================================================== --- pkg/Dowd/R/BootstrapESConfInterval.R 2015-06-22 13:44:33 UTC (rev 3695) +++ pkg/Dowd/R/BootstrapESConfInterval.R 2015-06-22 13:44:51 UTC (rev 3696) @@ -4,7 +4,7 @@ #' level and holding period implied by data frequency. #' #' @param Ra Vector corresponding to profit and loss distribution -#' @param number.resample Number of samples to be taken in bootstrap procedure +#' @param number.resamples Number of samples to be taken in bootstrap procedure #' @param cl Number corresponding to Expected Shortfall confidence level #' @return 90% Confidence interval for bootstrapped ES #' From noreply at r-forge.r-project.org Mon Jun 22 15:45:10 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 15:45:10 +0200 (CEST) Subject: [Returnanalytics-commits] r3697 - pkg/Dowd/R Message-ID: <20150622134510.3A691186CBC@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 15:45:09 +0200 (Mon, 22 Jun 2015) New Revision: 3697 Modified: pkg/Dowd/R/BootstrapESFigure.R pkg/Dowd/R/BootstrapVaR.R pkg/Dowd/R/BootstrapVaRConfInterval.R pkg/Dowd/R/BootstrapVaRFigure.R Log: Typo in parameters in documentation corrected. Modified: pkg/Dowd/R/BootstrapESFigure.R =================================================================== --- pkg/Dowd/R/BootstrapESFigure.R 2015-06-22 13:44:51 UTC (rev 3696) +++ pkg/Dowd/R/BootstrapESFigure.R 2015-06-22 13:45:09 UTC (rev 3697) @@ -4,7 +4,7 @@ #' level and holding period implied by data frequency. #' #' @param Ra Vector corresponding to profit and loss distribution -#' @param number.resample Number of samples to be taken in bootstrap procedure +#' @param number.resamples Number of samples to be taken in bootstrap procedure #' @param cl Number corresponding to Expected Shortfall confidence level #' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. Modified: pkg/Dowd/R/BootstrapVaR.R =================================================================== --- pkg/Dowd/R/BootstrapVaR.R 2015-06-22 13:44:51 UTC (rev 3696) +++ pkg/Dowd/R/BootstrapVaR.R 2015-06-22 13:45:09 UTC (rev 3697) @@ -4,8 +4,9 @@ #' implied by data frequency. #' #' @param Ra Vector corresponding to profit and loss distribution -#' @param number.sample Number of samples to be taken in bootstrap procedure -#' @return cl Number corresponding to Value at Risk confidence level +#' @param number.resamples Number of samples to be taken in bootstrap procedure +#' @param cl Number corresponding to Value at Risk confidence level +#' @return Bootstrapped VaR #' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' Modified: pkg/Dowd/R/BootstrapVaRConfInterval.R =================================================================== --- pkg/Dowd/R/BootstrapVaRConfInterval.R 2015-06-22 13:44:51 UTC (rev 3696) +++ pkg/Dowd/R/BootstrapVaRConfInterval.R 2015-06-22 13:45:09 UTC (rev 3697) @@ -4,7 +4,7 @@ #' level and holding period implied by data frequency. #' #' @param Ra Vector corresponding to profit and loss distribution -#' @param number.sample Number of samples to be taken in bootstrap procedure +#' @param number.resamples Number of samples to be taken in bootstrap procedure #' @param cl Number corresponding to Value at Risk confidence level #' @return 90% Confidence interval for bootstrapped VaR #' Modified: pkg/Dowd/R/BootstrapVaRFigure.R =================================================================== --- pkg/Dowd/R/BootstrapVaRFigure.R 2015-06-22 13:44:51 UTC (rev 3696) +++ pkg/Dowd/R/BootstrapVaRFigure.R 2015-06-22 13:45:09 UTC (rev 3697) @@ -4,7 +4,7 @@ #' level and holding period implied by data frequency. #' #' @param Ra Vector corresponding to profit and loss distribution -#' @param number.sample Number of samples to be taken in bootstrap procedure +#' @param number.resamples Number of samples to be taken in bootstrap procedure #' @param cl Number corresponding to Value at Risk confidence level #' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. From noreply at r-forge.r-project.org Mon Jun 22 15:46:41 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 15:46:41 +0200 (CEST) Subject: [Returnanalytics-commits] r3698 - pkg/Dowd/R Message-ID: <20150622134641.9DBAE1805B3@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 15:46:41 +0200 (Mon, 22 Jun 2015) New Revision: 3698 Modified: pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R Log: Wrongly ported initialization corrected (double(x,y) -> matrix(0,x,y)). Modified: pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R =================================================================== --- pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R 2015-06-22 13:45:09 UTC (rev 3697) +++ pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R 2015-06-22 13:46:41 UTC (rev 3698) @@ -84,7 +84,7 @@ # Obtain copula as approximate double sum, which appriximates the 'true' # double integral - term <- double(length(x),length(y)) + term <- matrix(0, length(x),length(y)) for (i in 1:length(x)) { for (j in 1:length(y)) { term[i, j] <- exp(-(x[i]^2-2*rho*x[i]*y[j]+y[j]^2)/(2*(1-rho^2))) From noreply at r-forge.r-project.org Mon Jun 22 15:47:35 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 15:47:35 +0200 (CEST) Subject: [Returnanalytics-commits] r3699 - pkg/Dowd/R Message-ID: <20150622134735.70BEB1805B3@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 15:47:35 +0200 (Mon, 22 Jun 2015) New Revision: 3699 Modified: pkg/Dowd/R/HillEstimator.R Log: Mistake in parameter list corrected. Modified: pkg/Dowd/R/HillEstimator.R =================================================================== --- pkg/Dowd/R/HillEstimator.R 2015-06-22 13:46:41 UTC (rev 3698) +++ pkg/Dowd/R/HillEstimator.R 2015-06-22 13:47:35 UTC (rev 3699) @@ -9,7 +9,6 @@ #' @param Ra Data set #' @param tail.size Number of observations to be used to estimate the Hill #' estimator. -#' @param cl ES confidence level #' @return Estimated value of Hill Estimator #' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. From noreply at r-forge.r-project.org Mon Jun 22 15:48:20 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 15:48:20 +0200 (CEST) Subject: [Returnanalytics-commits] r3700 - pkg/Dowd/R Message-ID: <20150622134820.235AF186CF5@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 15:48:19 +0200 (Mon, 22 Jun 2015) New Revision: 3700 Modified: pkg/Dowd/R/HSES.R Log: Wrongly ported function corrected (ceil -> ceiling). Modified: pkg/Dowd/R/HSES.R =================================================================== --- pkg/Dowd/R/HSES.R 2015-06-22 13:47:35 UTC (rev 3699) +++ pkg/Dowd/R/HSES.R 2015-06-22 13:48:19 UTC (rev 3700) @@ -86,7 +86,7 @@ upper.tail.losses <- losses.data[upper.k] # Creates data set of upper tail loss obs. upper.es <- mean(upper.tail.losses) # Upper ES # Deal with loss observation just below VaR to derive lower ES - lower.index <- ceil(index) + lower.index <- ceiling(index) lower.VaR <- losses.data[lower.index] # Lower VaR lower.k <- which(lower.VaR <= losses.data) # Finds indices of lower tail loss data lower.tail.losses <- losses.data[lower.k] # Creates data set of lower tail loss obs. From noreply at r-forge.r-project.org Mon Jun 22 15:54:46 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 15:54:46 +0200 (CEST) Subject: [Returnanalytics-commits] r3701 - pkg/Dowd/R Message-ID: <20150622135447.081BA186CF5@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 15:54:46 +0200 (Mon, 22 Jun 2015) New Revision: 3701 Modified: pkg/Dowd/R/ProductCopulaVaR.R Log: Unnecessary additional parameter in CdfOfSumUsingProductCopula removed. Modified: pkg/Dowd/R/ProductCopulaVaR.R =================================================================== --- pkg/Dowd/R/ProductCopulaVaR.R 2015-06-22 13:48:19 UTC (rev 3700) +++ pkg/Dowd/R/ProductCopulaVaR.R 2015-06-22 13:54:46 UTC (rev 3701) @@ -48,7 +48,7 @@ tol <- 0.0001 # Tolerance level (NM: change manually if desired) while (U - L > tol){ x <- (L + U) / 2 # Bisection carried out in terms of P/L quantiles or minus VaR - cum.prob <- CdfOfSumUsingProductCopula(x, mu1, mu2, sigma1, sigma2, beta) + cum.prob <- CdfOfSumUsingProductCopula(x, mu1, mu2, sigma1, sigma2) fx <- cum.prob - p if (sign(fx) == sign(fL)){ L <- x From noreply at r-forge.r-project.org Mon Jun 22 16:06:36 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 16:06:36 +0200 (CEST) Subject: [Returnanalytics-commits] r3702 - pkg/Dowd/man Message-ID: <20150622140636.AE27B186CF5@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 16:06:36 +0200 (Mon, 22 Jun 2015) New Revision: 3702 Modified: pkg/Dowd/man/ADTestStat.Rd pkg/Dowd/man/AdjustedNormalESHotspots.Rd pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd pkg/Dowd/man/BinomialBacktest.Rd pkg/Dowd/man/BlancoIhleBacktest.Rd pkg/Dowd/man/BootstrapES.Rd pkg/Dowd/man/BootstrapESConfInterval.Rd pkg/Dowd/man/BootstrapESFigure.Rd pkg/Dowd/man/BootstrapVaR.Rd pkg/Dowd/man/BootstrapVaRConfInterval.Rd pkg/Dowd/man/BootstrapVaRFigure.Rd pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd pkg/Dowd/man/CdfOfSumUsingGumbelCopula.Rd pkg/Dowd/man/CdfOfSumUsingProductCopula.Rd pkg/Dowd/man/ChristoffersenBacktestForIndependence.Rd pkg/Dowd/man/ChristoffersenBacktestForUnconditionalCoverage.Rd pkg/Dowd/man/CornishFisherES.Rd pkg/Dowd/man/CornishFisherVaR.Rd pkg/Dowd/man/FrechetES.Rd pkg/Dowd/man/FrechetESPlot2DCl.Rd pkg/Dowd/man/FrechetVaR.Rd pkg/Dowd/man/FrechetVaRPlot2DCl.Rd pkg/Dowd/man/GParetoES.Rd pkg/Dowd/man/GParetoMEFPlot.Rd pkg/Dowd/man/GParetoMultipleMEFPlot.Rd pkg/Dowd/man/GParetoVaR.Rd pkg/Dowd/man/GaussianCopulaVaR.Rd pkg/Dowd/man/GumbelCopulaVaR.Rd pkg/Dowd/man/GumbelES.Rd pkg/Dowd/man/GumbelESPlot2DCl.Rd pkg/Dowd/man/GumbelVaR.Rd pkg/Dowd/man/GumbelVaRPlot2DCl.Rd pkg/Dowd/man/HSES.Rd pkg/Dowd/man/HSVaR.Rd pkg/Dowd/man/HSVaRDFPerc.Rd pkg/Dowd/man/HSVaRFigure.Rd pkg/Dowd/man/HillEstimator.Rd pkg/Dowd/man/HillPlot.Rd pkg/Dowd/man/HillQuantileEstimator.Rd pkg/Dowd/man/JarqueBeraBacktest.Rd pkg/Dowd/man/KSTestStat.Rd pkg/Dowd/man/KuiperTestStat.Rd pkg/Dowd/man/LopezBacktest.Rd pkg/Dowd/man/MEFPlot.Rd pkg/Dowd/man/NormalQQPlot.Rd pkg/Dowd/man/PickandsEstimator.Rd pkg/Dowd/man/PickandsPlot.Rd pkg/Dowd/man/ProductCopulaVaR.Rd pkg/Dowd/man/TQQPlot.Rd Log: Correction of typo in documentation/parameter list. Modified: pkg/Dowd/man/ADTestStat.Rd =================================================================== --- pkg/Dowd/man/ADTestStat.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/ADTestStat.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,45 +1,45 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/ADTestStat.R -\name{ADTestStat} -\alias{ADTestStat} -\title{Plots cumulative density for AD test and computes confidence -interval for AD test stat.} -\usage{ -ADTestStat(number.trials, sample.size, confidence.interval) -} -\arguments{ -\item{number.trials}{Number of trials} - -\item{sample.size}{Sample size} - -\item{confidence.interval}{Confidence Interval} -} -\value{ -Confidence Interval for AD test statistic -} -\description{ -Anderson-Darling(AD) test can be used to carry out distribution equality test and is -similar to Kolmogorov-Smirnov test. AD test statistic is defined as: -\deqn{A^2=n\int_{-\infty}^{\infty}\frac{[\hat{F}(x)-F(x)]^2}{F(x)[1-F(x)]}dF(x)} -which is equivalent to -\deqn{=-n-\frac{1}{n}\sum_{i=1}^n(2i-1)[\ln F(X_i)+\ln(1-F(X_{n+1-i}))]} -} -\examples{ -# Probability that the VaR model is correct for 3 failures, 100 number - # observations and 95\% confidence level - ADTestStat(1000, 100, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. - -Anderson, T.W. and Darling, D.A. Asymptotic Theory of Certain Goodness of -Fit Criteria Based on Stochastic Processes, The Annals of Mathematical -Statistics, 23(2), 1952, p. 193-212. - -Kvam, P.H. and Vidakovic, B. Nonparametric Statistics with Applications to -Science and Engineering, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/ADTestStat.R +\name{ADTestStat} +\alias{ADTestStat} +\title{Plots cumulative density for AD test and computes confidence +interval for AD test stat.} +\usage{ +ADTestStat(number.trials, sample.size, confidence.interval) +} +\arguments{ +\item{number.trials}{Number of trials} + +\item{sample.size}{Sample size} + +\item{confidence.interval}{Confidence Interval} +} +\value{ +Confidence Interval for AD test statistic +} +\description{ +Anderson-Darling(AD) test can be used to carry out distribution equality test and is +similar to Kolmogorov-Smirnov test. AD test statistic is defined as: +\deqn{A^2=n\int_{-\infty}^{\infty}\frac{[\hat{F}(x)-F(x)]^2}{F(x)[1-F(x)]}dF(x)} +which is equivalent to +\deqn{=-n-\frac{1}{n}\sum_{i=1}^n(2i-1)[\ln F(X_i)+\ln(1-F(X_{n+1-i}))]} +} +\examples{ +# Probability that the VaR model is correct for 3 failures, 100 number + # observations and 95\% confidence level + ADTestStat(1000, 100, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Anderson, T.W. and Darling, D.A. Asymptotic Theory of Certain Goodness of +Fit Criteria Based on Stochastic Processes, The Annals of Mathematical +Statistics, 23(2), 1952, p. 193-212. + +Kvam, P.H. and Vidakovic, B. Nonparametric Statistics with Applications to +Science and Engineering, Wiley, 2007. +} + Modified: pkg/Dowd/man/AdjustedNormalESHotspots.Rd =================================================================== --- pkg/Dowd/man/AdjustedNormalESHotspots.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/AdjustedNormalESHotspots.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,46 +1,46 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/AdjustedNormalESHotspots.R -\name{AdjustedNormalESHotspots} -\alias{AdjustedNormalESHotspots} -\title{Hotspots for ES adjusted by Cornish-Fisher correction} -\usage{ -AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\arguments{ -\item{vc.matrix}{Variance covariance matrix for returns} - -\item{mu}{Vector of expected position returns} - -\item{skew}{Return skew} - -\item{positions}{Vector of positions} - -\item{cl}{Confidence level and is scalar} - -\item{hp}{Holding period and is scalar} - -\item{kurtisos}{Return kurtosis} -} -\description{ -Estimates the ES hotspots (or vector of incremental ESs) for a -portfolio with portfolio return adjusted for non-normality by Cornish-Fisher -corerction, for specified confidence level and holding period. -} -\examples{ -# Hotspots for ES for randomly generated portfolio - vc.matrix <- matrix(rnorm(16),4,4) - mu <- rnorm(4) - skew <- .5 - kurtosis <- 1.2 - positions <- c(5,2,6,10) - cl <- .95 - hp <- 280 - AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/AdjustedNormalESHotspots.R +\name{AdjustedNormalESHotspots} +\alias{AdjustedNormalESHotspots} +\title{Hotspots for ES adjusted by Cornish-Fisher correction} +\usage{ +AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Return skew} + +\item{kurtosis}{Return kurtosis} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar} +} +\description{ +Estimates the ES hotspots (or vector of incremental ESs) for a +portfolio with portfolio return adjusted for non-normality by Cornish-Fisher +corerction, for specified confidence level and holding period. +} +\examples{ +# Hotspots for ES for randomly generated portfolio + vc.matrix <- matrix(rnorm(16),4,4) + mu <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,10) + cl <- .95 + hp <- 280 + AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd =================================================================== --- pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,46 +1,46 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/AdjustedNormalVaRHotspots.R -\name{AdjustedNormalVaRHotspots} -\alias{AdjustedNormalVaRHotspots} -\title{Hotspots for VaR adjusted by Cornish-Fisher correction} -\usage{ -AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\arguments{ -\item{vc.matrix}{Variance covariance matrix for returns} - -\item{mu}{Vector of expected position returns} - -\item{skew}{Return skew} - -\item{positions}{Vector of positions} - -\item{cl}{Confidence level and is scalar} - -\item{hp}{Holding period and is scalar} - -\item{kurtisos}{Return kurtosis} -} -\description{ -Estimates the VaR hotspots (or vector of incremental VaRs) for a -portfolio with portfolio return adjusted for non-normality by Cornish-Fisher -corerction, for specified confidence level and holding period. -} -\examples{ -# Hotspots for ES for randomly generated portfolio - vc.matrix <- matrix(rnorm(16),4,4) - mu <- rnorm(4) - skew <- .5 - kurtosis <- 1.2 - positions <- c(5,2,6,10) - cl <- .95 - hp <- 280 - AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/AdjustedNormalVaRHotspots.R +\name{AdjustedNormalVaRHotspots} +\alias{AdjustedNormalVaRHotspots} +\title{Hotspots for VaR adjusted by Cornish-Fisher correction} +\usage{ +AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Return skew} + +\item{kurtosis}{Return kurtosis} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar} +} +\description{ +Estimates the VaR hotspots (or vector of incremental VaRs) for a +portfolio with portfolio return adjusted for non-normality by Cornish-Fisher +corerction, for specified confidence level and holding period. +} +\examples{ +# Hotspots for ES for randomly generated portfolio + vc.matrix <- matrix(rnorm(16),4,4) + mu <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,10) + cl <- .95 + hp <- 280 + AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd =================================================================== --- pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,45 +1,45 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/AdjustedVarianceCovarianceES.R -\name{AdjustedVarianceCovarianceES} -\alias{AdjustedVarianceCovarianceES} -\title{Cornish-Fisher adjusted Variance-Covariance ES} -\usage{ -AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\arguments{ -\item{vc.matrix}{Variance covariance matrix for returns} - -\item{mu}{Vector of expected position returns} - -\item{skew}{Return skew} - -\item{positions}{Vector of positions} - -\item{cl}{Confidence level and is scalar} - -\item{hp}{Holding period and is scalar} - -\item{kurtisos}{Return kurtosis} -} -\description{ -Function estimates the Variance-Covariance ES of a multi-asset -portfolio using the Cornish - Fisher adjustment for portfolio return -non-normality, for specified confidence level and holding period. -} -\examples{ -# Variance-covariance ES for randomly generated portfolio - vc.matrix <- matrix(rnorm(16), 4, 4) - skew <- .5 - kurtosis <- 1.2 - positions <- c(5, 2, 6, 10) - cl <- .95 - hp <- 280 - AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/AdjustedVarianceCovarianceES.R +\name{AdjustedVarianceCovarianceES} +\alias{AdjustedVarianceCovarianceES} +\title{Cornish-Fisher adjusted Variance-Covariance ES} +\usage{ +AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Return skew} + +\item{kurtosis}{Return kurtosis} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar} +} +\description{ +Function estimates the Variance-Covariance ES of a multi-asset +portfolio using the Cornish - Fisher adjustment for portfolio return +non-normality, for specified confidence level and holding period. +} +\examples{ +# Variance-covariance ES for randomly generated portfolio + vc.matrix <- matrix(rnorm(16), 4, 4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5, 2, 6, 10) + cl <- .95 + hp <- 280 + AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd =================================================================== --- pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,44 +1,44 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/AdjustedVarianceCovarianceVaR.R -\name{AdjustedVarianceCovarianceVaR} -\alias{AdjustedVarianceCovarianceVaR} -\title{Cornish-Fisher adjusted variance-covariance VaR} -\usage{ -AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\arguments{ -\item{vc.matrix}{Assumed variance covariance matrix for returns} - -\item{mu}{Vector of expected position returns} - -\item{skew}{Portfolio return skewness} - -\item{positions}{Vector of positions} - -\item{cl}{Confidence level and is scalar or vector} - -\item{hp}{Holding period and is scalar or vector} - -\item{kurtisos}{Portfolio return kurtosis} -} -\description{ -Estimates the variance-covariance VaR of a multi-asset portfolio using the Cornish-Fisher adjustment for portfolio-return non-normality, for specified confidence level and holding period. -} -\examples{ -# Variance-covariance for randomly generated portfolio - vc.matrix <- matrix(rnorm(16),4,4) - return <- rnorm(4) - skew <- .5 - kurtosis <- 1.2 - positions <- c(5,2,6,10) - cl <- .95 - hp <- 280 - AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/AdjustedVarianceCovarianceVaR.R +\name{AdjustedVarianceCovarianceVaR} +\alias{AdjustedVarianceCovarianceVaR} +\title{Cornish-Fisher adjusted variance-covariance VaR} +\usage{ +AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Assumed variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Portfolio return skewness} + +\item{kurtosis}{Portfolio return kurtosis} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar or vector} + +\item{hp}{Holding period and is scalar or vector} +} +\description{ +Estimates the variance-covariance VaR of a multi-asset portfolio using the Cornish-Fisher adjustment for portfolio-return non-normality, for specified confidence level and holding period. +} +\examples{ +# Variance-covariance for randomly generated portfolio + vc.matrix <- matrix(rnorm(16),4,4) + return <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,10) + cl <- .95 + hp <- 280 + AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BinomialBacktest.Rd =================================================================== --- pkg/Dowd/man/BinomialBacktest.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/BinomialBacktest.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,41 +1,41 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BinomialBacktest.R -\name{BinomialBacktest} -\alias{BinomialBacktest} -\title{Carries out the binomial backtest for a VaR risk measurement model.} -\usage{ -BinomialBacktest(x, n, cl) -} -\arguments{ -\item{x}{Number of failures} - -\item{n}{Number of observations} - -\item{cl}{Confidence level for VaR} -} -\value{ -Probability that the VaR model is correct -} -\description{ -The basic idea behind binomial backtest (also called basic frequency -test) is to test whether the observed frequency of losses that exceed VaR is -consistent with the frequency of tail losses predicted by the mode. Binomial -Backtest carries out the binomial backtest for a VaR risk measurement model -for specified VaR confidence level and for a one-sided alternative -hypothesis (H1). -} -\examples{ -# Probability that the VaR model is correct for 3 failures, 100 number - # observations and 95\% confidence level - BinomialBacktest(55, 1000, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, Kevin. Measuring Market Risk, Wiley, 2007. - -Kupiec, Paul. Techniques for verifying the accuracy of risk measurement -models, Journal of Derivatives, Winter 1995, p. 79. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/BinomialBacktest.R +\name{BinomialBacktest} +\alias{BinomialBacktest} +\title{Carries out the binomial backtest for a VaR risk measurement model.} +\usage{ +BinomialBacktest(x, n, cl) +} +\arguments{ +\item{x}{Number of failures} + +\item{n}{Number of observations} + +\item{cl}{Confidence level for VaR} +} +\value{ +Probability that the VaR model is correct +} +\description{ +The basic idea behind binomial backtest (also called basic frequency +test) is to test whether the observed frequency of losses that exceed VaR is +consistent with the frequency of tail losses predicted by the mode. Binomial +Backtest carries out the binomial backtest for a VaR risk measurement model +for specified VaR confidence level and for a one-sided alternative +hypothesis (H1). +} +\examples{ +# Probability that the VaR model is correct for 3 failures, 100 number + # observations and 95\% confidence level + BinomialBacktest(55, 1000, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Kupiec, Paul. Techniques for verifying the accuracy of risk measurement +models, Journal of Derivatives, Winter 1995, p. 79. +} + Modified: pkg/Dowd/man/BlancoIhleBacktest.Rd =================================================================== --- pkg/Dowd/man/BlancoIhleBacktest.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/BlancoIhleBacktest.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,42 +1,42 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BlancoIhleBacktest.R -\name{BlancoIhleBacktest} -\alias{BlancoIhleBacktest} -\title{Blanco-Ihle forecast evaluation backtest measure} -\usage{ -BlancoIhleBacktest(Ra, Rb, Rc, cl) -} -\arguments{ -\item{Ra}{Vector of a portfolio profit and loss} - -\item{Rb}{Vector of corresponding VaR forecasts} - -\item{Rc}{Vector of corresponding Expected Tailed Loss forecasts} - -\item{cl}{VaR confidence interval} -} -\value{ -Something -} -\description{ -Derives the Blanco-Ihle forecast evaluation loss measure for a VaR -risk measurement model. -} -\examples{ -# Has to be modified with appropriate data: - # Christoffersen Backtest For Independence for given parameters - a <- rnorm(1*100) - b <- abs(rnorm(1*100))+2 - c <- abs(rnorm(1*100))+2 - BlancoIhleBacktest(a, b, c, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, Kevin. Measuring Market Risk, Wiley, 2007. - -Blanco, C. and Ihle, G. How Good is Your Var? Using Backtesting to Assess -System Performance. Financial Engineering News, 1999. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/BlancoIhleBacktest.R +\name{BlancoIhleBacktest} +\alias{BlancoIhleBacktest} +\title{Blanco-Ihle forecast evaluation backtest measure} +\usage{ +BlancoIhleBacktest(Ra, Rb, Rc, cl) +} +\arguments{ +\item{Ra}{Vector of a portfolio profit and loss} + +\item{Rb}{Vector of corresponding VaR forecasts} + +\item{Rc}{Vector of corresponding Expected Tailed Loss forecasts} + +\item{cl}{VaR confidence interval} +} +\value{ +Something +} +\description{ +Derives the Blanco-Ihle forecast evaluation loss measure for a VaR +risk measurement model. +} +\examples{ +# Has to be modified with appropriate data: + # Christoffersen Backtest For Independence for given parameters + a <- rnorm(1*100) + b <- abs(rnorm(1*100))+2 + c <- abs(rnorm(1*100))+2 + BlancoIhleBacktest(a, b, c, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Blanco, C. and Ihle, G. How Good is Your Var? Using Backtesting to Assess +System Performance. Financial Engineering News, 1999. +} + Modified: pkg/Dowd/man/BootstrapES.Rd =================================================================== --- pkg/Dowd/man/BootstrapES.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/BootstrapES.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,32 +1,34 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapES.R -\name{BootstrapES} -\alias{BootstrapES} -\title{Bootstrapped ES for specified confidence level} -\usage{ -BootstrapES(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.resamples}{Number of samples to be taken in bootstrap procedure} -} -\value{ -cl Number corresponding to Expected Shortfall confidence level -} -\description{ -Estimates the bootstrapped ES for confidence level and holding period -implied by data frequency. -} -\examples{ -# Estimates bootstrapped ES for given parameters - a <- rnorm(100) # generate a random profit/loss vector - BootstrapVaR(a, 50, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/BootstrapES.R +\name{BootstrapES} +\alias{BootstrapES} +\title{Bootstrapped ES for specified confidence level} +\usage{ +BootstrapES(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Expected Shortfall confidence level} +} +\value{ +Bootstrapped Expected Shortfall +} +\description{ +Estimates the bootstrapped ES for confidence level and holding period +implied by data frequency. +} +\examples{ +# Estimates bootstrapped ES for given parameters + a <- rnorm(100) # generate a random profit/loss vector + BootstrapVaR(a, 50, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapESConfInterval.Rd =================================================================== --- pkg/Dowd/man/BootstrapESConfInterval.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/BootstrapESConfInterval.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,36 +1,36 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapESConfInterval.R -\name{BootstrapESConfInterval} -\alias{BootstrapESConfInterval} -\title{Bootstrapped ES Confidence Interval} -\usage{ -BootstrapESConfInterval(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{cl}{Number corresponding to Expected Shortfall confidence level} - -\item{number.resample}{Number of samples to be taken in bootstrap procedure} -} -\value{ -90% Confidence interval for bootstrapped ES -} -\description{ -Estimates the 90% confidence interval for bootstrapped ES, for confidence -level and holding period implied by data frequency. -} -\examples{ -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped ES for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapESConfInterval(Ra, 50, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/BootstrapESConfInterval.R +\name{BootstrapESConfInterval} +\alias{BootstrapESConfInterval} +\title{Bootstrapped ES Confidence Interval} +\usage{ +BootstrapESConfInterval(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Expected Shortfall confidence level} +} +\value{ +90% Confidence interval for bootstrapped ES +} +\description{ +Estimates the 90% confidence interval for bootstrapped ES, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped ES for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapESConfInterval(Ra, 50, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapESFigure.Rd =================================================================== --- pkg/Dowd/man/BootstrapESFigure.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/BootstrapESFigure.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,33 +1,33 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapESFigure.R -\name{BootstrapESFigure} -\alias{BootstrapESFigure} -\title{Plots figure of bootstrapped ES} -\usage{ -BootstrapESFigure(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{cl}{Number corresponding to Expected Shortfall confidence level} - -\item{number.resample}{Number of samples to be taken in bootstrap procedure} -} -\description{ -Plots figure for the bootstrapped ES, for confidence -level and holding period implied by data frequency. -} -\examples{ -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped ES for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapESFigure(Ra, 500, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/BootstrapESFigure.R +\name{BootstrapESFigure} +\alias{BootstrapESFigure} +\title{Plots figure of bootstrapped ES} +\usage{ +BootstrapESFigure(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Expected Shortfall confidence level} +} +\description{ +Plots figure for the bootstrapped ES, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped ES for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapESFigure(Ra, 500, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapVaR.Rd =================================================================== --- pkg/Dowd/man/BootstrapVaR.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/BootstrapVaR.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,32 +1,34 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapVaR.R -\name{BootstrapVaR} -\alias{BootstrapVaR} -\title{Bootstrapped VaR for specified confidence level} -\usage{ -BootstrapVaR(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.sample}{Number of samples to be taken in bootstrap procedure} -} -\value{ -cl Number corresponding to Value at Risk confidence level -} -\description{ -Estimates the bootstrapped VaR for confidence level and holding period -implied by data frequency. -} -\examples{ -# Estimates bootstrapped VaR for given parameters - a <- rnorm(100) # generate a random profit/loss vector - BootstrapES(a, 50, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/BootstrapVaR.R +\name{BootstrapVaR} +\alias{BootstrapVaR} +\title{Bootstrapped VaR for specified confidence level} +\usage{ +BootstrapVaR(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Value at Risk confidence level} +} +\value{ +Bootstrapped VaR +} +\description{ +Estimates the bootstrapped VaR for confidence level and holding period +implied by data frequency. +} +\examples{ +# Estimates bootstrapped VaR for given parameters + a <- rnorm(100) # generate a random profit/loss vector + BootstrapES(a, 50, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapVaRConfInterval.Rd =================================================================== --- pkg/Dowd/man/BootstrapVaRConfInterval.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/BootstrapVaRConfInterval.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,36 +1,36 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapVaRConfInterval.R -\name{BootstrapVaRConfInterval} -\alias{BootstrapVaRConfInterval} -\title{Bootstrapped VaR Confidence Interval} -\usage{ -BootstrapVaRConfInterval(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{cl}{Number corresponding to Value at Risk confidence level} - -\item{number.sample}{Number of samples to be taken in bootstrap procedure} -} -\value{ -90% Confidence interval for bootstrapped VaR -} -\description{ -Estimates the 90% confidence interval for bootstrapped VaR, for confidence -level and holding period implied by data frequency. -} -\examples{ -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped Var for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapVaRConfInterval(Ra, 500, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/BootstrapVaRConfInterval.R +\name{BootstrapVaRConfInterval} +\alias{BootstrapVaRConfInterval} +\title{Bootstrapped VaR Confidence Interval} +\usage{ +BootstrapVaRConfInterval(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Value at Risk confidence level} +} +\value{ +90% Confidence interval for bootstrapped VaR +} +\description{ +Estimates the 90% confidence interval for bootstrapped VaR, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped Var for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapVaRConfInterval(Ra, 500, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapVaRFigure.Rd =================================================================== --- pkg/Dowd/man/BootstrapVaRFigure.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/BootstrapVaRFigure.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,33 +1,33 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapVaRFigure.R -\name{BootstrapVaRFigure} -\alias{BootstrapVaRFigure} -\title{Plots figure of bootstrapped VaR} -\usage{ -BootstrapVaRFigure(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{cl}{Number corresponding to Value at Risk confidence level} - -\item{number.sample}{Number of samples to be taken in bootstrap procedure} -} -\description{ -Plots figure for the bootstrapped VaR, for confidence -level and holding period implied by data frequency. -} -\examples{ -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped VaR for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapESFigure(Ra, 500, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/BootstrapVaRFigure.R +\name{BootstrapVaRFigure} +\alias{BootstrapVaRFigure} +\title{Plots figure of bootstrapped VaR} +\usage{ +BootstrapVaRFigure(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Value at Risk confidence level} +} +\description{ +Plots figure for the bootstrapped VaR, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped VaR for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapESFigure(Ra, 500, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd =================================================================== --- pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd 2015-06-22 13:54:46 UTC (rev 3701) +++ pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd 2015-06-22 14:06:36 UTC (rev 3702) @@ -1,49 +1,49 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/CdfOfSumUsingGaussianCopula.R -\name{CdfOfSumUsingGaussianCopula} -\alias{CdfOfSumUsingGaussianCopula} -\title{Derives prob ( X + Y < quantile) using Gumbel copula} -\usage{ -CdfOfSumUsingGaussianCopula(quantile, mu1, mu2, sigma1, sigma2, rho, - number.steps.in.copula) -} -\arguments{ -\item{quantile}{Portfolio quantile (or negative of Var, if X, Y are position P/Ls)} - -\item{mu1}{Mean of Profit/Loss on first position} - -\item{mu2}{Mean of Profit/Loss on second position} - -\item{sigma1}{Standard Deviation of Profit/Loss on first position} - -\item{sigma2}{Standard Deviation of Profit/Loss on second position} - [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3702 From noreply at r-forge.r-project.org Mon Jun 22 16:09:11 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 16:09:11 +0200 (CEST) Subject: [Returnanalytics-commits] r3703 - pkg/Dowd/R Message-ID: <20150622140911.5923D1861AB@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 16:09:11 +0200 (Mon, 22 Jun 2015) New Revision: 3703 Modified: pkg/Dowd/R/ADTestStat.R Log: Condition on parameter "cl" corrected. Modified: pkg/Dowd/R/ADTestStat.R =================================================================== --- pkg/Dowd/R/ADTestStat.R 2015-06-22 14:06:36 UTC (rev 3702) +++ pkg/Dowd/R/ADTestStat.R 2015-06-22 14:09:11 UTC (rev 3703) @@ -33,7 +33,7 @@ if (confidence.interval >= 1){ stop("Confidence Interval should be less than 1.") } - if (confidence.interval <= 1){ + if (confidence.interval <= 0){ stop("Confidence Interval should be positive.") } From noreply at r-forge.r-project.org Mon Jun 22 16:13:28 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 16:13:28 +0200 (CEST) Subject: [Returnanalytics-commits] r3704 - pkg/Dowd/R Message-ID: <20150622141328.6B5491861AB@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 16:13:28 +0200 (Mon, 22 Jun 2015) New Revision: 3704 Modified: pkg/Dowd/R/AdjustedNormalESHotspots.R Log: Typo in function name in example corrected. Modified: pkg/Dowd/R/AdjustedNormalESHotspots.R =================================================================== --- pkg/Dowd/R/AdjustedNormalESHotspots.R 2015-06-22 14:09:11 UTC (rev 3703) +++ pkg/Dowd/R/AdjustedNormalESHotspots.R 2015-06-22 14:13:28 UTC (rev 3704) @@ -26,7 +26,7 @@ #' positions <- c(5,2,6,10) #' cl <- .95 #' hp <- 280 -#' AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +#' AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) #' #' @export AdjustedNormalESHotspots <- function(vc.matrix, mu, skew, kurtosis, positions, From noreply at r-forge.r-project.org Mon Jun 22 16:14:59 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 16:14:59 +0200 (CEST) Subject: [Returnanalytics-commits] r3705 - pkg/Dowd/man Message-ID: <20150622141459.F04221861AB@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 16:14:59 +0200 (Mon, 22 Jun 2015) New Revision: 3705 Modified: pkg/Dowd/man/AdjustedNormalESHotspots.Rd Log: Typo in function name in example corrected. Modified: pkg/Dowd/man/AdjustedNormalESHotspots.Rd =================================================================== --- pkg/Dowd/man/AdjustedNormalESHotspots.Rd 2015-06-22 14:13:28 UTC (rev 3704) +++ pkg/Dowd/man/AdjustedNormalESHotspots.Rd 2015-06-22 14:14:59 UTC (rev 3705) @@ -35,7 +35,7 @@ positions <- c(5,2,6,10) cl <- .95 hp <- 280 - AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) + AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) } \author{ Dinesh Acharya From noreply at r-forge.r-project.org Mon Jun 22 16:35:46 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 16:35:46 +0200 (CEST) Subject: [Returnanalytics-commits] r3706 - in pkg/Dowd: R man Message-ID: <20150622143546.BE678186CF5@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 16:35:46 +0200 (Mon, 22 Jun 2015) New Revision: 3706 Modified: pkg/Dowd/R/AdjustedVarianceCovarianceES.R pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd Log: In example undefined parameter mu was defined. Modified: pkg/Dowd/R/AdjustedVarianceCovarianceES.R =================================================================== --- pkg/Dowd/R/AdjustedVarianceCovarianceES.R 2015-06-22 14:14:59 UTC (rev 3705) +++ pkg/Dowd/R/AdjustedVarianceCovarianceES.R 2015-06-22 14:35:46 UTC (rev 3706) @@ -20,6 +20,7 @@ #' #' # Variance-covariance ES for randomly generated portfolio #' vc.matrix <- matrix(rnorm(16), 4, 4) +#' mu <- rnorm(4) #' skew <- .5 #' kurtosis <- 1.2 #' positions <- c(5, 2, 6, 10) Modified: pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd =================================================================== --- pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd 2015-06-22 14:14:59 UTC (rev 3705) +++ pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd 2015-06-22 14:35:46 UTC (rev 3706) @@ -29,6 +29,7 @@ \examples{ # Variance-covariance ES for randomly generated portfolio vc.matrix <- matrix(rnorm(16), 4, 4) + mu <- rnorm(4) skew <- .5 kurtosis <- 1.2 positions <- c(5, 2, 6, 10) From noreply at r-forge.r-project.org Mon Jun 22 16:36:41 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 16:36:41 +0200 (CEST) Subject: [Returnanalytics-commits] r3707 - in pkg/Dowd: R man Message-ID: <20150622143641.9C51E186CF5@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 16:36:41 +0200 (Mon, 22 Jun 2015) New Revision: 3707 Modified: pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd Log: In example, wrongly named parameter was corrected. Modified: pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R =================================================================== --- pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R 2015-06-22 14:35:46 UTC (rev 3706) +++ pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R 2015-06-22 14:36:41 UTC (rev 3707) @@ -18,7 +18,7 @@ #' #' # Variance-covariance for randomly generated portfolio #' vc.matrix <- matrix(rnorm(16),4,4) -#' return <- rnorm(4) +#' mu <- rnorm(4) #' skew <- .5 #' kurtosis <- 1.2 #' positions <- c(5,2,6,10) Modified: pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd =================================================================== --- pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd 2015-06-22 14:35:46 UTC (rev 3706) +++ pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd 2015-06-22 14:36:41 UTC (rev 3707) @@ -27,7 +27,7 @@ \examples{ # Variance-covariance for randomly generated portfolio vc.matrix <- matrix(rnorm(16),4,4) - return <- rnorm(4) + mu <- rnorm(4) skew <- .5 kurtosis <- 1.2 positions <- c(5,2,6,10) From noreply at r-forge.r-project.org Mon Jun 22 16:37:09 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 16:37:09 +0200 (CEST) Subject: [Returnanalytics-commits] r3708 - pkg/Dowd Message-ID: <20150622143709.0ABE3186CF5@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 16:37:08 +0200 (Mon, 22 Jun 2015) New Revision: 3708 Removed: pkg/Dowd/readme.txt Log: "readme.txt" replaced with README. Deleted: pkg/Dowd/readme.txt =================================================================== --- pkg/Dowd/readme.txt 2015-06-22 14:36:41 UTC (rev 3707) +++ pkg/Dowd/readme.txt 2015-06-22 14:37:08 UTC (rev 3708) @@ -1,28 +0,0 @@ -# -# General Notes for Modification: -#*************************************************************** -# FrechetVaR does not use hp and the remark about return value when it is vector is vaccuous. -#*************************************************************** -# In Normal/t QQ Plots, dowd code does not work for matrices but the code contains parts that -# work for matrices. some vectors like pvec are not defined anywhere in his code. -#*************************************************************** -# Some error is present in GumbelCopulaVaR and needs correction -#*************************************************************** -# Bootstrap is functional (but HSVaR still does not accept matrix P/L -# and only still accepts vectors, its needs to be modified) -#*************************************************************** -# Jarque-Bera Test: -# It has to be checked Probability of null (H0) or (H1). -#*************************************************************** -# Christofferson Backtest for Independence: -# VaR(excess_loss<=0)=[]; Does not make sense. It is still to be checked if it is as intended. -# if(excess.loss[i-1]<=0) if condition incomplete statement. -#*************************************************************** -# Tests/Examples for profit.loss distribution and corresponding VaR and ETL -# still needs to be completed. Around 4 in Backtest do not have examples. -# It still has to be completed. -#*************************************************************** -# Lopez Backtest: -# In Christofferson , excess.loss is defined as -profit.loss-VaR -# But in Lopez Backtest, profit.loss-VaR is used. It has to be checked. -#*************************************************************** \ No newline at end of file From noreply at r-forge.r-project.org Mon Jun 22 16:43:14 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 16:43:14 +0200 (CEST) Subject: [Returnanalytics-commits] r3709 - in pkg/Dowd: R man Message-ID: <20150622144314.EC36A18111F@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 16:43:14 +0200 (Mon, 22 Jun 2015) New Revision: 3709 Modified: pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd Log: Wrong function name corrected in example. Modified: pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R =================================================================== --- pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R 2015-06-22 14:37:08 UTC (rev 3708) +++ pkg/Dowd/R/AdjustedVarianceCovarianceVaR.R 2015-06-22 14:43:14 UTC (rev 3709) @@ -24,7 +24,7 @@ #' positions <- c(5,2,6,10) #' cl <- .95 #' hp <- 280 -#' AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +#' AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) #' #' @export AdjustedVarianceCovarianceVaR <- function(vc.matrix, mu, skew, kurtosis, positions, cl, hp){ Modified: pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd =================================================================== --- pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd 2015-06-22 14:37:08 UTC (rev 3708) +++ pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd 2015-06-22 14:43:14 UTC (rev 3709) @@ -33,7 +33,7 @@ positions <- c(5,2,6,10) cl <- .95 hp <- 280 - AdjustedNormalESHotsopts(vc.matrix, mu, skew, kurtosis, positions, cl, hp) + AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) } \author{ Dinesh Acharya From noreply at r-forge.r-project.org Mon Jun 22 17:09:36 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 17:09:36 +0200 (CEST) Subject: [Returnanalytics-commits] r3710 - pkg/Dowd/R Message-ID: <20150622150936.C331C186CF5@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 17:09:36 +0200 (Mon, 22 Jun 2015) New Revision: 3710 Modified: pkg/Dowd/R/BootstrapESConfInterval.R Log: Error in accessing element from list while using bootstrap corrected. Modified: pkg/Dowd/R/BootstrapESConfInterval.R =================================================================== --- pkg/Dowd/R/BootstrapESConfInterval.R 2015-06-22 14:43:14 UTC (rev 3709) +++ pkg/Dowd/R/BootstrapESConfInterval.R 2015-06-22 15:09:36 UTC (rev 3710) @@ -59,8 +59,8 @@ } # ES estimation - es <- bootstrap(losses.data, number.resamples, HSES, cl)[1] + es <- bootstrap(losses.data, number.resamples, HSES, cl)$thetastar y <- quantile(es, c(.05, .95)) return(y) -} \ No newline at end of file +} From noreply at r-forge.r-project.org Mon Jun 22 17:13:37 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 17:13:37 +0200 (CEST) Subject: [Returnanalytics-commits] r3711 - in pkg/Dowd: R man Message-ID: <20150622151337.828B9186752@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 17:13:37 +0200 (Mon, 22 Jun 2015) New Revision: 3711 Modified: pkg/Dowd/R/GParetoES.R pkg/Dowd/man/GParetoES.Rd Log: "randn" in Example corrected to "rnorm". Modified: pkg/Dowd/R/GParetoES.R =================================================================== --- pkg/Dowd/R/GParetoES.R 2015-06-22 15:09:36 UTC (rev 3710) +++ pkg/Dowd/R/GParetoES.R 2015-06-22 15:13:37 UTC (rev 3711) @@ -18,7 +18,7 @@ #' @examples #' #' # Computes ES assuming generalised Pareto for following parameters -#' Ra <- 5 * randn(100) +#' Ra <- 5 * rnorm(100) #' beta <- 1.2 #' zeta <- 1.6 #' threshold.prob <- .85 @@ -45,4 +45,4 @@ - 1))/(1 - zeta)+(beta - zeta * u) / (1 - zeta); return(y) -} \ No newline at end of file +} Modified: pkg/Dowd/man/GParetoES.Rd =================================================================== --- pkg/Dowd/man/GParetoES.Rd 2015-06-22 15:09:36 UTC (rev 3710) +++ pkg/Dowd/man/GParetoES.Rd 2015-06-22 15:13:37 UTC (rev 3711) @@ -25,7 +25,7 @@ } \examples{ # Computes ES assuming generalised Pareto for following parameters - Ra <- 5 * randn(100) + Ra <- 5 * rnorm(100) beta <- 1.2 zeta <- 1.6 threshold.prob <- .85 From noreply at r-forge.r-project.org Mon Jun 22 17:20:07 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 17:20:07 +0200 (CEST) Subject: [Returnanalytics-commits] r3712 - in pkg/Dowd: R man Message-ID: <20150622152007.E5617186752@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 17:20:07 +0200 (Mon, 22 Jun 2015) New Revision: 3712 Modified: pkg/Dowd/R/GParetoVaR.R pkg/Dowd/man/GParetoVaR.Rd Log: "randn" was corrected to "rnorm" in example. Modified: pkg/Dowd/R/GParetoVaR.R =================================================================== --- pkg/Dowd/R/GParetoVaR.R 2015-06-22 15:13:37 UTC (rev 3711) +++ pkg/Dowd/R/GParetoVaR.R 2015-06-22 15:20:07 UTC (rev 3712) @@ -20,7 +20,7 @@ #' @examples #' #' # Computes ES assuming generalised Pareto for following parameters -#' Ra <- 5 * randn(100) +#' Ra <- 5 * rnorm(100) #' beta <- 1.2 #' zeta <- 1.6 #' threshold.prob <- .85 Modified: pkg/Dowd/man/GParetoVaR.Rd =================================================================== --- pkg/Dowd/man/GParetoVaR.Rd 2015-06-22 15:13:37 UTC (rev 3711) +++ pkg/Dowd/man/GParetoVaR.Rd 2015-06-22 15:20:07 UTC (rev 3712) @@ -27,7 +27,7 @@ } \examples{ # Computes ES assuming generalised Pareto for following parameters - Ra <- 5 * randn(100) + Ra <- 5 * rnorm(100) beta <- 1.2 zeta <- 1.6 threshold.prob <- .85 From noreply at r-forge.r-project.org Mon Jun 22 17:28:14 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 17:28:14 +0200 (CEST) Subject: [Returnanalytics-commits] r3713 - in pkg/Dowd: R man Message-ID: <20150622152814.1B1B6186752@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 17:28:13 +0200 (Mon, 22 Jun 2015) New Revision: 3713 Modified: pkg/Dowd/R/GaussianCopulaVaR.R pkg/Dowd/man/GaussianCopulaVaR.Rd Log: Wrong function name in example corrected. Modified: pkg/Dowd/R/GaussianCopulaVaR.R =================================================================== --- pkg/Dowd/R/GaussianCopulaVaR.R 2015-06-22 15:20:07 UTC (rev 3712) +++ pkg/Dowd/R/GaussianCopulaVaR.R 2015-06-22 15:28:13 UTC (rev 3713) @@ -21,7 +21,7 @@ #' @examples #' #' # VaR using bivariate Gumbel for X and Y with given parameters: -#' GumbelCopulaVaR(2.3, 4.1, 1.2, 1.5, .6, .95) +#' GaussianCopulaVaR(2.3, 4.1, 1.2, 1.5, .6, 50, .95) #' #' @export GaussianCopulaVaR <- function(mu1, mu2, sigma1, sigma2, rho, @@ -71,4 +71,4 @@ cat("Var using bivariate gaussian copula: ", y, "\n") cat("Error in Copula VaR Estimate: ", analytical.variance.covariance.VaR-y) return(y) -} \ No newline at end of file +} Modified: pkg/Dowd/man/GaussianCopulaVaR.Rd =================================================================== --- pkg/Dowd/man/GaussianCopulaVaR.Rd 2015-06-22 15:20:07 UTC (rev 3712) +++ pkg/Dowd/man/GaussianCopulaVaR.Rd 2015-06-22 15:28:13 UTC (rev 3713) @@ -31,7 +31,7 @@ } \examples{ # VaR using bivariate Gumbel for X and Y with given parameters: - GumbelCopulaVaR(2.3, 4.1, 1.2, 1.5, .6, .95) + GaussianCopulaVaR(2.3, 4.1, 1.2, 1.5, .6, 50, .95) } \author{ Dinesh Acharya From noreply at r-forge.r-project.org Mon Jun 22 18:29:03 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 18:29:03 +0200 (CEST) Subject: [Returnanalytics-commits] r3714 - pkg/Dowd/R Message-ID: <20150622162903.869E6184426@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 18:29:03 +0200 (Mon, 22 Jun 2015) New Revision: 3714 Modified: pkg/Dowd/R/MEFPlot.R Log: Variable "mef" that was not initialized before was initialized. Modified: pkg/Dowd/R/MEFPlot.R =================================================================== --- pkg/Dowd/R/MEFPlot.R 2015-06-22 15:28:13 UTC (rev 3713) +++ pkg/Dowd/R/MEFPlot.R 2015-06-22 16:29:03 UTC (rev 3714) @@ -21,7 +21,7 @@ } u <- data n <- length(u) - mef <- + mef <- double(n-1) for (i in 1:n - 1) { data <- data[which(data > u[i])] mef[i] <- mean(data) - u[i] @@ -30,4 +30,4 @@ plot(u, mef, type = "l", xlab = "Threshold", ylab = "e(u)", main = "Empirical Mean Excess Function") -} \ No newline at end of file +} From noreply at r-forge.r-project.org Mon Jun 22 18:30:25 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 22 Jun 2015 18:30:25 +0200 (CEST) Subject: [Returnanalytics-commits] r3715 - in pkg/Dowd: R man Message-ID: <20150622163025.6B816184426@r-forge.r-project.org> Author: dacharya Date: 2015-06-22 18:30:25 +0200 (Mon, 22 Jun 2015) New Revision: 3715 Modified: pkg/Dowd/R/GaussianCopulaVaR.R pkg/Dowd/man/GaussianCopulaVaR.Rd Log: Example parameter slightly changed to change test time. Modified: pkg/Dowd/R/GaussianCopulaVaR.R =================================================================== --- pkg/Dowd/R/GaussianCopulaVaR.R 2015-06-22 16:29:03 UTC (rev 3714) +++ pkg/Dowd/R/GaussianCopulaVaR.R 2015-06-22 16:30:25 UTC (rev 3715) @@ -21,7 +21,7 @@ #' @examples #' #' # VaR using bivariate Gumbel for X and Y with given parameters: -#' GaussianCopulaVaR(2.3, 4.1, 1.2, 1.5, .6, 50, .95) +#' GaussianCopulaVaR(2.3, 4.1, 1.2, 1.5, .6, 10, .95) #' #' @export GaussianCopulaVaR <- function(mu1, mu2, sigma1, sigma2, rho, Modified: pkg/Dowd/man/GaussianCopulaVaR.Rd =================================================================== --- pkg/Dowd/man/GaussianCopulaVaR.Rd 2015-06-22 16:29:03 UTC (rev 3714) +++ pkg/Dowd/man/GaussianCopulaVaR.Rd 2015-06-22 16:30:25 UTC (rev 3715) @@ -31,7 +31,7 @@ } \examples{ # VaR using bivariate Gumbel for X and Y with given parameters: - GaussianCopulaVaR(2.3, 4.1, 1.2, 1.5, .6, 50, .95) + GaussianCopulaVaR(2.3, 4.1, 1.2, 1.5, .6, 10, .95) } \author{ Dinesh Acharya From noreply at r-forge.r-project.org Tue Jun 23 08:54:57 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 08:54:57 +0200 (CEST) Subject: [Returnanalytics-commits] r3716 - pkg/Meucci/demo Message-ID: <20150623065457.CD3FF183A0A@r-forge.r-project.org> Author: xavierv Date: 2015-06-23 08:54:57 +0200 (Tue, 23 Jun 2015) New Revision: 3716 Modified: pkg/Meucci/demo/HermiteGrid_CVaR_Recursion.R Log: - fixed HermiteGrid_CVaR_Recursion demo script Modified: pkg/Meucci/demo/HermiteGrid_CVaR_Recursion.R =================================================================== --- pkg/Meucci/demo/HermiteGrid_CVaR_Recursion.R 2015-06-22 16:30:25 UTC (rev 3715) +++ pkg/Meucci/demo/HermiteGrid_CVaR_Recursion.R 2015-06-23 06:54:57 UTC (rev 3716) @@ -4,6 +4,8 @@ # The most recent version of this code is available at # MATLAB Central - File Exchange +data(gqhx) + # Prior market model (normal) on grid emptyMatrix <- matrix(nrow = 0, ncol = 0) market.mu <- 0.0 @@ -44,24 +46,30 @@ posteriorEntropy <- EntropyProg(p, t(idx), as.matrix(0.05), rbind(rep(1, J), t(idx * X)), rbind(1, 0.05 * view.CVaR95)) p_[,i] <- posteriorEntropy$p_ - KLdiv[i] <- posteriorEntropy$optimizationPerformance$ml + # when maximizing, objective turns negative. Bringing it back to normal + KLdiv[i] <- -posteriorEntropy$optimizationPerformance$ml } # Display results -plot(s_, KLdiv) +dev.new() +par(mfrow = c(2,1)) +plot(s_, KLdiv, "l", col = "blue", xlab = "s", ylab = "KL divergence") dummy <- min(KLdiv) idxMin <- which.min(KLdiv) -plot(s_[idxMin], KLdiv[idxMin]) +lines(s_[idxMin], KLdiv[idxMin], type = "b") tmp <- p_[, idxMin] tmp <- tmp / sum(tmp) -plot(X, tmp) +plot(X, tmp, type = "l", col = "blue", lwd = 1.5, xlab="", + ylab = "", ylim = c(0, 0.006)) x <- seq(min(X), max(X), len = J) tmp <- market.pdf(x) tmp <- tmp / sum(tmp) -plot(x, tmp) -plot(market.CVaR95, 0) -plot(view.CVaR95, 0) +lines(x, tmp, type = "l", col = "red", lwd = 1.5) +lines(market.CVaR95, 0.0, type = "p", pch = 17, col = "blue") +lines(view.CVaR95, 0.0, type = "p", pch = 17, col = "red") +legend("topright", 1.9, c("Prior", "Posterior"), + col = c("blue", "red"), lty = 1) # Entropy posterior from extreme view on CVaR: Newton Raphson approach @@ -72,7 +80,7 @@ s[1] <- sum(idx) posteriorEntropy <- EntropyProg(p, t(idx), as.matrix(0.05), rbind(rep(1, J), t(idx * X)), rbind(1, 0.05 * view.CVaR95)) -KLdiv <- as.matrix(posteriorEntropy$optimizationPerformance$ml) +KLdiv <- as.matrix(-posteriorEntropy$optimizationPerformance$ml) p_ <- posteriorEntropy$p_ # iterate @@ -121,7 +129,8 @@ # [tmp.p_, tmp.KLdiv] = optimizeEntropy(p, [idx'; (idx .* X)'], # [0.05; 0.05 * view.CVaR95], [ones(1, J); X'], [1; view.mu]); p_ <- cbind(p_, tempEntropy$p_) - KLdiv <- rbind(KLdiv, tempEntropy$optimizationPerformance$ml) #ok<*AGROW> + # when maximizing, objective turns negative. Bringing it back to normal + KLdiv <- rbind(KLdiv, -tempEntropy$optimizationPerformance$ml) # if change in KLdiv less than one percent, stop if(abs((KLdiv[i] - KLdiv[i - 1]) / KLdiv[i - 1]) < 0.01) @@ -131,20 +140,27 @@ # Display results N <- length(s) - -plot(1:N, KLdiv) +dev.new() +par(mfrow = c(2,1)) +plot(1:N, KLdiv, type = "l", xlab = "s", ylab = "KL divergence") +lines(repmat(1:N, N, 1), repmat(t(KLdiv), N, 1), type = "p") x <- seq(min(X), max(X), len = J) tmp <- market.pdf(x) tmp <- tmp / sum(tmp) -plot(t(X), tmp) -plot(t(X), p_[, ncol(p_)]) -plot(market.CVaR95, 0.0) -plot(view.CVaR95, 0.0) +plot(t(X), tmp, type = "l", col = "blue", lwd = 1.5, xlab="", + ylab = "", ylim = c(0, 0.006)) +lines(t(X), p_[, ncol(p_)], type = "l", col = "red", lwd = 1.5) +lines(market.CVaR95, 0.0, type = "p", pch = 17, col = "blue") +lines(view.CVaR95, 0.0, type = "p", pch = 17, col = "red") +legend("topright", 1.9, c("Prior", "Posterior"), + col = c("blue", "red"), lty = 1) # zoom here -plot(t(X), tmp) -plot(t(X), p_[, 1]) -plot(t(X), p_[, 2]) -plot(t(X), p_[, ncol(p_)]) -plot(market.CVaR95, 0) -plot(view.CVaR95, 0) +dev.new() +plot(t(X), tmp, "l", col = "blue", xlim = c(-4, -2), ylim = c(0, 0.001), + xlab="", ylab = "") +lines(t(X), p_[, 1], col = "magenta") +lines(t(X), p_[, 2], col = "green") +lines(t(X), p_[, ncol(p_)], col = "red") +lines(market.CVaR95, 0.0, type = "p", pch = 17, col = "blue") +lines(view.CVaR95, 0.0, type = "p", pch = 17, col = "red") From noreply at r-forge.r-project.org Tue Jun 23 10:26:44 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 10:26:44 +0200 (CEST) Subject: [Returnanalytics-commits] r3717 - in pkg/Meucci: R demo man Message-ID: <20150623082644.39ADF186F26@r-forge.r-project.org> Author: xavierv Date: 2015-06-23 10:26:43 +0200 (Tue, 23 Jun 2015) New Revision: 3717 Modified: pkg/Meucci/R/EntropyProg.R pkg/Meucci/demo/HermiteGrid_demo.R pkg/Meucci/man/pHist.Rd Log: - fixed HermiteGrid_demo demo script Modified: pkg/Meucci/R/EntropyProg.R =================================================================== --- pkg/Meucci/R/EntropyProg.R 2015-06-23 06:54:57 UTC (rev 3716) +++ pkg/Meucci/R/EntropyProg.R 2015-06-23 08:26:43 UTC (rev 3717) @@ -301,6 +301,9 @@ #' @param nBins expected number of Bins the data set is to be broken down into #' @param freq boolean variable to indicate whether the graphic is a #' representation of frequencies +#' @param main title for the plot +#' @param xlim limits for the x-axis +#' @param ylim limits for the y-axis #' #' @return a list with #' f the frequency for each midpoint @@ -314,7 +317,9 @@ #' #' @export -PHist <- function(X, p, nBins, freq = FALSE) { +PHist <- function(X, p, nBins, freq = FALSE, + main = "Portfolio return distribution", + xlim = NULL, ylim = NULL) { if (length(match.call()) < 3) { J <- dim(X)[1] @@ -336,7 +341,7 @@ f <- np / D } - plot(x, f, type = "h", main = "Portfolio return distribution") + plot(x, f, type = "h", main = main, xlim = xlim, ylim = ylim) return(list(f = f, x = x)) } Modified: pkg/Meucci/demo/HermiteGrid_demo.R =================================================================== --- pkg/Meucci/demo/HermiteGrid_demo.R 2015-06-23 06:54:57 UTC (rev 3716) +++ pkg/Meucci/demo/HermiteGrid_demo.R 2015-06-23 08:26:43 UTC (rev 3717) @@ -14,18 +14,19 @@ ################################################################################ # analytical (normal) prior emptyMatrix <- matrix(nrow = 0, ncol = 0) -market.mu <- 0.0 -market.sig2 <- 1.0 -market.pdf <- function(x) dnorm(x, mean = market.mu, sd = sqrt(market.sig2)) -market.cdf <- function(x) pnorm(x, mean = market.mu, sd = sqrt(market.sig2)) -market.rnd <- function(x) rnorm(x, mean = market.mu, sd = sqrt(market.sig2)) -market.inv <- function(x) qnorm(x, mean = market.mu, sd = sqrt(market.sig2)) +market <- list() +market$mu <- 0.0 +market$sig2 <- 1.0 +market$pdf <- function(x) dnorm(x, mean = market$mu, sd = sqrt(market$sig2)) +market$cdf <- function(x) pnorm(x, mean = market$mu, sd = sqrt(market$sig2)) +market$rnd <- function(x) rnorm(x, mean = market$mu, sd = sqrt(market$sig2)) +market$inv <- function(x) qnorm(x, mean = market$mu, sd = sqrt(market$sig2)) # numerical (Monte Carlo) prior monteCarlo <- emptyMatrix -monteCarlo.J <- 100000 -monteCarlo.X <- market.rnd(monteCarlo.J) -monteCarlo.p <- normalizeProb(1 / monteCarlo.J * ones(monteCarlo.J, 1)) +monteCarlo$J <- 100000 +monteCarlo$X <- market$rnd(monteCarlo$J) +monteCarlo$p <- normalizeProb(1 / monteCarlo$J * ones(monteCarlo$J, 1)) # numerical (Gauss-Hermite grid) prior ghqMesh <- emptyMatrix @@ -33,56 +34,67 @@ # rescale GH zeros so they belong to [0,1] tmp <- (ghqx - min(ghqx)) / (max(ghqx) - min(ghqx)) epsilon <- 1e-10 -Lower <- market.inv(epsilon) -Upper <- market.inv(1 - epsilon) -ghqMesh.X <- Lower + tmp * (Upper - Lower) # rescale mesh +Lower <- market$inv(epsilon) +Upper <- market$inv(1 - epsilon) +ghqMesh$X <- Lower + tmp * (Upper - Lower) # rescale mesh -p <- integrateSubIntervals(ghqMesh.X, market.cdf) -ghqMesh.p <- normalizeProb(p) -ghqMesh.J <- nrow(ghqMesh.X) +p <- integrateSubIntervals(ghqMesh$X, market$cdf) +ghqMesh$p <- normalizeProb(p) +ghqMesh$J <- nrow(ghqMesh$X) ################################################################################ # Entropy posterior from extreme view on expectation ################################################################################ # view of the analyst view <- emptyMatrix -view.mu <- -3.0 +view$mu <- -3.0 # analytical (known since normal model has analytical solution) truePosterior <- emptyMatrix -truePosterior <- Prior2Posterior(market.mu, 1, view.mu, market.sig2, 0) -truePosterior$pdf <- function(x) dnorm(x, truePosterior.mu, - sqrt(truePosterior.sig2)) +truePosterior <- Prior2Posterior(market$mu, 1, view$mu, market$sig2, 0) +truePosterior$pdf <- function(x) dnorm(x, truePosterior$M_, + sqrt(truePosterior$S_)) # numerical (Monte Carlo) -Aeq <- rbind(ones(1, monteCarlo.J), t(monteCarlo.X)) -beq <- rbind(1, view.mu) -monteCarloOptimResult <- EntropyProg(monteCarlo.p, emptyMatrix, emptyMatrix, Aeq, +Aeq <- rbind(ones(1, monteCarlo$J), t(monteCarlo$X)) +beq <- rbind(1, view$mu) +monteCarloOptimResult <- EntropyProg(monteCarlo$p, emptyMatrix, emptyMatrix, Aeq, beq) -monteCarlo.p_ <- monteCarloOptimResult$p_ -monteCarlo.KLdiv <- monteCarloOptimResult$optimizationPerformance$ml +monteCarlo$p_ <- monteCarloOptimResult$p_ +monteCarlo$KLdiv <- monteCarloOptimResult$optimizationPerformance$ml # numerical (Gaussian-Hermite grid) -Aeq <- rbind(ones(1, ghqMesh.J), t(ghqMesh.X)) -beq <- rbind(1, view.mu) -ghqMeshOptimResult <- EntropyProg(ghqMesh.p, emptyMatrix, emptyMatrix, Aeq, beq) +Aeq <- rbind(ones(1, ghqMesh$J), t(ghqMesh$X)) +beq <- rbind(1, view$mu) +ghqMeshOptimResult <- EntropyProg(ghqMesh$p, emptyMatrix, emptyMatrix, Aeq, beq) -ghqMesh.p_ <- ghqMeshOptimResult$p_ -ghqMesh.KLdiv <- ghqMeshOptimResult$optimizationPerformance$ml +ghqMesh$p_ <- ghqMeshOptimResult$p_ +ghqMesh$KLdiv <- ghqMeshOptimResult$optimizationPerformance$ml ################################################################################ # Plots ################################################################################ -xmin <- min(ghqMesh.X) -xmax <- max(ghqMesh.X) +xmin <- min(ghqMesh$X) +xmax <- max(ghqMesh$X) ymax <- 1.0 -xmesh <- t(linspace(xmin, xmax, ghqMesh.J)) +xmesh <- t(linspace(xmin, xmax, ghqMesh$J)) # Monte Carlo -plotDataMC <- PHist(monteCarlo.X, monteCarlo.p_, 50) -lines(plotDataMC$x, plotDataMC$f, type = "l", col = "red") +dev.new() +plotDataMC <- PHist(monteCarlo$X, monteCarlo$p_, 50, main = "Monte Carlo", + xlim = c(xmin, xmax), ylim = c(0, ymax)) +lines(xmesh, market$pdf(xmesh), type = "l", col = "blue") +lines(xmesh, truePosterior$pdf(xmesh), type = "l", col = "red") +lines(0.0, 0.0, type = "p", pch = 17, col = "blue") +lines(view.mu, 0.0, type = "p", pch = 17, col = "red") # Gauss Hermite Grid -plotDataGHQ <- PHist(data.matrix(ghqMesh.X), ghqMesh.p_, 50) -lines(plotDataGHQ$x, plotDataGHQ$f, type = "l", col = "red") +dev.new() +plotDataGHQ <- PHist(data.matrix(ghqMesh$X), ghqMesh$p_, 50, + main = "Gauss-Hermite grid", + xlim = c(xmin, xmax), ylim = c(0, ymax)) +lines(xmesh, market$pdf(xmesh), type = "l", col = "blue") +lines(xmesh, truePosterior$pdf(xmesh), type = "l", col = "red") +lines(0.0, 0.0, type = "p", pch = 17, col = "blue") +lines(view$mu, 0.0, type = "p", pch = 17, col = "red") Modified: pkg/Meucci/man/pHist.Rd =================================================================== --- pkg/Meucci/man/pHist.Rd 2015-06-23 06:54:57 UTC (rev 3716) +++ pkg/Meucci/man/pHist.Rd 2015-06-23 08:26:43 UTC (rev 3717) @@ -4,7 +4,8 @@ \alias{PHist} \title{Generates histogram} \usage{ -PHist(X, p, nBins, freq = FALSE) +PHist(X, p, nBins, freq = FALSE, main = "Portfolio return distribution", + xlim = NULL, ylim = NULL) } \arguments{ \item{X}{vector containing the data points} @@ -15,7 +16,13 @@ \item{nBins}{expected number of Bins the data set is to be broken down into} \item{freq}{boolean variable to indicate whether the graphic is a - representation of frequencies} +representation of frequencies} + +\item{main}{title for the plot} + +\item{xlim}{limits for the x-axis} + +\item{ylim}{limits for the y-axis} } \value{ a list with From noreply at r-forge.r-project.org Tue Jun 23 11:22:58 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 11:22:58 +0200 (CEST) Subject: [Returnanalytics-commits] r3718 - in pkg/Dowd: R man Message-ID: <20150623092258.3107F186999@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 11:22:57 +0200 (Tue, 23 Jun 2015) New Revision: 3718 Modified: pkg/Dowd/R/MEFPlot.R pkg/Dowd/man/MEFPlot.Rd Log: Error in loop corrected from 1:n-1 to 1:(n-1). Modified: pkg/Dowd/R/MEFPlot.R =================================================================== --- pkg/Dowd/R/MEFPlot.R 2015-06-23 08:26:43 UTC (rev 3717) +++ pkg/Dowd/R/MEFPlot.R 2015-06-23 09:22:57 UTC (rev 3718) @@ -1,33 +1,34 @@ -#' Mean Excess Function Plot -#' -#' Plots mean-excess function values of the data set. -#' -#' @param Ra Vector data -#' -#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. -#' -#' @author Dinesh Acharya -#' @examples -#' -#' # Plots -#' Ra <- rnorm(1000) -#' MEFPlot(Ra) -#' -#' @export -MEFPlot <- function(Ra){ - data <- as.vector(Ra) - if (!is.vector(data)) { - stop("Input should be a vector data.") - } - u <- data - n <- length(u) - mef <- double(n-1) - for (i in 1:n - 1) { - data <- data[which(data > u[i])] - mef[i] <- mean(data) - u[i] - } - u <- u[!u==max(u)] - plot(u, mef, type = "l", xlab = "Threshold", ylab = "e(u)", - main = "Empirical Mean Excess Function") - -} +#' Mean Excess Function Plot +#' +#' Plots mean-excess function values of the data set. +#' +#' @param Ra Vector data +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots mean-excess function values +#' Ra <- rnorm(1000) +#' MEFPlot(Ra) +#' +#' @export +MEFPlot <- function(Ra){ + data <- as.vector(Ra) + if (!is.vector(data)) { + stop("Input should be a vector data.") + } + data <- sort(data) + u <- data + n <- length(u) + mef <- double(n-1) + for (i in 1:(n-1)) { + data <- data[which(data > u[i])] + mef[i] <- mean(data) - u[i] + } + u <- u[!u == max(u)] + plot(u, mef, type = "l", xlab = "Threshold", ylab = "e(u)", + main = "Empirical Mean Excess Function") + +} Modified: pkg/Dowd/man/MEFPlot.Rd =================================================================== --- pkg/Dowd/man/MEFPlot.Rd 2015-06-23 08:26:43 UTC (rev 3717) +++ pkg/Dowd/man/MEFPlot.Rd 2015-06-23 09:22:57 UTC (rev 3718) @@ -13,7 +13,7 @@ Plots mean-excess function values of the data set. } \examples{ -# Plots +# Plots mean-excess function values Ra <- rnorm(1000) MEFPlot(Ra) } From noreply at r-forge.r-project.org Tue Jun 23 11:23:49 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 11:23:49 +0200 (CEST) Subject: [Returnanalytics-commits] r3719 - in pkg/Dowd: R man Message-ID: <20150623092350.017D5186999@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 11:23:48 +0200 (Tue, 23 Jun 2015) New Revision: 3719 Modified: pkg/Dowd/R/ProductCopulaVaR.R pkg/Dowd/man/ProductCopulaVaR.Rd Log: Example changed so that the result lies in assumed region. Missing return was also added. Modified: pkg/Dowd/R/ProductCopulaVaR.R =================================================================== --- pkg/Dowd/R/ProductCopulaVaR.R 2015-06-23 09:22:57 UTC (rev 3718) +++ pkg/Dowd/R/ProductCopulaVaR.R 2015-06-23 09:23:48 UTC (rev 3719) @@ -1,63 +1,64 @@ -#' Bivariate Product Copule VaR -#' -#' Derives VaR using bivariate Product or logistic copula with specified inputs -#' for normal marginals. -#' -#' @param mu1 Mean of Profit/Loss on first position -#' @param mu2 Mean of Profit/Loss on second position -#' @param sigma1 Standard Deviation of Profit/Loss on first position -#' @param sigma2 Standard Deviation of Profit/Loss on second position -#' @param cl VaR onfidece level -#' @return Copula based VaR -#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. -#' -#' Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering -#' News, 2004. -#' -#' -#' @author Dinesh Acharya -#' @examples -#' -#' # VaR using bivariate Product for X and Y with given parameters: -#' ProductCopulaVaR(2.3, 4.1, 1.2, 1.5, .95) -#' -#' @export -ProductCopulaVaR <- function(mu1, mu2, sigma1, sigma2, cl){ - - p <- 1 - cl # p is tail probability or cdf - - # Compute portfolio mean and sigma (NB: These are used here to help compute - # initial bounds automatically) - portfolio.mu <- mu1 + mu2 - portfolio.variance <- sigma1^2+sigma2^2 - portfolio.sigma <- sqrt(portfolio.variance) - - # Specify bounds arbitrarily (NB: Would need to change manually if these were - # inappropriate) - L <- -portfolio.mu - 5 * portfolio.sigma - fL <- CdfOfSumUsingProductCopula(L, mu1, mu2, sigma1, sigma2) - p - sign.fL <- sign(fL) - U <- -portfolio.mu + 5 * portfolio.sigma - fU <- CdfOfSumUsingProductCopula(U, mu1, mu2, sigma1, sigma2) - p - sign.fU <- sign(fU) - if (sign.fL == sign.fU){ - stop("Assumed bounds do not include answer") - } - - # Bisection Algorithm - tol <- 0.0001 # Tolerance level (NM: change manually if desired) - while (U - L > tol){ - x <- (L + U) / 2 # Bisection carried out in terms of P/L quantiles or minus VaR - cum.prob <- CdfOfSumUsingProductCopula(x, mu1, mu2, sigma1, sigma2) - fx <- cum.prob - p - if (sign(fx) == sign(fL)){ - L <- x - fL <- fx - } else { - U <- x - fU <- fx - } - } - y <- -x # VaR is negative of terminal x-value or P/L quantile - -} \ No newline at end of file +#' Bivariate Product Copule VaR +#' +#' Derives VaR using bivariate Product or logistic copula with specified inputs +#' for normal marginals. +#' +#' @param mu1 Mean of Profit/Loss on first position +#' @param mu2 Mean of Profit/Loss on second position +#' @param sigma1 Standard Deviation of Profit/Loss on first position +#' @param sigma2 Standard Deviation of Profit/Loss on second position +#' @param cl VaR onfidece level +#' @return Copula based VaR +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Dowd, K. and Fackler, P. Estimating VaR with copulas. Financial Engineering +#' News, 2004. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # VaR using bivariate Product for X and Y with given parameters: +#' ProductCopulaVaR(.9, 2.1, 1.2, 1.5, .95) +#' +#' @export +ProductCopulaVaR <- function(mu1, mu2, sigma1, sigma2, cl){ + + p <- 1 - cl # p is tail probability or cdf + + # Compute portfolio mean and sigma (NB: These are used here to help compute + # initial bounds automatically) + portfolio.mu <- mu1 + mu2 + portfolio.variance <- sigma1^2+sigma2^2 + portfolio.sigma <- sqrt(portfolio.variance) + + # Specify bounds arbitrarily (NB: Would need to change manually if these were + # inappropriate) + L <- -portfolio.mu - 5 * portfolio.sigma + fL <- CdfOfSumUsingProductCopula(L, mu1, mu2, sigma1, sigma2) - p + sign.fL <- sign(fL) + U <- -portfolio.mu + 5 * portfolio.sigma + fU <- CdfOfSumUsingProductCopula(U, mu1, mu2, sigma1, sigma2) - p + sign.fU <- sign(fU) + if (sign.fL == sign.fU){ + stop("Assumed bounds do not include answer") + } + + # Bisection Algorithm + tol <- 0.0001 # Tolerance level (NM: change manually if desired) + while (U - L > tol){ + x <- (L + U) / 2 # Bisection carried out in terms of P/L quantiles or minus VaR + cum.prob <- CdfOfSumUsingProductCopula(x, mu1, mu2, sigma1, sigma2) + fx <- cum.prob - p + if (sign(fx) == sign(fL)){ + L <- x + fL <- fx + } else { + U <- x + fU <- fx + } + } + y <- -x # VaR is negative of terminal x-value or P/L quantile + + return(y) +} Modified: pkg/Dowd/man/ProductCopulaVaR.Rd =================================================================== --- pkg/Dowd/man/ProductCopulaVaR.Rd 2015-06-23 09:22:57 UTC (rev 3718) +++ pkg/Dowd/man/ProductCopulaVaR.Rd 2015-06-23 09:23:48 UTC (rev 3719) @@ -26,7 +26,7 @@ } \examples{ # VaR using bivariate Product for X and Y with given parameters: - ProductCopulaVaR(2.3, 4.1, 1.2, 1.5, .95) + ProductCopulaVaR(.9, 2.1, 1.2, 1.5, .95) } \author{ Dinesh Acharya From noreply at r-forge.r-project.org Tue Jun 23 21:52:58 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 21:52:58 +0200 (CEST) Subject: [Returnanalytics-commits] r3720 - pkg/Dowd/man Message-ID: <20150623195258.7614D187A23@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 21:52:58 +0200 (Tue, 23 Jun 2015) New Revision: 3720 Modified: pkg/Dowd/man/ADTestStat.Rd pkg/Dowd/man/AdjustedNormalESHotspots.Rd pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd pkg/Dowd/man/BinomialBacktest.Rd pkg/Dowd/man/BlancoIhleBacktest.Rd pkg/Dowd/man/BootstrapES.Rd pkg/Dowd/man/BootstrapESConfInterval.Rd pkg/Dowd/man/BootstrapESFigure.Rd pkg/Dowd/man/BootstrapVaR.Rd pkg/Dowd/man/BootstrapVaRConfInterval.Rd pkg/Dowd/man/BootstrapVaRFigure.Rd pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd pkg/Dowd/man/CdfOfSumUsingGumbelCopula.Rd pkg/Dowd/man/CdfOfSumUsingProductCopula.Rd pkg/Dowd/man/ChristoffersenBacktestForIndependence.Rd pkg/Dowd/man/ChristoffersenBacktestForUnconditionalCoverage.Rd pkg/Dowd/man/CornishFisherES.Rd pkg/Dowd/man/CornishFisherVaR.Rd pkg/Dowd/man/FrechetES.Rd pkg/Dowd/man/FrechetESPlot2DCl.Rd pkg/Dowd/man/FrechetVaR.Rd pkg/Dowd/man/FrechetVaRPlot2DCl.Rd pkg/Dowd/man/GParetoES.Rd pkg/Dowd/man/GParetoMEFPlot.Rd pkg/Dowd/man/GParetoMultipleMEFPlot.Rd pkg/Dowd/man/GParetoVaR.Rd pkg/Dowd/man/GaussianCopulaVaR.Rd pkg/Dowd/man/GumbelCopulaVaR.Rd pkg/Dowd/man/GumbelES.Rd pkg/Dowd/man/GumbelESPlot2DCl.Rd pkg/Dowd/man/GumbelVaR.Rd pkg/Dowd/man/GumbelVaRPlot2DCl.Rd pkg/Dowd/man/HSES.Rd pkg/Dowd/man/HSVaR.Rd pkg/Dowd/man/HSVaRDFPerc.Rd pkg/Dowd/man/HSVaRFigure.Rd pkg/Dowd/man/HillEstimator.Rd pkg/Dowd/man/HillPlot.Rd pkg/Dowd/man/HillQuantileEstimator.Rd pkg/Dowd/man/JarqueBeraBacktest.Rd pkg/Dowd/man/KSTestStat.Rd pkg/Dowd/man/KuiperTestStat.Rd pkg/Dowd/man/LopezBacktest.Rd pkg/Dowd/man/MEFPlot.Rd pkg/Dowd/man/NormalQQPlot.Rd pkg/Dowd/man/PickandsEstimator.Rd pkg/Dowd/man/PickandsPlot.Rd pkg/Dowd/man/ProductCopulaVaR.Rd pkg/Dowd/man/TQQPlot.Rd Log: Update from roxygen2 version 4.1.0 to 4.1.1. Modified: pkg/Dowd/man/ADTestStat.Rd =================================================================== --- pkg/Dowd/man/ADTestStat.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/ADTestStat.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,45 +1,45 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/ADTestStat.R -\name{ADTestStat} -\alias{ADTestStat} -\title{Plots cumulative density for AD test and computes confidence -interval for AD test stat.} -\usage{ -ADTestStat(number.trials, sample.size, confidence.interval) -} -\arguments{ -\item{number.trials}{Number of trials} - -\item{sample.size}{Sample size} - -\item{confidence.interval}{Confidence Interval} -} -\value{ -Confidence Interval for AD test statistic -} -\description{ -Anderson-Darling(AD) test can be used to carry out distribution equality test and is -similar to Kolmogorov-Smirnov test. AD test statistic is defined as: -\deqn{A^2=n\int_{-\infty}^{\infty}\frac{[\hat{F}(x)-F(x)]^2}{F(x)[1-F(x)]}dF(x)} -which is equivalent to -\deqn{=-n-\frac{1}{n}\sum_{i=1}^n(2i-1)[\ln F(X_i)+\ln(1-F(X_{n+1-i}))]} -} -\examples{ -# Probability that the VaR model is correct for 3 failures, 100 number - # observations and 95\% confidence level - ADTestStat(1000, 100, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. - -Anderson, T.W. and Darling, D.A. Asymptotic Theory of Certain Goodness of -Fit Criteria Based on Stochastic Processes, The Annals of Mathematical -Statistics, 23(2), 1952, p. 193-212. - -Kvam, P.H. and Vidakovic, B. Nonparametric Statistics with Applications to -Science and Engineering, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/ADTestStat.R +\name{ADTestStat} +\alias{ADTestStat} +\title{Plots cumulative density for AD test and computes confidence +interval for AD test stat.} +\usage{ +ADTestStat(number.trials, sample.size, confidence.interval) +} +\arguments{ +\item{number.trials}{Number of trials} + +\item{sample.size}{Sample size} + +\item{confidence.interval}{Confidence Interval} +} +\value{ +Confidence Interval for AD test statistic +} +\description{ +Anderson-Darling(AD) test can be used to carry out distribution equality test and is +similar to Kolmogorov-Smirnov test. AD test statistic is defined as: +\deqn{A^2=n\int_{-\infty}^{\infty}\frac{[\hat{F}(x)-F(x)]^2}{F(x)[1-F(x)]}dF(x)} +which is equivalent to +\deqn{=-n-\frac{1}{n}\sum_{i=1}^n(2i-1)[\ln F(X_i)+\ln(1-F(X_{n+1-i}))]} +} +\examples{ +# Probability that the VaR model is correct for 3 failures, 100 number + # observations and 95\% confidence level + ADTestStat(1000, 100, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Anderson, T.W. and Darling, D.A. Asymptotic Theory of Certain Goodness of +Fit Criteria Based on Stochastic Processes, The Annals of Mathematical +Statistics, 23(2), 1952, p. 193-212. + +Kvam, P.H. and Vidakovic, B. Nonparametric Statistics with Applications to +Science and Engineering, Wiley, 2007. +} + Modified: pkg/Dowd/man/AdjustedNormalESHotspots.Rd =================================================================== --- pkg/Dowd/man/AdjustedNormalESHotspots.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/AdjustedNormalESHotspots.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,46 +1,46 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/AdjustedNormalESHotspots.R -\name{AdjustedNormalESHotspots} -\alias{AdjustedNormalESHotspots} -\title{Hotspots for ES adjusted by Cornish-Fisher correction} -\usage{ -AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\arguments{ -\item{vc.matrix}{Variance covariance matrix for returns} - -\item{mu}{Vector of expected position returns} - -\item{skew}{Return skew} - -\item{kurtosis}{Return kurtosis} - -\item{positions}{Vector of positions} - -\item{cl}{Confidence level and is scalar} - -\item{hp}{Holding period and is scalar} -} -\description{ -Estimates the ES hotspots (or vector of incremental ESs) for a -portfolio with portfolio return adjusted for non-normality by Cornish-Fisher -corerction, for specified confidence level and holding period. -} -\examples{ -# Hotspots for ES for randomly generated portfolio - vc.matrix <- matrix(rnorm(16),4,4) - mu <- rnorm(4) - skew <- .5 - kurtosis <- 1.2 - positions <- c(5,2,6,10) - cl <- .95 - hp <- 280 - AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AdjustedNormalESHotspots.R +\name{AdjustedNormalESHotspots} +\alias{AdjustedNormalESHotspots} +\title{Hotspots for ES adjusted by Cornish-Fisher correction} +\usage{ +AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Return skew} + +\item{kurtosis}{Return kurtosis} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar} +} +\description{ +Estimates the ES hotspots (or vector of incremental ESs) for a +portfolio with portfolio return adjusted for non-normality by Cornish-Fisher +corerction, for specified confidence level and holding period. +} +\examples{ +# Hotspots for ES for randomly generated portfolio + vc.matrix <- matrix(rnorm(16),4,4) + mu <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,10) + cl <- .95 + hp <- 280 + AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd =================================================================== --- pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,46 +1,46 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/AdjustedNormalVaRHotspots.R -\name{AdjustedNormalVaRHotspots} -\alias{AdjustedNormalVaRHotspots} -\title{Hotspots for VaR adjusted by Cornish-Fisher correction} -\usage{ -AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\arguments{ -\item{vc.matrix}{Variance covariance matrix for returns} - -\item{mu}{Vector of expected position returns} - -\item{skew}{Return skew} - -\item{kurtosis}{Return kurtosis} - -\item{positions}{Vector of positions} - -\item{cl}{Confidence level and is scalar} - -\item{hp}{Holding period and is scalar} -} -\description{ -Estimates the VaR hotspots (or vector of incremental VaRs) for a -portfolio with portfolio return adjusted for non-normality by Cornish-Fisher -corerction, for specified confidence level and holding period. -} -\examples{ -# Hotspots for ES for randomly generated portfolio - vc.matrix <- matrix(rnorm(16),4,4) - mu <- rnorm(4) - skew <- .5 - kurtosis <- 1.2 - positions <- c(5,2,6,10) - cl <- .95 - hp <- 280 - AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AdjustedNormalVaRHotspots.R +\name{AdjustedNormalVaRHotspots} +\alias{AdjustedNormalVaRHotspots} +\title{Hotspots for VaR adjusted by Cornish-Fisher correction} +\usage{ +AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Return skew} + +\item{kurtosis}{Return kurtosis} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar} +} +\description{ +Estimates the VaR hotspots (or vector of incremental VaRs) for a +portfolio with portfolio return adjusted for non-normality by Cornish-Fisher +corerction, for specified confidence level and holding period. +} +\examples{ +# Hotspots for ES for randomly generated portfolio + vc.matrix <- matrix(rnorm(16),4,4) + mu <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,10) + cl <- .95 + hp <- 280 + AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd =================================================================== --- pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,46 +1,46 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/AdjustedVarianceCovarianceES.R -\name{AdjustedVarianceCovarianceES} -\alias{AdjustedVarianceCovarianceES} -\title{Cornish-Fisher adjusted Variance-Covariance ES} -\usage{ -AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\arguments{ -\item{vc.matrix}{Variance covariance matrix for returns} - -\item{mu}{Vector of expected position returns} - -\item{skew}{Return skew} - -\item{kurtosis}{Return kurtosis} - -\item{positions}{Vector of positions} - -\item{cl}{Confidence level and is scalar} - -\item{hp}{Holding period and is scalar} -} -\description{ -Function estimates the Variance-Covariance ES of a multi-asset -portfolio using the Cornish - Fisher adjustment for portfolio return -non-normality, for specified confidence level and holding period. -} -\examples{ -# Variance-covariance ES for randomly generated portfolio - vc.matrix <- matrix(rnorm(16), 4, 4) - mu <- rnorm(4) - skew <- .5 - kurtosis <- 1.2 - positions <- c(5, 2, 6, 10) - cl <- .95 - hp <- 280 - AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AdjustedVarianceCovarianceES.R +\name{AdjustedVarianceCovarianceES} +\alias{AdjustedVarianceCovarianceES} +\title{Cornish-Fisher adjusted Variance-Covariance ES} +\usage{ +AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Return skew} + +\item{kurtosis}{Return kurtosis} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar} +} +\description{ +Function estimates the Variance-Covariance ES of a multi-asset +portfolio using the Cornish - Fisher adjustment for portfolio return +non-normality, for specified confidence level and holding period. +} +\examples{ +# Variance-covariance ES for randomly generated portfolio + vc.matrix <- matrix(rnorm(16), 4, 4) + mu <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5, 2, 6, 10) + cl <- .95 + hp <- 280 + AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd =================================================================== --- pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,44 +1,44 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/AdjustedVarianceCovarianceVaR.R -\name{AdjustedVarianceCovarianceVaR} -\alias{AdjustedVarianceCovarianceVaR} -\title{Cornish-Fisher adjusted variance-covariance VaR} -\usage{ -AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\arguments{ -\item{vc.matrix}{Assumed variance covariance matrix for returns} - -\item{mu}{Vector of expected position returns} - -\item{skew}{Portfolio return skewness} - -\item{kurtosis}{Portfolio return kurtosis} - -\item{positions}{Vector of positions} - -\item{cl}{Confidence level and is scalar or vector} - -\item{hp}{Holding period and is scalar or vector} -} -\description{ -Estimates the variance-covariance VaR of a multi-asset portfolio using the Cornish-Fisher adjustment for portfolio-return non-normality, for specified confidence level and holding period. -} -\examples{ -# Variance-covariance for randomly generated portfolio - vc.matrix <- matrix(rnorm(16),4,4) - mu <- rnorm(4) - skew <- .5 - kurtosis <- 1.2 - positions <- c(5,2,6,10) - cl <- .95 - hp <- 280 - AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AdjustedVarianceCovarianceVaR.R +\name{AdjustedVarianceCovarianceVaR} +\alias{AdjustedVarianceCovarianceVaR} +\title{Cornish-Fisher adjusted variance-covariance VaR} +\usage{ +AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Assumed variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Portfolio return skewness} + +\item{kurtosis}{Portfolio return kurtosis} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar or vector} + +\item{hp}{Holding period and is scalar or vector} +} +\description{ +Estimates the variance-covariance VaR of a multi-asset portfolio using the Cornish-Fisher adjustment for portfolio-return non-normality, for specified confidence level and holding period. +} +\examples{ +# Variance-covariance for randomly generated portfolio + vc.matrix <- matrix(rnorm(16),4,4) + mu <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,10) + cl <- .95 + hp <- 280 + AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BinomialBacktest.Rd =================================================================== --- pkg/Dowd/man/BinomialBacktest.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/BinomialBacktest.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,41 +1,41 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/BinomialBacktest.R -\name{BinomialBacktest} -\alias{BinomialBacktest} -\title{Carries out the binomial backtest for a VaR risk measurement model.} -\usage{ -BinomialBacktest(x, n, cl) -} -\arguments{ -\item{x}{Number of failures} - -\item{n}{Number of observations} - -\item{cl}{Confidence level for VaR} -} -\value{ -Probability that the VaR model is correct -} -\description{ -The basic idea behind binomial backtest (also called basic frequency -test) is to test whether the observed frequency of losses that exceed VaR is -consistent with the frequency of tail losses predicted by the mode. Binomial -Backtest carries out the binomial backtest for a VaR risk measurement model -for specified VaR confidence level and for a one-sided alternative -hypothesis (H1). -} -\examples{ -# Probability that the VaR model is correct for 3 failures, 100 number - # observations and 95\% confidence level - BinomialBacktest(55, 1000, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, Kevin. Measuring Market Risk, Wiley, 2007. - -Kupiec, Paul. Techniques for verifying the accuracy of risk measurement -models, Journal of Derivatives, Winter 1995, p. 79. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BinomialBacktest.R +\name{BinomialBacktest} +\alias{BinomialBacktest} +\title{Carries out the binomial backtest for a VaR risk measurement model.} +\usage{ +BinomialBacktest(x, n, cl) +} +\arguments{ +\item{x}{Number of failures} + +\item{n}{Number of observations} + +\item{cl}{Confidence level for VaR} +} +\value{ +Probability that the VaR model is correct +} +\description{ +The basic idea behind binomial backtest (also called basic frequency +test) is to test whether the observed frequency of losses that exceed VaR is +consistent with the frequency of tail losses predicted by the mode. Binomial +Backtest carries out the binomial backtest for a VaR risk measurement model +for specified VaR confidence level and for a one-sided alternative +hypothesis (H1). +} +\examples{ +# Probability that the VaR model is correct for 3 failures, 100 number + # observations and 95\% confidence level + BinomialBacktest(55, 1000, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Kupiec, Paul. Techniques for verifying the accuracy of risk measurement +models, Journal of Derivatives, Winter 1995, p. 79. +} + Modified: pkg/Dowd/man/BlancoIhleBacktest.Rd =================================================================== --- pkg/Dowd/man/BlancoIhleBacktest.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/BlancoIhleBacktest.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,42 +1,42 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/BlancoIhleBacktest.R -\name{BlancoIhleBacktest} -\alias{BlancoIhleBacktest} -\title{Blanco-Ihle forecast evaluation backtest measure} -\usage{ -BlancoIhleBacktest(Ra, Rb, Rc, cl) -} -\arguments{ -\item{Ra}{Vector of a portfolio profit and loss} - -\item{Rb}{Vector of corresponding VaR forecasts} - -\item{Rc}{Vector of corresponding Expected Tailed Loss forecasts} - -\item{cl}{VaR confidence interval} -} -\value{ -Something -} -\description{ -Derives the Blanco-Ihle forecast evaluation loss measure for a VaR -risk measurement model. -} -\examples{ -# Has to be modified with appropriate data: - # Christoffersen Backtest For Independence for given parameters - a <- rnorm(1*100) - b <- abs(rnorm(1*100))+2 - c <- abs(rnorm(1*100))+2 - BlancoIhleBacktest(a, b, c, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, Kevin. Measuring Market Risk, Wiley, 2007. - -Blanco, C. and Ihle, G. How Good is Your Var? Using Backtesting to Assess -System Performance. Financial Engineering News, 1999. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BlancoIhleBacktest.R +\name{BlancoIhleBacktest} +\alias{BlancoIhleBacktest} +\title{Blanco-Ihle forecast evaluation backtest measure} +\usage{ +BlancoIhleBacktest(Ra, Rb, Rc, cl) +} +\arguments{ +\item{Ra}{Vector of a portfolio profit and loss} + +\item{Rb}{Vector of corresponding VaR forecasts} + +\item{Rc}{Vector of corresponding Expected Tailed Loss forecasts} + +\item{cl}{VaR confidence interval} +} +\value{ +Something +} +\description{ +Derives the Blanco-Ihle forecast evaluation loss measure for a VaR +risk measurement model. +} +\examples{ +# Has to be modified with appropriate data: + # Christoffersen Backtest For Independence for given parameters + a <- rnorm(1*100) + b <- abs(rnorm(1*100))+2 + c <- abs(rnorm(1*100))+2 + BlancoIhleBacktest(a, b, c, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Blanco, C. and Ihle, G. How Good is Your Var? Using Backtesting to Assess +System Performance. Financial Engineering News, 1999. +} + Modified: pkg/Dowd/man/BootstrapES.Rd =================================================================== --- pkg/Dowd/man/BootstrapES.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/BootstrapES.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,34 +1,34 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/BootstrapES.R -\name{BootstrapES} -\alias{BootstrapES} -\title{Bootstrapped ES for specified confidence level} -\usage{ -BootstrapES(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.resamples}{Number of samples to be taken in bootstrap procedure} - -\item{cl}{Number corresponding to Expected Shortfall confidence level} -} -\value{ -Bootstrapped Expected Shortfall -} -\description{ -Estimates the bootstrapped ES for confidence level and holding period -implied by data frequency. -} -\examples{ -# Estimates bootstrapped ES for given parameters - a <- rnorm(100) # generate a random profit/loss vector - BootstrapVaR(a, 50, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapES.R +\name{BootstrapES} +\alias{BootstrapES} +\title{Bootstrapped ES for specified confidence level} +\usage{ +BootstrapES(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Expected Shortfall confidence level} +} +\value{ +Bootstrapped Expected Shortfall +} +\description{ +Estimates the bootstrapped ES for confidence level and holding period +implied by data frequency. +} +\examples{ +# Estimates bootstrapped ES for given parameters + a <- rnorm(100) # generate a random profit/loss vector + BootstrapVaR(a, 50, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapESConfInterval.Rd =================================================================== --- pkg/Dowd/man/BootstrapESConfInterval.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/BootstrapESConfInterval.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,36 +1,36 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/BootstrapESConfInterval.R -\name{BootstrapESConfInterval} -\alias{BootstrapESConfInterval} -\title{Bootstrapped ES Confidence Interval} -\usage{ -BootstrapESConfInterval(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.resamples}{Number of samples to be taken in bootstrap procedure} - -\item{cl}{Number corresponding to Expected Shortfall confidence level} -} -\value{ -90% Confidence interval for bootstrapped ES -} -\description{ -Estimates the 90% confidence interval for bootstrapped ES, for confidence -level and holding period implied by data frequency. -} -\examples{ -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped ES for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapESConfInterval(Ra, 50, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapESConfInterval.R +\name{BootstrapESConfInterval} +\alias{BootstrapESConfInterval} +\title{Bootstrapped ES Confidence Interval} +\usage{ +BootstrapESConfInterval(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Expected Shortfall confidence level} +} +\value{ +90% Confidence interval for bootstrapped ES +} +\description{ +Estimates the 90% confidence interval for bootstrapped ES, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped ES for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapESConfInterval(Ra, 50, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapESFigure.Rd =================================================================== --- pkg/Dowd/man/BootstrapESFigure.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/BootstrapESFigure.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,33 +1,33 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/BootstrapESFigure.R -\name{BootstrapESFigure} -\alias{BootstrapESFigure} -\title{Plots figure of bootstrapped ES} -\usage{ -BootstrapESFigure(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.resamples}{Number of samples to be taken in bootstrap procedure} - -\item{cl}{Number corresponding to Expected Shortfall confidence level} -} -\description{ -Plots figure for the bootstrapped ES, for confidence -level and holding period implied by data frequency. -} -\examples{ -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped ES for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapESFigure(Ra, 500, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapESFigure.R +\name{BootstrapESFigure} +\alias{BootstrapESFigure} +\title{Plots figure of bootstrapped ES} +\usage{ +BootstrapESFigure(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Expected Shortfall confidence level} +} +\description{ +Plots figure for the bootstrapped ES, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped ES for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapESFigure(Ra, 500, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapVaR.Rd =================================================================== --- pkg/Dowd/man/BootstrapVaR.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/BootstrapVaR.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,34 +1,34 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/BootstrapVaR.R -\name{BootstrapVaR} -\alias{BootstrapVaR} -\title{Bootstrapped VaR for specified confidence level} -\usage{ -BootstrapVaR(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.resamples}{Number of samples to be taken in bootstrap procedure} - -\item{cl}{Number corresponding to Value at Risk confidence level} -} -\value{ -Bootstrapped VaR -} -\description{ -Estimates the bootstrapped VaR for confidence level and holding period -implied by data frequency. -} -\examples{ -# Estimates bootstrapped VaR for given parameters - a <- rnorm(100) # generate a random profit/loss vector - BootstrapES(a, 50, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapVaR.R +\name{BootstrapVaR} +\alias{BootstrapVaR} +\title{Bootstrapped VaR for specified confidence level} +\usage{ +BootstrapVaR(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Value at Risk confidence level} +} +\value{ +Bootstrapped VaR +} +\description{ +Estimates the bootstrapped VaR for confidence level and holding period +implied by data frequency. +} +\examples{ +# Estimates bootstrapped VaR for given parameters + a <- rnorm(100) # generate a random profit/loss vector + BootstrapES(a, 50, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapVaRConfInterval.Rd =================================================================== --- pkg/Dowd/man/BootstrapVaRConfInterval.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/BootstrapVaRConfInterval.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,36 +1,36 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/BootstrapVaRConfInterval.R -\name{BootstrapVaRConfInterval} -\alias{BootstrapVaRConfInterval} -\title{Bootstrapped VaR Confidence Interval} -\usage{ -BootstrapVaRConfInterval(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.resamples}{Number of samples to be taken in bootstrap procedure} - -\item{cl}{Number corresponding to Value at Risk confidence level} -} -\value{ -90% Confidence interval for bootstrapped VaR -} -\description{ -Estimates the 90% confidence interval for bootstrapped VaR, for confidence -level and holding period implied by data frequency. -} -\examples{ -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped Var for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapVaRConfInterval(Ra, 500, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapVaRConfInterval.R +\name{BootstrapVaRConfInterval} +\alias{BootstrapVaRConfInterval} +\title{Bootstrapped VaR Confidence Interval} +\usage{ +BootstrapVaRConfInterval(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Value at Risk confidence level} +} +\value{ +90% Confidence interval for bootstrapped VaR +} +\description{ +Estimates the 90% confidence interval for bootstrapped VaR, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped Var for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapVaRConfInterval(Ra, 500, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapVaRFigure.Rd =================================================================== --- pkg/Dowd/man/BootstrapVaRFigure.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/BootstrapVaRFigure.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,33 +1,33 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/BootstrapVaRFigure.R -\name{BootstrapVaRFigure} -\alias{BootstrapVaRFigure} -\title{Plots figure of bootstrapped VaR} -\usage{ -BootstrapVaRFigure(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.resamples}{Number of samples to be taken in bootstrap procedure} - -\item{cl}{Number corresponding to Value at Risk confidence level} -} -\description{ -Plots figure for the bootstrapped VaR, for confidence -level and holding period implied by data frequency. -} -\examples{ -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped VaR for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapESFigure(Ra, 500, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapVaRFigure.R +\name{BootstrapVaRFigure} +\alias{BootstrapVaRFigure} +\title{Plots figure of bootstrapped VaR} +\usage{ +BootstrapVaRFigure(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Value at Risk confidence level} +} +\description{ +Plots figure for the bootstrapped VaR, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped VaR for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapESFigure(Ra, 500, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd =================================================================== --- pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd 2015-06-23 09:23:48 UTC (rev 3719) +++ pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd 2015-06-23 19:52:58 UTC (rev 3720) @@ -1,49 +1,49 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/CdfOfSumUsingGaussianCopula.R -\name{CdfOfSumUsingGaussianCopula} -\alias{CdfOfSumUsingGaussianCopula} -\title{Derives prob ( X + Y < quantile) using Gumbel copula} -\usage{ -CdfOfSumUsingGaussianCopula(quantile, mu1, mu2, sigma1, sigma2, rho, - number.steps.in.copula) -} -\arguments{ -\item{quantile}{Portfolio quantile (or negative of Var, if X, Y are position P/Ls)} - -\item{mu1}{Mean of Profit/Loss on first position} - -\item{mu2}{Mean of Profit/Loss on second position} - [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3720 From noreply at r-forge.r-project.org Tue Jun 23 21:53:57 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 21:53:57 +0200 (CEST) Subject: [Returnanalytics-commits] r3721 - pkg/Dowd Message-ID: <20150623195357.2BA35187A19@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 21:53:56 +0200 (Tue, 23 Jun 2015) New Revision: 3721 Modified: pkg/Dowd/NAMESPACE Log: Update of roxygen2 from 4.1.0 to 4.1.1. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-23 19:52:58 UTC (rev 3720) +++ pkg/Dowd/NAMESPACE 2015-06-23 19:53:56 UTC (rev 3721) @@ -1,54 +1,54 @@ -# Generated by roxygen2 (4.1.0): do not edit by hand - -export(ADTestStat) -export(AdjustedNormalESHotspots) -export(AdjustedNormalVaRHotspots) -export(AdjustedVarianceCovarianceES) -export(AdjustedVarianceCovarianceVaR) -export(BinomialBacktest) -export(BlancoIhleBacktest) -export(BootstrapES) -export(BootstrapESConfInterval) -export(BootstrapESFigure) -export(BootstrapVaR) -export(BootstrapVaRConfInterval) -export(BootstrapVaRFigure) -export(CdfOfSumUsingGaussianCopula) -export(CdfOfSumUsingGumbelCopula) -export(CdfOfSumUsingProductCopula) -export(ChristoffersenBacktestForIndependence) -export(ChristoffersenBacktestForUnconditionalCoverage) -export(CornishFisherES) -export(CornishFisherVaR) -export(FrechetES) -export(FrechetESPlot2DCl) -export(FrechetVaR) -export(FrechetVaRPlot2DCl) -export(GParetoES) -export(GParetoMEFPlot) -export(GParetoMultipleMEFPlot) -export(GParetoVaR) -export(GaussianCopulaVaR) -export(GumbelCopulaVaR) -export(GumbelES) -export(GumbelESPlot2DCl) -export(GumbelVaR) -export(GumbelVaRPlot2DCl) -export(HSES) -export(HSVaR) -export(HSVaRDFPerc) -export(HSVaRFigure) -export(HillEstimator) -export(HillPlot) -export(HillQuantileEstimator) -export(JarqueBeraBacktest) -export(KSTestStat) -export(KuiperTestStat) -export(LopezBacktest) -export(MEFPlot) -export(NormalQQPlot) -export(PickandsEstimator) -export(PickandsPlot) -export(ProductCopulaVaR) -export(TQQPlot) -import(bootstrap) +# Generated by roxygen2 (4.1.1): do not edit by hand + +export(ADTestStat) +export(AdjustedNormalESHotspots) +export(AdjustedNormalVaRHotspots) +export(AdjustedVarianceCovarianceES) +export(AdjustedVarianceCovarianceVaR) +export(BinomialBacktest) +export(BlancoIhleBacktest) +export(BootstrapES) +export(BootstrapESConfInterval) +export(BootstrapESFigure) +export(BootstrapVaR) +export(BootstrapVaRConfInterval) +export(BootstrapVaRFigure) +export(CdfOfSumUsingGaussianCopula) +export(CdfOfSumUsingGumbelCopula) +export(CdfOfSumUsingProductCopula) +export(ChristoffersenBacktestForIndependence) +export(ChristoffersenBacktestForUnconditionalCoverage) +export(CornishFisherES) +export(CornishFisherVaR) +export(FrechetES) +export(FrechetESPlot2DCl) +export(FrechetVaR) +export(FrechetVaRPlot2DCl) +export(GParetoES) +export(GParetoMEFPlot) +export(GParetoMultipleMEFPlot) +export(GParetoVaR) +export(GaussianCopulaVaR) +export(GumbelCopulaVaR) +export(GumbelES) +export(GumbelESPlot2DCl) +export(GumbelVaR) +export(GumbelVaRPlot2DCl) +export(HSES) +export(HSVaR) +export(HSVaRDFPerc) +export(HSVaRFigure) +export(HillEstimator) +export(HillPlot) +export(HillQuantileEstimator) +export(JarqueBeraBacktest) +export(KSTestStat) +export(KuiperTestStat) +export(LopezBacktest) +export(MEFPlot) +export(NormalQQPlot) +export(PickandsEstimator) +export(PickandsPlot) +export(ProductCopulaVaR) +export(TQQPlot) +import(bootstrap) From noreply at r-forge.r-project.org Tue Jun 23 22:01:13 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 22:01:13 +0200 (CEST) Subject: [Returnanalytics-commits] r3722 - pkg/Dowd/tests/testthat Message-ID: <20150623200113.D4BF7187A02@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 22:01:13 +0200 (Tue, 23 Jun 2015) New Revision: 3722 Modified: pkg/Dowd/tests/testthat/testJarqueBeraBacktest.R Log: One more test case added/modified. Modified: pkg/Dowd/tests/testthat/testJarqueBeraBacktest.R =================================================================== --- pkg/Dowd/tests/testthat/testJarqueBeraBacktest.R 2015-06-23 19:53:56 UTC (rev 3721) +++ pkg/Dowd/tests/testthat/testJarqueBeraBacktest.R 2015-06-23 20:01:13 UTC (rev 3722) @@ -1,5 +1,6 @@ -test_that("Binomial Backtest Works.",{ +test_that("JarqueBera Backtest.",{ # Success - expect_equal(0.6942, JarqueBeraBacktest(-0.0758, 2.8888, 500), tolerance=0.01) + expect_equal(0.6940, JarqueBeraBacktest(-0.0758, 2.8888, 500), tolerance=0.01) expect_equal(1, JarqueBeraBacktest(0, 3, 100), tolerance=0.01) + }) \ No newline at end of file From noreply at r-forge.r-project.org Tue Jun 23 22:01:39 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 22:01:39 +0200 (CEST) Subject: [Returnanalytics-commits] r3723 - pkg/Dowd/tests/testthat Message-ID: <20150623200139.91347187A02@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 22:01:39 +0200 (Tue, 23 Jun 2015) New Revision: 3723 Modified: pkg/Dowd/tests/testthat/testBinomialBacktest.R Log: More test cases added. Modified: pkg/Dowd/tests/testthat/testBinomialBacktest.R =================================================================== --- pkg/Dowd/tests/testthat/testBinomialBacktest.R 2015-06-23 20:01:13 UTC (rev 3722) +++ pkg/Dowd/tests/testthat/testBinomialBacktest.R 2015-06-23 20:01:39 UTC (rev 3723) @@ -1,11 +1,19 @@ test_that("Binomial Backtest Works.",{ - # Success + # Success - 1 + # x < n * p expect_equal(0.7358, BinomialBacktest(1, 100, 0.99), tolerance=0.001) - expect_equal(0.2529, BinomialBacktest(55, 1000, 0.95), tolerance=0.001) - # Warnings - expect_warning(val <- BinomialBacktest(35,30,0.95)) - expect_true(is.nan(val)) - expect_warning(val <- BinomialBacktest(5,30,1.5)) - expect_true(is.nan(val)) + # Success - 2 + # x >= n * p + expect_equal(0, BinomialBacktest(91, 100, 0.90), tolerance=0.001) + + # Error - 1 + expect_error(val <- BinomialBacktest(35, 30, 0.95)) + + # Error - 2 + expect_error(val <- BinomialBacktest(5, 30, 1.5)) + + # Error - 3 + expect_error(val <- BinomialBacktest(5, 30, -.95)) + }) \ No newline at end of file From noreply at r-forge.r-project.org Tue Jun 23 22:41:11 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 22:41:11 +0200 (CEST) Subject: [Returnanalytics-commits] r3724 - pkg/Dowd/R Message-ID: <20150623204111.1A7B31861F4@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 22:41:10 +0200 (Tue, 23 Jun 2015) New Revision: 3724 Modified: pkg/Dowd/R/AdjustedNormalESHotspots.R Log: Mistake in for loop corrected. Modified: pkg/Dowd/R/AdjustedNormalESHotspots.R =================================================================== --- pkg/Dowd/R/AdjustedNormalESHotspots.R 2015-06-23 20:01:39 UTC (rev 3723) +++ pkg/Dowd/R/AdjustedNormalESHotspots.R 2015-06-23 20:41:10 UTC (rev 3724) @@ -89,7 +89,7 @@ # Portfolio ES es <- double(length(positions)) ies <- double(length(positions)) - for (j in range(1: length(positions))) { + for (j in 1:length(positions)) { x <- positions x[j] <- 0 sigma <- x %*% vc.matrix %*% t(x) / (sum(x)^2) From noreply at r-forge.r-project.org Tue Jun 23 22:42:08 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 22:42:08 +0200 (CEST) Subject: [Returnanalytics-commits] r3725 - pkg/Dowd/tests/testthat Message-ID: <20150623204208.429311861F4@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 22:42:07 +0200 (Tue, 23 Jun 2015) New Revision: 3725 Added: pkg/Dowd/tests/testthat/testAdjustedNormalESHotspots.R Log: Complete test case for AdjustedNormalESHotspots added. Added: pkg/Dowd/tests/testthat/testAdjustedNormalESHotspots.R =================================================================== --- pkg/Dowd/tests/testthat/testAdjustedNormalESHotspots.R (rev 0) +++ pkg/Dowd/tests/testthat/testAdjustedNormalESHotspots.R 2015-06-23 20:42:07 UTC (rev 3725) @@ -0,0 +1,77 @@ +test_that("Adjusted Normal ES Hotspots.",{ + + # Success - 1 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- .95 + hp <- 280 + val <- AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) + expect_equal(c(4655.6, -725, 308.2), val, tolerance=1) + + + # Success - 2 + vc.matrix <- matrix(c(2.6, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, + 1, 3.4, -2, -5, -1.2, 3.2, 0, -1.2), 4, 4) + mu <- c(-.5, -.3, -1.2, 0) + skew <- -.4 + kurtosis <- 2.2 + positions <- c(4,1,10,3) + cl <- .99 + hp <- 50 + val <- AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) + expect_equal(c(1482.4, 2096.8, -5079.3, -2071.2), val, tolerance=1) + + # Error - 1 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- .95 + hp <- -10 + expect_error(val <- AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 2 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- 1.2 + hp <- 280 + expect_error(val <- AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 3 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- -.95 + hp <- 280 + expect_error(val <- AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 4 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1, 1.2) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5, 2, 6) + cl <- -.95 + hp <- 280 + expect_error(val <- AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 5 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,3) + cl <- -.95 + hp <- 280 + expect_error(val <- AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + +}) \ No newline at end of file From noreply at r-forge.r-project.org Tue Jun 23 22:54:26 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 22:54:26 +0200 (CEST) Subject: [Returnanalytics-commits] r3726 - pkg/Dowd/tests/testthat Message-ID: <20150623205426.B1A43187A1C@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 22:54:26 +0200 (Tue, 23 Jun 2015) New Revision: 3726 Added: pkg/Dowd/tests/testthat/testAdjustedNormalVaRHotspots.R Log: Complete test case for AdjustedNormalVaRHotspots added. Added: pkg/Dowd/tests/testthat/testAdjustedNormalVaRHotspots.R =================================================================== --- pkg/Dowd/tests/testthat/testAdjustedNormalVaRHotspots.R (rev 0) +++ pkg/Dowd/tests/testthat/testAdjustedNormalVaRHotspots.R 2015-06-23 20:54:26 UTC (rev 3726) @@ -0,0 +1,76 @@ +test_that("Adjusted Normal VaR Hotspots.",{ + + # Success - 1 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- .95 + hp <- 280 + val <- AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) + expect_equal(c(4870.2, 1056.3, 1280.1), val, tolerance=0.001) + + # Success - 2 + vc.matrix <- matrix(c(2.6, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, + 1, 3.4, -2, -5, -1.2, 3.2, 0, -1.2), 4, 4) + mu <- c(-.5, -.3, -1.2, 0) + skew <- -.4 + kurtosis <- 2.2 + positions <- c(4,1,10,3) + cl <- .99 + hp <- 50 + val <- AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) + expect_equal(c(1200.9, 1738.4, -4585.4, -1973.5), val, tolerance=1) + + # Error - 1 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- .95 + hp <- -10 + expect_error(val <- AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 2 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- 1.2 + hp <- 280 + expect_error(val <- AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 3 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- -.95 + hp <- 280 + expect_error(val <- AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 4 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1, 1.2) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5, 2, 6) + cl <- -.95 + hp <- 280 + expect_error(val <- AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 5 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,3) + cl <- -.95 + hp <- 280 + expect_error(val <- AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + +}) \ No newline at end of file From noreply at r-forge.r-project.org Tue Jun 23 23:14:25 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 23:14:25 +0200 (CEST) Subject: [Returnanalytics-commits] r3727 - pkg/Dowd/tests/testthat Message-ID: <20150623211425.A2CF5186BFD@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 23:14:25 +0200 (Tue, 23 Jun 2015) New Revision: 3727 Added: pkg/Dowd/tests/testthat/testAdjustedVarianceCovarianceES.R Log: Complete test case for AdjustedVarianceCovarianceES added. Added: pkg/Dowd/tests/testthat/testAdjustedVarianceCovarianceES.R =================================================================== --- pkg/Dowd/tests/testthat/testAdjustedVarianceCovarianceES.R (rev 0) +++ pkg/Dowd/tests/testthat/testAdjustedVarianceCovarianceES.R 2015-06-23 21:14:25 UTC (rev 3727) @@ -0,0 +1,76 @@ +test_that("Adjusted Variance Covariance ES.",{ + + # Success - 1 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- .95 + hp <- 280 + val <- AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) + expect_equal(as.matrix(4434.6), val, tolerance=.1) + + + vc.matrix <- matrix(c(2.6, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, + 1, 3.4, -2, -5, -1.2, 3.2, 0, -1.2), 4, 4) + mu <- c(-.5, -.3, -1.2, 0) + skew <- -.4 + kurtosis <- 2.2 + positions <- c(4,1,10,3) + cl <- .99 + hp <- 50 + val <- AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) + expect_equal(as.matrix(-3198.0), val, tolerance=.1) + + # Error - 1 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- .95 + hp <- -10 + expect_error(val <- AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 2 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- 1.2 + hp <- 280 + expect_error(val <- AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 3 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- -.95 + hp <- 280 + expect_error(val <- AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 4 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1, 1.2) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5, 2, 6) + cl <- -.95 + hp <- 280 + expect_error(val <- AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 5 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,3) + cl <- -.95 + hp <- 280 + expect_error(val <- AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + +}) \ No newline at end of file From noreply at r-forge.r-project.org Tue Jun 23 23:25:08 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 23:25:08 +0200 (CEST) Subject: [Returnanalytics-commits] r3728 - pkg/Dowd/tests/testthat Message-ID: <20150623212508.628511879C1@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 23:25:08 +0200 (Tue, 23 Jun 2015) New Revision: 3728 Added: pkg/Dowd/tests/testthat/testAdjustedVarianceCovarianceVaR.R Log: Complete test case for AdjustedVarianceCovarianceVaR added. Added: pkg/Dowd/tests/testthat/testAdjustedVarianceCovarianceVaR.R =================================================================== --- pkg/Dowd/tests/testthat/testAdjustedVarianceCovarianceVaR.R (rev 0) +++ pkg/Dowd/tests/testthat/testAdjustedVarianceCovarianceVaR.R 2015-06-23 21:25:08 UTC (rev 3728) @@ -0,0 +1,77 @@ +test_that("Adjusted Variance Covariance VaR.",{ + + # Success - 1 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- .95 + hp <- 280 + val <- AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) + expect_equal(as.matrix(4705.9), val, tolerance=0.001) + + + # Success - 2 + vc.matrix <- matrix(c(2.6, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, + 1, 3.4, -2, -5, -1.2, 3.2, 0, -1.2), 4, 4) + mu <- c(-.5, -.3, -1.2, 0) + skew <- -.4 + kurtosis <- 2.2 + positions <- c(4,1,10,3) + cl <- .99 + hp <- 50 + val <- AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) + expect_equal(as.matrix(-2898.0), val, tolerance=.1) + + # Error - 1 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- .95 + hp <- -10 + expect_error(val <- AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 2 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- 1.2 + hp <- 280 + expect_error(val <- AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 3 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6) + cl <- -.95 + hp <- 280 + expect_error(val <- AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 4 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1, 1.2) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5, 2, 6) + cl <- -.95 + hp <- 280 + expect_error(val <- AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + + # Error - 5 + vc.matrix <- matrix(c(2.5, 3.4, -1.9, 4.3, 2.3, -3.1, 4.3, -1.2, 1), 3, 3) + mu <- c(.4, -.3, .1) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,3) + cl <- -.95 + hp <- 280 + expect_error(val <- AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp)) + +}) \ No newline at end of file From noreply at r-forge.r-project.org Tue Jun 23 23:28:41 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 23:28:41 +0200 (CEST) Subject: [Returnanalytics-commits] r3729 - pkg/Dowd/tests/testthat Message-ID: <20150623212841.ABDF51879C1@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 23:28:41 +0200 (Tue, 23 Jun 2015) New Revision: 3729 Added: pkg/Dowd/tests/testthat/testADTestStat.R Log: Test for ADTestStat added. Added: pkg/Dowd/tests/testthat/testADTestStat.R =================================================================== --- pkg/Dowd/tests/testthat/testADTestStat.R (rev 0) +++ pkg/Dowd/tests/testthat/testADTestStat.R 2015-06-23 21:28:41 UTC (rev 3729) @@ -0,0 +1,11 @@ +test_that("AD Test Stat.",{ + + # Success cases were/can be tested by comparing plots and confidence intervals. + + # Error - 1 + expect_error(val <- ADTestStat(1000, 100, 1.05)) + + # Error - 2 + expect_error(val <- ADTestStat(1000, 100, -.95)) + +}) \ No newline at end of file From noreply at r-forge.r-project.org Tue Jun 23 23:33:59 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 23:33:59 +0200 (CEST) Subject: [Returnanalytics-commits] r3730 - pkg/Dowd/R Message-ID: <20150623213359.CF2B11872A5@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 23:33:59 +0200 (Tue, 23 Jun 2015) New Revision: 3730 Modified: pkg/Dowd/R/AdjustedVarianceCovarianceES.R Log: Mistake in return value corrected. Modified: pkg/Dowd/R/AdjustedVarianceCovarianceES.R =================================================================== --- pkg/Dowd/R/AdjustedVarianceCovarianceES.R 2015-06-23 21:28:41 UTC (rev 3729) +++ pkg/Dowd/R/AdjustedVarianceCovarianceES.R 2015-06-23 21:33:59 UTC (rev 3730) @@ -121,6 +121,6 @@ } } y <- t(es) - return(es) + return(y) } From noreply at r-forge.r-project.org Tue Jun 23 23:34:57 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 23:34:57 +0200 (CEST) Subject: [Returnanalytics-commits] r3731 - pkg/Dowd/R Message-ID: <20150623213457.E0EAD1872A5@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 23:34:57 +0200 (Tue, 23 Jun 2015) New Revision: 3731 Modified: pkg/Dowd/R/BlancoIhleBacktest.R Log: Return value and mistake in example corrected. Modified: pkg/Dowd/R/BlancoIhleBacktest.R =================================================================== --- pkg/Dowd/R/BlancoIhleBacktest.R 2015-06-23 21:33:59 UTC (rev 3730) +++ pkg/Dowd/R/BlancoIhleBacktest.R 2015-06-23 21:34:57 UTC (rev 3731) @@ -7,7 +7,7 @@ #' @param Rb Vector of corresponding VaR forecasts #' @param Rc Vector of corresponding Expected Tailed Loss forecasts #' @param cl VaR confidence interval -#' @return Something +#' @return First Blanco-Ihle score measure. #' #' @references Dowd, Kevin. Measuring Market Risk, Wiley, 2007. #' @@ -18,7 +18,7 @@ #' @examples #' #' # Has to be modified with appropriate data: -#' # Christoffersen Backtest For Independence for given parameters +#' # Blanco-Ihle Backtest For Independence for given parameters #' a <- rnorm(1*100) #' b <- abs(rnorm(1*100))+2 #' c <- abs(rnorm(1*100))+2 From noreply at r-forge.r-project.org Tue Jun 23 23:35:26 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 23:35:26 +0200 (CEST) Subject: [Returnanalytics-commits] r3732 - pkg/Dowd/man Message-ID: <20150623213526.1AEB81872A5@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 23:35:25 +0200 (Tue, 23 Jun 2015) New Revision: 3732 Modified: pkg/Dowd/man/BlancoIhleBacktest.Rd Log: Return value and mistake in example corrected. Modified: pkg/Dowd/man/BlancoIhleBacktest.Rd =================================================================== --- pkg/Dowd/man/BlancoIhleBacktest.Rd 2015-06-23 21:34:57 UTC (rev 3731) +++ pkg/Dowd/man/BlancoIhleBacktest.Rd 2015-06-23 21:35:25 UTC (rev 3732) @@ -16,7 +16,7 @@ \item{cl}{VaR confidence interval} } \value{ -Something +First Blanco-Ihle score measure. } \description{ Derives the Blanco-Ihle forecast evaluation loss measure for a VaR @@ -24,7 +24,7 @@ } \examples{ # Has to be modified with appropriate data: - # Christoffersen Backtest For Independence for given parameters + # Blanco-Ihle Backtest For Independence for given parameters a <- rnorm(1*100) b <- abs(rnorm(1*100))+2 c <- abs(rnorm(1*100))+2 From noreply at r-forge.r-project.org Tue Jun 23 23:56:55 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 23 Jun 2015 23:56:55 +0200 (CEST) Subject: [Returnanalytics-commits] r3733 - in pkg/Dowd: . R man Message-ID: <20150623215656.024C81878F6@r-forge.r-project.org> Author: dacharya Date: 2015-06-23 23:56:55 +0200 (Tue, 23 Jun 2015) New Revision: 3733 Added: pkg/Dowd/R/InsuranceVaR.R pkg/Dowd/man/InsuranceVaR.Rd Modified: pkg/Dowd/NAMESPACE Log: InsuranceVaR: source and documentation added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-23 21:35:25 UTC (rev 3732) +++ pkg/Dowd/NAMESPACE 2015-06-23 21:56:55 UTC (rev 3733) @@ -41,6 +41,7 @@ export(HillEstimator) export(HillPlot) export(HillQuantileEstimator) +export(InsuranceVaR) export(JarqueBeraBacktest) export(KSTestStat) export(KuiperTestStat) Added: pkg/Dowd/R/InsuranceVaR.R =================================================================== --- pkg/Dowd/R/InsuranceVaR.R (rev 0) +++ pkg/Dowd/R/InsuranceVaR.R 2015-06-23 21:56:55 UTC (rev 3733) @@ -0,0 +1,53 @@ +#' VaR of Insurance Portfolio +#' +#' Generates Monte Carlo VaR for insurance portfolio in Chapter 6.5 +#' +#' @param mu Mean of returns +#' @param sigma Volatility of returns +#' @param n Number of contracts +#' @param p Probability of any loss event +#' @param theta Expected profit per contract +#' @param deductible Deductible +#' @param number.trials Number of simulation trials +#' @param cl VaR confidence level +#' @return VaR of the specified portfolio +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates VaR of Insurance portfolio with given parameters +#' InsuranceVaR(.8, 1.3, 100, .6, 21, 12, 50, .95) +#' +#' @export +InsuranceVaR<- function(mu, sigma, n, p, theta, deductible, number.trials, cl){ + M <- number.trials + D <- deductible + L <- matrix(0, n, M) + company.loss <- L + total.company.loss <- double(M) + for (j in 1:M) { + L[1, j] <- rbinom( 1, 1, p) * rlnorm(1, mu, sigma) # Realisation of L + company.loss[1, j] <- max(L[1,j] - D, 0) # Adjust for deductible + + for (i in 2:n) { + L[i, j] <- rbinom(1, 1, p) * rlnorm(1, mu, sigma) # Realisation of L + company.loss[i, j] <- max(L[i,j] - D, 0) + company.loss[i - 1, j] # Adjust + # for deductible + } + total.company.loss[j] <- company.loss[n,j] # Total company loss for + # given j trial + } + # Sample of total company losses + adjusted.total.company.loss <- total.company.loss - mean(total.company.loss) - + theta * mean(total.company.loss) / n # Adjusts for premium + profit.or.loss <- - adjusted.total.company.loss # Convert to P/L + hist(adjusted.total.company.loss, col = "blue", + xlab = "Total Company Loss", yab = "Frequency", + main = "Adjusted Total Company Loss") + y <- HSVaR(profit.or.loss, cl) + return(y) + +} \ No newline at end of file Added: pkg/Dowd/man/InsuranceVaR.Rd =================================================================== --- pkg/Dowd/man/InsuranceVaR.Rd (rev 0) +++ pkg/Dowd/man/InsuranceVaR.Rd 2015-06-23 21:56:55 UTC (rev 3733) @@ -0,0 +1,42 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/InsuranceVaR.R +\name{InsuranceVaR} +\alias{InsuranceVaR} +\title{VaR of Insurance Portfolio} +\usage{ +InsuranceVaR(mu, sigma, n, p, theta, deductible, number.trials, cl) +} +\arguments{ +\item{mu}{Mean of returns} + +\item{sigma}{Volatility of returns} + +\item{n}{Number of contracts} + +\item{p}{Probability of any loss event} + +\item{theta}{Expected profit per contract} + +\item{deductible}{Deductible} + +\item{number.trials}{Number of simulation trials} + +\item{cl}{VaR confidence level} +} +\value{ +VaR of the specified portfolio +} +\description{ +Generates Monte Carlo VaR for insurance portfolio in Chapter 6.5 +} +\examples{ +# Estimates VaR of Insurance portfolio with given parameters + InsuranceVaR(.8, 1.3, 100, .6, 21, 12, 50, .95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Wed Jun 24 00:00:51 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 24 Jun 2015 00:00:51 +0200 (CEST) Subject: [Returnanalytics-commits] r3734 - pkg/Dowd/R Message-ID: <20150623220051.B5E181879C0@r-forge.r-project.org> Author: dacharya Date: 2015-06-24 00:00:51 +0200 (Wed, 24 Jun 2015) New Revision: 3734 Modified: pkg/Dowd/R/InsuranceVaR.R Log: Typo corrected in hist function: yab -> ylab. Modified: pkg/Dowd/R/InsuranceVaR.R =================================================================== --- pkg/Dowd/R/InsuranceVaR.R 2015-06-23 21:56:55 UTC (rev 3733) +++ pkg/Dowd/R/InsuranceVaR.R 2015-06-23 22:00:51 UTC (rev 3734) @@ -45,7 +45,7 @@ theta * mean(total.company.loss) / n # Adjusts for premium profit.or.loss <- - adjusted.total.company.loss # Convert to P/L hist(adjusted.total.company.loss, col = "blue", - xlab = "Total Company Loss", yab = "Frequency", + xlab = "Total Company Loss", ylab = "Frequency", main = "Adjusted Total Company Loss") y <- HSVaR(profit.or.loss, cl) return(y) From noreply at r-forge.r-project.org Wed Jun 24 09:37:27 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 24 Jun 2015 09:37:27 +0200 (CEST) Subject: [Returnanalytics-commits] r3735 - in pkg/Meucci: . R demo Message-ID: <20150624073727.F0A36187A0C@r-forge.r-project.org> Author: xavierv Date: 2015-06-24 09:37:27 +0200 (Wed, 24 Jun 2015) New Revision: 3735 Modified: pkg/Meucci/NAMESPACE pkg/Meucci/R/HermiteGrid.R pkg/Meucci/R/data.R pkg/Meucci/demo/HermiteGrid_CaseStudy.R pkg/Meucci/demo/HermiteGrid_demo.R Log: - fixed HermiteGrid_CaseStudy demo script, ported the necessary data and exported its functions Modified: pkg/Meucci/NAMESPACE =================================================================== --- pkg/Meucci/NAMESPACE 2015-06-23 22:00:51 UTC (rev 3734) +++ pkg/Meucci/NAMESPACE 2015-06-24 07:37:27 UTC (rev 3735) @@ -73,9 +73,14 @@ export(garch2f8) export(hermitePolynomial) export(integrateSubIntervals) +export(kernelbw) +export(kernelcdf) +export(kernelinv) +export(kernelpdf) export(linreturn) export(normalizeProb) export(pHistPriorPosterior) +export(private_fun) export(robustBayesianPortfolioOptimization) export(std) export(subIntervals) Modified: pkg/Meucci/R/HermiteGrid.R =================================================================== --- pkg/Meucci/R/HermiteGrid.R 2015-06-23 22:00:51 UTC (rev 3734) +++ pkg/Meucci/R/HermiteGrid.R 2015-06-24 07:37:27 UTC (rev 3735) @@ -146,6 +146,7 @@ #' @return bw a numeric signifying the bandwidth #' #' @author Manan Shah \email{mkshah@@tepper.cmu.edu} +#' @export kernelbw <- function(xi) { N <- length(xi) @@ -174,6 +175,7 @@ #' value of length equal to x #' #' @author Manan Shah \email{mkshah@@tepper.cmu.edu} +#' @export kernelcdf <- function(x, xi, bw, wi) { n <- length(xi) @@ -205,6 +207,7 @@ #' length equal to x #' #' @author Manan Shah \email{mkshah@@tepper.cmu.edu} +#' @export kernelpdf <- function(x, xi, bw, wi) { n <- length(xi) @@ -237,6 +240,7 @@ #' to p #' #' @author Manan Shah \email{mkshah@@tepper.cmu.edu} +#' @export kernelinv <- function(p, xi, bw, wi) { nargin <- length(as.list(match.call())) - 1 @@ -289,6 +293,7 @@ #' length equal to x or p #' #' @author Manan Shah \email{mkshah@@tepper.cmu.edu} +#' @export private_fun <- function(x, xi, bw, wi, p) { f <- kernelcdf(x, xi, bw, wi) - p Modified: pkg/Meucci/R/data.R =================================================================== --- pkg/Meucci/R/data.R 2015-06-23 22:00:51 UTC (rev 3734) +++ pkg/Meucci/R/data.R 2015-06-24 07:37:27 UTC (rev 3735) @@ -283,4 +283,13 @@ #' @author Xavier Valls\email{xaviervallspla@@gmail.com} #' @references A. Meucci, D. Ardia, S. Keel - "Fully Flexible Extreme Views" #' @keywords data -NULL \ No newline at end of file +NULL + +#' @title Pseudo data: Gauss-Hermite grid case study input data +#' +#' @name pseudodata +#' @docType data +#' @author Xavier Valls\email{xaviervallspla@@gmail.com} +#' @references A. Meucci, D. Ardia, S. Keel - "Fully Flexible Extreme Views" +#' @keywords data +NULL Modified: pkg/Meucci/demo/HermiteGrid_CaseStudy.R =================================================================== --- pkg/Meucci/demo/HermiteGrid_CaseStudy.R 2015-06-23 22:00:51 UTC (rev 3734) +++ pkg/Meucci/demo/HermiteGrid_CaseStudy.R 2015-06-24 07:37:27 UTC (rev 3735) @@ -10,7 +10,10 @@ # IMPORTANT - This script is about the methodology, not the input data, # which has been modified -xi <- as.matrix(100 * data[, 2]) +data(pseudodata) +data(ghqx) + +xi <- as.matrix(100 * pseudodata[, 2]) n <- nrow(xi) # bandwidth @@ -23,31 +26,32 @@ # Prior market model # kernel density +market <- list() +market$mu <- mean(xi) +market$pdf <- function (x) kernelpdf(x, xi, bw, wi) +market$cdf <- function (x) kernelcdf(x, xi, bw, wi) +market$inv <- function (x) kernelinv(x, xi, bw, wi) +market$VaR95 <- market$inv(c(0.05)) +market$CVaR95 <- integrate(function(x) x * market$pdf(x), -100, + market$VaR95)$val / 0.05 -market.mu <- mean(xi) -market.pdf <- function (x) kernelpdf(x, xi, bw, wi) -market.cdf <- function (x) kernelcdf(x, xi, bw, wi) -market.inv <- function (x) kernelinv(x, xi, bw, wi) -market.VaR95 <- market.inv(c(0.05)) -market.CVaR95 <- integrate(function(x) x * market.pdf(x), -100, - market.VaR95)$val / 0.05 - # numerical (Gauss-Hermite grid) prior # rescale GH zeros so they belong to [0,1] tmp <- (ghqx - min(ghqx)) / (max(ghqx) - min(ghqx)) epsilon <- 1e-10 -Lower <- market.inv(epsilon) -Upper <- market.inv(1 - epsilon) +Lower <- market$inv(epsilon) +Upper <- market$inv(1 - epsilon) X <- Lower + tmp * (Upper - Lower) # rescale mesh -p <- integrateSubIntervals(X, market.cdf) +p <- integrateSubIntervals(X, market$cdf) p <- normalizeProb(p) J <- nrow(X) # Entropy posterior from extreme view on mean and CVaR -view.mu <- mean(xi) - 1.0 -view.CVaR95 <- market.CVaR95 - 1.0 +view <- list() +view$mu <- mean(xi) - 1.0 +view$CVaR95 <- market$CVaR95 - 1.0 # Netwton Raphson emptyMatrix <- matrix(,nrow = 0, ncol = 0) @@ -55,8 +59,8 @@ idx <- as.matrix(cumsum(p) <= 0.05) s[1] <- sum(idx) posteriorEntropy <- EntropyProg(p, t(idx), as.matrix(0.05), rbind(rep(1, J), - t(X), t(idx * X)), rbind(1, view.mu, - 0.05 * view.CVaR95)) + t(X), t(idx * X)), rbind(1, view$mu, + 0.05 * view$CVaR95)) KLdiv <- as.matrix(posteriorEntropy$optimizationPerformance$ml) p_ <- posteriorEntropy$p_ @@ -68,27 +72,18 @@ idx <- cbind(matrix(1, 1, s[i - 1]), matrix(0, 1, J - s[i - 1])) posteriorEntropy1 <- EntropyProg(p, idx, as.matrix(0.05), rbind(matrix(1, 1, J), t(X), t(t(idx) * X)), - rbind(1, view.mu, 0.05 * view.CVaR95)) - # [dummy, KLdiv_s] = optimizeEntropy(p, [idx'; (idx .* X)'], - # [0.05; 0.05 * view.CVaR95], - # [ones(1, J); X'], [1; view.mu]); - + rbind(1, view$mu, 0.05 * view$CVaR95)) + idx <- cbind(matrix(1, 1, s[i - 1] + 1), matrix(0, 1, J - s[i - 1] - 1)) posteriorEntropy2 <- EntropyProg(p, idx, as.matrix(0.05), rbind(matrix(1, 1, J), t(X), t(t(idx) * X)), - rbind(1, view.mu, 0.05 * view.CVaR95)) - # [dummy, KLdiv_s1] = optimizeEntropy(p, [idx'; (idx .* X)'], - # [0.05; 0.05 * view.CVaR95], - # [ones(1, J); X'], [1; view.mu]); - + rbind(1, view$mu, 0.05 * view$CVaR95)) + idx <- cbind(matrix(1, 1, s[i - 1] + 2), matrix(0, 1, J - s[i - 1] - 2)) posteriorEntropy3 <- EntropyProg(p, idx, as.matrix(0.05), rbind(matrix(1, 1, J), t(X), t(t(idx) * X)), - rbind(1, view.mu, 0.05 * view.CVaR95)) - # [dummy, KLdiv_s2] = optimizeEntropy(p, [idx'; (idx .* X)'], - # [0.05; 0.05 * view.CVaR95], - # [ones(1, J); X'], [1; view.mu]); - + rbind(1, view$mu, 0.05 * view$CVaR95)) + # first difference DE <- posteriorEntropy2$optimizationPerformance$ml - posteriorEntropy1$optimizationPerformance$ml @@ -105,17 +100,22 @@ idx <- cbind(matrix(1, 1, s[i]), matrix(0, 1, J - s[i])) tempEntropy <- EntropyProg(p, idx, as.matrix(0.05), rbind(matrix(1, 1, J), t(X), t(t(idx) * X)), - rbind(1, view.mu, 0.05 * view.CVaR95)) - # [tmp.p_, tmp.KLdiv] = optimizeEntropy(p, [idx'; (idx .* X)'], - # [0.05; 0.05 * view.CVaR95], - # [ones(1, J); X'], [1; view.mu]); + rbind(1, view$mu, 0.05 * view$CVaR95)) p_ <- cbind(p_, tempEntropy$p_) - KLdiv <- rbind(KLdiv, tempEntropy$optimizationPerformance$ml) #ok<*AGROW> + KLdiv <- rbind(KLdiv, tempEntropy$optimizationPerformance$ml) # if change in KLdiv less than one percent, stop if(abs((KLdiv[i] - KLdiv[i - 1]) / KLdiv[i - 1]) < 0.01) doStop <- 1 } -plot(t(X), p) -plot(t(X), p_[,ncol(p_)]) +plot(t(X), p, type = "l", col = "blue", lwd = 1.5, xlab="Returns %", + ylab = "") +lines(t(X), p_[, ncol(p_)], type = "l", col = "red", lwd = 1.5) +lines(market$mu, 0.0, type = "p", pch = 16, col = "blue") +lines(market$CVaR95, 0.0, type = "p", pch = 17, col = "blue") +lines(view$mu, 0.0, type = "p", pch = 16, col = "red") +lines(view$CVaR95, 0.0, type = "p", pch = 17, col = "red") +legend("topright", 1.9, c("Prior", "Posterior"), + col = c("blue", "red"), lty = 1) + Modified: pkg/Meucci/demo/HermiteGrid_demo.R =================================================================== --- pkg/Meucci/demo/HermiteGrid_demo.R 2015-06-23 22:00:51 UTC (rev 3734) +++ pkg/Meucci/demo/HermiteGrid_demo.R 2015-06-24 07:37:27 UTC (rev 3735) @@ -23,13 +23,13 @@ market$inv <- function(x) qnorm(x, mean = market$mu, sd = sqrt(market$sig2)) # numerical (Monte Carlo) prior -monteCarlo <- emptyMatrix +monteCarlo <- list() monteCarlo$J <- 100000 monteCarlo$X <- market$rnd(monteCarlo$J) monteCarlo$p <- normalizeProb(1 / monteCarlo$J * ones(monteCarlo$J, 1)) # numerical (Gauss-Hermite grid) prior -ghqMesh <- emptyMatrix +ghqMesh <- list() # rescale GH zeros so they belong to [0,1] tmp <- (ghqx - min(ghqx)) / (max(ghqx) - min(ghqx)) @@ -46,11 +46,11 @@ # Entropy posterior from extreme view on expectation ################################################################################ # view of the analyst -view <- emptyMatrix +view <- list() view$mu <- -3.0 # analytical (known since normal model has analytical solution) -truePosterior <- emptyMatrix +truePosterior <- list() truePosterior <- Prior2Posterior(market$mu, 1, view$mu, market$sig2, 0) truePosterior$pdf <- function(x) dnorm(x, truePosterior$M_, sqrt(truePosterior$S_)) @@ -58,8 +58,8 @@ # numerical (Monte Carlo) Aeq <- rbind(ones(1, monteCarlo$J), t(monteCarlo$X)) beq <- rbind(1, view$mu) -monteCarloOptimResult <- EntropyProg(monteCarlo$p, emptyMatrix, emptyMatrix, Aeq, - beq) +monteCarloOptimResult <- EntropyProg(monteCarlo$p, emptyMatrix, emptyMatrix, + Aeq, beq) monteCarlo$p_ <- monteCarloOptimResult$p_ monteCarlo$KLdiv <- monteCarloOptimResult$optimizationPerformance$ml @@ -83,17 +83,17 @@ # Monte Carlo dev.new() plotDataMC <- PHist(monteCarlo$X, monteCarlo$p_, 50, main = "Monte Carlo", - xlim = c(xmin, xmax), ylim = c(0, ymax)) + xlim = c(xmin, xmax), ylim = c(0, ymax)) lines(xmesh, market$pdf(xmesh), type = "l", col = "blue") lines(xmesh, truePosterior$pdf(xmesh), type = "l", col = "red") lines(0.0, 0.0, type = "p", pch = 17, col = "blue") -lines(view.mu, 0.0, type = "p", pch = 17, col = "red") +lines(view$mu, 0.0, type = "p", pch = 17, col = "red") # Gauss Hermite Grid dev.new() plotDataGHQ <- PHist(data.matrix(ghqMesh$X), ghqMesh$p_, 50, main = "Gauss-Hermite grid", - xlim = c(xmin, xmax), ylim = c(0, ymax)) + xlim = c(xmin, xmax), ylim = c(0, ymax)) lines(xmesh, market$pdf(xmesh), type = "l", col = "blue") lines(xmesh, truePosterior$pdf(xmesh), type = "l", col = "red") lines(0.0, 0.0, type = "p", pch = 17, col = "blue") From noreply at r-forge.r-project.org Wed Jun 24 20:25:43 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 24 Jun 2015 20:25:43 +0200 (CEST) Subject: [Returnanalytics-commits] r3736 - pkg/Dowd/R Message-ID: <20150624182543.C7FBF1879AB@r-forge.r-project.org> Author: dacharya Date: 2015-06-24 20:25:43 +0200 (Wed, 24 Jun 2015) New Revision: 3736 Modified: pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R Log: Missing return added. Modified: pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R =================================================================== --- pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R 2015-06-24 07:37:27 UTC (rev 3735) +++ pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R 2015-06-24 18:25:43 UTC (rev 3736) @@ -59,6 +59,7 @@ y<- sum(approximate.copula.differential) * dw + return(y) } GaussianCopula <- function(u, v, rho, number.steps){ From noreply at r-forge.r-project.org Wed Jun 24 22:54:14 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 24 Jun 2015 22:54:14 +0200 (CEST) Subject: [Returnanalytics-commits] r3737 - pkg/Dowd Message-ID: <20150624205414.52EB11858DF@r-forge.r-project.org> Author: dacharya Date: 2015-06-24 22:54:14 +0200 (Wed, 24 Jun 2015) New Revision: 3737 Modified: pkg/Dowd/NAMESPACE Log: Insurance VaR added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-24 18:25:43 UTC (rev 3736) +++ pkg/Dowd/NAMESPACE 2015-06-24 20:54:14 UTC (rev 3737) @@ -1,55 +1,55 @@ -# Generated by roxygen2 (4.1.1): do not edit by hand - -export(ADTestStat) -export(AdjustedNormalESHotspots) -export(AdjustedNormalVaRHotspots) -export(AdjustedVarianceCovarianceES) -export(AdjustedVarianceCovarianceVaR) -export(BinomialBacktest) -export(BlancoIhleBacktest) -export(BootstrapES) -export(BootstrapESConfInterval) -export(BootstrapESFigure) -export(BootstrapVaR) -export(BootstrapVaRConfInterval) -export(BootstrapVaRFigure) -export(CdfOfSumUsingGaussianCopula) -export(CdfOfSumUsingGumbelCopula) -export(CdfOfSumUsingProductCopula) -export(ChristoffersenBacktestForIndependence) -export(ChristoffersenBacktestForUnconditionalCoverage) -export(CornishFisherES) -export(CornishFisherVaR) -export(FrechetES) -export(FrechetESPlot2DCl) -export(FrechetVaR) -export(FrechetVaRPlot2DCl) -export(GParetoES) -export(GParetoMEFPlot) -export(GParetoMultipleMEFPlot) -export(GParetoVaR) -export(GaussianCopulaVaR) -export(GumbelCopulaVaR) -export(GumbelES) -export(GumbelESPlot2DCl) -export(GumbelVaR) -export(GumbelVaRPlot2DCl) -export(HSES) -export(HSVaR) -export(HSVaRDFPerc) -export(HSVaRFigure) -export(HillEstimator) -export(HillPlot) -export(HillQuantileEstimator) -export(InsuranceVaR) -export(JarqueBeraBacktest) -export(KSTestStat) -export(KuiperTestStat) -export(LopezBacktest) -export(MEFPlot) -export(NormalQQPlot) -export(PickandsEstimator) -export(PickandsPlot) -export(ProductCopulaVaR) -export(TQQPlot) -import(bootstrap) +# Generated by roxygen2 (4.1.1): do not edit by hand + +export(ADTestStat) +export(AdjustedNormalESHotspots) +export(AdjustedNormalVaRHotspots) +export(AdjustedVarianceCovarianceES) +export(AdjustedVarianceCovarianceVaR) +export(BinomialBacktest) +export(BlancoIhleBacktest) +export(BootstrapES) +export(BootstrapESConfInterval) +export(BootstrapESFigure) +export(BootstrapVaR) +export(BootstrapVaRConfInterval) +export(BootstrapVaRFigure) +export(CdfOfSumUsingGaussianCopula) +export(CdfOfSumUsingGumbelCopula) +export(CdfOfSumUsingProductCopula) +export(ChristoffersenBacktestForIndependence) +export(ChristoffersenBacktestForUnconditionalCoverage) +export(CornishFisherES) +export(CornishFisherVaR) +export(FrechetES) +export(FrechetESPlot2DCl) +export(FrechetVaR) +export(FrechetVaRPlot2DCl) +export(GParetoES) +export(GParetoMEFPlot) +export(GParetoMultipleMEFPlot) +export(GParetoVaR) +export(GaussianCopulaVaR) +export(GumbelCopulaVaR) +export(GumbelES) +export(GumbelESPlot2DCl) +export(GumbelVaR) +export(GumbelVaRPlot2DCl) +export(HSES) +export(HSVaR) +export(HSVaRDFPerc) +export(HSVaRFigure) +export(HillEstimator) +export(HillPlot) +export(HillQuantileEstimator) +export(InsuranceVaR) +export(JarqueBeraBacktest) +export(KSTestStat) +export(KuiperTestStat) +export(LopezBacktest) +export(MEFPlot) +export(NormalQQPlot) +export(PickandsEstimator) +export(PickandsPlot) +export(ProductCopulaVaR) +export(TQQPlot) +import(bootstrap) From noreply at r-forge.r-project.org Wed Jun 24 22:56:13 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 24 Jun 2015 22:56:13 +0200 (CEST) Subject: [Returnanalytics-commits] r3738 - pkg/Dowd/man Message-ID: <20150624205613.2E3DB186948@r-forge.r-project.org> Author: dacharya Date: 2015-06-24 22:56:12 +0200 (Wed, 24 Jun 2015) New Revision: 3738 Modified: pkg/Dowd/man/ADTestStat.Rd pkg/Dowd/man/AdjustedNormalESHotspots.Rd pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd pkg/Dowd/man/BinomialBacktest.Rd pkg/Dowd/man/BlancoIhleBacktest.Rd pkg/Dowd/man/BootstrapES.Rd pkg/Dowd/man/BootstrapESConfInterval.Rd pkg/Dowd/man/BootstrapESFigure.Rd pkg/Dowd/man/BootstrapVaR.Rd pkg/Dowd/man/BootstrapVaRConfInterval.Rd pkg/Dowd/man/BootstrapVaRFigure.Rd pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd pkg/Dowd/man/CdfOfSumUsingGumbelCopula.Rd pkg/Dowd/man/CdfOfSumUsingProductCopula.Rd pkg/Dowd/man/ChristoffersenBacktestForIndependence.Rd pkg/Dowd/man/ChristoffersenBacktestForUnconditionalCoverage.Rd pkg/Dowd/man/CornishFisherES.Rd pkg/Dowd/man/CornishFisherVaR.Rd pkg/Dowd/man/FrechetES.Rd pkg/Dowd/man/FrechetESPlot2DCl.Rd pkg/Dowd/man/FrechetVaR.Rd pkg/Dowd/man/FrechetVaRPlot2DCl.Rd pkg/Dowd/man/GParetoES.Rd pkg/Dowd/man/GParetoMEFPlot.Rd pkg/Dowd/man/GParetoMultipleMEFPlot.Rd pkg/Dowd/man/GParetoVaR.Rd pkg/Dowd/man/GaussianCopulaVaR.Rd pkg/Dowd/man/GumbelCopulaVaR.Rd pkg/Dowd/man/GumbelES.Rd pkg/Dowd/man/GumbelESPlot2DCl.Rd pkg/Dowd/man/GumbelVaR.Rd pkg/Dowd/man/GumbelVaRPlot2DCl.Rd pkg/Dowd/man/HSES.Rd pkg/Dowd/man/HSVaR.Rd pkg/Dowd/man/HSVaRDFPerc.Rd pkg/Dowd/man/HSVaRFigure.Rd pkg/Dowd/man/HillEstimator.Rd pkg/Dowd/man/HillPlot.Rd pkg/Dowd/man/HillQuantileEstimator.Rd pkg/Dowd/man/InsuranceVaR.Rd pkg/Dowd/man/JarqueBeraBacktest.Rd pkg/Dowd/man/KSTestStat.Rd pkg/Dowd/man/KuiperTestStat.Rd pkg/Dowd/man/LopezBacktest.Rd pkg/Dowd/man/MEFPlot.Rd pkg/Dowd/man/NormalQQPlot.Rd pkg/Dowd/man/PickandsEstimator.Rd pkg/Dowd/man/PickandsPlot.Rd pkg/Dowd/man/ProductCopulaVaR.Rd pkg/Dowd/man/TQQPlot.Rd Log: Roxygen version 4.1.0 -> 4.1.1 changed. Modified: pkg/Dowd/man/ADTestStat.Rd =================================================================== --- pkg/Dowd/man/ADTestStat.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/ADTestStat.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,45 +1,45 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/ADTestStat.R -\name{ADTestStat} -\alias{ADTestStat} -\title{Plots cumulative density for AD test and computes confidence -interval for AD test stat.} -\usage{ -ADTestStat(number.trials, sample.size, confidence.interval) -} -\arguments{ -\item{number.trials}{Number of trials} - -\item{sample.size}{Sample size} - -\item{confidence.interval}{Confidence Interval} -} -\value{ -Confidence Interval for AD test statistic -} -\description{ -Anderson-Darling(AD) test can be used to carry out distribution equality test and is -similar to Kolmogorov-Smirnov test. AD test statistic is defined as: -\deqn{A^2=n\int_{-\infty}^{\infty}\frac{[\hat{F}(x)-F(x)]^2}{F(x)[1-F(x)]}dF(x)} -which is equivalent to -\deqn{=-n-\frac{1}{n}\sum_{i=1}^n(2i-1)[\ln F(X_i)+\ln(1-F(X_{n+1-i}))]} -} -\examples{ -# Probability that the VaR model is correct for 3 failures, 100 number - # observations and 95\% confidence level - ADTestStat(1000, 100, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. - -Anderson, T.W. and Darling, D.A. Asymptotic Theory of Certain Goodness of -Fit Criteria Based on Stochastic Processes, The Annals of Mathematical -Statistics, 23(2), 1952, p. 193-212. - -Kvam, P.H. and Vidakovic, B. Nonparametric Statistics with Applications to -Science and Engineering, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/ADTestStat.R +\name{ADTestStat} +\alias{ADTestStat} +\title{Plots cumulative density for AD test and computes confidence +interval for AD test stat.} +\usage{ +ADTestStat(number.trials, sample.size, confidence.interval) +} +\arguments{ +\item{number.trials}{Number of trials} + +\item{sample.size}{Sample size} + +\item{confidence.interval}{Confidence Interval} +} +\value{ +Confidence Interval for AD test statistic +} +\description{ +Anderson-Darling(AD) test can be used to carry out distribution equality test and is +similar to Kolmogorov-Smirnov test. AD test statistic is defined as: +\deqn{A^2=n\int_{-\infty}^{\infty}\frac{[\hat{F}(x)-F(x)]^2}{F(x)[1-F(x)]}dF(x)} +which is equivalent to +\deqn{=-n-\frac{1}{n}\sum_{i=1}^n(2i-1)[\ln F(X_i)+\ln(1-F(X_{n+1-i}))]} +} +\examples{ +# Probability that the VaR model is correct for 3 failures, 100 number + # observations and 95\% confidence level + ADTestStat(1000, 100, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Anderson, T.W. and Darling, D.A. Asymptotic Theory of Certain Goodness of +Fit Criteria Based on Stochastic Processes, The Annals of Mathematical +Statistics, 23(2), 1952, p. 193-212. + +Kvam, P.H. and Vidakovic, B. Nonparametric Statistics with Applications to +Science and Engineering, Wiley, 2007. +} + Modified: pkg/Dowd/man/AdjustedNormalESHotspots.Rd =================================================================== --- pkg/Dowd/man/AdjustedNormalESHotspots.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/AdjustedNormalESHotspots.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,46 +1,46 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/AdjustedNormalESHotspots.R -\name{AdjustedNormalESHotspots} -\alias{AdjustedNormalESHotspots} -\title{Hotspots for ES adjusted by Cornish-Fisher correction} -\usage{ -AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\arguments{ -\item{vc.matrix}{Variance covariance matrix for returns} - -\item{mu}{Vector of expected position returns} - -\item{skew}{Return skew} - -\item{kurtosis}{Return kurtosis} - -\item{positions}{Vector of positions} - -\item{cl}{Confidence level and is scalar} - -\item{hp}{Holding period and is scalar} -} -\description{ -Estimates the ES hotspots (or vector of incremental ESs) for a -portfolio with portfolio return adjusted for non-normality by Cornish-Fisher -corerction, for specified confidence level and holding period. -} -\examples{ -# Hotspots for ES for randomly generated portfolio - vc.matrix <- matrix(rnorm(16),4,4) - mu <- rnorm(4) - skew <- .5 - kurtosis <- 1.2 - positions <- c(5,2,6,10) - cl <- .95 - hp <- 280 - AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AdjustedNormalESHotspots.R +\name{AdjustedNormalESHotspots} +\alias{AdjustedNormalESHotspots} +\title{Hotspots for ES adjusted by Cornish-Fisher correction} +\usage{ +AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Return skew} + +\item{kurtosis}{Return kurtosis} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar} +} +\description{ +Estimates the ES hotspots (or vector of incremental ESs) for a +portfolio with portfolio return adjusted for non-normality by Cornish-Fisher +corerction, for specified confidence level and holding period. +} +\examples{ +# Hotspots for ES for randomly generated portfolio + vc.matrix <- matrix(rnorm(16),4,4) + mu <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,10) + cl <- .95 + hp <- 280 + AdjustedNormalESHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd =================================================================== --- pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/AdjustedNormalVaRHotspots.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,46 +1,46 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/AdjustedNormalVaRHotspots.R -\name{AdjustedNormalVaRHotspots} -\alias{AdjustedNormalVaRHotspots} -\title{Hotspots for VaR adjusted by Cornish-Fisher correction} -\usage{ -AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\arguments{ -\item{vc.matrix}{Variance covariance matrix for returns} - -\item{mu}{Vector of expected position returns} - -\item{skew}{Return skew} - -\item{kurtosis}{Return kurtosis} - -\item{positions}{Vector of positions} - -\item{cl}{Confidence level and is scalar} - -\item{hp}{Holding period and is scalar} -} -\description{ -Estimates the VaR hotspots (or vector of incremental VaRs) for a -portfolio with portfolio return adjusted for non-normality by Cornish-Fisher -corerction, for specified confidence level and holding period. -} -\examples{ -# Hotspots for ES for randomly generated portfolio - vc.matrix <- matrix(rnorm(16),4,4) - mu <- rnorm(4) - skew <- .5 - kurtosis <- 1.2 - positions <- c(5,2,6,10) - cl <- .95 - hp <- 280 - AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AdjustedNormalVaRHotspots.R +\name{AdjustedNormalVaRHotspots} +\alias{AdjustedNormalVaRHotspots} +\title{Hotspots for VaR adjusted by Cornish-Fisher correction} +\usage{ +AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Return skew} + +\item{kurtosis}{Return kurtosis} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar} +} +\description{ +Estimates the VaR hotspots (or vector of incremental VaRs) for a +portfolio with portfolio return adjusted for non-normality by Cornish-Fisher +corerction, for specified confidence level and holding period. +} +\examples{ +# Hotspots for ES for randomly generated portfolio + vc.matrix <- matrix(rnorm(16),4,4) + mu <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,10) + cl <- .95 + hp <- 280 + AdjustedNormalVaRHotspots(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd =================================================================== --- pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/AdjustedVarianceCovarianceES.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,46 +1,46 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/AdjustedVarianceCovarianceES.R -\name{AdjustedVarianceCovarianceES} -\alias{AdjustedVarianceCovarianceES} -\title{Cornish-Fisher adjusted Variance-Covariance ES} -\usage{ -AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\arguments{ -\item{vc.matrix}{Variance covariance matrix for returns} - -\item{mu}{Vector of expected position returns} - -\item{skew}{Return skew} - -\item{kurtosis}{Return kurtosis} - -\item{positions}{Vector of positions} - -\item{cl}{Confidence level and is scalar} - -\item{hp}{Holding period and is scalar} -} -\description{ -Function estimates the Variance-Covariance ES of a multi-asset -portfolio using the Cornish - Fisher adjustment for portfolio return -non-normality, for specified confidence level and holding period. -} -\examples{ -# Variance-covariance ES for randomly generated portfolio - vc.matrix <- matrix(rnorm(16), 4, 4) - mu <- rnorm(4) - skew <- .5 - kurtosis <- 1.2 - positions <- c(5, 2, 6, 10) - cl <- .95 - hp <- 280 - AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AdjustedVarianceCovarianceES.R +\name{AdjustedVarianceCovarianceES} +\alias{AdjustedVarianceCovarianceES} +\title{Cornish-Fisher adjusted Variance-Covariance ES} +\usage{ +AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Return skew} + +\item{kurtosis}{Return kurtosis} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar} +} +\description{ +Function estimates the Variance-Covariance ES of a multi-asset +portfolio using the Cornish - Fisher adjustment for portfolio return +non-normality, for specified confidence level and holding period. +} +\examples{ +# Variance-covariance ES for randomly generated portfolio + vc.matrix <- matrix(rnorm(16), 4, 4) + mu <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5, 2, 6, 10) + cl <- .95 + hp <- 280 + AdjustedVarianceCovarianceES(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd =================================================================== --- pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/AdjustedVarianceCovarianceVaR.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,44 +1,44 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/AdjustedVarianceCovarianceVaR.R -\name{AdjustedVarianceCovarianceVaR} -\alias{AdjustedVarianceCovarianceVaR} -\title{Cornish-Fisher adjusted variance-covariance VaR} -\usage{ -AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\arguments{ -\item{vc.matrix}{Assumed variance covariance matrix for returns} - -\item{mu}{Vector of expected position returns} - -\item{skew}{Portfolio return skewness} - -\item{kurtosis}{Portfolio return kurtosis} - -\item{positions}{Vector of positions} - -\item{cl}{Confidence level and is scalar or vector} - -\item{hp}{Holding period and is scalar or vector} -} -\description{ -Estimates the variance-covariance VaR of a multi-asset portfolio using the Cornish-Fisher adjustment for portfolio-return non-normality, for specified confidence level and holding period. -} -\examples{ -# Variance-covariance for randomly generated portfolio - vc.matrix <- matrix(rnorm(16),4,4) - mu <- rnorm(4) - skew <- .5 - kurtosis <- 1.2 - positions <- c(5,2,6,10) - cl <- .95 - hp <- 280 - AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AdjustedVarianceCovarianceVaR.R +\name{AdjustedVarianceCovarianceVaR} +\alias{AdjustedVarianceCovarianceVaR} +\title{Cornish-Fisher adjusted variance-covariance VaR} +\usage{ +AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\arguments{ +\item{vc.matrix}{Assumed variance covariance matrix for returns} + +\item{mu}{Vector of expected position returns} + +\item{skew}{Portfolio return skewness} + +\item{kurtosis}{Portfolio return kurtosis} + +\item{positions}{Vector of positions} + +\item{cl}{Confidence level and is scalar or vector} + +\item{hp}{Holding period and is scalar or vector} +} +\description{ +Estimates the variance-covariance VaR of a multi-asset portfolio using the Cornish-Fisher adjustment for portfolio-return non-normality, for specified confidence level and holding period. +} +\examples{ +# Variance-covariance for randomly generated portfolio + vc.matrix <- matrix(rnorm(16),4,4) + mu <- rnorm(4) + skew <- .5 + kurtosis <- 1.2 + positions <- c(5,2,6,10) + cl <- .95 + hp <- 280 + AdjustedVarianceCovarianceVaR(vc.matrix, mu, skew, kurtosis, positions, cl, hp) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BinomialBacktest.Rd =================================================================== --- pkg/Dowd/man/BinomialBacktest.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/BinomialBacktest.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,41 +1,41 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BinomialBacktest.R -\name{BinomialBacktest} -\alias{BinomialBacktest} -\title{Carries out the binomial backtest for a VaR risk measurement model.} -\usage{ -BinomialBacktest(x, n, cl) -} -\arguments{ -\item{x}{Number of failures} - -\item{n}{Number of observations} - -\item{cl}{Confidence level for VaR} -} -\value{ -Probability that the VaR model is correct -} -\description{ -The basic idea behind binomial backtest (also called basic frequency -test) is to test whether the observed frequency of losses that exceed VaR is -consistent with the frequency of tail losses predicted by the mode. Binomial -Backtest carries out the binomial backtest for a VaR risk measurement model -for specified VaR confidence level and for a one-sided alternative -hypothesis (H1). -} -\examples{ -# Probability that the VaR model is correct for 3 failures, 100 number - # observations and 95\% confidence level - BinomialBacktest(55, 1000, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, Kevin. Measuring Market Risk, Wiley, 2007. - -Kupiec, Paul. Techniques for verifying the accuracy of risk measurement -models, Journal of Derivatives, Winter 1995, p. 79. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BinomialBacktest.R +\name{BinomialBacktest} +\alias{BinomialBacktest} +\title{Carries out the binomial backtest for a VaR risk measurement model.} +\usage{ +BinomialBacktest(x, n, cl) +} +\arguments{ +\item{x}{Number of failures} + +\item{n}{Number of observations} + +\item{cl}{Confidence level for VaR} +} +\value{ +Probability that the VaR model is correct +} +\description{ +The basic idea behind binomial backtest (also called basic frequency +test) is to test whether the observed frequency of losses that exceed VaR is +consistent with the frequency of tail losses predicted by the mode. Binomial +Backtest carries out the binomial backtest for a VaR risk measurement model +for specified VaR confidence level and for a one-sided alternative +hypothesis (H1). +} +\examples{ +# Probability that the VaR model is correct for 3 failures, 100 number + # observations and 95\% confidence level + BinomialBacktest(55, 1000, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Kupiec, Paul. Techniques for verifying the accuracy of risk measurement +models, Journal of Derivatives, Winter 1995, p. 79. +} + Modified: pkg/Dowd/man/BlancoIhleBacktest.Rd =================================================================== --- pkg/Dowd/man/BlancoIhleBacktest.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/BlancoIhleBacktest.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,42 +1,42 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BlancoIhleBacktest.R -\name{BlancoIhleBacktest} -\alias{BlancoIhleBacktest} -\title{Blanco-Ihle forecast evaluation backtest measure} -\usage{ -BlancoIhleBacktest(Ra, Rb, Rc, cl) -} -\arguments{ -\item{Ra}{Vector of a portfolio profit and loss} - -\item{Rb}{Vector of corresponding VaR forecasts} - -\item{Rc}{Vector of corresponding Expected Tailed Loss forecasts} - -\item{cl}{VaR confidence interval} -} -\value{ -First Blanco-Ihle score measure. -} -\description{ -Derives the Blanco-Ihle forecast evaluation loss measure for a VaR -risk measurement model. -} -\examples{ -# Has to be modified with appropriate data: - # Blanco-Ihle Backtest For Independence for given parameters - a <- rnorm(1*100) - b <- abs(rnorm(1*100))+2 - c <- abs(rnorm(1*100))+2 - BlancoIhleBacktest(a, b, c, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, Kevin. Measuring Market Risk, Wiley, 2007. - -Blanco, C. and Ihle, G. How Good is Your Var? Using Backtesting to Assess -System Performance. Financial Engineering News, 1999. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BlancoIhleBacktest.R +\name{BlancoIhleBacktest} +\alias{BlancoIhleBacktest} +\title{Blanco-Ihle forecast evaluation backtest measure} +\usage{ +BlancoIhleBacktest(Ra, Rb, Rc, cl) +} +\arguments{ +\item{Ra}{Vector of a portfolio profit and loss} + +\item{Rb}{Vector of corresponding VaR forecasts} + +\item{Rc}{Vector of corresponding Expected Tailed Loss forecasts} + +\item{cl}{VaR confidence interval} +} +\value{ +First Blanco-Ihle score measure. +} +\description{ +Derives the Blanco-Ihle forecast evaluation loss measure for a VaR +risk measurement model. +} +\examples{ +# Has to be modified with appropriate data: + # Blanco-Ihle Backtest For Independence for given parameters + a <- rnorm(1*100) + b <- abs(rnorm(1*100))+2 + c <- abs(rnorm(1*100))+2 + BlancoIhleBacktest(a, b, c, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Blanco, C. and Ihle, G. How Good is Your Var? Using Backtesting to Assess +System Performance. Financial Engineering News, 1999. +} + Modified: pkg/Dowd/man/BootstrapES.Rd =================================================================== --- pkg/Dowd/man/BootstrapES.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/BootstrapES.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,34 +1,34 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapES.R -\name{BootstrapES} -\alias{BootstrapES} -\title{Bootstrapped ES for specified confidence level} -\usage{ -BootstrapES(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.resamples}{Number of samples to be taken in bootstrap procedure} - -\item{cl}{Number corresponding to Expected Shortfall confidence level} -} -\value{ -Bootstrapped Expected Shortfall -} -\description{ -Estimates the bootstrapped ES for confidence level and holding period -implied by data frequency. -} -\examples{ -# Estimates bootstrapped ES for given parameters - a <- rnorm(100) # generate a random profit/loss vector - BootstrapVaR(a, 50, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapES.R +\name{BootstrapES} +\alias{BootstrapES} +\title{Bootstrapped ES for specified confidence level} +\usage{ +BootstrapES(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Expected Shortfall confidence level} +} +\value{ +Bootstrapped Expected Shortfall +} +\description{ +Estimates the bootstrapped ES for confidence level and holding period +implied by data frequency. +} +\examples{ +# Estimates bootstrapped ES for given parameters + a <- rnorm(100) # generate a random profit/loss vector + BootstrapVaR(a, 50, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapESConfInterval.Rd =================================================================== --- pkg/Dowd/man/BootstrapESConfInterval.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/BootstrapESConfInterval.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,36 +1,36 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapESConfInterval.R -\name{BootstrapESConfInterval} -\alias{BootstrapESConfInterval} -\title{Bootstrapped ES Confidence Interval} -\usage{ -BootstrapESConfInterval(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.resamples}{Number of samples to be taken in bootstrap procedure} - -\item{cl}{Number corresponding to Expected Shortfall confidence level} -} -\value{ -90% Confidence interval for bootstrapped ES -} -\description{ -Estimates the 90% confidence interval for bootstrapped ES, for confidence -level and holding period implied by data frequency. -} -\examples{ -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped ES for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapESConfInterval(Ra, 50, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapESConfInterval.R +\name{BootstrapESConfInterval} +\alias{BootstrapESConfInterval} +\title{Bootstrapped ES Confidence Interval} +\usage{ +BootstrapESConfInterval(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Expected Shortfall confidence level} +} +\value{ +90% Confidence interval for bootstrapped ES +} +\description{ +Estimates the 90% confidence interval for bootstrapped ES, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped ES for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapESConfInterval(Ra, 50, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapESFigure.Rd =================================================================== --- pkg/Dowd/man/BootstrapESFigure.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/BootstrapESFigure.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,33 +1,33 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapESFigure.R -\name{BootstrapESFigure} -\alias{BootstrapESFigure} -\title{Plots figure of bootstrapped ES} -\usage{ -BootstrapESFigure(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.resamples}{Number of samples to be taken in bootstrap procedure} - -\item{cl}{Number corresponding to Expected Shortfall confidence level} -} -\description{ -Plots figure for the bootstrapped ES, for confidence -level and holding period implied by data frequency. -} -\examples{ -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped ES for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapESFigure(Ra, 500, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapESFigure.R +\name{BootstrapESFigure} +\alias{BootstrapESFigure} +\title{Plots figure of bootstrapped ES} +\usage{ +BootstrapESFigure(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Expected Shortfall confidence level} +} +\description{ +Plots figure for the bootstrapped ES, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped ES for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapESFigure(Ra, 500, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapVaR.Rd =================================================================== --- pkg/Dowd/man/BootstrapVaR.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/BootstrapVaR.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,34 +1,34 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapVaR.R -\name{BootstrapVaR} -\alias{BootstrapVaR} -\title{Bootstrapped VaR for specified confidence level} -\usage{ -BootstrapVaR(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.resamples}{Number of samples to be taken in bootstrap procedure} - -\item{cl}{Number corresponding to Value at Risk confidence level} -} -\value{ -Bootstrapped VaR -} -\description{ -Estimates the bootstrapped VaR for confidence level and holding period -implied by data frequency. -} -\examples{ -# Estimates bootstrapped VaR for given parameters - a <- rnorm(100) # generate a random profit/loss vector - BootstrapES(a, 50, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapVaR.R +\name{BootstrapVaR} +\alias{BootstrapVaR} +\title{Bootstrapped VaR for specified confidence level} +\usage{ +BootstrapVaR(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Value at Risk confidence level} +} +\value{ +Bootstrapped VaR +} +\description{ +Estimates the bootstrapped VaR for confidence level and holding period +implied by data frequency. +} +\examples{ +# Estimates bootstrapped VaR for given parameters + a <- rnorm(100) # generate a random profit/loss vector + BootstrapES(a, 50, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapVaRConfInterval.Rd =================================================================== --- pkg/Dowd/man/BootstrapVaRConfInterval.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/BootstrapVaRConfInterval.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,36 +1,36 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapVaRConfInterval.R -\name{BootstrapVaRConfInterval} -\alias{BootstrapVaRConfInterval} -\title{Bootstrapped VaR Confidence Interval} -\usage{ -BootstrapVaRConfInterval(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.resamples}{Number of samples to be taken in bootstrap procedure} - -\item{cl}{Number corresponding to Value at Risk confidence level} -} -\value{ -90% Confidence interval for bootstrapped VaR -} -\description{ -Estimates the 90% confidence interval for bootstrapped VaR, for confidence -level and holding period implied by data frequency. -} -\examples{ -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped Var for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapVaRConfInterval(Ra, 500, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapVaRConfInterval.R +\name{BootstrapVaRConfInterval} +\alias{BootstrapVaRConfInterval} +\title{Bootstrapped VaR Confidence Interval} +\usage{ +BootstrapVaRConfInterval(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Value at Risk confidence level} +} +\value{ +90% Confidence interval for bootstrapped VaR +} +\description{ +Estimates the 90% confidence interval for bootstrapped VaR, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped Var for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapVaRConfInterval(Ra, 500, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/BootstrapVaRFigure.Rd =================================================================== --- pkg/Dowd/man/BootstrapVaRFigure.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/BootstrapVaRFigure.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,33 +1,33 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/BootstrapVaRFigure.R -\name{BootstrapVaRFigure} -\alias{BootstrapVaRFigure} -\title{Plots figure of bootstrapped VaR} -\usage{ -BootstrapVaRFigure(Ra, number.resamples, cl) -} -\arguments{ -\item{Ra}{Vector corresponding to profit and loss distribution} - -\item{number.resamples}{Number of samples to be taken in bootstrap procedure} - -\item{cl}{Number corresponding to Value at Risk confidence level} -} -\description{ -Plots figure for the bootstrapped VaR, for confidence -level and holding period implied by data frequency. -} -\examples{ -# To be modified with appropriate data. - # Estimates 90\% confidence interval for bootstrapped VaR for 95\% - # confidence interval - Ra <- rnorm(1000) - BootstrapESFigure(Ra, 500, 0.95) -} -\author{ -Dinesh Acharya -} -\references{ -Dowd, K. Measuring Market Risk, Wiley, 2007. -} - +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BootstrapVaRFigure.R +\name{BootstrapVaRFigure} +\alias{BootstrapVaRFigure} +\title{Plots figure of bootstrapped VaR} +\usage{ +BootstrapVaRFigure(Ra, number.resamples, cl) +} +\arguments{ +\item{Ra}{Vector corresponding to profit and loss distribution} + +\item{number.resamples}{Number of samples to be taken in bootstrap procedure} + +\item{cl}{Number corresponding to Value at Risk confidence level} +} +\description{ +Plots figure for the bootstrapped VaR, for confidence +level and holding period implied by data frequency. +} +\examples{ +# To be modified with appropriate data. + # Estimates 90\% confidence interval for bootstrapped VaR for 95\% + # confidence interval + Ra <- rnorm(1000) + BootstrapESFigure(Ra, 500, 0.95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + Modified: pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd =================================================================== --- pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd 2015-06-24 20:54:14 UTC (rev 3737) +++ pkg/Dowd/man/CdfOfSumUsingGaussianCopula.Rd 2015-06-24 20:56:12 UTC (rev 3738) @@ -1,49 +1,49 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/CdfOfSumUsingGaussianCopula.R -\name{CdfOfSumUsingGaussianCopula} -\alias{CdfOfSumUsingGaussianCopula} -\title{Derives prob ( X + Y < quantile) using Gumbel copula} -\usage{ -CdfOfSumUsingGaussianCopula(quantile, mu1, mu2, sigma1, sigma2, rho, - number.steps.in.copula) -} -\arguments{ -\item{quantile}{Portfolio quantile (or negative of Var, if X, Y are position P/Ls)} - -\item{mu1}{Mean of Profit/Loss on first position} - -\item{mu2}{Mean of Profit/Loss on second position} - [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3738 From noreply at r-forge.r-project.org Wed Jun 24 22:56:39 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 24 Jun 2015 22:56:39 +0200 (CEST) Subject: [Returnanalytics-commits] r3739 - pkg/Dowd/R Message-ID: <20150624205639.3C1F9186948@r-forge.r-project.org> Author: dacharya Date: 2015-06-24 22:56:39 +0200 (Wed, 24 Jun 2015) New Revision: 3739 Modified: pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R Log: Example modified to make check faster. Modified: pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R =================================================================== --- pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R 2015-06-24 20:56:12 UTC (rev 3738) +++ pkg/Dowd/R/CdfOfSumUsingGaussianCopula.R 2015-06-24 20:56:39 UTC (rev 3739) @@ -24,7 +24,7 @@ #' #' # Prob ( X + Y < q ) using Gaussian Copula for X with mean 2.3 and std. .2 #' # and Y with mean 4.5 and std. 1.5 with beta 1.2 at 0.9 quantile -#' CdfOfSumUsingGaussianCopula(0.9, 2.3, 4.5, 1.2, 1.5, 0.6, 100) +#' CdfOfSumUsingGaussianCopula(0.9, 2.3, 4.5, 1.2, 1.5, 0.6, 15) #' #' @export CdfOfSumUsingGaussianCopula <- function(quantile, mu1, mu2, sigma1, sigma2, rho, number.steps.in.copula){ @@ -95,4 +95,4 @@ y <- sum(term) * dx * dy / (2 * pi * (1 - rho^2)^0.5) return(y) -} \ No newline at end of file +} From noreply at r-forge.r-project.org Wed Jun 24 23:13:47 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 24 Jun 2015 23:13:47 +0200 (CEST) Subject: [Returnanalytics-commits] r3740 - pkg/Dowd/tests/testthat Message-ID: <20150624211347.EE19B186949@r-forge.r-project.org> Author: dacharya Date: 2015-06-24 23:13:47 +0200 (Wed, 24 Jun 2015) New Revision: 3740 Added: pkg/Dowd/tests/testthat/testCdfOfSumUsingGaussianCopula.R Log: Test for CdfOfSumUsingGaussianCopula. Added: pkg/Dowd/tests/testthat/testCdfOfSumUsingGaussianCopula.R =================================================================== --- pkg/Dowd/tests/testthat/testCdfOfSumUsingGaussianCopula.R (rev 0) +++ pkg/Dowd/tests/testthat/testCdfOfSumUsingGaussianCopula.R 2015-06-24 21:13:47 UTC (rev 3740) @@ -0,0 +1,8 @@ +test_that("Cdf Of Sum Using Gaussian Copula.",{ + # Success - 1 + expect_equal(0.3446, CdfOfSumUsingGaussianCopula(0.9, 0.3, 1.5, 1.2, 1.5, 0.6, 25), tolerance=0.001) + + # Success - 2 + expect_equal(0.9939, CdfOfSumUsingGaussianCopula(0.1, -0.3, -3, .2, 1.5, 0.6, 10), tolerance=0.001) + +}) Property changes on: pkg/Dowd/tests/testthat/testCdfOfSumUsingGaussianCopula.R ___________________________________________________________________ Added: svn:executable + * From noreply at r-forge.r-project.org Wed Jun 24 23:43:26 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 24 Jun 2015 23:43:26 +0200 (CEST) Subject: [Returnanalytics-commits] r3741 - pkg/Dowd/R Message-ID: <20150624214326.E33B3186948@r-forge.r-project.org> Author: dacharya Date: 2015-06-24 23:43:26 +0200 (Wed, 24 Jun 2015) New Revision: 3741 Modified: pkg/Dowd/R/CdfOfSumUsingGumbelCopula.R Log: Missing return added. Modified: pkg/Dowd/R/CdfOfSumUsingGumbelCopula.R =================================================================== --- pkg/Dowd/R/CdfOfSumUsingGumbelCopula.R 2015-06-24 21:13:47 UTC (rev 3740) +++ pkg/Dowd/R/CdfOfSumUsingGumbelCopula.R 2015-06-24 21:43:26 UTC (rev 3741) @@ -62,6 +62,7 @@ y<- sum(approximate.copula.differential) * dw + return(y) } GumbelCopula <- function(u, v, beta){ From noreply at r-forge.r-project.org Wed Jun 24 23:43:48 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 24 Jun 2015 23:43:48 +0200 (CEST) Subject: [Returnanalytics-commits] r3742 - pkg/Dowd/R Message-ID: <20150624214348.C7E7D186948@r-forge.r-project.org> Author: dacharya Date: 2015-06-24 23:43:48 +0200 (Wed, 24 Jun 2015) New Revision: 3742 Modified: pkg/Dowd/R/CdfOfSumUsingProductCopula.R Log: Missing return added. Modified: pkg/Dowd/R/CdfOfSumUsingProductCopula.R =================================================================== --- pkg/Dowd/R/CdfOfSumUsingProductCopula.R 2015-06-24 21:43:26 UTC (rev 3741) +++ pkg/Dowd/R/CdfOfSumUsingProductCopula.R 2015-06-24 21:43:48 UTC (rev 3742) @@ -55,6 +55,8 @@ y<- sum(approximate.copula.differential) * dw + return(y) + } ProductCopula <- function(u, v){ From noreply at r-forge.r-project.org Thu Jun 25 00:24:19 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 25 Jun 2015 00:24:19 +0200 (CEST) Subject: [Returnanalytics-commits] r3743 - pkg/Dowd/tests/testthat Message-ID: <20150624222419.5B571187835@r-forge.r-project.org> Author: dacharya Date: 2015-06-25 00:24:18 +0200 (Thu, 25 Jun 2015) New Revision: 3743 Added: pkg/Dowd/tests/testthat/testCdfOfSumUsingGumbelCopula.R Log: Test for CdfOfSumUsingGumbelCopula. Added: pkg/Dowd/tests/testthat/testCdfOfSumUsingGumbelCopula.R =================================================================== --- pkg/Dowd/tests/testthat/testCdfOfSumUsingGumbelCopula.R (rev 0) +++ pkg/Dowd/tests/testthat/testCdfOfSumUsingGumbelCopula.R 2015-06-24 22:24:18 UTC (rev 3743) @@ -0,0 +1,10 @@ +test_that("Cdf Of Sum Using Gumbel Copula.",{ + # Success - 1 + expect_equal(0.0259, CdfOfSumUsingGumbelCopula(0.1, 1.3, 2.5, 1.2, 1.5, 1.2), tolerance=0.001) + + # Success - 2 + expect_equal(0.8896, CdfOfSumUsingGumbelCopula(0.1, 1.5, -2.5, 0.4, 5.1, 2.1), tolerance=0.001) + + # Error - 1 + expect_error(val <- CdfOfSumUsingGumbelCopula(0.1, 1.5, -2.5, 0.4, 5.1, .9)) +}) Property changes on: pkg/Dowd/tests/testthat/testCdfOfSumUsingGumbelCopula.R ___________________________________________________________________ Added: svn:executable + * From noreply at r-forge.r-project.org Thu Jun 25 00:54:29 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 25 Jun 2015 00:54:29 +0200 (CEST) Subject: [Returnanalytics-commits] r3744 - pkg/Dowd/tests/testthat Message-ID: <20150624225430.02AD9183F12@r-forge.r-project.org> Author: dacharya Date: 2015-06-25 00:54:29 +0200 (Thu, 25 Jun 2015) New Revision: 3744 Added: pkg/Dowd/tests/testthat/testCdfOfSumUsingProductCopula.R Log: Test for CdfOfSumUsingProductCopula. Added: pkg/Dowd/tests/testthat/testCdfOfSumUsingProductCopula.R =================================================================== --- pkg/Dowd/tests/testthat/testCdfOfSumUsingProductCopula.R (rev 0) +++ pkg/Dowd/tests/testthat/testCdfOfSumUsingProductCopula.R 2015-06-24 22:54:29 UTC (rev 3744) @@ -0,0 +1,8 @@ +test_that("Cdf Of Sum Using Product Copula.",{ + # Success - 1 + expect_equal(0.1628, CdfOfSumUsingProductCopula(0.9, .3, 2.1, .3, 1.5), tolerance=0.001) + + # Success - 2 + expect_equal(0.5839, CdfOfSumUsingProductCopula(0.1, 1.5, -2.5, 0.4, 5.1), tolerance=0.001) + +}) \ No newline at end of file From noreply at r-forge.r-project.org Thu Jun 25 10:43:25 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 25 Jun 2015 10:43:25 +0200 (CEST) Subject: [Returnanalytics-commits] r3745 - in pkg/Meucci: . R data demo man Message-ID: <20150625084325.934E9185E99@r-forge.r-project.org> Author: xavierv Date: 2015-06-25 10:43:25 +0200 (Thu, 25 Jun 2015) New Revision: 3745 Added: pkg/Meucci/R/EffectiveBets.R pkg/Meucci/R/InverseCallTransformation.R pkg/Meucci/R/Torsion.R pkg/Meucci/data/JGB.rda pkg/Meucci/data/ghqx.rda pkg/Meucci/data/linRet.rda pkg/Meucci/data/pseudodata.rda pkg/Meucci/demo/S_AnalyzeJGBrates.R pkg/Meucci/demo/S_MainDiversification.R pkg/Meucci/man/EffectiveBets.Rd pkg/Meucci/man/InverseCallTransformation.Rd pkg/Meucci/man/JGB.Rd pkg/Meucci/man/PHist.Rd pkg/Meucci/man/Torsion.Rd pkg/Meucci/man/ghqx.Rd pkg/Meucci/man/linRet.Rd pkg/Meucci/man/pseudodata.Rd Removed: pkg/Meucci/man/pHist.Rd Modified: pkg/Meucci/NAMESPACE pkg/Meucci/R/PlotDistributions.R pkg/Meucci/R/RankingInformationFunctions.R pkg/Meucci/demo/InvariantProjection.R pkg/Meucci/demo/MeanDiversificationFrontier.R pkg/Meucci/demo/Prior2Posterior.R pkg/Meucci/demo/RankingInformation.R pkg/Meucci/demo/logToArithmeticCovariance.R pkg/Meucci/man/PlotFrontier.Rd pkg/Meucci/man/PlotResults.Rd pkg/Meucci/man/RIEfficientFrontier.Rd pkg/Meucci/man/ViewRanking.Rd Log: - Added files missing. Fixed and formatted scripts up to RankingInformation demo Modified: pkg/Meucci/NAMESPACE =================================================================== --- pkg/Meucci/NAMESPACE 2015-06-24 22:54:29 UTC (rev 3744) +++ pkg/Meucci/NAMESPACE 2015-06-25 08:43:25 UTC (rev 3745) @@ -51,6 +51,7 @@ export(PlotDistributions) export(PlotFrontier) export(PlotMarginalsNormalInverseWishart) +export(PlotResults) export(PlotVolVsCompositionEfficientFrontier) export(Prior2Posterior) export(ProjectionStudentT) @@ -68,6 +69,7 @@ export(TwoDimEllipsoid) export(ViewCurveSlope) export(ViewImpliedVol) +export(ViewRanking) export(ViewRealizedVol) export(garch1f4) export(garch2f8) Added: pkg/Meucci/R/EffectiveBets.R =================================================================== --- pkg/Meucci/R/EffectiveBets.R (rev 0) +++ pkg/Meucci/R/EffectiveBets.R 2015-06-25 08:43:25 UTC (rev 3745) @@ -0,0 +1,29 @@ +#' @title computes the Effective Number of Bets and the Diversification +#' distribution +#' +#' @description computes the Effective Number of Bets and the Diversification +#' distribution, as described in A. Meucci, A. Santangelo, R. Deguest - +#' "Measuring Portfolio Diversification Based on Optimized Uncorrelated Factors" +#' +#' @param b [vector] (n_ x 1) exposures +#' @param Sigma [matrix] (n_ x n_) covariance matrix +#' @param t [matrix] (n_ x n_) torsion matrix +#' +#' @return enb [scalar] Effetive Number of Bets +#' @return p [vector] (n_ x 1) diversification distribution +#' +#' @references +#' A. Meucci, A. Santangelo, R. Deguest - "Measuring Portfolio Diversification +#' Based on Optimized Uncorrelated Factors" \url{http://symmys.com/node/599} +#' +#' See Meucci's script "EffectiveBets.m" +# +#' @author Xavier Valls \email{xaviervallspla@@gmail.com} +#' @export + +EffectiveBets <- function(b, Sigma, t) { + p <- mldivide(t(t), b) * (t %*% Sigma %*% b) / (t(b) %*% Sigma %*% b)[1]; + enb <- exp(-sum(p * log(1 + (p - 1) * (p > 1e-5)))); + + return(list(p = p, enb = enb)); +} Added: pkg/Meucci/R/InverseCallTransformation.R =================================================================== --- pkg/Meucci/R/InverseCallTransformation.R (rev 0) +++ pkg/Meucci/R/InverseCallTransformation.R 2015-06-25 08:43:25 UTC (rev 3745) @@ -0,0 +1,61 @@ +#' @title Computes the Inverse Call Transformation +#' +#' @description Computes the Inverse Call Transformation and returns shadow +#' rates, as described in A. Meucci, A. Loregian -"Neither Normal not Lognormal: +#' Modeling Interest Rates Across all Regimes". +#' +#' @param Rates [matrix] (N x length(timeseries)) number of portfolio +#' in the efficient frontier +#' @param Tau [vector] (N x 1) vector containing the times to +#' maturity corresponding to the rows of the rates matrix +#' @param Eta [scalar] Inverse-call transformation parameter +#' @param Zeta [scalar] Inverse-call transformation parameter +#' +#' @return x [vector] (NumPortf x 1) shadow rates, computed from +#' rates via inverse-call transformation +#' +#' @note Smoothing parameter s obtained as s=eta*exp(zeta*tau) +#' +#' @references +#' A. Meucci, A. Loregian - "Neither Normal not Lognormal: Modeling Interest +#' Rates Across all Regimes" \url{http://symmys.com/node/601} +#' +#' See Meucci's script "InverseCallTransformation.m". +# +#' @author Xavier Valls \email{xaviervallspla@@gmail.com} +#' @export + +InverseCallTransformation <- function(rates, tau, eta, zeta){ + + t_ <- dim(rates)[2] + x <- matrix(0, nrow(rates), ncol(rates)) + s <- eta * exp( zeta * tau ) + + + for (v in 1:length(tau)){ + # inverse call transformation + + x0 <- 0 # initialization + + CallFit <- function(tmpX, y = rates[v, t], sigma = s[v]){ + c <- BachelierCallPrice(tmpX, sigma) + return(F = y - c) + } + for (t in 1:t_){ + # fitting inverse call + x[v,t] <- lsqnonlin(fun = CallFit, x0 = x0)$x + } + } + + return(x) +} + +# Bachelier call pricing function +# Call function (zero-strike call option price profile according to the +# Bachelier pricing function) +# +# s: smoothing parameter + +BachelierCallPrice <- function( x , s){ + return(x * pnorm( x / s ) + s %*% dnorm(x / s)) +} Modified: pkg/Meucci/R/PlotDistributions.R =================================================================== --- pkg/Meucci/R/PlotDistributions.R 2015-06-24 22:54:29 UTC (rev 3744) +++ pkg/Meucci/R/PlotDistributions.R 2015-06-25 08:43:25 UTC (rev 3745) @@ -29,16 +29,16 @@ x <- as.matrix(seq(from = xl, to = xh, by = (xh - xl) / 100)) # posterior numerical - PHist(X[,n] , p_ , NBins) + PHist(X[, n], p_ , NBins) # posterior analytical - y1 <- dnorm(x , Mu_[n] , sqrt(Sigma_[n,n])) - lines(x , y1, type = "l", col = "red", xlab = "", ylab = "") + y1 <- dnorm(x, Mu_[n], sqrt(Sigma_[n,n])) + lines(x, y1, type = "l", col = "red", xlab = "", ylab = "") # prior analytical - y2 <- dnorm(x , Mu[n] ,sqrt(Sigma[n,n])) - lines(x , y2, col = "blue", xlab = "", ylab = "") + y2 <- dnorm(x, Mu[n], sqrt(Sigma[n,n])) + lines(x, y2, col = "blue", xlab = "", ylab = "") - legend(x = 1.5, y = 0.4 , legend = c("analytical","prior"), - lwd = c(0.2,0.2), lty = c(1,1), col = c("red", "blue")) + legend(x = 1.5, y = 0.4 , legend = c("analytical", "prior"), + lwd = c(0.2, 0.2), lty = c(1, 1), col = c("red", "blue")) } -} \ No newline at end of file +} Modified: pkg/Meucci/R/RankingInformationFunctions.R =================================================================== --- pkg/Meucci/R/RankingInformationFunctions.R 2015-06-24 22:54:29 UTC (rev 3744) +++ pkg/Meucci/R/RankingInformationFunctions.R 2015-06-25 08:43:25 UTC (rev 3745) @@ -1,224 +1,271 @@ # TODO: add max weights constraint to EfficientFrontier() # TODO: add computeCVaR to EfficientFrontier() -# TODO: confirm QuadProg does not have a bug (i.e. it can optimize expected returns without use dvec by adding an equality constraint) +# TODO: confirm QuadProg does not have a bug (i.e. it can optimize expected +# returns without use dvec by adding an equality constraint) -#' Plots the efficient frontier, as it appears in A. Meucci, "Fully Flexible Views: Theory and Practice", The Risk Magazine, -#' October 2008, p 100-106. +#' @title Plots the efficient frontier #' -#' @param e the NumPortf x 1 matrix of expected returns for each portfolio along the efficient frontier -#' @param s the NumPortf x 1 matrix of standard deviation of returns for each portfolio along the efficient frontier -#' @param w the NumPortf x N matrix of compositions (security weights) for each portfolio along the efficient frontier -#' -#' @references -#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158} -#' See Meucci script for "RankingInformation/PlotFrontier.m" +#' @description Plots the efficient frontier, as it appears in A. Meucci, "Fully +#' Flexible Views: Theory and Practice", The Risk Magazine, October 2008, +#' p 100-106. #' -#' @author Xavier Valls \email{flamejat@@gmail.com} -#' @export +#' @param e the NumPortf x 1 matrix of expected returns for each portfolio +#' along the efficient frontier +#' @param s the NumPortf x 1 matrix of standard deviation of returns for each +#' portfolio along the efficient frontier +#' @param w the NumPortf x N matrix of compositions (security weights) for +#' each portfolio along the efficient frontier +#' +#' @references +#' A. Meucci, "Fully Flexible Views: Theory and Practice" +#' \url{http://www.symmys.com/node/158}. See Meucci script for +#' "RankingInformation/PlotFrontier.m" +#' +#' @author Xavier Valls \email{xaviervallspla@@gmail.com} +#' @export -PlotFrontier = function( e, s, w ) -{ - xx = dim( w )[ 1 ]; - N = dim( w )[ 2 ]; - Data = t( apply( w, 1, cumsum ) ); +PlotFrontier <- function(e, s, w) { + N <- dim(w)[2] + Data <- t(apply(w, 1, cumsum)) - plot( c(min(s), 0), xlim = c( min(s) , max(s) ), ylim = c( 0, max(Data) ), - main= "frontier", xlab = " Portfolio # risk propensity", ylab = "Portfolio composition" ); - - for( n in 1 : N ) - { - x = rbind( min(s), s, max(s) ); - y = rbind( 0, matrix( Data[ , N-n+1 ] ), 0 ); - polygon( x, y, col = rgb( 0.9 - mod(n,3)*0.2, 0.9 - mod(n,3)*0.2, 0.9 - mod(n,3)*0.2) ); + plot(c(min(s), 0), xlim = c(min(s), max(s)), ylim = c(0, max(Data)), + main= "frontier", xlab = " Portfolio # risk propensity", + ylab = "Portfolio composition") + + for (n in 1 : N) { + x <- rbind(min(s), s, max(s)) + y <- rbind(0, matrix(Data[, N - n + 1]), 0) + polygon(x, y, col = rgb(0.9 - mod(n, 3) * 0.2, 0.9 - mod(n,3) * 0.2, + 0.9 - mod(n, 3) * 0.2)) } } -#' Plots the results of computing the efficient frontier (Expected returns and frontier), as it appears in A. Meucci, "Fully Flexible Views: Theory and Practice", The Risk Magazine, -#' October 2008, p 100-106. +#' @title Plots the results of computing the efficient frontier (Expected +#' returns and frontier) #' -#' @param e the NumPortf x 1 matrix of expected returns for each portfolio along the efficient frontier -#' @param s the NumPortf x 1 matrix of standard deviation of returns for each portfolio along the efficient frontier -#' @param w the NumPortf x N matrix of compositions (security weights) for each portfolio along the efficient frontier +#' @description Plots the results of computing the efficient frontier (Expected +#' returns and frontier), as it appears in A. Meucci, "Fully Flexible Views: +#' Theory and Practice", The Risk Magazine, October 2008, p 100-106. +#' +#' @param e the NumPortf x 1 matrix of expected returns for each portfolio +#' along the efficient frontier +#' @param s the NumPortf x 1 matrix of standard deviation of returns for +#' each portfolio along the efficient frontier +#' @param w the NumPortf x N matrix of compositions (security weights) for +#' each portfolio along the efficient frontier #' @param M the NumPortf x 1 vector of expected returns for each asset #' @param Lower constraints -#' @param Upper constraints -#' -#' @references -#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158} -#' See Meucci script for "RankingInformation/PlotResults.m" +#' @param Upper constraints #' -#' @author Xavier Valls \email{flamejat@@gmail.com} +#' @references +#' A. Meucci, "Fully Flexible Views: Theory and Practice" +#' \url{http://www.symmys.com/node/158}. See Meucci script for +#' "RankingInformation/PlotResults.m" +#' +#' @author Xavier Valls \email{xaviervallspla@@gmail.com} +#' @export -PlotResults = function( e, s, w, M, Lower = NULL , Upper = NULL) -{ - N = length( M ); - dev.new(); - par( mfrow = c( 1, 2 ) ); - h1 = hist( M*100, plot = F ) - barplot( h1$density, horiz = T, main = "expected returns", xlab = "", ylab = "" ); - if(length(Lower) || length(Upper)) - { - Changed = array( 0, N ); - Changed[ union( Lower, Upper ) ] = M[ union( Lower, Upper ) ] * 100; - h2 = hist(Changed, plot = F ); - barplot( h2$density, horiz = T, col = "red", add = T ); +PlotResults <- function(e, s, w, M, Lower = NULL, Upper = NULL) { + N <- length(M) + dev.new() + par(mfrow = c(1, 2)) + h1 <- hist(M * 100, plot = F) + barplot(h1$density, horiz = T, main = "expected returns", xlab = "", + ylab = "") + if (length(Lower) || length(Upper)) { + Changed <- array(0, N) + Changed[union(Lower, Upper)] <- M[union(Lower, Upper)] * 100 + h2 <- hist(Changed, plot = F) + barplot(h2$density, horiz = T, col = "red", add = T) } - PlotFrontier( e*100, s*100, w ); + PlotFrontier(e * 100, s * 100, w) } - -#' Computes posterior probabilities to view the rankings, as it appears in A. Meucci, -#' "Fully Flexible Views: Theory and Practice", The Risk Magazine, October 2008, p 100-106. +#' @title Computes posterior probabilities to view the rankings #' +#' @description Computes posterior probabilities to view the rankings, as it +#' appears in A. Meucci, "Fully Flexible Views: Theory and Practice", The Risk +#' Magazine, October 2008, p 100-106. +#' #' @param X a vector containing returns for all the asset classes #' @param p a vector containing the prior probability values -#' @param Lower a vector of indexes indicating which column is lower than the corresponding column number in Upper -#' @param Upper a vector of indexes indicating which column is lower than the corresponding column number in Upper +#' @param Lower a vector of indexes indicating which column is lower than +#' the corresponding column number in Upper +#' @param Upper a vector of indexes indicating which column is lower than +#' the corresponding column number in Upper #' #' @references -#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158} -#' See Meucci script for "RankingInformation/ViewRanking.m" +#' A. Meucci, "Fully Flexible Views: Theory and Practice" +#' \url{http://www.symmys.com/node/158}. See Meucci script for +#' "RankingInformation/ViewRanking.m" #' #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} -#' @export EntropyProg +#' @export -# example ViewRanking( X , p , Lower = c(3,4) , Upper = c(4,5) ) # two inequality views: asset 3 < asset 4 returns, and asset 4 < asset 5 returns +# example ViewRanking(X, p, Lower = c(3,4), Upper = c(4,5)) +# two inequality views: asset 3 < asset 4 returns, and asset 4 < asset 5 returns -ViewRanking = function( X , p , Lower , Upper ) -{ - library( matlab ) - J = nrow( X ) - N = ncol( X ) - - K = length( Lower ) - +ViewRanking <- function(X, p, Lower, Upper) { + J <- nrow(X) + # constrain probabilities to sum to one across all scenarios... - Aeq = ones( 1 , J ) - beq = 1 - + Aeq <- matrix(1, 1, J) + beq <- 1 + # ...constrain the expectations... A*x <= 0 # X[,Lower] refers to the column of returns for Asset-lower # X[,Upper] refers to the column of returns for Asset-lower - # X[ , Lower ] - X[ , Upper ] is vector returns of the "lower"" asset less the returns of the "higher" asset - V = X[ , Lower ] - X[ , Upper ] # Jx1 vector. Expectation is assigned to each scenario - - A = t( V ) - b = 0 # The expectation is that (Lower - Upper)x <= 0. (i.e. The returns of upper are greater than zero for each scenario) - + # X[, Lower] - X[, Upper] is vector returns of the "lower"" asset less the + # returns of the "higher" asset + + # Jx1 vector. Expectation is assigned to each scenario + V <- X[, Lower] - X[, Upper] + + A <- t(V) + # The expectation is that (Lower - Upper)x <= 0. + # (i.e. The returns of upper are greater than zero for each scenario) + b <- 0 + # ...compute posterior probabilities - p_ = EntropyProg( p , A , as.matrix(b) , Aeq , as.matrix(beq) ) - - return( p_ ) + p_ <- EntropyProg(p, A, as.matrix(b), Aeq, as.matrix(beq)) + + return(p_) } -#' Generates an efficient frontier based on Meucci's Ranking Information version and returns a A list with -#' NumPortf efficient portfolios whos returns are equally spaced along the whole range of the efficient frontier, -#' as it appears in A. Meucci, "Fully Flexible Views: Theory and Practice", The Risk Magazine, October 2008, -#' p 100-106. +#' @title Generates an efficient frontier #' +#' @description Generates an efficient frontier based on Meucci's Ranking +#' Information version and returns a A list with NumPortf efficient portfolios +#' whose returns are equally spaced along the whole range of the efficient +#' frontier, as it appears in A. Meucci, "Fully Flexible Views: Theory and +#' Practice", The Risk Magazine, October 2008, p 100-106. +#' #' Most recent version of article and MATLAB code available at #' http://www.symmys.com/node/158 #' -#' @param X a matrix with the joint-scenario probabilities by asset (rows are joint-scenarios, columns are assets) -#' @param p a vector of probabilities associated with each scenario in matrix X +#' @param X a matrix with the joint-scenario probabilities by asset +#' (rows are joint-scenarios, columns are assets) +#' @param p a vector of probabilities associated with each scenario +#' in matrix X #' @param Options a list of options....TBD #' -#' @return Exps the NumPortf x 1 vector of expected returns for each asset -#' @return Covs the NumPortf x N vector of security volatilities along the efficient frontier -#' @return w the NumPortf x N matrix of compositions (security weights) for each portfolio along the efficient frontier -#' @return e the NumPortf x 1 matrix of expected returns for each portfolio along the efficient frontier -#' @return s the NumPortf x 1 matrix of standard deviation of returns for each portfolio along the efficient frontier +#' @return Exps the NumPortf x 1 vector of expected returns for each +#' asset +#' @return Covs the NumPortf x N vector of security volatilities along +#' the efficient frontier +#' @return w the NumPortf x N matrix of compositions (security +#' weights)for each portfolio along the efficient frontier +#' @return e the NumPortf x 1 matrix of expected returns for each +#' portfolio along the efficient frontier +#' @return s the NumPortf x 1 matrix of standard deviation of +#' returns for each portfolio along the efficient frontier #' -#' @references -#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158} -#' See Meucci script for "RankingInformation/EfficientFrontier.m" +#' @references +#' A. Meucci, "Fully Flexible Views: Theory and Practice" +#' \url{http://www.symmys.com/node/158}. See Meucci script for +#' "RankingInformation/EfficientFrontier.m" #' -#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and Xavier Valls \email{flamejat@@gmail.com} +#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and +#' Xavier Valls \email{xaviervallspla@@gmail.com} #' @export -RIEfficientFrontier = function( X , p , Options) -{ +RIEfficientFrontier <- function(X, p, Options) { - if( !require("limSolve") ) stop("This script requieres the limSolve package installed") + if(!require("limSolve")) + stop("This script requieres the limSolve package installed") + N <- ncol(X) # number of assets - library( matlab ) - - J = nrow( X ) # number of scenarios - N = ncol( X ) # number of assets - - Exps = t(X) %*% p # probability-weighted expected return of each asset - - Scnd_Mom = t(X) %*% (X * ( p %*% matrix( 1, 1 , N ) ) ) - Scnd_Mom = ( Scnd_Mom + t(Scnd_Mom) ) / 2 # an N*N matrix - Covs = Scnd_Mom - Exps %*% t( Exps ) - - Constr = list() - + Exps <- t(X) %*% p # probability-weighted expected return of each asset + + Scnd_Mom <- t(X) %*% (X * (p %*% matrix(1, 1, N))) + Scnd_Mom <- (Scnd_Mom + t(Scnd_Mom)) / 2 # an N*N matrix + Covs <- Scnd_Mom - Exps %*% t(Exps) + + Constr <- list() + # constrain the sum of weights to 1 - Constr$Aeq = matrix( 1, 1 , N ) - Constr$beq = 1 - + Constr$Aeq <- matrix(1, 1, N) + Constr$beq <- 1 + # constrain the weight of any security to between 0 and 1 - Constr$Aleq = rbind( diag( 1, N ) , - diag( 1, N ) ) # linear coefficients matrix A in the inequality constraint A*x <= b - Constr$bleq = rbind( matrix( 1, N, 1 ) , matrix( 0, N, 1 ) ) # constraint vector b in the inequality constraint A*x <= b - - Amat = rbind( Constr$Aeq , Constr$Aleq ) # stack the equality constraints on top of the inequality constraints - bvec = rbind( Constr$beq , Constr$bleq ) # stack the equality constraints on top of the inequality constraints - - ############################################################################################ + + # linear coefficients matrix A in the inequality constraint A*x <= b + Constr$Aleq <- rbind(diag(1, N), - diag(1, N)) + # constraint vector b in the inequality constraint A*x <= b + Constr$bleq <- rbind(matrix(1, N, 1), matrix(0, N, 1)) + + # stack the equality constraints on top of the inequality constraints + Amat <- rbind(Constr$Aeq, Constr$Aleq) + # stack the equality constraints on top of the inequality constraints + bvec <- rbind(Constr$beq, Constr$bleq) + + ############################################################################## # determine return of minimum-risk portfolio - FirstDegree = matrix( 0, N , 1 ) # TODO: assumes that securities have zero expected returns when computing efficient frontier? - SecondDegree = Covs - # Why is FirstDegree "expected returns" set to 0? + + # TODO: assumes that securities have zero expected returns when computing + # efficient frontier? + FirstDegree <- matrix(0, N, 1) + SecondDegree <- Covs + # Why is FirstDegree "expected returns" set to 0? # We capture the equality view in the equality constraints matrix - # In other words, we have a constraint that the Expected Returns by Asset %*% Weights = Target Return - MinVol_Weights = solve.QP( Dmat = SecondDegree , dvec = -1*FirstDegree , Amat = -1*t(Amat) , bvec = -1*bvec , meq = length( Constr$beq ) ) - MinSDev_Exp = t( MinVol_Weights$solution ) %*% Exps - - ############################################################################################ + # In other words, we have a constraint that the Expected Returns by + # Asset %*% Weights = Target Return + MinVol_Weights <- solve.QP(Dmat = SecondDegree, dvec = -1 * FirstDegree, + Amat = -1 * t(Amat), bvec = -1 * bvec, + meq = length(Constr$beq)) + MinSDev_Exp <- t(MinVol_Weights$solution) %*% Exps + + ############################################################################## # determine return of maximum-return portfolio - FirstDegree = -Exps - MaxRet_Weights = linp( E = Constr$Aeq , F = Constr$beq , G = -1*Constr$Aleq , H = -1*Constr$bleq , Cost = FirstDegree , ispos = FALSE )$X - MaxExp_Exp = t( MaxRet_Weights) %*% Exps - - ############################################################################################ + FirstDegree <- -Exps + MaxRet_Weights <- linp(E = Constr$Aeq, F = Constr$beq, G = -1 * Constr$Aleq, + H = -1 * Constr$bleq, Cost = FirstDegree, + ispos = FALSE)$X + MaxExp_Exp <- t(MaxRet_Weights) %*% Exps + + ############################################################################## # slice efficient frontier in NumPortf equally thick horizontal sections - Grid = matrix( , ncol = 0 , nrow = 0 ) - Grid = t( seq( from = Options$FrontierSpan[1] , to = Options$FrontierSpan[2] , length.out = Options$NumPortf ) ) - - # the portfolio return varies from a minimum of MinSDev_Exp up to a maximum of MaxExp_Exp - # We establish equally-spaced portfolio return targets and use this find efficient portfolios - # in the next step - Targets = as.numeric( MinSDev_Exp ) + Grid * as.numeric( ( MaxExp_Exp - MinSDev_Exp ) ) - - ############################################################################################ - # compute the NumPortf compositions and risk-return coordinates - FirstDegree = matrix( 0, N , 1 ) - - w = matrix( , ncol = N , nrow = 0 ) - e = matrix( , ncol = 1 , nrow = 0 ) - s = matrix( , ncol = 1 , nrow = 0 ) - - for ( i in 1:Options$NumPortf ) - { + Grid <- matrix(, ncol = 0, nrow = 0) + Grid <- t(seq(from = Options$FrontierSpan[1], to = Options$FrontierSpan[2], + length.out = Options$NumPortf)) + + # the portfolio return varies from a minimum of MinSDev_Exp up to a maximum of + # MaxExp_Exp. We establish equally-spaced portfolio return targets and use + # this find efficient portfolios in the next step. + Targets <- as.numeric(MinSDev_Exp) + Grid * as.numeric((MaxExp_Exp - + MinSDev_Exp)) + + ############################################################################## + # compute the NumPortf compositions and risk-return coordinates + FirstDegree <- matrix(0, N, 1) + + w <- matrix(, ncol = N, nrow = 0) + e <- matrix(, ncol = 1, nrow = 0) + s <- matrix(, ncol = 1, nrow = 0) + + for (i in 1:Options$NumPortf) { # determine least risky portfolio for given expected return - # Ax = b ; Exps %*% weights = Target Return - AEq = rbind( Constr$Aeq , t( Exps ) ) # equality constraint: set expected return for each asset... - bEq = rbind( Constr$beq , Targets[ i ] ) # ...and target portfolio return for i'th efficient portfolio - - Amat = rbind( AEq , Constr$Aleq ) # stack the equality constraints on top of the inequality constraints - bvec = rbind( bEq , Constr$bleq ) - - Weights = solve.QP( Dmat = SecondDegree , dvec = -1*FirstDegree , Amat = -1*t(Amat) , bvec = -1*bvec , meq = length( bEq ) ) - - w = rbind( w , Weights$solution ) - s = rbind( s , sqrt( t(Weights$solution) %*% Covs %*% Weights$solution ) ) - e = rbind( e , Weights$solution %*% Exps ) + # Ax = b Exps %*% weights = Target Return + # equality constraint: set expected return for each asset... + AEq <- rbind(Constr$Aeq, t(Exps)) + # ...and target portfolio return for i'th efficient portfolio + bEq <- rbind(Constr$beq, Targets[i]) + + # stack the equality constraints on top of the inequality constraints + Amat <- rbind(AEq, Constr$Aleq) + bvec <- rbind(bEq, Constr$bleq) + + Weights <- solve.QP(Dmat = SecondDegree, dvec = -1 * FirstDegree, + Amat = -1 * t(Amat), bvec = -1 * bvec, meq = length(bEq)) + + w <- rbind(w, Weights$solution) + s <- rbind(s, sqrt(t(Weights$solution) %*% Covs %*% Weights$solution)) + e <- rbind(e, Weights$solution %*% Exps) } - - return( list( e = e , Sdev = s , Composition = w , Exps = Exps , Covs = Covs ) ) + + return(list(e = e, Sdev = s, Composition = w, Exps = Exps, Covs = Covs)) } Added: pkg/Meucci/R/Torsion.R =================================================================== --- pkg/Meucci/R/Torsion.R (rev 0) +++ pkg/Meucci/R/Torsion.R 2015-06-25 08:43:25 UTC (rev 3745) @@ -0,0 +1,79 @@ + +#' @title Computes the Principal Components torsion and the Minimum Torsion +#' +#' @description Computes the Principal Components torsion and the Minimum +#' Torsion for diversification analysis, as described in A. Meucci, +#' A. Santangelo, R. Deguest - "Measuring Portfolio Diversification Based on +#' Optimized Uncorrelated Factors" +#' +#' @param Sigma [matrix] (n_ x n_) covariance matrix +#' @param model [string] choose between 'pca' and 'minimum-torsion' +#' model +#' @param method [string] choose between 'approximate' and 'exact' +#' method for 'minimum-torsion' model +#' @param max_niter [scalar] choose number of iterations of numerical +#' algorithm +#' +#' @return t [matrix] (n_ x n_) torsion matrix +#' +#' @references +#' A. Meucci, A. Santangelo, R. Deguest - "Measuring Portfolio Diversification +#' Based on Optimized Uncorrelated Factors" \url{http://symmys.com/node/599} +#' +#' See Meucci's script "torsion.m" +# +#' @author Xavier Valls \email{xaviervallspla@@gmail.com} +#' @export + +Torsion = function(Sigma, model, method = NULL, max_niter = 10000 ) { + + if (model == "pca") { + # PCA decomposition + e <- eigen(Sigma) + lambda <- e$values + ev <- e$vectors + flip <- ev[1,] < 0 + # fix the sign of the eigenvector based on the sign of its first entry + ev[, flip] <- -ev[, flip] + index <- order(-lambda) + + # PCA torsion + t <- t(ev[, index]) + + } else if (model == "minimum-torsion") { + # Correlation matrix + sigma <- diag(Sigma) ^ (1 / 2) + C <- diag(1 / sigma) %*% Sigma %*% diag(1 / sigma) + c <- sqrtm(C)$B # Riccati root of C + + if (method == "approximate") { + t <- mrdivide(diag(sigma), c) %*% diag(1 / sigma) + } else if (method == "exact") { + n_ <- nrow(Sigma) + + # initialize + d <- array(1, n_) + f <- array(0, max_niter) + for (i in 1:max_niter) { + + U <- diag(d) %*% c %*% c %*% diag(d) + u <- sqrtm(U)$B + q <- mldivide(u, (diag(d) %*% c)) + d <- diag(q %*% c) + pi_ <- diag(d) %*% q # perturbation + f[i] <- norm(c - pi_, type = "f") + + if(i > 1 && abs(f[i] - f[i - 1]) / f[i] / n_ <= 10 ^ (-8)) { + f <- f[1:i] + break + } else if( i == max_niter && abs(f[max_niter] - + f[max_niter - 1]) / f[max_niter] / n_ > 10 ^ -8 ) { + print(paste("number of max iterations reached: n_iter =", max_niter)) + } + } + x <- pi_ %*% solve(c) + t <- diag(sigma) %*% x %*% diag(1/sigma) + } + } + return(t) +} Added: pkg/Meucci/data/JGB.rda =================================================================== (Binary files differ) Property changes on: pkg/Meucci/data/JGB.rda ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: pkg/Meucci/data/ghqx.rda =================================================================== (Binary files differ) Property changes on: pkg/Meucci/data/ghqx.rda ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: pkg/Meucci/data/linRet.rda =================================================================== (Binary files differ) Property changes on: pkg/Meucci/data/linRet.rda ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: pkg/Meucci/data/pseudodata.rda =================================================================== (Binary files differ) Property changes on: pkg/Meucci/data/pseudodata.rda ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Modified: pkg/Meucci/demo/InvariantProjection.R =================================================================== --- pkg/Meucci/demo/InvariantProjection.R 2015-06-24 22:54:29 UTC (rev 3744) +++ pkg/Meucci/demo/InvariantProjection.R 2015-06-25 08:43:25 UTC (rev 3745) @@ -1,65 +1,87 @@ # Annualization and Projection algorithm for invariant # -# SYMMYS - Last version of article and code available at http://symmys.com/node/136 +# SYMMYS - Last version of article and code available at +# http://symmys.com/node/136 # Project summary statistics to arbitrary horizons under i.i.d. assumption -# see Meucci, A. (2010) "Annualization and General Projection of Skewness, Kurtosis and All Summary Statistics" +# see Meucci, A. (2010) "Annualization and General Projection of Skewness, +# Kurtosis and All Summary Statistics" # GARP Risk Professional, August, pp. 52-54 -N = 6 # a numeric with the number of the first N stadardized summary statistics to project -K = 100 # a numeric with an arbitrary projection horizon +# numeric with number of the first N stadardized summary statistics to project +N <- 6 +# numeric with an arbitrary projection horizon +K <- 100 -J = 100000 # a numeric with the number of scenarios -a = -1 # a numeric with the location shift parameter. Mean of distribution will be exp(a) -m = 0.2 # log of the mean of the distribution -s = 0.4 # log of the standard deviation of the distribution - -X = GenerateLogNormalDistribution(J, a, m, s) +# numeric with the number of scenarios +J <- 100000 +# numeric with the location shift parameter. Mean of distribution will be exp(a) +a <- -1 +# log of the mean of the distribution +m <- 0.2 +# log of the standard deviation of the distribution +s <- 0.4 + +X <- GenerateLogNormalDistribution(J, a, m, s) # TODO: Expectations on outputs # Ga[1] should equal K*mean(X) # Ga[2] should equal sqrt(K)*std(X) - -# show distribution of the invariant. Invariance test: The three distributions should be very similar -hist( X , 50 , freq = FALSE , main = "Distribution of Invariant" , xlab = "X" ) # chart 1: distribution of invariant -hist( X[ 1 : length( X ) / 2 ] , 50 , freq = FALSE , main = "Distribution (1st Half of Pop.)" , xlab = "X" ) # chart 2: distribution of invariant (1st-half of population) -hist( X[ ( length( X ) / 2 ) : length( X ) ] , 50 , freq = FALSE , main = "Distribution (2nd Half of Pop.)" , xlab = "X" ) # chart 3: distribution of invariant (2nd-half of population) - + +# show distribution of the invariant +# Invariance test: The three distributions should be very similar +# chart 1: distribution of invariant +hist(X, 50, freq = FALSE, main = "Distribution of Invariant", xlab = "X") +# chart 2: distribution of invariant (1st-half of population) +hist(X[1 : length(X) / 2], 50, freq = FALSE, + main = "Distribution (1st Half of Pop.)", xlab = "X") [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3745 From noreply at r-forge.r-project.org Fri Jun 26 20:45:08 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 26 Jun 2015 20:45:08 +0200 (CEST) Subject: [Returnanalytics-commits] r3746 - pkg/Dowd/tests/testthat Message-ID: <20150626184509.042C618625C@r-forge.r-project.org> Author: dacharya Date: 2015-06-26 20:45:08 +0200 (Fri, 26 Jun 2015) New Revision: 3746 Added: pkg/Dowd/tests/testthat/testFrechetES.R Log: Test for FrechetES. Added: pkg/Dowd/tests/testthat/testFrechetES.R =================================================================== --- pkg/Dowd/tests/testthat/testFrechetES.R (rev 0) +++ pkg/Dowd/tests/testthat/testFrechetES.R 2015-06-26 18:45:08 UTC (rev 3746) @@ -0,0 +1,8 @@ +test_that("Frechet ES.",{ + # Success - 1 + expect_equal(as.matrix(623.485), FrechetES(3.5, 2.3, 1.6, 10, .95, 30), tolerance=0.01) + + # Success - 2 + expect_equal(as.matrix(0.1514), FrechetES(-1.3, 1.2, .2, 10, .9, 280), tolerance=0.01) + +}) \ No newline at end of file From noreply at r-forge.r-project.org Fri Jun 26 20:46:02 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 26 Jun 2015 20:46:02 +0200 (CEST) Subject: [Returnanalytics-commits] r3747 - pkg/Dowd Message-ID: <20150626184602.236531846B3@r-forge.r-project.org> Author: dacharya Date: 2015-06-26 20:46:01 +0200 (Fri, 26 Jun 2015) New Revision: 3747 Modified: pkg/Dowd/NAMESPACE Log: Several HS functions added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-26 18:45:08 UTC (rev 3746) +++ pkg/Dowd/NAMESPACE 2015-06-26 18:46:01 UTC (rev 3747) @@ -35,9 +35,13 @@ export(GumbelVaR) export(GumbelVaRPlot2DCl) export(HSES) +export(HSESDFPerc) +export(HSESPlot2DCl) export(HSVaR) export(HSVaRDFPerc) +export(HSVaRESPlot2DCl) export(HSVaRFigure) +export(HSVaRPlot2DCl) export(HillEstimator) export(HillPlot) export(HillQuantileEstimator) From noreply at r-forge.r-project.org Fri Jun 26 20:47:29 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 26 Jun 2015 20:47:29 +0200 (CEST) Subject: [Returnanalytics-commits] r3748 - in pkg/Dowd: R man Message-ID: <20150626184729.800031846B3@r-forge.r-project.org> Author: dacharya Date: 2015-06-26 20:47:29 +0200 (Fri, 26 Jun 2015) New Revision: 3748 Added: pkg/Dowd/R/HSESDFPerc.R pkg/Dowd/man/HSESDFPerc.Rd Log: HSESDFPerc added. Added: pkg/Dowd/R/HSESDFPerc.R =================================================================== --- pkg/Dowd/R/HSESDFPerc.R (rev 0) +++ pkg/Dowd/R/HSESDFPerc.R 2015-06-26 18:47:29 UTC (rev 3748) @@ -0,0 +1,82 @@ +#' @title Percentile of historical simulation VaR distribution function +#' +#' @description Estimates percentiles of historical simulation VaR distribution +#' function, using theory of order statistics, for specified confidence level. +#' +#' @param Ra Vector of daily P/L data +#' @param perc Desired percentile and is scalar +#' @param cl VaR confidence level and is scalar +#' @return Value of percentile of VaR distribution function +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates Percentiles for random standard normal returns and given perc +#' # and cl +#' Ra <- rnorm(100) +#' HSESDFPerc(Ra, .75, .95) +#' +#' @export +HSESDFPerc <- function(Ra, perc, cl){ + + # Determine if there are three arguments, and ensure that arguments are read as intended + if (nargs() < 3) { + stop("Too few arguments.") + } + if (nargs() > 3) { + stop("Too many arguments") + } + if (nargs() == 3) { + profit.loss <- as.vector(Ra) + data <- sort(profit.loss) + n <- length(data) + } + + # Check that inputs obey sign and value restrictions + if (n < 0) { + stop("Number of observations must be greater than zero.") + } + if (perc <= 0) { + stop("Chosen percentile must be positive.") + } + if (perc > 1) { + stop("Chosen percentile must not exceed 1") + } + if (cl >= 1) { + stop("Confidence level must be less than 1.") + } + if (cl <= 0) { + stop("Confidence level must positive.") + } + + # Derive order statistics and ensure it is an integer + w <- n * cl # Derive rth order statistics + r <- round(w) # Round r to nearest integer + + # Bisection routine + a <- 0 + fa <- -Inf + b <- 1 + fb <- Inf + eps <- .Machine$double.eps + while (b - a > eps * b) { + x <- (a + b) / 2 + fx <- 1 - pbinom(r - 1, n, x) - perc + if (sign(fx) == sign(fa)){ + a = x + fa = fx + } else { + b = x + fb = fx + } + } + i <- round(n * x) + VaR <- data[i] # Value of percentile of VaR distribution function + j <- i:n + y <- mean(data[j]) # Value of percentile of ES distribution function + return(y) + +} \ No newline at end of file Added: pkg/Dowd/man/HSESDFPerc.Rd =================================================================== --- pkg/Dowd/man/HSESDFPerc.Rd (rev 0) +++ pkg/Dowd/man/HSESDFPerc.Rd 2015-06-26 18:47:29 UTC (rev 3748) @@ -0,0 +1,35 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/HSESDFPerc.R +\name{HSESDFPerc} +\alias{HSESDFPerc} +\title{Percentile of historical simulation VaR distribution function} +\usage{ +HSESDFPerc(Ra, perc, cl) +} +\arguments{ +\item{Ra}{Vector of daily P/L data} + +\item{perc}{Desired percentile and is scalar} + +\item{cl}{VaR confidence level and is scalar} +} +\value{ +Value of percentile of VaR distribution function +} +\description{ +Estimates percentiles of historical simulation VaR distribution +function, using theory of order statistics, for specified confidence level. +} +\examples{ +# Estimates Percentiles for random standard normal returns and given perc + # and cl + Ra <- rnorm(100) + HSESDFPerc(Ra, .75, .95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Fri Jun 26 20:48:03 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 26 Jun 2015 20:48:03 +0200 (CEST) Subject: [Returnanalytics-commits] r3749 - in pkg/Dowd: R man Message-ID: <20150626184803.9F6971846B3@r-forge.r-project.org> Author: dacharya Date: 2015-06-26 20:48:03 +0200 (Fri, 26 Jun 2015) New Revision: 3749 Added: pkg/Dowd/R/HSESPlot2DCl.R pkg/Dowd/man/HSESPlot2DCl.Rd Log: HSESPlot2DCl added. Added: pkg/Dowd/R/HSESPlot2DCl.R =================================================================== --- pkg/Dowd/R/HSESPlot2DCl.R (rev 0) +++ pkg/Dowd/R/HSESPlot2DCl.R 2015-06-26 18:48:03 UTC (rev 3749) @@ -0,0 +1,62 @@ +#' @title Plots historical simulation ES against confidence level +#' +#' @description Function plots the historical simulation ES of a +#' portfolio against confidence level, for specified range of confidence level +#' and holding period implied by data frequency. +#' +#' @param Ra Vector of daily P/L data +#' @param cl Vector of ES confidence levels +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots historical simulation ES against confidence level +#' Ra <- rnorm(100) +#' cl <- seq(.90, .99, .01) +#' HSESPlot2DCl(Ra, cl) +#' +#' @export +HSESPlot2DCl <- function(Ra, cl){ + + # Determine if there are three arguments, and ensure that arguments are read + # as intended + if (nargs() < 2) { + stop("Too few arguments.") + } + if (nargs() > 2) { + stop("Too many arguments") + } + if (nargs() == 2) { + profit.loss <- as.vector(Ra) + n <- length(profit.loss) + } + + # Check that inputs have correct dimensions + cl <- as.matrix(cl) + cl.rows <- dim(cl)[1] + cl.columns <- dim(cl)[2] + if (min(cl.rows, cl.columns) > 1) { + stop("Confidence level must be a vector.") + } + cl <- as.vector(cl) + + # Check that inputs obey sign and value restrictions + if (max(cl) >= 1) { + stop("Confidence level must be less than 1.") + } + if (min(cl) <= 0) { + stop("Confidence level must positive.") + } + + # ES estimation + ES <- double(length(cl)) + for (k in 1:length(cl)) { + ES[k] <- HSES(profit.loss, cl[k]) + } + + # Plot + plot(cl, ES, type = "l", col = 5, xlab = "Confidence Level", ylab = "ES", main = "Historical ES against confidence level") +} \ No newline at end of file Added: pkg/Dowd/man/HSESPlot2DCl.Rd =================================================================== --- pkg/Dowd/man/HSESPlot2DCl.Rd (rev 0) +++ pkg/Dowd/man/HSESPlot2DCl.Rd 2015-06-26 18:48:03 UTC (rev 3749) @@ -0,0 +1,31 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/HSESPlot2DCl.R +\name{HSESPlot2DCl} +\alias{HSESPlot2DCl} +\title{Plots historical simulation ES against confidence level} +\usage{ +HSESPlot2DCl(Ra, cl) +} +\arguments{ +\item{Ra}{Vector of daily P/L data} + +\item{cl}{Vector of ES confidence levels} +} +\description{ +Function plots the historical simulation ES of a +portfolio against confidence level, for specified range of confidence level +and holding period implied by data frequency. +} +\examples{ +# Plots historical simulation ES against confidence level + Ra <- rnorm(100) + cl <- seq(.90, .99, .01) + HSESPlot2DCl(Ra, cl) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Fri Jun 26 20:48:31 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 26 Jun 2015 20:48:31 +0200 (CEST) Subject: [Returnanalytics-commits] r3750 - in pkg/Dowd: R man Message-ID: <20150626184831.3E0851846B3@r-forge.r-project.org> Author: dacharya Date: 2015-06-26 20:48:31 +0200 (Fri, 26 Jun 2015) New Revision: 3750 Added: pkg/Dowd/R/HSVaRESPlot2DCl.R pkg/Dowd/man/HSVaRESPlot2DCl.Rd Log: HSVaRESPlot2DCl.R added. Added: pkg/Dowd/R/HSVaRESPlot2DCl.R =================================================================== --- pkg/Dowd/R/HSVaRESPlot2DCl.R (rev 0) +++ pkg/Dowd/R/HSVaRESPlot2DCl.R 2015-06-26 18:48:31 UTC (rev 3750) @@ -0,0 +1,67 @@ +#' @title Plots historical simulation VaR and ES against confidence level +#' +#' @description Function plots the historical simulation VaR and ES of a +#' portfolio against confidence level, for specified range of confidence level +#' and holding period implied by data frequency. +#' +#' @param Ra Vector of daily P/L data +#' @param cl Vectof of VaR confidence levels +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots historical simulation VaR and ES against confidence level +#' Ra <- rnorm(100) +#' cl <- seq(.90, .99, .01) +#' HSVaRESPlot2DCl(Ra, cl) +#' +#' @export +HSVaRESPlot2DCl <- function(Ra, cl){ + + # Determine if there are three arguments, and ensure that arguments are read + # as intended + if (nargs() < 2) { + stop("Too few arguments.") + } + if (nargs() > 2) { + stop("Too many arguments") + } + if (nargs() == 2) { + profit.loss <- as.vector(Ra) + n <- length(profit.loss) + } + + # Check that inputs have correct dimensions + cl <- as.matrix(cl) + cl.rows <- dim(cl)[1] + cl.columns <- dim(cl)[2] + if (min(cl.rows, cl.columns) > 1) { + stop("Confidence level must be a vector.") + } + cl <- as.vector(cl) + + # Check that inputs obey sign and value restrictions + if (max(cl) >= 1) { + stop("Confidence level must be less than 1.") + } + if (min(cl) <= 0) { + stop("Confidence level must positive.") + } + + # VaR and ES estimation + VaR <- double(length(cl)) + ES <- double(length(cl)) + for (k in 1:length(cl)) { + VaR[k] <- HSVaR(profit.loss, cl[k]) + ES[k] <- HSES(profit.loss, cl[k]) + } + + # Plot + plot(cl, VaR, type = "l", col = 3, xlab = "Confidence Level", ylab = "VaR/ES", main = "Historical VaR and ES against confidence level") + par(new = TRUE) + plot(cl, ES, type = "l", col = 5, xlab = "Confidence Level", ylab = "VaR/ES", main = "Historical VaR and ES against confidence level") + legend("topleft", c("ES", "VaR")) +} \ No newline at end of file Added: pkg/Dowd/man/HSVaRESPlot2DCl.Rd =================================================================== --- pkg/Dowd/man/HSVaRESPlot2DCl.Rd (rev 0) +++ pkg/Dowd/man/HSVaRESPlot2DCl.Rd 2015-06-26 18:48:31 UTC (rev 3750) @@ -0,0 +1,31 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/HSVaRESPlot2DCl.R +\name{HSVaRESPlot2DCl} +\alias{HSVaRESPlot2DCl} +\title{Plots historical simulation VaR and ES against confidence level} +\usage{ +HSVaRESPlot2DCl(Ra, cl) +} +\arguments{ +\item{Ra}{Vector of daily P/L data} + +\item{cl}{Vectof of VaR confidence levels} +} +\description{ +Function plots the historical simulation VaR and ES of a +portfolio against confidence level, for specified range of confidence level +and holding period implied by data frequency. +} +\examples{ +# Plots historical simulation VaR and ES against confidence level + Ra <- rnorm(100) + cl <- seq(.90, .99, .01) + HSVaRESPlot2DCl(Ra, cl) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Fri Jun 26 20:49:05 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 26 Jun 2015 20:49:05 +0200 (CEST) Subject: [Returnanalytics-commits] r3751 - in pkg/Dowd: R man Message-ID: <20150626184905.1BC7F1846B3@r-forge.r-project.org> Author: dacharya Date: 2015-06-26 20:49:04 +0200 (Fri, 26 Jun 2015) New Revision: 3751 Added: pkg/Dowd/R/HSVaRPlot2DCl.R pkg/Dowd/man/HSVaRPlot2DCl.Rd Log: HSVaRPlot2DCl added. Added: pkg/Dowd/R/HSVaRPlot2DCl.R =================================================================== --- pkg/Dowd/R/HSVaRPlot2DCl.R (rev 0) +++ pkg/Dowd/R/HSVaRPlot2DCl.R 2015-06-26 18:49:04 UTC (rev 3751) @@ -0,0 +1,62 @@ +#' @title Plots historical simulation VaR against confidence level +#' +#' @description Function plots the historical simulation VaR of a +#' portfolio against confidence level, for specified range of confidence level +#' and holding period implied by data frequency. +#' +#' @param Ra Vector of daily P/L data +#' @param cl Vector of VaR confidence levels +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots historical simulation VaR against confidence level +#' Ra <- rnorm(100) +#' cl <- seq(.90, .99, .01) +#' HSVaRPlot2DCl(Ra, cl) +#' +#' @export +HSVaRPlot2DCl <- function(Ra, cl){ + + # Determine if there are three arguments, and ensure that arguments are read + # as intended + if (nargs() < 2) { + stop("Too few arguments.") + } + if (nargs() > 2) { + stop("Too many arguments") + } + if (nargs() == 2) { + profit.loss <- as.vector(Ra) + n <- length(profit.loss) + } + + # Check that inputs have correct dimensions + cl <- as.matrix(cl) + cl.rows <- dim(cl)[1] + cl.columns <- dim(cl)[2] + if (min(cl.rows, cl.columns) > 1) { + stop("Confidence level must be a vector.") + } + cl <- as.vector(cl) + + # Check that inputs obey sign and value restrictions + if (max(cl) >= 1) { + stop("Confidence level must be less than 1.") + } + if (min(cl) <= 0) { + stop("Confidence level must positive.") + } + + # VaR estimation + VaR <- double(length(cl)) + for (k in 1:length(cl)) { + VaR[k] <- HSVaR(profit.loss, cl[k]) + } + + # Plot + plot(cl, VaR, type = "l", col = 3, xlab = "Confidence Level", ylab = "VaR", main = "Historical VaR against confidence level") + par(new = TRUE) +} \ No newline at end of file Added: pkg/Dowd/man/HSVaRPlot2DCl.Rd =================================================================== --- pkg/Dowd/man/HSVaRPlot2DCl.Rd (rev 0) +++ pkg/Dowd/man/HSVaRPlot2DCl.Rd 2015-06-26 18:49:04 UTC (rev 3751) @@ -0,0 +1,31 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/HSVaRPlot2DCl.R +\name{HSVaRPlot2DCl} +\alias{HSVaRPlot2DCl} +\title{Plots historical simulation VaR against confidence level} +\usage{ +HSVaRPlot2DCl(Ra, cl) +} +\arguments{ +\item{Ra}{Vector of daily P/L data} + +\item{cl}{Vector of VaR confidence levels} +} +\description{ +Function plots the historical simulation VaR of a +portfolio against confidence level, for specified range of confidence level +and holding period implied by data frequency. +} +\examples{ +# Plots historical simulation VaR against confidence level + Ra <- rnorm(100) + cl <- seq(.90, .99, .01) + HSVaRPlot2DCl(Ra, cl) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Sun Jun 28 10:10:32 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 28 Jun 2015 10:10:32 +0200 (CEST) Subject: [Returnanalytics-commits] r3752 - pkg/Dowd/tests/testthat Message-ID: <20150628081032.2E8E1185645@r-forge.r-project.org> Author: dacharya Date: 2015-06-28 10:10:31 +0200 (Sun, 28 Jun 2015) New Revision: 3752 Added: pkg/Dowd/tests/testthat/testBlancoIhleBacktest.R Log: Test for BlancoIhleBacktest. Added: pkg/Dowd/tests/testthat/testBlancoIhleBacktest.R =================================================================== --- pkg/Dowd/tests/testthat/testBlancoIhleBacktest.R (rev 0) +++ pkg/Dowd/tests/testthat/testBlancoIhleBacktest.R 2015-06-28 08:10:31 UTC (rev 3752) @@ -0,0 +1,20 @@ +test_that("BlancoIhleBacktest.",{ + + # Tests based on first 19 return data of SP500 returns from managers data set + # Success - 1 + a <- c(0.034000, 0.009300, 0.009600, 0.014700, 0.025800, 0.003800, + -0.044200, 0.021100, 0.056300, 0.027600, 0.075600, -0.019800, + 0.062500, 0.007800, -0.041100, 0.059700, 0.060900, 0.044800, + 0.079600) # First 19 SP500 returns from managers dataset in PerformanceAnalytics + b <- c(0.03400, -0.01424, -0.00939, -0.00942, -0.00945, -0.00710, 0.01060, + 0.00580, 0.00100, -0.00380, -0.00435, 0.01508, 0.01272, 0.01036, + 0.03045, 0.02832, 0.02619, 0.02406, 0.02193) # Computed Using HSVaR + # at 90% confidence level + c <- c(0.03400, -0.00930, -0.00930, -0.00930, -0.00930, -0.00380, 0.04420, + 0.04420, 0.04420, 0.02020, 0.02020, 0.03200, 0.03200, 0.03200, + 0.04265, 0.04265, 0.04265, 0.04265, 0.04265) # Computed using HSES at + # 90% confidence level + + expect_equal(26.5564, BlancoIhleBacktest(a, b, c, .9), tol=1) + +}) \ No newline at end of file From noreply at r-forge.r-project.org Sun Jun 28 10:16:18 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 28 Jun 2015 10:16:18 +0200 (CEST) Subject: [Returnanalytics-commits] r3753 - pkg/Dowd/tests/testthat Message-ID: <20150628081619.0AA2A185F82@r-forge.r-project.org> Author: dacharya Date: 2015-06-28 10:16:18 +0200 (Sun, 28 Jun 2015) New Revision: 3753 Added: pkg/Dowd/tests/testthat/testLopezBacktest.R Log: Test for Lopez Backtest. Added: pkg/Dowd/tests/testthat/testLopezBacktest.R =================================================================== --- pkg/Dowd/tests/testthat/testLopezBacktest.R (rev 0) +++ pkg/Dowd/tests/testthat/testLopezBacktest.R 2015-06-28 08:16:18 UTC (rev 3753) @@ -0,0 +1,16 @@ +test_that("Lopez Backtest.",{ + + # Tests based on first 19 return data of SP500 returns from managers data set + # Success - 1 + a <- c(0.034000, 0.009300, 0.009600, 0.014700, 0.025800, 0.003800, + -0.044200, 0.021100, 0.056300, 0.027600, 0.075600, -0.019800, + 0.062500, 0.007800, -0.041100, 0.059700, 0.060900, 0.044800, + 0.079600) # First 19 SP500 returns from managers dataset in PerformanceAnalytics + b <- c(0.03400, -0.01424, -0.00939, -0.00942, -0.00945, -0.00710, 0.01060, + 0.00580, 0.00100, -0.00380, -0.00435, 0.01508, 0.01272, 0.01036, + 0.03045, 0.02832, 0.02619, 0.02406, 0.02193) # Computed Using HSVaR + # at 90% confidence level + + expect_equal(15.4116, LopezBacktest(a, b, .9), tol=1) + +}) \ No newline at end of file From noreply at r-forge.r-project.org Mon Jun 29 14:36:04 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 29 Jun 2015 14:36:04 +0200 (CEST) Subject: [Returnanalytics-commits] r3754 - pkg/Dowd/R Message-ID: <20150629123604.D0E561879EF@r-forge.r-project.org> Author: dacharya Date: 2015-06-29 14:36:04 +0200 (Mon, 29 Jun 2015) New Revision: 3754 Modified: pkg/Dowd/R/HSVaRPlot2DCl.R Log: One unnecessary line removed. Modified: pkg/Dowd/R/HSVaRPlot2DCl.R =================================================================== --- pkg/Dowd/R/HSVaRPlot2DCl.R 2015-06-28 08:16:18 UTC (rev 3753) +++ pkg/Dowd/R/HSVaRPlot2DCl.R 2015-06-29 12:36:04 UTC (rev 3754) @@ -58,5 +58,4 @@ # Plot plot(cl, VaR, type = "l", col = 3, xlab = "Confidence Level", ylab = "VaR", main = "Historical VaR against confidence level") - par(new = TRUE) -} \ No newline at end of file +} From noreply at r-forge.r-project.org Mon Jun 29 14:38:34 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 29 Jun 2015 14:38:34 +0200 (CEST) Subject: [Returnanalytics-commits] r3755 - in pkg/Dowd: . R man Message-ID: <20150629123834.434171879F7@r-forge.r-project.org> Author: dacharya Date: 2015-06-29 14:38:33 +0200 (Mon, 29 Jun 2015) New Revision: 3755 Added: pkg/Dowd/R/HSESFigure.R pkg/Dowd/man/HSESFigure.Rd Modified: pkg/Dowd/NAMESPACE Log: HSESFigure added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-29 12:36:04 UTC (rev 3754) +++ pkg/Dowd/NAMESPACE 2015-06-29 12:38:33 UTC (rev 3755) @@ -36,6 +36,7 @@ export(GumbelVaRPlot2DCl) export(HSES) export(HSESDFPerc) +export(HSESFigure) export(HSESPlot2DCl) export(HSVaR) export(HSVaRDFPerc) Added: pkg/Dowd/R/HSESFigure.R =================================================================== --- pkg/Dowd/R/HSESFigure.R (rev 0) +++ pkg/Dowd/R/HSESFigure.R 2015-06-29 12:38:33 UTC (rev 3755) @@ -0,0 +1,71 @@ +#' @title Figure of Historical SImulation VaR and ES and histogram of L/P +#' +#' @description Plots figure showing the historical simulation VaR and ES and histogram +#' of L/P for specified confidence level and holding period implied by data +#' frequency. +#' +#' @param Ra Vector of profit loss data +#' @param cl VaR confidence level +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots figure showing VaR and histogram of P/L data +#' Ra <- rnorm(100) +#' HSESFigure(Ra, .95) +#' +#' @export +HSESFigure<- function(Ra, cl){ + # Determine if there are two arguments and ensure that arguments are read as intended + if (nargs() < 2) { + stop("Too few arguments") + } + if (nargs() > 2){ + stop("Too many arguments") + } + if (nargs() == 2){ + profit.loss <- as.vector(Ra) + n <- length(profit.loss) + } + + # Check that inputs have correct dimensions + if (length(cl) != 1) { + stop("Confidence level must be a scalar") + } + + if ( cl >= 1){ + stop("Confidence level must be less than 1") + } + if ( cl <= 0){ + stop("Confidence level must be positive.") + } + # VaR and ES estimation + VaR <- HSVaR(profit.loss, cl) # HS VaR + ES <- HSES(profit.loss, cl) # HS ES + # Histogram + n <- hist(-profit.loss, main = "Historical Simulation VaR", breaks = 50, col = 4, + xlab = "Loss(+) / Profit(-)", ylab = "Frequency") + + # Insert line showing VaR + v <- c(0, .625 * max(n$counts)) # Coordinates for VaR line + u <- VaR * matrix(1, length(v),1) # Coordinates for VaR line + lines(u, v, type = "l", col = "black") # VaR line + + # Insert line showing ES + w <- c(0, .45 * max(n$counts)) # Coordinates for ES + z <- ES * matrix(1, length(w), 1) # Coordinates for ES line + lines(z, w, type = "l", col = "black") # ES line + cl.for.label <- 100 * cl # Input to confidence level label + + + # VaR line label + text(VaR, .75*max(n$counts), paste('VaR at', cl.for.label, "%Cl")) + text(VaR, .65*max(n$counts), c(round(VaR, digits = 2))) + + # ES line label + text(ES, .55*max(n$counts), c('ES =')) + text(ES, .45*max(n$counts), paste(round(ES, digits = 2))) + +} Added: pkg/Dowd/man/HSESFigure.Rd =================================================================== --- pkg/Dowd/man/HSESFigure.Rd (rev 0) +++ pkg/Dowd/man/HSESFigure.Rd 2015-06-29 12:38:33 UTC (rev 3755) @@ -0,0 +1,30 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/HSESFigure.R +\name{HSESFigure} +\alias{HSESFigure} +\title{Figure of Historical SImulation VaR and ES and histogram of L/P} +\usage{ +HSESFigure(Ra, cl) +} +\arguments{ +\item{Ra}{Vector of profit loss data} + +\item{cl}{VaR confidence level} +} +\description{ +Plots figure showing the historical simulation VaR and ES and histogram + of L/P for specified confidence level and holding period implied by data + frequency. +} +\examples{ +# Plots figure showing VaR and histogram of P/L data + Ra <- rnorm(100) + HSESFigure(Ra, .95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jun 30 01:48:13 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 30 Jun 2015 01:48:13 +0200 (CEST) Subject: [Returnanalytics-commits] r3756 - in pkg/Dowd: . R man Message-ID: <20150629234813.4BFF31872A4@r-forge.r-project.org> Author: dacharya Date: 2015-06-30 01:48:12 +0200 (Tue, 30 Jun 2015) New Revision: 3756 Added: pkg/Dowd/R/KernelVaRTriangleKernel.R pkg/Dowd/man/KernelVaRTriangleKernel.Rd Modified: pkg/Dowd/NAMESPACE Log: KernelVaRTriangle added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-29 12:38:33 UTC (rev 3755) +++ pkg/Dowd/NAMESPACE 2015-06-29 23:48:12 UTC (rev 3756) @@ -49,6 +49,7 @@ export(InsuranceVaR) export(JarqueBeraBacktest) export(KSTestStat) +export(KernelVaRTriangleKernel) export(KuiperTestStat) export(LopezBacktest) export(MEFPlot) Added: pkg/Dowd/R/KernelVaRTriangleKernel.R =================================================================== --- pkg/Dowd/R/KernelVaRTriangleKernel.R (rev 0) +++ pkg/Dowd/R/KernelVaRTriangleKernel.R 2015-06-29 23:48:12 UTC (rev 3756) @@ -0,0 +1,50 @@ +#' Calculates VaR using triangle kernel approach +#' +#' The output consists of a scalar VaR for specified confidence level. +#' +#' @param Ra Profit and Loss data set +#' @param cl VaR confidence level +#' @return Scalar VaR +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # VaR for specified confidence level using triangle kernel approach +#' Ra <- rnorm(30) +#' KernelVaRTriangleKernel(Ra, .95) +#' +#' @export +KernelVaRTriangleKernel <- function(Ra, cl) { + PandL <- as.vector(Ra) + mu <- mean(PandL) + sigma <- sd(PandL) + + # Obtain pdf values + kernel.data <- density(PandL, kernel = "triangular", from = mu - 4 * sigma, to = mu + 4 * sigma, n = 1000) + kernel.pdf <- kernel.data$y + x.values <- kernel.data$x + delta.x <- x.values[2]-x.values[1] + n <- 1000 # = length(x.values) + + # Obtain cdf values + cdf <- double(n) + cdf[1] <- kernel.pdf[1] * delta.x + for (i in 2:n) { + cdf[i] <- kernel.pdf[i] * delta.x + cdf[i - 1] + } + plot(x.values, kernel.pdf, type="l", main = "Constructed Pdf") + + # Derivation of required percentile + cdf.indices.less.than.prob <- which(cdf Author: dacharya Date: 2015-06-30 02:31:18 +0200 (Tue, 30 Jun 2015) New Revision: 3757 Added: pkg/Dowd/R/KernelVaREpanechinikovKernel.R pkg/Dowd/man/KernelVaREpanechinikovKernel.Rd Log: KernelVaREpanechinikovKernel added. Added: pkg/Dowd/R/KernelVaREpanechinikovKernel.R =================================================================== --- pkg/Dowd/R/KernelVaREpanechinikovKernel.R (rev 0) +++ pkg/Dowd/R/KernelVaREpanechinikovKernel.R 2015-06-30 00:31:18 UTC (rev 3757) @@ -0,0 +1,50 @@ +#' Calculates VaR using epanechinikov kernel approach +#' +#' The output consists of a scalar VaR for specified confidence level. +#' +#' @param Ra Profit and Loss data set +#' @param cl VaR confidence level +#' @return Scalar VaR +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # VaR for specified confidence level using epanechinikov kernel approach +#' Ra <- rnorm(30) +#' KernelVaREpanechinikovKernel(Ra, .95) +#' +#' @export +KernelVaREpanechinikovKernel <- function(Ra, cl) { + PandL <- as.vector(Ra) + mu <- mean(PandL) + sigma <- sd(PandL) + + # Obtain pdf values + kernel.data <- density(PandL, kernel = "epanechinikov", from = mu - 4 * sigma, to = mu + 4 * sigma, n = 1000, bw = "nrd") + kernel.pdf <- kernel.data$y + x.values <- kernel.data$x + delta.x <- x.values[2]-x.values[1] + n <- 1000 # = length(x.values) + + # Obtain cdf values + cdf <- double(n) + cdf[1] <- kernel.pdf[1] * delta.x + for (i in 2:n) { + cdf[i] <- kernel.pdf[i] * delta.x + cdf[i - 1] + } + plot(x.values, kernel.pdf, type="l", main = "Constructed Pdf") + + # Derivation of required percentile + cdf.indices.less.than.prob <- which(cdf Author: dacharya Date: 2015-06-30 02:32:18 +0200 (Tue, 30 Jun 2015) New Revision: 3758 Added: pkg/Dowd/R/KernelVaRNormalKernel.R pkg/Dowd/man/KernelVaRNormalKernel.Rd Log: KernelVaRNormalKernell added. Added: pkg/Dowd/R/KernelVaRNormalKernel.R =================================================================== --- pkg/Dowd/R/KernelVaRNormalKernel.R (rev 0) +++ pkg/Dowd/R/KernelVaRNormalKernel.R 2015-06-30 00:32:18 UTC (rev 3758) @@ -0,0 +1,50 @@ +#' Calculates VaR using normal kernel approach +#' +#' The output consists of a scalar VaR for specified confidence level. +#' +#' @param Ra Profit and Loss data set +#' @param cl VaR confidence level +#' @return Scalar VaR +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # VaR for specified confidence level using normal kernel approach +#' Ra <- rnorm(30) +#' KernelVaRNormalKernel(Ra, .95) +#' +#' @export +KernelVaRNormalKernel <- function(Ra, cl) { + PandL <- as.vector(Ra) + mu <- mean(PandL) + sigma <- sd(PandL) + + # Obtain pdf values + kernel.data <- density(PandL, kernel = "gaussian", from = mu - 4 * sigma, to = mu + 4 * sigma, n = 1000, bw = "nrd") + kernel.pdf <- kernel.data$y + x.values <- kernel.data$x + delta.x <- x.values[2]-x.values[1] + n <- 1000 # = length(x.values) + + # Obtain cdf values + cdf <- double(n) + cdf[1] <- kernel.pdf[1] * delta.x + for (i in 2:n) { + cdf[i] <- kernel.pdf[i] * delta.x + cdf[i - 1] + } + plot(x.values, kernel.pdf, type="l", main = "Constructed Pdf") + + # Derivation of required percentile + cdf.indices.less.than.prob <- which(cdf Author: dacharya Date: 2015-06-30 02:34:28 +0200 (Tue, 30 Jun 2015) New Revision: 3759 Modified: pkg/Dowd/R/KernelVaRTriangleKernel.R Log: Bandwidth in source code removed. Modified: pkg/Dowd/R/KernelVaRTriangleKernel.R =================================================================== --- pkg/Dowd/R/KernelVaRTriangleKernel.R 2015-06-30 00:32:18 UTC (rev 3758) +++ pkg/Dowd/R/KernelVaRTriangleKernel.R 2015-06-30 00:34:28 UTC (rev 3759) @@ -21,7 +21,7 @@ sigma <- sd(PandL) # Obtain pdf values - kernel.data <- density(PandL, kernel = "triangular", from = mu - 4 * sigma, to = mu + 4 * sigma, n = 1000) + kernel.data <- density(PandL, kernel = "triangular", from = mu - 4 * sigma, to = mu + 4 * sigma, n = 1000, bw = "nrd") kernel.pdf <- kernel.data$y x.values <- kernel.data$x delta.x <- x.values[2]-x.values[1] From noreply at r-forge.r-project.org Tue Jun 30 09:47:43 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 30 Jun 2015 09:47:43 +0200 (CEST) Subject: [Returnanalytics-commits] r3760 - pkg/Dowd Message-ID: <20150630074743.17D011876AF@r-forge.r-project.org> Author: dacharya Date: 2015-06-30 09:47:42 +0200 (Tue, 30 Jun 2015) New Revision: 3760 Modified: pkg/Dowd/NAMESPACE Log: KernelVaREpanechinikovKernel and KernelVaREpanechinikovKernel added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-30 00:34:28 UTC (rev 3759) +++ pkg/Dowd/NAMESPACE 2015-06-30 07:47:42 UTC (rev 3760) @@ -49,6 +49,8 @@ export(InsuranceVaR) export(JarqueBeraBacktest) export(KSTestStat) +export(KernelVaREpanechinikovKernel) +export(KernelVaRNormalKernel) export(KernelVaRTriangleKernel) export(KuiperTestStat) export(LopezBacktest) From noreply at r-forge.r-project.org Tue Jun 30 10:44:55 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 30 Jun 2015 10:44:55 +0200 (CEST) Subject: [Returnanalytics-commits] r3761 - pkg/Dowd Message-ID: <20150630084455.D466D187783@r-forge.r-project.org> Author: dacharya Date: 2015-06-30 10:44:55 +0200 (Tue, 30 Jun 2015) New Revision: 3761 Modified: pkg/Dowd/NAMESPACE Log: KernelESNormalKernel, KernelESTriangleKernel, KernelESEpanechinikovKernel added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-30 07:47:42 UTC (rev 3760) +++ pkg/Dowd/NAMESPACE 2015-06-30 08:44:55 UTC (rev 3761) @@ -49,6 +49,9 @@ export(InsuranceVaR) export(JarqueBeraBacktest) export(KSTestStat) +export(KernelESEpanechinikovKernel) +export(KernelESNormalKernel) +export(KernelESTriangleKernel) export(KernelVaREpanechinikovKernel) export(KernelVaRNormalKernel) export(KernelVaRTriangleKernel) From noreply at r-forge.r-project.org Tue Jun 30 10:45:48 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 30 Jun 2015 10:45:48 +0200 (CEST) Subject: [Returnanalytics-commits] r3762 - in pkg/Dowd: R man Message-ID: <20150630084548.A04211877EA@r-forge.r-project.org> Author: dacharya Date: 2015-06-30 10:45:48 +0200 (Tue, 30 Jun 2015) New Revision: 3762 Added: pkg/Dowd/R/KernelESEpanechinikovKernel.R pkg/Dowd/man/KernelESEpanechinikovKernel.Rd Log: KernelESEpanechinikovKernel function added. Added: pkg/Dowd/R/KernelESEpanechinikovKernel.R =================================================================== --- pkg/Dowd/R/KernelESEpanechinikovKernel.R (rev 0) +++ pkg/Dowd/R/KernelESEpanechinikovKernel.R 2015-06-30 08:45:48 UTC (rev 3762) @@ -0,0 +1,29 @@ +#' Calculates ES using Epanechinikov kernel approach +#' +#' The output consists of a scalar ES for specified confidence level. +#' +#' @param Ra Profit and Loss data set +#' @param cl ES confidence level +#' @return Scalar ES +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # ES for specified confidence level using Epanechinikov kernel approach +#' Ra <- rnorm(30) +#' KernelESEpanechinikovKernel(Ra, .95) +#' +#' @export +KernelESEpanechinikovKernel <- function(Ra, cl){ + PandL <- as.vector(Ra) + n <- 1000 + delta.cl <- (1 - cl) / n + VaR <- double(999) + for (i in 1:(n - 1)) { + VaR[i] <- KernelVaREpanechinikovKernel(PandL, cl + i * delta.cl) + } + ES <- mean(VaR) + return(ES) + +} \ No newline at end of file Added: pkg/Dowd/man/KernelESEpanechinikovKernel.Rd =================================================================== --- pkg/Dowd/man/KernelESEpanechinikovKernel.Rd (rev 0) +++ pkg/Dowd/man/KernelESEpanechinikovKernel.Rd 2015-06-30 08:45:48 UTC (rev 3762) @@ -0,0 +1,31 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/KernelESEpanechinikovKernel.R +\name{KernelESEpanechinikovKernel} +\alias{KernelESEpanechinikovKernel} +\title{Calculates ES using Epanechinikov kernel approach} +\usage{ +KernelESEpanechinikovKernel(Ra, cl) +} +\arguments{ +\item{Ra}{Profit and Loss data set} + +\item{cl}{ES confidence level} +} +\value{ +Scalar ES +} +\description{ +The output consists of a scalar ES for specified confidence level. +} +\examples{ +# ES for specified confidence level using Epanechinikov kernel approach + Ra <- rnorm(30) + KernelESEpanechinikovKernel(Ra, .95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jun 30 10:46:23 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 30 Jun 2015 10:46:23 +0200 (CEST) Subject: [Returnanalytics-commits] r3763 - in pkg/Dowd: R man Message-ID: <20150630084623.77B0E1877EA@r-forge.r-project.org> Author: dacharya Date: 2015-06-30 10:46:23 +0200 (Tue, 30 Jun 2015) New Revision: 3763 Added: pkg/Dowd/R/KernelESNormalKernel.R pkg/Dowd/man/KernelESNormalKernel.Rd Log: KernelESNormalKernel function added. Added: pkg/Dowd/R/KernelESNormalKernel.R =================================================================== --- pkg/Dowd/R/KernelESNormalKernel.R (rev 0) +++ pkg/Dowd/R/KernelESNormalKernel.R 2015-06-30 08:46:23 UTC (rev 3763) @@ -0,0 +1,29 @@ +#' Calculates ES using normal kernel approach +#' +#' The output consists of a scalar ES for specified confidence level. +#' +#' @param Ra Profit and Loss data set +#' @param cl VaR confidence level +#' @return Scalar VaR +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # ES for specified confidence level using normal kernel approach +#' Ra <- rnorm(30) +#' KernelESNormalKernel(Ra, .95) +#' +#' @export +KernelESNormalKernel <- function(Ra, cl){ + PandL <- as.vector(Ra) + n <- 1000 + delta.cl <- (1 - cl) / n + VaR <- double(999) + for (i in 1:(n - 1)) { + VaR[i] <- KernelVaRNormalKernel(PandL, cl + i * delta.cl) + } + ES <- mean(VaR) + return(ES) + +} Added: pkg/Dowd/man/KernelESNormalKernel.Rd =================================================================== --- pkg/Dowd/man/KernelESNormalKernel.Rd (rev 0) +++ pkg/Dowd/man/KernelESNormalKernel.Rd 2015-06-30 08:46:23 UTC (rev 3763) @@ -0,0 +1,31 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/KernelESNormalKernel.R +\name{KernelESNormalKernel} +\alias{KernelESNormalKernel} +\title{Calculates ES using normal kernel approach} +\usage{ +KernelESNormalKernel(Ra, cl) +} +\arguments{ +\item{Ra}{Profit and Loss data set} + +\item{cl}{VaR confidence level} +} +\value{ +Scalar VaR +} +\description{ +The output consists of a scalar ES for specified confidence level. +} +\examples{ +# ES for specified confidence level using normal kernel approach + Ra <- rnorm(30) + KernelESNormalKernel(Ra, .95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jun 30 10:47:19 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 30 Jun 2015 10:47:19 +0200 (CEST) Subject: [Returnanalytics-commits] r3764 - in pkg/Dowd: R man Message-ID: <20150630084719.3C6CF1877EA@r-forge.r-project.org> Author: dacharya Date: 2015-06-30 10:47:19 +0200 (Tue, 30 Jun 2015) New Revision: 3764 Added: pkg/Dowd/R/KernelESTriangleKernel.R pkg/Dowd/man/KernelESTriangleKernel.Rd Log: KernelESTriangleKernel function added. Added: pkg/Dowd/R/KernelESTriangleKernel.R =================================================================== --- pkg/Dowd/R/KernelESTriangleKernel.R (rev 0) +++ pkg/Dowd/R/KernelESTriangleKernel.R 2015-06-30 08:47:19 UTC (rev 3764) @@ -0,0 +1,29 @@ +#' Calculates ES using triangle kernel approach +#' +#' The output consists of a scalar ES for specified confidence level. +#' +#' @param Ra Profit and Loss data set +#' @param cl VaR confidence level +#' @return Scalar VaR +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # VaR for specified confidence level using triangle kernel approach +#' Ra <- rnorm(30) +#' KernelESTriangleKernel(Ra, .95) +#' +#' @export +KernelESTriangleKernel <- function(Ra, cl){ + PandL <- as.vector(Ra) + n <- 1000 + delta.cl <- (1 - cl) / n + VaR <- double(999) + for (i in 1:(n - 1)) { + VaR[i] <- KernelVaRTriangleKernel(PandL, cl + i * delta.cl) + } + ES <- mean(VaR) + return(ES) + +} Added: pkg/Dowd/man/KernelESTriangleKernel.Rd =================================================================== --- pkg/Dowd/man/KernelESTriangleKernel.Rd (rev 0) +++ pkg/Dowd/man/KernelESTriangleKernel.Rd 2015-06-30 08:47:19 UTC (rev 3764) @@ -0,0 +1,31 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/KernelESTriangleKernel.R +\name{KernelESTriangleKernel} +\alias{KernelESTriangleKernel} +\title{Calculates ES using triangle kernel approach} +\usage{ +KernelESTriangleKernel(Ra, cl) +} +\arguments{ +\item{Ra}{Profit and Loss data set} + +\item{cl}{VaR confidence level} +} +\value{ +Scalar VaR +} +\description{ +The output consists of a scalar ES for specified confidence level. +} +\examples{ +# VaR for specified confidence level using triangle kernel approach + Ra <- rnorm(30) + KernelESTriangleKernel(Ra, .95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jun 30 10:49:02 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 30 Jun 2015 10:49:02 +0200 (CEST) Subject: [Returnanalytics-commits] r3765 - pkg/Dowd/R Message-ID: <20150630084902.88AF21877EA@r-forge.r-project.org> Author: dacharya Date: 2015-06-30 10:49:02 +0200 (Tue, 30 Jun 2015) New Revision: 3765 Modified: pkg/Dowd/R/KernelVaREpanechinikovKernel.R Log: Mistake in kernel method argument of density function added. Modified: pkg/Dowd/R/KernelVaREpanechinikovKernel.R =================================================================== --- pkg/Dowd/R/KernelVaREpanechinikovKernel.R 2015-06-30 08:47:19 UTC (rev 3764) +++ pkg/Dowd/R/KernelVaREpanechinikovKernel.R 2015-06-30 08:49:02 UTC (rev 3765) @@ -21,7 +21,7 @@ sigma <- sd(PandL) # Obtain pdf values - kernel.data <- density(PandL, kernel = "epanechinikov", from = mu - 4 * sigma, to = mu + 4 * sigma, n = 1000, bw = "nrd") + kernel.data <- density(PandL, kernel = "epanechnikov", from = mu - 4 * sigma, to = mu + 4 * sigma, n = 1000, bw = "nrd") kernel.pdf <- kernel.data$y x.values <- kernel.data$x delta.x <- x.values[2]-x.values[1] @@ -47,4 +47,4 @@ VaR <- (lower.x.bound + upper.x.bound) / 2 # Desired percentile, ie, answer. return(VaR) -} \ No newline at end of file +}