Rollapply for time series

前端 未结 2 621
我寻月下人不归
我寻月下人不归 2021-02-02 01:55

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

2条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 02:58

    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)
    

提交回复
热议问题