rolling computations in xts by month

后端 未结 3 1358
庸人自扰
庸人自扰 2021-01-14 11:27

I am familiar with the zoo function rollapply which allows you to do rolling computations on zoo or xts objects and you c

3条回答
  •  心在旅途
    2021-01-14 12:08

    If I understand correctly, you can get the dates of your endpoints, then for each endpoint (i.e. using lapply or for), call rollapply using data up to that point.

    getSymbols("SPY", src='yahoo', from='2012-01-01', to='2012-08-01')
    idx <- index(SPY)[endpoints(SPY, 'months')]
    out <- lapply(idx, function(i) {
      as.xts(rollapplyr(as.zoo(SPY[paste0("/", i)]), 5, 
                        function(x) coef(lm(x[, 4] ~ x[, 1]))[2], by.column=FALSE))
    })
    sapply(out, NROW)
    #[1]  16  36  58  78 100 121 142 143
    

    I temporarily coerce to zoo for the rollapplyr to make sure the rollapply.zoo method is being used (as opposed to the unexported rollapply.xts method), then coerce back to xts

提交回复
热议问题