S&P 500 components heatmap in R

October 12, 2011

(This article was first published on DataPunks.com » R, and kindly contributed to R-bloggers)

In this article, Hans Gilde exposes the clever use of a heatmap hidden in the Bioconductor library. In his example, he describes a way to show different ‘observations’ on subjects, with the concept of time.

Financial indices, like the S&P 500 or the Dow Jones indices, are mathematically some kind of measure of overall market performance, and their calculations (usually in real-time) might not translate very well the different price movements of the underlying index components.

Combining the different features of the quantmod package (as described here), one can come up with a time-series based heatmap of some financial indices, like the S&P 500 for example.

Below is an adaptation of Hans Gilde’s ideas to the S&P 500 since 2007. Note that some symbols were removed while preparing the data. Note also how highly correlated the different components are.

# get the list of symbols
l <- readHTMLTable('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies')[[1]]
l <- as.vector(l$Ticker)
l <- l[c(-59, -71, -80, -124, -141, -147, -275, -283, -292, -299, -309, -316, -360, -378, -381, -406, -439, -470, -471)]
getMonthlyReturns <- function(sym) {
    y <- to.monthly(getSymbols(sym, auto.assign=FALSE, from='2007-01-01'))
d <- unlist(llply(l, getMonthlyReturns, .progress="text"))
# bounds at -10% and +10% for visual clarity
d[d < -10] <- -10
d[d > 10] <- 10
heatmap_2(t(matrix(d, ncol=481)), col=brewer.pal(9, 'PuBu'), Rowv=NA, Colv=NA, do.dendro=c(FALSE,FALSE), scale='none', legend=2, main="S&P 500 since 2007 (monthly returns)")

To leave a comment for the author, please follow the link and comment on their blog: DataPunks.com » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Mango solutions

RStudio homepage

Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training





CRC R books series

Six Sigma Online Training

Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)