Bellow is a stock daily returns matrix example (ret_matriz)
IBOV PETR4 VALE5 ITUB4 BBDC4 PETR3
[1,]
1) The apply
part can be eliminated. We also use rollapplyr
for brevity:
rollapplyr(ret_matriz, 5, sd, fill = 0)
2) Also rollmean
is faster than rollapply
so we could construct it from that using the formula sd = sqrt(n/(n-1) * (mean(x^2) - mean(x)^2))
:
sqrt((5/4) * (rollmeanr(ret_matriz^2, 5, fill = 0) -
rollmeanr(ret_matriz, 5, fill = 0)^2))