按月在xts中滚动计算 [英] rolling computations in xts by month

查看:135
本文介绍了按月在xts中滚动计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉zoo函数rollapply,该函数允许您对zooxts对象进行滚动计算,并且可以通过by参数指定滚动增量.我特别想每月应用一个函数,但要在计算中使用所有过去的每日数据.例如说我的数据集如下:

I am familiar with the zoo function rollapply which allows you to do rolling computations on zoo or xts objects and you can specify the rolling increment via the by parameter. I am specifically interested in applying a function every month but using all of the past daily data in the computation. For example say my data set looks like this:

dte, val
1/01/2001, 10
1/02/2001, 11
...
1/31/2001, 2
2/01/2001, 54
2/02/2001, 34
...
2/30/2001, 29

我想选择每个月的结束时间,而apply选择一个使用所有每日数据的函数.这似乎不适用于rollapply,因为by参数有时为30,其他月份为29,依此类推.我目前的想法是:

I would like to select the end of each month and apply a function that uses all the daily data. This doesn't seem like it would work with rollapply since the by argument would be 30 sometimes, 29 other months, etc. My current idea is:

f <- function(xts_obj) { coef(lm(a ~ b, data=as.data.frame(xts_obj)))[1] }
month_end <- endpoints(my_xts, on="months", k=1)
rslt <- apply(month_end, 1, function(idx) { my_xts[paste0("/",idx)] })

当然,有更好的方法可以更快地做到这一点,不是吗? 需要说明的是:我想使用重叠期,只是应该每月进行一次滚动.

Surely there is a better way to do this that would be quicker no? To clarify: I would like to use overlapping periods just the rolling should be done monthly.

推荐答案

如果我理解正确,则可以获取端点的日期,然后对于每个端点(即使用lapplyfor),调用直到那时使用数据.

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

我暂时将rollapplyr强制转换为zoo,以确保正在使用rollapply.zoo方法(与未导出的rollapply.xts方法相对),然后强制转换回xts

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

这篇关于按月在xts中滚动计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆