[R-sig-Finance] Rolling correlations with zoo object

Achim Zeileis Achim.Zeileis at wu-wien.ac.at
Mon May 22 16:55:43 CEST 2006


On Mon, 22 May 2006 10:23:25 -0400 jladekarl at worldbank.org wrote:

> I'm a novice user of R so, please, excuse me for asking a basic
> question I hope there is a basic answer to:
> 
> I have tried to created a correlation matrix using a "zoo object".  I
> don't have any issues using the cor("zoo data") function, but when I
> try to expand the process by introducing rolling correlations I run
> into problems. I have created a workaround using "rapply" specifying
> the exact variables to use, rather than the general zoo object, but
> it's not very practical solution for large matrixes. Any hints?

Mmmmh, I'm not sure what exactly you would like to compute...but I
guess you want to have the lower triangle of the correlation matrix,
i.e., all pairwise correlations, right? If this is what you want, you
could set up a function for that, e.g.:

  lcor <- function(x, ...)
  {
    rval <- cor(x, ...)
    rval <- rval[lower.tri(rval)]
    if(!is.null(colnames(x))) {
      nam <- outer(colnames(x), colnames(x),
        function(a, b) paste(a, b, sep = "."))
      names(rval) <- nam[lower.tri(nam)]
    }
    return(rval)
  }

which returns the lower triangular of cor(x) with name formatting if
available.

> ##Connect to Bloomberg through session "conn"
> conn <- blpConnect ()
[...]

Thanks for providing this example. Note however, that Bloomberg is not
freely available which renders the example irreproducible for some of
us.

A simpler example which might do what you want:
  ## generate data
  z <- zoo(matrix(rnorm(120), ncol = 3))
  colnames(z) <- c("EUR", "CHF", "USD")  
  ## full sample estimates
  cor(z)
  ## lower triangle only
  lcor(z)
  ## rolling estimates
  rapply(z, 30, lcor, by.column = FALSE)

hth,
Z



More information about the R-SIG-Finance mailing list