econ589riskmeasures.r

Download Econ589riskMeasures.r

If you can't read please download the document

Upload: jasonclark

Post on 16-Nov-2015

2 views

Category:

Documents


0 download

DESCRIPTION

Risk measurement

TRANSCRIPT

# 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 librarieslibrary(PerformanceAnalytics)library(quantmod)library(MASS)library(mvtnorm)library(mnormt) options(digits=4)## Example: Normal VaR#mu = 10sigma = 100alpha = 0.95VaR.alpha = qnorm(alpha, mu, sigma)VaR.alpha# alternative approachVaR.alpha = mu + sigma*qnorm(alpha,0,1)VaR.alpha## Example: normal ES#mu = 10sigma = 100alpha = 0.95q.alpha.z = qnorm(alpha)ES.alpha = mu + sigma*(dnorm(q.alpha.z)/(1-alpha))ES.alpha## Estimating risk measures## download datasymbol.vec = c("MSFT", "^GSPC")getSymbols(symbol.vec, from ="2000-01-03", to = "2012-04-03")colnames(MSFT)start(MSFT)end(MSFT)# extract adjusted closing pricesMSFT = MSFT[, "MSFT.Adjusted", drop=F]GSPC = GSPC[, "GSPC.Adjusted", drop=F]# plot pricesplot(MSFT)plot(GSPC)# calculate returns MSFT.ret = CalculateReturns(MSFT, method="simple") GSPC.ret = CalculateReturns(GSPC, method="simple")# remove first NA observationMSFT.ret = MSFT.ret[-1,]GSPC.ret = GSPC.ret[-1,]# create combined data seriesMSFT.GSPC.ret = cbind(MSFT.ret,GSPC.ret)# plot returnsplot(MSFT.ret)plot(GSPC.ret)## calculate nonparametric risk measures## standard deviationapply(MSFT.GSPC.ret, 2, sd)# empirical 5% and 1% quantiles (historical VaR)apply(MSFT.GSPC.ret, 2, quantile, probs=c(0.05, 0.01))# historical 5% and 1% ESES.fun = function(x, alpha=0.05) { qhat = quantile(x, probs=alpha) mean(x[x