I want to calculate the VaR at the end of a month with the historical method. My time series will start at the beginning of 2000 until now. The calculation should start lets say in 2005 to have enough data. There is a similar post rolling computations in xts by month and I have tried to modify the code for my case. The VaR at the end of each month should use the past data.
Here is my code (here it starts in 2012 because otherwise it would take to long):
library(quantmod)
getSymbols("^GSPC",return.class = "zoo",from = "2012-01-01",to = Sys.Date())
sp500 <- Ad(GSPC)
ldr_sp500 <- Return.calculate(sp500, method = "log")
ldr_sp500 <- na.omit(ldr_sp500)
idx <- index(ldr_sp500)[endpoints(ldr_sp500, 'months')]
out <- lapply(idx, function(i) {
as.xts(rollapplyr(as.zoo(ldr_sp500), 30, VaR))
})
sapply(out, NROW)
First of all there is a big error in my code. What should width be? Is it also possible to give the output as zoo object? Iam a beginner with this kind of functions... When I dont want to use the historical method but rather the gaussian method I would use:
apply.monthly(as.xts(ldr_sp500), VaR, method="gaussian")
It seems this works fine with non overlapping periods...
In your code, the function in lapply
does not use its argument i
:
you are computing the same thing (the VaR for each day in the period)
over and over.
In addition, the default method for VaR
is modified
:
you need to specify method="historical"
.
If you want to compute the value at risk from the daily returns of the current month,
your suggestion to use use apply.monthly
actually works:
apply.monthly(ldr_sp500, VaR, method="historical")
If you want an expanding window instead:
library(quantmod)
library(PerformanceAnalytics)
getSymbols("^GSPC", from = "2012-01-01" )
x <- Return.calculate( Ad(GSPC), method = "log" )
idx <- index(x)[endpoints(x, 'months')]
result <- sapply( idx,
function(i) VaR( x[paste0("/",i)], method = "historical" )
)
xts( result, idx )