Skip to content

Instantly share code, notes, and snippets.

@JoesDataDiner
Created February 23, 2013 14:03
Show Gist options
  • Save JoesDataDiner/5019876 to your computer and use it in GitHub Desktop.
Save JoesDataDiner/5019876 to your computer and use it in GitHub Desktop.
The Financial Crisis on Tape Part I - Correlation Computation
#now use Hadley's great plyr library and a simple function to compute the
#rolling correlation matrix
library(plyr)
DataFrameCorOutput<-function(hist.returns){
require(reshape2)
correls = melt(cor(as.matrix(na.omit(hist.returns))))
colnames(correls) = c("Var1","Var2","Correl")
correls
}
rolling.correlmatrix =
ddply(hist.returns,
.(year,quarter),
.fun = function(x){
DataFrameCorOutput(
x[,grep("Adjusted",colnames(x))]
)}
)
#rename some of the series to make obtain a pretty plot a little easier!
rolling.correlmatrix$Var1 = factor(gsub(".Adjusted","",rolling.correlmatrix$Var1),symbols)
rolling.correlmatrix$Var2 = factor(gsub(".Adjusted","",rolling.correlmatrix$Var2),symbols)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment