Rollapply for time series

こ雲淡風輕ζ 提交于 2019-12-03 07:32:39

问题


I am trying to calculate the rolling 20 period historical volatility. I take the daily returns:

ret<-ROC(data1)

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

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

The problem is that observations in vol starts appearing after ten days which is wrong as I specified 20.

For demonstration here is sample of the 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

Assume the data above is stored in x, then:

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

will yield a first observation at 10th row instead of 20. Also the sd is wrong too.

I should be missing something here...


回答1:


You need to use align='right' instead of using the default which is align='center', or instead of using rollapply, use the rollapplyr wrapper which has align='right' as the default.

From ?rollapply:

align specifyies whether the index of the result should be left- or right-aligned or centered (default) compared to the rolling window of observations. This argument is only used if width represents widths.

Although, for this, personally, I'd use runSD from the TTR package because it uses compiled code and will be faster.

Either of these should do what you expect, but the second one will be faster.

library(zoo)
rollapply(x, 20, sd, fill=NA, align='right')

library(TTR)
runSD(x, 20)


来源:https://stackoverflow.com/questions/13243148/rollapply-for-time-series

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!