Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuaulrich/1443358 to your computer and use it in GitHub Desktop.
Save joshuaulrich/1443358 to your computer and use it in GitHub Desktop.
require(quantmod)
#get index tickers without the ^ which we will add in the getSymbols
tckrs=c("GSPC","TNX","DJUBS","W3DOW","W5DOW")
#name the indexes
names(tckrs) <- c("S&P 500","US 10y Yld","DJ Commodity","Developed","Developing")
#use paste to add the ^ to the index tickers
getSymbols(paste("^",tckrs,sep=""), from="1986-01-01", to=Sys.Date())
#start with 1st; just avoids an if statement in the for loop
#not sure what is best coding practice
indexes <- to.monthly(get(tckrs[1]))[,4]
for (i in 2:length(tckrs)) {
#merge into one big nice xts
indexes <- merge(indexes,to.monthly(get(tckrs[i]))[,4])
}
colnames(indexes) <- names(tckrs)
indexes <- na.omit(indexes)
index(indexes) <- as.Date(index(indexes))
#set start date to 2008-06 but feel free to use any date you like
indexes.roc <- indexes["2008-06::"]/lag(indexes["2008-06::"],k=1)-1
indexes.roc[1,] <- 0
indexes.cumul <- as.xts(apply(1+indexes.roc[,1:5],MARGIN=2,cumprod))
#stuff we re-use
labs=colnames(indexes.cumul)
colors=c("antiquewhite3","grey70","darkolivegreen4","indianred4","cadetblue4")
barInd=c(1,4,5,3,2)
#make plot
layout(matrix(1:2, 2),heights=c(8,5))
par(mar=c(2,4,4,7),oma=c(2,1,2,0))
plot.zoo(indexes.cumul-1,col=colors,lwd=c(3,3,2,2,2),screens=1,xlab=NA,ylab="% Change",las=1)
axis(4, coredata(last(indexes.cumul))-1,labels=FALSE)
mtext(labs, 4, at=coredata(last(indexes.cumul))-1,las=1,col=colors,line=1)
title(main="World Equity, Bond, and Commodity Indexes since June 2008",cex.main=1.25)
par(mar=c(4,4,2,3))
barplot(last(indexes.cumul)[,barInd]-1,las=1,beside=TRUE,col=colors[barInd],
names.arg=labs[barInd], ylab="% Change",ylim=c(-0.5,0),cex.names=0.75)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment