[R-SIG-Finance] Rolling Correlation Matrixes
Achim Zeileis
Achim.Zeileis at uibk.ac.at
Sun Jun 19 22:45:14 CEST 2011
On Sun, 19 Jun 2011, tonyp wrote:
> Hi,
>
> I am fairly new to R and I was hoping some of the great geniuses could help
> me with my problem. Basically, I have 5 time series of daily data. Let's
> say:
>
> ####
> x1=rnorm(200, 0,1)
> x2=rnorm(200, 10, 2)
> x3=rnorm(200, 1,5)
> x4=rnorm(200, 2,1)
> x5=rnorm(200, 9,2)
> x=cbind(x1,x2,x3,x4,x5)
> rt=zoo(x, as.Date("2004-01-01") + 0:199)
>
> and I want to calculate weekly rolling matrices (pairwise) correlations (not
> average pairwise correlations). And I am looking to output the very last
> (window) correlation a.k.a. the last period correlation matrix. So I did
> this:
>
> pw <- rollapply(rt, width = 5, FUN = function(x)
> y <- cor(x), by.column = FALSE, align='right')
> p=tail(pw,1)
>
> I get really messy output. Something like this:
>
> 2004-07-18 1 0.5276424 -0.05103385
>
> 2004-07-18 -0.0783848 0.1752491 0.5276424 1
>
> 2004-07-18 -0.4639914 0.4708166 0.1443911
>
> 2004-07-18 -0.05103385 -0.4639914 1
>
> 2004-07-18 -0.8756658 0.3756958 -0.0783848
>
> 2004-07-18 0.4708166 -0.8756658 1
>
> 2004-07-18 0.01812455 0.1752491 0.1443911
>
> 2004-07-18 0.3756958 0.01812455 1
It's not that messy but it may be more than you expected. Your 200x5
series is transformed into a 196x25. The 196 is due to "losing" four
observations with a five observation window. The 25 is due to the 5x5
correlation matrix that you compute. But it would be sufficient to use
something like
mycor <- function(x) {
rval <- cor(x)
rval[lower.tri(rval)]
}
and then to use FUN = mycor in your rollapply() call. Maybe you can also
improve the labeling somewhat.
> Can you help me with that please? In addition, if I want to calculate the
> current percentile of each pair of this last period with respect to its
> rolling correlation distribution how can I do that? I was reading that
> rank() may do the job but I am not sure. Thank you. :)
Maybe something like this?
apply(pw, 2, function(x) mean(x <= tail(x, 1)))
hth,
Z
>
>
>
>
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Rolling-Correlation-Matrixes-tp3609808p3609808.html
> Sent from the Rmetrics mailing list archive at Nabble.com.
>
> _______________________________________________
> R-SIG-Finance at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-finance
> -- Subscriber-posting only. If you want to post, subscribe first.
> -- Also note that this is not the r-help list where general R questions should go.
>
More information about the R-SIG-Finance
mailing list