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
I recommend runner
function in runner package to apply any R function on rolling windows. Below runner
output identical to zoo
.
library(runner)
runner(
x,
function(x) sd(x),
k = 20,
na_pad = TRUE
)
runner
can reproduce zoo
output and also have options like handling unequally spaced data and other (for more go to documentation and vignettes for more).
library(runner)
library(zoo)
x <- c(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)
identical(
runner(x, sd, k = 20, na_pad = TRUE),
rollapply(x, 20, sd, fill = NA, align = "right")
)
# centered alignment
identical(
runner(x, sd, k = 20, lag = -10, na_pad = TRUE),
rollapply(x, 20, sd, fill = NA, align = "center")
)
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)