Rolling Standard Deviation in a Matrix in R

后端 未结 2 1316
情书的邮戳
情书的邮戳 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:01

    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
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
提交回复
热议问题