Rollapply for Time Series

I am trying to calculate the historical volatility of the rolling period. I accept daily returns:

ret<-ROC(data1) 

And then I use rollapply to get a 20 day HV for each column:

 vol<-rollapply(ret,20,sd,by.column=T,fill=NA) 

The problem is that the observations in vol begin to appear in ten days, which is wrong, as I pointed out 20.

For demonstration, here is an example of data:

 0.000000000, 0.005277045, 0.023622047, 0.002564103,-0.002557545, -0.020512821, 0.007853403,-0.012987013, 0.007894737, 0.015665796, 0.000000000, -0.002570694, 0.002577320, -0.015424165, 0.002610966, 0.010416667, 0.002577320, 0.015424165, 0.000000000, -0.002531646, -0.002538071, 0.030534351, 0.014814815, -0.007299270, -0.009803922, -0.012376238, 0.002506266, -0.015000000,-0.002538071, 0.002544529 

Suppose the data above is stored in x, then:

 rollapply(x,20,sd,fill=NA) 

will give the first observation in the 10th line instead of 20. Also sd is also mistaken.

I'm missing something here ...

+7
source share
1 answer

You need to use align='right' instead of using the default value align='center' or use rollapply wrapper instead of rollapply which has align='right' by default.

From ?rollapply :

Align indicates whether the result index should be left or right aligned or centered (default) compared to the calendar observation window. This argument is used only if the width represents the width.

Although for this I personally used runSD from TTR , because it uses compiled code and will be faster.

Any of them should do what you expect, but the second will be faster.

 library(zoo) rollapply(x, 20, sd, fill=NA, align='right') library(TTR) runSD(x, 20) 
+18
source

All Articles