Skip to content

Instantly share code, notes, and snippets.

@JoesDataDiner
Created February 23, 2013 14:03

Revisions

  1. JoesDataDiner created this gist Feb 23, 2013.
    23 changes: 23 additions & 0 deletions FinCrisisPartI_CorrelComp.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    #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)