I want to programm a rolling Value at Risk by hand. So I don't want to use the VaR from the PerformanceAnalytics package. I want to plot after calculations against the log-returns of a time series. Input:
getSymbols('^GDAXI', src='yahoo', return.class='ts',from="2005-01-01", to="2015-01-01")
GDAXI.DE=GDAXI[ , "GDAXI.Close"]
log_r1=diff(log(GDAXI.DE)) #log_r1=data
alpha=0.95
The VaR function:
VatR=function(data, alpha)
{
x=diff(log(data))
mu=mean(x)
sigma=sqrt(var(x))
quant=qnorm(alpha, mean=0, sd=1)
vatr=tail(data,n=1)*(1-exp((-sigma)*quant+mu))
}
data=GDAXI.DE
alpha=0.95
t=125
l=(-1)*diff(data) #if GDAXI used code must be changed here diff
loss=c(0,l)
ValueatRisk=matrix(rep(0),length(data),1)
violations=matrix(rep(0),length(data),1)
for(i in (t+1):length(data))
{
ValueatRisk[i]=VatRnorm(data[(i-t):(i-1)] ,alpha) #failure source
violations[i]=(loss[i] > ValueatRisk[i])
}
outputtheo=(1-alpha)*(length(data)-t)
print(outputtheo)
outputreal=sum(violations)
print(outputreal)
I want to combine these graphics. It seems to be a scaling problem, I tried qplot, ggplot and so on without success.
graph1=plot(loss[(t+1):length(data)], type="l", col="blue")
graph2=plot(ValueatRisk[(t+1):length(data)], type="l", col="red")
How to bring them together in one plot?
If plotting is the only issue now, I think this will produce what you want.
plot(loss[(t+1):length(data)], type="l", col="blue")
lines(ValueatRisk[(t+1):length(data)], type="l", col="red")
(And BTW, your code won't run as is because VatRnorm()
inside the loop is really the old/original VatR()
.)