[R] Expanding VaR package
Benjamin Dickgiesser
dickgiesser at gmail.com
Tue Nov 21 12:32:34 CET 2006
Hi,
it would be nice if the VaR package could get expanded to work with
more models. I wrote a function which calculates the VaR for a
Garch(1,1) AR(2) model. Since I am fairly new to R I am sure it can be
written much neater.
If someone feels like having a go, here is what I have written
library(fSeries)
library(tseries)
VaR.Garch <- function(data,stockId=1,p=0.01,dt=1)
{
r <- diff(log(data))
#fit Garch(1,1), Ar(2) modell
fit = garchFit(~arma(2,0), ~garch(1,1), series = r)
#init vars
rhat[1:3] <- 0
a[1:3] <- 0
sigma[1:3] <- 0
VaR[1:3] <- 0
for (t in 3:length(r))
{
#Calculate r suggested by AR
rhat[t] <- fit at fit$matcoef[1,1] + fit at fit$matcoef[2,1] * r[t-1] +
fit at fit$matcoef[3,1]* r[t-2]
#calculate error from fitted AR
a[t] <- r[t] - rhat[t]
#estimate sigma
sigma[t] <- sqrt(fit at fit$matcoef[4,1] + fit at fit$matcoef[5,1] *
sigma[t-1]^2 + fit at fit$matcoef[6,1] * a[t - 1]^2)
# calculate the value at risk
VaR[t] <- (1 - exp(rhat[t] * dt + sqrt(dt) * qnorm(p) * sigma[t])) * data[t]
}
list(VaR=VaR,r=rhat,std=sigma)
}
Sorry if this isn't the right place to post this.
Benjamin
More information about the R-help
mailing list