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
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)