Bellow is a stock daily returns matrix example (ret_matriz)
IBOV PETR4 VALE5 ITUB4 BBDC4 PETR3
[1,]
You can use TTR::runSD
instead.
library(quantmod)
getSymbols("SPY")
spy <- apply(ROC(SPY), 2, runSD, n=5)
# head(spy)
# SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted
# [1,] NA NA NA NA NA NA
# [2,] NA NA NA NA NA NA
# [3,] NA NA NA NA NA NA
# [4,] NA NA NA NA NA NA
# [5,] NA NA NA NA NA NA
# [6,] 0.004369094 0.003112967 0.001064232 0.005035266 0.1577499 0.005063025
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))