Last active
September 18, 2018 14:55
-
-
Save jpicerno1/a30ba128953189cc8d88eb1664a5ec9d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# R code re: CapitalSpecator.com post for generating rolling correlations for asset class fund proxies | |
# "Are Correlations Between Asset Classes Rising?" | |
# http://www.capitalspectator.com/are-correlations-between-asset-classes-rising/ | |
# 27 May 2016 | |
# By James Picerno | |
# http://www.capitalspectator.com/ | |
# (c) 2016 by Beta Publishing LLC | |
# load packages | |
library(xts) | |
library(timeSeries) | |
library(tseries) | |
library(TTR) | |
library(quantmod) | |
library(PerformanceAnalytics) | |
# download fund prices | |
symbols <-c("SPY","IJS","EFA","EEM","IEF","LQD","VWEHX","RPIBX","PREMX","QRAAX","VGSIX") | |
getSymbols(symbols, src='yahoo', from='2003-12-31') | |
for(symbol in symbols) { | |
x <- get(symbol) | |
indexFormat(x) <- '%Y-%m-%d' | |
colnames(x) <- gsub("x",symbol,colnames(x)) | |
x <- x[,6] | |
assign(symbol,x) | |
} | |
# merge price histories into one data set | |
prices <- do.call(merge, lapply(symbols, get)) | |
colnames(prices) <-c(symbols) | |
# generate daily return series for funds | |
returns <-na.omit(ROC(prices,1,"discrete")) | |
colnames(prices) <-c("spy","ijs","efa","eem","ief","lqd","vwehx","rpibx","premx","qraax","vgsix") | |
# generate correlation matrix | |
corr.1 <- cor(returns,use="complete.obs") | |
up.tri <- upper.tri(corr.1) | |
fund.names <- paste(rownames(corr.1)[row(corr.1)[up.tri]],":", | |
rownames(corr.1)[col(corr.1)[up.tri]]) | |
funds.corr <- na.omit(rollapply(returns, | |
width=756, | |
FUN = function(a) | |
{ | |
return(cor(a,use="pairwise.complete.obs")[up.tri]) | |
}, | |
by.column=FALSE, align="right")) | |
colnames(funds.corr) <- fund.names | |
# generate median rolling 3-year correlation data for funds | |
corr.median <-as.xts(apply(funds.corr,1,median)) | |
# review correlation matrix for first 3 funds | |
# corr.1[1:3,1:3] | |
# Extract correlation data for four pairs: SPY:IJS, SPY:EFA, SPY:EEM, SPY:IEF | |
funds.corr.a <-funds.corr[,c(1,2,4,7)] | |
### END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment