Homer Jay Simpson
Homer Jay Simpson

Reputation: 1280

Rollapply for backtesting the value at risk

I want to backtest the empirical (unconditional) value at risk of a time series vector:


x = rnorm(1000)
xt = diff(x)
quantile(xt,0.01)

So I am thinking that rollapply function in R might be helpful, since I want to roll estimate the quantile a from time t until the end time T with rolling window 100 by one observation.

If I code the following :

a = rollapply(xt,width=100,quantile(xt,probs=c(0.01)))

I receive an error:

Error in match.fun(FUN) : 
  'quantile(xt, probs = c(0.01))' is not a function, character or symbol

What I am doing wrong here ?

PLUS: How can I plot the two series (historical estimate and backtesting result) in one plot?

Upvotes: 0

Views: 145

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269654

Convert x to zoo series z and then use diff, rollapply and plot as shown. cbind.zoo will align the series. Note that rollapply uses centered windows. If you want right aligned windows use rollapplyr with an r on the end instead. If you want the series in a single panel add screen = 1 argument to plot.

library(zoo)

set.seed(123)

x <- rnorm(1000)
z <- zoo(x)
zt <- diff(z)
a <- rollapply(zt, 100, quantile, probs = 0.01)
plot(cbind(z, zt, a))

screnshot

Upvotes: 3

Related Questions