From noreply at r-forge.r-project.org Thu Jul 2 20:04:35 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 2 Jul 2015 20:04:35 +0200 (CEST) Subject: [Returnanalytics-commits] r3766 - in pkg/Dowd: . R man Message-ID: <20150702180435.4E352187A6B@r-forge.r-project.org> Author: dacharya Date: 2015-07-02 20:04:34 +0200 (Thu, 02 Jul 2015) New Revision: 3766 Added: pkg/Dowd/R/PCAVaR.R pkg/Dowd/man/PCAVaR.Rd Modified: pkg/Dowd/NAMESPACE Log: PCAVaR added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-06-30 08:49:02 UTC (rev 3765) +++ pkg/Dowd/NAMESPACE 2015-07-02 18:04:34 UTC (rev 3766) @@ -59,6 +59,7 @@ export(LopezBacktest) export(MEFPlot) export(NormalQQPlot) +export(PCAVaR) export(PickandsEstimator) export(PickandsPlot) export(ProductCopulaVaR) Added: pkg/Dowd/R/PCAVaR.R =================================================================== --- pkg/Dowd/R/PCAVaR.R (rev 0) +++ pkg/Dowd/R/PCAVaR.R 2015-07-02 18:04:34 UTC (rev 3766) @@ -0,0 +1,52 @@ +#' Estimates VaR by principal components analysis +#' +#' Estimates the VaR of a multi position portfolio by principal components analysis, using chosen number of principal components and a specified confidence level or range of confidence levels. +#' +#' @param Ra Matrix return data set where each row is interpreted as a set of daily observations, and each column as the returns to each position in a portfolio +#' @param position.data Position-size vector, giving amount invested in each position +#' @param number.of.principal.components Chosen number of principal components +#' @param cl Chosen confidence level +#' @return VaR +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes PCA VaR +#' +#' Ra <- rnorm(30) +#' KernelESEpanechinikovKernel(Ra, .95) +#' +#' @export +PCAVaR <- function(Ra, position.data, number.of.principal.components, cl){ + # Check that inputs have correct dimensions + return.data<-as.matrix(Ra) + m <- dim(return.data)[1] + n <- dim(return.data)[2] + if (min(m, n) == 1) { + stop("Input data set has insufficient dimensionality") + } + if (number.of.principal.components < 0) { + stop("Number of principal components must be positive") + } + if (number.of.principal.components > n) { + stop("Number of principal components cannot exceed number of positions") + } + # Check that dimensions of position data and return data match + if (n != length(position.data)) { + stop("Dimensions of return data and position data should be compatible") + } + + # Principal components estimation + a <- svd(return.data) # SVD; provides U and V + index <- n - number.of.principal.components # Establishes how many zero terms on diagonal of S matrix + print(index) + S.diag <- sort(a$d, decreasing = TRUE)[1:number.of.principal.components] # Creates diagonal for S matrix + S.diag <- diag(S.diag) + S <- matrix(0, min(m, n), min(m, n)) + S[1:number.of.principal.components,1:number.of.principal.components] <- S.diag # Creates S matrix with diagonal S.diag + synthetic.PandL.data <- a$u %*% S %*% t(a$v) %*% position.data + + y <- HSVaR(synthetic.PandL.data, cl) + return(y) +} \ No newline at end of file Added: pkg/Dowd/man/PCAVaR.Rd =================================================================== --- pkg/Dowd/man/PCAVaR.Rd (rev 0) +++ pkg/Dowd/man/PCAVaR.Rd 2015-07-02 18:04:34 UTC (rev 3766) @@ -0,0 +1,36 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/PCAVaR.R +\name{PCAVaR} +\alias{PCAVaR} +\title{Estimates VaR by principal components analysis} +\usage{ +PCAVaR(Ra, position.data, number.of.principal.components, cl) +} +\arguments{ +\item{Ra}{Matrix return data set where each row is interpreted as a set of daily observations, and each column as the returns to each position in a portfolio} + +\item{position.data}{Position-size vector, giving amount invested in each position} + +\item{number.of.principal.components}{Chosen number of principal components} + +\item{cl}{Chosen confidence level} +} +\value{ +VaR +} +\description{ +Estimates the VaR of a multi position portfolio by principal components analysis, using chosen number of principal components and a specified confidence level or range of confidence levels. +} +\examples{ +# Computes PCA VaR + + 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 Thu Jul 2 20:17:26 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 2 Jul 2015 20:17:26 +0200 (CEST) Subject: [Returnanalytics-commits] r3767 - in pkg/Dowd: . R man Message-ID: <20150702181727.0D734187B6B@r-forge.r-project.org> Author: dacharya Date: 2015-07-02 20:17:26 +0200 (Thu, 02 Jul 2015) New Revision: 3767 Added: pkg/Dowd/R/PCAES.R pkg/Dowd/man/PCAES.Rd Modified: pkg/Dowd/NAMESPACE Log: PCAES (Principal Component Analysis ES) added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-02 18:04:34 UTC (rev 3766) +++ pkg/Dowd/NAMESPACE 2015-07-02 18:17:26 UTC (rev 3767) @@ -59,6 +59,7 @@ export(LopezBacktest) export(MEFPlot) export(NormalQQPlot) +export(PCAES) export(PCAVaR) export(PickandsEstimator) export(PickandsPlot) Added: pkg/Dowd/R/PCAES.R =================================================================== --- pkg/Dowd/R/PCAES.R (rev 0) +++ pkg/Dowd/R/PCAES.R 2015-07-02 18:17:26 UTC (rev 3767) @@ -0,0 +1,51 @@ +#' Estimates ES by principal components analysis +#' +#' Estimates the ES of a multi position portfolio by principal components analysis, using chosen number of principal components and a specified confidence level or range of confidence levels. +#' +#' @param Ra Matrix return data set where each row is interpreted as a set of daily observations, and each column as the returns to each position in a portfolio +#' @param position.data Position-size vector, giving amount invested in each position +#' @param number.of.principal.components Chosen number of principal components +#' @param cl Chosen confidence level +#' @return ES +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes PCA ES +#' Ra <- matrix(rnorm(4*6),4,6) +#' position.data <- rnorm(6) +#' PCAES(Ra, position.data, 2, .95) +#' +#' @export +PCAES <- function(Ra, position.data, number.of.principal.components, cl){ + # Check that inputs have correct dimensions + return.data<-as.matrix(Ra) + m <- dim(return.data)[1] + n <- dim(return.data)[2] + if (min(m, n) == 1) { + stop("Input data set has insufficient dimensionality") + } + if (number.of.principal.components < 0) { + stop("Number of principal components must be positive") + } + if (number.of.principal.components > n) { + stop("Number of principal components cannot exceed number of positions") + } + # Check that dimensions of position data and return data match + if (n != length(position.data)) { + stop("Dimensions of return data and position data should be compatible") + } + + # Principal components estimation + a <- svd(return.data) # SVD; provides U and V + index <- n - number.of.principal.components # Establishes how many zero terms on diagonal of S matrix + S.diag <- c(sort(a$d, decreasing = TRUE)[1:number.of.principal.components], + double(index)) # Creates diagonal for S matrix + S <- matrix(0, m, n) + diag(S) <- S.diag # Creates S matrix with diagonal S.diag + synthetic.PandL.data <- a$u %*% S * t(a$v) * position.data + + y <- HSES(synthetic.PandL.data, cl) + return(y) +} \ No newline at end of file Added: pkg/Dowd/man/PCAES.Rd =================================================================== --- pkg/Dowd/man/PCAES.Rd (rev 0) +++ pkg/Dowd/man/PCAES.Rd 2015-07-02 18:17:26 UTC (rev 3767) @@ -0,0 +1,36 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/PCAES.R +\name{PCAES} +\alias{PCAES} +\title{Estimates ES by principal components analysis} +\usage{ +PCAES(Ra, position.data, number.of.principal.components, cl) +} +\arguments{ +\item{Ra}{Matrix return data set where each row is interpreted as a set of daily observations, and each column as the returns to each position in a portfolio} + +\item{position.data}{Position-size vector, giving amount invested in each position} + +\item{number.of.principal.components}{Chosen number of principal components} + +\item{cl}{Chosen confidence level} +} +\value{ +ES +} +\description{ +Estimates the ES of a multi position portfolio by principal components analysis, using chosen number of principal components and a specified confidence level or range of confidence levels. +} +\examples{ +# Computes PCA ES + Ra <- matrix(rnorm(4*6),4,6) + position.data <- rnorm(6) + PCAES(Ra, position.data, 2, .95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Thu Jul 2 20:22:44 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 2 Jul 2015 20:22:44 +0200 (CEST) Subject: [Returnanalytics-commits] r3768 - pkg/Dowd/R Message-ID: <20150702182244.EA0AE1811FC@r-forge.r-project.org> Author: dacharya Date: 2015-07-02 20:22:44 +0200 (Thu, 02 Jul 2015) New Revision: 3768 Modified: pkg/Dowd/R/PCAES.R Log: Mistakes in svd decomposition corrected. Modified: pkg/Dowd/R/PCAES.R =================================================================== --- pkg/Dowd/R/PCAES.R 2015-07-02 18:17:26 UTC (rev 3767) +++ pkg/Dowd/R/PCAES.R 2015-07-02 18:22:44 UTC (rev 3768) @@ -40,11 +40,11 @@ # Principal components estimation a <- svd(return.data) # SVD; provides U and V index <- n - number.of.principal.components # Establishes how many zero terms on diagonal of S matrix - S.diag <- c(sort(a$d, decreasing = TRUE)[1:number.of.principal.components], - double(index)) # Creates diagonal for S matrix - S <- matrix(0, m, n) - diag(S) <- S.diag # Creates S matrix with diagonal S.diag - synthetic.PandL.data <- a$u %*% S * t(a$v) * position.data + S.diag <- sort(a$d, decreasing = TRUE)[1:number.of.principal.components] # Creates diagonal for S matrix + S.diag <- diag(S.diag) + S <- matrix(0, min(m, n), min(m, n)) + S[1:number.of.principal.components,1:number.of.principal.components] <- S.diag # Creates S matrix with diagonal S.diag + synthetic.PandL.data <- a$u %*% S %*% t(a$v) %*% position.data y <- HSES(synthetic.PandL.data, cl) return(y) From noreply at r-forge.r-project.org Thu Jul 2 20:23:28 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 2 Jul 2015 20:23:28 +0200 (CEST) Subject: [Returnanalytics-commits] r3769 - pkg/Dowd/R Message-ID: <20150702182328.A31861811FC@r-forge.r-project.org> Author: dacharya Date: 2015-07-02 20:23:28 +0200 (Thu, 02 Jul 2015) New Revision: 3769 Modified: pkg/Dowd/R/PCAVaR.R Log: Mistake in example was corrected. Modified: pkg/Dowd/R/PCAVaR.R =================================================================== --- pkg/Dowd/R/PCAVaR.R 2015-07-02 18:22:44 UTC (rev 3768) +++ pkg/Dowd/R/PCAVaR.R 2015-07-02 18:23:28 UTC (rev 3769) @@ -13,9 +13,9 @@ #' @examples #' #' # Computes PCA VaR -#' -#' Ra <- rnorm(30) -#' KernelESEpanechinikovKernel(Ra, .95) +#' Ra <- matrix(rnorm(4*6),4,6) +#' position.data <- rnorm(6) +#' PCAVaR(Ra, position.data, 2, .95) #' #' @export PCAVaR <- function(Ra, position.data, number.of.principal.components, cl){ @@ -40,7 +40,6 @@ # Principal components estimation a <- svd(return.data) # SVD; provides U and V index <- n - number.of.principal.components # Establishes how many zero terms on diagonal of S matrix - print(index) S.diag <- sort(a$d, decreasing = TRUE)[1:number.of.principal.components] # Creates diagonal for S matrix S.diag <- diag(S.diag) S <- matrix(0, min(m, n), min(m, n)) From noreply at r-forge.r-project.org Thu Jul 2 20:24:24 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 2 Jul 2015 20:24:24 +0200 (CEST) Subject: [Returnanalytics-commits] r3770 - pkg/Dowd/man Message-ID: <20150702182424.4B7E61811FC@r-forge.r-project.org> Author: dacharya Date: 2015-07-02 20:24:24 +0200 (Thu, 02 Jul 2015) New Revision: 3770 Modified: pkg/Dowd/man/PCAVaR.Rd Log: Mistake in example was corrected. Modified: pkg/Dowd/man/PCAVaR.Rd =================================================================== --- pkg/Dowd/man/PCAVaR.Rd 2015-07-02 18:23:28 UTC (rev 3769) +++ pkg/Dowd/man/PCAVaR.Rd 2015-07-02 18:24:24 UTC (rev 3770) @@ -23,9 +23,9 @@ } \examples{ # Computes PCA VaR - - Ra <- rnorm(30) - KernelESEpanechinikovKernel(Ra, .95) + Ra <- matrix(rnorm(4*6),4,6) + position.data <- rnorm(6) + PCAVaR(Ra, position.data, 2, .95) } \author{ Dinesh Acharya From noreply at r-forge.r-project.org Thu Jul 2 22:42:59 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 2 Jul 2015 22:42:59 +0200 (CEST) Subject: [Returnanalytics-commits] r3771 - pkg/Dowd/R Message-ID: <20150702204300.0001E183C11@r-forge.r-project.org> Author: dacharya Date: 2015-07-02 22:42:59 +0200 (Thu, 02 Jul 2015) New Revision: 3771 Modified: pkg/Dowd/R/PCAES.R Log: Condition for the special case when number.of.principal.components is 1 was added. Additional unnecessary line was removed. Modified: pkg/Dowd/R/PCAES.R =================================================================== --- pkg/Dowd/R/PCAES.R 2015-07-02 18:24:24 UTC (rev 3770) +++ pkg/Dowd/R/PCAES.R 2015-07-02 20:42:59 UTC (rev 3771) @@ -39,9 +39,14 @@ # Principal components estimation a <- svd(return.data) # SVD; provides U and V - index <- n - number.of.principal.components # Establishes how many zero terms on diagonal of S matrix S.diag <- sort(a$d, decreasing = TRUE)[1:number.of.principal.components] # Creates diagonal for S matrix - S.diag <- diag(S.diag) + # Following condition for the fact that scalar argument to diag returns + # identity matrix + if (length(S.diag) == 1) { + S.diag <- as.matrix(S.diag) + } else { + S.diag <- diag(S.diag) + } S <- matrix(0, min(m, n), min(m, n)) S[1:number.of.principal.components,1:number.of.principal.components] <- S.diag # Creates S matrix with diagonal S.diag synthetic.PandL.data <- a$u %*% S %*% t(a$v) %*% position.data From noreply at r-forge.r-project.org Thu Jul 2 22:43:15 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 2 Jul 2015 22:43:15 +0200 (CEST) Subject: [Returnanalytics-commits] r3772 - pkg/Dowd/R Message-ID: <20150702204315.C49DD183C11@r-forge.r-project.org> Author: dacharya Date: 2015-07-02 22:43:15 +0200 (Thu, 02 Jul 2015) New Revision: 3772 Modified: pkg/Dowd/R/PCAVaR.R Log: Condition for the special case when number.of.principal.components is 1 was added. Additional unnecessary line was removed. Modified: pkg/Dowd/R/PCAVaR.R =================================================================== --- pkg/Dowd/R/PCAVaR.R 2015-07-02 20:42:59 UTC (rev 3771) +++ pkg/Dowd/R/PCAVaR.R 2015-07-02 20:43:15 UTC (rev 3772) @@ -39,8 +39,14 @@ # Principal components estimation a <- svd(return.data) # SVD; provides U and V - index <- n - number.of.principal.components # Establishes how many zero terms on diagonal of S matrix S.diag <- sort(a$d, decreasing = TRUE)[1:number.of.principal.components] # Creates diagonal for S matrix + # Following condition for the fact that scalar argument to diag returns + # identity matrix + if (length(S.diag) == 1) { + S.diag <- as.matrix(S.diag) + } else { + S.diag <- diag(S.diag) + } S.diag <- diag(S.diag) S <- matrix(0, min(m, n), min(m, n)) S[1:number.of.principal.components,1:number.of.principal.components] <- S.diag # Creates S matrix with diagonal S.diag From noreply at r-forge.r-project.org Thu Jul 2 23:00:59 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 2 Jul 2015 23:00:59 +0200 (CEST) Subject: [Returnanalytics-commits] r3773 - pkg/Dowd Message-ID: <20150702210059.94AFE1811FC@r-forge.r-project.org> Author: dacharya Date: 2015-07-02 23:00:59 +0200 (Thu, 02 Jul 2015) New Revision: 3773 Modified: pkg/Dowd/NAMESPACE Log: PCAESPlot and PCAVaRPlot added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-02 20:43:15 UTC (rev 3772) +++ pkg/Dowd/NAMESPACE 2015-07-02 21:00:59 UTC (rev 3773) @@ -60,7 +60,9 @@ export(MEFPlot) export(NormalQQPlot) export(PCAES) +export(PCAESPlot) export(PCAVaR) +export(PCAVaRPlot) export(PickandsEstimator) export(PickandsPlot) export(ProductCopulaVaR) From noreply at r-forge.r-project.org Thu Jul 2 23:01:35 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 2 Jul 2015 23:01:35 +0200 (CEST) Subject: [Returnanalytics-commits] r3774 - in pkg/Dowd: R man Message-ID: <20150702210135.CD2EF1811FC@r-forge.r-project.org> Author: dacharya Date: 2015-07-02 23:01:35 +0200 (Thu, 02 Jul 2015) New Revision: 3774 Added: pkg/Dowd/R/PCAESPlot.R pkg/Dowd/man/PCAESPlot.Rd Log: Plot for PCA ES added. Added: pkg/Dowd/R/PCAESPlot.R =================================================================== --- pkg/Dowd/R/PCAESPlot.R (rev 0) +++ pkg/Dowd/R/PCAESPlot.R 2015-07-02 21:01:35 UTC (rev 3774) @@ -0,0 +1,32 @@ +#' ES plot +#' +#' Estimates ES plot using principal components analysis +#' +#' @param Ra Matrix return data set where each row is interpreted as a set of daily observations, and each column as the returns to each position in a portfolio +#' @param position.data Position-size vector, giving amount invested in each position +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes PCA ES +#' Ra <- matrix(rnorm(15*20),15,20) +#' position.data <- rnorm(20) +#' PCAESPlot(Ra, position.data) +#' +#' @export +PCAESPlot <- function(Ra, position.data){ + # Check that inputs have correct dimensions + return.data<-as.matrix(Ra) + pcaes.95 <- double(10) + pcaes.99 <- double(10) + for (i in 1:10) { + pcaes.95[i] <- PCAES(return.data, position.data, i, .95) + pcaes.99[i] <- PCAES(return.data, position.data, i, .99) + } + t <- 1:10 + par(mfrow=c(2,1)) + plot(t, pcaes.99, type="l") + plot(t, pcaes.95, type="l") + +} \ No newline at end of file Added: pkg/Dowd/man/PCAESPlot.Rd =================================================================== --- pkg/Dowd/man/PCAESPlot.Rd (rev 0) +++ pkg/Dowd/man/PCAESPlot.Rd 2015-07-02 21:01:35 UTC (rev 3774) @@ -0,0 +1,29 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/PCAESPlot.R +\name{PCAESPlot} +\alias{PCAESPlot} +\title{ES plot} +\usage{ +PCAESPlot(Ra, position.data) +} +\arguments{ +\item{Ra}{Matrix return data set where each row is interpreted as a set of daily observations, and each column as the returns to each position in a portfolio} + +\item{position.data}{Position-size vector, giving amount invested in each position} +} +\description{ +Estimates ES plot using principal components analysis +} +\examples{ +# Computes PCA ES + Ra <- matrix(rnorm(15*20),15,20) + position.data <- rnorm(20) + PCAESPlot(Ra, position.data) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Thu Jul 2 23:01:58 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 2 Jul 2015 23:01:58 +0200 (CEST) Subject: [Returnanalytics-commits] r3775 - in pkg/Dowd: R man Message-ID: <20150702210158.854091811FC@r-forge.r-project.org> Author: dacharya Date: 2015-07-02 23:01:58 +0200 (Thu, 02 Jul 2015) New Revision: 3775 Added: pkg/Dowd/R/PCAVaRPlot.R pkg/Dowd/man/PCAVaRPlot.Rd Log: Plot for PCA VaR added. Added: pkg/Dowd/R/PCAVaRPlot.R =================================================================== --- pkg/Dowd/R/PCAVaRPlot.R (rev 0) +++ pkg/Dowd/R/PCAVaRPlot.R 2015-07-02 21:01:58 UTC (rev 3775) @@ -0,0 +1,32 @@ +#' VaR plot +#' +#' Estimates VaR plot using principal components analysis +#' +#' @param Ra Matrix return data set where each row is interpreted as a set of daily observations, and each column as the returns to each position in a portfolio +#' @param position.data Position-size vector, giving amount invested in each position +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes PCA VaR +#' Ra <- matrix(rnorm(15*20),15,20) +#' position.data <- rnorm(20) +#' PCAVaRPlot(Ra, position.data) +#' +#' @export +PCAVaRPlot <- function(Ra, position.data){ + # Check that inputs have correct dimensions + return.data<-as.matrix(Ra) + pcavar.95 <- double(10) + pcavar.99 <- double(10) + for (i in 1:10) { + pcavar.95[i] <- PCAVaR(return.data, position.data, i, .95) + pcavar.99[i] <- PCAVaR(return.data, position.data, i, .99) + } + t <- 1:10 + par(mfrow=c(2,1)) + plot(t, pcavar.99, type="l") + plot(t, pcavar.95, type="l") + +} \ No newline at end of file Added: pkg/Dowd/man/PCAVaRPlot.Rd =================================================================== --- pkg/Dowd/man/PCAVaRPlot.Rd (rev 0) +++ pkg/Dowd/man/PCAVaRPlot.Rd 2015-07-02 21:01:58 UTC (rev 3775) @@ -0,0 +1,29 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/PCAVaRPlot.R +\name{PCAVaRPlot} +\alias{PCAVaRPlot} +\title{VaR plot} +\usage{ +PCAVaRPlot(Ra, position.data) +} +\arguments{ +\item{Ra}{Matrix return data set where each row is interpreted as a set of daily observations, and each column as the returns to each position in a portfolio} + +\item{position.data}{Position-size vector, giving amount invested in each position} +} +\description{ +Estimates VaR plot using principal components analysis +} +\examples{ +# Computes PCA VaR + Ra <- matrix(rnorm(15*20),15,20) + position.data <- rnorm(20) + PCAVaRPlot(Ra, position.data) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Fri Jul 3 07:01:33 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 3 Jul 2015 07:01:33 +0200 (CEST) Subject: [Returnanalytics-commits] r3776 - pkg/FactorAnalytics/tests Message-ID: <20150703050133.3E74A187A1D@r-forge.r-project.org> Author: pragnya Date: 2015-07-03 07:01:30 +0200 (Fri, 03 Jul 2015) New Revision: 3776 Added: pkg/FactorAnalytics/tests/FactorAnalytics_06_04_2015.pdf Removed: pkg/FactorAnalytics/tests/FactorAnalytics_04_25_15.pdf Log: Updated user manual Deleted: pkg/FactorAnalytics/tests/FactorAnalytics_04_25_15.pdf =================================================================== (Binary files differ) Added: pkg/FactorAnalytics/tests/FactorAnalytics_06_04_2015.pdf =================================================================== (Binary files differ) Property changes on: pkg/FactorAnalytics/tests/FactorAnalytics_06_04_2015.pdf ___________________________________________________________________ Added: svn:mime-type + application/octet-stream From noreply at r-forge.r-project.org Sun Jul 5 22:31:58 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 5 Jul 2015 22:31:58 +0200 (CEST) Subject: [Returnanalytics-commits] r3777 - in pkg/Dowd: R man Message-ID: <20150705203158.BDF08187B79@r-forge.r-project.org> Author: dacharya Date: 2015-07-05 22:31:58 +0200 (Sun, 05 Jul 2015) New Revision: 3777 Added: pkg/Dowd/R/KernelESBoxKernel.R pkg/Dowd/man/KernelESBoxKernel.Rd Log: KernelESBoxKernel added. Added: pkg/Dowd/R/KernelESBoxKernel.R =================================================================== --- pkg/Dowd/R/KernelESBoxKernel.R (rev 0) +++ pkg/Dowd/R/KernelESBoxKernel.R 2015-07-05 20:31:58 UTC (rev 3777) @@ -0,0 +1,29 @@ +#' Calculates ES using box 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 box kernel approach +#' Ra <- rnorm(30) +#' KernelESBoxKernel(Ra, .95) +#' +#' @export +KernelESBoxKernel <- 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] <- KernelVaRBoxKernel(PandL, cl + i * delta.cl) + } + ES <- mean(VaR) + return(ES) + +} Added: pkg/Dowd/man/KernelESBoxKernel.Rd =================================================================== --- pkg/Dowd/man/KernelESBoxKernel.Rd (rev 0) +++ pkg/Dowd/man/KernelESBoxKernel.Rd 2015-07-05 20:31:58 UTC (rev 3777) @@ -0,0 +1,31 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/KernelESBoxKernel.R +\name{KernelESBoxKernel} +\alias{KernelESBoxKernel} +\title{Calculates ES using box kernel approach} +\usage{ +KernelESBoxKernel(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 box kernel approach + Ra <- rnorm(30) + KernelESBoxKernel(Ra, .95) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Sun Jul 5 22:32:33 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 5 Jul 2015 22:32:33 +0200 (CEST) Subject: [Returnanalytics-commits] r3778 - in pkg/Dowd: R man Message-ID: <20150705203233.C483E187B79@r-forge.r-project.org> Author: dacharya Date: 2015-07-05 22:32:33 +0200 (Sun, 05 Jul 2015) New Revision: 3778 Added: pkg/Dowd/R/KernelVaRBoxKernel.R pkg/Dowd/man/KernelVaRBoxKernel.Rd Log: KernelVaRBoxKernel added. Added: pkg/Dowd/R/KernelVaRBoxKernel.R =================================================================== --- pkg/Dowd/R/KernelVaRBoxKernel.R (rev 0) +++ pkg/Dowd/R/KernelVaRBoxKernel.R 2015-07-05 20:32:33 UTC (rev 3778) @@ -0,0 +1,50 @@ +#' Calculates VaR using box 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 box kernel approach +#' Ra <- rnorm(30) +#' KernelVaRBoxKernel(Ra, .95) +#' +#' @export +KernelVaRBoxKernel <- function(Ra, cl) { + PandL <- as.vector(Ra) + mu <- mean(PandL) + sigma <- sd(PandL) + + # Obtain pdf values + kernel.data <- density(PandL, kernel = "rectangular", 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-07-05 22:33:01 +0200 (Sun, 05 Jul 2015) New Revision: 3779 Added: pkg/Dowd/R/PCAPrelim.R pkg/Dowd/man/PCAPrelim.Rd Log: PCAPrelim added. Added: pkg/Dowd/R/PCAPrelim.R =================================================================== --- pkg/Dowd/R/PCAPrelim.R (rev 0) +++ pkg/Dowd/R/PCAPrelim.R 2015-07-05 20:33:01 UTC (rev 3779) @@ -0,0 +1,68 @@ +#' PCAPrelim +#' +#' Estimates VaR plot using principal components analysis +#' +#' @param Ra Matrix return data set where each row is interpreted as a set of +#' daily observations, and each column as the returns to each position in a +#' portfolio +#' @param position.data Position-size vector, giving amount invested in each +#' position +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes PCA Prelim +#' Ra <- matrix(rnorm(4*4), 4, 4) +#' PCAPrelim(Ra) +#' +#' @import expm MASS +#' +#' @export +PCAPrelim <- function(Ra){ + rho <- as.matrix(Ra) + corr.matrix <- rbind(cbind(rho%^%0, rho%^%1, rho%^%2, rho%^%3, rho%^%4, + rho%^%5, rho%^%6, rho%^%7, rho%^%8, rho%^%9), + cbind(rho%^%1, rho%^%0, rho%^%1, rho%^%2, rho%^%3, + rho%^%4, rho%^%5, rho%^%6, rho%^%7, rho%^%8), + cbind(rho%^%2, rho%^%1, rho%^%0, rho%^%1, rho%^%2, + rho%^%3, rho%^%4, rho%^%5, rho%^%6, rho%^%7), + cbind(rho%^%3, rho%^%2, rho%^%1, rho%^%0, rho%^%1, + rho%^%2, rho%^%3, rho%^%4, rho%^%5, rho%^%6), + cbind(rho%^%4, rho%^%3, rho%^%2, rho%^%1, rho%^%0, + rho%^%1, rho%^%2, rho%^%3, rho%^%4, rho%^%5), + cbind(rho%^%5, rho%^%4, rho%^%3, rho%^%2, rho%^%1, + rho%^%0, rho%^%1, rho%^%2, rho%^%3, rho%^%4), + cbind(rho%^%6, rho%^%5, rho%^%4, rho%^%3, rho%^%2, + rho%^%1, rho%^%0, rho%^%1, rho%^%2, rho%^%3), + cbind(rho%^%7, rho%^%6, rho%^%5, rho%^%4, rho%^%3, + rho%^%2, rho%^%1, rho%^%0, rho%^%1, rho%^%2), + cbind(rho%^%8, rho%^%7, rho%^%6, rho%^%5, rho%^%4, + rho%^%3, rho%^%2, rho%^%1, rho%^%0, rho%^%1), + cbind(rho%^%9, rho%^%8, rho%^%7, rho%^%6, rho%^%5, + rho%^%4, rho%^%3, rho%^%2, rho%^%1, rho%^%0)) + mu <- double(10) + sigma <- corr.matrix + # Random number generation + returns <- mvrnorm(1000, mu, sigma) + # Dowd code uses princomp in matlab. Similar function "princomp" is available + # in "stats" package. However, the return values from princomp are not used + # explicitly. So, following alternative was used. + variances <- eigen(cov(returns))$values # eigenvalues of covariance matrix. + + # Scree Plot + n <- 1000 + par(c(2,1)) + percent.explained <- 100 * variances / sum(variances) + barplot(percent.explained, xlab = "%") + + cum.variance <- double(length(variances)) + cum.variance[1] <- percent.explained[1] + for (i in 2:length(variances)) { + cum.variances[i] <- percent.explained[i] + cum.variance[i-1] + } + t <- 0:10 + plot(t, c(0, cum_variance), xlab = "Principal component", ylab = "%") + title("Explanatory Power of the Principal Components") + +} Added: pkg/Dowd/man/PCAPrelim.Rd =================================================================== --- pkg/Dowd/man/PCAPrelim.Rd (rev 0) +++ pkg/Dowd/man/PCAPrelim.Rd 2015-07-05 20:33:01 UTC (rev 3779) @@ -0,0 +1,31 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/PCAPrelim.R +\name{PCAPrelim} +\alias{PCAPrelim} +\title{PCAPrelim} +\usage{ +PCAPrelim(Ra) +} +\arguments{ +\item{Ra}{Matrix return data set where each row is interpreted as a set of +daily observations, and each column as the returns to each position in a +portfolio} + +\item{position.data}{Position-size vector, giving amount invested in each +position} +} +\description{ +Estimates VaR plot using principal components analysis +} +\examples{ +# Computes PCA Prelim + Ra <- matrix(rnorm(4*4), 4, 4) + PCAPrelim(Ra) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Sun Jul 5 22:33:52 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 5 Jul 2015 22:33:52 +0200 (CEST) Subject: [Returnanalytics-commits] r3780 - pkg/Dowd Message-ID: <20150705203352.AAD78187B7A@r-forge.r-project.org> Author: dacharya Date: 2015-07-05 22:33:52 +0200 (Sun, 05 Jul 2015) New Revision: 3780 Modified: pkg/Dowd/NAMESPACE Log: KernelVaR and KernelES for Box Kernel, and PCAPrelim added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-05 20:33:01 UTC (rev 3779) +++ pkg/Dowd/NAMESPACE 2015-07-05 20:33:52 UTC (rev 3780) @@ -49,9 +49,11 @@ export(InsuranceVaR) export(JarqueBeraBacktest) export(KSTestStat) +export(KernelESBoxKernel) export(KernelESEpanechinikovKernel) export(KernelESNormalKernel) export(KernelESTriangleKernel) +export(KernelVaRBoxKernel) export(KernelVaREpanechinikovKernel) export(KernelVaRNormalKernel) export(KernelVaRTriangleKernel) @@ -61,10 +63,13 @@ export(NormalQQPlot) export(PCAES) export(PCAESPlot) +export(PCAPrelim) export(PCAVaR) export(PCAVaRPlot) export(PickandsEstimator) export(PickandsPlot) export(ProductCopulaVaR) export(TQQPlot) +import(MASS) import(bootstrap) +import(expm) From noreply at r-forge.r-project.org Mon Jul 6 18:47:37 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 6 Jul 2015 18:47:37 +0200 (CEST) Subject: [Returnanalytics-commits] r3781 - pkg/Dowd Message-ID: <20150706164737.84188187A1A@r-forge.r-project.org> Author: dacharya Date: 2015-07-06 18:47:37 +0200 (Mon, 06 Jul 2015) New Revision: 3781 Modified: pkg/Dowd/DESCRIPTION Log: Depends (MASS and espm) added. Modified: pkg/Dowd/DESCRIPTION =================================================================== --- pkg/Dowd/DESCRIPTION 2015-07-05 20:33:52 UTC (rev 3780) +++ pkg/Dowd/DESCRIPTION 2015-07-06 16:47:37 UTC (rev 3781) @@ -8,7 +8,9 @@ Description: This package is R-version of MMR2 Toolbox that supplements Kevin Dowd's book measuring market risk. Depends: R (>= 3.0.0), - bootstrap + bootstrap, + MASS, + expm Suggests: PerformanceAnalytics, testthat License: GPL From noreply at r-forge.r-project.org Mon Jul 6 20:04:46 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 6 Jul 2015 20:04:46 +0200 (CEST) Subject: [Returnanalytics-commits] r3782 - in pkg/Dowd: R man Message-ID: <20150706180446.D44E218698D@r-forge.r-project.org> Author: dacharya Date: 2015-07-06 20:04:46 +0200 (Mon, 06 Jul 2015) New Revision: 3782 Modified: pkg/Dowd/R/PCAPrelim.R pkg/Dowd/man/PCAPrelim.Rd Log: PCAPrelim example edited. Modified: pkg/Dowd/R/PCAPrelim.R =================================================================== --- pkg/Dowd/R/PCAPrelim.R 2015-07-06 16:47:37 UTC (rev 3781) +++ pkg/Dowd/R/PCAPrelim.R 2015-07-06 18:04:46 UTC (rev 3782) @@ -5,7 +5,6 @@ #' @param Ra Matrix return data set where each row is interpreted as a set of #' daily observations, and each column as the returns to each position in a #' portfolio -#' @param position.data Position-size vector, giving amount invested in each #' position #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' @@ -13,7 +12,11 @@ #' @examples #' #' # Computes PCA Prelim -#' Ra <- matrix(rnorm(4*4), 4, 4) +#' # This code was based on Dowd's code and similar to Dowd's code, +#' # it is inconsistent for non-scalar data (Ra). +#' library(MASS) +#' library(expm) +#' Ra <- .15 #' PCAPrelim(Ra) #' #' @import expm MASS @@ -41,8 +44,8 @@ rho%^%3, rho%^%2, rho%^%1, rho%^%0, rho%^%1), cbind(rho%^%9, rho%^%8, rho%^%7, rho%^%6, rho%^%5, rho%^%4, rho%^%3, rho%^%2, rho%^%1, rho%^%0)) - mu <- double(10) sigma <- corr.matrix + mu <- double(dim(sigma)[1]) # Random number generation returns <- mvrnorm(1000, mu, sigma) # Dowd code uses princomp in matlab. Similar function "princomp" is available @@ -59,10 +62,10 @@ cum.variance <- double(length(variances)) cum.variance[1] <- percent.explained[1] for (i in 2:length(variances)) { - cum.variances[i] <- percent.explained[i] + cum.variance[i-1] + cum.variance[i] <- percent.explained[i] + cum.variance[i-1] } t <- 0:10 - plot(t, c(0, cum_variance), xlab = "Principal component", ylab = "%") + plot(t, c(0, cum.variance), xlab = "Principal component", ylab = "%", type="l") title("Explanatory Power of the Principal Components") } Modified: pkg/Dowd/man/PCAPrelim.Rd =================================================================== --- pkg/Dowd/man/PCAPrelim.Rd 2015-07-06 16:47:37 UTC (rev 3781) +++ pkg/Dowd/man/PCAPrelim.Rd 2015-07-06 18:04:46 UTC (rev 3782) @@ -9,9 +9,7 @@ \arguments{ \item{Ra}{Matrix return data set where each row is interpreted as a set of daily observations, and each column as the returns to each position in a -portfolio} - -\item{position.data}{Position-size vector, giving amount invested in each +portfolio position} } \description{ @@ -19,7 +17,11 @@ } \examples{ # Computes PCA Prelim - Ra <- matrix(rnorm(4*4), 4, 4) + # This code was based on Dowd's code and similar to Dowd's code, + # it is inconsistent for non-scalar data (Ra). + library(MASS) + library(expm) + Ra <- .15 PCAPrelim(Ra) } \author{ From noreply at r-forge.r-project.org Mon Jul 6 23:59:32 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 6 Jul 2015 23:59:32 +0200 (CEST) Subject: [Returnanalytics-commits] r3783 - pkg/Dowd Message-ID: <20150706215932.4298F187A3D@r-forge.r-project.org> Author: dacharya Date: 2015-07-06 23:59:31 +0200 (Mon, 06 Jul 2015) New Revision: 3783 Modified: pkg/Dowd/NAMESPACE Log: Function LogtVaR added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-06 18:04:46 UTC (rev 3782) +++ pkg/Dowd/NAMESPACE 2015-07-06 21:59:31 UTC (rev 3783) @@ -58,6 +58,7 @@ export(KernelVaRNormalKernel) export(KernelVaRTriangleKernel) export(KuiperTestStat) +export(LogtVaR) export(LopezBacktest) export(MEFPlot) export(NormalQQPlot) From noreply at r-forge.r-project.org Tue Jul 7 00:00:02 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 7 Jul 2015 00:00:02 +0200 (CEST) Subject: [Returnanalytics-commits] r3784 - in pkg/Dowd: R man Message-ID: <20150706220002.5DF97187A3D@r-forge.r-project.org> Author: dacharya Date: 2015-07-07 00:00:02 +0200 (Tue, 07 Jul 2015) New Revision: 3784 Added: pkg/Dowd/R/LogtVaR.R pkg/Dowd/man/LogtVaR.Rd Log: LogtVaR function added. Added: pkg/Dowd/R/LogtVaR.R =================================================================== --- pkg/Dowd/R/LogtVaR.R (rev 0) +++ pkg/Dowd/R/LogtVaR.R 2015-07-06 22:00:02 UTC (rev 3784) @@ -0,0 +1,114 @@ +#' VaR for t distributed geometric returns +#' +#' Estimates the VaR of a portfolio assuming that geometric returns are +#' Student t distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param df Number of degrees of freedom in the t distribution +#' @param cl VaR confidence level +#' @param hp VaR holding period +#' @return Matrix of VaRs whose dimension depends on dimension of hp and cl. If +#' cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is +#' a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, +#' the matrix is column matrix and if both cl and hp are vectors, the matrix +#' has dimension length of cl * length of hp. +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 6. In case there 5 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes VaR given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogtVaR(returns = data, investment = 5, df = 6, cl = .95, hp = 90) +#' +#' # Computes VaR given mean and standard deviation of return data +#' LogtVaR(mu = .012, sigma = .03, investment = 5, df = 6, cl = .95, hp = 90) +#' +#' +#' @export +LogtVaR <- function(...){ + if (nargs() < 5) { + stop("Too few arguments") + } + if (nargs() > 6) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 6) { + mu <- args$mu + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 5) { + mu <- mean(args$returns) + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar or a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar or a vector") + } + + # Check that cl and hp are read as row and column vectors respectively + if (cl.row > cl.col) { + cl <- t(cl) + } + if (hp.row > hp.col) { + hp <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + # VaR estimation + y <- investment - exp(((df - 2) / 2) * sigma %*% sqrt(t(hp)) %*% qt(1 - cl, df) + + mu * t(hp) %*% matrix(1, cl.row, cl.col) + log(investment)) # VaR + return (y) +} Added: pkg/Dowd/man/LogtVaR.Rd =================================================================== --- pkg/Dowd/man/LogtVaR.Rd (rev 0) +++ pkg/Dowd/man/LogtVaR.Rd 2015-07-06 22:00:02 UTC (rev 3784) @@ -0,0 +1,55 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogtVaR.R +\name{LogtVaR} +\alias{LogtVaR} +\title{VaR for t distributed geometric returns} +\usage{ +LogtVaR(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{df}{Number of degrees of freedom in the t distribution} + +\item{cl}{VaR confidence level} + +\item{hp}{VaR holding period} +} +\value{ +Matrix of VaRs whose dimension depends on dimension of hp and cl. If +cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is + a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, + the matrix is column matrix and if both cl and hp are vectors, the matrix + has dimension length of cl * length of hp. +} +\description{ +Estimates the VaR of a portfolio assuming that geometric returns are +Student t distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 5 + or 6. In case there 5 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Computes VaR given geometric return data + data <- runif(5, min = 0, max = .2) + LogtVaR(returns = data, investment = 5, df = 6, cl = .95, hp = 90) + + # Computes VaR given mean and standard deviation of return data + LogtVaR(mu = .012, sigma = .03, investment = 5, df = 6, cl = .95, hp = 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jul 7 00:34:06 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 7 Jul 2015 00:34:06 +0200 (CEST) Subject: [Returnanalytics-commits] r3785 - pkg/Dowd Message-ID: <20150706223406.CEF861879F4@r-forge.r-project.org> Author: dacharya Date: 2015-07-07 00:34:06 +0200 (Tue, 07 Jul 2015) New Revision: 3785 Modified: pkg/Dowd/NAMESPACE Log: Function LogtES added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-06 22:00:02 UTC (rev 3784) +++ pkg/Dowd/NAMESPACE 2015-07-06 22:34:06 UTC (rev 3785) @@ -58,6 +58,7 @@ export(KernelVaRNormalKernel) export(KernelVaRTriangleKernel) export(KuiperTestStat) +export(LogtES) export(LogtVaR) export(LopezBacktest) export(MEFPlot) From noreply at r-forge.r-project.org Tue Jul 7 00:34:29 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 7 Jul 2015 00:34:29 +0200 (CEST) Subject: [Returnanalytics-commits] r3786 - in pkg/Dowd: R man Message-ID: <20150706223429.A12BA1879F4@r-forge.r-project.org> Author: dacharya Date: 2015-07-07 00:34:29 +0200 (Tue, 07 Jul 2015) New Revision: 3786 Added: pkg/Dowd/R/LogtES.R pkg/Dowd/man/LogtES.Rd Log: Function LogtES added. Added: pkg/Dowd/R/LogtES.R =================================================================== --- pkg/Dowd/R/LogtES.R (rev 0) +++ pkg/Dowd/R/LogtES.R 2015-07-06 22:34:29 UTC (rev 3786) @@ -0,0 +1,126 @@ +#' ES for t distributed geometric returns +#' +#' Estimates the ES of a portfolio assuming that geometric returns are +#' Student t distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param df Number of degrees of freedom in the t distribution +#' @param cl VaR confidence level +#' @param hp VaR holding period +#' @return Matrix of ES whose dimension depends on dimension of hp and cl. If +#' cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is +#' a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, +#' the matrix is column matrix and if both cl and hp are vectors, the matrix +#' has dimension length of cl * length of hp. +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 6. In case there 5 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes ES given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogtES(returns = data, investment = 5, df = 6, cl = .95, hp = 90) +#' +#' # Computes ES given mean and standard deviation of return data +#' LogtES(mu = .012, sigma = .03, investment = 5, df = 6, cl = .95, hp = 90) +#' +#' +#' @export +LogtES <- function(...){ + if (nargs() < 5) { + stop("Too few arguments") + } + if (nargs() > 6) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 6) { + mu <- args$mu + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 5) { + mu <- mean(args$returns) + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar or a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar or a vector") + } + + # Check that cl and hp are read as row and column vectors respectively + if (cl.row > cl.col) { + cl <- t(cl) + } + if (hp.row > hp.col) { + hp <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + # VaR estimation + VaR <- investment - exp(((df - 2) / df) * sigma %*% sqrt(t(hp)) %*% qt(1 - cl, df) + + mu * t(hp) %*% matrix(1, cl.row, cl.col) + log(investment)) # VaR + # ES estimation + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + term <- VaR + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl # Revised cl + term <- term + investment - exp(((df - 2) / df) * sigma %*% sqrt(t(hp)) %*% + qt(1 - cl, df) + mu * t(hp) %*% + matrix(1, cl.row, cl.col) + log(investment)) + } + y <- term/n + return (y) +} Added: pkg/Dowd/man/LogtES.Rd =================================================================== --- pkg/Dowd/man/LogtES.Rd (rev 0) +++ pkg/Dowd/man/LogtES.Rd 2015-07-06 22:34:29 UTC (rev 3786) @@ -0,0 +1,55 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogtES.R +\name{LogtES} +\alias{LogtES} +\title{ES for t distributed geometric returns} +\usage{ +LogtES(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{df}{Number of degrees of freedom in the t distribution} + +\item{cl}{VaR confidence level} + +\item{hp}{VaR holding period} +} +\value{ +Matrix of ES whose dimension depends on dimension of hp and cl. If +cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is + a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, + the matrix is column matrix and if both cl and hp are vectors, the matrix + has dimension length of cl * length of hp. +} +\description{ +Estimates the ES of a portfolio assuming that geometric returns are +Student t distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 5 + or 6. In case there 5 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Computes ES given geometric return data + data <- runif(5, min = 0, max = .2) + LogtES(returns = data, investment = 5, df = 6, cl = .95, hp = 90) + + # Computes ES given mean and standard deviation of return data + LogtES(mu = .012, sigma = .03, investment = 5, df = 6, cl = .95, hp = 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jul 7 18:05:45 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 7 Jul 2015 18:05:45 +0200 (CEST) Subject: [Returnanalytics-commits] r3787 - pkg/Dowd/R Message-ID: <20150707160545.82BB9187290@r-forge.r-project.org> Author: dacharya Date: 2015-07-07 18:05:44 +0200 (Tue, 07 Jul 2015) New Revision: 3787 Modified: pkg/Dowd/R/LogtES.R Log: Mistake in ES computation. Modified: pkg/Dowd/R/LogtES.R =================================================================== --- pkg/Dowd/R/LogtES.R 2015-07-06 22:34:29 UTC (rev 3786) +++ pkg/Dowd/R/LogtES.R 2015-07-07 16:05:44 UTC (rev 3787) @@ -123,4 +123,4 @@ } y <- term/n return (y) -} +} \ No newline at end of file From noreply at r-forge.r-project.org Wed Jul 8 00:13:08 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 8 Jul 2015 00:13:08 +0200 (CEST) Subject: [Returnanalytics-commits] r3788 - pkg/Dowd Message-ID: <20150707221308.72B3C184636@r-forge.r-project.org> Author: dacharya Date: 2015-07-08 00:13:08 +0200 (Wed, 08 Jul 2015) New Revision: 3788 Modified: pkg/Dowd/NAMESPACE Log: Two functions: LogtESPlot2DHP and LogtVaRPlot2DHP added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-07 16:05:44 UTC (rev 3787) +++ pkg/Dowd/NAMESPACE 2015-07-07 22:13:08 UTC (rev 3788) @@ -59,7 +59,9 @@ export(KernelVaRTriangleKernel) export(KuiperTestStat) export(LogtES) +export(LogtESPlot2DHP) export(LogtVaR) +export(LogtVaRPlot2DHP) export(LopezBacktest) export(MEFPlot) export(NormalQQPlot) From noreply at r-forge.r-project.org Wed Jul 8 00:15:57 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 8 Jul 2015 00:15:57 +0200 (CEST) Subject: [Returnanalytics-commits] r3789 - in pkg/Dowd: R man Message-ID: <20150707221557.B7196184636@r-forge.r-project.org> Author: dacharya Date: 2015-07-08 00:15:57 +0200 (Wed, 08 Jul 2015) New Revision: 3789 Added: pkg/Dowd/R/LogtESPlot2DHP.R pkg/Dowd/man/LogtESPlot2DHP.Rd Log: LogtESPlot2DHP added. Added: pkg/Dowd/R/LogtESPlot2DHP.R =================================================================== --- pkg/Dowd/R/LogtESPlot2DHP.R (rev 0) +++ pkg/Dowd/R/LogtESPlot2DHP.R 2015-07-07 22:15:57 UTC (rev 3789) @@ -0,0 +1,135 @@ +#' Plots log-t ES against holding period +#' +#' Plots the ES of a portfolio against holding period assuming that geometric returns are +#' Student t distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param df Number of degrees of freedom in the t distribution +#' @param cl ES confidence level and must be a scalar +#' @param hp ES holding period and must be a vector +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 6. In case there 5 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes ES given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogtESPlot2DHP(returns = data, investment = 5, df = 6, cl = .95, hp = 60:90) +#' +#' # Computes v given mean and standard deviation of return data +#' LogtESPlot2DHP(mu = .012, sigma = .03, investment = 5, df = 6, cl = .99, hp = 40:80) +#' +#' +#' @export +LogtESPlot2DHP <- function(...){ + if (nargs() < 5) { + stop("Too few arguments") + } + if (nargs() > 6) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 6) { + mu <- args$mu + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 5) { + mu <- mean(args$returns) + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (max(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a vector") + } + + # Check that hp is read as row vector + if (hp.row > hp.col) { + hp <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + # VaR estimation + VaR <- investment - exp(((df - 2) / 2) * sigma[1,1] * sqrt(t(hp)) * qt(1 - cl[1,1], df) + + mu[1,1] * t(hp) %*% matrix(1, cl.row, cl.col) + log(investment)) # VaR + + # ES etimation + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + v <- VaR + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl # Revised cl + v <- v + investment - exp(((df - 2) / df) * sigma[1,1] * sqrt(t(hp)) * + qt(1 - cl[1,1], df) + mu[1,1] * t(hp) %*% + matrix(1, cl.row, cl.col) + log(investment)) + } + v <- v/n + + # Plotting + plot(hp, v, type = "l", xlab = "Holding Period", ylab = "ES") + title("Log-t ES against holding period") + xmin <-min(hp)+.25*(max(hp)-min(hp)) + text(xmin,max(v)-.1*(max(v)-min(v)), + 'Input parameters', cex=.75, font = 2) + text(xmin,max(v)-.15*(max(v)-min(v)), + paste('Daily mean geometric return = ',mu[1,1]),cex=.75) + text(xmin,max(v)-.2*(max(v)-min(v)), + paste('Stdev. of daily geometric returns = ',sigma[1,1]),cex=.75) + text(xmin,max(v)-.25*(max(v)-min(v)), + paste('Degrees of freedom = ',df),cex=.75) + text(xmin,max(v)-.3*(max(v)-min(v)), + paste('Investment size = ',investment),cex=.75) + text(xmin,max(v)-.35*(max(v)-min(v)), + paste('Confidence level = ',cl,'%'),cex=.75) +} Added: pkg/Dowd/man/LogtESPlot2DHP.Rd =================================================================== --- pkg/Dowd/man/LogtESPlot2DHP.Rd (rev 0) +++ pkg/Dowd/man/LogtESPlot2DHP.Rd 2015-07-07 22:15:57 UTC (rev 3789) @@ -0,0 +1,48 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogtESPlot2DHP.R +\name{LogtESPlot2DHP} +\alias{LogtESPlot2DHP} +\title{Plots log-t ES against holding period} +\usage{ +LogtESPlot2DHP(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{df}{Number of degrees of freedom in the t distribution} + +\item{cl}{ES confidence level and must be a scalar} + +\item{hp}{ES holding period and must be a vector} +} +\description{ +Plots the ES of a portfolio against holding period assuming that geometric returns are +Student t distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 5 + or 6. In case there 5 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Computes ES given geometric return data + data <- runif(5, min = 0, max = .2) + LogtESPlot2DHP(returns = data, investment = 5, df = 6, cl = .95, hp = 60:90) + + # Computes v given mean and standard deviation of return data + LogtESPlot2DHP(mu = .012, sigma = .03, investment = 5, df = 6, cl = .99, hp = 40:80) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Wed Jul 8 00:16:23 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 8 Jul 2015 00:16:23 +0200 (CEST) Subject: [Returnanalytics-commits] r3790 - in pkg/Dowd: R man Message-ID: <20150707221623.ACA6A184636@r-forge.r-project.org> Author: dacharya Date: 2015-07-08 00:16:23 +0200 (Wed, 08 Jul 2015) New Revision: 3790 Added: pkg/Dowd/R/LogtVaRPlot2DHP.R pkg/Dowd/man/LogtVaRPlot2DHP.Rd Log: LogtVaRPlot2DHP added. Added: pkg/Dowd/R/LogtVaRPlot2DHP.R =================================================================== --- pkg/Dowd/R/LogtVaRPlot2DHP.R (rev 0) +++ pkg/Dowd/R/LogtVaRPlot2DHP.R 2015-07-07 22:16:23 UTC (rev 3790) @@ -0,0 +1,121 @@ +#' Plots log-t VaR against holding period +#' +#' Plots the VaR of a portfolio against holding period assuming that geometric returns are +#' Student t distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param df Number of degrees of freedom in the t distribution +#' @param cl VaR confidence level and must be a scalar +#' @param hp VaR holding period and must be a vector +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 6. In case there 5 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes VaR given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogtVaRPlot2DHP(returns = data, investment = 5, df = 6, cl = .95, hp = 60:90) +#' +#' # Computes VaR given mean and standard deviation of return data +#' LogtVaRPlot2DHP(mu = .012, sigma = .03, investment = 5, df = 6, cl = .99, hp = 40:80) +#' +#' +#' @export +LogtVaRPlot2DHP <- function(...){ + if (nargs() < 5) { + stop("Too few arguments") + } + if (nargs() > 6) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 6) { + mu <- args$mu + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 5) { + mu <- mean(args$returns) + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (max(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a vector") + } + + # Check that hp is read as row vector + if (hp.row > hp.col) { + hp <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + # VaR estimation + VaR <- investment - exp(((df - 2) / df) * sigma[1,1] * sqrt(t(hp)) * qt(1 - cl[1,1], df) + + mu[1,1] * t(hp) %*% matrix(1, cl.row, cl.col) + log(investment)) # VaR + # Plotting + plot(hp, VaR, type = "l", xlab = "Holding Period", ylab = "VaR") + title("Log-t VaR against holding period") + xmin <-min(hp)+.25*(max(hp)-min(hp)) + text(xmin,max(VaR)-.1*(max(VaR)-min(VaR)), + 'Input parameters', cex=.75, font = 2) + text(xmin,max(VaR)-.15*(max(VaR)-min(VaR)), + paste('Daily mean geometric return = ',mu[1,1]),cex=.75) + text(xmin,max(VaR)-.2*(max(VaR)-min(VaR)), + paste('Stdev. of daily geometric returns = ',sigma[1,1]),cex=.75) + text(xmin,max(VaR)-.25*(max(VaR)-min(VaR)), + paste('Degrees of freedom = ',df),cex=.75) + text(xmin,max(VaR)-.3*(max(VaR)-min(VaR)), + paste('Investment size = ',investment),cex=.75) + text(xmin,max(VaR)-.35*(max(VaR)-min(VaR)), + paste('Confidence level = ',cl,'%'),cex=.75) +} Added: pkg/Dowd/man/LogtVaRPlot2DHP.Rd =================================================================== --- pkg/Dowd/man/LogtVaRPlot2DHP.Rd (rev 0) +++ pkg/Dowd/man/LogtVaRPlot2DHP.Rd 2015-07-07 22:16:23 UTC (rev 3790) @@ -0,0 +1,48 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogtVaRPlot2DHP.R +\name{LogtVaRPlot2DHP} +\alias{LogtVaRPlot2DHP} +\title{Plots log-t VaR against holding period} +\usage{ +LogtVaRPlot2DHP(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{df}{Number of degrees of freedom in the t distribution} + +\item{cl}{VaR confidence level and must be a scalar} + +\item{hp}{VaR holding period and must be a vector} +} +\description{ +Plots the VaR of a portfolio against holding period assuming that geometric returns are +Student t distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 5 + or 6. In case there 5 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Computes VaR given geometric return data + data <- runif(5, min = 0, max = .2) + LogtVaRPlot2DHP(returns = data, investment = 5, df = 6, cl = .95, hp = 60:90) + + # Computes VaR given mean and standard deviation of return data + LogtVaRPlot2DHP(mu = .012, sigma = .03, investment = 5, df = 6, cl = .99, hp = 40:80) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Wed Jul 8 14:32:02 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 8 Jul 2015 14:32:02 +0200 (CEST) Subject: [Returnanalytics-commits] r3791 - in pkg/Dowd: . R man Message-ID: <20150708123202.3FB521858DF@r-forge.r-project.org> Author: dacharya Date: 2015-07-08 14:32:01 +0200 (Wed, 08 Jul 2015) New Revision: 3791 Added: pkg/Dowd/R/LogtVaRPlot2DCL.R pkg/Dowd/man/LogtVaRPlot2DCL.Rd Modified: pkg/Dowd/NAMESPACE Log: Function LogtVaRPlot2DCL added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-07 22:16:23 UTC (rev 3790) +++ pkg/Dowd/NAMESPACE 2015-07-08 12:32:01 UTC (rev 3791) @@ -61,6 +61,7 @@ export(LogtES) export(LogtESPlot2DHP) export(LogtVaR) +export(LogtVaRPlot2DCL) export(LogtVaRPlot2DHP) export(LopezBacktest) export(MEFPlot) Added: pkg/Dowd/R/LogtVaRPlot2DCL.R =================================================================== --- pkg/Dowd/R/LogtVaRPlot2DCL.R (rev 0) +++ pkg/Dowd/R/LogtVaRPlot2DCL.R 2015-07-08 12:32:01 UTC (rev 3791) @@ -0,0 +1,122 @@ +#' Plots log-t VaR against confidence level +#' +#' Plots the VaR of a portfolio against confidence level assuming that geometric +#' returns are Student-t distributed, for specified confidence level and +#' holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param df Number of degrees of freedom in the t distribution +#' @param cl VaR confidence level and must be a vector +#' @param hp VaR holding period and must be a scalar +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 6. In case there 5 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots VaR against confidene level given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogtVaRPlot2DCL(returns = data, investment = 5, df = 6, cl = seq(.85,.99,.01), hp = 60) +#' +#' # Computes VaR against confidence level given mean and standard deviation of return data +#' LogtVaRPlot2DCL(mu = .012, sigma = .03, investment = 5, df = 6, cl = seq(.85,.99,.01), hp = 40) +#' +#' +#' @export +LogtVaRPlot2DCL <- function(...){ + if (nargs() < 5) { + stop("Too few arguments") + } + if (nargs() > 6) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 6) { + mu <- args$mu + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 5) { + mu <- mean(args$returns) + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that cl is read as row vector + if (cl.row > cl.col) { + cl <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + # VaR estimation + VaR <- investment - exp( ((df-2)/df)*sigma[1,1] * sqrt(hp[1,1]) * qt(1 - cl, df)+mu[1,1]*hp[1,1]*matrix(1,cl.col,cl.row) + log(investment) + ) # VaR + # Plotting + plot(cl, VaR, type = "l", xlab = "Holding Period", ylab = "VaR") + title("Log-t VaR against holding period") + xmin <-min(cl)+.3*(max(cl)-min(cl)) + text(xmin,max(VaR)-.1*(max(VaR)-min(VaR)), + 'Input parameters', cex=.75, font = 2) + text(xmin,max(VaR)-.15*(max(VaR)-min(VaR)), + paste('Daily mean geometric return = ',round(mu[1,1],3)),cex=.75) + text(xmin,max(VaR)-.2*(max(VaR)-min(VaR)), + paste('Stdev. of daily geometric returns = ',round(sigma[1,1],3)),cex=.75) + text(xmin,max(VaR)-.25*(max(VaR)-min(VaR)), + paste('Degrees of freedom = ',df),cex=.75) + text(xmin,max(VaR)-.3*(max(VaR)-min(VaR)), + paste('Investment size = ',investment),cex=.75) + text(xmin,max(VaR)-.35*(max(VaR)-min(VaR)), + paste('Holding period = ',hp,'days'),cex=.75) +} Added: pkg/Dowd/man/LogtVaRPlot2DCL.Rd =================================================================== --- pkg/Dowd/man/LogtVaRPlot2DCL.Rd (rev 0) +++ pkg/Dowd/man/LogtVaRPlot2DCL.Rd 2015-07-08 12:32:01 UTC (rev 3791) @@ -0,0 +1,49 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogtVaRPlot2DCL.R +\name{LogtVaRPlot2DCL} +\alias{LogtVaRPlot2DCL} +\title{Plots log-t VaR against confidence level} +\usage{ +LogtVaRPlot2DCL(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{df}{Number of degrees of freedom in the t distribution} + +\item{cl}{VaR confidence level and must be a vector} + +\item{hp}{VaR holding period and must be a scalar} +} +\description{ +Plots the VaR of a portfolio against confidence level assuming that geometric + returns are Student-t distributed, for specified confidence level and + holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 5 + or 6. In case there 5 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Plots VaR against confidene level given geometric return data + data <- runif(5, min = 0, max = .2) + LogtVaRPlot2DCL(returns = data, investment = 5, df = 6, cl = seq(.85,.99,.01), hp = 60) + + # Computes VaR against confidence level given mean and standard deviation of return data + LogtVaRPlot2DCL(mu = .012, sigma = .03, investment = 5, df = 6, cl = seq(.85,.99,.01), hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Wed Jul 8 14:35:49 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 8 Jul 2015 14:35:49 +0200 (CEST) Subject: [Returnanalytics-commits] r3792 - pkg/Dowd/R Message-ID: <20150708123549.5FE781858DF@r-forge.r-project.org> Author: dacharya Date: 2015-07-08 14:35:49 +0200 (Wed, 08 Jul 2015) New Revision: 3792 Modified: pkg/Dowd/R/LogtVaRPlot2DCL.R Log: Label in plot corrected. Modified: pkg/Dowd/R/LogtVaRPlot2DCL.R =================================================================== --- pkg/Dowd/R/LogtVaRPlot2DCL.R 2015-07-08 12:32:01 UTC (rev 3791) +++ pkg/Dowd/R/LogtVaRPlot2DCL.R 2015-07-08 12:35:49 UTC (rev 3792) @@ -101,11 +101,11 @@ stop("Confidence level(s) must be greater than 0") } # VaR estimation - VaR <- investment - exp( ((df-2)/df)*sigma[1,1] * sqrt(hp[1,1]) * qt(1 - cl, df)+mu[1,1]*hp[1,1]*matrix(1,cl.col,cl.row) + log(investment) + VaR <- investment - exp(((df-2)/df)*sigma[1,1] * sqrt(hp[1,1]) * qt(1 - cl, df)+mu[1,1]*hp[1,1]*matrix(1,cl.col,cl.row) + log(investment) ) # VaR # Plotting - plot(cl, VaR, type = "l", xlab = "Holding Period", ylab = "VaR") - title("Log-t VaR against holding period") + plot(cl, VaR, type = "l", xlab = "Confidence Level", ylab = "VaR") + title("Log-t VaR against confidence level") xmin <-min(cl)+.3*(max(cl)-min(cl)) text(xmin,max(VaR)-.1*(max(VaR)-min(VaR)), 'Input parameters', cex=.75, font = 2) From noreply at r-forge.r-project.org Wed Jul 8 16:47:32 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 8 Jul 2015 16:47:32 +0200 (CEST) Subject: [Returnanalytics-commits] r3793 - pkg/Dowd Message-ID: <20150708144732.19A251879F3@r-forge.r-project.org> Author: dacharya Date: 2015-07-08 16:47:31 +0200 (Wed, 08 Jul 2015) New Revision: 3793 Modified: pkg/Dowd/NAMESPACE Log: Function LogtESPlot2DCL added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-08 12:35:49 UTC (rev 3792) +++ pkg/Dowd/NAMESPACE 2015-07-08 14:47:31 UTC (rev 3793) @@ -59,6 +59,7 @@ export(KernelVaRTriangleKernel) export(KuiperTestStat) export(LogtES) +export(LogtESPlot2DCL) export(LogtESPlot2DHP) export(LogtVaR) export(LogtVaRPlot2DCL) From noreply at r-forge.r-project.org Wed Jul 8 16:48:06 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 8 Jul 2015 16:48:06 +0200 (CEST) Subject: [Returnanalytics-commits] r3794 - in pkg/Dowd: R man Message-ID: <20150708144806.D3B36187A60@r-forge.r-project.org> Author: dacharya Date: 2015-07-08 16:48:06 +0200 (Wed, 08 Jul 2015) New Revision: 3794 Added: pkg/Dowd/R/LogtESPlot2DCL.R pkg/Dowd/man/LogtESPlot2DCL.Rd Log: Function LogtESPlot2DCL added. Added: pkg/Dowd/R/LogtESPlot2DCL.R =================================================================== --- pkg/Dowd/R/LogtESPlot2DCL.R (rev 0) +++ pkg/Dowd/R/LogtESPlot2DCL.R 2015-07-08 14:48:06 UTC (rev 3794) @@ -0,0 +1,135 @@ +#' Plots log-t ES against confidence level +#' +#' Plots the ES of a portfolio against confidence level assuming that geometric returns are +#' Student t distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param df Number of degrees of freedom in the t distribution +#' @param cl ES confidence level and must be a vector +#' @param hp ES holding period and must be a scalar +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 6. In case there 5 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes ES given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogtESPlot2DCL(returns = data, investment = 5, df = 6, cl = seq(.9,.99,.01), hp = 60) +#' +#' # Computes v given mean and standard deviation of return data +#' LogtESPlot2DCL(mu = .012, sigma = .03, investment = 5, df = 6, cl = seq(.9,.99,.01), hp = 40) +#' +#' +#' @export +LogtESPlot2DCL <- function(...){ + if (nargs() < 5) { + stop("Too few arguments") + } + if (nargs() > 6) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 6) { + mu <- args$mu + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 5) { + mu <- mean(args$returns) + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that hp is read as row vector + if (cl.row > cl.col) { + cl <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + # VaR estimation + VaR <- investment - exp(((df - 2) / df) * sigma[1,1] * sqrt(hp[1,1]) * qt(1 - cl[1,1], df) + + mu[1,1] * t(hp[1,1]) * matrix(1, cl.col, cl.row) + log(investment)) # VaR + + # ES etimation + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + v <- VaR + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl # Revised cl + v <- v + investment - exp(((df - 2) / df) * sigma[1,1] * sqrt(hp[1,1]) * + qt(1 - cl, df) + mu[1,1] * hp[1,1] * + matrix(1, cl.col, cl.row) + log(investment)) + } + v <- v/n + + # Plotting + plot(cl, v, type = "l", xlab = "Holding Period", ylab = "ES") + title("Log-t ES against holding period") + xmin <-min(cl)+.25*(max(cl)-min(cl)) + text(xmin,max(v)-.1*(max(v)-min(v)), + 'Input parameters', cex=.75, font = 2) + text(xmin,max(v)-.15*(max(v)-min(v)), + paste('Daily mean geometric return = ',mu[1,1]),cex=.75) + text(xmin,max(v)-.2*(max(v)-min(v)), + paste('Stdev. of daily geometric returns = ',sigma[1,1]),cex=.75) + text(xmin,max(v)-.25*(max(v)-min(v)), + paste('Degrees of freedom = ',df),cex=.75) + text(xmin,max(v)-.3*(max(v)-min(v)), + paste('Investment size = ',investment),cex=.75) + text(xmin,max(v)-.35*(max(v)-min(v)), + paste('Confidence level = ',cl,'%'),cex=.75) +} Added: pkg/Dowd/man/LogtESPlot2DCL.Rd =================================================================== --- pkg/Dowd/man/LogtESPlot2DCL.Rd (rev 0) +++ pkg/Dowd/man/LogtESPlot2DCL.Rd 2015-07-08 14:48:06 UTC (rev 3794) @@ -0,0 +1,48 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogtESPlot2DCL.R +\name{LogtESPlot2DCL} +\alias{LogtESPlot2DCL} +\title{Plots log-t ES against confidence level} +\usage{ +LogtESPlot2DCL(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{df}{Number of degrees of freedom in the t distribution} + +\item{cl}{ES confidence level and must be a vector} + +\item{hp}{ES holding period and must be a scalar} +} +\description{ +Plots the ES of a portfolio against confidence level assuming that geometric returns are +Student t distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 5 + or 6. In case there 5 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Computes ES given geometric return data + data <- runif(5, min = 0, max = .2) + LogtESPlot2DCL(returns = data, investment = 5, df = 6, cl = seq(.9,.99,.01), hp = 60) + + # Computes v given mean and standard deviation of return data + LogtESPlot2DCL(mu = .012, sigma = .03, investment = 5, df = 6, cl = seq(.9,.99,.01), hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Thu Jul 9 16:15:13 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 9 Jul 2015 16:15:13 +0200 (CEST) Subject: [Returnanalytics-commits] r3795 - pkg/Dowd Message-ID: <20150709141513.AF624185CC4@r-forge.r-project.org> Author: dacharya Date: 2015-07-09 16:15:13 +0200 (Thu, 09 Jul 2015) New Revision: 3795 Modified: pkg/Dowd/NAMESPACE Log: Functions LogtESDFperc, LogtVaRDFperc, LogESPlot2DCL, LogtESPlot2D and LogtVaRPlot2D added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-08 14:48:06 UTC (rev 3794) +++ pkg/Dowd/NAMESPACE 2015-07-09 14:15:13 UTC (rev 3795) @@ -59,11 +59,15 @@ export(KernelVaRTriangleKernel) export(KuiperTestStat) export(LogtES) +export(LogtESDFPerc) export(LogtESPlot2DCL) export(LogtESPlot2DHP) +export(LogtESPlot3D) export(LogtVaR) +export(LogtVaRDFPerc) export(LogtVaRPlot2DCL) export(LogtVaRPlot2DHP) +export(LogtVaRPlot3D) export(LopezBacktest) export(MEFPlot) export(NormalQQPlot) From noreply at r-forge.r-project.org Thu Jul 9 16:16:46 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 9 Jul 2015 16:16:46 +0200 (CEST) Subject: [Returnanalytics-commits] r3796 - in pkg/Dowd: R man Message-ID: <20150709141646.8C3E2185CC4@r-forge.r-project.org> Author: dacharya Date: 2015-07-09 16:16:46 +0200 (Thu, 09 Jul 2015) New Revision: 3796 Modified: pkg/Dowd/R/HSESDFPerc.R pkg/Dowd/man/HSESDFPerc.Rd Log: Function HSESDFPerc added. Modified: pkg/Dowd/R/HSESDFPerc.R =================================================================== --- pkg/Dowd/R/HSESDFPerc.R 2015-07-09 14:15:13 UTC (rev 3795) +++ pkg/Dowd/R/HSESDFPerc.R 2015-07-09 14:16:46 UTC (rev 3796) @@ -1,82 +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) - +#' @title Percentile of historical simulation ES distribution function +#' +#' @description Estimates percentiles of historical simulation ES 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 Modified: pkg/Dowd/man/HSESDFPerc.Rd =================================================================== --- pkg/Dowd/man/HSESDFPerc.Rd 2015-07-09 14:15:13 UTC (rev 3795) +++ pkg/Dowd/man/HSESDFPerc.Rd 2015-07-09 14:16:46 UTC (rev 3796) @@ -2,7 +2,7 @@ % Please edit documentation in R/HSESDFPerc.R \name{HSESDFPerc} \alias{HSESDFPerc} -\title{Percentile of historical simulation VaR distribution function} +\title{Percentile of historical simulation ES distribution function} \usage{ HSESDFPerc(Ra, perc, cl) } @@ -17,7 +17,7 @@ Value of percentile of VaR distribution function } \description{ -Estimates percentiles of historical simulation VaR distribution +Estimates percentiles of historical simulation ES distribution function, using theory of order statistics, for specified confidence level. } \examples{ From noreply at r-forge.r-project.org Thu Jul 9 16:17:26 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 9 Jul 2015 16:17:26 +0200 (CEST) Subject: [Returnanalytics-commits] r3797 - in pkg/Dowd: R man Message-ID: <20150709141726.338FE185CC4@r-forge.r-project.org> Author: dacharya Date: 2015-07-09 16:17:25 +0200 (Thu, 09 Jul 2015) New Revision: 3797 Added: pkg/Dowd/R/LogtESDFPerc.R pkg/Dowd/man/LogtESDFPerc.Rd Log: Function HSVaRDFPerc added. Added: pkg/Dowd/R/LogtESDFPerc.R =================================================================== --- pkg/Dowd/R/LogtESDFPerc.R (rev 0) +++ pkg/Dowd/R/LogtESDFPerc.R 2015-07-09 14:17:25 UTC (rev 3797) @@ -0,0 +1,164 @@ +#' Percentiles of ES distribution function for Student-t +#' +#' Plots the ES of a portfolio against confidence level assuming that geometric returns are +#' Student t distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param n Sample size +#' @param investment Size of investment +#' @param perc Desired percentile +#' @param df Number of degrees of freedom in the t distribution +#' @param cl ES confidence level and must be a scalar +#' @param hp ES holding period and must be a a scalar +#' @return Percentiles of ES distribution function +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 6. In case there 5 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates Percentiles of ES distribution +#' data <- runif(5, min = 0, max = .2) +#' LogtESDFPerc(returns = data, investment = 5, perc = .7, df = 6, cl = .95, hp = 60) +#' +#' # Computes v given mean and standard deviation of return data +#' LogtESDFPerc(mu = .012, sigma = .03, n= 10, investment = 5, perc = .8, df = 6, cl = .99, hp = 40) +#' +#' +#' @export +LogtESDFPerc <- function(...){ + if (nargs() < 6) { + stop("Too few arguments") + } + if (nargs() == 7) { + stop("Incorrect number of arguments") + } + if (nargs() > 8) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 8) { + mu <- args$mu + investment <- args$investment + df <- args$df + cl <- args$cl + perc <- args$sigma + n <- args$n + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 6) { + mu <- mean(args$returns) + investment <- args$investment + df <- args$df + n <- max(dim(as.matrix(args$returns))) + perc <- args$perc + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + n <- as.matrix(n) + n.row <- dim(n)[1] + n.col <- dim(n)[2] + if (max(n.row, n.col) > 1) { + stop("Number of observations in a sample must be an integer") + } + perc <- as.matrix(perc) + perc.row <- dim(perc)[1] + perc.col <- dim(perc)[2] + if (max(perc.row, perc.col) > 1) { + stop("Chosen percentile of the distribution must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (max(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (n < 0) { + stop("Number of observations must be non-negative") + } + if (cl > 1){ + stop("Chosen percentile must not exceed 1") + } + if (cl <= 0){ + stop("Confidence level must be positive") + } + if (cl >= 1){ + stop("Confidence level(s) must be less than 1") + } + if (cl <= 0){ + stop("Confidence level must be greater than 0") + } + if (hp <= 0){ + stop("Honding period must be greater than 0") + } + + # Derive order statistic and ensure it is an integer + w <- n * cl # Derive r-th order statistic + 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 + } + } + + # VaR estimation + VaR <- investment - exp( ((df-2)/df) * sigma[1,1] * sqrt(hp) %*% qt(1 - cl, df) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) # VaR + + # ES etimation + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + term <- VaR + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl # Revised cl + term <- term + investment - exp( ((df-2)/df) * sigma[1,1] * sqrt(hp) %*% qt(1 - cl, df) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) + } + y <- term/n + return(y) + +} Added: pkg/Dowd/man/LogtESDFPerc.Rd =================================================================== --- pkg/Dowd/man/LogtESDFPerc.Rd (rev 0) +++ pkg/Dowd/man/LogtESDFPerc.Rd 2015-07-09 14:17:25 UTC (rev 3797) @@ -0,0 +1,55 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogtESDFPerc.R +\name{LogtESDFPerc} +\alias{LogtESDFPerc} +\title{Percentiles of ES distribution function for Student-t} +\usage{ +LogtESDFPerc(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{n}{Sample size} + +\item{investment}{Size of investment} + +\item{perc}{Desired percentile} + +\item{df}{Number of degrees of freedom in the t distribution} + +\item{cl}{ES confidence level and must be a scalar} + +\item{hp}{ES holding period and must be a a scalar} +} +\value{ +Percentiles of ES distribution function +} +\description{ +Plots the ES of a portfolio against confidence level assuming that geometric returns are +Student t distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and +standard deviation data. Accordingly, number of input arguments is either 5 +or 6. In case there 5 input arguments, the mean and standard deviation of +data is computed from return data. See examples for details. +} +\examples{ +# Estimates Percentiles of ES distribution + data <- runif(5, min = 0, max = .2) + LogtESDFPerc(returns = data, investment = 5, perc = .7, df = 6, cl = .95, hp = 60) + + # Computes v given mean and standard deviation of return data + LogtESDFPerc(mu = .012, sigma = .03, n= 10, investment = 5, perc = .8, df = 6, cl = .99, hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Thu Jul 9 16:20:34 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 9 Jul 2015 16:20:34 +0200 (CEST) Subject: [Returnanalytics-commits] r3798 - in pkg/Dowd: R man Message-ID: <20150709142034.66474185CC4@r-forge.r-project.org> Author: dacharya Date: 2015-07-09 16:20:34 +0200 (Thu, 09 Jul 2015) New Revision: 3798 Added: pkg/Dowd/R/LogtVaRDFPerc.R pkg/Dowd/man/LogtVaRDFPerc.Rd Log: Function LogtVaRDFPerc added. Added: pkg/Dowd/R/LogtVaRDFPerc.R =================================================================== --- pkg/Dowd/R/LogtVaRDFPerc.R (rev 0) +++ pkg/Dowd/R/LogtVaRDFPerc.R 2015-07-09 14:20:34 UTC (rev 3798) @@ -0,0 +1,154 @@ +#' Percentiles of VaR distribution function for Student-t +#' +#' Plots the VaR of a portfolio against confidence level assuming that geometric returns are +#' Student t distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param n Sample size +#' @param investment Size of investment +#' @param perc Desired percentile +#' @param df Number of degrees of freedom in the t distribution +#' @param cl VaR confidence level and must be a scalar +#' @param hp VaR holding period and must be a a scalar +#' @return Percentiles of VaR distribution function +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 6. In case there 5 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates Percentiles of VaR distribution +#' data <- runif(5, min = 0, max = .2) +#' LogtVaRDFPerc(returns = data, investment = 5, perc = .7, df = 6, cl = .95, hp = 60) +#' +#' # Computes v given mean and standard deviation of return data +#' LogtVaRDFPerc(mu = .012, sigma = .03, n= 10, investment = 5, perc = .8, df = 6, cl = .99, hp = 40) +#' +#' +#' @export +LogtVaRDFPerc <- function(...){ + if (nargs() < 6) { + stop("Too few arguments") + } + if (nargs() == 7) { + stop("Incorrect number of arguments") + } + if (nargs() > 8) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 8) { + mu <- args$mu + investment <- args$investment + df <- args$df + cl <- args$cl + perc <- args$sigma + n <- args$n + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 6) { + mu <- mean(args$returns) + investment <- args$investment + df <- args$df + n <- max(dim(as.matrix(args$returns))) + perc <- args$perc + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + n <- as.matrix(n) + n.row <- dim(n)[1] + n.col <- dim(n)[2] + if (max(n.row, n.col) > 1) { + stop("Number of observations in a sample must be an integer") + } + perc <- as.matrix(perc) + perc.row <- dim(perc)[1] + perc.col <- dim(perc)[2] + if (max(perc.row, perc.col) > 1) { + stop("Chosen percentile of the distribution must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (max(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (n < 0) { + stop("Number of observations must be non-negative") + } + if (cl > 1){ + stop("Chosen percentile must not exceed 1") + } + if (cl <= 0){ + stop("Confidence level must be positive") + } + if (cl >= 1){ + stop("Confidence level(s) must be less than 1") + } + if (cl <= 0){ + stop("Confidence level must be greater than 0") + } + if (hp <= 0){ + stop("Honding period must be greater than 0") + } + + # Derive order statistic and ensure it is an integer + w <- n * cl # Derive r-th order statistic + 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 + } + } + + # VaR estimation + y <- investment - exp( ((df-2)/df) * sigma[1,1] * sqrt(hp) %*% qt(1 - cl, df) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) # VaR + + return(y) +} Added: pkg/Dowd/man/LogtVaRDFPerc.Rd =================================================================== --- pkg/Dowd/man/LogtVaRDFPerc.Rd (rev 0) +++ pkg/Dowd/man/LogtVaRDFPerc.Rd 2015-07-09 14:20:34 UTC (rev 3798) @@ -0,0 +1,55 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogtVaRDFPerc.R +\name{LogtVaRDFPerc} +\alias{LogtVaRDFPerc} +\title{Percentiles of VaR distribution function for Student-t} +\usage{ +LogtVaRDFPerc(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{n}{Sample size} + +\item{investment}{Size of investment} + +\item{perc}{Desired percentile} + +\item{df}{Number of degrees of freedom in the t distribution} + +\item{cl}{VaR confidence level and must be a scalar} + +\item{hp}{VaR holding period and must be a a scalar} +} +\value{ +Percentiles of VaR distribution function +} +\description{ +Plots the VaR of a portfolio against confidence level assuming that geometric returns are +Student t distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and +standard deviation data. Accordingly, number of input arguments is either 5 +or 6. In case there 5 input arguments, the mean and standard deviation of +data is computed from return data. See examples for details. +} +\examples{ +# Estimates Percentiles of VaR distribution + data <- runif(5, min = 0, max = .2) + LogtVaRDFPerc(returns = data, investment = 5, perc = .7, df = 6, cl = .95, hp = 60) + + # Computes v given mean and standard deviation of return data + LogtVaRDFPerc(mu = .012, sigma = .03, n= 10, investment = 5, perc = .8, df = 6, cl = .99, hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Thu Jul 9 16:21:15 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 9 Jul 2015 16:21:15 +0200 (CEST) Subject: [Returnanalytics-commits] r3799 - in pkg/Dowd: R man Message-ID: <20150709142115.BE5A5185CC4@r-forge.r-project.org> Author: dacharya Date: 2015-07-09 16:21:15 +0200 (Thu, 09 Jul 2015) New Revision: 3799 Added: pkg/Dowd/R/LogtESPlot3D.R pkg/Dowd/man/LogtESPlot3D.Rd Log: Function LogtESPlot3D added. Added: pkg/Dowd/R/LogtESPlot3D.R =================================================================== --- pkg/Dowd/R/LogtESPlot3D.R (rev 0) +++ pkg/Dowd/R/LogtESPlot3D.R 2015-07-09 14:21:15 UTC (rev 3799) @@ -0,0 +1,131 @@ +#' Plots log-t ES against confidence level and holding period +#' +#' Plots the ES of a portfolio against confidence level and holding period assuming that geometric +#' returns are Student-t distributed, for specified confidence level and +#' holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param df Number of degrees of freedom in the t distribution +#' @param cl VaR confidence level and must be a vector +#' @param hp VaR holding period and must be a vector +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 6. In case there 5 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots VaR against confidene level given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogtESPlot3D(returns = data, investment = 5, df = 6, cl = seq(.85,.99,.01), hp = 60:90) +#' +#' # Computes VaR against confidence level given mean and standard deviation of return data +#' LogtESPlot3D(mu = .012, sigma = .03, investment = 5, df = 6, cl = seq(.85,.99,.02), hp = 40:80) +#' +#' +#' @export +LogtESPlot3D <- function(...){ + if (nargs() < 5) { + stop("Too few arguments") + } + if (nargs() > 6) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 6) { + mu <- args$mu + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 5) { + mu <- mean(args$returns) + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a vector") + } + + # Check that cl is read as row vector + if (cl.row > cl.col) { + cl <- t(cl) + } + # Check that hp is read as column vector + if (hp.col > hp.row) { + hp <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + + VaR <- investment - exp( ((df-2)/df) * sigma[1,1] * sqrt(hp) %*% qt(1 - cl, df) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) # VaR + + # ES etimation + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + v <- VaR + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl # Revised cl + v <- v + investment - exp( ((df-2)/df) * sigma[1,1] * sqrt(hp) %*% qt(1 - cl, df) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) + } + v <- v/n + + # Plotting + persp(x=cl, y=hp, t(VaR), xlab = "Confidence Level", + ylab = "Holding Period", zlab = "VaR", + main = "Log-t ES against confidence level") +} Added: pkg/Dowd/man/LogtESPlot3D.Rd =================================================================== --- pkg/Dowd/man/LogtESPlot3D.Rd (rev 0) +++ pkg/Dowd/man/LogtESPlot3D.Rd 2015-07-09 14:21:15 UTC (rev 3799) @@ -0,0 +1,49 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogtESPlot3D.R +\name{LogtESPlot3D} +\alias{LogtESPlot3D} +\title{Plots log-t ES against confidence level and holding period} +\usage{ +LogtESPlot3D(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{df}{Number of degrees of freedom in the t distribution} + +\item{cl}{VaR confidence level and must be a vector} + +\item{hp}{VaR holding period and must be a vector} +} +\description{ +Plots the ES of a portfolio against confidence level and holding period assuming that geometric + returns are Student-t distributed, for specified confidence level and + holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 5 + or 6. In case there 5 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Plots VaR against confidene level given geometric return data + data <- runif(5, min = 0, max = .2) + LogtESPlot3D(returns = data, investment = 5, df = 6, cl = seq(.85,.99,.01), hp = 60:90) + + # Computes VaR against confidence level given mean and standard deviation of return data + LogtESPlot3D(mu = .012, sigma = .03, investment = 5, df = 6, cl = seq(.85,.99,.02), hp = 40:80) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Thu Jul 9 16:22:09 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 9 Jul 2015 16:22:09 +0200 (CEST) Subject: [Returnanalytics-commits] r3800 - in pkg/Dowd: R man Message-ID: <20150709142209.3A25E187824@r-forge.r-project.org> Author: dacharya Date: 2015-07-09 16:22:08 +0200 (Thu, 09 Jul 2015) New Revision: 3800 Added: pkg/Dowd/R/LogtVaRPlot3D.R pkg/Dowd/man/LogtVaRPlot3D.Rd Log: Function LogtVaRPlot3D added. Added: pkg/Dowd/R/LogtVaRPlot3D.R =================================================================== --- pkg/Dowd/R/LogtVaRPlot3D.R (rev 0) +++ pkg/Dowd/R/LogtVaRPlot3D.R 2015-07-09 14:22:08 UTC (rev 3800) @@ -0,0 +1,117 @@ +#' Plots log-t VaR against confidence level and holding period +#' +#' Plots the VaR of a portfolio against confidence level and holding period assuming that geometric +#' returns are Student-t distributed, for specified confidence level and +#' holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param df Number of degrees of freedom in the t distribution +#' @param cl VaR confidence level and must be a vector +#' @param hp VaR holding period and must be a vector +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 6. In case there 5 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots VaR against confidene level given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogtVaRPlot3D(returns = data, investment = 5, df = 6, cl = seq(.85,.99,.01), hp = 60:90) +#' +#' # Computes VaR against confidence level given mean and standard deviation of return data +#' LogtVaRPlot3D(mu = .012, sigma = .03, investment = 5, df = 6, cl = seq(.85,.99,.02), hp = 40:80) +#' +#' +#' @export +LogtVaRPlot3D <- function(...){ + if (nargs() < 5) { + stop("Too few arguments") + } + if (nargs() > 6) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 6) { + mu <- args$mu + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 5) { + mu <- mean(args$returns) + investment <- args$investment + df <- args$df + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a vector") + } + + # Check that cl is read as row vector + if (cl.row > cl.col) { + cl <- t(cl) + } + # Check that hp is read as column vector + if (hp.col > hp.row) { + hp <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- investment - exp( ((df-2)/df) * sigma[1,1] * sqrt(hp) %*% qt(1 - cl, df) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) # VaR + # Plotting + persp(x=cl, y=hp, t(VaR), xlab = "Confidence Level", + ylab = "Holding Period", zlab = "VaR", + main = "Log-t VaR against confidence level") + +} Added: pkg/Dowd/man/LogtVaRPlot3D.Rd =================================================================== --- pkg/Dowd/man/LogtVaRPlot3D.Rd (rev 0) +++ pkg/Dowd/man/LogtVaRPlot3D.Rd 2015-07-09 14:22:08 UTC (rev 3800) @@ -0,0 +1,49 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogtVaRPlot3D.R +\name{LogtVaRPlot3D} +\alias{LogtVaRPlot3D} +\title{Plots log-t VaR against confidence level and holding period} +\usage{ +LogtVaRPlot3D(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{df}{Number of degrees of freedom in the t distribution} + +\item{cl}{VaR confidence level and must be a vector} + +\item{hp}{VaR holding period and must be a vector} +} +\description{ +Plots the VaR of a portfolio against confidence level and holding period assuming that geometric + returns are Student-t distributed, for specified confidence level and + holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 5 + or 6. In case there 5 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Plots VaR against confidene level given geometric return data + data <- runif(5, min = 0, max = .2) + LogtVaRPlot3D(returns = data, investment = 5, df = 6, cl = seq(.85,.99,.01), hp = 60:90) + + # Computes VaR against confidence level given mean and standard deviation of return data + LogtVaRPlot3D(mu = .012, sigma = .03, investment = 5, df = 6, cl = seq(.85,.99,.02), hp = 40:80) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Thu Jul 9 16:28:27 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 9 Jul 2015 16:28:27 +0200 (CEST) Subject: [Returnanalytics-commits] r3801 - pkg/Dowd/R Message-ID: <20150709142827.DAAAF187826@r-forge.r-project.org> Author: dacharya Date: 2015-07-09 16:28:27 +0200 (Thu, 09 Jul 2015) New Revision: 3801 Modified: pkg/Dowd/R/LogtESPlot2DCL.R Log: Mistake in plot(...) corrected (cl replaced with cl0). Modified: pkg/Dowd/R/LogtESPlot2DCL.R =================================================================== --- pkg/Dowd/R/LogtESPlot2DCL.R 2015-07-09 14:22:08 UTC (rev 3800) +++ pkg/Dowd/R/LogtESPlot2DCL.R 2015-07-09 14:28:27 UTC (rev 3801) @@ -100,8 +100,10 @@ stop("Confidence level(s) must be greater than 0") } # VaR estimation - VaR <- investment - exp(((df - 2) / df) * sigma[1,1] * sqrt(hp[1,1]) * qt(1 - cl[1,1], df) - + mu[1,1] * t(hp[1,1]) * matrix(1, cl.col, cl.row) + log(investment)) # VaR + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- investment - exp(((df - 2) / df) * sigma[1,1] * sqrt(hp[1,1]) * qt(1 - cl, df) + + mu[1,1] * hp[1,1] * matrix(1, cl.row, cl.col) + log(investment)) # VaR # ES etimation n <- 1000 # Number of slices into which tail is divided @@ -112,24 +114,24 @@ cl <- cl0 + i * delta.cl # Revised cl v <- v + investment - exp(((df - 2) / df) * sigma[1,1] * sqrt(hp[1,1]) * qt(1 - cl, df) + mu[1,1] * hp[1,1] * - matrix(1, cl.col, cl.row) + log(investment)) + matrix(1, cl.row, cl.col) + log(investment)) } v <- v/n # Plotting - plot(cl, v, type = "l", xlab = "Holding Period", ylab = "ES") + plot(cl0, v, type = "l", xlab = "Holding Period", ylab = "ES") title("Log-t ES against holding period") - xmin <-min(cl)+.25*(max(cl)-min(cl)) + xmin <-min(cl0)+.25*(max(cl0)-min(cl0)) text(xmin,max(v)-.1*(max(v)-min(v)), 'Input parameters', cex=.75, font = 2) text(xmin,max(v)-.15*(max(v)-min(v)), - paste('Daily mean geometric return = ',mu[1,1]),cex=.75) + paste('Daily mean geometric return = ',round(mu[1,1],3)),cex=.75) text(xmin,max(v)-.2*(max(v)-min(v)), - paste('Stdev. of daily geometric returns = ',sigma[1,1]),cex=.75) + paste('Stdev. of daily geometric returns = ',round(sigma[1,1],3)),cex=.75) text(xmin,max(v)-.25*(max(v)-min(v)), paste('Degrees of freedom = ',df),cex=.75) text(xmin,max(v)-.3*(max(v)-min(v)), paste('Investment size = ',investment),cex=.75) text(xmin,max(v)-.35*(max(v)-min(v)), - paste('Confidence level = ',cl,'%'),cex=.75) + paste('Holding Period = ',hp),cex=.75) } From noreply at r-forge.r-project.org Mon Jul 13 13:35:14 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 13:35:14 +0200 (CEST) Subject: [Returnanalytics-commits] r3802 - pkg/Dowd/R Message-ID: <20150713113514.342A1186F23@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 13:35:13 +0200 (Mon, 13 Jul 2015) New Revision: 3802 Modified: pkg/Dowd/R/LogtES.R Log: Minor mistakes in documentation. Modified: pkg/Dowd/R/LogtES.R =================================================================== --- pkg/Dowd/R/LogtES.R 2015-07-09 14:28:27 UTC (rev 3801) +++ pkg/Dowd/R/LogtES.R 2015-07-13 11:35:13 UTC (rev 3802) @@ -1,7 +1,7 @@ #' ES for t distributed geometric returns #' #' Estimates the ES of a portfolio assuming that geometric returns are -#' Student t distributed, for specified confidence level and holding period. +#' Student-t distributed, for specified confidence level and holding period. #' #' @param returns Vector of daily geometric return data #' @param mu Mean of daily geometric return data @@ -105,9 +105,11 @@ stop("Confidence level(s) must be greater than 0") } if (min(hp) <= 0){ - stop("Confidence level(s) must be greater than 0") + stop("Holding Period(s) must be greater than 0") } # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] VaR <- investment - exp(((df - 2) / df) * sigma %*% sqrt(t(hp)) %*% qt(1 - cl, df) + mu * t(hp) %*% matrix(1, cl.row, cl.col) + log(investment)) # VaR # ES estimation From noreply at r-forge.r-project.org Mon Jul 13 13:36:45 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 13:36:45 +0200 (CEST) Subject: [Returnanalytics-commits] r3803 - pkg/Dowd/R Message-ID: <20150713113645.F22A718766D@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 13:36:45 +0200 (Mon, 13 Jul 2015) New Revision: 3803 Modified: pkg/Dowd/R/LogtESDFPerc.R Log: Minor mistake in documentation and restriction to input data corrected. Modified: pkg/Dowd/R/LogtESDFPerc.R =================================================================== --- pkg/Dowd/R/LogtESDFPerc.R 2015-07-13 11:35:13 UTC (rev 3802) +++ pkg/Dowd/R/LogtESDFPerc.R 2015-07-13 11:36:45 UTC (rev 3803) @@ -14,8 +14,8 @@ #' @param hp ES holding period and must be a a scalar #' @return Percentiles of ES distribution function #' @note The input arguments contain either return data or else mean and -#' standard deviation data. Accordingly, number of input arguments is either 5 -#' or 6. In case there 5 input arguments, the mean and standard deviation of +#' standard deviation data. Accordingly, number of input arguments is either 6 +#' or 8. In case there 6 input arguments, the mean and standard deviation of #' data is computed from return data. See examples for details. #' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. @@ -109,11 +109,11 @@ if (n < 0) { stop("Number of observations must be non-negative") } - if (cl > 1){ + if (perc > 1){ stop("Chosen percentile must not exceed 1") } - if (cl <= 0){ - stop("Confidence level must be positive") + if (perc <= 0){ + stop("Chosen percentile must be positive") } if (cl >= 1){ stop("Confidence level(s) must be less than 1") From noreply at r-forge.r-project.org Mon Jul 13 13:37:18 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 13:37:18 +0200 (CEST) Subject: [Returnanalytics-commits] r3804 - pkg/Dowd/R Message-ID: <20150713113718.981F118766D@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 13:37:18 +0200 (Mon, 13 Jul 2015) New Revision: 3804 Modified: pkg/Dowd/R/LogtESPlot2DCL.R Log: Minor mistakes in documentation. Modified: pkg/Dowd/R/LogtESPlot2DCL.R =================================================================== --- pkg/Dowd/R/LogtESPlot2DCL.R 2015-07-13 11:36:45 UTC (rev 3803) +++ pkg/Dowd/R/LogtESPlot2DCL.R 2015-07-13 11:37:18 UTC (rev 3804) @@ -31,6 +31,7 @@ #' #' @export LogtESPlot2DCL <- function(...){ + # Determine if there are five or six arguments, and ensure that arguments are read as intended if (nargs() < 5) { stop("Too few arguments") } @@ -97,7 +98,7 @@ stop("Confidence level(s) must be greater than 0") } if (min(hp) <= 0){ - stop("Confidence level(s) must be greater than 0") + stop("Holding period(s) must be greater than 0") } # VaR estimation cl.row <- dim(cl)[1] From noreply at r-forge.r-project.org Mon Jul 13 13:37:53 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 13:37:53 +0200 (CEST) Subject: [Returnanalytics-commits] r3805 - pkg/Dowd/R Message-ID: <20150713113753.3F28318766D@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 13:37:52 +0200 (Mon, 13 Jul 2015) New Revision: 3805 Modified: pkg/Dowd/R/LogtESPlot2DHP.R Log: Minor mistakes in documentation. Modified: pkg/Dowd/R/LogtESPlot2DHP.R =================================================================== --- pkg/Dowd/R/LogtESPlot2DHP.R 2015-07-13 11:37:18 UTC (rev 3804) +++ pkg/Dowd/R/LogtESPlot2DHP.R 2015-07-13 11:37:52 UTC (rev 3805) @@ -97,9 +97,11 @@ stop("Confidence level(s) must be greater than 0") } if (min(hp) <= 0){ - stop("Confidence level(s) must be greater than 0") + stop("Holding period(s) must be greater than 0") } # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] VaR <- investment - exp(((df - 2) / 2) * sigma[1,1] * sqrt(t(hp)) * qt(1 - cl[1,1], df) + mu[1,1] * t(hp) %*% matrix(1, cl.row, cl.col) + log(investment)) # VaR From noreply at r-forge.r-project.org Mon Jul 13 13:38:39 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 13:38:39 +0200 (CEST) Subject: [Returnanalytics-commits] r3806 - pkg/Dowd/R Message-ID: <20150713113839.333F918771E@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 13:38:38 +0200 (Mon, 13 Jul 2015) New Revision: 3806 Modified: pkg/Dowd/R/LogtESPlot3D.R Log: Minor mistakes in documentation. Modified: pkg/Dowd/R/LogtESPlot3D.R =================================================================== --- pkg/Dowd/R/LogtESPlot3D.R 2015-07-13 11:37:52 UTC (rev 3805) +++ pkg/Dowd/R/LogtESPlot3D.R 2015-07-13 11:38:38 UTC (rev 3806) @@ -22,16 +22,17 @@ #' @author Dinesh Acharya #' @examples #' -#' # Plots VaR against confidene level given geometric return data +#' # Plots ES against confidene level given geometric return data #' data <- runif(5, min = 0, max = .2) #' LogtESPlot3D(returns = data, investment = 5, df = 6, cl = seq(.85,.99,.01), hp = 60:90) #' -#' # Computes VaR against confidence level given mean and standard deviation of return data +#' # Computes ES against confidence level given mean and standard deviation of return data #' LogtESPlot3D(mu = .012, sigma = .03, investment = 5, df = 6, cl = seq(.85,.99,.02), hp = 40:80) #' #' #' @export LogtESPlot3D <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended if (nargs() < 5) { stop("Too few arguments") } From noreply at r-forge.r-project.org Mon Jul 13 13:39:19 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 13:39:19 +0200 (CEST) Subject: [Returnanalytics-commits] r3807 - pkg/Dowd/R Message-ID: <20150713113919.8E7D8183ED6@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 13:39:19 +0200 (Mon, 13 Jul 2015) New Revision: 3807 Modified: pkg/Dowd/R/LogtVaR.R Log: Minor mistakes in documentation. Modified: pkg/Dowd/R/LogtVaR.R =================================================================== --- pkg/Dowd/R/LogtVaR.R 2015-07-13 11:38:38 UTC (rev 3806) +++ pkg/Dowd/R/LogtVaR.R 2015-07-13 11:39:19 UTC (rev 3807) @@ -36,6 +36,7 @@ #' #' @export LogtVaR <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended if (nargs() < 5) { stop("Too few arguments") } @@ -105,7 +106,7 @@ stop("Confidence level(s) must be greater than 0") } if (min(hp) <= 0){ - stop("Confidence level(s) must be greater than 0") + stop("Holding Period(s) must be greater than 0") } # VaR estimation y <- investment - exp(((df - 2) / 2) * sigma %*% sqrt(t(hp)) %*% qt(1 - cl, df) From noreply at r-forge.r-project.org Mon Jul 13 13:40:40 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 13:40:40 +0200 (CEST) Subject: [Returnanalytics-commits] r3808 - pkg/Dowd/R Message-ID: <20150713114040.686A7183BF0@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 13:40:40 +0200 (Mon, 13 Jul 2015) New Revision: 3808 Modified: pkg/Dowd/R/LogtVaRPlot2DCL.R Log: Minor mistakes in documentation. Modified: pkg/Dowd/R/LogtVaRPlot2DCL.R =================================================================== --- pkg/Dowd/R/LogtVaRPlot2DCL.R 2015-07-13 11:39:19 UTC (rev 3807) +++ pkg/Dowd/R/LogtVaRPlot2DCL.R 2015-07-13 11:40:40 UTC (rev 3808) @@ -32,6 +32,7 @@ #' #' @export LogtVaRPlot2DCL <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended if (nargs() < 5) { stop("Too few arguments") } @@ -98,10 +99,12 @@ stop("Confidence level(s) must be greater than 0") } if (min(hp) <= 0){ - stop("Confidence level(s) must be greater than 0") + stop("Holding period(s) must be greater than 0") } - # VaR estimation - VaR <- investment - exp(((df-2)/df)*sigma[1,1] * sqrt(hp[1,1]) * qt(1 - cl, df)+mu[1,1]*hp[1,1]*matrix(1,cl.col,cl.row) + log(investment) + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- investment - exp(((df-2)/df)*sigma[1,1] * sqrt(hp[1,1]) * qt(1 - cl, df)+mu[1,1]*hp[1,1]*matrix(1,cl.row,cl.col) + log(investment) ) # VaR # Plotting plot(cl, VaR, type = "l", xlab = "Confidence Level", ylab = "VaR") From noreply at r-forge.r-project.org Mon Jul 13 13:40:58 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 13:40:58 +0200 (CEST) Subject: [Returnanalytics-commits] r3809 - pkg/Dowd/R Message-ID: <20150713114058.5DF82183BF0@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 13:40:58 +0200 (Mon, 13 Jul 2015) New Revision: 3809 Modified: pkg/Dowd/R/LogtVaRDFPerc.R Log: Minor mistakes in documentation. Modified: pkg/Dowd/R/LogtVaRDFPerc.R =================================================================== --- pkg/Dowd/R/LogtVaRDFPerc.R 2015-07-13 11:40:40 UTC (rev 3808) +++ pkg/Dowd/R/LogtVaRDFPerc.R 2015-07-13 11:40:58 UTC (rev 3809) @@ -14,8 +14,8 @@ #' @param hp VaR holding period and must be a a scalar #' @return Percentiles of VaR distribution function #' @note The input arguments contain either return data or else mean and -#' standard deviation data. Accordingly, number of input arguments is either 5 -#' or 6. In case there 5 input arguments, the mean and standard deviation of +#' standard deviation data. Accordingly, number of input arguments is either 6 +#' or 8. In case there 6 input arguments, the mean, standard deviation and number of observations of the #' data is computed from return data. See examples for details. #' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. @@ -33,6 +33,7 @@ #' #' @export LogtVaRDFPerc <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended if (nargs() < 6) { stop("Too few arguments") } @@ -109,20 +110,20 @@ if (n < 0) { stop("Number of observations must be non-negative") } - if (cl > 1){ + if (perc > 1){ stop("Chosen percentile must not exceed 1") } - if (cl <= 0){ - stop("Confidence level must be positive") + if (perc <= 0){ + stop("Chosen percentile must be positive") } if (cl >= 1){ stop("Confidence level(s) must be less than 1") } if (cl <= 0){ - stop("Confidence level must be greater than 0") + stop("Confidence level(s) must be greater than 0") } if (hp <= 0){ - stop("Honding period must be greater than 0") + stop("Honding period(s) must be greater than 0") } # Derive order statistic and ensure it is an integer From noreply at r-forge.r-project.org Mon Jul 13 13:41:20 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 13:41:20 +0200 (CEST) Subject: [Returnanalytics-commits] r3810 - pkg/Dowd/R Message-ID: <20150713114120.76769183BF0@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 13:41:19 +0200 (Mon, 13 Jul 2015) New Revision: 3810 Modified: pkg/Dowd/R/LogtVaRPlot2DHP.R Log: Minor mistakes in documentation corrected. Modified: pkg/Dowd/R/LogtVaRPlot2DHP.R =================================================================== --- pkg/Dowd/R/LogtVaRPlot2DHP.R 2015-07-13 11:40:58 UTC (rev 3809) +++ pkg/Dowd/R/LogtVaRPlot2DHP.R 2015-07-13 11:41:19 UTC (rev 3810) @@ -100,10 +100,13 @@ stop("Confidence level(s) must be greater than 0") } # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] VaR <- investment - exp(((df - 2) / df) * sigma[1,1] * sqrt(t(hp)) * qt(1 - cl[1,1], df) + mu[1,1] * t(hp) %*% matrix(1, cl.row, cl.col) + log(investment)) # VaR # Plotting plot(hp, VaR, type = "l", xlab = "Holding Period", ylab = "VaR") + cl.label <- 100 * cl[1,1] title("Log-t VaR against holding period") xmin <-min(hp)+.25*(max(hp)-min(hp)) text(xmin,max(VaR)-.1*(max(VaR)-min(VaR)), @@ -117,5 +120,5 @@ text(xmin,max(VaR)-.3*(max(VaR)-min(VaR)), paste('Investment size = ',investment),cex=.75) text(xmin,max(VaR)-.35*(max(VaR)-min(VaR)), - paste('Confidence level = ',cl,'%'),cex=.75) + paste('Confidence level = ',cl.label,'%'),cex=.75) } From noreply at r-forge.r-project.org Mon Jul 13 13:42:16 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 13:42:16 +0200 (CEST) Subject: [Returnanalytics-commits] r3811 - pkg/Dowd/R Message-ID: <20150713114216.166A5183BF0@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 13:42:15 +0200 (Mon, 13 Jul 2015) New Revision: 3811 Modified: pkg/Dowd/R/LogtVaRPlot3D.R Log: Minor mistakes in documentation corrected. Modified: pkg/Dowd/R/LogtVaRPlot3D.R =================================================================== --- pkg/Dowd/R/LogtVaRPlot3D.R 2015-07-13 11:41:19 UTC (rev 3810) +++ pkg/Dowd/R/LogtVaRPlot3D.R 2015-07-13 11:42:15 UTC (rev 3811) @@ -102,7 +102,7 @@ stop("Confidence level(s) must be greater than 0") } if (min(hp) <= 0){ - stop("Confidence level(s) must be greater than 0") + stop("Holding period(s) must be greater than 0") } # VaR estimation From noreply at r-forge.r-project.org Mon Jul 13 13:44:12 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 13:44:12 +0200 (CEST) Subject: [Returnanalytics-commits] r3812 - pkg/Dowd/man Message-ID: <20150713114412.46EAD186EDE@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 13:44:12 +0200 (Mon, 13 Jul 2015) New Revision: 3812 Modified: pkg/Dowd/man/LogtES.Rd pkg/Dowd/man/LogtESDFPerc.Rd pkg/Dowd/man/LogtESPlot3D.Rd pkg/Dowd/man/LogtVaRDFPerc.Rd Log: Minor changes in documentation. Modified: pkg/Dowd/man/LogtES.Rd =================================================================== --- pkg/Dowd/man/LogtES.Rd 2015-07-13 11:42:15 UTC (rev 3811) +++ pkg/Dowd/man/LogtES.Rd 2015-07-13 11:44:12 UTC (rev 3812) @@ -30,7 +30,7 @@ } \description{ Estimates the ES of a portfolio assuming that geometric returns are -Student t distributed, for specified confidence level and holding period. +Student-t distributed, for specified confidence level and holding period. } \note{ The input arguments contain either return data or else mean and Modified: pkg/Dowd/man/LogtESDFPerc.Rd =================================================================== --- pkg/Dowd/man/LogtESDFPerc.Rd 2015-07-13 11:42:15 UTC (rev 3811) +++ pkg/Dowd/man/LogtESDFPerc.Rd 2015-07-13 11:44:12 UTC (rev 3812) @@ -34,8 +34,8 @@ } \note{ The input arguments contain either return data or else mean and -standard deviation data. Accordingly, number of input arguments is either 5 -or 6. In case there 5 input arguments, the mean and standard deviation of +standard deviation data. Accordingly, number of input arguments is either 6 +or 8. In case there 6 input arguments, the mean and standard deviation of data is computed from return data. See examples for details. } \examples{ Modified: pkg/Dowd/man/LogtESPlot3D.Rd =================================================================== --- pkg/Dowd/man/LogtESPlot3D.Rd 2015-07-13 11:42:15 UTC (rev 3811) +++ pkg/Dowd/man/LogtESPlot3D.Rd 2015-07-13 11:44:12 UTC (rev 3812) @@ -33,11 +33,11 @@ data is computed from return data. See examples for details. } \examples{ -# Plots VaR against confidene level given geometric return data +# Plots ES against confidene level given geometric return data data <- runif(5, min = 0, max = .2) LogtESPlot3D(returns = data, investment = 5, df = 6, cl = seq(.85,.99,.01), hp = 60:90) - # Computes VaR against confidence level given mean and standard deviation of return data + # Computes ES against confidence level given mean and standard deviation of return data LogtESPlot3D(mu = .012, sigma = .03, investment = 5, df = 6, cl = seq(.85,.99,.02), hp = 40:80) } \author{ Modified: pkg/Dowd/man/LogtVaRDFPerc.Rd =================================================================== --- pkg/Dowd/man/LogtVaRDFPerc.Rd 2015-07-13 11:42:15 UTC (rev 3811) +++ pkg/Dowd/man/LogtVaRDFPerc.Rd 2015-07-13 11:44:12 UTC (rev 3812) @@ -34,8 +34,8 @@ } \note{ The input arguments contain either return data or else mean and -standard deviation data. Accordingly, number of input arguments is either 5 -or 6. In case there 5 input arguments, the mean and standard deviation of +standard deviation data. Accordingly, number of input arguments is either 6 +or 8. In case there 6 input arguments, the mean, standard deviation and number of observations of the data is computed from return data. See examples for details. } \examples{ From noreply at r-forge.r-project.org Mon Jul 13 14:03:06 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 14:03:06 +0200 (CEST) Subject: [Returnanalytics-commits] r3813 - pkg/Dowd Message-ID: <20150713120307.07E1D187A19@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 14:03:06 +0200 (Mon, 13 Jul 2015) New Revision: 3813 Modified: pkg/Dowd/NAMESPACE Log: LogNormalES, LogNormalESDFPerc and LogNormalESPlot2DCL added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-13 11:44:12 UTC (rev 3812) +++ pkg/Dowd/NAMESPACE 2015-07-13 12:03:06 UTC (rev 3813) @@ -58,6 +58,9 @@ export(KernelVaRNormalKernel) export(KernelVaRTriangleKernel) export(KuiperTestStat) +export(LogNormalES) +export(LogNormalESDFPerc) +export(LogNormalESPlot2DCL) export(LogtES) export(LogtESDFPerc) export(LogtESPlot2DCL) From noreply at r-forge.r-project.org Mon Jul 13 14:03:56 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 14:03:56 +0200 (CEST) Subject: [Returnanalytics-commits] r3814 - in pkg/Dowd: R man Message-ID: <20150713120356.5E101187A19@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 14:03:55 +0200 (Mon, 13 Jul 2015) New Revision: 3814 Added: pkg/Dowd/R/LogNormalES.R pkg/Dowd/man/LogNormalES.Rd Log: Function LogNormalES added. Added: pkg/Dowd/R/LogNormalES.R =================================================================== --- pkg/Dowd/R/LogNormalES.R (rev 0) +++ pkg/Dowd/R/LogNormalES.R 2015-07-13 12:03:55 UTC (rev 3814) @@ -0,0 +1,125 @@ +#' ES for normally distributed geometric returns +#' +#' Estimates the ES of a portfolio assuming that geometric returns are +#' normally distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param cl VaR confidence level +#' @param hp VaR holding period in days +#' @return Matrix of ES whose dimension depends on dimension of hp and cl. If +#' cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is +#' a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, +#' the matrix is column matrix and if both cl and hp are vectors, the matrix +#' has dimension length of cl * length of hp. +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes ES given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogNormalES(returns = data, investment = 5, cl = .95, hp = 90) +#' +#' # Computes ES given mean and standard deviation of return data +#' LogNormalES(mu = .012, sigma = .03, investment = 5, cl = .95, hp = 90) +#' +#' +#' @export +LogNormalES <- function(...){ + # Determine if there are four or fice arguments and ensure that arguments are + # read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() > 5) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 5) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + investment <- args$investment + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar or a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar or a vector") + } + + # Check that cl and hp are read as row and column vectors respectively + if (cl.row > cl.col) { + cl <- t(cl) + } + if (hp.row > hp.col) { + hp <- t(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 greater than 0") + } + if (min(hp) <= 0){ + stop("Holding periods must be greater than 0") + } + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- investment - exp(sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) # VaR + + # ES estimation + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + term <- VaR + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl # Revised cl + term <- term + investment - exp(sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) + } + y <- term/n + return (y) +} \ No newline at end of file Added: pkg/Dowd/man/LogNormalES.Rd =================================================================== --- pkg/Dowd/man/LogNormalES.Rd (rev 0) +++ pkg/Dowd/man/LogNormalES.Rd 2015-07-13 12:03:55 UTC (rev 3814) @@ -0,0 +1,53 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogNormalES.R +\name{LogNormalES} +\alias{LogNormalES} +\title{ES for normally distributed geometric returns} +\usage{ +LogNormalES(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{cl}{VaR confidence level} + +\item{hp}{VaR holding period in days} +} +\value{ +Matrix of ES whose dimension depends on dimension of hp and cl. If +cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is + a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, + the matrix is column matrix and if both cl and hp are vectors, the matrix + has dimension length of cl * length of hp. +} +\description{ +Estimates the ES of a portfolio assuming that geometric returns are +normally distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 4 + or 5. In case there 4 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Computes ES given geometric return data + data <- runif(5, min = 0, max = .2) + LogNormalES(returns = data, investment = 5, cl = .95, hp = 90) + + # Computes ES given mean and standard deviation of return data + LogNormalES(mu = .012, sigma = .03, investment = 5, cl = .95, hp = 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Mon Jul 13 14:04:29 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 14:04:29 +0200 (CEST) Subject: [Returnanalytics-commits] r3815 - in pkg/Dowd: R man Message-ID: <20150713120429.4E98F187A19@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 14:04:29 +0200 (Mon, 13 Jul 2015) New Revision: 3815 Added: pkg/Dowd/R/LogNormalESDFPerc.R pkg/Dowd/man/LogNormalESDFPerc.Rd Log: Function LogNormalESDFPerc added. Added: pkg/Dowd/R/LogNormalESDFPerc.R =================================================================== --- pkg/Dowd/R/LogNormalESDFPerc.R (rev 0) +++ pkg/Dowd/R/LogNormalESDFPerc.R 2015-07-13 12:04:29 UTC (rev 3815) @@ -0,0 +1,165 @@ +#' Percentiles of ES distribution function for normally distributed geometric returns +#' +#' Estimates the percentiles of ES distribution for normally distributed geometric returns, for specified confidence level and holding period using the theory of order statistics. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param n Sample size +#' @param investment Size of investment +#' @param perc Desired percentile +#' @param cl ES confidence level and must be a scalar +#' @param hp ES holding period and must be a a scalar +#' @return Percentiles of ES distribution function +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 7. In case there 5 input arguments, the mean, standard deviation and number of +#' samples is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates Percentiles of ES distribution +#' data <- runif(5, min = 0, max = .2) +#' LogNormalESDFPerc(returns = data, investment = 5, perc = .7, cl = .95, hp = 60) +#' +#' # Estimates Percentiles given mean, standard deviation and number of sambles of return data +#' LogNormalESDFPerc(mu = .012, sigma = .03, n= 10, investment = 5, perc = .8, cl = .99, hp = 40) +#' +#' +#' @export +LogNormalESDFPerc <- function(...){ + # Determine if there are five or seven arguments, and ensure that arguments are read as intended + if (nargs() < 5) { + stop("Too few arguments") + } + if (nargs() == 6) { + stop("Incorrect number of arguments") + } + if (nargs() > 7) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 7) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + perc <- args$sigma + n <- args$n + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 5) { + mu <- mean(args$returns) + investment <- args$investment + n <- max(dim(as.matrix(args$returns))) + perc <- args$perc + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + n <- as.matrix(n) + n.row <- dim(n)[1] + n.col <- dim(n)[2] + if (max(n.row, n.col) > 1) { + stop("Number of observations in a sample must be a scalar") + } + if (n %% 1 != 0) { + stop("Number of observations in a sample must be an integer.") + } + perc <- as.matrix(perc) + perc.row <- dim(perc)[1] + perc.col <- dim(perc)[2] + if (max(perc.row, perc.col) > 1) { + stop("Chosen percentile of the distribution must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (max(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (n < 0) { + stop("Number of observations must be non-negative") + } + if (perc > 1){ + stop("Chosen percentile must not exceed 1") + } + if (perc <= 0){ + stop("Chosen percentile must be positive") + } + 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("Honding period must be greater than 0") + } + + # Derive order statistic and ensure it is an integer + w <- n * cl # Derive r-th order statistic + 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 + } + } + + # VaR estimation + VaR <- investment - exp( sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) # VaR + + # ES estimation + cl <- x + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + term <- VaR + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl # Revised cl + term <- term + investment - exp(sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) + } + y <- term/n + return(y) + +} \ No newline at end of file Added: pkg/Dowd/man/LogNormalESDFPerc.Rd =================================================================== --- pkg/Dowd/man/LogNormalESDFPerc.Rd (rev 0) +++ pkg/Dowd/man/LogNormalESDFPerc.Rd 2015-07-13 12:04:29 UTC (rev 3815) @@ -0,0 +1,52 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogNormalESDFPerc.R +\name{LogNormalESDFPerc} +\alias{LogNormalESDFPerc} +\title{Percentiles of ES distribution function for normally distributed geometric returns} +\usage{ +LogNormalESDFPerc(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{n}{Sample size} + +\item{investment}{Size of investment} + +\item{perc}{Desired percentile} + +\item{cl}{ES confidence level and must be a scalar} + +\item{hp}{ES holding period and must be a a scalar} +} +\value{ +Percentiles of ES distribution function +} +\description{ +Estimates the percentiles of ES distribution for normally distributed geometric returns, for specified confidence level and holding period using the theory of order statistics. +} +\note{ +The input arguments contain either return data or else mean and +standard deviation data. Accordingly, number of input arguments is either 5 +or 7. In case there 5 input arguments, the mean, standard deviation and number of +samples is computed from return data. See examples for details. +} +\examples{ +# Estimates Percentiles of ES distribution + data <- runif(5, min = 0, max = .2) + LogNormalESDFPerc(returns = data, investment = 5, perc = .7, cl = .95, hp = 60) + + # Estimates Percentiles given mean, standard deviation and number of sambles of return data + LogNormalESDFPerc(mu = .012, sigma = .03, n= 10, investment = 5, perc = .8, cl = .99, hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Mon Jul 13 14:04:58 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 13 Jul 2015 14:04:58 +0200 (CEST) Subject: [Returnanalytics-commits] r3816 - in pkg/Dowd: R man Message-ID: <20150713120458.80B2C187A19@r-forge.r-project.org> Author: dacharya Date: 2015-07-13 14:04:58 +0200 (Mon, 13 Jul 2015) New Revision: 3816 Added: pkg/Dowd/R/LogNormalESPlot2DCL.R pkg/Dowd/man/LogNormalESPlot2DCL.Rd Log: Function LogNormalESPlot2DCL added. Added: pkg/Dowd/R/LogNormalESPlot2DCL.R =================================================================== --- pkg/Dowd/R/LogNormalESPlot2DCL.R (rev 0) +++ pkg/Dowd/R/LogNormalESPlot2DCL.R 2015-07-13 12:04:58 UTC (rev 3816) @@ -0,0 +1,133 @@ +#' Plots log normal ES against confidence level +#' +#' Plots the ES of a portfolio against confidence level assuming that geometric returns are +#' normally distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param cl ES confidence level and must be a vector +#' @param hp ES holding period and must be a scalar +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots ES against confidence level +#' data <- runif(5, min = 0, max = .2) +#' LogNormalESPlot2DCL(returns = data, investment = 5, cl = seq(.9,.99,.01), hp = 60) +#' +#' # Plots ES against confidence level +#' LogNormalESPlot2DCL(mu = .012, sigma = .03, investment = 5, cl = seq(.9,.99,.01), hp = 40) +#' +#' +#' @export +LogNormalESPlot2DCL <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() > 5) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 5) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + investment <- args$investment + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that hp is read as row vector + if (cl.row > cl.col) { + cl <- t(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 greater than 0") + } + if (min(hp) <= 0){ + stop("Holding period must be greater than 0") + } + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- investment - exp(sigma[1,1] * sqrt(hp[1,1]) * qnorm(1 - cl, 0, 1) + + mu[1,1] * hp[1,1] * matrix(1, cl.row, cl.col) + log(investment)) # VaR + + # ES etimation + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + v <- VaR + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl # Revised cl + v <- v + investment - exp(sigma[1,1] * sqrt(hp[1,1]) * + qnorm(1 - cl, 0, 1) + mu[1,1] * hp[1,1] * + matrix(1, cl.row, cl.col) + log(investment)) + } + v <- v/n + + # Plotting + plot(cl0, v, type = "l", xlab = "Holding Period", ylab = "ES") + title("Log Normal ES against holding period") + xmin <-min(cl0)+.25*(max(cl0)-min(cl0)) + text(xmin,max(v)-.1*(max(v)-min(v)), + 'Input parameters', cex=.75, font = 2) + text(xmin,max(v)-.15*(max(v)-min(v)), + paste('Daily mean geometric return = ',round(mu[1,1],3)),cex=.75) + text(xmin,max(v)-.2*(max(v)-min(v)), + paste('Stdev. of daily geometric returns = ',round(sigma[1,1],3)),cex=.75) + text(xmin,max(v)-.25*(max(v)-min(v)), + paste('Investment size = ',investment),cex=.75) + text(xmin,max(v)-.3*(max(v)-min(v)), + paste('Holding Period = ',hp),cex=.75) +} Added: pkg/Dowd/man/LogNormalESPlot2DCL.Rd =================================================================== --- pkg/Dowd/man/LogNormalESPlot2DCL.Rd (rev 0) +++ pkg/Dowd/man/LogNormalESPlot2DCL.Rd 2015-07-13 12:04:58 UTC (rev 3816) @@ -0,0 +1,46 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogNormalESPlot2DCL.R +\name{LogNormalESPlot2DCL} +\alias{LogNormalESPlot2DCL} +\title{Plots log normal ES against confidence level} +\usage{ +LogNormalESPlot2DCL(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{cl}{ES confidence level and must be a vector} + +\item{hp}{ES holding period and must be a scalar} +} +\description{ +Plots the ES of a portfolio against confidence level assuming that geometric returns are +normally distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 4 + or 5. In case there 4 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Plots ES against confidence level + data <- runif(5, min = 0, max = .2) + LogNormalESPlot2DCL(returns = data, investment = 5, cl = seq(.9,.99,.01), hp = 60) + + # Plots ES against confidence level + LogNormalESPlot2DCL(mu = .012, sigma = .03, investment = 5, cl = seq(.9,.99,.01), hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Wed Jul 15 01:11:30 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 15 Jul 2015 01:11:30 +0200 (CEST) Subject: [Returnanalytics-commits] r3817 - pkg/Dowd Message-ID: <20150714231130.5CDBA186F6B@r-forge.r-project.org> Author: dacharya Date: 2015-07-15 01:11:30 +0200 (Wed, 15 Jul 2015) New Revision: 3817 Modified: pkg/Dowd/NAMESPACE Log: Functions LogNormalESPlot3d, LornormalESPlot2DHP, LogNormalVaR and LogNormalVaRDFPerc added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-13 12:04:58 UTC (rev 3816) +++ pkg/Dowd/NAMESPACE 2015-07-14 23:11:30 UTC (rev 3817) @@ -61,6 +61,10 @@ export(LogNormalES) export(LogNormalESDFPerc) export(LogNormalESPlot2DCL) +export(LogNormalESPlot2DHP) +export(LogNormalESPlot3D) +export(LogNormalVaR) +export(LogNormalVaRDFPerc) export(LogtES) export(LogtESDFPerc) export(LogtESPlot2DCL) From noreply at r-forge.r-project.org Wed Jul 15 01:16:47 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 15 Jul 2015 01:16:47 +0200 (CEST) Subject: [Returnanalytics-commits] r3818 - in pkg/Dowd: R man Message-ID: <20150714231648.0D6E0186F6B@r-forge.r-project.org> Author: dacharya Date: 2015-07-15 01:16:47 +0200 (Wed, 15 Jul 2015) New Revision: 3818 Added: pkg/Dowd/R/LogNormalVaRDFPerc.R pkg/Dowd/man/LogNormalVaRDFPerc.Rd Log: Function LogNormalVaRDFPerc added. Added: pkg/Dowd/R/LogNormalVaRDFPerc.R =================================================================== --- pkg/Dowd/R/LogNormalVaRDFPerc.R (rev 0) +++ pkg/Dowd/R/LogNormalVaRDFPerc.R 2015-07-14 23:16:47 UTC (rev 3818) @@ -0,0 +1,157 @@ +#' Percentiles of VaR distribution function for normally distributed geometric returns +#' +#' Estimates the percentile of VaR distribution function for normally distributed geometric returns, using the theory of order statistics. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param n Sample size +#' @param investment Size of investment +#' @param perc Desired percentile +#' @param cl VaR confidence level and must be a scalar +#' @param hp VaR holding period and must be a a scalar +#' @return Percentiles of VaR distribution function and is scalar +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 7. In case there 5 input arguments, the mean, standard deviation and number of observations of +#' data are computed from returns data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates Percentiles of VaR distribution +#' data <- runif(5, min = 0, max = .2) +#' LogNormalVaRDFPerc(returns = data, investment = 5, perc = .7, cl = .95, hp = 60) +#' +#' # Computes v given mean and standard deviation of return data +#' LogNormalVaRDFPerc(mu = .012, sigma = .03, n= 10, investment = 5, perc = .8, cl = .99, hp = 40) +#' +#' +#' @export +LogNormalVaRDFPerc <- function(...){ + # Determine if there are five or seven arguments, and ensure that arguments are read as intended + if (nargs() < 5) { + stop("Too few arguments") + } + if (nargs() == 6) { + stop("Incorrect number of arguments") + } + if (nargs() > 7) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 7) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + perc <- args$sigma + n <- args$n + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 5) { + mu <- mean(args$returns) + investment <- args$investment + n <- max(dim(as.matrix(args$returns))) + perc <- args$perc + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + n <- as.matrix(n) + n.row <- dim(n)[1] + n.col <- dim(n)[2] + if (max(n.row, n.col) > 1) { + stop("Number of observations in a sample must be an integer") + } + if (n %% 1 != 0) { + stop("Number of observations in a sample must be an integer.") + } + perc <- as.matrix(perc) + perc.row <- dim(perc)[1] + perc.col <- dim(perc)[2] + if (max(perc.row, perc.col) > 1) { + stop("Chosen percentile of the distribution must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (max(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (n < 0) { + stop("Number of observations must be non-negative") + } + if (perc > 1){ + stop("Chosen percentile must not exceed 1") + } + if (perc <= 0){ + stop("Chosen percentile must be positive") + } + if (cl >= 1){ + stop("Confidence level(s) must be less than 1") + } + if (cl <= 0){ + stop("Confidence level must be greater than 0") + } + if (hp <= 0){ + stop("Honding period must be greater than 0") + } + + # Derive order statistic and ensure it is an integer + w <- n * cl # Derive r-th order statistic + r <- round(w) # Round r to nearest integer + + # Bisection routine (this routine is not use below, but is left as it is as it was present in original code by Dowd) + 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 + } + } + + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + + y <- investment - exp(sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) # VaR + + return(y) +} Added: pkg/Dowd/man/LogNormalVaRDFPerc.Rd =================================================================== --- pkg/Dowd/man/LogNormalVaRDFPerc.Rd (rev 0) +++ pkg/Dowd/man/LogNormalVaRDFPerc.Rd 2015-07-14 23:16:47 UTC (rev 3818) @@ -0,0 +1,52 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogNormalVaRDFPerc.R +\name{LogNormalVaRDFPerc} +\alias{LogNormalVaRDFPerc} +\title{Percentiles of VaR distribution function for normally distributed geometric returns} +\usage{ +LogNormalVaRDFPerc(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{n}{Sample size} + +\item{investment}{Size of investment} + +\item{perc}{Desired percentile} + +\item{cl}{VaR confidence level and must be a scalar} + +\item{hp}{VaR holding period and must be a a scalar} +} +\value{ +Percentiles of VaR distribution function and is scalar +} +\description{ +Estimates the percentile of VaR distribution function for normally distributed geometric returns, using the theory of order statistics. +} +\note{ +The input arguments contain either return data or else mean and +standard deviation data. Accordingly, number of input arguments is either 5 +or 7. In case there 5 input arguments, the mean, standard deviation and number of observations of +data are computed from returns data. See examples for details. +} +\examples{ +# Estimates Percentiles of VaR distribution + data <- runif(5, min = 0, max = .2) + LogNormalVaRDFPerc(returns = data, investment = 5, perc = .7, cl = .95, hp = 60) + + # Computes v given mean and standard deviation of return data + LogNormalVaRDFPerc(mu = .012, sigma = .03, n= 10, investment = 5, perc = .8, cl = .99, hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Wed Jul 15 01:17:19 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 15 Jul 2015 01:17:19 +0200 (CEST) Subject: [Returnanalytics-commits] r3819 - in pkg/Dowd: R man Message-ID: <20150714231719.DCE85187A34@r-forge.r-project.org> Author: dacharya Date: 2015-07-15 01:17:19 +0200 (Wed, 15 Jul 2015) New Revision: 3819 Added: pkg/Dowd/R/LogNormalVaR.R pkg/Dowd/man/LogNormalVaR.Rd Log: Function LogNormalVaR added. Added: pkg/Dowd/R/LogNormalVaR.R =================================================================== --- pkg/Dowd/R/LogNormalVaR.R (rev 0) +++ pkg/Dowd/R/LogNormalVaR.R 2015-07-14 23:17:19 UTC (rev 3819) @@ -0,0 +1,115 @@ +#' VaR for normally distributed geometric returns +#' +#' Estimates the VaR of a portfolio assuming that geometric returns are +#' normally distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param cl VaR confidence level +#' @param hp VaR holding period in days +#' @return Matrix of VaR whose dimension depends on dimension of hp and cl. If +#' cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is +#' a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, +#' the matrix is column matrix and if both cl and hp are vectors, the matrix +#' has dimension length of cl * length of hp. +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes VaR given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogNormalVaR(returns = data, investment = 5, cl = .95, hp = 90) +#' +#' # Computes VaR given mean and standard deviation of return data +#' LogNormalVaR(mu = .012, sigma = .03, investment = 5, cl = .95, hp = 90) +#' +#' +#' @export +LogNormalVaR <- function(...){ + # Determine if there are four or five arguments and ensure that arguments are + # read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() > 5) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 5) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + investment <- args$investment + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar or a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar or a vector") + } + + # Check that cl and hp are read as row and column vectors respectively + if (cl.row > cl.col) { + cl <- t(cl) + } + if (hp.row > hp.col) { + hp <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Holding Period(s) must be greater than 0") + } + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- investment - exp(sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) # VaR + + return (VaR) +} \ No newline at end of file Added: pkg/Dowd/man/LogNormalVaR.Rd =================================================================== --- pkg/Dowd/man/LogNormalVaR.Rd (rev 0) +++ pkg/Dowd/man/LogNormalVaR.Rd 2015-07-14 23:17:19 UTC (rev 3819) @@ -0,0 +1,53 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogNormalVaR.R +\name{LogNormalVaR} +\alias{LogNormalVaR} +\title{VaR for normally distributed geometric returns} +\usage{ +LogNormalVaR(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{cl}{VaR confidence level} + +\item{hp}{VaR holding period in days} +} +\value{ +Matrix of VaR whose dimension depends on dimension of hp and cl. If +cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is + a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, + the matrix is column matrix and if both cl and hp are vectors, the matrix + has dimension length of cl * length of hp. +} +\description{ +Estimates the VaR of a portfolio assuming that geometric returns are +normally distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 4 + or 5. In case there 4 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Computes VaR given geometric return data + data <- runif(5, min = 0, max = .2) + LogNormalVaR(returns = data, investment = 5, cl = .95, hp = 90) + + # Computes VaR given mean and standard deviation of return data + LogNormalVaR(mu = .012, sigma = .03, investment = 5, cl = .95, hp = 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Wed Jul 15 01:18:11 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 15 Jul 2015 01:18:11 +0200 (CEST) Subject: [Returnanalytics-commits] r3820 - in pkg/Dowd: R man Message-ID: <20150714231811.B19F2187AE0@r-forge.r-project.org> Author: dacharya Date: 2015-07-15 01:18:11 +0200 (Wed, 15 Jul 2015) New Revision: 3820 Added: pkg/Dowd/R/LogNormalESPlot3D.R pkg/Dowd/man/LogNormalESPlot3D.Rd Log: Function LogNormalESPlot3D added. Added: pkg/Dowd/R/LogNormalESPlot3D.R =================================================================== --- pkg/Dowd/R/LogNormalESPlot3D.R (rev 0) +++ pkg/Dowd/R/LogNormalESPlot3D.R 2015-07-14 23:18:11 UTC (rev 3820) @@ -0,0 +1,126 @@ +#' Plots log normal ES against confidence level and holding period +#' +#' Plots the ES of a portfolio against confidence level and holding period assuming that geometric +#' returns are normally distributed, for specified confidence level and +#' holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param cl VaR confidence level and must be a vector +#' @param hp VaR holding period and must be a vector +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots VaR against confidene level given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogNormalESPlot3D(returns = data, investment = 5, cl = seq(.85,.99,.01), hp = 60:90) +#' +#' # Computes VaR against confidence level given mean and standard deviation of return data +#' LogNormalESPlot3D(mu = .012, sigma = .03, investment = 5, cl = seq(.85,.99,.02), hp = 40:80) +#' +#' +#' @export +LogNormalESPlot3D <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() > 5) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 5) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + investment <- args$investment + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a vector") + } + + # Check that cl is read as row vector + if (cl.row > cl.col) { + cl <- t(cl) + } + # Check that hp is read as column vector + if (hp.col > hp.row) { + hp <- t(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 greater than 0") + } + if (min(hp) <= 0){ + stop("Holding periods must be greater than 0") + } + + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + + VaR <- investment - exp(sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) # VaR + + # ES estimation + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + v <- VaR + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl # Revised cl + v <- v + investment - exp(sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) + } + v <- v/n + + # Plotting + persp(x=cl, y=hp, t(VaR), xlab = "Confidence Level", + ylab = "Holding Period", zlab = "VaR", + main = "Log-t ES against confidence level") +} Added: pkg/Dowd/man/LogNormalESPlot3D.Rd =================================================================== --- pkg/Dowd/man/LogNormalESPlot3D.Rd (rev 0) +++ pkg/Dowd/man/LogNormalESPlot3D.Rd 2015-07-14 23:18:11 UTC (rev 3820) @@ -0,0 +1,45 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogNormalESPlot3D.R +\name{LogNormalESPlot3D} +\alias{LogNormalESPlot3D} +\title{Plots log normal ES against confidence level and holding period} +\usage{ +LogNormalESPlot3D(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{cl}{VaR confidence level and must be a vector} + +\item{hp}{VaR holding period and must be a vector} +} +\description{ +Plots the ES of a portfolio against confidence level and holding period assuming that geometric + returns are normally distributed, for specified confidence level and + holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 4 + or 5. In case there 4 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Plots VaR against confidene level given geometric return data + data <- runif(5, min = 0, max = .2) + LogNormalESPlot3D(returns = data, investment = 5, cl = seq(.85,.99,.01), hp = 60:90) + + # Computes VaR against confidence level given mean and standard deviation of return data + LogNormalESPlot3D(mu = .012, sigma = .03, investment = 5, cl = seq(.85,.99,.02), hp = 40:80) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Wed Jul 15 01:18:48 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 15 Jul 2015 01:18:48 +0200 (CEST) Subject: [Returnanalytics-commits] r3821 - in pkg/Dowd: R man Message-ID: <20150714231848.38326187AE4@r-forge.r-project.org> Author: dacharya Date: 2015-07-15 01:18:47 +0200 (Wed, 15 Jul 2015) New Revision: 3821 Added: pkg/Dowd/R/LogNormalESPlot2DHP.R pkg/Dowd/man/LogNormalESPlot2DHP.Rd Log: Function LogNormalESPlot2DHP added. Added: pkg/Dowd/R/LogNormalESPlot2DHP.R =================================================================== --- pkg/Dowd/R/LogNormalESPlot2DHP.R (rev 0) +++ pkg/Dowd/R/LogNormalESPlot2DHP.R 2015-07-14 23:18:47 UTC (rev 3821) @@ -0,0 +1,135 @@ +#' Plots log normal ES against holding period +#' +#' Plots the ES of a portfolio against holding period assuming that geometric returns are +#' normal distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param cl ES confidence level and must be a scalar +#' @param hp ES holding period and must be a vector +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes ES given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogNormalESPlot2DHP(returns = data, investment = 5, cl = .95, hp = 60:90) +#' +#' # Computes v given mean and standard deviation of return data +#' LogNormalESPlot2DHP(mu = .012, sigma = .03, investment = 5, cl = .99, hp = 40:80) +#' +#' +#' @export +LogNormalESPlot2DHP <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() > 5) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 5) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + investment <- args$investment + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (max(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a vector") + } + + # Check that hp is read as row vector + if (hp.row > hp.col) { + hp <- t(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 greater than 0") + } + if (min(hp) <= 0){ + stop("Holding Period must be greater than 0") + } + # VaR estimation + + cl.row <- dim(cl)[1] + cl.cl <- dim(cl)[2] + VaR <- investment - exp(sigma[1,1] * sqrt(t(hp)) * qnorm(1 - cl[1,1], 0, 1) + + mu[1,1] * t(hp) %*% matrix(1, cl.row, cl.col) + log(investment)) # VaR + + # ES etimation + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + w <- VaR + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl # Revised cl + w <- w + investment - exp(sigma[1,1] * sqrt(t(hp)) * + qnorm(1 - cl[1,1], 0, 1) + mu[1,1] * t(hp) %*% + matrix(1, cl.row, cl.col) + log(investment)) + } + es <- w/n + + # Plotting + plot(hp, es, type = "l", xlab = "Holding Period", ylab = "ES") + title("Log normal ES against holding period") + cl.label <- 100*cl0 + xmin <-min(hp)+.25*(max(hp)-min(hp)) + text(xmin,max(es)-.1*(max(es)-min(es)), + 'Input parameters', cex=.75, font = 2) + text(xmin,max(es)-.15*(max(es)-min(es)), + paste('Daily mean geometric return = ',mu[1,1]),cex=.75) + text(xmin,max(es)-.2*(max(es)-min(es)), + paste('Stdev. of daily geometric returns = ',sigma[1,1]),cex=.75) + text(xmin,max(es)-.25*(max(es)-min(es)), + paste('Investment size = ',investment),cex=.75) + text(xmin,max(es)-.3*(max(es)-min(es)), + paste('Confidence level = ',cl.label,'%'),cex=.75) +} Added: pkg/Dowd/man/LogNormalESPlot2DHP.Rd =================================================================== --- pkg/Dowd/man/LogNormalESPlot2DHP.Rd (rev 0) +++ pkg/Dowd/man/LogNormalESPlot2DHP.Rd 2015-07-14 23:18:47 UTC (rev 3821) @@ -0,0 +1,46 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogNormalESPlot2DHP.R +\name{LogNormalESPlot2DHP} +\alias{LogNormalESPlot2DHP} +\title{Plots log normal ES against holding period} +\usage{ +LogNormalESPlot2DHP(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{cl}{ES confidence level and must be a scalar} + +\item{hp}{ES holding period and must be a vector} +} +\description{ +Plots the ES of a portfolio against holding period assuming that geometric returns are +normal distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 4 + or 5. In case there 4 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Computes ES given geometric return data + data <- runif(5, min = 0, max = .2) + LogNormalESPlot2DHP(returns = data, investment = 5, cl = .95, hp = 60:90) + + # Computes v given mean and standard deviation of return data + LogNormalESPlot2DHP(mu = .012, sigma = .03, investment = 5, cl = .99, hp = 40:80) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Thu Jul 16 09:13:44 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 16 Jul 2015 09:13:44 +0200 (CEST) Subject: [Returnanalytics-commits] r3822 - pkg/Dowd Message-ID: <20150716071344.E1A90183ED2@r-forge.r-project.org> Author: dacharya Date: 2015-07-16 09:13:44 +0200 (Thu, 16 Jul 2015) New Revision: 3822 Modified: pkg/Dowd/NAMESPACE Log: Functions LogNormalVaRFigure, LogNormalVaRPlot2DCL, LogNormalVaRPlot3D and LogNormalVaRPlot2DHP added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-14 23:18:47 UTC (rev 3821) +++ pkg/Dowd/NAMESPACE 2015-07-16 07:13:44 UTC (rev 3822) @@ -65,6 +65,10 @@ export(LogNormalESPlot3D) export(LogNormalVaR) export(LogNormalVaRDFPerc) +export(LogNormalVaRFigure) +export(LogNormalVaRPlot2DCL) +export(LogNormalVaRPlot2DHP) +export(LogNormalVaRPlot3D) export(LogtES) export(LogtESDFPerc) export(LogtESPlot2DCL) From noreply at r-forge.r-project.org Thu Jul 16 10:14:02 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 16 Jul 2015 10:14:02 +0200 (CEST) Subject: [Returnanalytics-commits] r3823 - in pkg/Dowd: R man Message-ID: <20150716081402.315F0187A3E@r-forge.r-project.org> Author: dacharya Date: 2015-07-16 10:14:01 +0200 (Thu, 16 Jul 2015) New Revision: 3823 Added: pkg/Dowd/R/LogNormalVaRFigure.R pkg/Dowd/man/LogNormalVaRFigure.Rd Log: Function LogNormalVaRPlot3D added. Added: pkg/Dowd/R/LogNormalVaRFigure.R =================================================================== --- pkg/Dowd/R/LogNormalVaRFigure.R (rev 0) +++ pkg/Dowd/R/LogNormalVaRFigure.R 2015-07-16 08:14:01 UTC (rev 3823) @@ -0,0 +1,133 @@ +#' Figure of lognormal VaR and pdf against L/P +#' +#' Gives figure showing the VaR and probability distribution function against L/P of a portfolio assuming geometric returns are normally distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param cl VaR confidence level and should be scalar +#' @param hp VaR holding period in days and should be scalar +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots lognormal VaR and pdf against L/P data for given returns data +#' data <- runif(5, min = 0, max = .2) +#' LogNormalVaRFigure(returns = data, investment = 5, cl = .95, hp = 90) +#' +#' # Plots lognormal VaR and pdf against L/P data with given parameters +#' LogNormalVaRFigure(mu = .012, sigma = .03, investment = 5, cl = .95, hp = 90) +#' +#' +#' @export +LogNormalVaRFigure <- function(...){ + # Determine if there are four or five arguments and ensure that arguments are + # read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() > 5) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 5) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + investment <- args$investment + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar or a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar or a vector") + } + + # Check that cl and hp are read as row and column vectors respectively + if (cl.row > cl.col) { + cl <- t(cl) + } + if (hp.row > hp.col) { + hp <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Holding Period(s) must be greater than 0") + } + + # Message to indicate how matrix of results is to be interpreted, if cl and hp both vary and results are given in matrix form + if (max(cl.row, cl.col) > 1 & max(hp.row, hp.col) > 1) { + print('VaR results with confidence level varying across row and holding period down column') + } + + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- investment - exp(sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) # VaR + + # Plotting + x.min <- mu - 5 * sigma + x.max <- investment + delta <- (x.max-x.min) / 100 + x <- seq(x.min, x.max, delta) + p <- dlnorm(investment - x, mu, sigma) + plot(x, p, type = "l", xlim = c(x.min, x.max), ylim = c(0, max(p)*1.1), xlab = "Loss (+) / Profit (-)", ylab = "Probability", main = "Lognormal VaR") + u <- c(VaR, VaR) + v <- c(0, .6*max(p)) + lines(0,0,2,.6,type="l") + lines(u, v, type = "l", col = "blue") + cl.for.label <- 100*cl + text(1,.95*max(p), pos = 1, 'Input parameters', cex=.75, font = 2) + text(1, .875*max(p),pos = 1, paste('Daily mean geometric return = ', round(mu,2)), cex=.75) + text(1, .8*max(p),pos = 1, paste('St. dev. of daily geometric returns = ',round(sigma,2)), cex=.75) + text(1, .725*max(p),pos = 1, paste('Investment size = ', investment), cex=.75) + text(1, .65*max(p),pos = 1, paste('Holding period = ', hp,' day(s)'), cex=.75) + text(VaR, .7*max(p),pos = 2, paste('VaR at ', cl.for.label,'% CL'), cex=.75) + text(VaR, .64 * max(p),pos = 2, paste('= ',VaR), cex=.75) +} Added: pkg/Dowd/man/LogNormalVaRFigure.Rd =================================================================== --- pkg/Dowd/man/LogNormalVaRFigure.Rd (rev 0) +++ pkg/Dowd/man/LogNormalVaRFigure.Rd 2015-07-16 08:14:01 UTC (rev 3823) @@ -0,0 +1,45 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogNormalVaRFigure.R +\name{LogNormalVaRFigure} +\alias{LogNormalVaRFigure} +\title{Figure of lognormal VaR and pdf against L/P} +\usage{ +LogNormalVaRFigure(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{cl}{VaR confidence level and should be scalar} + +\item{hp}{VaR holding period in days and should be scalar} +} +\description{ +Gives figure showing the VaR and probability distribution function against L/P of a portfolio assuming geometric returns are normally distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 4 + or 5. In case there 4 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Plots lognormal VaR and pdf against L/P data for given returns data + data <- runif(5, min = 0, max = .2) + LogNormalVaRFigure(returns = data, investment = 5, cl = .95, hp = 90) + + # Plots lognormal VaR and pdf against L/P data with given parameters + LogNormalVaRFigure(mu = .012, sigma = .03, investment = 5, cl = .95, hp = 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Thu Jul 16 10:14:52 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 16 Jul 2015 10:14:52 +0200 (CEST) Subject: [Returnanalytics-commits] r3824 - in pkg/Dowd: R man Message-ID: <20150716081452.C77E2187A3E@r-forge.r-project.org> Author: dacharya Date: 2015-07-16 10:14:52 +0200 (Thu, 16 Jul 2015) New Revision: 3824 Added: pkg/Dowd/R/LogNormalVaRPlot2DCL.R pkg/Dowd/man/LogNormalVaRPlot2DCL.Rd Log: Function LogNormalVaRPlot2DCL added. Added: pkg/Dowd/R/LogNormalVaRPlot2DCL.R =================================================================== --- pkg/Dowd/R/LogNormalVaRPlot2DCL.R (rev 0) +++ pkg/Dowd/R/LogNormalVaRPlot2DCL.R 2015-07-16 08:14:52 UTC (rev 3824) @@ -0,0 +1,120 @@ +#' Plots log normal VaR against confidence level +#' +#' Plots the VaR of a portfolio against confidence level assuming that geometric +#' returns are normally distributed, for specified confidence level and +#' holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param cl VaR confidence level and must be a vector +#' @param hp VaR holding period and must be a scalar +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there are 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots VaR against confidene level given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogNormalVaRPlot2DCL(returns = data, investment = 5, cl = seq(.85,.99,.01), hp = 60) +#' +#' # Computes VaR against confidence level given mean and standard deviation of return data +#' LogNormalVaRPlot2DCL(mu = .012, sigma = .03, investment = 5, cl = seq(.85,.99,.01), hp = 40) +#' +#' +#' @export +LogNormalVaRPlot2DCL <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() > 5) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 5) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + investment <- args$investment + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that cl is read as row vector + if (cl.row > cl.col) { + cl <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Holding period must be greater than 0") + } + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- investment - exp(sigma[1,1] * sqrt(hp[1,1]) * qnorm(1 - cl, 0, 1)+mu[1,1]*hp[1,1]*matrix(1,cl.row,cl.col) + log(investment) + ) # VaR + # Plotting + plot(cl, VaR, type = "l", xlab = "Confidence Level", ylab = "VaR") + title("Log-t VaR against confidence level") + xmin <-min(cl)+.3*(max(cl)-min(cl)) + text(xmin,max(VaR)-.1*(max(VaR)-min(VaR)), + 'Input parameters', cex=.75, font = 2) + text(xmin,max(VaR)-.15*(max(VaR)-min(VaR)), + paste('Daily mean geometric return = ',round(mu[1,1],3)),cex=.75) + text(xmin,max(VaR)-.2*(max(VaR)-min(VaR)), + paste('Stdev. of daily geometric returns = ',round(sigma[1,1],3)),cex=.75) + text(xmin,max(VaR)-.25*(max(VaR)-min(VaR)), + paste('Investment size = ',investment),cex=.75) + text(xmin,max(VaR)-.3*(max(VaR)-min(VaR)), + paste('Holding period = ',hp,'days'),cex=.75) +} Added: pkg/Dowd/man/LogNormalVaRPlot2DCL.Rd =================================================================== --- pkg/Dowd/man/LogNormalVaRPlot2DCL.Rd (rev 0) +++ pkg/Dowd/man/LogNormalVaRPlot2DCL.Rd 2015-07-16 08:14:52 UTC (rev 3824) @@ -0,0 +1,47 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogNormalVaRPlot2DCL.R +\name{LogNormalVaRPlot2DCL} +\alias{LogNormalVaRPlot2DCL} +\title{Plots log normal VaR against confidence level} +\usage{ +LogNormalVaRPlot2DCL(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{cl}{VaR confidence level and must be a vector} + +\item{hp}{VaR holding period and must be a scalar} +} +\description{ +Plots the VaR of a portfolio against confidence level assuming that geometric + returns are normally distributed, for specified confidence level and + holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 4 + or 5. In case there are 4 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Plots VaR against confidene level given geometric return data + data <- runif(5, min = 0, max = .2) + LogNormalVaRPlot2DCL(returns = data, investment = 5, cl = seq(.85,.99,.01), hp = 60) + + # Computes VaR against confidence level given mean and standard deviation of return data + LogNormalVaRPlot2DCL(mu = .012, sigma = .03, investment = 5, cl = seq(.85,.99,.01), hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Thu Jul 16 10:15:28 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 16 Jul 2015 10:15:28 +0200 (CEST) Subject: [Returnanalytics-commits] r3825 - in pkg/Dowd: R man Message-ID: <20150716081528.EC824187A3E@r-forge.r-project.org> Author: dacharya Date: 2015-07-16 10:15:28 +0200 (Thu, 16 Jul 2015) New Revision: 3825 Added: pkg/Dowd/R/LogNormalVaRPlot2DHP.R pkg/Dowd/man/LogNormalVaRPlot2DHP.Rd Log: Function LogNormalVaRPlot2DHP added. Added: pkg/Dowd/R/LogNormalVaRPlot2DHP.R =================================================================== --- pkg/Dowd/R/LogNormalVaRPlot2DHP.R (rev 0) +++ pkg/Dowd/R/LogNormalVaRPlot2DHP.R 2015-07-16 08:15:28 UTC (rev 3825) @@ -0,0 +1,120 @@ +#' Plots log normal VaR against holding period +#' +#' Plots the VaR of a portfolio against holding period assuming that geometric returns are +#' normal distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param cl VaR confidence level and must be a scalar +#' @param hp VaR holding period and must be a vector +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes VaR given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogNormalVaRPlot2DHP(returns = data, investment = 5, cl = .95, hp = 60:90) +#' +#' # Computes VaR given mean and standard deviation of return data +#' LogNormalVaRPlot2DHP(mu = .012, sigma = .03, investment = 5, cl = .99, hp = 40:80) +#' +#' +#' @export +LogNormalVaRPlot2DHP <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() > 5) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 5) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + investment <- args$investment + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (max(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a vector") + } + + # Check that hp is read as row vector + if (hp.row > hp.col) { + hp <- t(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 level must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level must be greater than 0") + } + if (min(hp) <= 0){ + stop("Holding periods must be greater than 0") + } + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- investment - exp(sigma[1,1] * sqrt(t(hp)) * qnorm(1 - cl[1,1], 0, 1) + + mu[1,1] * t(hp) %*% matrix(1, cl.row, cl.col) + log(investment)) # VaR + # Plotting + plot(hp, VaR, type = "l", xlab = "Holding Period", ylab = "VaR") + cl.label <- cl * 100 + title("Log Normal VaR against holding period") + xmin <-min(hp)+.25*(max(hp)-min(hp)) + text(xmin,max(VaR)-.1*(max(VaR)-min(VaR)), + 'Input parameters', cex=.75, font = 2) + text(xmin,max(VaR)-.15*(max(VaR)-min(VaR)), + paste('Daily mean geometric return = ',mu[1,1]),cex=.75) + text(xmin,max(VaR)-.2*(max(VaR)-min(VaR)), + paste('Stdev. of daily geometric returns = ',sigma[1,1]),cex=.75) + text(xmin,max(VaR)-.25*(max(VaR)-min(VaR)), + paste('Investment size = ',investment),cex=.75) + text(xmin,max(VaR)-.3*(max(VaR)-min(VaR)), + paste('Confidence level = ',cl.label,'%'),cex=.75) +} Added: pkg/Dowd/man/LogNormalVaRPlot2DHP.Rd =================================================================== --- pkg/Dowd/man/LogNormalVaRPlot2DHP.Rd (rev 0) +++ pkg/Dowd/man/LogNormalVaRPlot2DHP.Rd 2015-07-16 08:15:28 UTC (rev 3825) @@ -0,0 +1,46 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogNormalVaRPlot2DHP.R +\name{LogNormalVaRPlot2DHP} +\alias{LogNormalVaRPlot2DHP} +\title{Plots log normal VaR against holding period} +\usage{ +LogNormalVaRPlot2DHP(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{cl}{VaR confidence level and must be a scalar} + +\item{hp}{VaR holding period and must be a vector} +} +\description{ +Plots the VaR of a portfolio against holding period assuming that geometric returns are +normal distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 4 + or 5. In case there 4 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Computes VaR given geometric return data + data <- runif(5, min = 0, max = .2) + LogNormalVaRPlot2DHP(returns = data, investment = 5, cl = .95, hp = 60:90) + + # Computes VaR given mean and standard deviation of return data + LogNormalVaRPlot2DHP(mu = .012, sigma = .03, investment = 5, cl = .99, hp = 40:80) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Thu Jul 16 10:16:00 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 16 Jul 2015 10:16:00 +0200 (CEST) Subject: [Returnanalytics-commits] r3826 - in pkg/Dowd: R man Message-ID: <20150716081600.C731F187AD7@r-forge.r-project.org> Author: dacharya Date: 2015-07-16 10:16:00 +0200 (Thu, 16 Jul 2015) New Revision: 3826 Added: pkg/Dowd/R/LogNormalVaRPlot3D.R pkg/Dowd/man/LogNormalVaRPlot3D.Rd Log: Function LogNormalVaRPlot3D added. Added: pkg/Dowd/R/LogNormalVaRPlot3D.R =================================================================== --- pkg/Dowd/R/LogNormalVaRPlot3D.R (rev 0) +++ pkg/Dowd/R/LogNormalVaRPlot3D.R 2015-07-16 08:16:00 UTC (rev 3826) @@ -0,0 +1,115 @@ +#' Plots log normal VaR against confidence level and holding period +#' +#' Plots the VaR of a portfolio against confidence level and holding period assuming that geometric +#' returns are normal distributed, for specified confidence level and +#' holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param cl VaR confidence level and must be a vector +#' @param hp VaR holding period and must be a vector +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots VaR against confidene level given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogNormalVaRPlot3D(returns = data, investment = 5, cl = seq(.85,.99,.01), hp = 60:90) +#' +#' # Computes VaR against confidence level given mean and standard deviation of return data +#' LogNormalVaRPlot3D(mu = .012, sigma = .03, investment = 5, cl = seq(.85,.99,.02), hp = 40:80) +#' +#' +#' @export +LogNormalVaRPlot3D <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() > 5) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 5) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + investment <- args$investment + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a vector") + } + + # Check that cl is read as row vector + if (cl.row > cl.col) { + cl <- t(cl) + } + # Check that hp is read as column vector + if (hp.col > hp.row) { + hp <- t(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 greater than 0") + } + if (min(hp) <= 0){ + stop("Holding periods must be greater than 0") + } + + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- investment - exp( sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) # VaR + # Plotting + persp(x=cl, y=hp, t(VaR), xlab = "Confidence Level", + ylab = "Holding Period", zlab = "VaR", + main = "Log Normal VaR against confidence level and holding period") + +} Added: pkg/Dowd/man/LogNormalVaRPlot3D.Rd =================================================================== --- pkg/Dowd/man/LogNormalVaRPlot3D.Rd (rev 0) +++ pkg/Dowd/man/LogNormalVaRPlot3D.Rd 2015-07-16 08:16:00 UTC (rev 3826) @@ -0,0 +1,47 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogNormalVaRPlot3D.R +\name{LogNormalVaRPlot3D} +\alias{LogNormalVaRPlot3D} +\title{Plots log normal VaR against confidence level and holding period} +\usage{ +LogNormalVaRPlot3D(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{cl}{VaR confidence level and must be a vector} + +\item{hp}{VaR holding period and must be a vector} +} +\description{ +Plots the VaR of a portfolio against confidence level and holding period assuming that geometric + returns are normal distributed, for specified confidence level and + holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 4 + or 5. In case there 4 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Plots VaR against confidene level given geometric return data + data <- runif(5, min = 0, max = .2) + LogNormalVaRPlot3D(returns = data, investment = 5, cl = seq(.85,.99,.01), hp = 60:90) + + # Computes VaR against confidence level given mean and standard deviation of return data + LogNormalVaRPlot3D(mu = .012, sigma = .03, investment = 5, cl = seq(.85,.99,.02), hp = 40:80) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Fri Jul 17 16:33:13 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 17 Jul 2015 16:33:13 +0200 (CEST) Subject: [Returnanalytics-commits] r3827 - pkg/Dowd Message-ID: <20150717143313.6EE41183C15@r-forge.r-project.org> Author: dacharya Date: 2015-07-17 16:33:13 +0200 (Fri, 17 Jul 2015) New Revision: 3827 Modified: pkg/Dowd/NAMESPACE Log: Functions LogNormalESFigure and LogNormalVaRETLPlot2DCL added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-16 08:16:00 UTC (rev 3826) +++ pkg/Dowd/NAMESPACE 2015-07-17 14:33:13 UTC (rev 3827) @@ -60,11 +60,13 @@ export(KuiperTestStat) export(LogNormalES) export(LogNormalESDFPerc) +export(LogNormalESFigure) export(LogNormalESPlot2DCL) export(LogNormalESPlot2DHP) export(LogNormalESPlot3D) export(LogNormalVaR) export(LogNormalVaRDFPerc) +export(LogNormalVaRETLPlot2DCL) export(LogNormalVaRFigure) export(LogNormalVaRPlot2DCL) export(LogNormalVaRPlot2DHP) From noreply at r-forge.r-project.org Fri Jul 17 16:35:12 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 17 Jul 2015 16:35:12 +0200 (CEST) Subject: [Returnanalytics-commits] r3828 - in pkg/Dowd: R man Message-ID: <20150717143512.9E406186EC4@r-forge.r-project.org> Author: dacharya Date: 2015-07-17 16:35:12 +0200 (Fri, 17 Jul 2015) New Revision: 3828 Added: pkg/Dowd/R/LogNormalVaRETLPlot2DCL.R pkg/Dowd/man/LogNormalVaRETLPlot2DCL.Rd Log: Function LogNormalVaRETLPlot2DCL added. Added: pkg/Dowd/R/LogNormalVaRETLPlot2DCL.R =================================================================== --- pkg/Dowd/R/LogNormalVaRETLPlot2DCL.R (rev 0) +++ pkg/Dowd/R/LogNormalVaRETLPlot2DCL.R 2015-07-17 14:35:12 UTC (rev 3828) @@ -0,0 +1,146 @@ +#' Plots log normal VaR and ETL against confidence level +#' +#' Plots the VaR and ETL of a portfolio against confidence level assuming that geometric +#' returns are normally distributed, for specified confidence level and +#' holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param cl VaR confidence level and must be a vector +#' @param hp VaR holding period and must be a scalar +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there are 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots VaR and ETL against confidene level given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' LogNormalVaRETLPlot2DCL(returns = data, investment = 5, cl = seq(.85,.99,.01), hp = 60) +#' +#' # Computes VaR against confidence level given mean and standard deviation of return data +#' LogNormalVaRETLPlot2DCL(mu = .012, sigma = .03, investment = 5, cl = seq(.85,.99,.01), hp = 40) +#' +#' +#' @export +LogNormalVaRETLPlot2DCL<- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() > 5) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 5) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + investment <- args$investment + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that cl is read as row vector + if (cl.row > cl.col) { + cl <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Holding period must be greater than 0") + } + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- investment - exp(sigma[1,1] * sqrt(hp[1,1]) * qnorm(1 - cl, 0, 1)+mu[1,1]*hp[1,1]*matrix(1,cl.row,cl.col) + log(investment)) # VaR + + # ES estimation + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + v <- VaR + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl # Revised cl + v <- v + investment - exp(sigma[1,1] * sqrt(hp[1,1]) * + qnorm(1 - cl, 0, 1) + mu[1,1] * hp[1,1] * + matrix(1, cl.row, cl.col) + log(investment)) + } + v <- v/n + + + # Plotting + ymin <- min(VaR, v) + ymax <- max(VaR, v) + xmin <- min(cl0) + xmax <- max(cl0) + + plot(cl0, VaR, type = "l", xlim = c(xmin, xmax), ylim = c(ymin, ymax), xlab = "Confidence level", ylab = "VaR/ETL") + par(new=TRUE) + plot(cl0, v, type = "l", xlim = c(xmin, xmax), ylim = c(ymin, ymax), xlab = "Confidence level", ylab = "VaR/ETL") + + title("Lognormal VaR and ETL against confidence level") + xmin <- min(cl0)+.3*(max(cl0)-min(cl0)) + text(xmin,max(VaR)-.1*(max(VaR)-min(VaR)), + 'Input parameters', cex=.75, font = 2) + text(xmin,max(VaR)-.15*(max(VaR)-min(VaR)), + paste('Daily mean geometric return = ',round(mu[1,1],3)),cex=.75) + text(xmin,max(VaR)-.2*(max(VaR)-min(VaR)), + paste('Stdev. of daily geometric returns = ',round(sigma[1,1],3)),cex=.75) + text(xmin,max(VaR)-.25*(max(VaR)-min(VaR)), + paste('Investment size = ',investment),cex=.75) + text(xmin,max(VaR)-.3*(max(VaR)-min(VaR)), + paste('Holding period = ',hp,'days'),cex=.75) + # VaR and ETL labels + text(max(cl0)-.4*(max(cl0)-min(cl0)),min(VaR)+.3*(max(VaR)-min(VaR)),'Upper line - ETL',cex=.75); + text(max(cl0)-.4*(max(cl0)-min(cl0)),min(VaR)+.2*(max(VaR)-min(VaR)),'Lower line - VaR',cex=.75); + +} Added: pkg/Dowd/man/LogNormalVaRETLPlot2DCL.Rd =================================================================== --- pkg/Dowd/man/LogNormalVaRETLPlot2DCL.Rd (rev 0) +++ pkg/Dowd/man/LogNormalVaRETLPlot2DCL.Rd 2015-07-17 14:35:12 UTC (rev 3828) @@ -0,0 +1,47 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogNormalVaRETLPlot2DCL.R +\name{LogNormalVaRETLPlot2DCL} +\alias{LogNormalVaRETLPlot2DCL} +\title{Plots log normal VaR and ETL against confidence level} +\usage{ +LogNormalVaRETLPlot2DCL(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{cl}{VaR confidence level and must be a vector} + +\item{hp}{VaR holding period and must be a scalar} +} +\description{ +Plots the VaR and ETL of a portfolio against confidence level assuming that geometric + returns are normally distributed, for specified confidence level and + holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 4 + or 5. In case there are 4 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Plots VaR and ETL against confidene level given geometric return data + data <- runif(5, min = 0, max = .2) + LogNormalVaRETLPlot2DCL(returns = data, investment = 5, cl = seq(.85,.99,.01), hp = 60) + + # Computes VaR against confidence level given mean and standard deviation of return data + LogNormalVaRETLPlot2DCL(mu = .012, sigma = .03, investment = 5, cl = seq(.85,.99,.01), hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Fri Jul 17 16:35:42 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 17 Jul 2015 16:35:42 +0200 (CEST) Subject: [Returnanalytics-commits] r3829 - in pkg/Dowd: R man Message-ID: <20150717143542.C1E85186EC4@r-forge.r-project.org> Author: dacharya Date: 2015-07-17 16:35:42 +0200 (Fri, 17 Jul 2015) New Revision: 3829 Added: pkg/Dowd/R/LogNormalESFigure.R pkg/Dowd/man/LogNormalESFigure.Rd Log: Function LogNormalESFigure added. Added: pkg/Dowd/R/LogNormalESFigure.R =================================================================== --- pkg/Dowd/R/LogNormalESFigure.R (rev 0) +++ pkg/Dowd/R/LogNormalESFigure.R 2015-07-17 14:35:42 UTC (rev 3829) @@ -0,0 +1,159 @@ +#' Figure of lognormal VaR and ES and pdf against L/P +#' +#' Gives figure showing the VaR and ES and probability distribution function against L/P of a portfolio assuming geometric returns are normally distributed, for specified confidence level and holding period. +#' +#' @param returns Vector of daily geometric return data +#' @param mu Mean of daily geometric return data +#' @param sigma Standard deviation of daily geometric return data +#' @param investment Size of investment +#' @param cl VaR confidence level and should be scalar +#' @param hp VaR holding period in days and should be scalar +#' +#' @note The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots lognormal VaR, ES and pdf against L/P data for given returns data +#' data <- runif(5, min = 0, max = .2) +#' LogNormalESFigure(returns = data, investment = 5, cl = .95, hp = 90) +#' +#' # Plots lognormal VaR, ES and pdf against L/P data with given parameters +#' LogNormalESFigure(mu = .012, sigma = .03, investment = 5, cl = .95, hp = 90) +#' +#' +#' @export +LogNormalESFigure <- function(...){ + # Determine if there are four or five arguments and ensure that arguments are + # read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() > 5) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 5) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + investment <- args$investment + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar or a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar or a vector") + } + + # Check that cl and hp are read as row and column vectors respectively + if (cl.row > cl.col) { + cl <- t(cl) + } + if (hp.row > hp.col) { + hp <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Holding Period(s) must be greater than 0") + } + + # Message to indicate how matrix of results is to be interpreted, if cl and hp both vary and results are given in matrix form + if (max(cl.row, cl.col) > 1 & max(hp.row, hp.col) > 1) { + print('VaR results with confidence level varying across row and holding period down column') + } + + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- investment - exp(sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) # VaR + + # ES Estimation + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + term <- VaR + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl # Revised cl + term <- term + investment - exp(sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) + log(investment)) + } + es <- term/n + + # Plotting + x.min <- mu - 5 * sigma + x.max <- investment + delta <- (x.max-x.min) / 100 + x <- seq(x.min, x.max, delta) + p <- dlnorm(investment - x, mu, sigma) + plot(x, p, type = "l", xlim = c(x.min, x.max), ylim = c(0, max(p)*1.1), xlab = "Loss (+) / Profit (-)", ylab = "Probability", main = "Lognormal VaR") + + # VaR line + u <- c(VaR, VaR) + v <- c(0, .6*max(p)) + lines(u, v, type = "l", col = "blue") + + # ES line + w <- c(es, es) + z <- c(0, .45*max(p)) + + # Input Labels + cl.for.label <- 100*cl + text(1,.95*max(p), pos = 1, 'Input parameters', cex=.75, font = 2) + text(1, .875*max(p),pos = 1, paste('Daily mean geometric return = ', round(mu,2)), cex=.75) + text(1, .8*max(p),pos = 1, paste('St. dev. of daily geometric returns = ',round(sigma,2)), cex=.75) + text(1, .725*max(p),pos = 1, paste('Investment size = ', investment), cex=.75) + text(1, .65*max(p),pos = 1, paste('Holding period = ', hp,' day(s)'), cex=.75) + + # VaR label + text(VaR, .7*max(p),pos = 2, paste('VaR at ', cl.for.label,'% CL'), cex=.75) + text(VaR, .65 * max(p),pos = 2, paste('= ',VaR), cex=.75) + + # ES label + text(es, .55*max(p),pos = 2, 'ES =', cex=.75) + text(VaR, .65 * max(p),pos = 2, paste(es), cex=.75) + + +} \ No newline at end of file Added: pkg/Dowd/man/LogNormalESFigure.Rd =================================================================== --- pkg/Dowd/man/LogNormalESFigure.Rd (rev 0) +++ pkg/Dowd/man/LogNormalESFigure.Rd 2015-07-17 14:35:42 UTC (rev 3829) @@ -0,0 +1,45 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LogNormalESFigure.R +\name{LogNormalESFigure} +\alias{LogNormalESFigure} +\title{Figure of lognormal VaR and ES and pdf against L/P} +\usage{ +LogNormalESFigure(...) +} +\arguments{ +\item{returns}{Vector of daily geometric return data} + +\item{mu}{Mean of daily geometric return data} + +\item{sigma}{Standard deviation of daily geometric return data} + +\item{investment}{Size of investment} + +\item{cl}{VaR confidence level and should be scalar} + +\item{hp}{VaR holding period in days and should be scalar} +} +\description{ +Gives figure showing the VaR and ES and probability distribution function against L/P of a portfolio assuming geometric returns are normally distributed, for specified confidence level and holding period. +} +\note{ +The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 4 + or 5. In case there 4 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +} +\examples{ +# Plots lognormal VaR, ES and pdf against L/P data for given returns data + data <- runif(5, min = 0, max = .2) + LogNormalESFigure(returns = data, investment = 5, cl = .95, hp = 90) + + # Plots lognormal VaR, ES and pdf against L/P data with given parameters + LogNormalESFigure(mu = .012, sigma = .03, investment = 5, cl = .95, hp = 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Sun Jul 19 23:30:16 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 19 Jul 2015 23:30:16 +0200 (CEST) Subject: [Returnanalytics-commits] r3830 - in pkg/Dowd: R man Message-ID: <20150719213016.86781187ADA@r-forge.r-project.org> Author: dacharya Date: 2015-07-19 23:30:16 +0200 (Sun, 19 Jul 2015) New Revision: 3830 Modified: pkg/Dowd/R/LogNormalES.R pkg/Dowd/R/LogNormalESDFPerc.R pkg/Dowd/R/LogNormalESFigure.R pkg/Dowd/R/LogNormalESPlot2DCL.R pkg/Dowd/R/LogNormalESPlot2DHP.R pkg/Dowd/R/LogNormalESPlot3D.R pkg/Dowd/R/LogNormalVaR.R pkg/Dowd/R/LogNormalVaRDFPerc.R pkg/Dowd/R/LogNormalVaRETLPlot2DCL.R pkg/Dowd/R/LogNormalVaRFigure.R pkg/Dowd/R/LogNormalVaRPlot2DCL.R pkg/Dowd/R/LogNormalVaRPlot2DHP.R pkg/Dowd/R/LogNormalVaRPlot3D.R pkg/Dowd/R/LogtES.R pkg/Dowd/R/LogtESDFPerc.R pkg/Dowd/R/LogtESPlot2DCL.R pkg/Dowd/R/LogtESPlot2DHP.R pkg/Dowd/R/LogtESPlot3D.R pkg/Dowd/R/LogtVaR.R pkg/Dowd/R/LogtVaRDFPerc.R pkg/Dowd/R/LogtVaRPlot2DCL.R pkg/Dowd/R/LogtVaRPlot2DHP.R pkg/Dowd/R/LogtVaRPlot3D.R pkg/Dowd/man/LogNormalES.Rd pkg/Dowd/man/LogNormalESDFPerc.Rd pkg/Dowd/man/LogNormalESFigure.Rd pkg/Dowd/man/LogNormalESPlot2DCL.Rd pkg/Dowd/man/LogNormalESPlot2DHP.Rd pkg/Dowd/man/LogNormalESPlot3D.Rd pkg/Dowd/man/LogNormalVaR.Rd pkg/Dowd/man/LogNormalVaRDFPerc.Rd pkg/Dowd/man/LogNormalVaRETLPlot2DCL.Rd pkg/Dowd/man/LogNormalVaRFigure.Rd pkg/Dowd/man/LogNormalVaRPlot2DCL.Rd pkg/Dowd/man/LogNormalVaRPlot2DHP.Rd pkg/Dowd/man/LogNormalVaRPlot3D.Rd pkg/Dowd/man/LogtES.Rd pkg/Dowd/man/LogtESDFPerc.Rd pkg/Dowd/man/LogtESPlot2DCL.Rd pkg/Dowd/man/LogtESPlot2DHP.Rd pkg/Dowd/man/LogtESPlot3D.Rd pkg/Dowd/man/LogtVaR.Rd pkg/Dowd/man/LogtVaRDFPerc.Rd pkg/Dowd/man/LogtVaRPlot2DCL.Rd pkg/Dowd/man/LogtVaRPlot2DHP.Rd pkg/Dowd/man/LogtVaRPlot3D.Rd Log: Documentation style for parameters changed. Modified: pkg/Dowd/R/LogNormalES.R =================================================================== --- pkg/Dowd/R/LogNormalES.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogNormalES.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -3,24 +3,30 @@ #' Estimates the ES of a portfolio assuming that geometric returns are #' normally distributed, for specified confidence level and holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param cl VaR confidence level -#' @param hp VaR holding period in days +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' investment Size of investment +#' +#' cl VaR confidence level +#' +#' hp VaR holding period in days +#' #' @return Matrix of ES whose dimension depends on dimension of hp and cl. If #' cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is #' a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, #' the matrix is column matrix and if both cl and hp are vectors, the matrix #' has dimension length of cl * length of hp. #' -#' @note The input arguments contain either return data or else mean and -#' standard deviation data. Accordingly, number of input arguments is either 4 -#' or 5. In case there 4 input arguments, the mean and standard deviation of -#' data is computed from return data. See examples for details. -#' -#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya #' @examples Modified: pkg/Dowd/R/LogNormalESDFPerc.R =================================================================== --- pkg/Dowd/R/LogNormalESDFPerc.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogNormalESDFPerc.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -1,21 +1,33 @@ -#' Percentiles of ES distribution function for normally distributed geometric returns +#' Percentiles of ES distribution function for normally distributed geometric +#' returns #' -#' Estimates the percentiles of ES distribution for normally distributed geometric returns, for specified confidence level and holding period using the theory of order statistics. +#' Estimates the percentiles of ES distribution for normally distributed +#' geometric returns, for specified confidence level and holding period using +#' the theory of order statistics. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param n Sample size -#' @param investment Size of investment -#' @param perc Desired percentile -#' @param cl ES confidence level and must be a scalar -#' @param hp ES holding period and must be a a scalar -#' @return Percentiles of ES distribution function -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 5 -#' or 7. In case there 5 input arguments, the mean, standard deviation and number of -#' samples is computed from return data. See examples for details. +#' or 7. In case there 5 input arguments, the mean, standard deviation and +#' number of samples is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data #' +#' sigma Standard deviation of daily geometric return data +#' +#' n Sample size +#' +#' investment Size of investment +#' +#' perc Desired percentile +#' +#' cl ES confidence level and must be a scalar +#' +#' hp ES holding period and must be a a scalar +#' +#' @return Percentiles of ES distribution function +#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya Modified: pkg/Dowd/R/LogNormalESFigure.R =================================================================== --- pkg/Dowd/R/LogNormalESFigure.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogNormalESFigure.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -1,20 +1,27 @@ #' Figure of lognormal VaR and ES and pdf against L/P #' -#' Gives figure showing the VaR and ES and probability distribution function against L/P of a portfolio assuming geometric returns are normally distributed, for specified confidence level and holding period. +#' Gives figure showing the VaR and ES and probability distribution function +#' against L/P of a portfolio assuming geometric returns are normally +#' distributed, for specified confidence level and holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param cl VaR confidence level and should be scalar -#' @param hp VaR holding period in days and should be scalar -#' -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 4 #' or 5. In case there 4 input arguments, the mean and standard deviation of #' data is computed from return data. See examples for details. #' -#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' investment Size of investment +#' +#' cl VaR confidence level and should be scalar +#' +#' hp VaR holding period in days and should be scalar +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya #' @examples @@ -138,6 +145,7 @@ # ES line w <- c(es, es) z <- c(0, .45*max(p)) + lines(w, z, type = "l", col = "blue") # Input Labels cl.for.label <- 100*cl Modified: pkg/Dowd/R/LogNormalESPlot2DCL.R =================================================================== --- pkg/Dowd/R/LogNormalESPlot2DCL.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogNormalESPlot2DCL.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -1,20 +1,26 @@ #' Plots log normal ES against confidence level #' -#' Plots the ES of a portfolio against confidence level assuming that geometric returns are -#' normally distributed, for specified confidence level and holding period. +#' Plots the ES of a portfolio against confidence level assuming that geometric +#' returns are normally distributed, for specified confidence level and holding +#' period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param cl ES confidence level and must be a vector -#' @param hp ES holding period and must be a scalar -#' -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 4 #' or 5. In case there 4 input arguments, the mean and standard deviation of #' data is computed from return data. See examples for details. #' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' investment Size of investment +#' +#' cl ES confidence level and must be a vector +#' +#' hp ES holding period and must be a scalar +#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya @@ -22,15 +28,18 @@ #' #' # Plots ES against confidence level #' data <- runif(5, min = 0, max = .2) -#' LogNormalESPlot2DCL(returns = data, investment = 5, cl = seq(.9,.99,.01), hp = 60) +#' LogNormalESPlot2DCL(returns = data, investment = 5, +#' cl = seq(.9,.99,.01), hp = 60) #' #' # Plots ES against confidence level -#' LogNormalESPlot2DCL(mu = .012, sigma = .03, investment = 5, cl = seq(.9,.99,.01), hp = 40) +#' LogNormalESPlot2DCL(mu = .012, sigma = .03, investment = 5, +#' cl = seq(.9,.99,.01), hp = 40) #' #' #' @export LogNormalESPlot2DCL <- function(...){ - # Determine if there are four or five arguments, and ensure that arguments are read as intended + # Determine if there are four or five arguments, and ensure that arguments are + # read as intended if (nargs() < 4) { stop("Too few arguments") } Modified: pkg/Dowd/R/LogNormalESPlot2DHP.R =================================================================== --- pkg/Dowd/R/LogNormalESPlot2DHP.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogNormalESPlot2DHP.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -3,18 +3,23 @@ #' Plots the ES of a portfolio against holding period assuming that geometric returns are #' normal distributed, for specified confidence level and holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param cl ES confidence level and must be a scalar -#' @param hp ES holding period and must be a vector -#' -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 4 #' or 5. In case there 4 input arguments, the mean and standard deviation of #' data is computed from return data. See examples for details. #' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' investment Size of investment +#' +#' cl ES confidence level and must be a scalar +#' +#' hp ES holding period and must be a vector +#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya Modified: pkg/Dowd/R/LogNormalESPlot3D.R =================================================================== --- pkg/Dowd/R/LogNormalESPlot3D.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogNormalESPlot3D.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -4,17 +4,21 @@ #' returns are normally distributed, for specified confidence level and #' holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param cl VaR confidence level and must be a vector -#' @param hp VaR holding period and must be a vector -#' -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 4 #' or 5. In case there 4 input arguments, the mean and standard deviation of #' data is computed from return data. See examples for details. #' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' cl VaR confidence level and must be a vector +#' +#' hp VaR holding period and must be a vector +#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya Modified: pkg/Dowd/R/LogNormalVaR.R =================================================================== --- pkg/Dowd/R/LogNormalVaR.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogNormalVaR.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -3,23 +3,29 @@ #' Estimates the VaR of a portfolio assuming that geometric returns are #' normally distributed, for specified confidence level and holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param cl VaR confidence level -#' @param hp VaR holding period in days +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' investment Size of investment +#' +#' cl VaR confidence level +#' +#' hp VaR holding period in days +#' #' @return Matrix of VaR whose dimension depends on dimension of hp and cl. If #' cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is #' a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, #' the matrix is column matrix and if both cl and hp are vectors, the matrix #' has dimension length of cl * length of hp. #' -#' @note The input arguments contain either return data or else mean and -#' standard deviation data. Accordingly, number of input arguments is either 4 -#' or 5. In case there 4 input arguments, the mean and standard deviation of -#' data is computed from return data. See examples for details. -#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya Modified: pkg/Dowd/R/LogNormalVaRDFPerc.R =================================================================== --- pkg/Dowd/R/LogNormalVaRDFPerc.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogNormalVaRDFPerc.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -1,20 +1,30 @@ #' Percentiles of VaR distribution function for normally distributed geometric returns #' -#' Estimates the percentile of VaR distribution function for normally distributed geometric returns, using the theory of order statistics. +#' Estimates the percentile of VaR distribution function for normally distributed +#' geometric returns, using the theory of order statistics. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param n Sample size -#' @param investment Size of investment -#' @param perc Desired percentile -#' @param cl VaR confidence level and must be a scalar -#' @param hp VaR holding period and must be a a scalar -#' @return Percentiles of VaR distribution function and is scalar -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 5 -#' or 7. In case there 5 input arguments, the mean, standard deviation and number of observations of -#' data are computed from returns data. See examples for details. +#' or 7. In case there 5 input arguments, the mean, standard deviation and number +#' of observations of data are computed from returns data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' n Sample size +#' +#' investment Size of investment +#' +#' perc Desired percentile +#' +#' cl VaR confidence level and must be a scalar +#' +#' hp VaR holding period and must be a a scalar +#' +#' Percentiles of VaR distribution function and is scalar #' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' Modified: pkg/Dowd/R/LogNormalVaRETLPlot2DCL.R =================================================================== --- pkg/Dowd/R/LogNormalVaRETLPlot2DCL.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogNormalVaRETLPlot2DCL.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -4,18 +4,23 @@ #' returns are normally distributed, for specified confidence level and #' holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param cl VaR confidence level and must be a vector -#' @param hp VaR holding period and must be a scalar -#' -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 4 #' or 5. In case there are 4 input arguments, the mean and standard deviation of #' data is computed from return data. See examples for details. #' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' investment Size of investment +#' +#' cl VaR confidence level and must be a vector +#' +#' hp VaR holding period and must be a scalar +#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya Modified: pkg/Dowd/R/LogNormalVaRFigure.R =================================================================== --- pkg/Dowd/R/LogNormalVaRFigure.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogNormalVaRFigure.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -1,19 +1,26 @@ #' Figure of lognormal VaR and pdf against L/P #' -#' Gives figure showing the VaR and probability distribution function against L/P of a portfolio assuming geometric returns are normally distributed, for specified confidence level and holding period. +#' Gives figure showing the VaR and probability distribution function against +#' L/P of a portfolio assuming geometric returns are normally distributed, for +#' specified confidence level and holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param cl VaR confidence level and should be scalar -#' @param hp VaR holding period in days and should be scalar -#' -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 4 #' or 5. In case there 4 input arguments, the mean and standard deviation of #' data is computed from return data. See examples for details. #' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' investment Size of investment +#' +#' cl VaR confidence level and should be scalar +#' +#' hp VaR holding period in days and should be scalar +#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya Modified: pkg/Dowd/R/LogNormalVaRPlot2DCL.R =================================================================== --- pkg/Dowd/R/LogNormalVaRPlot2DCL.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogNormalVaRPlot2DCL.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -4,18 +4,23 @@ #' returns are normally distributed, for specified confidence level and #' holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param cl VaR confidence level and must be a vector -#' @param hp VaR holding period and must be a scalar -#' -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 4 #' or 5. In case there are 4 input arguments, the mean and standard deviation of #' data is computed from return data. See examples for details. #' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' investment Size of investment +#' +#' cl VaR confidence level and must be a vector +#' +#' hp VaR holding period and must be a scalar +#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya Modified: pkg/Dowd/R/LogNormalVaRPlot2DHP.R =================================================================== --- pkg/Dowd/R/LogNormalVaRPlot2DHP.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogNormalVaRPlot2DHP.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -3,19 +3,24 @@ #' Plots the VaR of a portfolio against holding period assuming that geometric returns are #' normal distributed, for specified confidence level and holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param cl VaR confidence level and must be a scalar -#' @param hp VaR holding period and must be a vector -#' -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 4 #' or 5. In case there 4 input arguments, the mean and standard deviation of #' data is computed from return data. See examples for details. #' -#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' investment Size of investment +#' +#' cl VaR confidence level and must be a scalar +#' +#' hp VaR holding period and must be a vector +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya #' @examples Modified: pkg/Dowd/R/LogNormalVaRPlot3D.R =================================================================== --- pkg/Dowd/R/LogNormalVaRPlot3D.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogNormalVaRPlot3D.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -4,18 +4,23 @@ #' returns are normal distributed, for specified confidence level and #' holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param cl VaR confidence level and must be a vector -#' @param hp VaR holding period and must be a vector -#' -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 4 #' or 5. In case there 4 input arguments, the mean and standard deviation of #' data is computed from return data. See examples for details. #' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' investment Size of investment +#' +#' cl VaR confidence level and must be a vector +#' +#' hp VaR holding period and must be a vector +#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya Modified: pkg/Dowd/R/LogtES.R =================================================================== --- pkg/Dowd/R/LogtES.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogtES.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -3,24 +3,31 @@ #' Estimates the ES of a portfolio assuming that geometric returns are #' Student-t distributed, for specified confidence level and holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param df Number of degrees of freedom in the t distribution -#' @param cl VaR confidence level -#' @param hp VaR holding period +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 6. In case there 5 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' investment Size of investment +#' +#' df Number of degrees of freedom in the t distribution +#' +#' cl VaR confidence level +#' +#' hp VaR holding period +#' #' @return Matrix of ES whose dimension depends on dimension of hp and cl. If #' cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is #' a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, #' the matrix is column matrix and if both cl and hp are vectors, the matrix #' has dimension length of cl * length of hp. #' -#' @note The input arguments contain either return data or else mean and -#' standard deviation data. Accordingly, number of input arguments is either 5 -#' or 6. In case there 5 input arguments, the mean and standard deviation of -#' data is computed from return data. See examples for details. -#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya Modified: pkg/Dowd/R/LogtESDFPerc.R =================================================================== --- pkg/Dowd/R/LogtESDFPerc.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogtESDFPerc.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -3,21 +3,31 @@ #' Plots the ES of a portfolio against confidence level assuming that geometric returns are #' Student t distributed, for specified confidence level and holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param n Sample size -#' @param investment Size of investment -#' @param perc Desired percentile -#' @param df Number of degrees of freedom in the t distribution -#' @param cl ES confidence level and must be a scalar -#' @param hp ES holding period and must be a a scalar -#' @return Percentiles of ES distribution function -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 6 #' or 8. In case there 6 input arguments, the mean and standard deviation of #' data is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data #' +#' sigma Standard deviation of daily geometric return data +#' +#' n Sample size +#' +#' investment Size of investment +#' +#' perc Desired percentile +#' +#' df Number of degrees of freedom in the t distribution +#' +#' cl ES confidence level and must be a scalar +#' +#' hp ES holding period and must be a a scalar +#' +#' @return Percentiles of ES distribution function +#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya Modified: pkg/Dowd/R/LogtESPlot2DCL.R =================================================================== --- pkg/Dowd/R/LogtESPlot2DCL.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogtESPlot2DCL.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -3,19 +3,25 @@ #' Plots the ES of a portfolio against confidence level assuming that geometric returns are #' Student t distributed, for specified confidence level and holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param df Number of degrees of freedom in the t distribution -#' @param cl ES confidence level and must be a vector -#' @param hp ES holding period and must be a scalar -#' -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 5 #' or 6. In case there 5 input arguments, the mean and standard deviation of #' data is computed from return data. See examples for details. #' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' investment Size of investment +#' +#' df Number of degrees of freedom in the t distribution +#' +#' cl ES confidence level and must be a vector +#' +#' hp ES holding period and must be a scalar +#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya Modified: pkg/Dowd/R/LogtESPlot2DHP.R =================================================================== --- pkg/Dowd/R/LogtESPlot2DHP.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogtESPlot2DHP.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -3,19 +3,25 @@ #' Plots the ES of a portfolio against holding period assuming that geometric returns are #' Student t distributed, for specified confidence level and holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param df Number of degrees of freedom in the t distribution -#' @param cl ES confidence level and must be a scalar -#' @param hp ES holding period and must be a vector -#' -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 5 #' or 6. In case there 5 input arguments, the mean and standard deviation of #' data is computed from return data. See examples for details. #' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' investment Size of investment +#' +#' df Number of degrees of freedom in the t distribution +#' +#' cl ES confidence level and must be a scalar +#' +#' hp ES holding period and must be a vector +#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya @@ -28,7 +34,6 @@ #' # Computes v given mean and standard deviation of return data #' LogtESPlot2DHP(mu = .012, sigma = .03, investment = 5, df = 6, cl = .99, hp = 40:80) #' -#' #' @export LogtESPlot2DHP <- function(...){ if (nargs() < 5) { Modified: pkg/Dowd/R/LogtESPlot3D.R =================================================================== --- pkg/Dowd/R/LogtESPlot3D.R 2015-07-17 14:35:42 UTC (rev 3829) +++ pkg/Dowd/R/LogtESPlot3D.R 2015-07-19 21:30:16 UTC (rev 3830) @@ -4,19 +4,25 @@ #' returns are Student-t distributed, for specified confidence level and #' holding period. #' -#' @param returns Vector of daily geometric return data -#' @param mu Mean of daily geometric return data -#' @param sigma Standard deviation of daily geometric return data -#' @param investment Size of investment -#' @param df Number of degrees of freedom in the t distribution -#' @param cl VaR confidence level and must be a vector -#' @param hp VaR holding period and must be a vector -#' -#' @note The input arguments contain either return data or else mean and +#' @param ... The input arguments contain either return data or else mean and #' standard deviation data. Accordingly, number of input arguments is either 5 #' or 6. In case there 5 input arguments, the mean and standard deviation of [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3830 From noreply at r-forge.r-project.org Mon Jul 20 16:13:11 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 20 Jul 2015 16:13:11 +0200 (CEST) Subject: [Returnanalytics-commits] r3831 - pkg/Dowd Message-ID: <20150720141311.2A740185FF7@r-forge.r-project.org> Author: dacharya Date: 2015-07-20 16:13:10 +0200 (Mon, 20 Jul 2015) New Revision: 3831 Modified: pkg/Dowd/DESCRIPTION Log: Lower case in Title changed (compatibility to CRAN). Modified: pkg/Dowd/DESCRIPTION =================================================================== --- pkg/Dowd/DESCRIPTION 2015-07-19 21:30:16 UTC (rev 3830) +++ pkg/Dowd/DESCRIPTION 2015-07-20 14:13:10 UTC (rev 3831) @@ -1,12 +1,12 @@ Package: Dowd Type: Package -Title: R-version of MMR II toolbox offered in Kevin Dowd's book Measuring Market Risk +Title: R-version of MMR II Toolbox Offered in Kevin Dowd's Book Measuring Market Risk Version: 0.1 Date: 2015-05-24 Author: Dinesh Acharya Maintainer: Dinesh Acharya -Description: This package is R-version of MMR2 Toolbox that supplements - Kevin Dowd's book measuring market risk. +Description: R-version of MMR2 Toolbox that supplements + Kevin Dowd's book Measuring Market Risk Depends: R (>= 3.0.0), bootstrap, MASS, From noreply at r-forge.r-project.org Mon Jul 20 16:15:53 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 20 Jul 2015 16:15:53 +0200 (CEST) Subject: [Returnanalytics-commits] r3832 - pkg/Dowd/R Message-ID: <20150720141553.4C3BE185FF7@r-forge.r-project.org> Author: dacharya Date: 2015-07-20 16:15:52 +0200 (Mon, 20 Jul 2015) New Revision: 3832 Modified: pkg/Dowd/R/LogtVaRDFPerc.R Log: Changed length of example from longer than 100 chars to lesser. Modified: pkg/Dowd/R/LogtVaRDFPerc.R =================================================================== --- pkg/Dowd/R/LogtVaRDFPerc.R 2015-07-20 14:13:10 UTC (rev 3831) +++ pkg/Dowd/R/LogtVaRDFPerc.R 2015-07-20 14:15:52 UTC (rev 3832) @@ -36,10 +36,12 @@ #' #' # Estimates Percentiles of VaR distribution #' data <- runif(5, min = 0, max = .2) -#' LogtVaRDFPerc(returns = data, investment = 5, perc = .7, df = 6, cl = .95, hp = 60) +#' LogtVaRDFPerc(returns = data, investment = 5, perc = .7, +#' df = 6, cl = .95, hp = 60) #' #' # Computes v given mean and standard deviation of return data -#' LogtVaRDFPerc(mu = .012, sigma = .03, n= 10, investment = 5, perc = .8, df = 6, cl = .99, hp = 40) +#' LogtVaRDFPerc(mu = .012, sigma = .03, n= 10, investment = 5, +#' perc = .8, df = 6, cl = .99, hp = 40) #' #' #' @export From noreply at r-forge.r-project.org Mon Jul 20 17:07:35 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 20 Jul 2015 17:07:35 +0200 (CEST) Subject: [Returnanalytics-commits] r3833 - in pkg/Dowd: R man Message-ID: <20150720150735.5B4F4187ABC@r-forge.r-project.org> Author: dacharya Date: 2015-07-20 17:07:35 +0200 (Mon, 20 Jul 2015) New Revision: 3833 Modified: pkg/Dowd/R/HSES.R pkg/Dowd/R/HSVaR.R pkg/Dowd/man/HSES.Rd pkg/Dowd/man/HSVaR.Rd Log: "o with Umlaut" replaced with "oe" in Foellmer in reference. Modified: pkg/Dowd/R/HSES.R =================================================================== --- pkg/Dowd/R/HSES.R 2015-07-20 14:15:52 UTC (rev 3832) +++ pkg/Dowd/R/HSES.R 2015-07-20 15:07:35 UTC (rev 3833) @@ -19,7 +19,7 @@ #' Artzner, P., Delbaen, F., Eber, J.M. and Heath, D. Coherent Risk Measures #' of Risk. Mathematical Finance 9(3), 1999, 203. #' -#' F?llmer, H. and Scheid, A. Stochastic Finance: An Introduction in Discrete +#' Foellmer, H. and Scheid, A. Stochastic Finance: An Introduction in Discrete #' Time. De Gryuter, 2011. #' #' @author Dinesh Acharya @@ -109,4 +109,4 @@ } } return(y) -} \ No newline at end of file +} Modified: pkg/Dowd/R/HSVaR.R =================================================================== --- pkg/Dowd/R/HSVaR.R 2015-07-20 14:15:52 UTC (rev 3832) +++ pkg/Dowd/R/HSVaR.R 2015-07-20 15:07:35 UTC (rev 3833) @@ -19,7 +19,7 @@ #' Artzner, P., Delbaen, F., Eber, J.M. and Heath, D. Coherent Risk Measures #' of Risk. Mathematical Finance 9(3), 1999, 203. #' -#' F?llmer, H. and Scheid, A. Stochastic Finance: An Introduction in Discrete +#' Foellmer, H. and Scheid, A. Stochastic Finance: An Introduction in Discrete #' Time. De Gryuter, 2011. #' #' @author Dinesh Acharya @@ -103,4 +103,4 @@ } return(y) -} \ No newline at end of file +} Modified: pkg/Dowd/man/HSES.Rd =================================================================== --- pkg/Dowd/man/HSES.Rd 2015-07-20 14:15:52 UTC (rev 3832) +++ pkg/Dowd/man/HSES.Rd 2015-07-20 15:07:35 UTC (rev 3833) @@ -40,6 +40,7 @@ Artzner, P., Delbaen, F., Eber, J.M. and Heath, D. Coherent Risk Measures of Risk. Mathematical Finance 9(3), 1999, 203. +Foellmer, H. and Scheid, A. Stochastic Finance: An Introduction in Discrete Time. De Gryuter, 2011. } Modified: pkg/Dowd/man/HSVaR.Rd =================================================================== --- pkg/Dowd/man/HSVaR.Rd 2015-07-20 14:15:52 UTC (rev 3832) +++ pkg/Dowd/man/HSVaR.Rd 2015-07-20 15:07:35 UTC (rev 3833) @@ -39,6 +39,7 @@ Artzner, P., Delbaen, F., Eber, J.M. and Heath, D. Coherent Risk Measures of Risk. Mathematical Finance 9(3), 1999, 203. +Foellmer, H. and Scheid, A. Stochastic Finance: An Introduction in Discrete Time. De Gryuter, 2011. } From noreply at r-forge.r-project.org Mon Jul 20 17:09:56 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 20 Jul 2015 17:09:56 +0200 (CEST) Subject: [Returnanalytics-commits] r3834 - pkg/Dowd/man Message-ID: <20150720150956.F3C95187493@r-forge.r-project.org> Author: dacharya Date: 2015-07-20 17:09:56 +0200 (Mon, 20 Jul 2015) New Revision: 3834 Modified: pkg/Dowd/man/LogtVaRDFPerc.Rd Log: Long single line broken into multi lines. Modified: pkg/Dowd/man/LogtVaRDFPerc.Rd =================================================================== --- pkg/Dowd/man/LogtVaRDFPerc.Rd 2015-07-20 15:07:35 UTC (rev 3833) +++ pkg/Dowd/man/LogtVaRDFPerc.Rd 2015-07-20 15:09:56 UTC (rev 3834) @@ -40,10 +40,12 @@ \examples{ # Estimates Percentiles of VaR distribution data <- runif(5, min = 0, max = .2) - LogtVaRDFPerc(returns = data, investment = 5, perc = .7, df = 6, cl = .95, hp = 60) + LogtVaRDFPerc(returns = data, investment = 5, perc = .7, + df = 6, cl = .95, hp = 60) # Computes v given mean and standard deviation of return data - LogtVaRDFPerc(mu = .012, sigma = .03, n= 10, investment = 5, perc = .8, df = 6, cl = .99, hp = 40) + LogtVaRDFPerc(mu = .012, sigma = .03, n= 10, investment = 5, + perc = .8, df = 6, cl = .99, hp = 40) } \author{ Dinesh Acharya From noreply at r-forge.r-project.org Tue Jul 21 23:02:48 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 21 Jul 2015 23:02:48 +0200 (CEST) Subject: [Returnanalytics-commits] r3835 - pkg/Dowd Message-ID: <20150721210248.9A0C2187941@r-forge.r-project.org> Author: dacharya Date: 2015-07-21 23:02:47 +0200 (Tue, 21 Jul 2015) New Revision: 3835 Modified: pkg/Dowd/NAMESPACE Log: Normal Functions namely: NormalES, NormalESConfidenceInterval, NormalESDFPerc, NormalESFigure, NormalESPlot2DCL, NormalESPlot2DHP and NormalESPlot3D added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-20 15:09:56 UTC (rev 3834) +++ pkg/Dowd/NAMESPACE 2015-07-21 21:02:47 UTC (rev 3835) @@ -83,6 +83,13 @@ export(LogtVaRPlot3D) export(LopezBacktest) export(MEFPlot) +export(NormalES) +export(NormalESConfidenceInterval) +export(NormalESDFPerc) +export(NormalESFigure) +export(NormalESPlot2DCL) +export(NormalESPlot2DHP) +export(NormalESPlot3D) export(NormalQQPlot) export(PCAES) export(PCAESPlot) From noreply at r-forge.r-project.org Tue Jul 21 23:03:52 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 21 Jul 2015 23:03:52 +0200 (CEST) Subject: [Returnanalytics-commits] r3836 - in pkg/Dowd: R man Message-ID: <20150721210352.B2B71187941@r-forge.r-project.org> Author: dacharya Date: 2015-07-21 23:03:52 +0200 (Tue, 21 Jul 2015) New Revision: 3836 Added: pkg/Dowd/R/NormalES.R pkg/Dowd/man/NormalES.Rd Log: Function NormalES added. Added: pkg/Dowd/R/NormalES.R =================================================================== --- pkg/Dowd/R/NormalES.R (rev 0) +++ pkg/Dowd/R/NormalES.R 2015-07-21 21:03:52 UTC (rev 3836) @@ -0,0 +1,119 @@ +#' ES for normally distributed P/L +#' +#' Estimates the ES of a portfolio assuming that P/L is +#' normally distributed, for specified confidence level and holding period. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data along with the remaining arguments. Accordingly, number of input arguments is either 3 +#' or 4. In case there 3 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' cl VaR confidence level +#' +#' hp VaR holding period in days +#' +#' @return Matrix of ES whose dimension depends on dimension of hp and cl. If +#' cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is +#' a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, +#' the matrix is column matrix and if both cl and hp are vectors, the matrix +#' has dimension length of cl * length of hp. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes VaR given P/L +#' data <- runif(5, min = 0, max = .2) +#' NormalES(returns = data, cl = .95, hp = 90) +#' +#' # Computes VaR given mean and standard deviation of P/L data +#' NormalES(mu = .012, sigma = .03, cl = .95, hp = 90) +#' +#' @export +NormalES <- function(...){ + # Determine if there are three or four arguments and ensure that arguments are + # read as intended + if (nargs() < 3) { + stop("Too few arguments") + } + if (nargs() > 4) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 4) { + mu <- args$mu + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 3) { + mu <- mean(args$returns) + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar or a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar or a vector") + } + + # Check that cl and hp are read as row and column vectors respectively + if (cl.row > cl.col) { + cl <- t(cl) + } + if (hp.row > hp.col) { + hp <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Holding Period(s) must be greater than 0") + } + es <- matrix(0, length(hp), length(cl)) + # ES estimation + for (i in 1:length(cl)) { + for (j in 1:length(hp)) { + es[j, i] = sigma * sqrt(hp[j]) * dnorm(qnorm(1 - cl[i], 0, 1), 0, 1) / (1 - cl[i]) - mu * hp[j] # ES + } + } + + return (es) +} \ No newline at end of file Added: pkg/Dowd/man/NormalES.Rd =================================================================== --- pkg/Dowd/man/NormalES.Rd (rev 0) +++ pkg/Dowd/man/NormalES.Rd 2015-07-21 21:03:52 UTC (rev 3836) @@ -0,0 +1,50 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalES.R +\name{NormalES} +\alias{NormalES} +\title{ES for normally distributed P/L} +\usage{ +NormalES(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and + standard deviation data along with the remaining arguments. Accordingly, number of input arguments is either 3 + or 4. In case there 3 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. + + returns Vector of daily geometric return data + + mu Mean of daily geometric return data + + sigma Standard deviation of daily geometric return data + + cl VaR confidence level + + hp VaR holding period in days} +} +\value{ +Matrix of ES whose dimension depends on dimension of hp and cl. If +cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is + a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, + the matrix is column matrix and if both cl and hp are vectors, the matrix + has dimension length of cl * length of hp. +} +\description{ +Estimates the ES of a portfolio assuming that P/L is +normally distributed, for specified confidence level and holding period. +} +\examples{ +# Computes VaR given P/L + data <- runif(5, min = 0, max = .2) + NormalES(returns = data, cl = .95, hp = 90) + + # Computes VaR given mean and standard deviation of P/L data + NormalES(mu = .012, sigma = .03, cl = .95, hp = 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jul 21 23:04:57 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 21 Jul 2015 23:04:57 +0200 (CEST) Subject: [Returnanalytics-commits] r3837 - in pkg/Dowd: R man Message-ID: <20150721210457.ADDCF186FFD@r-forge.r-project.org> Author: dacharya Date: 2015-07-21 23:04:57 +0200 (Tue, 21 Jul 2015) New Revision: 3837 Added: pkg/Dowd/R/NormalESConfidenceInterval.R pkg/Dowd/man/NormalESConfidenceInterval.Rd Log: Function NormalESConfidenceInterval added. Added: pkg/Dowd/R/NormalESConfidenceInterval.R =================================================================== --- pkg/Dowd/R/NormalESConfidenceInterval.R (rev 0) +++ pkg/Dowd/R/NormalESConfidenceInterval.R 2015-07-21 21:04:57 UTC (rev 3837) @@ -0,0 +1,37 @@ +#' Generates Monte Carlo 95\% Confidence Intervals for normal ES +#' +#' Generates 95\% confidence intervals for normal ES using Monte Carlo simulation +#' +#' @param mu Mean of the P/L process +#' @param sigma Standard deviation of the P/L process +#' @param number.trials Number of trials used in the simulations +#' @param sample.size Sample drawn in each trial +#' @param cl Confidence Level +#' @param hp Holding Period +#' +#' @return 95\% confidence intervals for normal ES +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' +#' @examples +#' +#' # Generates 95\% confidence intervals for normal ES for given parameters +#' NormalESConfidenceInterval(0, .5, 20, 20, .95, 90) +#' +#' +#' @export +NormalESConfidenceInterval <- function(mu, sigma, number.trials, sample.size, cl, hp){ + ES <- double(number.trials) + for (k in 1:number.trials) { + z <- rnorm(sample.size) + x <- sigma * z + mu + ES[k] <- NormalES(returns = x, cl = cl, hp = hp) + } + ES <- sort(ES) + lower.order.stat <- floor(0.025 * number.trials) + upper.order.stat <- ceiling(0.975 * number.trials) + y <- c(ES[lower.order.stat], ES[upper.order.stat]) + return(y) +} Added: pkg/Dowd/man/NormalESConfidenceInterval.Rd =================================================================== --- pkg/Dowd/man/NormalESConfidenceInterval.Rd (rev 0) +++ pkg/Dowd/man/NormalESConfidenceInterval.Rd 2015-07-21 21:04:57 UTC (rev 3837) @@ -0,0 +1,38 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalESConfidenceInterval.R +\name{NormalESConfidenceInterval} +\alias{NormalESConfidenceInterval} +\title{Generates Monte Carlo 95\% Confidence Intervals for normal ES} +\usage{ +NormalESConfidenceInterval(mu, sigma, number.trials, sample.size, cl, hp) +} +\arguments{ +\item{mu}{Mean of the P/L process} + +\item{sigma}{Standard deviation of the P/L process} + +\item{number.trials}{Number of trials used in the simulations} + +\item{sample.size}{Sample drawn in each trial} + +\item{cl}{Confidence Level} + +\item{hp}{Holding Period} +} +\value{ +95\% confidence intervals for normal ES +} +\description{ +Generates 95\% confidence intervals for normal ES using Monte Carlo simulation +} +\examples{ +# Generates 95\\\% confidence intervals for normal ES for given parameters + NormalESConfidenceInterval(0, .5, 20, 20, .95, 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jul 21 23:05:47 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 21 Jul 2015 23:05:47 +0200 (CEST) Subject: [Returnanalytics-commits] r3838 - in pkg/Dowd: R man Message-ID: <20150721210547.1BB27186FFD@r-forge.r-project.org> Author: dacharya Date: 2015-07-21 23:05:46 +0200 (Tue, 21 Jul 2015) New Revision: 3838 Added: pkg/Dowd/R/NormalESDFPerc.R pkg/Dowd/man/NormalESDFPerc.Rd Log: Function NormalESDFPerc added. Added: pkg/Dowd/R/NormalESDFPerc.R =================================================================== --- pkg/Dowd/R/NormalESDFPerc.R (rev 0) +++ pkg/Dowd/R/NormalESDFPerc.R 2015-07-21 21:05:46 UTC (rev 3838) @@ -0,0 +1,158 @@ +#' Percentiles of ES distribution function for normally distributed P/L data +#' +#' Estimates the percentiles of ES distribution for normally distributed P/L data, for specified confidence level and holding period using the theory of order statistics. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 or 6. In case there 4 input arguments, the mean, standard deviation and number of samples is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' n Sample size +#' +#' perc Desired percentile +#' +#' cl ES confidence level and must be a scalar +#' +#' hp ES holding period and must be a a scalar +#' +#' @return Percentiles of ES distribution function +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates Percentiles of ES distribution +#' data <- runif(5, min = 0, max = .2) +#' NormalESDFPerc(returns = data, perc = .7, cl = .95, hp = 60) +#' +#' # Estimates Percentiles given mean, standard deviation and number of sambles of return data +#' NormalESDFPerc(mu = .012, sigma = .03, n= 10, perc = .8, cl = .99, hp = 40) +#' +#' +#' @export +NormalESDFPerc <- function(...){ + # Determine if there are five or seven arguments, and ensure that arguments are read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() == 5) { + stop("Incorrect number of arguments") + } + if (nargs() > 6) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 6) { + mu <- args$mu + cl <- args$cl + perc <- args$sigma + n <- args$n + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + n <- max(dim(as.matrix(args$returns))) + perc <- args$perc + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + n <- as.matrix(n) + n.row <- dim(n)[1] + n.col <- dim(n)[2] + if (max(n.row, n.col) > 1) { + stop("Number of observations in a sample must be a scalar") + } + if (n %% 1 != 0) { + stop("Number of observations in a sample must be an integer.") + } + perc <- as.matrix(perc) + perc.row <- dim(perc)[1] + perc.col <- dim(perc)[2] + if (max(perc.row, perc.col) > 1) { + stop("Chosen percentile of the distribution must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (max(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (n < 0) { + stop("Number of observations must be non-negative") + } + if (perc > 1){ + stop("Chosen percentile must not exceed 1") + } + if (perc <= 0){ + stop("Chosen percentile must be positive") + } + 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("Honding period must be greater than 0") + } + + # Derive order statistic and ensure it is an integer + w <- n * cl # Derive r-th order statistic + 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 + } + } + + VaR.perc <- qnorm(x, -mu * hp, sigma * sqrt(hp)) # Value of VaR percentile; note normal VaR formula + + # ES estimation + ES <- sigma[1,1] * sqrt(hp) %*% dnorm(VaR.perc, 0, 1) / (1 - cl) - mu[1,1] * hp %*% matrix(1,cl.row,cl.col) # Value of ES percentile + + return(ES) +} \ No newline at end of file Added: pkg/Dowd/man/NormalESDFPerc.Rd =================================================================== --- pkg/Dowd/man/NormalESDFPerc.Rd (rev 0) +++ pkg/Dowd/man/NormalESDFPerc.Rd 2015-07-21 21:05:46 UTC (rev 3838) @@ -0,0 +1,47 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalESDFPerc.R +\name{NormalESDFPerc} +\alias{NormalESDFPerc} +\title{Percentiles of ES distribution function for normally distributed P/L data} +\usage{ +NormalESDFPerc(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and +standard deviation data. Accordingly, number of input arguments is either 4 or 6. In case there 4 input arguments, the mean, standard deviation and number of samples is computed from return data. See examples for details. + +returns Vector of daily geometric return data + +mu Mean of daily geometric return data + +sigma Standard deviation of daily geometric return data + +n Sample size + +perc Desired percentile + +cl ES confidence level and must be a scalar + +hp ES holding period and must be a a scalar} +} +\value{ +Percentiles of ES distribution function +} +\description{ +Estimates the percentiles of ES distribution for normally distributed P/L data, for specified confidence level and holding period using the theory of order statistics. +} +\examples{ +# Estimates Percentiles of ES distribution + data <- runif(5, min = 0, max = .2) + NormalESDFPerc(returns = data, perc = .7, cl = .95, hp = 60) + + # Estimates Percentiles given mean, standard deviation and number of sambles of return data + NormalESDFPerc(mu = .012, sigma = .03, n= 10, perc = .8, cl = .99, hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jul 21 23:06:16 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 21 Jul 2015 23:06:16 +0200 (CEST) Subject: [Returnanalytics-commits] r3839 - in pkg/Dowd: R man Message-ID: <20150721210616.34A61186FFD@r-forge.r-project.org> Author: dacharya Date: 2015-07-21 23:06:15 +0200 (Tue, 21 Jul 2015) New Revision: 3839 Added: pkg/Dowd/R/NormalESFigure.R pkg/Dowd/man/NormalESFigure.Rd Log: Function NormalESFigure added. Added: pkg/Dowd/R/NormalESFigure.R =================================================================== --- pkg/Dowd/R/NormalESFigure.R (rev 0) +++ pkg/Dowd/R/NormalESFigure.R 2015-07-21 21:06:15 UTC (rev 3839) @@ -0,0 +1,150 @@ +#' Figure of normal VaR and ES and pdf against L/P +#' +#' Gives figure showing the VaR and ES and probability distribution function against L/P of a portfolio assuming geometric returns are normally distributed, for specified confidence level and holding period. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 3 +#' or 4. In case there 3 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +# +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' cl VaR confidence level and should be scalar +#' +#' hp VaR holding period in days and should be scalar +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots lognormal VaR, ES and pdf against L/P data for given returns data +#' data <- runif(5, min = 0, max = .2) +#' NormalESFigure(returns = data, cl = .95, hp = 90) +#' +#' # Plots lognormal VaR, ES and pdf against L/P data with given parameters +#' NormalESFigure(mu = .012, sigma = .03, cl = .95, hp = 90) +#' +#' +#' @export +NormalESFigure <- function(...){ + # Determine if there are four or five arguments and ensure that arguments are + # read as intended + if (nargs() < 3) { + stop("Too few arguments") + } + if (nargs() > 4) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 4) { + mu <- args$mu + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 3) { + mu <- mean(args$returns) + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar or a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar or a vector") + } + + # Check that cl and hp are read as row and column vectors respectively + if (cl.row > cl.col) { + cl <- t(cl) + } + if (hp.row > hp.col) { + hp <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Holding Period(s) must be greater than 0") + } + + # Message to indicate how matrix of results is to be interpreted, if cl and hp both vary and results are given in matrix form + if (max(cl.row, cl.col) > 1 & max(hp.row, hp.col) > 1) { + print('VaR results with confidence level varying across row and holding period down column') + } + + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- - sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) - mu[1,1] * hp %*% matrix(1, cl.row, cl.col) # VaR + + # ES Estimation + es <- NormalES(mu = mu, sigma = sigma, cl = cl, hp = hp) + + # Plotting + x.min <- -mu - 5 * sigma + x.max <- -mu + 5 * sigma + delta <- (x.max-x.min) / 100 + x <- seq(x.min, x.max, delta) + p <- dlnorm(x, -mu, sigma) + plot(x, p, type = "l", xlim = c(x.min, x.max), ylim = c(0, max(p)*1.1), xlab = "Loss (+) / Profit (-)", ylab = "Probability", main = "Normal VaR") + + # VaR line + u <- c(VaR, VaR) + v <- c(0, .6*max(p)) + lines(u, v, type = "l", col = "blue") + + # ES line + w <- c(es, es) + z <- c(0, .45*max(p)) + lines(w, z, type = "l", col = "blue") + # Input Labels + cl.for.label <- 100 * cl + text(1,.95*max(p), pos = 1, 'Input parameters', cex=.75, font = 2) + text(1, .875*max(p),pos = 1, paste('Daily mean L/P = ', round(mu,2)), cex=.75) + text(1, .8*max(p),pos = 1, paste('St. dev. of daily L/P = ',round(sigma,2)), cex=.75) + text(1, .725*max(p),pos = 1, paste('Holding period = ', hp,' day(s)'), cex=.75) + + # VaR label + text(VaR, .7*max(p),pos = 2, paste('VaR at ', cl.for.label,'% CL'), cex=.75) + text(VaR, .65 * max(p),pos = 2, paste('= ',VaR), cex=.75) + + # ES label + text(es, .55*max(p),pos = 2, 'ES =', cex=.75) + text(VaR, .65 * max(p),pos = 2, paste(es), cex=.75) + +} Added: pkg/Dowd/man/NormalESFigure.Rd =================================================================== --- pkg/Dowd/man/NormalESFigure.Rd (rev 0) +++ pkg/Dowd/man/NormalESFigure.Rd 2015-07-21 21:06:15 UTC (rev 3839) @@ -0,0 +1,41 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalESFigure.R +\name{NormalESFigure} +\alias{NormalESFigure} +\title{Figure of normal VaR and ES and pdf against L/P} +\usage{ +NormalESFigure(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 3 + or 4. In case there 3 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. + returns Vector of daily geometric return data + + mu Mean of daily geometric return data + + sigma Standard deviation of daily geometric return data + + cl VaR confidence level and should be scalar + + hp VaR holding period in days and should be scalar} +} +\description{ +Gives figure showing the VaR and ES and probability distribution function against L/P of a portfolio assuming geometric returns are normally distributed, for specified confidence level and holding period. +} +\examples{ +# Plots lognormal VaR, ES and pdf against L/P data for given returns data + data <- runif(5, min = 0, max = .2) + NormalESFigure(returns = data, cl = .95, hp = 90) + + # Plots lognormal VaR, ES and pdf against L/P data with given parameters + NormalESFigure(mu = .012, sigma = .03, cl = .95, hp = 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jul 21 23:07:06 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 21 Jul 2015 23:07:06 +0200 (CEST) Subject: [Returnanalytics-commits] r3840 - in pkg/Dowd: R man Message-ID: <20150721210706.14E1F186FFD@r-forge.r-project.org> Author: dacharya Date: 2015-07-21 23:07:05 +0200 (Tue, 21 Jul 2015) New Revision: 3840 Added: pkg/Dowd/R/NormalESPlot2DCL.R pkg/Dowd/man/NormalESPlot2DCL.Rd Log: Function NormalESPlot2DCL added. Added: pkg/Dowd/R/NormalESPlot2DCL.R =================================================================== --- pkg/Dowd/R/NormalESPlot2DCL.R (rev 0) +++ pkg/Dowd/R/NormalESPlot2DCL.R 2015-07-21 21:07:05 UTC (rev 3840) @@ -0,0 +1,116 @@ +#' Plots normal ES against confidence level +#' +#' Plots the ES of a portfolio against confidence level assuming that P/L are +#' normally distributed, for specified confidence level and holding period. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 3 +#' or 4. In case there 3 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' cl ES confidence level and must be a vector +#' +#' hp ES holding period and must be a scalar +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots ES against confidence level +#' data <- runif(5, min = 0, max = .2) +#' NormalESPlot2DCL(returns = data, cl = seq(.9,.99,.01), hp = 60) +#' +#' # Plots ES against confidence level +#' NormalESPlot2DCL(mu = .012, sigma = .03, cl = seq(.9,.99,.01), hp = 40) +#' +#' @export +NormalESPlot2DCL <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended + if (nargs() < 3) { + stop("Too few arguments") + } + if (nargs() > 4) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 4) { + mu <- args$mu + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 3) { + mu <- mean(args$returns) + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that hp is read as row vector + if (cl.row > cl.col) { + cl <- t(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 greater than 0") + } + if (min(hp) <= 0){ + stop("Holding period must be greater than 0") + } + + # ES estimation + v <- NormalES(mu = mu[1,1], sigma = sigma[1,1], cl = as.vector(cl), hp = hp[1,1]) + + # Plotting + plot(cl, v, type = "l", xlab = "Holding Period", ylab = "ES") + title("Normal ES against holding period") + xmin <-min(cl)+.25*(max(cl)-min(cl)) + text(xmin,max(v)-.1*(max(v)-min(v)), + 'Input parameters', cex=.75, font = 2) + text(xmin,max(v)-.15*(max(v)-min(v)), + paste('Daily mean geometric return = ',round(mu[1,1],3)),cex=.75) + text(xmin,max(v)-.2*(max(v)-min(v)), + paste('Stdev. of daily geometric returns = ',round(sigma[1,1],3)),cex=.75) + text(xmin,max(v)-.25*(max(v)-min(v)), + paste('Holding Period = ',hp),cex=.75) +} Added: pkg/Dowd/man/NormalESPlot2DCL.Rd =================================================================== --- pkg/Dowd/man/NormalESPlot2DCL.Rd (rev 0) +++ pkg/Dowd/man/NormalESPlot2DCL.Rd 2015-07-21 21:07:05 UTC (rev 3840) @@ -0,0 +1,43 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalESPlot2DCL.R +\name{NormalESPlot2DCL} +\alias{NormalESPlot2DCL} +\title{Plots normal ES against confidence level} +\usage{ +NormalESPlot2DCL(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 3 + or 4. In case there 3 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. + + returns Vector of daily geometric return data + + mu Mean of daily geometric return data + + sigma Standard deviation of daily geometric return data + + cl ES confidence level and must be a vector + + hp ES holding period and must be a scalar} +} +\description{ +Plots the ES of a portfolio against confidence level assuming that P/L are +normally distributed, for specified confidence level and holding period. +} +\examples{ +# Plots ES against confidence level + data <- runif(5, min = 0, max = .2) + NormalESPlot2DCL(returns = data, cl = seq(.9,.99,.01), hp = 60) + + # Plots ES against confidence level + NormalESPlot2DCL(mu = .012, sigma = .03, cl = seq(.9,.99,.01), hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jul 21 23:07:39 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 21 Jul 2015 23:07:39 +0200 (CEST) Subject: [Returnanalytics-commits] r3841 - in pkg/Dowd: R man Message-ID: <20150721210739.E23EE186FFD@r-forge.r-project.org> Author: dacharya Date: 2015-07-21 23:07:39 +0200 (Tue, 21 Jul 2015) New Revision: 3841 Added: pkg/Dowd/R/NormalESPlot2DHP.R pkg/Dowd/man/NormalESPlot2DHP.Rd Log: Function NormalESPlot3DHP added. Added: pkg/Dowd/R/NormalESPlot2DHP.R =================================================================== --- pkg/Dowd/R/NormalESPlot2DHP.R (rev 0) +++ pkg/Dowd/R/NormalESPlot2DHP.R 2015-07-21 21:07:39 UTC (rev 3841) @@ -0,0 +1,124 @@ +#' Plots normal ES against holding period +#' +#' Plots the ES of a portfolio against holding period assuming that P/L distribution is +#' normally distributed, for specified confidence level and holding period. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 3 +#' or 4. In case there 3 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' cl ES confidence level and must be a scalar +#' +#' hp ES holding period and must be a vector +#' +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes ES given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' NormalESPlot2DHP(returns = data, cl = .95, hp = 60:90) +#' +#' # Computes v given mean and standard deviation of return data +#' NormalESPlot2DHP(mu = .012, sigma = .03, cl = .99, hp = 40:80) +#' +#' @export +NormalESPlot2DHP <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended + if (nargs() < 3) { + stop("Too few arguments") + } + if (nargs() > 4) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 4) { + mu <- args$mu + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 3) { + mu <- mean(args$returns) + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (max(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a vector") + } + + # Check that hp is read as row vector + if (hp.row > hp.col) { + hp <- t(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 greater than 0") + } + if (min(hp) <= 0){ + stop("Holding Period must be greater than 0") + } + # VaR estimation + + cl.row <- dim(cl)[1] + cl.cl <- dim(cl)[2] + VaR <- - sigma[1,1] * sqrt(t(hp)) * qnorm(1 - cl[1,1], 0, 1) + + mu[1,1] * t(hp) %*% matrix(1, cl.row, cl.col) # VaR + + # ES etimation + es <- NormalES(mu = mu[1,1], sigma = sigma[1,1], cl = cl, hp = hp) + + # Plotting + plot(hp, es, type = "l", xlab = "Holding Period", ylab = "ES") + title("Normal ES against holding period") + cl.label <- 100*cl + xmin <-min(hp)+.25*(max(hp)-min(hp)) + text(xmin,max(es)-.1*(max(es)-min(es)), + 'Input parameters', cex=.75, font = 2) + text(xmin,max(es)-.15*(max(es)-min(es)), + paste('Daily mean L/P = ',mu[1,1]),cex=.75) + text(xmin,max(es)-.2*(max(es)-min(es)), + paste('Stdev. of daily L/P = ',sigma[1,1]),cex=.75) + text(xmin,max(es)-.25*(max(es)-min(es)), + paste('Confidence level = ',cl.label,'%'),cex=.75) +} Added: pkg/Dowd/man/NormalESPlot2DHP.Rd =================================================================== --- pkg/Dowd/man/NormalESPlot2DHP.Rd (rev 0) +++ pkg/Dowd/man/NormalESPlot2DHP.Rd 2015-07-21 21:07:39 UTC (rev 3841) @@ -0,0 +1,43 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalESPlot2DHP.R +\name{NormalESPlot2DHP} +\alias{NormalESPlot2DHP} +\title{Plots normal ES against holding period} +\usage{ +NormalESPlot2DHP(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 3 + or 4. In case there 3 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. + +returns Vector of daily geometric return data + + mu Mean of daily geometric return data + + sigma Standard deviation of daily geometric return data + + cl ES confidence level and must be a scalar + + hp ES holding period and must be a vector} +} +\description{ +Plots the ES of a portfolio against holding period assuming that P/L distribution is +normally distributed, for specified confidence level and holding period. +} +\examples{ +# Computes ES given geometric return data + data <- runif(5, min = 0, max = .2) + NormalESPlot2DHP(returns = data, cl = .95, hp = 60:90) + + # Computes v given mean and standard deviation of return data + NormalESPlot2DHP(mu = .012, sigma = .03, cl = .99, hp = 40:80) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jul 21 23:08:16 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 21 Jul 2015 23:08:16 +0200 (CEST) Subject: [Returnanalytics-commits] r3842 - in pkg/Dowd: R man Message-ID: <20150721210816.3034F186FFD@r-forge.r-project.org> Author: dacharya Date: 2015-07-21 23:08:15 +0200 (Tue, 21 Jul 2015) New Revision: 3842 Added: pkg/Dowd/R/NormalESPlot3D.R pkg/Dowd/man/NormalESPlot3D.Rd Log: Function NormalESPlot3D added. Added: pkg/Dowd/R/NormalESPlot3D.R =================================================================== --- pkg/Dowd/R/NormalESPlot3D.R (rev 0) +++ pkg/Dowd/R/NormalESPlot3D.R 2015-07-21 21:08:15 UTC (rev 3842) @@ -0,0 +1,119 @@ +#' Plots normal ES against confidence level and holding period +#' +#' Plots the ES of a portfolio against confidence level and holding period assuming that P/L is normally distributed, for specified ranges of confidence level and +#' holding period. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 3 +#' or 4. In case there 3 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' cl VaR confidence level and must be a vector +#' +#' hp VaR holding period and must be a vector +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots VaR against confidene level given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' NormalESPlot3D(returns = data, cl = seq(.85,.99,.01), hp = 60:90) +#' +#' # Computes VaR against confidence level given mean and standard deviation of return data +#' NormalESPlot3D(mu = .012, sigma = .03, cl = seq(.85,.99,.02), hp = 40:80) +#' +#' +#' @export +NormalESPlot3D <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended + if (nargs() < 3) { + stop("Too few arguments") + } + if (nargs() > 4) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 4) { + mu <- args$mu + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 3) { + mu <- mean(args$returns) + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a vector") + } + + # Check that cl is read as row vector + if (cl.row > cl.col) { + cl <- t(cl) + } + # Check that hp is read as column vector + if (hp.col > hp.row) { + hp <- t(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 greater than 0") + } + if (min(hp) <= 0){ + stop("Holding periods must be greater than 0") + } + + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + + VaR <- - sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) + mu[1,1] * hp %*% matrix(1,cl.row,cl.col) # VaR + + # ES estimation + es <-NormalES(mu = mu ,sigma = sigma, cl = cl, hp = hp) + + # Plotting + persp(x=cl, y=hp, t(VaR), xlab = "Confidence Level", + ylab = "Holding Period", zlab = "VaR", + main = "Normal ES against confidence level") +} Added: pkg/Dowd/man/NormalESPlot3D.Rd =================================================================== --- pkg/Dowd/man/NormalESPlot3D.Rd (rev 0) +++ pkg/Dowd/man/NormalESPlot3D.Rd 2015-07-21 21:08:15 UTC (rev 3842) @@ -0,0 +1,43 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalESPlot3D.R +\name{NormalESPlot3D} +\alias{NormalESPlot3D} +\title{Plots normal ES against confidence level and holding period} +\usage{ +NormalESPlot3D(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 3 + or 4. In case there 3 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. + + returns Vector of daily geometric return data + + mu Mean of daily geometric return data + + sigma Standard deviation of daily geometric return data + + cl VaR confidence level and must be a vector + + hp VaR holding period and must be a vector} +} +\description{ +Plots the ES of a portfolio against confidence level and holding period assuming that P/L is normally distributed, for specified ranges of confidence level and + holding period. +} +\examples{ +# Plots VaR against confidene level given geometric return data + data <- runif(5, min = 0, max = .2) + NormalESPlot3D(returns = data, cl = seq(.85,.99,.01), hp = 60:90) + + # Computes VaR against confidence level given mean and standard deviation of return data + NormalESPlot3D(mu = .012, sigma = .03, cl = seq(.85,.99,.02), hp = 40:80) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Wed Jul 22 23:28:43 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 22 Jul 2015 23:28:43 +0200 (CEST) Subject: [Returnanalytics-commits] r3843 - pkg/Dowd Message-ID: <20150722212843.C38E4187AA6@r-forge.r-project.org> Author: dacharya Date: 2015-07-22 23:28:43 +0200 (Wed, 22 Jul 2015) New Revision: 3843 Modified: pkg/Dowd/NAMESPACE Log: Functions NormalSpectralRiskMeasure, NormalVar, NormalVaRConfidenceInterval and NormalVaRDFPerc added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-21 21:08:15 UTC (rev 3842) +++ pkg/Dowd/NAMESPACE 2015-07-22 21:28:43 UTC (rev 3843) @@ -91,6 +91,10 @@ export(NormalESPlot2DHP) export(NormalESPlot3D) export(NormalQQPlot) +export(NormalSpectralRiskMeasure) +export(NormalVaR) +export(NormalVaRConfidenceInterval) +export(NormalVaRDFPerc) export(PCAES) export(PCAESPlot) export(PCAPrelim) From noreply at r-forge.r-project.org Wed Jul 22 23:29:44 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 22 Jul 2015 23:29:44 +0200 (CEST) Subject: [Returnanalytics-commits] r3844 - pkg/Dowd Message-ID: <20150722212944.6AA9C187B77@r-forge.r-project.org> Author: dacharya Date: 2015-07-22 23:29:44 +0200 (Wed, 22 Jul 2015) New Revision: 3844 Modified: pkg/Dowd/DESCRIPTION Log: minor change. version changed to Version. Modified: pkg/Dowd/DESCRIPTION =================================================================== --- pkg/Dowd/DESCRIPTION 2015-07-22 21:28:43 UTC (rev 3843) +++ pkg/Dowd/DESCRIPTION 2015-07-22 21:29:44 UTC (rev 3844) @@ -1,12 +1,12 @@ Package: Dowd Type: Package -Title: R-version of MMR II Toolbox Offered in Kevin Dowd's Book Measuring Market Risk +Title: R-Version of MMR II Toolbox Offered in Kevin Dowd's Book Measuring Market Risk Version: 0.1 Date: 2015-05-24 Author: Dinesh Acharya Maintainer: Dinesh Acharya Description: R-version of MMR2 Toolbox that supplements - Kevin Dowd's book Measuring Market Risk + Kevin Dowd's book Measuring Market Risk. Depends: R (>= 3.0.0), bootstrap, MASS, From noreply at r-forge.r-project.org Wed Jul 22 23:30:21 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 22 Jul 2015 23:30:21 +0200 (CEST) Subject: [Returnanalytics-commits] r3845 - in pkg/Dowd: R man Message-ID: <20150722213021.B2834187B77@r-forge.r-project.org> Author: dacharya Date: 2015-07-22 23:30:21 +0200 (Wed, 22 Jul 2015) New Revision: 3845 Added: pkg/Dowd/R/NormalVaRDFPerc.R pkg/Dowd/man/NormalVaRDFPerc.Rd Log: Function NormalVaRDFPerc added. Added: pkg/Dowd/R/NormalVaRDFPerc.R =================================================================== --- pkg/Dowd/R/NormalVaRDFPerc.R (rev 0) +++ pkg/Dowd/R/NormalVaRDFPerc.R 2015-07-22 21:30:21 UTC (rev 3845) @@ -0,0 +1,159 @@ +#' Percentiles of VaR distribution function for normally distributed P/L +#' +#' Estimates the percentile of VaR distribution function for normally distributed P/L, using the theory of order statistics. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 6. In case there 4 input arguments, the mean, standard deviation and number of observations of +#' data are computed from returns data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data + +#' sigma Standard deviation of daily geometric return data +#' +#' n Sample size +#' +#' perc Desired percentile +#' +#' cl VaR confidence level and must be a scalar +#' +#' hp VaR holding period and must be a a scalar +#' +#' @return Percentiles of VaR distribution function and is scalar +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates Percentiles of VaR distribution +#' data <- runif(5, min = 0, max = .2) +#' NormalVaRDFPerc(returns = data, perc = .7, cl = .95, hp = 60) +#' +#' # Estimates Percentiles of VaR distribution +#' NormalVaRDFPerc(mu = .012, sigma = .03, n= 10, perc = .8, cl = .99, hp = 40) +#' +#' +#' @export +NormalVaRDFPerc <- function(...){ + # Determine if there are four or six arguments, and ensure that arguments are read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() == 5) { + stop("Incorrect number of arguments") + } + if (nargs() > 6) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 6) { + mu <- args$mu + cl <- args$cl + perc <- args$sigma + n <- args$n + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + n <- max(dim(as.matrix(args$returns))) + perc <- args$perc + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + n <- as.matrix(n) + n.row <- dim(n)[1] + n.col <- dim(n)[2] + if (max(n.row, n.col) > 1) { + stop("Number of observations in a sample must be an integer") + } + if (n %% 1 != 0) { + stop("Number of observations in a sample must be an integer.") + } + perc <- as.matrix(perc) + perc.row <- dim(perc)[1] + perc.col <- dim(perc)[2] + if (max(perc.row, perc.col) > 1) { + stop("Chosen percentile of the distribution must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (max(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (n < 0) { + stop("Number of observations must be non-negative") + } + if (perc > 1){ + stop("Chosen percentile must not exceed 1") + } + if (perc <= 0){ + stop("Chosen percentile must be positive") + } + if (cl >= 1){ + stop("Confidence level(s) must be less than 1") + } + if (cl <= 0){ + stop("Confidence level must be greater than 0") + } + if (hp <= 0){ + stop("Honding period must be greater than 0") + } + + # Derive order statistic and ensure it is an integer + w <- n * cl # Derive r-th order statistic + 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 + } + } + + # VaR estimation + y <- qnorm(x, -mu * hp, sigma*sqrt(hp)) # Value of percentile; not normal VaR formula + + return(y) +} Added: pkg/Dowd/man/NormalVaRDFPerc.Rd =================================================================== --- pkg/Dowd/man/NormalVaRDFPerc.Rd (rev 0) +++ pkg/Dowd/man/NormalVaRDFPerc.Rd 2015-07-22 21:30:21 UTC (rev 3845) @@ -0,0 +1,48 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalVaRDFPerc.R +\name{NormalVaRDFPerc} +\alias{NormalVaRDFPerc} +\title{Percentiles of VaR distribution function for normally distributed P/L} +\usage{ +NormalVaRDFPerc(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and +standard deviation data. Accordingly, number of input arguments is either 4 +or 6. In case there 4 input arguments, the mean, standard deviation and number of observations of +data are computed from returns data. See examples for details. + +returns Vector of daily geometric return data + + mu Mean of daily geometric return data + sigma Standard deviation of daily geometric return data + + n Sample size + + perc Desired percentile + + cl VaR confidence level and must be a scalar + + hp VaR holding period and must be a a scalar} +} +\value{ +Percentiles of VaR distribution function and is scalar +} +\description{ +Estimates the percentile of VaR distribution function for normally distributed P/L, using the theory of order statistics. +} +\examples{ +# Estimates Percentiles of VaR distribution + data <- runif(5, min = 0, max = .2) + NormalVaRDFPerc(returns = data, perc = .7, cl = .95, hp = 60) + + # Estimates Percentiles of VaR distribution + NormalVaRDFPerc(mu = .012, sigma = .03, n= 10, perc = .8, cl = .99, hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Wed Jul 22 23:31:05 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 22 Jul 2015 23:31:05 +0200 (CEST) Subject: [Returnanalytics-commits] r3846 - in pkg/Dowd: R man Message-ID: <20150722213105.8EA8F187B77@r-forge.r-project.org> Author: dacharya Date: 2015-07-22 23:31:05 +0200 (Wed, 22 Jul 2015) New Revision: 3846 Added: pkg/Dowd/R/NormalSpectralRiskMeasure.R pkg/Dowd/man/NormalSpectralRiskMeasure.Rd Log: Function NormalSpectralRiskMeasure added. Added: pkg/Dowd/R/NormalSpectralRiskMeasure.R =================================================================== --- pkg/Dowd/R/NormalSpectralRiskMeasure.R (rev 0) +++ pkg/Dowd/R/NormalSpectralRiskMeasure.R 2015-07-22 21:31:05 UTC (rev 3846) @@ -0,0 +1,142 @@ +#' Estimates the spectral risk measure of a portfolio +#' +#' Function estimates the spectral risk measure of a portfolio +#' assuming losses are normally distributed, assuming exponential weighting +#' function with specified gamma. +#' +#' @param mu Mean losses +#' @param sigma Standard deviation of losses +#' @param gamma Gamma parameter in exponential risk aversion +#' @param number.of.slices Number of slices into which density function is divided +#' +#' @return Estimated spectral risk measure +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Generates 95% confidence intervals for normal VaR for given parameters +#' NormalSpectralRiskMeasure(0, .5, .8, 20) +#' +#' @export +NormalSpectralRiskMeasure <- function(mu, sigma, gamma, number.of.slices){ + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be n.on-negative") + } + if (min(gamma) <= 0) { + stop("Gamma must be greater than 0") + } + + n <- number.of.slices + + # Crude (weighted average quantile) evstimate of risk measure + + crude.estimate.of.risk.measure <- crude.estimate.of.spectral.risk.measure(mu, sigma, gamma, n) + crude.halving.error <- crude.estimate.of.risk.measure - crude.estimate.of.spectral.risk.measure(mu, sigma, gamma, n/2) + # Trapezoidal rule estimate of risk measure + trapezoidal.estimate <- trapezoidal.quadrature.estimate(mu, sigma, gamma, n) + trapezoidal.halving.error <- (1/3) * trapezoidal.estimate - trapezoidal.quadrature.estimate(mu, sigma, gamma, n/2) + # Simpson's rule estimate of risk measure + simpsons.estimate <- simpsons.quadrature.estimate(mu, sigma, gamma, n) + simpsons.halving.error <- (1/15) * (simpsons.estimate-simpsons.quadrature.estimate(mu, sigma, gamma, n/2)) + print(paste("Crude Estimate Of Risk Measure:", crude.estimate.of.risk.measure)) + print(paste("Crude Halving Error:", crude.halving.error)) + print(paste("Trapezoidal Estimate:",trapezoidal.estimate )) + print(paste("Trapezoidal Halving Error:", trapezoidal.halving.error)) + print(paste("Simpsons Estimate:", simpsons.estimate)) + print(paste("Simpsons Halving Error:", simpsons.halving.error)) + +} + +crude.estimate.of.spectral.risk.measure <- function(mu, sigma, gamma, n) { + # Applies crude average approach to estimate exponential spectral risk measure + # Input arguments: + # mu : mean losses + # sigma : std. losses + # gamma : gamma weight in exponential spectral risk aversion function + # n : number of slices + p <- seq(1/n, (n-1)/n, 1/n) + product <- double(n-1) + phi <- double(n-1) + VaR <- double(n-1) + for (i in 1:(n-1)) { + VaR[i] <- mu + sigma * qnorm(p[i], 0, 1) # VaRs + phi[i]=exp(-(1-p[i])/gamma)/(gamma*(1-exp(-1/gamma))); # Weights + product[i]=VaR[i]*phi[i]; # Weighed VaR + } + y <- sum(product) / (n - 1) # Crude estimate of exponential spectral risk measure + return(y) +} + + +trapezoidal.quadrature.estimate<- function(mu, sigma, gamma, n) { + # Applies trapezioidal rule to estimateintegral of f( x) numerifcally using trapezoidal rule with given n, where f(x) is the fuction in te exponentnial spectrahl risk measure. + # Input parameters: + # mu : mean losses + # sigma : standard losses + # gamma : gamma wight in exponential sepectral risk aversion function + # n : number of slics + a <- 1/n + b <- (n-1)/n # Limits of integration, bearing in mind we wish to avoid limits of 0 and 1 because inverses may not be not defined + h <- (b-a)/(n-1) + p <- double(n) + for (i in 1:n) { + p[i] <- a + (i - 1) * h + } + w <- double(n) + w[1] <- h/2 # Initial trap weights + w[n] <- h/2 # Other trap weights + for (i in 2:(n-1)) { + w[i] <- h + } + # Specify f(x) + phi <- double(n) + VaR <- double(n) + f <- double(n) + for (i in 1:n) { + VaR[i] <- mu + sigma * qnorm(p[i], 0, 1) # VaRs + phi[i] <- exp(-(1-p[i]) /gamma)/(gamma * (1-exp(-1/gamma))) # Spectral weights in risk measure + f[i] <- VaR[i] * phi[i] # f(i), weighted VaR + } + y <- t(as.matrix(w)) %*% as.matrix(f) + return(y) +} + +simpsons.quadrature.estimate <- function(mu, sigma, gamma, n) { + # Function applies Simpson's rule to estimate intaegral of f(x) numerically + # using Simpson's rule with given n, where f(x) is the function in the + # exponential spectral risk measure. + # Input arguments: + # mu : mean losses + # sigma : std losses + # gamma : gamma weight in exponential spectral risk aversion function + # n : number of slices. NB: must be even + n <- n - 1 # Convert to odd for purposes of algorithm + a <- 1/n + b <- (n - 1) / n # Limits of integration, bearing in mind we wish to avoid limits of 0 and 1 because inverses may not be not defined + h <- (b - a) / (n - 1) # Increment + p <- double(n) + for (i in 1:n) { # Domain of integration, x + p[i] <- a + (i - 1) * h + } + # Simpson's rule weights + a[1] <- h/3 + w <- double(n-1) + w[n] <- h/3 # Initial trap weights + for (i in seq(2, (n-1), 2)) { # odd trap weights + w[i] <- 4 * h / 3 + } + # Specify f(x) + VaR <- double(n) + phi <- double(n) + f <- double(n) + for (i in 1:n) { + VaR[i] <- mu + sigma *qnorm(p[i], 0, 1) # VaRs + phi[i] <- exp( - (1 - p[i]) / gamma) / (gamma * (1-exp(-1/gamma))) + # Spectral weights in risk measure + f[i] <- VaR[i] * phi[i] # f[i], weighted VaR + } + y <- t(as.matrix(w)) %*% as.matrix(f) + return(y) +} \ No newline at end of file Added: pkg/Dowd/man/NormalSpectralRiskMeasure.Rd =================================================================== --- pkg/Dowd/man/NormalSpectralRiskMeasure.Rd (rev 0) +++ pkg/Dowd/man/NormalSpectralRiskMeasure.Rd 2015-07-22 21:31:05 UTC (rev 3846) @@ -0,0 +1,36 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalSpectralRiskMeasure.R +\name{NormalSpectralRiskMeasure} +\alias{NormalSpectralRiskMeasure} +\title{Estimates the spectral risk measure of a portfolio} +\usage{ +NormalSpectralRiskMeasure(mu, sigma, gamma, number.of.slices) +} +\arguments{ +\item{mu}{Mean losses} + +\item{sigma}{Standard deviation of losses} + +\item{gamma}{Gamma parameter in exponential risk aversion} + +\item{number.of.slices}{Number of slices into which density function is divided} +} +\value{ +Estimated spectral risk measure +} +\description{ +Function estimates the spectral risk measure of a portfolio +assuming losses are normally distributed, assuming exponential weighting +function with specified gamma. +} +\examples{ +# Generates 95\% confidence intervals for normal VaR for given parameters + NormalSpectralRiskMeasure(0, .5, .8, 20) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Wed Jul 22 23:31:32 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 22 Jul 2015 23:31:32 +0200 (CEST) Subject: [Returnanalytics-commits] r3847 - in pkg/Dowd: R man Message-ID: <20150722213132.E90A8187B77@r-forge.r-project.org> Author: dacharya Date: 2015-07-22 23:31:32 +0200 (Wed, 22 Jul 2015) New Revision: 3847 Added: pkg/Dowd/R/NormalVaR.R pkg/Dowd/man/NormalVaR.Rd Log: Function NormalVaR added. Added: pkg/Dowd/R/NormalVaR.R =================================================================== --- pkg/Dowd/R/NormalVaR.R (rev 0) +++ pkg/Dowd/R/NormalVaR.R 2015-07-22 21:31:32 UTC (rev 3847) @@ -0,0 +1,118 @@ +#' VaR for normally distributed P/L +#' +#' Estimates the VaR of a portfolio assuming that P/L is +#' normally distributed, for specified confidence level and holding period. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data along with the remaining arguments. Accordingly, number of input arguments is either 3 +#' or 4. In case there 3 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' cl VaR confidence level +#' +#' hp VaR holding period in days +#' +#' @return Matrix of VaR whose dimension depends on dimension of hp and cl. If +#' cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is +#' a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, +#' the matrix is column matrix and if both cl and hp are vectors, the matrix +#' has dimension length of cl * length of hp. +#' +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes VaR given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' NormalVaR(returns = data, cl = .95, hp = 90) +#' +#' # Computes VaR given mean and standard deviation of return data +#' NormalVaR(mu = .012, sigma = .03, cl = .95, hp = 90) +#' +#' +#' @export +NormalVaR <- function(...){ + # Determine if there are three or four arguments and ensure that arguments are + # read as intended + if (nargs() < 3) { + stop("Too few arguments") + } + if (nargs() > 4) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 4) { + mu <- args$mu + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 3) { + mu <- mean(args$returns) + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar or a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar or a vector") + } + + # Check that cl and hp are read as row and column vectors respectively + if (cl.row > cl.col) { + cl <- t(cl) + } + if (hp.row > hp.col) { + hp <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Holding Period(s) must be greater than 0") + } + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- - sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) - mu[1,1] * hp %*% matrix(1,cl.row,cl.col) # VaR + + return (VaR) +} \ No newline at end of file Added: pkg/Dowd/man/NormalVaR.Rd =================================================================== --- pkg/Dowd/man/NormalVaR.Rd (rev 0) +++ pkg/Dowd/man/NormalVaR.Rd 2015-07-22 21:31:32 UTC (rev 3847) @@ -0,0 +1,50 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalVaR.R +\name{NormalVaR} +\alias{NormalVaR} +\title{VaR for normally distributed P/L} +\usage{ +NormalVaR(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and + standard deviation data along with the remaining arguments. Accordingly, number of input arguments is either 3 + or 4. In case there 3 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. + + returns Vector of daily geometric return data + + mu Mean of daily geometric return data + + sigma Standard deviation of daily geometric return data + + cl VaR confidence level + + hp VaR holding period in days} +} +\value{ +Matrix of VaR whose dimension depends on dimension of hp and cl. If +cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is + a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, + the matrix is column matrix and if both cl and hp are vectors, the matrix + has dimension length of cl * length of hp. +} +\description{ +Estimates the VaR of a portfolio assuming that P/L is +normally distributed, for specified confidence level and holding period. +} +\examples{ +# Computes VaR given geometric return data + data <- runif(5, min = 0, max = .2) + NormalVaR(returns = data, cl = .95, hp = 90) + + # Computes VaR given mean and standard deviation of return data + NormalVaR(mu = .012, sigma = .03, cl = .95, hp = 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Wed Jul 22 23:32:02 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 22 Jul 2015 23:32:02 +0200 (CEST) Subject: [Returnanalytics-commits] r3848 - in pkg/Dowd: R man Message-ID: <20150722213202.B201D187B77@r-forge.r-project.org> Author: dacharya Date: 2015-07-22 23:32:02 +0200 (Wed, 22 Jul 2015) New Revision: 3848 Added: pkg/Dowd/R/NormalVaRConfidenceInterval.R pkg/Dowd/man/NormalVaRConfidenceInterval.Rd Log: Function NormalVaRConfidenceInterval added. Added: pkg/Dowd/R/NormalVaRConfidenceInterval.R =================================================================== --- pkg/Dowd/R/NormalVaRConfidenceInterval.R (rev 0) +++ pkg/Dowd/R/NormalVaRConfidenceInterval.R 2015-07-22 21:32:02 UTC (rev 3848) @@ -0,0 +1,35 @@ +#' Generates Monte Carlo 95\% Confidence Intervals for normal VaR +#' +#' Generates 95\% confidence intervals for normal VaR using Monte Carlo simulation +#' +#' @param mu Mean of the P/L process +#' @param sigma Standard deviation of the P/L process +#' @param number.trials Number of trials used in the simulations +#' @param sample.size Sample drawn in each trial +#' @param cl Confidence Level +#' @param hp Holding Period +#' +#' @return 95\% confidence intervals for normal VaR +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Generates 95\% confidence intervals for normal VaR for given parameters +#' NormalVaRConfidenceInterval(0, .5, 20, 15, .95, 90) +#' +#' +#' @export +NormalVaRConfidenceInterval <- function(mu, sigma, number.trials, sample.size, cl, hp){ + VaR <- double(number.trials) + for (k in 1:number.trials) { + z <- rnorm(sample.size) + x <- sigma * z + mu + VaR[k] <- NormalVaR(returns = x, cl = cl, hp = hp) + } + VaR <- sort(VaR) + lower.order.stat <- floor(0.025 * number.trials) + upper.order.stat <- ceiling(0.975 * number.trials) + y <- c(VaR[lower.order.stat], VaR[upper.order.stat]) + return(y) +} Added: pkg/Dowd/man/NormalVaRConfidenceInterval.Rd =================================================================== --- pkg/Dowd/man/NormalVaRConfidenceInterval.Rd (rev 0) +++ pkg/Dowd/man/NormalVaRConfidenceInterval.Rd 2015-07-22 21:32:02 UTC (rev 3848) @@ -0,0 +1,38 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalVaRConfidenceInterval.R +\name{NormalVaRConfidenceInterval} +\alias{NormalVaRConfidenceInterval} +\title{Generates Monte Carlo 95\% Confidence Intervals for normal VaR} +\usage{ +NormalVaRConfidenceInterval(mu, sigma, number.trials, sample.size, cl, hp) +} +\arguments{ +\item{mu}{Mean of the P/L process} + +\item{sigma}{Standard deviation of the P/L process} + +\item{number.trials}{Number of trials used in the simulations} + +\item{sample.size}{Sample drawn in each trial} + +\item{cl}{Confidence Level} + +\item{hp}{Holding Period} +} +\value{ +95\% confidence intervals for normal VaR +} +\description{ +Generates 95\% confidence intervals for normal VaR using Monte Carlo simulation +} +\examples{ +# Generates 95\\\% confidence intervals for normal VaR for given parameters + NormalVaRConfidenceInterval(0, .5, 20, 15, .95, 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Fri Jul 24 08:38:57 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 24 Jul 2015 08:38:57 +0200 (CEST) Subject: [Returnanalytics-commits] r3849 - in pkg/FactorAnalytics: . R man Message-ID: <20150724063858.01553183C47@r-forge.r-project.org> Author: pragnya Date: 2015-07-24 08:38:57 +0200 (Fri, 24 Jul 2015) New Revision: 3849 Modified: pkg/FactorAnalytics/DESCRIPTION pkg/FactorAnalytics/NAMESPACE pkg/FactorAnalytics/R/CornishFisher.R pkg/FactorAnalytics/R/fitTsfm.R pkg/FactorAnalytics/R/zzz.R pkg/FactorAnalytics/man/CornishFisher.Rd pkg/FactorAnalytics/man/fitTsfm.Rd Log: Add semi-parametric factor model Monte Carlo Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2015-07-22 21:32:02 UTC (rev 3848) +++ pkg/FactorAnalytics/DESCRIPTION 2015-07-24 06:38:57 UTC (rev 3849) @@ -1,8 +1,8 @@ Package: factorAnalytics Type: Package Title: Factor Analytics -Version:2.0.21 -Date:2015-05-28 +Version:2.0.22 +Date:2015-07-23 Author: Eric Zivot, Sangeetha Srinivasan and Yi-An Chen Maintainer: Sangeetha Srinivasan Description: An R package for the estimation and risk analysis of linear factor @@ -36,7 +36,8 @@ parallel, doSNOW, RCurl, - bestglm + bestglm, + tseries Suggests: testthat LazyLoad: yes Modified: pkg/FactorAnalytics/NAMESPACE =================================================================== --- pkg/FactorAnalytics/NAMESPACE 2015-07-22 21:32:02 UTC (rev 3848) +++ pkg/FactorAnalytics/NAMESPACE 2015-07-24 06:38:57 UTC (rev 3849) @@ -83,5 +83,7 @@ importFrom(sandwich,vcovHAC.default) importFrom(sandwich,vcovHC.default) importFrom(sn,dst) +importFrom(sn,rst) importFrom(sn,st.mple) importFrom(strucchange,efp) +importFrom(tseries,tsbootstrap) Modified: pkg/FactorAnalytics/R/CornishFisher.R =================================================================== --- pkg/FactorAnalytics/R/CornishFisher.R 2015-07-22 21:32:02 UTC (rev 3848) +++ pkg/FactorAnalytics/R/CornishFisher.R 2015-07-24 06:38:57 UTC (rev 3849) @@ -22,6 +22,9 @@ #' @param sigma scalar standard deviation. #' @param skew scalar; skewness. #' @param ekurt scalar; excess kurtosis. +#' @param dp a vector of length 3, whose elements represent sigma, skew and +#' ekurt, respectively. If dp is specified, the individual parameters cannot be +#' set. Default is \code{NULL}. #' @param seed scalar; set seed. Default is \code{NULL}. #' @param x,q vector of standardized quantiles. #' @param p vector of probabilities. @@ -95,16 +98,26 @@ #' @rdname CornishFisher #' @export -rCornishFisher <- function(n, sigma, skew, ekurt, seed=NULL) { +rCornishFisher <- function(n, sigma, skew, ekurt, dp=NULL, seed=NULL) { ## inputs: ## n scalar, number of simulated values ## sigma scalar, standard deviation ## skew scalar, skewness ## ekurt scalar, excess kurtosis + ## dp vector of values for sigma, skew and ekurt respectively ## outputs: ## n simulated values from Cornish-Fisher distribution + if (!is.null(dp)) { + if (!missing(sigma)) { + stop("Invalid argument: Cannot set both component parameters and dp") + } + sigma <- dp[1] + skew <- dp[2] + ekurt <- dp[3] + } + if (!is.null(seed)) set.seed(seed) zc <- rnorm(n) z.cf <- zc + Modified: pkg/FactorAnalytics/R/fitTsfm.R =================================================================== --- pkg/FactorAnalytics/R/fitTsfm.R 2015-07-22 21:32:02 UTC (rev 3848) +++ pkg/FactorAnalytics/R/fitTsfm.R 2015-07-24 06:38:57 UTC (rev 3849) @@ -54,10 +54,10 @@ #' @param asset.names vector containing names of assets, whose returns or #' excess returns are the dependent variable. #' @param factor.names vector containing names of the macroeconomic factors. -#' @param mkt.name name of the column for market returns. Default is NULL. +#' @param mkt.name name of the column for market returns. Default is \code{NULL}. #' @param rf.name name of the column of risk free rate variable to calculate #' excess returns for all assets (in \code{asset.names}) and factors (in -#' \code{factor.names}). Default is NULL, and no action is taken. +#' \code{factor.names}). Default is \code{NULL}, and no action is taken. #' @param data vector, matrix, data.frame, xts, timeSeries or zoo object #' containing column(s) named in \code{asset.names}, \code{factor.names} and #' optionally, \code{mkt.name} and \code{rf.name}. @@ -125,17 +125,17 @@ #' \code{\link{paFm}} for Performance Attribution. #' #' @examples -#' # load data from the database #' data(managers) #' fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), #' factor.names=colnames(managers[,(7:9)]), data=managers) #' summary(fit) #' fitted(fit) +#' #' # plot actual returns vs. fitted factor model returns for HAM1 #' plot(fit, plot.single=TRUE, asset.name="HAM1", which=1) -#' # group plot; type selected from menu prompt; auto-looped for multiple plots -#' # plot(fit) #' +#' # plot(fit) # this presents a menu for group plots +#' # select desired plot from the menu (auto-looped for multiple plots) #' #' # example using "subsets" variable selection #' fit.sub <- fitTsfm(asset.names=colnames(managers[,(1:6)]), Modified: pkg/FactorAnalytics/R/zzz.R =================================================================== --- pkg/FactorAnalytics/R/zzz.R 2015-07-22 21:32:02 UTC (rev 3848) +++ pkg/FactorAnalytics/R/zzz.R 2015-07-24 06:38:57 UTC (rev 3849) @@ -9,13 +9,14 @@ #' @importFrom lmtest coeftest.default #' @importFrom sandwich vcovHC.default vcovHAC.default #' @importFrom MASS ginv +#' @importFrom tseries tsbootstrap #' @importFrom PerformanceAnalytics chart.TimeSeries chart.ACFplus #' chart.Histogram chart.QQPlot chart.Correlation #' @importFrom lattice barchart xyplot panel.barchart panel.grid #' @importFrom corrplot corrplot.mixed #' @importFrom strucchange efp -#' @importFrom sn dst st.mple +#' @importFrom sn dst rst st.mple #' @importFrom parallel makeCluster detectCores clusterEvalQ clusterExport #' stopCluster Modified: pkg/FactorAnalytics/man/CornishFisher.Rd =================================================================== --- pkg/FactorAnalytics/man/CornishFisher.Rd 2015-07-22 21:32:02 UTC (rev 3848) +++ pkg/FactorAnalytics/man/CornishFisher.Rd 2015-07-24 06:38:57 UTC (rev 3849) @@ -14,7 +14,7 @@ qCornishFisher(p, n, skew, ekurt) -rCornishFisher(n, sigma, skew, ekurt, seed = NULL) +rCornishFisher(n, sigma, skew, ekurt, dp = NULL, seed = NULL) } \arguments{ \item{x,q}{vector of standardized quantiles.} @@ -30,6 +30,10 @@ \item{sigma}{scalar standard deviation.} +\item{dp}{a vector of length 3, whose elements represent sigma, skew and +ekurt, respectively. If dp is specified, the individual parameters cannot be +set. Default is \code{NULL}.} + \item{seed}{scalar; set seed. Default is \code{NULL}.} } \value{ Modified: pkg/FactorAnalytics/man/fitTsfm.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfm.Rd 2015-07-22 21:32:02 UTC (rev 3848) +++ pkg/FactorAnalytics/man/fitTsfm.Rd 2015-07-24 06:38:57 UTC (rev 3849) @@ -24,11 +24,11 @@ \item{factor.names}{vector containing names of the macroeconomic factors.} -\item{mkt.name}{name of the column for market returns. Default is NULL.} +\item{mkt.name}{name of the column for market returns. Default is \code{NULL}.} \item{rf.name}{name of the column of risk free rate variable to calculate excess returns for all assets (in \code{asset.names}) and factors (in -\code{factor.names}). Default is NULL, and no action is taken.} +\code{factor.names}). Default is \code{NULL}, and no action is taken.} \item{data}{vector, matrix, data.frame, xts, timeSeries or zoo object containing column(s) named in \code{asset.names}, \code{factor.names} and @@ -133,17 +133,17 @@ } } \examples{ -# load data from the database data(managers) fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), factor.names=colnames(managers[,(7:9)]), data=managers) summary(fit) fitted(fit) + # plot actual returns vs. fitted factor model returns for HAM1 plot(fit, plot.single=TRUE, asset.name="HAM1", which=1) -# group plot; type selected from menu prompt; auto-looped for multiple plots -# plot(fit) +# plot(fit) # this presents a menu for group plots +# select desired plot from the menu (auto-looped for multiple plots) # example using "subsets" variable selection fit.sub <- fitTsfm(asset.names=colnames(managers[,(1:6)]), From noreply at r-forge.r-project.org Fri Jul 24 21:01:13 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 24 Jul 2015 21:01:13 +0200 (CEST) Subject: [Returnanalytics-commits] r3850 - in pkg/Dowd: R man Message-ID: <20150724190113.34D3918796C@r-forge.r-project.org> Author: dacharya Date: 2015-07-24 21:01:12 +0200 (Fri, 24 Jul 2015) New Revision: 3850 Modified: pkg/Dowd/R/KernelESBoxKernel.R pkg/Dowd/R/KernelESEpanechinikovKernel.R pkg/Dowd/R/KernelESNormalKernel.R pkg/Dowd/R/KernelESTriangleKernel.R pkg/Dowd/R/KernelVaRBoxKernel.R pkg/Dowd/R/KernelVaREpanechinikovKernel.R pkg/Dowd/R/KernelVaRNormalKernel.R pkg/Dowd/R/KernelVaRTriangleKernel.R pkg/Dowd/man/GaussianCopulaVaR.Rd pkg/Dowd/man/KernelESEpanechinikovKernel.Rd pkg/Dowd/man/KernelVaRBoxKernel.Rd pkg/Dowd/man/KernelVaREpanechinikovKernel.Rd pkg/Dowd/man/KernelVaRNormalKernel.Rd pkg/Dowd/man/KernelVaRTriangleKernel.Rd Log: An additional conditional variable was introduced to avoid multiple plot while using KernelES* function. Modified: pkg/Dowd/R/KernelESBoxKernel.R =================================================================== --- pkg/Dowd/R/KernelESBoxKernel.R 2015-07-24 06:38:57 UTC (rev 3849) +++ pkg/Dowd/R/KernelESBoxKernel.R 2015-07-24 19:01:12 UTC (rev 3850) @@ -21,8 +21,13 @@ delta.cl <- (1 - cl) / n VaR <- double(999) for (i in 1:(n - 1)) { - VaR[i] <- KernelVaRBoxKernel(PandL, cl + i * delta.cl) + if(i<(n-1)){ + VaR[i] <- KernelVaRBoxKernel(PandL, cl + i * delta.cl, FALSE) + } else if (i == n-1) { + VaR[i] <- KernelVaRBoxKernel(PandL, cl + i * delta.cl, TRUE) + } } + ES <- mean(VaR) return(ES) Modified: pkg/Dowd/R/KernelESEpanechinikovKernel.R =================================================================== --- pkg/Dowd/R/KernelESEpanechinikovKernel.R 2015-07-24 06:38:57 UTC (rev 3849) +++ pkg/Dowd/R/KernelESEpanechinikovKernel.R 2015-07-24 19:01:12 UTC (rev 3850) @@ -4,6 +4,7 @@ #' #' @param Ra Profit and Loss data set #' @param cl ES confidence level +#' @param plot Bool, plots cdf if true #' @return Scalar ES #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' @@ -15,13 +16,17 @@ #' KernelESEpanechinikovKernel(Ra, .95) #' #' @export -KernelESEpanechinikovKernel <- function(Ra, cl){ +KernelESEpanechinikovKernel <- function(Ra, cl, plot = TRUE){ PandL <- as.vector(Ra) - n <- 1000 + n <- 200 delta.cl <- (1 - cl) / n - VaR <- double(999) + VaR <- double(199) for (i in 1:(n - 1)) { - VaR[i] <- KernelVaREpanechinikovKernel(PandL, cl + i * delta.cl) + if(i<(n-1)){ + VaR[i] <- KernelVaREpanechinikovKernel(PandL, cl + i * delta.cl, FALSE) + } else if (i == n-1) { + VaR[i] <- KernelVaREpanechinikovKernel(PandL, cl + i * delta.cl, TRUE) + } } ES <- mean(VaR) return(ES) Modified: pkg/Dowd/R/KernelESNormalKernel.R =================================================================== --- pkg/Dowd/R/KernelESNormalKernel.R 2015-07-24 06:38:57 UTC (rev 3849) +++ pkg/Dowd/R/KernelESNormalKernel.R 2015-07-24 19:01:12 UTC (rev 3850) @@ -21,7 +21,11 @@ delta.cl <- (1 - cl) / n VaR <- double(999) for (i in 1:(n - 1)) { - VaR[i] <- KernelVaRNormalKernel(PandL, cl + i * delta.cl) + if(i<(n-1)){ + VaR[i] <- KernelVaRNormalKernel(PandL, cl + i * delta.cl, FALSE) + } else if (i == n-1) { + VaR[i] <- KernelVaRNormalKernel(PandL, cl + i * delta.cl, TRUE) + } } ES <- mean(VaR) return(ES) Modified: pkg/Dowd/R/KernelESTriangleKernel.R =================================================================== --- pkg/Dowd/R/KernelESTriangleKernel.R 2015-07-24 06:38:57 UTC (rev 3849) +++ pkg/Dowd/R/KernelESTriangleKernel.R 2015-07-24 19:01:12 UTC (rev 3850) @@ -21,7 +21,11 @@ delta.cl <- (1 - cl) / n VaR <- double(999) for (i in 1:(n - 1)) { - VaR[i] <- KernelVaRTriangleKernel(PandL, cl + i * delta.cl) + if(i<(n-1)){ + VaR[i] <- KernelVaRTriangleKernel(PandL, cl + i * delta.cl, FALSE) + } else if (i == n-1) { + VaR[i] <- KernelVaRTriangleKernel(PandL, cl + i * delta.cl, TRUE) + } } ES <- mean(VaR) return(ES) Modified: pkg/Dowd/R/KernelVaRBoxKernel.R =================================================================== --- pkg/Dowd/R/KernelVaRBoxKernel.R 2015-07-24 06:38:57 UTC (rev 3849) +++ pkg/Dowd/R/KernelVaRBoxKernel.R 2015-07-24 19:01:12 UTC (rev 3850) @@ -4,6 +4,7 @@ #' #' @param Ra Profit and Loss data set #' @param cl VaR confidence level +#' @param plot Bool which indicates whether the graph is plotted or not #' @return Scalar VaR #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' @@ -15,7 +16,7 @@ #' KernelVaRBoxKernel(Ra, .95) #' #' @export -KernelVaRBoxKernel <- function(Ra, cl) { +KernelVaRBoxKernel <- function(Ra, cl, plot=TRUE) { PandL <- as.vector(Ra) mu <- mean(PandL) sigma <- sd(PandL) @@ -33,8 +34,9 @@ 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") - + if (plot == TRUE) { + 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-07-24 21:44:44 +0200 (Fri, 24 Jul 2015) New Revision: 3851 Modified: pkg/Dowd/R/KernelESEpanechinikovKernel.R Log: value of n corrected to 1000. Modified: pkg/Dowd/R/KernelESEpanechinikovKernel.R =================================================================== --- pkg/Dowd/R/KernelESEpanechinikovKernel.R 2015-07-24 19:01:12 UTC (rev 3850) +++ pkg/Dowd/R/KernelESEpanechinikovKernel.R 2015-07-24 19:44:44 UTC (rev 3851) @@ -18,9 +18,9 @@ #' @export KernelESEpanechinikovKernel <- function(Ra, cl, plot = TRUE){ PandL <- as.vector(Ra) - n <- 200 + n <- 1000 delta.cl <- (1 - cl) / n - VaR <- double(199) + VaR <- double(999) for (i in 1:(n - 1)) { if(i<(n-1)){ VaR[i] <- KernelVaREpanechinikovKernel(PandL, cl + i * delta.cl, FALSE) From noreply at r-forge.r-project.org Fri Jul 24 21:46:12 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 24 Jul 2015 21:46:12 +0200 (CEST) Subject: [Returnanalytics-commits] r3852 - pkg/Dowd Message-ID: <20150724194612.749E01878FC@r-forge.r-project.org> Author: dacharya Date: 2015-07-24 21:46:12 +0200 (Fri, 24 Jul 2015) New Revision: 3852 Modified: pkg/Dowd/NAMESPACE Log: Functions NormalVaRFigure, NormalVaRPlot3D and NormalVaRPlot2DCL added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-24 19:44:44 UTC (rev 3851) +++ pkg/Dowd/NAMESPACE 2015-07-24 19:46:12 UTC (rev 3852) @@ -95,6 +95,9 @@ export(NormalVaR) export(NormalVaRConfidenceInterval) export(NormalVaRDFPerc) +export(NormalVaRFigure) +export(NormalVaRPlot2DCL) +export(NormalVaRPlot3D) export(PCAES) export(PCAESPlot) export(PCAPrelim) From noreply at r-forge.r-project.org Fri Jul 24 21:47:57 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 24 Jul 2015 21:47:57 +0200 (CEST) Subject: [Returnanalytics-commits] r3853 - in pkg/Dowd: R man Message-ID: <20150724194757.1A06518796C@r-forge.r-project.org> Author: dacharya Date: 2015-07-24 21:47:56 +0200 (Fri, 24 Jul 2015) New Revision: 3853 Added: pkg/Dowd/R/NormalVaRFigure.R pkg/Dowd/man/NormalVaRFigure.Rd Log: Function NormalVaRFigure added. Added: pkg/Dowd/R/NormalVaRFigure.R =================================================================== --- pkg/Dowd/R/NormalVaRFigure.R (rev 0) +++ pkg/Dowd/R/NormalVaRFigure.R 2015-07-24 19:47:56 UTC (rev 3853) @@ -0,0 +1,133 @@ +#' Figure of normal VaR and pdf against L/P +#' +#' Gives figure showing the VaR and probability distribution function against L/P of a portfolio assuming P/L are normally distributed, for specified confidence level and holding period. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 3 +#' or 4. In case there 3 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' cl VaR confidence level and should be scalar +#' +#' hp VaR holding period in days and should be scalar +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots normal VaR and pdf against L/P data for given returns data +#' data <- runif(5, min = 0, max = .2) +#' NormalVaRFigure(returns = data, cl = .95, hp = 90) +#' +#' # Plots normal VaR and pdf against L/P data with given parameters +#' NormalVaRFigure(mu = .012, sigma = .03, cl = .95, hp = 90) +#' +#' +#' @export +NormalVaRFigure <- function(...){ + # Determine if there are three or four arguments and ensure that arguments are + # read as intended + if (nargs() < 3) { + stop("Too few arguments") + } + if (nargs() > 4) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 4) { + mu <- args$mu + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 3) { + mu <- mean(args$returns) + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar or a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar or a vector") + } + + # Check that cl and hp are read as row and column vectors respectively + if (cl.row > cl.col) { + cl <- t(cl) + } + if (hp.row > hp.col) { + hp <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Holding Period(s) must be greater than 0") + } + + # Message to indicate how matrix of results is to be interpreted, if cl and hp both vary and results are given in matrix form + if (max(cl.row, cl.col) > 1 & max(hp.row, hp.col) > 1) { + print('VaR results with confidence level varying across row and holding period down column') + } + + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- - sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) - mu[1,1] * hp %*% matrix(1,cl.row,cl.col) # VaR + + # Plotting + x.min <- -mu - 5 * sigma + x.max <- -mu + 5 * sigma + delta <- (x.max-x.min) / 100 + x <- seq(x.min, x.max, delta) + p <- dlnorm(x, - mu, sigma) + plot(x, p, type = "l", xlim = c(x.min, x.max), ylim = c(0, max(p)*1.1), xlab = "Loss (+) / Profit (-)", ylab = "Probability", main = "Normal VaR") + u <- c(VaR, VaR) + v <- c(0, .6*max(p)) + lines(0,0,2,.6,type="l") + lines(u, v, type = "l", col = "blue") + cl.for.label <- 100*cl + text(1,.95*max(p), pos = 1, 'Input parameters', cex=.75, font = 2) + text(1, .875*max(p),pos = 1, paste('Daily mean L/P = ', round(mu,2)), cex=.75) + text(1, .8*max(p),pos = 1, paste('St. dev. of daily L/P = ',round(sigma,2)), cex=.75) + text(1, .725*max(p),pos = 1, paste('Holding period = ', hp,' day(s)'), cex=.75) + text(VaR, .7*max(p),pos = 2, paste('VaR at ', cl.for.label,'% CL'), cex=.75) + text(VaR, .64 * max(p),pos = 2, paste('= ',VaR), cex=.75) +} Added: pkg/Dowd/man/NormalVaRFigure.Rd =================================================================== --- pkg/Dowd/man/NormalVaRFigure.Rd (rev 0) +++ pkg/Dowd/man/NormalVaRFigure.Rd 2015-07-24 19:47:56 UTC (rev 3853) @@ -0,0 +1,42 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalVaRFigure.R +\name{NormalVaRFigure} +\alias{NormalVaRFigure} +\title{Figure of normal VaR and pdf against L/P} +\usage{ +NormalVaRFigure(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 3 + or 4. In case there 3 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. + + returns Vector of daily geometric return data + + mu Mean of daily geometric return data + + sigma Standard deviation of daily geometric return data + + cl VaR confidence level and should be scalar + + hp VaR holding period in days and should be scalar} +} +\description{ +Gives figure showing the VaR and probability distribution function against L/P of a portfolio assuming P/L are normally distributed, for specified confidence level and holding period. +} +\examples{ +# Plots normal VaR and pdf against L/P data for given returns data + data <- runif(5, min = 0, max = .2) + NormalVaRFigure(returns = data, cl = .95, hp = 90) + + # Plots normal VaR and pdf against L/P data with given parameters + NormalVaRFigure(mu = .012, sigma = .03, cl = .95, hp = 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Fri Jul 24 21:48:24 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 24 Jul 2015 21:48:24 +0200 (CEST) Subject: [Returnanalytics-commits] r3854 - in pkg/Dowd: R man Message-ID: <20150724194824.3320518796C@r-forge.r-project.org> Author: dacharya Date: 2015-07-24 21:48:23 +0200 (Fri, 24 Jul 2015) New Revision: 3854 Added: pkg/Dowd/R/NormalVaRPlot2DCL.R pkg/Dowd/man/NormalVaRPlot2DCL.Rd Log: Function NormalVaRPlot2DCL added. Added: pkg/Dowd/R/NormalVaRPlot2DCL.R =================================================================== --- pkg/Dowd/R/NormalVaRPlot2DCL.R (rev 0) +++ pkg/Dowd/R/NormalVaRPlot2DCL.R 2015-07-24 19:48:23 UTC (rev 3854) @@ -0,0 +1,117 @@ +#' Plots normal VaR against confidence level +#' +#' Plots the VaR of a portfolio against confidence level assuming that P/L are normally distributed, for specified confidence level and +#' holding period. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 3 +#' or 4. In case there are 3 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' cl VaR confidence level and must be a vector +#' +#' hp VaR holding period and must be a scalar +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots VaR against confidene level given P/L data +#' data <- runif(5, min = 0, max = .2) +#' NormalVaRPlot2DCL(returns = data, cl = seq(.85,.99,.01), hp = 60) +#' +#' # Computes VaR against confidence level given mean and standard deviation of return data +#' NormalVaRPlot2DCL(mu = .012, sigma = .03, cl = seq(.85,.99,.01), hp = 40) +#' +#' +#' @export +NormalVaRPlot2DCL <- function(...){ + # Determine if there are four or five arguments, and ensure that arguments are read as intended + if (nargs() < 3) { + stop("Too few arguments") + } + if (nargs() > 4) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 4) { + mu <- args$mu + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 3) { + mu <- mean(args$returns) + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that cl is read as row vector + if (cl.row > cl.col) { + cl <- t(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 level(s) must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level(s) must be greater than 0") + } + if (min(hp) <= 0){ + stop("Holding period must be greater than 0") + } + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- - sigma[1,1] * sqrt(hp[1,1]) * qnorm(1 - cl, 0, 1) - mu[1,1]*hp[1,1]*matrix(1,cl.row,cl.col) # VaR + # Plotting + plot(cl, VaR, type = "l", xlab = "Confidence Level", ylab = "VaR") + title("Normal VaR against confidence level") + xmin <-min(cl)+.3*(max(cl)-min(cl)) + text(xmin,max(VaR)-.1*(max(VaR)-min(VaR)), + 'Input parameters', cex=.75, font = 2) + text(xmin,max(VaR)-.15*(max(VaR)-min(VaR)), + paste('Daily mean L/P = ',round(mu[1,1],3)),cex=.75) + text(xmin,max(VaR)-.2*(max(VaR)-min(VaR)), + paste('Stdev. of daily L/P = ',round(sigma[1,1],3)),cex=.75) + text(xmin,max(VaR)-.25*(max(VaR)-min(VaR)), + paste('Holding period = ',hp,'days'),cex=.75) +} Added: pkg/Dowd/man/NormalVaRPlot2DCL.Rd =================================================================== --- pkg/Dowd/man/NormalVaRPlot2DCL.Rd (rev 0) +++ pkg/Dowd/man/NormalVaRPlot2DCL.Rd 2015-07-24 19:48:23 UTC (rev 3854) @@ -0,0 +1,43 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalVaRPlot2DCL.R +\name{NormalVaRPlot2DCL} +\alias{NormalVaRPlot2DCL} +\title{Plots normal VaR against confidence level} +\usage{ +NormalVaRPlot2DCL(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 3 + or 4. In case there are 3 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. + +returns Vector of daily geometric return data + + mu Mean of daily geometric return data + + sigma Standard deviation of daily geometric return data + + cl VaR confidence level and must be a vector + + hp VaR holding period and must be a scalar} +} +\description{ +Plots the VaR of a portfolio against confidence level assuming that P/L are normally distributed, for specified confidence level and + holding period. +} +\examples{ +# Plots VaR against confidene level given P/L data + data <- runif(5, min = 0, max = .2) + NormalVaRPlot2DCL(returns = data, cl = seq(.85,.99,.01), hp = 60) + + # Computes VaR against confidence level given mean and standard deviation of return data + NormalVaRPlot2DCL(mu = .012, sigma = .03, cl = seq(.85,.99,.01), hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Fri Jul 24 21:48:47 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 24 Jul 2015 21:48:47 +0200 (CEST) Subject: [Returnanalytics-commits] r3855 - in pkg/Dowd: R man Message-ID: <20150724194848.0049D18796C@r-forge.r-project.org> Author: dacharya Date: 2015-07-24 21:48:47 +0200 (Fri, 24 Jul 2015) New Revision: 3855 Added: pkg/Dowd/R/NormalVaRPlot3D.R pkg/Dowd/man/NormalVaRPlot3D.Rd Log: Function NormalVaRPlot3D added. Added: pkg/Dowd/R/NormalVaRPlot3D.R =================================================================== --- pkg/Dowd/R/NormalVaRPlot3D.R (rev 0) +++ pkg/Dowd/R/NormalVaRPlot3D.R 2015-07-24 19:48:47 UTC (rev 3855) @@ -0,0 +1,115 @@ +#' Plots normal VaR in 3D against confidence level and holding period +#' +#' Plots the VaR of a portfolio against confidence level and holding period assuming that P/L are normally distributed, for specified confidence level and +#' holding period. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 3 +#' or 4. In case there 3 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' cl VaR confidence level and must be a vector +#' +#' hp VaR holding period and must be a vector +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots VaR against confidene level given geometric return data +#' data <- runif(5, min = 0, max = .2) +#' NormalVaRPlot3D(returns = data, cl = seq(.85,.99,.01), hp = 60:90) +#' +#' # Computes VaR against confidence level given mean and standard deviation of return data +#' NormalVaRPlot3D(mu = .012, sigma = .03, cl = seq(.85,.99,.02), hp = 40:80) +#' +#' +#' @export +NormalVaRPlot3D <- function(...){ + # Determine if there are three or four arguments, and ensure that arguments are read as intended + if (nargs() < 3) { + stop("Too few arguments") + } + if (nargs() > 4) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 4) { + mu <- args$mu + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 3) { + mu <- mean(args$returns) + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a vector") + } + + # Check that cl is read as row vector + if (cl.row > cl.col) { + cl <- t(cl) + } + # Check that hp is read as column vector + if (hp.col > hp.row) { + hp <- t(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 greater than 0") + } + if (min(hp) <= 0){ + stop("Holding periods must be greater than 0") + } + + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- - sigma[1,1] * sqrt(hp) %*% qnorm(1 - cl, 0, 1) - mu[1,1] * hp %*% matrix(1,cl.row,cl.col) # VaR + # Plotting + persp(x=cl, y=hp, t(VaR), xlab = "Confidence Level", + ylab = "Holding Period", zlab = "VaR", + main = "Normal VaR against confidence level and holding period") + +} Added: pkg/Dowd/man/NormalVaRPlot3D.Rd =================================================================== --- pkg/Dowd/man/NormalVaRPlot3D.Rd (rev 0) +++ pkg/Dowd/man/NormalVaRPlot3D.Rd 2015-07-24 19:48:47 UTC (rev 3855) @@ -0,0 +1,43 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalVaRPlot3D.R +\name{NormalVaRPlot3D} +\alias{NormalVaRPlot3D} +\title{Plots normal VaR in 3D against confidence level and holding period} +\usage{ +NormalVaRPlot3D(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 3 + or 4. In case there 3 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. + +returns Vector of daily geometric return data + + mu Mean of daily geometric return data + + sigma Standard deviation of daily geometric return data + + cl VaR confidence level and must be a vector + + hp VaR holding period and must be a vector} +} +\description{ +Plots the VaR of a portfolio against confidence level and holding period assuming that P/L are normally distributed, for specified confidence level and + holding period. +} +\examples{ +# Plots VaR against confidene level given geometric return data + data <- runif(5, min = 0, max = .2) + NormalVaRPlot3D(returns = data, cl = seq(.85,.99,.01), hp = 60:90) + + # Computes VaR against confidence level given mean and standard deviation of return data + NormalVaRPlot3D(mu = .012, sigma = .03, cl = seq(.85,.99,.02), hp = 40:80) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Sat Jul 25 02:43:34 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sat, 25 Jul 2015 02:43:34 +0200 (CEST) Subject: [Returnanalytics-commits] r3856 - in pkg/FactorAnalytics: . R man Message-ID: <20150725004335.04258185404@r-forge.r-project.org> Author: pragnya Date: 2015-07-25 02:43:34 +0200 (Sat, 25 Jul 2015) New Revision: 3856 Added: pkg/FactorAnalytics/R/fmmcSemiParam.R pkg/FactorAnalytics/man/fmmcSemiParam.Rd Modified: pkg/FactorAnalytics/DESCRIPTION pkg/FactorAnalytics/NAMESPACE Log: Semi-parametric fmmc updated Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2015-07-24 19:48:47 UTC (rev 3855) +++ pkg/FactorAnalytics/DESCRIPTION 2015-07-25 00:43:34 UTC (rev 3856) @@ -1,8 +1,8 @@ Package: factorAnalytics Type: Package Title: Factor Analytics -Version:2.0.22 -Date:2015-07-23 +Version:2.0.23 +Date:2015-07-24 Author: Eric Zivot, Sangeetha Srinivasan and Yi-An Chen Maintainer: Sangeetha Srinivasan Description: An R package for the estimation and risk analysis of linear factor Modified: pkg/FactorAnalytics/NAMESPACE =================================================================== --- pkg/FactorAnalytics/NAMESPACE 2015-07-24 19:48:47 UTC (rev 3855) +++ pkg/FactorAnalytics/NAMESPACE 2015-07-25 00:43:34 UTC (rev 3856) @@ -44,6 +44,7 @@ export(fmVaRDecomp) export(fmmc) export(fmmc.estimate.se) +export(fmmcSemiParam) export(pCornishFisher) export(paFm) export(qCornishFisher) Added: pkg/FactorAnalytics/R/fmmcSemiParam.R =================================================================== --- pkg/FactorAnalytics/R/fmmcSemiParam.R (rev 0) +++ pkg/FactorAnalytics/R/fmmcSemiParam.R 2015-07-25 00:43:34 UTC (rev 3856) @@ -0,0 +1,167 @@ +#' @title Semi-parametric factor model Monte Carlo +#' +#' @description Simulate asset returns using semi-parametric Monte Carlo, by +#' making use of a fitted factor model. Residuals are randomly generated from a +#' chosen parametric distribution (Normal, Cornish-Fisher or Skew-t). Factor +#' returns are resampled through non-parametric or stationary bootstrap. +#' +#' @param B number of bootstrap samples. Default is 1000. +#' @param factor.ret \code{T x K} matrix or data.frame of factor returns having +#' a complete history of data. +#' @param beta \code{N x K} matrix of factor betas. +#' @param alpha \code{N x 1} matrix of factor alphas (intercepts). If missing, +#' these are assumed to be 0 for all funds. +#' @param resid.par \code{N x P} matrix of parameters for the residual +#' distribution. +#' @param resid.dist the residual distribution; one of "normal", +#' "Cornish-Fisher" or "skew-t". Default is "normal". +#' @param boot.method the resampling method for factor returns; one of "random" +#' or "block". +#' @param seed integer to set random number generator state before resampling +#' factor returns. +#' +#' @details Refer to Yindeng Jiang's PhD thesis referenced below for motivation +#' and empirical results. An abstract can be found at +#' . +#' +#' \code{T} is the no. of observations, \code{K} is the no. of factors, \code{N} +#' is the no. of assets or funds, \code{P} is the no. of parameters for the +#' residual distribution and \code{B} is the no. of bootstrap samples. +#' +#' The columns in \code{resid.par} depend on the choice of \code{resid.dist}. +#' If \code{resid.dist = "normal"}, \code{resid.par} has one column for +#' standard deviation. If \code{resid.dist = "Cornish-Fisher"}, \code{resid.par} +#' has three columns for sigma=standard deviation, skew=skewness and ekurt= +#' excess kurtosis. If \code{resid.dist = "skew-t"}, \code{resid.par} has four +#' columns for xi=location, omega=scale, alpha=shape, and nu=degrees of freedom. +#' Cornish-Fisher distribution is based on the Cornish-Fisher expansion of the +#' Normal quantile. Skew-t is the skewed Student's t-distribution-- Azzalini and +#' Captiano. The parameters can differ across funds, though the type of +#' distribution is the same. +#' +#' Bootstrap method: "random" corresponds to random sampling with replacement, +#' and "block" corresponds to stationary block bootstrap-- Politis and Romano +#' (1994). +#' +#' @return A list containing the following components: +#' \item{sim.fund.ret}{\code{B x N} matrix of simulated fund returns.} +#' \item{boot.factor.ret}{\code{B x K} matrix of resampled factor returns.} +#' \item{sim.residuals}{\code{B x N} matrix of simulated residuals.} +#' +#' @author Eric Zivot, Yi-An Chen, Sangeetha Srinivasan. +#' +#' @references Jiang, Y. (2009). Factor model Monte Carlo methods for general +#' fund-of-funds portfolio management. University of Washington. +#' +#' @seealso http://gradworks.umi.com/33/77/3377280.html +#' +#' @examples +#' # fit a time series factor model for all assets +#' data(managers) +#' fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), +#' factor.names=colnames(managers[,(7:9)]), data=managers) +#' +#' # bootstrap returns using the fitted factor model, Normal dist. for residuals +#' resid.par <- as.matrix(fit$resid.sd,1,6) +#' fmmc.returns <- fmmcSemiParam(factor.ret=managers[,(7:9)], beta=fit$beta, +#' alpha=fit$alpha, resid.par=resid.par) +#' +#' # Cornish-Fisher distribution for residuals +#' resid.par <- cbind(c(1,2,1,3,0.1,0.5), rnorm(6), c(2,3,1,2,1,0)) +#' colnames(resid.par) <- c("var","skew","xskurt") +#' rownames(resid.par) <- colnames(managers[,(1:6)]) +#' fmmc.returns.CF <- fmmcSemiParam(factor.ret=managers[,(7:9)], beta=fit$beta, +#' alpha=fit$alpha, resid.par=resid.par, +#' resid.dist="Cornish-Fisher") +#' +#' # skew-t distribution +#' resid.par <- cbind(rnorm(6), c(1,2,1,3,0.1,0.5), rnorm(6), c(2,3,1,6,10,100)) +#' colnames(resid.par) <- c("xi","omega","alpha","nu") +#' rownames(resid.par) <- colnames(managers[,(1:6)]) +#' fmmc.returns.skewt <- fmmcSemiParam(factor.ret=managers[,(7:9)], +#' beta=fit$beta, alpha=fit$alpha, +#' resid.dist="skew-t", resid.par=resid.par) +#' +#' @export + +fmmcSemiParam <- function (B=1000, factor.ret, beta, alpha, resid.par, + resid.dist=c("normal","Cornish-Fisher","skew-t"), + boot.method=c("random","block"), seed=123) { + + # set defaults and check input vailidity + if (missing(factor.ret)) { + stop("Missing argument: factor.ret") + } else { + factor.ret <- na.omit(as.matrix(factor.ret)) + factor.names <- colnames(factor.ret) + K = ncol(factor.ret) + T = nrow(factor.ret) + } + if (missing(beta)) { + stop("Missing argument: beta") + } else { + fund.names <- rownames(beta) + N = nrow(beta) + if (colnames(beta) != factor.names) { + stop("Invalid argument: beta and factor.ret should correspond to the same + set of factors") + } + } + resid.dist = resid.dist[1] + if (!(resid.dist %in% c("normal","Cornish-Fisher","skew-t"))) { + stop("Invalid argument: resid.dist must be 'normal','Cornish-Fisher' or + 'skew-t'") + } + boot.method = boot.method[1] + if (!(boot.method %in% c("random","block"))) { + stop("Invalid argument: boot.method must be either 'random' or 'block'") + } + if (missing(alpha)) { + alpha <- matrix(0, nrow(beta)) + rownames(alpha) = fund.names + } + if ((nrow(beta) != nrow(alpha)) || (nrow(beta) != nrow(resid.par))) { + stop("Invalid argument: alpha, beta and resid.par should have the same + number of funds") + } + + # set seed for random number generator + set.seed(seed) + + # determine resampling index + if (boot.method == "random") { + boot.idx <- sample(x=T, size=B, replace=TRUE) + } else { + # stationary block resampling + boot.idx <- as.vector(tsbootstrap(x=1:T, nb=ceiling(B/T), type="stationary")) + adj.B <- ceiling(B/T)* T - B + if (adj.B > 0) { + boot.idx <- boot.idx[1:B] + } + } + + # bootstrap factor returns + boot.factor.ret <- factor.ret[boot.idx,] # BxK + + # initialize resulting matrices of simulated values + sim.fund.ret <- matrix(0,B,N) + sim.resid <- matrix(0,B,N) + colnames(sim.fund.ret) = colnames(sim.resid) = fund.names + + # loop through funds to simulate residuals and fund returns + for (i in fund.names) { + # check type of parametric distribution for residuals + switch(resid.dist, + "normal" = {sim.resid[,i] <- rnorm(n=B, mean=0, sd=resid.par[i,]) }, # Bx1 + "Cornish-Fisher" = {sim.resid[,i] <- rCornishFisher(n=B, dp=resid.par[i,])}, + "skew-t" = {sim.resid[,i] <- rst(n=B, dp=resid.par[i,])} + ) + sim.fund.ret[,i] = + alpha[i,1] + boot.factor.ret %*% t(beta[i,,drop=FALSE]) + sim.resid[,i] # Bx1 + } + + # output simulated values as a named list + result <- list(sim.fund.ret=sim.fund.ret, boot.factor.ret=boot.factor.ret, + sim.resid=sim.resid) + return(result) +} Added: pkg/FactorAnalytics/man/fmmcSemiParam.Rd =================================================================== --- pkg/FactorAnalytics/man/fmmcSemiParam.Rd (rev 0) +++ pkg/FactorAnalytics/man/fmmcSemiParam.Rd 2015-07-25 00:43:34 UTC (rev 3856) @@ -0,0 +1,107 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/fmmcSemiParam.R +\name{fmmcSemiParam} +\alias{fmmcSemiParam} +\title{Semi-parametric factor model Monte Carlo} +\usage{ +fmmcSemiParam(B = 1000, factor.ret, beta, alpha, resid.par, + resid.dist = c("normal", "Cornish-Fisher", "skew-t"), + boot.method = c("random", "block"), seed = 123) +} +\arguments{ +\item{B}{number of bootstrap samples. Default is 1000.} + +\item{factor.ret}{\code{T x K} matrix or data.frame of factor returns having +a complete history of data.} + +\item{beta}{\code{N x K} matrix of factor betas.} + +\item{alpha}{\code{N x 1} matrix of factor alphas (intercepts). If missing, +these are assumed to be 0 for all funds.} + +\item{resid.par}{\code{N x P} matrix of parameters for the residual +distribution.} + +\item{resid.dist}{the residual distribution; one of "normal", +"Cornish-Fisher" or "skew-t". Default is "normal".} + +\item{boot.method}{the resampling method for factor returns; one of "random" +or "block".} + +\item{seed}{integer to set random number generator state before resampling +factor returns.} +} +\value{ +A list containing the following components: +\item{sim.fund.ret}{\code{B x N} matrix of simulated fund returns.} +\item{boot.factor.ret}{\code{B x K} matrix of resampled factor returns.} +\item{sim.residuals}{\code{B x N} matrix of simulated residuals.} +} +\description{ +Simulate asset returns using semi-parametric Monte Carlo, by +making use of a fitted factor model. Residuals are randomly generated from a +chosen parametric distribution (Normal, Cornish-Fisher or Skew-t). Factor +returns are resampled through non-parametric or stationary bootstrap. +} +\details{ +Refer to Yindeng Jiang's PhD thesis referenced below for motivation +and empirical results. An abstract can be found at +. + +\code{T} is the no. of observations, \code{K} is the no. of factors, \code{N} +is the no. of assets or funds, \code{P} is the no. of parameters for the +residual distribution and \code{B} is the no. of bootstrap samples. + +The columns in \code{resid.par} depend on the choice of \code{resid.dist}. +If \code{resid.dist = "normal"}, \code{resid.par} has one column for +standard deviation. If \code{resid.dist = "Cornish-Fisher"}, \code{resid.par} +has three columns for sigma=standard deviation, skew=skewness and ekurt= +excess kurtosis. If \code{resid.dist = "skew-t"}, \code{resid.par} has four +columns for xi=location, omega=scale, alpha=shape, and nu=degrees of freedom. +Cornish-Fisher distribution is based on the Cornish-Fisher expansion of the +Normal quantile. Skew-t is the skewed Student's t-distribution-- Azzalini and +Captiano. The parameters can differ across funds, though the type of +distribution is the same. + +Bootstrap method: "random" corresponds to random sampling with replacement, +and "block" corresponds to stationary block bootstrap-- Politis and Romano +(1994). +} +\examples{ +# fit a time series factor model for all assets +data(managers) +fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), + factor.names=colnames(managers[,(7:9)]), data=managers) + +# bootstrap returns using the fitted factor model, Normal dist. for residuals +resid.par <- as.matrix(fit$resid.sd,1,6) +fmmc.returns <- fmmcSemiParam(factor.ret=managers[,(7:9)], beta=fit$beta, + alpha=fit$alpha, resid.par=resid.par) + +# Cornish-Fisher distribution for residuals +resid.par <- cbind(c(1,2,1,3,0.1,0.5), rnorm(6), c(2,3,1,2,1,0)) +colnames(resid.par) <- c("var","skew","xskurt") +rownames(resid.par) <- colnames(managers[,(1:6)]) +fmmc.returns.CF <- fmmcSemiParam(factor.ret=managers[,(7:9)], beta=fit$beta, + alpha=fit$alpha, resid.par=resid.par, + resid.dist="Cornish-Fisher") + +# skew-t distribution +resid.par <- cbind(rnorm(6), c(1,2,1,3,0.1,0.5), rnorm(6), c(2,3,1,6,10,100)) +colnames(resid.par) <- c("xi","omega","alpha","nu") +rownames(resid.par) <- colnames(managers[,(1:6)]) +fmmc.returns.skewt <- fmmcSemiParam(factor.ret=managers[,(7:9)], + beta=fit$beta, alpha=fit$alpha, + resid.dist="skew-t", resid.par=resid.par) +} +\author{ +Eric Zivot, Yi-An Chen, Sangeetha Srinivasan. +} +\references{ +Jiang, Y. (2009). Factor model Monte Carlo methods for general +fund-of-funds portfolio management. University of Washington. +} +\seealso{ +http://gradworks.umi.com/33/77/3377280.html +} + From noreply at r-forge.r-project.org Sun Jul 26 21:51:59 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 26 Jul 2015 21:51:59 +0200 (CEST) Subject: [Returnanalytics-commits] r3857 - pkg/Dowd/man Message-ID: <20150726195159.7BB41187A17@r-forge.r-project.org> Author: dacharya Date: 2015-07-26 21:51:59 +0200 (Sun, 26 Jul 2015) New Revision: 3857 Modified: pkg/Dowd/man/GaussianCopulaVaR.Rd Log: Made documentation consistent with slight change in example in R file Modified: pkg/Dowd/man/GaussianCopulaVaR.Rd =================================================================== --- pkg/Dowd/man/GaussianCopulaVaR.Rd 2015-07-25 00:43:34 UTC (rev 3856) +++ pkg/Dowd/man/GaussianCopulaVaR.Rd 2015-07-26 19:51:59 UTC (rev 3857) @@ -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, 6, .95) + GaussianCopulaVaR(2.3, 4.1, 1.2, 1.5, .6, 10, .95) } \author{ Dinesh Acharya From noreply at r-forge.r-project.org Mon Jul 27 00:42:41 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 27 Jul 2015 00:42:41 +0200 (CEST) Subject: [Returnanalytics-commits] r3858 - pkg/Dowd/R Message-ID: <20150726224241.43B83187861@r-forge.r-project.org> Author: dacharya Date: 2015-07-27 00:42:40 +0200 (Mon, 27 Jul 2015) New Revision: 3858 Added: pkg/Dowd/R/NormalVaRPlot2DHP.R Log: Function NormalVaRPlot2DHP added Added: pkg/Dowd/R/NormalVaRPlot2DHP.R =================================================================== --- pkg/Dowd/R/NormalVaRPlot2DHP.R (rev 0) +++ pkg/Dowd/R/NormalVaRPlot2DHP.R 2015-07-26 22:42:40 UTC (rev 3858) @@ -0,0 +1,120 @@ +#' Plots normal VaR against holding period +#' +#' Plots the VaR of a portfolio against holding period assuming that P/L are +#' normally distributed, for specified confidence level and holding period. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 3 +#' or 4. In case there 3 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' cl VaR confidence level and must be a scalar +#' +#' hp VaR holding period and must be a vector +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes VaR given P/L data +#' data <- runif(5, min = 0, max = .2) +#' NormalVaRPlot2DHP(returns = data, cl = .95, hp = 60:90) +#' +#' # Computes VaR given mean and standard deviation of P/L data +#' NormalVaRPlot2DHP(mu = .012, sigma = .03, cl = .99, hp = 40:80) +#' +#' +#' @export +NormalVaRPlot2DHP <- function(...){ + # Determine if there are three or four arguments, and ensure that arguments are read as intended + if (nargs() < 3) { + stop("Too few arguments") + } + if (nargs() > 4) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 4) { + mu <- args$mu + investment <- args$investment + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 3) { + mu <- mean(args$returns) + investment <- args$investment + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (max(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a vector") + } + + # Check that hp is read as row vector + if (hp.row > hp.col) { + hp <- t(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 level must be less than 1") + } + if (min(cl) <= 0){ + stop("Confidence level must be greater than 0") + } + if (min(hp) <= 0){ + stop("Holding periods must be greater than 0") + } + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- - sigma[1,1] * sqrt(t(hp)) * qnorm(1 - cl[1,1], 0, 1) + - mu[1,1] * t(hp) %*% matrix(1, cl.row, cl.col) # VaR + # Plotting + plot(hp, VaR, type = "l", xlab = "Holding Period", ylab = "VaR") + cl.label <- cl * 100 + title("Normal VaR against holding period") + xmin <-min(hp)+.25*(max(hp)-min(hp)) + text(xmin,max(VaR)-.1*(max(VaR)-min(VaR)), + 'Input parameters', cex=.75, font = 2) + text(xmin,max(VaR)-.175*(max(VaR)-min(VaR)), + paste('Daily mean P/L = ',mu[1,1]),cex=.75) + text(xmin,max(VaR)-.25*(max(VaR)-min(VaR)), + paste('Stdev. of daily L/P = ',sigma[1,1]),cex=.75) + text(xmin,max(VaR)-.325*(max(VaR)-min(VaR)), + paste('Confidence level = ',cl.label,'%'),cex=.75) +} From noreply at r-forge.r-project.org Mon Jul 27 00:43:24 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 27 Jul 2015 00:43:24 +0200 (CEST) Subject: [Returnanalytics-commits] r3859 - pkg/Dowd/man Message-ID: <20150726224324.26BC5187861@r-forge.r-project.org> Author: dacharya Date: 2015-07-27 00:43:23 +0200 (Mon, 27 Jul 2015) New Revision: 3859 Added: pkg/Dowd/man/NormalVaRPlot2DHP.Rd Log: Function NormalVaRPlot2DHP added Added: pkg/Dowd/man/NormalVaRPlot2DHP.Rd =================================================================== --- pkg/Dowd/man/NormalVaRPlot2DHP.Rd (rev 0) +++ pkg/Dowd/man/NormalVaRPlot2DHP.Rd 2015-07-26 22:43:23 UTC (rev 3859) @@ -0,0 +1,42 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/NormalVaRPlot2DHP.R +\name{NormalVaRPlot2DHP} +\alias{NormalVaRPlot2DHP} +\title{Plots normal VaR against holding period} +\usage{ +NormalVaRPlot2DHP(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 3 + or 4. In case there 3 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. +returns Vector of daily geometric return data + + mu Mean of daily geometric return data + + sigma Standard deviation of daily geometric return data + + cl VaR confidence level and must be a scalar + + hp VaR holding period and must be a vector} +} +\description{ +Plots the VaR of a portfolio against holding period assuming that P/L are +normally distributed, for specified confidence level and holding period. +} +\examples{ +# Computes VaR given P/L data + data <- runif(5, min = 0, max = .2) + NormalVaRPlot2DHP(returns = data, cl = .95, hp = 60:90) + + # Computes VaR given mean and standard deviation of P/L data + NormalVaRPlot2DHP(mu = .012, sigma = .03, cl = .99, hp = 40:80) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Mon Jul 27 00:43:47 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 27 Jul 2015 00:43:47 +0200 (CEST) Subject: [Returnanalytics-commits] r3860 - pkg/Dowd Message-ID: <20150726224348.0564E187861@r-forge.r-project.org> Author: dacharya Date: 2015-07-27 00:43:47 +0200 (Mon, 27 Jul 2015) New Revision: 3860 Modified: pkg/Dowd/NAMESPACE Log: Function NormalVaRPlot2DHP added Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-26 22:43:23 UTC (rev 3859) +++ pkg/Dowd/NAMESPACE 2015-07-26 22:43:47 UTC (rev 3860) @@ -97,6 +97,7 @@ export(NormalVaRDFPerc) export(NormalVaRFigure) export(NormalVaRPlot2DCL) +export(NormalVaRPlot2DHP) export(NormalVaRPlot3D) export(PCAES) export(PCAESPlot) From noreply at r-forge.r-project.org Tue Jul 28 10:03:33 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 28 Jul 2015 10:03:33 +0200 (CEST) Subject: [Returnanalytics-commits] r3861 - in pkg/Dowd: . R man Message-ID: <20150728080333.839B41868F6@r-forge.r-project.org> Author: dacharya Date: 2015-07-28 10:03:33 +0200 (Tue, 28 Jul 2015) New Revision: 3861 Modified: pkg/Dowd/DESCRIPTION pkg/Dowd/NAMESPACE pkg/Dowd/R/PCAPrelim.R pkg/Dowd/man/PCAPrelim.Rd Log: Dependence on external package expm avoided. Simple version of function %^% was implemented. Modified: pkg/Dowd/DESCRIPTION =================================================================== --- pkg/Dowd/DESCRIPTION 2015-07-26 22:43:47 UTC (rev 3860) +++ pkg/Dowd/DESCRIPTION 2015-07-28 08:03:33 UTC (rev 3861) @@ -1,16 +1,15 @@ -Package: Dowd -Type: Package -Title: R-Version of MMR II Toolbox Offered in Kevin Dowd's Book Measuring Market Risk -Version: 0.1 -Date: 2015-05-24 -Author: Dinesh Acharya -Maintainer: Dinesh Acharya -Description: R-version of MMR2 Toolbox that supplements - Kevin Dowd's book Measuring Market Risk. -Depends: R (>= 3.0.0), - bootstrap, - MASS, - expm -Suggests: PerformanceAnalytics, - testthat -License: GPL +Package: Dowd +Type: Package +Title: R-Version of MMR II Toolbox Offered in Kevin Dowd's Book Measuring Market Risk +Version: 0.1 +Date: 2015-05-24 +Author: Dinesh Acharya +Maintainer: Dinesh Acharya +Description: R-version of MMR2 Toolbox that supplements + Kevin Dowd's book Measuring Market Risk. +Depends: R (>= 3.0.0), + bootstrap, + MASS +Suggests: PerformanceAnalytics, + testthat +License: GPL Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-26 22:43:47 UTC (rev 3860) +++ pkg/Dowd/NAMESPACE 2015-07-28 08:03:33 UTC (rev 3861) @@ -110,4 +110,3 @@ export(TQQPlot) import(MASS) import(bootstrap) -import(expm) Modified: pkg/Dowd/R/PCAPrelim.R =================================================================== --- pkg/Dowd/R/PCAPrelim.R 2015-07-26 22:43:47 UTC (rev 3860) +++ pkg/Dowd/R/PCAPrelim.R 2015-07-28 08:03:33 UTC (rev 3861) @@ -1,11 +1,10 @@ -#' PCAPrelim #' #' Estimates VaR plot using principal components analysis #' #' @param Ra Matrix return data set where each row is interpreted as a set of #' daily observations, and each column as the returns to each position in a -#' portfolio -#' position +#' portfolio position +#' #' @references Dowd, K. Measuring Market Risk, Wiley, 2007. #' #' @author Dinesh Acharya @@ -15,11 +14,10 @@ #' # This code was based on Dowd's code and similar to Dowd's code, #' # it is inconsistent for non-scalar data (Ra). #' library(MASS) -#' library(expm) #' Ra <- .15 #' PCAPrelim(Ra) #' -#' @import expm MASS +#' @import MASS #' #' @export PCAPrelim <- function(Ra){ @@ -69,3 +67,12 @@ title("Explanatory Power of the Principal Components") } + +# ------------------------------ Helper function ------------------------------ +# Matrix exponentiation +"%^%" <- function(S, power) { + # Uses eigenvalue decomposition A = PDP^-1 for matrix exponentiation. + # Also see expm package for larger matrices for efficiency. + y <- with(eigen(S), vectors %*% (values^power * solve(vectors))) + return(y) +} \ No newline at end of file Modified: pkg/Dowd/man/PCAPrelim.Rd =================================================================== --- pkg/Dowd/man/PCAPrelim.Rd 2015-07-26 22:43:47 UTC (rev 3860) +++ pkg/Dowd/man/PCAPrelim.Rd 2015-07-28 08:03:33 UTC (rev 3861) @@ -9,8 +9,7 @@ \arguments{ \item{Ra}{Matrix return data set where each row is interpreted as a set of daily observations, and each column as the returns to each position in a -portfolio -position} +portfolio position} } \description{ Estimates VaR plot using principal components analysis @@ -20,7 +19,6 @@ # This code was based on Dowd's code and similar to Dowd's code, # it is inconsistent for non-scalar data (Ra). library(MASS) - library(expm) Ra <- .15 PCAPrelim(Ra) } From noreply at r-forge.r-project.org Tue Jul 28 10:15:23 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 28 Jul 2015 10:15:23 +0200 (CEST) Subject: [Returnanalytics-commits] r3862 - pkg/Dowd/R Message-ID: <20150728081523.C2187183ED6@r-forge.r-project.org> Author: dacharya Date: 2015-07-28 10:15:23 +0200 (Tue, 28 Jul 2015) New Revision: 3862 Added: pkg/Dowd/R/tES.R pkg/Dowd/R/tESDFPerc.R pkg/Dowd/R/tESFigure.R Log: Function tES added. Added: pkg/Dowd/R/tES.R =================================================================== --- pkg/Dowd/R/tES.R (rev 0) +++ pkg/Dowd/R/tES.R 2015-07-28 08:15:23 UTC (rev 3862) @@ -0,0 +1,145 @@ +#' ES for t distributed P/L +#' +#' Estimates the ES of a portfolio assuming that P/L are +#' t-distributed, for specified confidence level and holding period. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +#' +#' returns Vector of daily P/L data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' df Number of degrees of freedom in the t-distribution +#' +#' cl ES confidence level +#' +#' hp ES holding period in days +#' +#' @return Matrix of ES whose dimension depends on dimension of hp and cl. If +#' cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is +#' a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, +#' the matrix is column matrix and if both cl and hp are vectors, the matrix +#' has dimension length of cl * length of hp. +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Evans, M., Hastings, M. and Peacock, B. Statistical Distributions, 3rd +#' edition, New York: John Wiley, ch. 38,39. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Computes ES given P/L data +#' data <- runif(5, min = 0, max = .2) +#' tES(returns = data, df = 6, cl = .95, hp = 90) +#' +#' # Computes ES given mean and standard deviation of P/L data +#' tES(mu = .012, sigma = .03, df = 6, cl = .95, hp = 90) +#' +#' +#' @export +tES <- function(...){ + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() > 5) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 5) { + mu <- args$mu + df <- args$df + cl <- args$cl + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + df <- args$df + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar or a vector") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar or a vector") + } + df <- as.matrix(df) + df.row <- dim(df)[1] + df.col <- dim(df)[2] + if (max(df.row, df.col) > 1) { + stop("Number of degrees of freedom must be a scalar") + } + + # Check that cl and hp are read as row and column vectors respectively + if (cl.row > cl.col) { + cl <- t(cl) + } + if (hp.row > hp.col) { + hp <- t(hp) + } + + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (df < 3) { + stop("Number of degrees of freedom must be at least 3 for first two moments of distribution to be defined") + } + 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(hp) <= 0){ + stop("Holding Period(s) must be greater than 0") + } + + # ES estimation + ES <- matrix(0, length(hp), length(cl)) + for (i in 1:length(cl)) { + for (j in 1:length(hp)) { + ES[j, i] <- Univariate.tES(mu, sigma, df, cl[i], hp[j]) + } + } + return (ES) +} + +# Accessory function +Univariate.tES <- function (mu, sigma, df, cl, hp) { + # This function estimates univariate t-ES using average tail quantile algorithm + number.slices <- 1000 + delta.p <- (1 - cl)/number.slices + p <- seq(cl + delta.p, 1 - delta.p, delta.p) # Tail confidence levels or cumulative probs + tail.VaRs <- -sigma * sqrt(hp) * sqrt((df - 2)/df) * qt((1 - p), df) - mu * hp # Tail VaRs + y <- mean(tail.VaRs) + return(y) +} \ No newline at end of file Added: pkg/Dowd/R/tESDFPerc.R =================================================================== --- pkg/Dowd/R/tESDFPerc.R (rev 0) +++ pkg/Dowd/R/tESDFPerc.R 2015-07-28 08:15:23 UTC (rev 3862) @@ -0,0 +1,179 @@ +#' Percentiles of ES distribution function for t-distributed P/L +#' +#' Estimates percentiles of ES distribution function for t-distributed P/L, +#' using the theory of order statistics +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 5 +#' or 7. In case there 5 input arguments, the mean, standard deviation and assumed sampel size of +#' data is computed from return data. See examples for details. +#' +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' n Sample size +#' +#' df Degrees of freedom +#' +#' perc Desired percentile +#' +#' df Number of degrees of freedom in the t distribution +#' +#' cl ES confidence level and must be a scalar +#' +#' hp ES holding period and must be a a scalar +#' +#' @return Percentiles of ES distribution function +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates Percentiles of ES distribution given P/L data +#' data <- runif(5, min = 0, max = .2) +#' tESDFPerc(returns = data, perc = .7, df = 6, cl = .95, hp = 60) +#' +#' # Estimates Percentiles of ES distribution given mean, std. deviation and sample size +#' tESDFPerc(mu = .012, sigma = .03, n= 10, perc = .8, df = 6, cl = .99, hp = 40) +#' +#' +#' @export +tESDFPerc <- function(...){ + if (nargs() < 5) { + stop("Too few arguments") + } + if (nargs() == 6) { + stop("Incorrect number of arguments") + } + if (nargs() > 7) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 7) { + mu <- args$mu + df <- args$df + cl <- args$cl + perc <- args$sigma + n <- args$n + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 5) { + mu <- mean(args$returns) + df <- args$df + n <- max(dim(as.matrix(args$returns))) + perc <- args$perc + cl <- args$cl + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + n <- as.matrix(n) + n.row <- dim(n)[1] + n.col <- dim(n)[2] + if (max(n.row, n.col) > 1) { + stop("Number of observations in a sample must be a scalar") + } + if (n - round(n) > 0 | n - round(n) < 0) { + stop("Number of observations in a sample must be an integer") + } + perc <- as.matrix(perc) + perc.row <- dim(perc)[1] + perc.col <- dim(perc)[2] + if (max(perc.row, perc.col) > 1) { + stop("Chosen percentile of the distribution must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (max(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (max(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar") + } + + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (n < 0) { + stop("Number of observations must be non-negative") + } + if (df < 0) { + stop("Number of degrees of freedom must be greater than zero") + } + if (perc > 1){ + stop("Chosen percentile must not exceed 1") + } + if (perc <= 0){ + stop("Chosen percentile must be positive") + } + 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("Honding period must be greater than 0") + } + + # Derive order statistic and ensure it is an integer + w <- n * cl # Derive r-th order statistic + 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 + } + } + + # VaR estimation + VaR <- - mu * hp + sigma * sqrt((df-2)/df)*sqrt(hp)*qt(x, df) # Value of VaR percentile, note t VaR formula + + # ES estimation + cl <- x + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + term <- VaR + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl # Revised cl + term <- term - mu * hp - sigma * sqrt((df-2)/df)*sqrt(hp)*qt(1 - cl, df) + } + y <- term/n + return(y) # Value of ES percentile +} Added: pkg/Dowd/R/tESFigure.R =================================================================== --- pkg/Dowd/R/tESFigure.R (rev 0) +++ pkg/Dowd/R/tESFigure.R 2015-07-28 08:15:23 UTC (rev 3862) @@ -0,0 +1,173 @@ +#' Figure of t - VaR and ES and pdf against L/P +#' +#' Gives figure showing the VaR and ES and probability distribution function assuming P/L is t- distributed, for specified confidence level and holding period. +#' +#' @param ... The input arguments contain either return data or else mean and +#' standard deviation data. Accordingly, number of input arguments is either 4 +#' or 5. In case there 4 input arguments, the mean and standard deviation of +#' data is computed from return data. See examples for details. +# +#' returns Vector of daily geometric return data +#' +#' mu Mean of daily geometric return data +#' +#' sigma Standard deviation of daily geometric return data +#' +#' df Number of degrees of freedom +#' +#' cl VaR confidence level and should be scalar +#' +#' hp VaR holding period in days and should be scalar +#' +#' @references Dowd, K. Measuring Market Risk, Wiley, 2007. +#' +#' Evans, M., Hastings, M. and Peacock, B. Statistical Distributions, 3rd +#' edition, New York: John Wiley, ch. 38,39. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Plots lognormal VaR, ES and pdf against L/P data for given returns data +#' data <- runif(5, min = 0, max = .2) +#' tESFigure(returns = data, df = 10, cl = .95, hp = 90) +#' +#' # Plots lognormal VaR, ES and pdf against L/P data with given parameters +#' tESFigure(mu = .012, sigma = .03, df = 10, cl = .95, hp = 90) +#' +#' @export +tESFigure <- function(...){ + # Determine if there are four or five arguments and ensure that arguments are + # read as intended + if (nargs() < 4) { + stop("Too few arguments") + } + if (nargs() > 5) { + stop("Too many arguments") + } + args <- list(...) + if (nargs() == 5) { + mu <- args$mu + cl <- args$cl + df <- args$df + sigma <- args$sigma + hp <- args$hp + } + if (nargs() == 4) { + mu <- mean(args$returns) + cl <- args$cl + df <- args$df + sigma <- sd(args$returns) + hp <- args$hp + } + + # Check that inputs have correct dimensions + mu <- as.matrix(mu) + mu.row <- dim(mu)[1] + mu.col <- dim(mu)[2] + if (max(mu.row, mu.col) > 1) { + stop("Mean must be a scalar") + } + sigma <- as.matrix(sigma) + sigma.row <- dim(sigma)[1] + sigma.col <- dim(sigma)[2] + if (max(sigma.row, sigma.col) > 1) { + stop("Standard deviation must be a scalar") + } + cl <- as.matrix(cl) + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + if (min(cl.row, cl.col) > 1) { + stop("Confidence level must be a scalar or a vector") + } + df <- as.matrix(df) + df.row <- dim(df)[1] + df.col <- dim(df)[2] + if (max(df.row, df.col) > 1) { + stop("Number of degrees of freedom must be a scalar") + } + hp <- as.matrix(hp) + hp.row <- dim(hp)[1] + hp.col <- dim(hp)[2] + if (min(hp.row, hp.col) > 1) { + stop("Holding period must be a scalar or a vector") + } + + # Check that cl and hp are read as row and column vectors respectively + if (cl.row > cl.col) { + cl <- t(cl) + } + if (hp.row > hp.col) { + hp <- t(hp) + } + + # Check that inputs obey sign and value restrictions + if (sigma < 0) { + stop("Standard deviation must be non-negative") + } + if (df < 3) { + stop("Number of degrees of freedom must be at least 3 for first two moments of distribution to be defined") + } + 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(hp) <= 0){ + stop("Holding Period(s) must be greater than 0") + } + + # Message to indicate how matrix of results is to be interpreted, if cl and hp both vary and results are given in matrix form + if (max(cl.row, cl.col) > 1 & max(hp.row, hp.col) > 1) { + print('VaR results with confidence level varying across row and holding period down column') + } + + # VaR estimation + cl.row <- dim(cl)[1] + cl.col <- dim(cl)[2] + VaR <- - sigma[1,1] * sqrt(hp) * sqrt((df - 2) / df) %*% qt(1 - cl, df) - mu[1,1] * hp %*% matrix(1, cl.row, cl.col) # VaR + + # ES Estimation + n <- 1000 # Number of slices into which tail is divided + cl0 <- cl # Initial confidence level + w <- VaR + delta.cl <- (1 - cl) / n # Increment to confidence level as each slice is taken + for (i in 1:(n-1)) { + cl <- cl0 + i * delta.cl + w <- w - sigma[1,1] * sqrt(hp) * sqrt((df - 2) / df) %*% qt(1 - cl, df) - mu[1,1] * hp %*% matrix(1, cl.row, cl.col) + } + ES <- w/n + # Plotting + x.min <- -mu - 5 * sigma + x.max <- -mu + 5 * sigma + delta <- (x.max-x.min) / 100 + x <- seq(x.min, x.max, delta) + p <- dt((x-mu) / sigma, df) + plot(x, p, type = "l", xlim = c(x.min, x.max), ylim = c(0, max(p)*1.1), xlab = "Loss (+) / Profit (-)", ylab = "Probability", main = "t- VaR and ES") + + # VaR line + u <- c(VaR, VaR) + v <- c(0, .6*max(p)) + lines(u, v, type = "l", col = "blue") + + # ES line + w <- c(ES, ES) + z <- c(0, .45*max(p)) + lines(w, z, type = "l", col = "blue") + # Input Labels + cl.for.label <- 100 * cl0 + xpos <- -mu-2.5*sigma + text(xpos,.95*max(p), pos = 1, 'Input parameters', cex=.75, font = 2) + text(xpos, .875*max(p),pos = 1, paste('Daily mean L/P = ', -mu), cex=.75) + text(xpos, .8*max(p),pos = 1, paste('St. dev. of daily L/P = ', sigma), cex=.75) + text(xpos, .725*max(p),pos = 1, paste('Degrees of freedom', df), cex=.75) + text(xpos, .65*max(p),pos = 1, paste('Holding period = ', hp,' day(s)'), cex=.75) + # VaR label + text(VaR, .7*max(p),pos = 2, paste('VaR at ', cl.for.label,'% CL'), cex=.75) + text(VaR, .65 * max(p),pos = 2, paste('= ',VaR), cex=.75) + + # ES label + text(ES, .55*max(p),pos = 2, 'ES =', cex=.75) + text(ES, .65 * max(p),pos = 2, paste(ES), cex=.75) + +} From noreply at r-forge.r-project.org Tue Jul 28 10:16:30 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 28 Jul 2015 10:16:30 +0200 (CEST) Subject: [Returnanalytics-commits] r3863 - pkg/Dowd Message-ID: <20150728081630.32C4D183ED6@r-forge.r-project.org> Author: dacharya Date: 2015-07-28 10:16:29 +0200 (Tue, 28 Jul 2015) New Revision: 3863 Modified: pkg/Dowd/NAMESPACE Log: Functions tES, tESDFPerc and tESFigure added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-28 08:15:23 UTC (rev 3862) +++ pkg/Dowd/NAMESPACE 2015-07-28 08:16:29 UTC (rev 3863) @@ -108,5 +108,8 @@ export(PickandsPlot) export(ProductCopulaVaR) export(TQQPlot) +export(tES) +export(tESDFPerc) +export(tESFigure) import(MASS) import(bootstrap) From noreply at r-forge.r-project.org Tue Jul 28 10:17:25 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 28 Jul 2015 10:17:25 +0200 (CEST) Subject: [Returnanalytics-commits] r3864 - pkg/Dowd/man Message-ID: <20150728081725.69735183ED6@r-forge.r-project.org> Author: dacharya Date: 2015-07-28 10:17:25 +0200 (Tue, 28 Jul 2015) New Revision: 3864 Modified: pkg/Dowd/man/PCAPrelim.Rd Log: Small modification in title. Modified: pkg/Dowd/man/PCAPrelim.Rd =================================================================== --- pkg/Dowd/man/PCAPrelim.Rd 2015-07-28 08:16:29 UTC (rev 3863) +++ pkg/Dowd/man/PCAPrelim.Rd 2015-07-28 08:17:25 UTC (rev 3864) @@ -2,7 +2,7 @@ % Please edit documentation in R/PCAPrelim.R \name{PCAPrelim} \alias{PCAPrelim} -\title{PCAPrelim} +\title{Estimates VaR plot using principal components analysis} \usage{ PCAPrelim(Ra) } From noreply at r-forge.r-project.org Tue Jul 28 10:18:02 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 28 Jul 2015 10:18:02 +0200 (CEST) Subject: [Returnanalytics-commits] r3865 - pkg/Dowd/man Message-ID: <20150728081802.A88FB183ED6@r-forge.r-project.org> Author: dacharya Date: 2015-07-28 10:18:02 +0200 (Tue, 28 Jul 2015) New Revision: 3865 Added: pkg/Dowd/man/tES.Rd Log: Function tES added. Added: pkg/Dowd/man/tES.Rd =================================================================== --- pkg/Dowd/man/tES.Rd (rev 0) +++ pkg/Dowd/man/tES.Rd 2015-07-28 08:18:02 UTC (rev 3865) @@ -0,0 +1,55 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/tES.R +\name{tES} +\alias{tES} +\title{ES for t distributed P/L} +\usage{ +tES(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 4 + or 5. In case there 4 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. + + returns Vector of daily P/L data + + mu Mean of daily geometric return data + + sigma Standard deviation of daily geometric return data + + df Number of degrees of freedom in the t-distribution + + cl ES confidence level + + hp ES holding period in days} +} +\value{ +Matrix of ES whose dimension depends on dimension of hp and cl. If +cl and hp are both scalars, the matrix is 1 by 1. If cl is a vector and hp is + a scalar, the matrix is row matrix, if cl is a scalar and hp is a vector, + the matrix is column matrix and if both cl and hp are vectors, the matrix + has dimension length of cl * length of hp. +} +\description{ +Estimates the ES of a portfolio assuming that P/L are +t-distributed, for specified confidence level and holding period. +} +\examples{ +# Computes ES given P/L data + data <- runif(5, min = 0, max = .2) + tES(returns = data, df = 6, cl = .95, hp = 90) + + # Computes ES given mean and standard deviation of P/L data + tES(mu = .012, sigma = .03, df = 6, cl = .95, hp = 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Evans, M., Hastings, M. and Peacock, B. Statistical Distributions, 3rd +edition, New York: John Wiley, ch. 38,39. +} + From noreply at r-forge.r-project.org Tue Jul 28 10:18:20 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 28 Jul 2015 10:18:20 +0200 (CEST) Subject: [Returnanalytics-commits] r3866 - pkg/Dowd/man Message-ID: <20150728081820.72241183ED6@r-forge.r-project.org> Author: dacharya Date: 2015-07-28 10:18:20 +0200 (Tue, 28 Jul 2015) New Revision: 3866 Added: pkg/Dowd/man/tESDFPerc.Rd Log: Function tESDFPerc added. Added: pkg/Dowd/man/tESDFPerc.Rd =================================================================== --- pkg/Dowd/man/tESDFPerc.Rd (rev 0) +++ pkg/Dowd/man/tESDFPerc.Rd 2015-07-28 08:18:20 UTC (rev 3866) @@ -0,0 +1,54 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/tESDFPerc.R +\name{tESDFPerc} +\alias{tESDFPerc} +\title{Percentiles of ES distribution function for t-distributed P/L} +\usage{ +tESDFPerc(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and +standard deviation data. Accordingly, number of input arguments is either 5 +or 7. In case there 5 input arguments, the mean, standard deviation and assumed sampel size of +data is computed from return data. See examples for details. + + returns Vector of daily geometric return data + + mu Mean of daily geometric return data + + sigma Standard deviation of daily geometric return data + + n Sample size + + df Degrees of freedom + + perc Desired percentile + + df Number of degrees of freedom in the t distribution + + cl ES confidence level and must be a scalar + + hp ES holding period and must be a a scalar} +} +\value{ +Percentiles of ES distribution function +} +\description{ +Estimates percentiles of ES distribution function for t-distributed P/L, +using the theory of order statistics +} +\examples{ +# Estimates Percentiles of ES distribution given P/L data + data <- runif(5, min = 0, max = .2) + tESDFPerc(returns = data, perc = .7, df = 6, cl = .95, hp = 60) + + # Estimates Percentiles of ES distribution given mean, std. deviation and sample size + tESDFPerc(mu = .012, sigma = .03, n= 10, perc = .8, df = 6, cl = .99, hp = 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. +} + From noreply at r-forge.r-project.org Tue Jul 28 10:19:45 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 28 Jul 2015 10:19:45 +0200 (CEST) Subject: [Returnanalytics-commits] r3867 - pkg/Dowd/man Message-ID: <20150728081945.3AD03186288@r-forge.r-project.org> Author: dacharya Date: 2015-07-28 10:19:44 +0200 (Tue, 28 Jul 2015) New Revision: 3867 Added: pkg/Dowd/man/tESFigure.Rd Log: Function tESFigure added. Added: pkg/Dowd/man/tESFigure.Rd =================================================================== --- pkg/Dowd/man/tESFigure.Rd (rev 0) +++ pkg/Dowd/man/tESFigure.Rd 2015-07-28 08:19:44 UTC (rev 3867) @@ -0,0 +1,46 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/tESFigure.R +\name{tESFigure} +\alias{tESFigure} +\title{Figure of t - VaR and ES and pdf against L/P} +\usage{ +tESFigure(...) +} +\arguments{ +\item{...}{The input arguments contain either return data or else mean and + standard deviation data. Accordingly, number of input arguments is either 4 + or 5. In case there 4 input arguments, the mean and standard deviation of + data is computed from return data. See examples for details. + returns Vector of daily geometric return data + + mu Mean of daily geometric return data + + sigma Standard deviation of daily geometric return data + + df Number of degrees of freedom + + cl VaR confidence level and should be scalar + + hp VaR holding period in days and should be scalar} +} +\description{ +Gives figure showing the VaR and ES and probability distribution function assuming P/L is t- distributed, for specified confidence level and holding period. +} +\examples{ +# Plots lognormal VaR, ES and pdf against L/P data for given returns data + data <- runif(5, min = 0, max = .2) + tESFigure(returns = data, df = 10, cl = .95, hp = 90) + + # Plots lognormal VaR, ES and pdf against L/P data with given parameters + tESFigure(mu = .012, sigma = .03, df = 10, cl = .95, hp = 90) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, K. Measuring Market Risk, Wiley, 2007. + +Evans, M., Hastings, M. and Peacock, B. Statistical Distributions, 3rd +edition, New York: John Wiley, ch. 38,39. +} + From noreply at r-forge.r-project.org Wed Jul 29 00:59:29 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 29 Jul 2015 00:59:29 +0200 (CEST) Subject: [Returnanalytics-commits] r3868 - pkg/Dowd Message-ID: <20150728225929.1919D187569@r-forge.r-project.org> Author: dacharya Date: 2015-07-29 00:59:28 +0200 (Wed, 29 Jul 2015) New Revision: 3868 Modified: pkg/Dowd/NAMESPACE Log: Functions AmericalPutESBinomial, AmericanPutPriceBinomial and AmericanPutVaRBinomial added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-28 08:19:44 UTC (rev 3867) +++ pkg/Dowd/NAMESPACE 2015-07-28 22:59:28 UTC (rev 3868) @@ -5,6 +5,9 @@ export(AdjustedNormalVaRHotspots) export(AdjustedVarianceCovarianceES) export(AdjustedVarianceCovarianceVaR) +export(AmericanPutESBinomial) +export(AmericanPutPriceBinomial) +export(AmericanPutVarBinomial) export(BinomialBacktest) export(BlancoIhleBacktest) export(BootstrapES) From noreply at r-forge.r-project.org Wed Jul 29 01:00:34 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 29 Jul 2015 01:00:34 +0200 (CEST) Subject: [Returnanalytics-commits] r3869 - pkg/Dowd/R Message-ID: <20150728230034.3630E187569@r-forge.r-project.org> Author: dacharya Date: 2015-07-29 01:00:33 +0200 (Wed, 29 Jul 2015) New Revision: 3869 Added: pkg/Dowd/R/AmericanPutESBinomial.R Log: Function AmericanPutESBinomial added. Added: pkg/Dowd/R/AmericanPutESBinomial.R =================================================================== --- pkg/Dowd/R/AmericanPutESBinomial.R (rev 0) +++ pkg/Dowd/R/AmericanPutESBinomial.R 2015-07-28 23:00:33 UTC (rev 3869) @@ -0,0 +1,96 @@ +#' Estimates ES of American vanilla put using binomial tree. +#' +#' Estimates ES of American Put Option using binomial tree to price the option +#' and historical method to compute the VaR. +#' +#' @param amountInvested Total amount paid for the Put Option. +#' @param stockPrice Stock price of underlying stock. +#' @param strike Strike price of the option. +#' @param r Risk-free rate. +#' @param volatility Volatility of the underlying stock. +#' @param maturity Time to maturity of the option in days. +#' @param numberSteps The number of time-steps considered for +#' the binomial model. +#' @param cl Confidence level for which VaR is computed. +#' @param hp Holding period of the option in days. +#' @return ES of the American Put Option +#' @references Dowd, Kevin. Measuring Market Risk, Wiley, 2007. +#' +#' Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +#' Mathematics, Algorithms, Cambridge University Press, 2002. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Market Risk of American Put with given parameters. +#' AmericanPutESBinomial(0.20, 27.2, 25, .16, .05, 60, 20, .95, 30) +#' +#' @export +AmericanPutESBinomial <- function(amountInvested, stockPrice, strike, r, + volatility, maturity, numberSteps, cl, hp){ + s <- stockPrice + x <- strike + time <- maturity + sigma <- volatility + # convert maturity and holding period unit from days to years + time <- time/360 + hp <- hp/360 + # calculate the length of each interval, dt, and number of steps to end of + # holding period + n <- numberSteps + dt <- time/n + m <- round(hp/dt) # number of steps to end of holding period + # + # calculate movements and associated probabilities + # + u <- exp(sigma*sqrt(dt)) + d <- 1/u + a <- exp(r*dt) # Note: Dowd's original code had (r-q), but since r is + # risk-free rate of returns, it should be r only. + p <- (a-d)/(u-d) + jspan <- n*.5 + jspan <- -((jspan>=0)*floor(jspan)+(jspan<0)*ceiling(jspan)) # j-th node + # offset number + ispan <- round(time/dt)%%2 # i-th node offset number + i <- ispan:(n+ispan) # i-th node numbers + j <- jspan:(n+jspan) # j-th node numbers + + # expand i and j to eliminate for loop + jex <- matrix(rep(j, each=length(i)), ncol=length(i), byrow=TRUE) + iex <- matrix(rep(i, each=length(j)), nrow=length(j)) + # + # asset price at nodes, matrix is flipped so tree appears correct visually + pr <- t(apply(apply((s*(u^jex)*(d^(iex-jex))), 2, rev), 1, rev)) + # get upper triangle of pr + lower.tri(pr) + pr[lower.tri(pr)] <- 0 + # + # option valuation along tree + opt <- matrix(0,nrow(pr),ncol(pr)) + opt[,n+1] <- pmax(x-pr[,n+1],0) # determine final option value from + # underlying price + for(l in seq(n,1,by=-1)){ + k=1:l + # probable option values discounted back one time step + discopt=(p*opt[k,l+1]+(1-p)*opt[k+1,l+1])*exp(-r*dt) + # option value is max of X - current price or discopt + opt[,l]=c(pmax(x-pr[1:l,l],discopt),rep(0,n+1-l)) + } + # initial option price and number of options in portfolio + initialOptionPrice <- opt[1,1] + numberOptions <- amountInvested/initialOptionPrice + # option tree values at end of holding period + endHpOptionPrice <- opt[,m+1] + endHpOptionPrice <- endHpOptionPrice[1:(m+1)] + # returns<-(endHpOptionPrice-initialOptionPrice)/initialOptionPrice + # option position Profit and Loss + profitOrLoss <- (endHpOptionPrice-initialOptionPrice)*numberOptions + #compute VaR + VaR <- HSVaR(profitOrLoss, cl) + if(VaR == amountInvested){ + ES <- VaR + } else { + ES <- HSES(profitOrLoss, cl) + } + return(ES) +} \ No newline at end of file From noreply at r-forge.r-project.org Wed Jul 29 01:01:40 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 29 Jul 2015 01:01:40 +0200 (CEST) Subject: [Returnanalytics-commits] r3870 - pkg/Dowd/man Message-ID: <20150728230140.2EB73187569@r-forge.r-project.org> Author: dacharya Date: 2015-07-29 01:01:39 +0200 (Wed, 29 Jul 2015) New Revision: 3870 Added: pkg/Dowd/man/AmericanPutESBinomial.Rd Log: Function AmericanPutESBinomial added. Added: pkg/Dowd/man/AmericanPutESBinomial.Rd =================================================================== --- pkg/Dowd/man/AmericanPutESBinomial.Rd (rev 0) +++ pkg/Dowd/man/AmericanPutESBinomial.Rd 2015-07-28 23:01:39 UTC (rev 3870) @@ -0,0 +1,50 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AmericanPutESBinomial.R +\name{AmericanPutESBinomial} +\alias{AmericanPutESBinomial} +\title{Estimates ES of American vanilla put using binomial tree.} +\usage{ +AmericanPutESBinomial(amountInvested, stockPrice, strike, r, volatility, + maturity, numberSteps, cl, hp) +} +\arguments{ +\item{amountInvested}{Total amount paid for the Put Option.} + +\item{stockPrice}{Stock price of underlying stock.} + +\item{strike}{Strike price of the option.} + +\item{r}{Risk-free rate.} + +\item{volatility}{Volatility of the underlying stock.} + +\item{maturity}{Time to maturity of the option in days.} + +\item{numberSteps}{The number of time-steps considered for +the binomial model.} + +\item{cl}{Confidence level for which VaR is computed.} + +\item{hp}{Holding period of the option in days.} +} +\value{ +ES of the American Put Option +} +\description{ +Estimates ES of American Put Option using binomial tree to price the option +and historical method to compute the VaR. +} +\examples{ +# Market Risk of American Put with given parameters. + AmericanPutESBinomial(0.20, 27.2, 25, .16, .05, 60, 20, .95, 30) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +Mathematics, Algorithms, Cambridge University Press, 2002. +} + From noreply at r-forge.r-project.org Wed Jul 29 01:02:39 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 29 Jul 2015 01:02:39 +0200 (CEST) Subject: [Returnanalytics-commits] r3871 - pkg/Dowd/R Message-ID: <20150728230239.2D21D187569@r-forge.r-project.org> Author: dacharya Date: 2015-07-29 01:02:35 +0200 (Wed, 29 Jul 2015) New Revision: 3871 Added: pkg/Dowd/R/AmericanPutVaRBinomial.R Log: Function AmericanPutVaRBinomial added. Added: pkg/Dowd/R/AmericanPutVaRBinomial.R =================================================================== --- pkg/Dowd/R/AmericanPutVaRBinomial.R (rev 0) +++ pkg/Dowd/R/AmericanPutVaRBinomial.R 2015-07-28 23:02:35 UTC (rev 3871) @@ -0,0 +1,90 @@ +#' Estimates VaR of American vanilla put using binomial tree. +#' +#' Estimates VaR of American Put Option using binomial tree to price the option +#' and historical method to compute the VaR. +#' +#' @param amountInvested Total amount paid for the Put Option. +#' @param stockPrice Stock price of underlying stock. +#' @param strike Strike price of the option. +#' @param r Risk-free rate. +#' @param volatility Volatility of the underlying stock. +#' @param maturity Time to maturity of the option in days. +#' @param numberSteps The number of time-steps considered for +#' the binomial model. +#' @param cl Confidence level for which VaR is computed. +#' @param hp Holding period of the option in days. +#' @return VaR of the American Put Option +#' @references Dowd, Kevin. Measuring Market Risk, Wiley, 2007. +#' +#' Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +#' Mathematics, Algorithms, Cambridge University Press, 2002. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Market Risk of American Put with given parameters. +#' AmericanPutVarBinomial(0.20, 27.2, 25, .16, .05, 60, 20, .95, 30) +#' +#' @export +AmericanPutVarBinomial <- function(amountInvested, stockPrice, strike, r, + volatility, maturity, numberSteps, cl, hp){ + s <- stockPrice + x <- strike + time <- maturity + sigma <- volatility + # convert maturity and holding period unit from days to years + time <- time/360 + hp <- hp/360 + # calculate the length of each interval, dt, and number of steps to end of + # holding period + n <- numberSteps + dt <- time/n + m <- round(hp/dt) # number of steps to end of holding period + # + # calculate movements and associated probabilities + # + u <- exp(sigma*sqrt(dt)) + d <- 1/u + a <- exp(r*dt) + p <- (a-d)/(u-d) + jspan <- n*.5 + jspan <- -((jspan>=0)*floor(jspan)+(jspan<0)*ceiling(jspan)) # j-th node + # offset number + ispan <- round(time/dt)%%2 # i-th node offset number + i <- ispan:(n+ispan) # i-th node numbers + j <- jspan:(n+jspan) # j-th node numbers + + # expand i and j to eliminate for loop + jex <- matrix(rep(j, each=length(i)), ncol=length(i), byrow=TRUE) + iex <- matrix(rep(i, each=length(j)), nrow=length(j)) + # + # asset price at nodes, matrix is flipped so tree appears correct visually + pr <- t(apply(apply((s*(u^jex)*(d^(iex-jex))), 2, rev), 1, rev)) + # get upper triangle of pr + lower.tri(pr) + pr[lower.tri(pr)] <- 0 + # + # option valuation along tree + opt <- matrix(0,nrow(pr),ncol(pr)) + opt[,n+1] <- pmax(x-pr[,n+1],0) # determine final option value from + # underlying price + for(l in seq(n,1,by=-1)){ + k=1:l + # probable option values discounted back one time step + discopt=(p*opt[k,l+1]+(1-p)*opt[k+1,l+1])*exp(-r*dt) + # option value is max of X - current price or discopt + opt[,l]=c(pmax(x-pr[1:l,l],discopt),rep(0,n+1-l)) + } + # initial option price and number of options in portfolio + initialOptionPrice <- opt[1,1] + numberOptions <- amountInvested/initialOptionPrice + # option tree values at end of holding period + endHpOptionPrice <- opt[,m+1] + endHpOptionPrice <- endHpOptionPrice[1:(m+1)] + # returns<-(endHpOptionPrice-initialOptionPrice)/initialOptionPrice + # option position Profit and Loss + profitOrLoss <- (endHpOptionPrice-initialOptionPrice)*numberOptions + #compute VaR + VaR <- HSVaR(profitOrLoss, cl) + return(VaR) +} \ No newline at end of file From noreply at r-forge.r-project.org Wed Jul 29 01:06:04 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 29 Jul 2015 01:06:04 +0200 (CEST) Subject: [Returnanalytics-commits] r3872 - pkg/Dowd/man Message-ID: <20150728230604.41E311801C7@r-forge.r-project.org> Author: dacharya Date: 2015-07-29 01:06:03 +0200 (Wed, 29 Jul 2015) New Revision: 3872 Added: pkg/Dowd/man/AmericanPutPriceBinomial.Rd Log: Function AmericanPutPriceBinomial added. Added: pkg/Dowd/man/AmericanPutPriceBinomial.Rd =================================================================== --- pkg/Dowd/man/AmericanPutPriceBinomial.Rd (rev 0) +++ pkg/Dowd/man/AmericanPutPriceBinomial.Rd 2015-07-28 23:06:03 UTC (rev 3872) @@ -0,0 +1,42 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AmericanPutPriceBinomial.R +\name{AmericanPutPriceBinomial} +\alias{AmericanPutPriceBinomial} +\title{Binomial Put Price} +\usage{ +AmericanPutPriceBinomial(stockPrice, strike, r, sigma, maturity, numberSteps) +} +\arguments{ +\item{stockPrice}{Stock price of underlying stock} + +\item{strike}{Strike price of the option} + +\item{r}{Risk-free rate} + +\item{sigma}{Volatility of the underlying stock and is in annualised +term} + +\item{maturity}{The term to maturity of the option in days} + +\item{numberSteps}{The number of time-steps in the binomial tree} +} +\value{ +Binomial American put price +} +\description{ +Estimates the price of an American Put, using the binomial approach. +} +\examples{ +# Estimates the price of an American Put + AmericanPutPriceBinomial(27.2, 25, .03, .2, 60, 30) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +Mathematics, Algorithms, Cambridge University Press, 2002. +} + From noreply at r-forge.r-project.org Wed Jul 29 01:06:29 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 29 Jul 2015 01:06:29 +0200 (CEST) Subject: [Returnanalytics-commits] r3873 - pkg/Dowd/R Message-ID: <20150728230629.970DB1801C7@r-forge.r-project.org> Author: dacharya Date: 2015-07-29 01:06:29 +0200 (Wed, 29 Jul 2015) New Revision: 3873 Added: pkg/Dowd/R/AmericanPutPriceBinomial.R Log: Function AmericanPutPriceBinomial added. Added: pkg/Dowd/R/AmericanPutPriceBinomial.R =================================================================== --- pkg/Dowd/R/AmericanPutPriceBinomial.R (rev 0) +++ pkg/Dowd/R/AmericanPutPriceBinomial.R 2015-07-28 23:06:29 UTC (rev 3873) @@ -0,0 +1,61 @@ +#' Binomial Put Price +#' +#' Estimates the price of an American Put, using the binomial approach. +#' +#' @param stockPrice Stock price of underlying stock +#' @param strike Strike price of the option +#' @param r Risk-free rate +#' @param sigma Volatility of the underlying stock and is in annualised +#' term +#' @param maturity The term to maturity of the option in days +#' @param numberSteps The number of time-steps in the binomial tree +#' @return Binomial American put price +#' @references Dowd, Kevin. Measuring Market Risk, Wiley, 2007. +#' +#' Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +#' Mathematics, Algorithms, Cambridge University Press, 2002. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates the price of an American Put +#' AmericanPutPriceBinomial(27.2, 25, .03, .2, 60, 30) +#' +#' @export +AmericanPutPriceBinomial <- function(stockPrice, strike, r, sigma, + maturity, numberSteps){ + prob <- .5 # Probability of up-move, equal probability approach used + N <- numberSteps + maturity <- maturity/360 # Convert maturity to units of years + deltat <- maturity/N # Length of incremental steps + u <- 2*exp(r * deltat + 2 * sigma * sqrt(deltat)) / (exp(2 * sigma * sqrt(deltat)) + 1) # Up-move + d <- 2*exp(r * deltat) / (exp(2 * sigma * sqrt(deltat)) + 1) # Dowd-move + # Note that there up- and down- moves incorporate risk neutral approach + discount <- exp(-r * deltat) # Discount factor + # Stock price tree + S <- double(N+1) + S[1] <- stockPrice * (d ^ N) + for (i in 2:(N + 1)) { # i is number of up-moves plus 1 + S[i] <- S[i-1] * u * u + } + # Option price tree + # Terminal option values + x <- double(N + 1) + for (i in 1:(N + 1)) { + x[i] <- max(strike - S[i], 0) + } + # Option values prior to expiration + for (j in seq(N, 1, -1)) { + for (i in 1:j){ + x[i] <- discount * (prob * x[i + 1] + (1 - prob) * x[i]) + S[i] <- S[i] * u + # Check for early exercise + exerciseValue <- max(0, strike - S[i]) + if (exerciseValue > x[i]) { + x[i] <- exerciseValue + } + } + } + y <- x[1] # Initial option value + return(y) +} \ No newline at end of file From noreply at r-forge.r-project.org Wed Jul 29 01:11:16 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 29 Jul 2015 01:11:16 +0200 (CEST) Subject: [Returnanalytics-commits] r3874 - pkg/Dowd/man Message-ID: <20150728231116.9F28D18775A@r-forge.r-project.org> Author: dacharya Date: 2015-07-29 01:11:16 +0200 (Wed, 29 Jul 2015) New Revision: 3874 Added: pkg/Dowd/man/AmericanPutVaRBinomial.Rd Log: Function AmericanPutVaRBinomial added. Added: pkg/Dowd/man/AmericanPutVaRBinomial.Rd =================================================================== --- pkg/Dowd/man/AmericanPutVaRBinomial.Rd (rev 0) +++ pkg/Dowd/man/AmericanPutVaRBinomial.Rd 2015-07-28 23:11:16 UTC (rev 3874) @@ -0,0 +1,50 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/AmericanPutVaRBinomial.R +\name{AmericanPutVaRBinomial} +\alias{AmericanPutVaRBinomial} +\title{Estimates VaR of American vanilla put using binomial tree.} +\usage{ +AmericanPutVaRBinomial(amountInvested, stockPrice, strike, r, volatility, + maturity, numberSteps, cl, hp) +} +\arguments{ +\item{amountInvested}{Total amount paid for the Put Option.} + +\item{stockPrice}{Stock price of underlying stock.} + +\item{strike}{Strike price of the option.} + +\item{r}{Risk-free rate.} + +\item{volatility}{Volatility of the underlying stock.} + +\item{maturity}{Time to maturity of the option in days.} + +\item{numberSteps}{The number of time-steps considered for +the binomial model.} + +\item{cl}{Confidence level for which VaR is computed.} + +\item{hp}{Holding period of the option in days.} +} +\value{ +VaR of the American Put Option +} +\description{ +Estimates VaR of American Put Option using binomial tree to price the option +and historical method to compute the VaR. +} +\examples{ +# Market Risk of American Put with given parameters. + AmericanPutVaRBinomial(0.20, 27.2, 25, .16, .05, 60, 20, .95, 30) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +Mathematics, Algorithms, Cambridge University Press, 2002. +} + From noreply at r-forge.r-project.org Wed Jul 29 01:12:13 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 29 Jul 2015 01:12:13 +0200 (CEST) Subject: [Returnanalytics-commits] r3875 - pkg/Dowd Message-ID: <20150728231213.F1FA6187A45@r-forge.r-project.org> Author: dacharya Date: 2015-07-29 01:12:13 +0200 (Wed, 29 Jul 2015) New Revision: 3875 Modified: pkg/Dowd/NAMESPACE Log: Typo in function mamecorrected: AmericanPutVarBinomial to AmericanPutVaRBinomial Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-28 23:11:16 UTC (rev 3874) +++ pkg/Dowd/NAMESPACE 2015-07-28 23:12:13 UTC (rev 3875) @@ -7,7 +7,7 @@ export(AdjustedVarianceCovarianceVaR) export(AmericanPutESBinomial) export(AmericanPutPriceBinomial) -export(AmericanPutVarBinomial) +export(AmericanPutVaRBinomial) export(BinomialBacktest) export(BlancoIhleBacktest) export(BootstrapES) From noreply at r-forge.r-project.org Wed Jul 29 01:12:58 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 29 Jul 2015 01:12:58 +0200 (CEST) Subject: [Returnanalytics-commits] r3876 - pkg/Dowd/R Message-ID: <20150728231259.09D7F187A38@r-forge.r-project.org> Author: dacharya Date: 2015-07-29 01:12:58 +0200 (Wed, 29 Jul 2015) New Revision: 3876 Modified: pkg/Dowd/R/AmericanPutVaRBinomial.R Log: Small type in function name corrected. Modified: pkg/Dowd/R/AmericanPutVaRBinomial.R =================================================================== --- pkg/Dowd/R/AmericanPutVaRBinomial.R 2015-07-28 23:12:13 UTC (rev 3875) +++ pkg/Dowd/R/AmericanPutVaRBinomial.R 2015-07-28 23:12:58 UTC (rev 3876) @@ -23,10 +23,10 @@ #' @examples #' #' # Market Risk of American Put with given parameters. -#' AmericanPutVarBinomial(0.20, 27.2, 25, .16, .05, 60, 20, .95, 30) +#' AmericanPutVaRBinomial(0.20, 27.2, 25, .16, .05, 60, 20, .95, 30) #' #' @export -AmericanPutVarBinomial <- function(amountInvested, stockPrice, strike, r, +AmericanPutVaRBinomial <- function(amountInvested, stockPrice, strike, r, volatility, maturity, numberSteps, cl, hp){ s <- stockPrice x <- strike From noreply at r-forge.r-project.org Thu Jul 30 01:06:36 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 30 Jul 2015 01:06:36 +0200 (CEST) Subject: [Returnanalytics-commits] r3877 - pkg/Dowd Message-ID: <20150729230636.733B3187A5E@r-forge.r-project.org> Author: dacharya Date: 2015-07-30 01:06:35 +0200 (Thu, 30 Jul 2015) New Revision: 3877 Modified: pkg/Dowd/NAMESPACE Log: Functions BlackScholesPutPrice, BlackScholesPutESSim, BlackScholesCallPrice and BlackScholesCallESSim added. Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-28 23:12:58 UTC (rev 3876) +++ pkg/Dowd/NAMESPACE 2015-07-29 23:06:35 UTC (rev 3877) @@ -9,6 +9,10 @@ export(AmericanPutPriceBinomial) export(AmericanPutVaRBinomial) export(BinomialBacktest) +export(BlackScholesCallESSim) +export(BlackScholesCallPrice) +export(BlackScholesPutESSim) +export(BlackScholesPutPrice) export(BlancoIhleBacktest) export(BootstrapES) export(BootstrapESConfInterval) From noreply at r-forge.r-project.org Thu Jul 30 01:08:04 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 30 Jul 2015 01:08:04 +0200 (CEST) Subject: [Returnanalytics-commits] r3878 - pkg/Dowd/R Message-ID: <20150729230804.F23A6187A5E@r-forge.r-project.org> Author: dacharya Date: 2015-07-30 01:08:04 +0200 (Thu, 30 Jul 2015) New Revision: 3878 Added: pkg/Dowd/R/BlackScholesCallESSim.R Log: Function BlackScholesCallESSim added. Added: pkg/Dowd/R/BlackScholesCallESSim.R =================================================================== --- pkg/Dowd/R/BlackScholesCallESSim.R (rev 0) +++ pkg/Dowd/R/BlackScholesCallESSim.R 2015-07-29 23:08:04 UTC (rev 3878) @@ -0,0 +1,70 @@ +#' ES of Black-Scholes call using Monte Carlo Simulation +#' +#' Estimates ES of Black-Scholes call Option using Monte Carlo simulation +#' +#' @param amountInvested Total amount paid for the Call Option and is positive +#' (negative) if the option position is long (short) +#' @param stockPrice Stock price of underlying stock +#' @param strike Strike price of the option +#' @param r Risk-free rate +#' @param mu Expected rate of return on the underlying asset and is in +#' annualised term +#' @param sigma Volatility of the underlying stock and is in annualised +#' term +#' @param maturity The term to maturity of the option in days +#' @param numberTrials The number of interations in the Monte Carlo simulation +#' exercise +#' @param cl Confidence level for which ES is computed and is scalar +#' @param hp Holding period of the option in days and is scalar +#' @return ES +#' @references Dowd, Kevin. Measuring Market Risk, Wiley, 2007. +#' +#' Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +#' Mathematics, Algorithms, Cambridge University Press, 2002. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Market Risk of American call with given parameters. +#' BlackScholesCallESSim(0.20, 27.2, 25, .16, .2, .05, 60, 30, .95, 30) +#' +#' @export +BlackScholesCallESSim <- function(amountInvested, stockPrice, strike, r, mu, + sigma, maturity, numberTrials, cl, hp){ + # Precompute Constants + annualMaturity <- maturity / 360 # Annualised maturity + annualHp <- hp / 360 # Annualised holding period + N <- 1 # Number of steps - only one needed for black scholes option + dt <- annualHp / N # Size of time-increment equal to holding period + nudt <- (mu - .5 * sigma^2) * dt + sigmadt <- sigma * sqrt(dt) + lnS <- log(stockPrice) + M <- numberTrials + initialOptionPrice <- BlackScholesCallPrice(stockPrice, strike, + r, sigma, maturity) + numberOfOptions <- abs(amountInvested) / initialOptionPrice + # Stock price simulation process + lnSt <- matrix(0, M, N) + newStockPrice <- matrix(0, M, N) + for (i in 1:M){ + lnSt[i] <- lnS + rnorm(1, nudt, sigmadt) # Random stock price movement + newStockPrice[i] <- exp(lnSt[i, 1]) # New stock price + } + # Profit/Loss camculation + profitOrLoss <- double(M) + if (amountInvested > 0) { # If option position is long + for (i in 1:M) { + profitOrLoss[i] <- (BlackScholesCallPrice(newStockPrice[i], strike, r, + sigma, maturity - hp) - initialOptionPrice) * numberOfOptions + } + } + if (amountInvested < 0) { # If option position is short + for (i in 1:M) { + profitOrLoss[i] <- (-BlackScholesCallPrice(newStockPrice[i], strike, r, + sigma, maturity - hp) + initialOptionPrice) * numberOfOptions + } + } + # VaR estimation + y <- HSES(profitOrLoss, cl) # VaR + return(y) +} \ No newline at end of file From noreply at r-forge.r-project.org Thu Jul 30 01:08:59 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 30 Jul 2015 01:08:59 +0200 (CEST) Subject: [Returnanalytics-commits] r3879 - pkg/Dowd/man Message-ID: <20150729230859.D256A187A5E@r-forge.r-project.org> Author: dacharya Date: 2015-07-30 01:08:59 +0200 (Thu, 30 Jul 2015) New Revision: 3879 Added: pkg/Dowd/man/BlackScholesCallESSim.Rd Log: Function BlackScholesCallESSim added. Added: pkg/Dowd/man/BlackScholesCallESSim.Rd =================================================================== --- pkg/Dowd/man/BlackScholesCallESSim.Rd (rev 0) +++ pkg/Dowd/man/BlackScholesCallESSim.Rd 2015-07-29 23:08:59 UTC (rev 3879) @@ -0,0 +1,54 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BlackScholesCallESSim.R +\name{BlackScholesCallESSim} +\alias{BlackScholesCallESSim} +\title{ES of Black-Scholes call using Monte Carlo Simulation} +\usage{ +BlackScholesCallESSim(amountInvested, stockPrice, strike, r, mu, sigma, + maturity, numberTrials, cl, hp) +} +\arguments{ +\item{amountInvested}{Total amount paid for the Call Option and is positive +(negative) if the option position is long (short)} + +\item{stockPrice}{Stock price of underlying stock} + +\item{strike}{Strike price of the option} + +\item{r}{Risk-free rate} + +\item{mu}{Expected rate of return on the underlying asset and is in +annualised term} + +\item{sigma}{Volatility of the underlying stock and is in annualised +term} + +\item{maturity}{The term to maturity of the option in days} + +\item{numberTrials}{The number of interations in the Monte Carlo simulation +exercise} + +\item{cl}{Confidence level for which ES is computed and is scalar} + +\item{hp}{Holding period of the option in days and is scalar} +} +\value{ +ES +} +\description{ +Estimates ES of Black-Scholes call Option using Monte Carlo simulation +} +\examples{ +# Market Risk of American call with given parameters. + BlackScholesCallESSim(0.20, 27.2, 25, .16, .2, .05, 60, 30, .95, 30) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +Mathematics, Algorithms, Cambridge University Press, 2002. +} + From noreply at r-forge.r-project.org Thu Jul 30 01:09:50 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 30 Jul 2015 01:09:50 +0200 (CEST) Subject: [Returnanalytics-commits] r3880 - pkg/Dowd/R Message-ID: <20150729230950.6FCEE1800C9@r-forge.r-project.org> Author: dacharya Date: 2015-07-30 01:09:50 +0200 (Thu, 30 Jul 2015) New Revision: 3880 Added: pkg/Dowd/R/BlackScholesPutPrice.R Log: Function BlackScholesPutPrice added. Added: pkg/Dowd/R/BlackScholesPutPrice.R =================================================================== --- pkg/Dowd/R/BlackScholesPutPrice.R (rev 0) +++ pkg/Dowd/R/BlackScholesPutPrice.R 2015-07-29 23:09:50 UTC (rev 3880) @@ -0,0 +1,34 @@ +#' Price of European Put Option +#' +#' Derives the price of European call option using the Black-Scholes approach +#' +#' @param stockPrice Stock price of underlying stock +#' @param strike Strike price of the option +#' @param rf Risk-free rate and is annualised +#' @param sigma Volatility of the underlying stock +#' @param t The term to maturity of the option in years +#' @return Price of European Call Option +#' @references Dowd, Kevin. Measuring Market Risk, Wiley, 2007. +#' +#' Hull, John C.. Options, Futures, and Other Derivatives. 5th ed., p. 246. +#' +#' Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +#' Mathematics, Algorithms, Cambridge University Press, 2002. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates the price of an American Put +#' BlackScholesPutPrice(27.2, 25, .03, .2, 60) +#' +#' @export +BlackScholesPutPrice <- function(stockPrice, strike, rf, sigma, t){ + S <- stockPrice + X <- strike + # d terms + d1 <- (log(S/X) + (rf + (sigma ^ 2) / 2) * t) / (sigma * sqrt(t)) + d2 <- d1 - sigma * sqrt(t) + # Option price + y <- exp(- rf * t) * strike * pnorm( - d2) - stockPrice * pnorm(- d1) + return(y) +} \ No newline at end of file From noreply at r-forge.r-project.org Thu Jul 30 01:10:09 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 30 Jul 2015 01:10:09 +0200 (CEST) Subject: [Returnanalytics-commits] r3881 - pkg/Dowd/man Message-ID: <20150729231009.12C4C180535@r-forge.r-project.org> Author: dacharya Date: 2015-07-30 01:10:08 +0200 (Thu, 30 Jul 2015) New Revision: 3881 Added: pkg/Dowd/man/BlackScholesPutPrice.Rd Log: Function BlackScholesPutPrice added. Added: pkg/Dowd/man/BlackScholesPutPrice.Rd =================================================================== --- pkg/Dowd/man/BlackScholesPutPrice.Rd (rev 0) +++ pkg/Dowd/man/BlackScholesPutPrice.Rd 2015-07-29 23:10:08 UTC (rev 3881) @@ -0,0 +1,41 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BlackScholesPutPrice.R +\name{BlackScholesPutPrice} +\alias{BlackScholesPutPrice} +\title{Price of European Put Option} +\usage{ +BlackScholesPutPrice(stockPrice, strike, rf, sigma, t) +} +\arguments{ +\item{stockPrice}{Stock price of underlying stock} + +\item{strike}{Strike price of the option} + +\item{rf}{Risk-free rate and is annualised} + +\item{sigma}{Volatility of the underlying stock} + +\item{t}{The term to maturity of the option in years} +} +\value{ +Price of European Call Option +} +\description{ +Derives the price of European call option using the Black-Scholes approach +} +\examples{ +# Estimates the price of an American Put + BlackScholesPutPrice(27.2, 25, .03, .2, 60) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Hull, John C.. Options, Futures, and Other Derivatives. 5th ed., p. 246. + +Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +Mathematics, Algorithms, Cambridge University Press, 2002. +} + From noreply at r-forge.r-project.org Thu Jul 30 01:11:01 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 30 Jul 2015 01:11:01 +0200 (CEST) Subject: [Returnanalytics-commits] r3882 - pkg/Dowd/R Message-ID: <20150729231101.40A19180535@r-forge.r-project.org> Author: dacharya Date: 2015-07-30 01:11:01 +0200 (Thu, 30 Jul 2015) New Revision: 3882 Added: pkg/Dowd/R/BlackScholesPutESSim.R Log: Function BlackScholesPutESSim added. Added: pkg/Dowd/R/BlackScholesPutESSim.R =================================================================== --- pkg/Dowd/R/BlackScholesPutESSim.R (rev 0) +++ pkg/Dowd/R/BlackScholesPutESSim.R 2015-07-29 23:11:01 UTC (rev 3882) @@ -0,0 +1,70 @@ +#' ES of Black-Scholes put using Monte Carlo Simulation +#' +#' Estimates ES of Black-Scholes Put Option using Monte Carlo simulation +#' +#' @param amountInvested Total amount paid for the Put Option and is positive +#' (negative) if the option position is long (short) +#' @param stockPrice Stock price of underlying stock +#' @param strike Strike price of the option +#' @param r Risk-free rate +#' @param mu Expected rate of return on the underlying asset and is in +#' annualised term +#' @param sigma Volatility of the underlying stock and is in annualised +#' term +#' @param maturity The term to maturity of the option in days +#' @param numberTrials The number of interations in the Monte Carlo simulation +#' exercise +#' @param cl Confidence level for which ES is computed and is scalar +#' @param hp Holding period of the option in days and is scalar +#' @return ES +#' @references Dowd, Kevin. Measuring Market Risk, Wiley, 2007. +#' +#' Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +#' Mathematics, Algorithms, Cambridge University Press, 2002. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Market Risk of American Put with given parameters. +#' BlackScholesPutESSim(0.20, 27.2, 25, .03, .12, .05, 60, 1000, .95, 30) +#' +#' @export +BlackScholesPutESSim <- function(amountInvested, stockPrice, strike, r, mu, + sigma, maturity, numberTrials, cl, hp){ + # Precompute Constants + annualMaturity <- maturity / 360 # Annualised maturity + annualHp <- hp / 360 # Annualised holding period + N <- 1 # Number of steps - only one needed for black scholes option + dt <- annualHp / N # Size of time-increment equal to holding period + nudt <- (mu - .5 * sigma^2) * dt + sigmadt <- sigma * sqrt(dt) + lnS <- log(stockPrice) + M <- numberTrials + initialOptionPrice <- BlackScholesPutPrice(stockPrice, strike, + r, sigma, maturity) + numberOfOptions <- abs(amountInvested) / initialOptionPrice + # Stock price simulation process + lnSt <- matrix(0, M, N) + newStockPrice <- matrix(0, M, N) + for (i in 1:M){ + lnSt[i] <- lnS + rnorm(1, nudt, sigmadt) # Random stock price movement + newStockPrice[i] <- exp(lnSt[i, 1]) # New stock price + } + # Profit/Loss camculation + profitOrLoss <- double(M) + if (amountInvested > 0) { # If option position is long + for (i in 1:M) { + profitOrLoss[i] <- (BlackScholesPutPrice(newStockPrice[i], strike, r, + sigma, maturity - hp) - initialOptionPrice) * numberOfOptions + } + } + if (amountInvested < 0) { # If option position is short + for (i in 1:M) { + profitOrLoss[i] <- (-BlackScholesPutPrice(newStockPrice[i], strike, r, + sigma, maturity - hp) + initialOptionPrice) * numberOfOptions + } + } + # VaR estimation + y <- HSES(profitOrLoss, cl) # VaR + return(y) +} \ No newline at end of file From noreply at r-forge.r-project.org Thu Jul 30 01:11:18 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 30 Jul 2015 01:11:18 +0200 (CEST) Subject: [Returnanalytics-commits] r3883 - pkg/Dowd/man Message-ID: <20150729231118.D6BA8180535@r-forge.r-project.org> Author: dacharya Date: 2015-07-30 01:11:18 +0200 (Thu, 30 Jul 2015) New Revision: 3883 Added: pkg/Dowd/man/BlackScholesPutESSim.Rd Log: Function BlackScholesPutESSim added. Added: pkg/Dowd/man/BlackScholesPutESSim.Rd =================================================================== --- pkg/Dowd/man/BlackScholesPutESSim.Rd (rev 0) +++ pkg/Dowd/man/BlackScholesPutESSim.Rd 2015-07-29 23:11:18 UTC (rev 3883) @@ -0,0 +1,54 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BlackScholesPutESSim.R +\name{BlackScholesPutESSim} +\alias{BlackScholesPutESSim} +\title{ES of Black-Scholes put using Monte Carlo Simulation} +\usage{ +BlackScholesPutESSim(amountInvested, stockPrice, strike, r, mu, sigma, maturity, + numberTrials, cl, hp) +} +\arguments{ +\item{amountInvested}{Total amount paid for the Put Option and is positive +(negative) if the option position is long (short)} + +\item{stockPrice}{Stock price of underlying stock} + +\item{strike}{Strike price of the option} + +\item{r}{Risk-free rate} + +\item{mu}{Expected rate of return on the underlying asset and is in +annualised term} + +\item{sigma}{Volatility of the underlying stock and is in annualised +term} + +\item{maturity}{The term to maturity of the option in days} + +\item{numberTrials}{The number of interations in the Monte Carlo simulation +exercise} + +\item{cl}{Confidence level for which ES is computed and is scalar} + +\item{hp}{Holding period of the option in days and is scalar} +} +\value{ +ES +} +\description{ +Estimates ES of Black-Scholes Put Option using Monte Carlo simulation +} +\examples{ +# Market Risk of American Put with given parameters. + BlackScholesPutESSim(0.20, 27.2, 25, .03, .12, .05, 60, 1000, .95, 30) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +Mathematics, Algorithms, Cambridge University Press, 2002. +} + From noreply at r-forge.r-project.org Thu Jul 30 01:12:07 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 30 Jul 2015 01:12:07 +0200 (CEST) Subject: [Returnanalytics-commits] r3884 - pkg/Dowd/R Message-ID: <20150729231207.31572187AA6@r-forge.r-project.org> Author: dacharya Date: 2015-07-30 01:12:06 +0200 (Thu, 30 Jul 2015) New Revision: 3884 Added: pkg/Dowd/R/BlackScholesCallPrice.R Log: Function BlackScholesCallPrice added. Added: pkg/Dowd/R/BlackScholesCallPrice.R =================================================================== --- pkg/Dowd/R/BlackScholesCallPrice.R (rev 0) +++ pkg/Dowd/R/BlackScholesCallPrice.R 2015-07-29 23:12:06 UTC (rev 3884) @@ -0,0 +1,34 @@ +#' Price of European Call Option +#' +#' Derives the price of European call option using the Black-Scholes approach +#' +#' @param stockPrice Stock price of underlying stock +#' @param strike Strike price of the option +#' @param rf Risk-free rate and is annualised +#' @param sigma Volatility of the underlying stock +#' @param t The term to maturity of the option in years +#' @return Price of European Call Option +#' @references Dowd, Kevin. Measuring Market Risk, Wiley, 2007. +#' +#' Hull, John C.. Options, Futures, and Other Derivatives. 5th ed., p. 246. +#' +#' Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +#' Mathematics, Algorithms, Cambridge University Press, 2002. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates the price of an American Put +#' BlackScholesCallPrice(27.2, 25, .03, .2, 60) +#' +#' @export +BlackScholesCallPrice <- function(stockPrice, strike, rf, sigma, t){ + S <- stockPrice + X <- strike + # d terms + d1 <- (log(S/X) + (rf + (sigma ^ 2) / 2) * t) / (sigma * sqrt(t)) + d2 <- d1 - sigma * sqrt(t) + # Option price + y <- stockPrice * pnorm(d1) - exp(- rf * t) * strike * pnorm(d2) + return(y) +} \ No newline at end of file From noreply at r-forge.r-project.org Thu Jul 30 01:12:24 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 30 Jul 2015 01:12:24 +0200 (CEST) Subject: [Returnanalytics-commits] r3885 - pkg/Dowd/man Message-ID: <20150729231224.6BAAA187AA6@r-forge.r-project.org> Author: dacharya Date: 2015-07-30 01:12:23 +0200 (Thu, 30 Jul 2015) New Revision: 3885 Added: pkg/Dowd/man/BlackScholesCallPrice.Rd Log: Function BlackScholesCallPrice added. Added: pkg/Dowd/man/BlackScholesCallPrice.Rd =================================================================== --- pkg/Dowd/man/BlackScholesCallPrice.Rd (rev 0) +++ pkg/Dowd/man/BlackScholesCallPrice.Rd 2015-07-29 23:12:23 UTC (rev 3885) @@ -0,0 +1,41 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/BlackScholesCallPrice.R +\name{BlackScholesCallPrice} +\alias{BlackScholesCallPrice} +\title{Price of European Call Option} +\usage{ +BlackScholesCallPrice(stockPrice, strike, rf, sigma, t) +} +\arguments{ +\item{stockPrice}{Stock price of underlying stock} + +\item{strike}{Strike price of the option} + +\item{rf}{Risk-free rate and is annualised} + +\item{sigma}{Volatility of the underlying stock} + +\item{t}{The term to maturity of the option in years} +} +\value{ +Price of European Call Option +} +\description{ +Derives the price of European call option using the Black-Scholes approach +} +\examples{ +# Estimates the price of an American Put + BlackScholesCallPrice(27.2, 25, .03, .2, 60) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Hull, John C.. Options, Futures, and Other Derivatives. 5th ed., p. 246. + +Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +Mathematics, Algorithms, Cambridge University Press, 2002. +} + From noreply at r-forge.r-project.org Fri Jul 31 11:21:53 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 31 Jul 2015 11:21:53 +0200 (CEST) Subject: [Returnanalytics-commits] r3886 - pkg/Dowd Message-ID: <20150731092153.7C35D183CD2@r-forge.r-project.org> Author: dacharya Date: 2015-07-31 11:21:52 +0200 (Fri, 31 Jul 2015) New Revision: 3886 Modified: pkg/Dowd/NAMESPACE Log: Functions LongBlackScholesPutVaR, LongBlackScholesCallVaR, ShortBlackScholesCallVaR, ShortBlackScholesPutVaR added Modified: pkg/Dowd/NAMESPACE =================================================================== --- pkg/Dowd/NAMESPACE 2015-07-29 23:12:23 UTC (rev 3885) +++ pkg/Dowd/NAMESPACE 2015-07-31 09:21:52 UTC (rev 3886) @@ -88,6 +88,8 @@ export(LogtVaRPlot2DCL) export(LogtVaRPlot2DHP) export(LogtVaRPlot3D) +export(LongBlackScholesCallVaR) +export(LongBlackScholesPutVaR) export(LopezBacktest) export(MEFPlot) export(NormalES) @@ -114,6 +116,8 @@ export(PickandsEstimator) export(PickandsPlot) export(ProductCopulaVaR) +export(ShortBlackScholesCallVaR) +export(ShortBlackScholesPutVaR) export(TQQPlot) export(tES) export(tESDFPerc) From noreply at r-forge.r-project.org Fri Jul 31 11:23:53 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 31 Jul 2015 11:23:53 +0200 (CEST) Subject: [Returnanalytics-commits] r3887 - pkg/Dowd/R Message-ID: <20150731092353.6E938183CD2@r-forge.r-project.org> Author: dacharya Date: 2015-07-31 11:23:53 +0200 (Fri, 31 Jul 2015) New Revision: 3887 Added: pkg/Dowd/R/LongBlackScholesCallVaR.R Log: Function LongBlackScholesCallVaR added. Added: pkg/Dowd/R/LongBlackScholesCallVaR.R =================================================================== --- pkg/Dowd/R/LongBlackScholesCallVaR.R (rev 0) +++ pkg/Dowd/R/LongBlackScholesCallVaR.R 2015-07-31 09:23:53 UTC (rev 3887) @@ -0,0 +1,42 @@ +#' Derives VaR of a long Black Scholes call option +#' +#' Function derives the VaR of a long Black Scholes call for specified +#' confidence level and holding period, using analytical solution. +#' +#' @param stockPrice Stock price of underlying stock +#' @param strike Strike price of the option +#' @param r Risk-free rate and is annualised +#' @param mu Mean return +#' @param sigma Volatility of the underlying stock +#' @param maturity Term to maturity and is expressed in days +#' @param cl Confidence level and is scalar +#' @param hp Holding period and is scalar and is expressed in days +#' @return Price of European Call Option +#' @references Dowd, Kevin. Measuring Market Risk, Wiley, 2007. +#' +#' Hull, John C.. Options, Futures, and Other Derivatives. 4th ed., Upper Saddle +#' River, NJ: Prentice Hall, 200, ch. 11. +#' +#' Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +#' Mathematics, Algorithms, Cambridge University Press, 2002. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates the price of an American Put +#' LongBlackScholesCallVaR(27.2, 25, .03, .12, .2, 60, .95, 40) +#' +#' @export +LongBlackScholesCallVaR <- function(stockPrice, strike, r, mu, sigma, + maturity, cl, hp){ + # Simplify notation + t <- maturity/360 + hp <- hp/360 + currentOptionPrice <- BlackScholesCallPrice(stockPrice, strike, r, sigma, t) + sStar <- exp(log(stockPrice) + (mu - (sigma ^ 2)/2) * hp - + qnorm(cl, 0, 1) * sigma * sqrt(hp)) + # Critical future stock price, see Hull, p. 238 + futureOptionPriceStar <- BlackScholesCallPrice(sStar, strike, r, sigma, t - hp) + y <- currentOptionPrice - futureOptionPriceStar + return(y) +} \ No newline at end of file From noreply at r-forge.r-project.org Fri Jul 31 11:24:14 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 31 Jul 2015 11:24:14 +0200 (CEST) Subject: [Returnanalytics-commits] r3888 - pkg/Dowd/man Message-ID: <20150731092414.72A02183CD2@r-forge.r-project.org> Author: dacharya Date: 2015-07-31 11:24:14 +0200 (Fri, 31 Jul 2015) New Revision: 3888 Added: pkg/Dowd/man/LongBlackScholesCallVaR.Rd Log: Function LongBlackScholesCallVaR added. Added: pkg/Dowd/man/LongBlackScholesCallVaR.Rd =================================================================== --- pkg/Dowd/man/LongBlackScholesCallVaR.Rd (rev 0) +++ pkg/Dowd/man/LongBlackScholesCallVaR.Rd 2015-07-31 09:24:14 UTC (rev 3888) @@ -0,0 +1,49 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LongBlackScholesCallVaR.R +\name{LongBlackScholesCallVaR} +\alias{LongBlackScholesCallVaR} +\title{Derives VaR of a long Black Scholes call option} +\usage{ +LongBlackScholesCallVaR(stockPrice, strike, r, mu, sigma, maturity, cl, hp) +} +\arguments{ +\item{stockPrice}{Stock price of underlying stock} + +\item{strike}{Strike price of the option} + +\item{r}{Risk-free rate and is annualised} + +\item{mu}{Mean return} + +\item{sigma}{Volatility of the underlying stock} + +\item{maturity}{Term to maturity and is expressed in days} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar and is expressed in days} +} +\value{ +Price of European Call Option +} +\description{ +Function derives the VaR of a long Black Scholes call for specified +confidence level and holding period, using analytical solution. +} +\examples{ +# Estimates the price of an American Put + LongBlackScholesCallVaR(27.2, 25, .03, .12, .2, 60, .95, 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Hull, John C.. Options, Futures, and Other Derivatives. 4th ed., Upper Saddle +River, NJ: Prentice Hall, 200, ch. 11. + +Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +Mathematics, Algorithms, Cambridge University Press, 2002. +} + From noreply at r-forge.r-project.org Fri Jul 31 11:24:49 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 31 Jul 2015 11:24:49 +0200 (CEST) Subject: [Returnanalytics-commits] r3889 - pkg/Dowd/R Message-ID: <20150731092449.9B4A4183CD2@r-forge.r-project.org> Author: dacharya Date: 2015-07-31 11:24:49 +0200 (Fri, 31 Jul 2015) New Revision: 3889 Added: pkg/Dowd/R/LongBlackScholesPutVaR.R Log: Function LongBlackScholesPutVaR added. Added: pkg/Dowd/R/LongBlackScholesPutVaR.R =================================================================== --- pkg/Dowd/R/LongBlackScholesPutVaR.R (rev 0) +++ pkg/Dowd/R/LongBlackScholesPutVaR.R 2015-07-31 09:24:49 UTC (rev 3889) @@ -0,0 +1,42 @@ +#' Derives VaR of a long Black Scholes put option +#' +#' Function derives the VaR of a long Black Scholes put for specified +#' confidence level and holding period, using analytical solution. +#' +#' @param stockPrice Stock price of underlying stock +#' @param strike Strike price of the option +#' @param r Risk-free rate and is annualised +#' @param mu Mean return +#' @param sigma Volatility of the underlying stock +#' @param maturity Term to maturity and is expressed in days +#' @param cl Confidence level and is scalar +#' @param hp Holding period and is scalar and is expressed in days +#' @return Price of European put Option +#' @references Dowd, Kevin. Measuring Market Risk, Wiley, 2007. +#' +#' Hull, John C.. Options, Futures, and Other Derivatives. 4th ed., Upper Saddle +#' River, NJ: Prentice Hall, 200, ch. 11. +#' +#' Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +#' Mathematics, Algorithms, Cambridge University Press, 2002. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates the price of an American Put +#' LongBlackScholesPutVaR(27.2, 25, .03, .12, .2, 60, .95, 40) +#' +#' @export +LongBlackScholesPutVaR <- function(stockPrice, strike, r, mu, sigma, + maturity, cl, hp){ + # Simplify notation + t <- maturity/360 + hp <- hp/360 + currentOptionPrice <- BlackScholesPutPrice(stockPrice, strike, r, sigma, t) + sStar <- exp(log(stockPrice) + (mu - (sigma ^ 2)/2) * hp + + qnorm(cl, 0, 1) * sigma * sqrt(hp)) + # Critical future stock price, see Hull, p. 238 + futureOptionPriceStar <- BlackScholesPutPrice(sStar, strike, r, sigma, t - hp) + y <- currentOptionPrice - futureOptionPriceStar + return(y) +} \ No newline at end of file From noreply at r-forge.r-project.org Fri Jul 31 11:25:11 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 31 Jul 2015 11:25:11 +0200 (CEST) Subject: [Returnanalytics-commits] r3890 - pkg/Dowd/man Message-ID: <20150731092511.AAF5C183CD2@r-forge.r-project.org> Author: dacharya Date: 2015-07-31 11:25:11 +0200 (Fri, 31 Jul 2015) New Revision: 3890 Added: pkg/Dowd/man/LongBlackScholesPutVaR.Rd Log: Function LongBlackScholesPutVaR added. Added: pkg/Dowd/man/LongBlackScholesPutVaR.Rd =================================================================== --- pkg/Dowd/man/LongBlackScholesPutVaR.Rd (rev 0) +++ pkg/Dowd/man/LongBlackScholesPutVaR.Rd 2015-07-31 09:25:11 UTC (rev 3890) @@ -0,0 +1,49 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/LongBlackScholesPutVaR.R +\name{LongBlackScholesPutVaR} +\alias{LongBlackScholesPutVaR} +\title{Derives VaR of a long Black Scholes put option} +\usage{ +LongBlackScholesPutVaR(stockPrice, strike, r, mu, sigma, maturity, cl, hp) +} +\arguments{ +\item{stockPrice}{Stock price of underlying stock} + +\item{strike}{Strike price of the option} + +\item{r}{Risk-free rate and is annualised} + +\item{mu}{Mean return} + +\item{sigma}{Volatility of the underlying stock} + +\item{maturity}{Term to maturity and is expressed in days} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar and is expressed in days} +} +\value{ +Price of European put Option +} +\description{ +Function derives the VaR of a long Black Scholes put for specified +confidence level and holding period, using analytical solution. +} +\examples{ +# Estimates the price of an American Put + LongBlackScholesPutVaR(27.2, 25, .03, .12, .2, 60, .95, 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Hull, John C.. Options, Futures, and Other Derivatives. 4th ed., Upper Saddle +River, NJ: Prentice Hall, 200, ch. 11. + +Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +Mathematics, Algorithms, Cambridge University Press, 2002. +} + From noreply at r-forge.r-project.org Fri Jul 31 11:26:01 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 31 Jul 2015 11:26:01 +0200 (CEST) Subject: [Returnanalytics-commits] r3891 - pkg/Dowd/R Message-ID: <20150731092601.9CC94183CD2@r-forge.r-project.org> Author: dacharya Date: 2015-07-31 11:26:01 +0200 (Fri, 31 Jul 2015) New Revision: 3891 Added: pkg/Dowd/R/ShortBlackScholesPutVaR.R Log: Function ShortBlackScholesPutVaR added. Added: pkg/Dowd/R/ShortBlackScholesPutVaR.R =================================================================== --- pkg/Dowd/R/ShortBlackScholesPutVaR.R (rev 0) +++ pkg/Dowd/R/ShortBlackScholesPutVaR.R 2015-07-31 09:26:01 UTC (rev 3891) @@ -0,0 +1,42 @@ +#' Derives VaR of a short Black Scholes put option +#' +#' Function derives the VaR of a Short Black Scholes put for specified +#' confidence level and holding period, using analytical solution. +#' +#' @param stockPrice Stock price of underlying stock +#' @param strike Strike price of the option +#' @param r Risk-free rate and is annualised +#' @param mu Mean return +#' @param sigma Volatility of the underlying stock +#' @param maturity Term to maturity and is expressed in days +#' @param cl Confidence level and is scalar +#' @param hp Holding period and is scalar and is expressed in days +#' @return Price of European put Option +#' @references Dowd, Kevin. Measuring Market Risk, Wiley, 2007. +#' +#' Hull, John C.. Options, Futures, and Other Derivatives. 4th ed., Upper Saddle +#' River, NJ: Prentice Hall, 200, ch. 11. +#' +#' Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +#' Mathematics, Algorithms, Cambridge University Press, 2002. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Derives VaR of a short Black Scholes put option +#' ShortBlackScholesPutVaR(27.2, 25, .03, .12, .2, 60, .95, 40) +#' +#' @export +ShortBlackScholesPutVaR <- function(stockPrice, strike, r, mu, sigma, + maturity, cl, hp){ + # Simplify notation + t <- maturity/360 + hp <- hp/360 + currentOptionPrice <- BlackScholesPutPrice(stockPrice, strike, r, sigma, t) + sStar <- exp(log(stockPrice) + (mu - (sigma ^ 2)/2) * hp - + qnorm(cl, 0, 1) * sigma * sqrt(hp)) + # Critical future stock price, see Hull, p. 238 + futureOptionPriceStar <- BlackScholesPutPrice(sStar, strike, r, sigma, t - hp) + y <- - currentOptionPrice + futureOptionPriceStar + return(y) +} \ No newline at end of file From noreply at r-forge.r-project.org Fri Jul 31 11:26:27 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 31 Jul 2015 11:26:27 +0200 (CEST) Subject: [Returnanalytics-commits] r3892 - pkg/Dowd/man Message-ID: <20150731092627.AD1B6183CD2@r-forge.r-project.org> Author: dacharya Date: 2015-07-31 11:26:27 +0200 (Fri, 31 Jul 2015) New Revision: 3892 Added: pkg/Dowd/man/ShortBlackScholesPutVaR.Rd Log: Function ShortBlackScholesPutVaR added. Added: pkg/Dowd/man/ShortBlackScholesPutVaR.Rd =================================================================== --- pkg/Dowd/man/ShortBlackScholesPutVaR.Rd (rev 0) +++ pkg/Dowd/man/ShortBlackScholesPutVaR.Rd 2015-07-31 09:26:27 UTC (rev 3892) @@ -0,0 +1,49 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/ShortBlackScholesPutVaR.R +\name{ShortBlackScholesPutVaR} +\alias{ShortBlackScholesPutVaR} +\title{Derives VaR of a short Black Scholes put option} +\usage{ +ShortBlackScholesPutVaR(stockPrice, strike, r, mu, sigma, maturity, cl, hp) +} +\arguments{ +\item{stockPrice}{Stock price of underlying stock} + +\item{strike}{Strike price of the option} + +\item{r}{Risk-free rate and is annualised} + +\item{mu}{Mean return} + +\item{sigma}{Volatility of the underlying stock} + +\item{maturity}{Term to maturity and is expressed in days} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar and is expressed in days} +} +\value{ +Price of European put Option +} +\description{ +Function derives the VaR of a Short Black Scholes put for specified +confidence level and holding period, using analytical solution. +} +\examples{ +# Derives VaR of a short Black Scholes put option + ShortBlackScholesPutVaR(27.2, 25, .03, .12, .2, 60, .95, 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Hull, John C.. Options, Futures, and Other Derivatives. 4th ed., Upper Saddle +River, NJ: Prentice Hall, 200, ch. 11. + +Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +Mathematics, Algorithms, Cambridge University Press, 2002. +} + From noreply at r-forge.r-project.org Fri Jul 31 11:27:05 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 31 Jul 2015 11:27:05 +0200 (CEST) Subject: [Returnanalytics-commits] r3893 - pkg/Dowd/R Message-ID: <20150731092705.9790C183CD2@r-forge.r-project.org> Author: dacharya Date: 2015-07-31 11:27:05 +0200 (Fri, 31 Jul 2015) New Revision: 3893 Added: pkg/Dowd/R/ShortBlackScholesCallVaR.R Log: Function ShortBlackScholesCallVaR added. Added: pkg/Dowd/R/ShortBlackScholesCallVaR.R =================================================================== --- pkg/Dowd/R/ShortBlackScholesCallVaR.R (rev 0) +++ pkg/Dowd/R/ShortBlackScholesCallVaR.R 2015-07-31 09:27:05 UTC (rev 3893) @@ -0,0 +1,42 @@ +#' Derives VaR of a short Black Scholes call option +#' +#' Function derives the VaR of a short Black Scholes call for specified +#' confidence level and holding period, using analytical solution. +#' +#' @param stockPrice Stock price of underlying stock +#' @param strike Strike price of the option +#' @param r Risk-free rate and is annualised +#' @param mu Mean return +#' @param sigma Volatility of the underlying stock +#' @param maturity Term to maturity and is expressed in days +#' @param cl Confidence level and is scalar +#' @param hp Holding period and is scalar and is expressed in days +#' @return Price of European Call Option +#' @references Dowd, Kevin. Measuring Market Risk, Wiley, 2007. +#' +#' Hull, John C.. Options, Futures, and Other Derivatives. 4th ed., Upper Saddle +#' River, NJ: Prentice Hall, 200, ch. 11. +#' +#' Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +#' Mathematics, Algorithms, Cambridge University Press, 2002. +#' +#' @author Dinesh Acharya +#' @examples +#' +#' # Estimates the price of an American Put +#' ShortBlackScholesCallVaR(27.2, 25, .03, .12, .2, 60, .95, 40) +#' +#' @export +ShortBlackScholesCallVaR <- function(stockPrice, strike, r, mu, sigma, + maturity, cl, hp){ + # Simplify notation + t <- maturity/360 + hp <- hp/360 + currentOptionPrice <- BlackScholesCallPrice(stockPrice, strike, r, sigma, t) + sStar <- exp(log(stockPrice) + (mu - (sigma ^ 2)/2) * hp + + qnorm(cl, 0, 1) * sigma * sqrt(hp)) + # Critical future stock price, see Hull, p. 238 + futureOptionPriceStar <- BlackScholesCallPrice(sStar, strike, r, sigma, t - hp) + y <- - currentOptionPrice + futureOptionPriceStar + return(y) +} \ No newline at end of file From noreply at r-forge.r-project.org Fri Jul 31 11:27:25 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 31 Jul 2015 11:27:25 +0200 (CEST) Subject: [Returnanalytics-commits] r3894 - pkg/Dowd/man Message-ID: <20150731092725.7D09D183CD2@r-forge.r-project.org> Author: dacharya Date: 2015-07-31 11:27:25 +0200 (Fri, 31 Jul 2015) New Revision: 3894 Added: pkg/Dowd/man/ShortBlackScholesCallVaR.Rd Log: Function ShortBlackScholesCallVaR added. Added: pkg/Dowd/man/ShortBlackScholesCallVaR.Rd =================================================================== --- pkg/Dowd/man/ShortBlackScholesCallVaR.Rd (rev 0) +++ pkg/Dowd/man/ShortBlackScholesCallVaR.Rd 2015-07-31 09:27:25 UTC (rev 3894) @@ -0,0 +1,49 @@ +% Generated by roxygen2 (4.1.1): do not edit by hand +% Please edit documentation in R/ShortBlackScholesCallVaR.R +\name{ShortBlackScholesCallVaR} +\alias{ShortBlackScholesCallVaR} +\title{Derives VaR of a short Black Scholes call option} +\usage{ +ShortBlackScholesCallVaR(stockPrice, strike, r, mu, sigma, maturity, cl, hp) +} +\arguments{ +\item{stockPrice}{Stock price of underlying stock} + +\item{strike}{Strike price of the option} + +\item{r}{Risk-free rate and is annualised} + +\item{mu}{Mean return} + +\item{sigma}{Volatility of the underlying stock} + +\item{maturity}{Term to maturity and is expressed in days} + +\item{cl}{Confidence level and is scalar} + +\item{hp}{Holding period and is scalar and is expressed in days} +} +\value{ +Price of European Call Option +} +\description{ +Function derives the VaR of a short Black Scholes call for specified +confidence level and holding period, using analytical solution. +} +\examples{ +# Estimates the price of an American Put + ShortBlackScholesCallVaR(27.2, 25, .03, .12, .2, 60, .95, 40) +} +\author{ +Dinesh Acharya +} +\references{ +Dowd, Kevin. Measuring Market Risk, Wiley, 2007. + +Hull, John C.. Options, Futures, and Other Derivatives. 4th ed., Upper Saddle +River, NJ: Prentice Hall, 200, ch. 11. + +Lyuu, Yuh-Dauh. Financial Engineering & Computation: Principles, +Mathematics, Algorithms, Cambridge University Press, 2002. +} +