Rolling Standard Deviation in a Matrix in R

后端 未结 2 1318
情书的邮戳
情书的邮戳 2021-02-10 13:14

Bellow is a stock daily returns matrix example (ret_matriz)

      IBOV        PETR4        VALE5        ITUB4        BBDC4        PETR3    
[1,]         


        
2条回答
  •  醉梦人生
    2021-02-10 14:16

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

提交回复
热议问题