rolling computations in xts by month

时间秒杀一切 提交于 2019-12-01 08:52:32

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

user128494

As an answer to "Is the zoo/xts conversion needed?": It isn't needed in this case, but rollapply won't work if you send it a dataframe, as I recently discovered from this StackOverflow answer

You want period.apply(), or its convenience helper apply.monthly(), both in xts.

Example:

R> foo <- xts(1:100, order.by=Sys.Date()+0:99)
R> apply.monthly(foo, sum)
           [,1]
2012-08-31  105
2012-09-30  885
2012-10-31 1860
2012-11-25 2200
R> 

or equally

R> apply.monthly(foo, quantile)
           0%   25%  50%   75% 100%
2012-08-31  1  4.25  7.5 10.75   14
2012-09-30 15 22.25 29.5 36.75   44
2012-10-31 45 52.50 60.0 67.50   75
2012-11-25 76 82.00 88.0 94.00  100
R> 

just to prove that functions returning more than one value can be used too.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!