R Functions to Calculate VaR 5% and VaR 1%

We'll use the following libraries:

library(fBasics)
library(tseries)

Below are the var5 and var1 functions.

## var5 and var 1 functions ## x is the stock ticker in quotes and y in the
## number of calendar days of history
var5 <- function(x, y) {

    x <- get.hist.quote(x, start = (Sys.Date() - y), quote = "Close")
    x <- ts(x)
    r <- log(x[2:(length(x))]/x[1:(length(x) - 1)])
    emp.var <- quantile(r, probs = 0.05) * 1e+06
    cat("The empirical VaR is", emp.var, "\n")
    cat("The VaR assuming a normal distribution is", quantile(rnorm(5e+05, mean = mean(r), 
        sd = sd(r)), probs = 0.05) * 1e+06, "\n")
    rm(x)
    rm(r)
}

var1 <- function(x, y) {

    x <- get.hist.quote(x, start = (Sys.Date() - y), quote = "Close")
    x <- ts(x)
    r <- log(x[2:(length(x))]/x[1:(length(x) - 1)])
    emp.var <- quantile(r, probs = 0.01) * 1e+06
    cat("The empirical VaR is", emp.var, "\n")
    cat("The VaR assuming a normal distribution is", quantile(rnorm(5e+05, mean = mean(r), 
        sd = sd(r)), probs = 0.01) * 1e+06, "\n")
    rm(x)
    rm(r)
}

Note the functions assume we have $1,000,000 invested in the asset. We can use the functions like:

var5("goog", 250)
## The empirical VaR is -14335 
## The VaR assuming a normal distribution is -21255

and

var1("ge", 340)
## The empirical VaR is -30014 
## The VaR assuming a normal distribution is -24945

These functions output VaR estimates using both the historical empirical density function and a normal density (with a mean and standard deviation based on the historical data).