Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

The formula would be for every date 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. For each date t I want to calculate the rolling sum over the last two dates (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)

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

where I would really like to have the result c(155, 160, 155, 160, 155, NA)

Any help is appreciated.

like image 950
Wolfgang Wu Avatar asked Jan 08 '14 11:01

Wolfgang Wu


1 Answers

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
a vector of filter coefficients in reverse time order (as for AR or MA coefficients).

like image 180
Sven Hohenstein Avatar answered Sep 25 '22 05:09

Sven Hohenstein