# [R-SIG-Finance] rolling window

Achim Zeileis Achim.Zeileis at wu-wien.ac.at
Thu Jul 19 15:31:06 CEST 2007

```As a follow-up to Gabor's comment. A more elaborate illustration might be
a rolling regression, e.g.,

## set up multivariate zoo series with
## number of UK driver deaths and lags 1 and 12
seat <- as.zoo(log(UKDriverDeaths))
time(seat) <- as.yearmon(time(seat))
seat <- merge(y = seat, y1 = lag(seat, k = -1),
y12 = lag(seat, k = -12), all = FALSE)

## run a rolling regression with a 3-year time window
## (similar to a SARIMA(1,0,0)(1,0,0)_12 fitted by OLS)
fm <- rollapply(seat, width = 36,
FUN = function(z) coef(lm(y ~ y1 + y12, data = as.data.frame(z))),
by.column = FALSE, align = "right")

## plot the changes in coefficients
plot(fm)
## showing the shifts after the oil crisis in Oct 1973
## and after the seatbelt legislation change in Jan 1983

Maybe we should add such an example to the rollaply() man page?

Best,
Z

On Thu, 19 Jul 2007, Gabor Grothendieck wrote:

> On 7/19/07, Jordi Molins <jordi.molins.coronado at gmail.com> wrote:
> > I want to do a rolling window calculation for multivariate data. In other
> > words: rollFun in fMultivar makes univariate calculations, ie, given for
> > example mydata[1:5], mydata[2:6],
I get one number (the function applied
> > to mydata[1:5]) every time. rollingFunction in PerformanceAnalytics does the
> > same but for possibly multivariate data, but one column at a time. rapply in
> > zoo also does rolling window for univariate data (at least, all examples are
> > with univariate data).
>
> rollapply (which was called rapply in old versions of zoo but was renamed
> to avoid collisions with a new function of the same name in the core of R)
> in zoo can handle multivariate zoo series either one column at a time (default)
> or combined (via by.column = FALSE):
>
> > library(zoo)
> > z <- zoo(matrix(1:24, 12))
> > z
>
> 1   1 13
> 2   2 14
> 3   3 15
> 4   4 16
> 5   5 17
> 6   6 18
> 7   7 19
> 8   8 20
> 9   9 21
> 10 10 22
> 11 11 23
> 12 12 24
> > rollapply(z, 3, mean, by.column = TRUE) # can omit by.column here
>
> 2   2 14
> 3   3 15
> 4   4 16
> 5   5 17
> 6   6 18
> 7   7 19
> 8   8 20
> 9   9 21
> 10 10 22
> 11 11 23
> > rollapply(z, 3, mean, by.column = FALSE)
>  2  3  4  5  6  7  8  9 10 11
>  8  9 10 11 12 13 14 15 16 17
>
> _______________________________________________
> R-SIG-Finance at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-finance
> -- Subscriber-posting only.
> -- If you want to post, subscribe first.
>
>

```