Historical VaR – R Code

This is a code for calculating the historical Value at Risk of a portfolio consisting of one stock. The same concept can be applied on portfolios involving multiple stocks or even multiple investments in a number of different asset classes.

## Historical VaR

# clear environment and console
rm(list = ls())
cat("\014")

# create a random vector of stock prices
St = matrix(runif(252, 10, 13), nrow = 252, ncol = 1)

# calculate log returns
ln = log(St)
ln[is.na(ln)] <- 0
ret = as.matrix(diff(as.matrix(ln, lag=1, difference=1)))

# inputs
p = 1000 # number of shares held
a = 0.95 # confidence level 5%

# calculate value at risk
value = St[1,1] * p # value of portfolio
vol = var(St) # daily volatility of stock price
avg = mean(St) # daily average stock price
VAR = abs(quantile(ret, 1 - a) * value)
VAR

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s