**rbresearch » R**, and kindly contributed to R-bloggers)

In this post, I will demonstrate how to quickly visualize correlations using the PerformanceAnalytics package. Thanks to the package creators, it is really easy correlation and many other performance metrics.

The first chart looks at the rolling 252 day correlation of nine sector ETFs using SPY as the benchmark. As expected the correlation is rather high because the sector ETFs are part of the S&P 500 index, but has been even more pronounced the last few years.

Chart 2 shows the correlation of five ETFs. Note that there is no single instrument I am using as a benchmark, all five ETFs will be benchmarked against one another. (note that I removed the legend because it literally took up the entire plot).

Chart 3 shows the same 4 ETFs, this time using SPY as a benchmark.

In my opinion, the beauty of the chart.RollingCorrelation function is that the inputs are time series returns. This means that the correlations of instruments (ETFs, stocks, mutual funds, etc.), hedge fund managers, portfolios, and even strategies we test in quantstrat.

Here is the R code used to generate the first chart. To do you own correlation analysis, just change the symbols or add in new data sets of different returns.

#Correlations of Sector ETFs to benchmarked against SPY #Load the packages used require(PerformanceAnalytics) require(quantmod) #create a list of symbols symbols = c("XLY", "XLP", "XLE", "XLF", "XLV", "XLI", "XLK", "XLB", "XLU") retsymbols <- paste("ret", symbols, sep = ".") #Downlad the data from yahoo getSymbols(symbols, src = 'yahoo', index.class = c("POSIXt","POSIXct"), from = '2000-01-01') getSymbols("SPY", src = 'yahoo', index.class = c("POSIXt","POSIXct"), from = '2000-01-01') #The benchmark is the return vector of which the other assets will be benchmarked against benchmark <- ROC(Ad(SPY), n=1, type="continuous", na.pad=TRUE) colnames(benchmark) <- "SPY" #Loop to create new xts objects with just the returns for (symbol in symbols){ x <- get(symbol) x1 <- ROC(Ad(x), n=1, type="continuous", na.pad=TRUE) colnames(x1)<-gsub("x",symbol,colnames(x1)) assign(paste("ret", symbol, sep = "."),x1) } #this merges all of the objects in 'retsymbols' into one object named 'ret' ret <- do.call(merge, lapply(retsymbols, get)) suppressWarnings(chart.RollingCorrelation(ret[,1:ncol(ret)], benchmark, width = 252, xaxis = TRUE, colorset = rich8equal, legend.loc = "bottomright", main = "Rolling 252 Day Correlation"))

Created by Pretty R at inside-R.org

**leave a comment**for the author, please follow the link and comment on their blog:

**rbresearch » 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...