Created
December 7, 2011 03:32
-
-
Save timelyportfolio/1441322 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
#I very much appreciate Joshua Ulrich's (http://blog.fosstrading.com) forked version | |
#which offers a much nicer top section of the final graph | |
#forked version resides here https://gist.github.com/1443358 | |
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) | |
#this is the primary change Joshua Ulrich made | |
#to allow a much nicer labelling of points on a right vertical margin | |
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