Strategy Diversification in R – follow up

The strategies used in Strategy Diversification in R were labeled as Strategy1 and Strategy2.

Strategy1

  • Indicator: 52 week Simple Moving Average
  • Entry Rule: Buy 1000 shares when price crosses and closes above 52 week Simple Moving Average
  • Exit Rule: Exit all positions when prices crosses and closes below 52 week Simple Moving Average
  • Classification: Long term trend following strategy

Strategy 2

  • Indicator: RSI(2) on weekly data
  • Entry Rule: Buy 100 shares when RSI(2) is less than 20 (Note that if RSI(2) is below 20 for N days, then you will have accumulated N * 100 shares)
  • Exit Rule: Exit all positions when RSI(2) is greater than 50
  • Classification: Short-Medium term reversal (dip buying) strategy

What did we diversify?

  1. Symbols? – No, the exact same instruments were used in the strategy.
  2. Markets? – No, see #1.
  3. Timeframe? Sort of, Strategy1 is a long term strategy and Strategy2 is a shorter term strategy, but both are on the weekly timeframe. We could diversify further by trading even shorter timeframes (i.e. Daily, Hourly, minute, tick, etc.)
  4. Strategy? Yes, Strategy1 is a trend following strategy and Strategy2 is a reversal strategy.
  5. Risk Levels? Yes, Strategy2 trades more often, but in smaller increments.

We achieved fairly low correlations by achieving only three “levels” of diversification. Think what we could do by using a “kitchen sink” portfolio with grains, softs, metals, currencies, stocks, fixed income, international stocks, international fixed income, style ETFs, etc.

Three R script files were used in the last post.

strategy1.R, strategy2.R, and correlation chart.R

The R scripts are pretty self explanatory so I won’t go into much detail. However, I do want to call attention to 2 lines of code from strategy1.R. The code for strategy2.R is virtually identical.

# logarithmic returns of the equity curve of strategy1.
strategy1_eclogret <- ec$logret

# write the logarithmic returns of strategy 1 to a csv file with the filename "strategy1.csv"
# you will have to change the file where you want to save it
write.zoo(strategy1_eclogret, file = "~/R/strats_for_cor/strategy1.csv", sep=",")

Created by Pretty R at inside-R.org

Here is the code to make the correlation chart.

#Load the packages used
require(PerformanceAnalytics)

# load the strategy 1 returns
strat1 <- as.xts(read.zoo(file = "~/R/strats_for_cor/strategy1.csv", header = TRUE, sep=","))
colnames(strat1) <- "strat1"

# load the strategy 2 returns
strat2 <- as.xts(read.zoo(file = "~/R/strats_for_cor/strategy2.csv", header = TRUE, sep=","))
colnames(strat2) <- "strat2"

suppressWarnings(chart.RollingCorrelation(strat1, strat2, width = 52, xaxis = TRUE, 
                                          colorset = rich8equal, legend.loc = "bottomright",
                                          main = "Rolling 52 Week Correlation"))

Created by Pretty R at inside-R.org

And that is all there is to it. (run strategy1.R, run strategy2.R, then run correlation chart.R – don’t forget to change the file directory!)

I listed 5 “levels” or ways to achieve diversification… what are other ways we can diversify? – post your ideas in the comments

Advertisements

Quick View on Correlations of Different Instruments

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.

rbresearch

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).

rbresearch

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

rbresearch

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