简体   繁体   English

时间序列的滚动总和

[英]Rolling sum of time series with factor

I am trying to calculate a rolling sum for a time series of returns r ranging over T dates. 我正在尝试计算范围为T的收益率r的时间序列的滚动总和。 However at each date t when I calculate the rolling sum, I want to factor in a weight w for each number in the rolling sum. 但是,在计算滚动总和的每个日期t时,我都希望将滚动总和中每个数字的权重w都考虑在内。

The formula would be for every date t: 该公式适用于每个日期t:

[Sum from i=1 to m](w(i)*r(t-i-1))

Lets look at a very simple example. 让我们看一个非常简单的例子。 I have a return series of T=6 returns r . 我有一个T = 6返回r的返回序列。 For each date t I want to calculate the rolling sum over the last two dates (m=2). 对于每个日期t我想计算最近两个日期(m = 2)的滚动总和。 I also want to weight the first observation twice as much as the second. 我还想将第一个观察的权重加权为第二个观察的两倍。

r <- c(100,110,100,110,100,110)                 
w <- c(1,0.5)

I know that I can easily do the rolling sum using the filter function: 我知道我可以使用过滤器函数轻松地计算总和:

filter(r, rep(1, 2))

However I am not able to include the weight factor into the rolling sum. 但是,我无法将权重因子包括在总和中。 The following line gives the wrong result of c(155, 155, 155, 155, 155, NA) 以下行给出了c(155, 155, 155, 155, 155, NA)的错误结果

filter(r*w, rep(1, 2))

where I would really like to have the result c(155, 160, 155, 160, 155, NA) 我真的想得到结果c(155, 160, 155, 160, 155, NA)

Any help is appreciated. 任何帮助表示赞赏。

Here's one way to do it: 这是一种实现方法:

filter(r, rev(w))
# [1] 155 160 155 160 155  NA

An important information about the argument filter from the help page of ?filter : ?filter帮助页面上有关参数filter的重要信息:

filter 过滤
a vector of filter coefficients in reverse time order (as for AR or MA coefficients). 逆序排列的滤波器系数向量(如AR或MA系数)。

rollapply in the zoo package can do that: Zoo包中执行rollapply可以做到这一点:

> rollapply(r, 2, crossprod, w, fill = NA)
[1] 155 160 155 160 155  NA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM