按月在 xts 中滚动计算 [英] rolling computations in xts by month
问题描述
我熟悉 zoo
函数 rollapply
,它允许您在 zoo
或 xts
上进行滚动计算对象,您可以通过 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
我想选择每个月的月底并应用
一个使用所有每日数据的函数.这似乎不适用于 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.
推荐答案
如果我理解正确,您可以获取端点的日期,然后针对每个端点(即使用 lapply
或 对于
),使用到该点的数据调用rollapply
.
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.zoo
code>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屋!