Académique Documents
Professionnel Documents
Culture Documents
#
#
#
#
#
#
#
#
#
#
#
#
econ589riskMeasures.r
R examples for lectures on estimating risk measures
Eric Zivot
April 2nd, 2012
update history
April 23rd, 2013
Fixed reversal of axis labels in scatterplot
April 17th, 2012
Added risk analysis from multivariate distribution examples
April 16th, 2012
Added multivariate distribution examples
# load libraries
library(PerformanceAnalytics)
library(quantmod)
library(MASS)
library(mvtnorm)
library(mnormt)
options(digits=4)
#
# Example: Normal VaR
#
mu = 10
sigma = 100
alpha = 0.95
VaR.alpha = qnorm(alpha, mu, sigma)
VaR.alpha
# alternative approach
VaR.alpha = mu + sigma*qnorm(alpha,0,1)
VaR.alpha
#
# Example: normal ES
#
mu = 10
sigma = 100
alpha = 0.95
q.alpha.z = qnorm(alpha)
ES.alpha = mu + sigma*(dnorm(q.alpha.z)/(1-alpha))
ES.alpha
#
# Estimating risk measures
#
# download data
symbol.vec = c("MSFT", "^GSPC")
getSymbols(symbol.vec, from ="2000-01-03", to = "2012-04-03")
colnames(MSFT)
start(MSFT)
end(MSFT)
# extract adjusted closing prices
MSFT = MSFT[, "MSFT.Adjusted", drop=F]
cr.vol = w * mcr.vol
pcr.vol = cr.vol / sigma.p.hat
cbind(mcr.vol, cr.vol, pcr.vol)
# check
sigma.p.hat
sum(cr.vol)
sum(pcr.vol)
# using PerformanceAnalytics function StdDev
StdDev(MSFT.GSPC.ret, portfolio_method="component",
weights=c(0.5, 0.5))
#
# nonparametric measures of risk budgets
#
# VaR
VaR(port.ret, p=0.95, method="historical")
VaR(port.ret, p=0.99, method="historical")
# ES
ES(port.ret, p=0.95, method="historical")
ES(port.ret, p=0.99, method="historical")
#
# Bivariate distributions for MSFT and GPSC
#
# Empirical scatterplots
plot(coredata(MSFT.ret), coredata(GSPC.ret),
main="Empirical Bivariate Distribution of Returns",
ylab="GSPC", xlab="MSFT", col="blue")
abline(h=mean(GSPC.ret), v=mean(MSFT.ret))
# empirical portfolio return distribution
chart.Histogram(port.ret, main="Equally Weighted Portfolio", methods=c("add.norm
al", "add.qqplot"))
# simulate from fitted multivariate normal distribution
# method 1: use mvtnorm package
library(mvtnorm)
n.obs = nrow(MSFT.GSPC.ret)
# estimate mean and covariance
mu.hat = apply(MSFT.GSPC.ret, 2, mean)
Sigma.hat = cov(MSFT.GSPC.ret)
Cor.hat = cov2cor(Sigma.hat)
mu.hat
Sigma.hat
Cor.hat
set.seed(123)
sim.ret = rmvnorm(n.obs, mean=mu.hat, sigma=Sigma.hat, method="chol")
# scaterplot of simulated returns
plot(sim.ret[,1], sim.ret[,2],
main="Simulated Bivariate Normal Distribution of Returns",
ylab="GSPC", xlab="MSFT", col="blue")
abline(v=mean(sim.ret[,1]), h=mean(sim.ret[,2]))
set.seed(123)
Z = rmvnorm(n=n.obs, mean=c(0,0), sigma=Sigma.mle.t(v.mle/(v.mle - 2)))
# generate W ~ chi-sq(v.mle)
W = rchisq(n.obs,df=v.mle)
# simulate bivariate t
sim.ret.t = mu.mle.t + sqrt(v.mle/W)*Z
colnames(sim.ret.t) = c("MSFT","GSPC")
# plot simulated data together with actual returns
plot(coredata(MSFT.ret),coredata(GSPC.ret),
main="Empirical vs. Bivariate t",
ylab="GSPC", xlab="MSFT", col="blue")
abline(h=mean(GSPC.ret), v=mean(MSFT.ret))
points(sim.ret.t, col="red")
legend(x="topleft", legend=c("Empirical", "Multivariate t"), col=c("blue", "red"
), pch=1)
# compute simulated returns
port.ret.sim.t = 0.5*sim.ret.t[,"MSFT"] + 0.5*sim.ret.t[,"GSPC"]
chart.Histogram(port.ret.sim.t, main="Equally Weighted Portfolio: Student's t",
methods=c("add.normal", "add.qqplot"))
# calculate VaR and ES from simulated returns
# volatility
StdDev(port.ret.sim.t)
# VaR
VaR(port.ret.sim.t, p = 0.95, method="historical")
VaR(port.ret.sim.t, p = 0.99, method="historical")
# ES
ES(port.ret.sim.t, p = 0.95, method="historical")
ES(port.ret.sim.t, p = 0.99, method="historical")
# ES risk budgets
# note: ES seems to choke if data is passed in as a matrix without rownames
rownames(sim.ret.t) = as.character(index(MSFT.ret))
names(port.ret.sim.t) = rownames(sim.ret.t)
sim.ret.t = zoo(sim.ret.t, as.Date(rownames(sim.ret.t)))
port.ret.sim.t = zoo(port.ret.sim.t, as.Date(names(port.ret.sim.t)))
# rownames(sim.ret.t) = as.character(1:n.obs)
port.ES.decomp = ES(sim.ret.t, p=0.95, weights=c(0.5, 0.5),
portfolio_method="component", method="historical")
VaR.p = quantile(port.ret.sim.t, prob=0.05)
idx = which(port.ret.sim.t <= VaR.p)
mcES = port.ES.decomp[["realizedcontrib"]]*port.ES.decomp[["-r_exceed/c_exceed"]
]/0.5
# mcETL plot for MSFT
par(mfrow=c(2,1))
# plot fund data with VaR violations
plot.zoo(port.ret.sim.t, type="b", main="Portfolio Returns and 5% VaR Violations
",
col="blue", ylab="Returns")
abline(h=0)
abline(h=VaR.p, lwd=2, col="red")
points(port.ret.sim.t[idx], type="p", pch=16, col="red")
# plot factor data and highlight obvs associated with R <= VaR
plot.zoo(sim.ret.t[, "MSFT"], type="b", main="Mean of MSFT when PORT <= 5% VaR",
col="blue", ylab="Returns")
abline(h=0)
abline(h=-mcES["MSFT"], lwd=2, col="red")
points(sim.ret.t[idx, "MSFT"], type="p", pch=16, col="red")
par(mfrow=c(1,1))