Quant
Quant

Reputation: 27

fixed rolling window

I want to construct a fixed rolling window in r. Say I have a dataset like this:

      Apple Microsoft     Amazon      Tesla
2000 0.91903890 0.5454254 0.22267026 0.41857974
2001 0.13638076 0.7640585 0.56990815 0.04490846
2002 0.19977390 0.9170585 0.04391331 0.72987722
2003 0.70627675 0.2583974 0.03485766 0.35594681
2004 0.08069703 0.2085965 0.19865918 0.30194120
2005 0.03334810 0.7955248 0.75876036 0.28129544
2006 0.94652374 0.6095904 0.98855677 0.36792881
2007 0.90060660 0.3144541 0.78201742 0.02731390

I know that the following function will give me an expanding window:

 all.cov.matrix <- lapply(1:nrow(stocks), function(y) cov(stocks[1:y,]))

To get a fixed window with four periods inside, I have tried the following function:

library(zoo)     
all.cov.matrix <- apply(rollapply(1:nrow(stocks), 4, c), 1, function(ix) cov(stocks[ix, ]))
    # However, this returns one big matrix, that is not what I am looking for. 
    # Ideally I want to get the following results:
     cov(stocks[1:4,]) # 1 period
     cov(stocks[2:5,]) # 2 period and so on

I want each of the matrices to be stored seperately in all.cov.matrix, thus in thix example all.cov.matrixshould store 5 different matrices.

Upvotes: 0

Views: 475

Answers (2)

Sotos
Sotos

Reputation: 51592

You need to use apply(..., margin = 2, ...) to get the columnar covariance. However, I wouldn't recommend apply. You can use lapply instead, i.e.

library(zoo)
lapply(as.data.frame(t(rollapply(1:nrow(stocks), 4, c))), function(i) cov(stocks[i,]))

Another way to write this (as per @G.Grothendieck comment),

r <- rollapplyr(stocks, 4, function(x) c(cov(x)), by.column = FALSE)
lapply(split(r, row(r)), matrix, 4)

Upvotes: 3

rosscova
rosscova

Reputation: 5580

If your expanding window example is close to what you want, you may be able to make it work with some slight adjustments to have the "window" roll the way you want:

all.cov.matrix <- lapply( 2:(nrow(stocks)-2),
                          function(y) {
                              cov(stocks[(y-1):(y+2),])
                          } )

The way you had 1:y means that the window always starts at 1, while y increases for each iteration, meaning the window expands. Changing that to (y-1):(y+2) means that both the start and end point of your window move along with y, always making a window of size 4.

To be careful not to go beyond the bounds of the data, we also need to change to X vector in lapply (the first parameter) such that the edges of the window stay within the data.

Upvotes: 3

Related Questions