[Returnanalytics-commits] r3862 - pkg/Dowd/R
noreply at r-forge.r-project.org
noreply at r-forge.r-project.org
Tue Jul 28 10:15:23 CEST 2015
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)
+
+}
More information about the Returnanalytics-commits
mailing list