Here is an example were we calculate the rolling correlation in a 30 day window, and then plot the result:
library(zoo)
roll.corrs <- rollapplyr(dates, 30, function(index) cor(df1[index, "x1"], df1[index, "x2"]), fill=NA)
library(ggplot2)
qplot(as.Date(dates), roll.corrs)
or, shorter:
z <- zoo(df1, as.Date(rownames(df1)))
r <- rollapplyr(z, 30, function(x) cor(x[,1], x[,2]), by.column = FALSE)
autoplot(r)
The qplot
output shows:
You can clearly see how there are in particular two sections with particularly high correlations between the time series. The data is purposefully designed to have periods of high and low correlation. Here is the data:
base <- c(rep(1, 100), 1:50, rep(50, 100), 50:1, rep(1, 65))
dates <- as.character(seq(as.Date("2013-01-01"), len=365, by="1 day"))
set.seed(1)
df1 <- data.frame(
x1=base+rnorm(365, 0, 5),
x2=base+rnorm(365, 0, 5),
row.names=dates
)