Fun with the googleVis Package for R

Using packages such as ggplot and lattice can produce some great charts and visualization, but googleVis is tough to beat for interactive charts to share on the web. Click on the image below to open up the html page.


This was all done in R!

I will warn you that it is too easy to blow an entire Saturday afternoon playing with the googleVis charts 🙂


Strategy Diversification in R – follow up

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


  • 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

Here is the code to make the correlation chart.

#Load the packages used

# 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

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

Strategy Diversification in R

In my last post, I looked at the correlations of different instruments. Understanding the correlations of instruments is important when developing a strategy and selecting the assets to include. In theory, selecting highly correlated instruments for a portfolio or strategy will be more volatile than a portfolio or strategy with several uncorrelated instruments. This sounds great in theory, but can be difficult to apply in real life. Why? – correlations change over time and just diversifying among instruments is not enough. Just take a look at the graph below from my post on correlations as well as Systematic Investor’s analysis of Cross Sectional Correlation.

Correlations are changing over time and markets are becoming more correlated in recent times. As the correlations between markets and instruments increases, the impact of diversification decreases. You may be asking yourself (like I am), “If I can’t diversify among assets, what else can I do to diversify?” My answer to this is to diversify in as many ways as you can – trade multiple strategies, multiple timeframes, multiple risk levels, multiple markets, multiple instruments, etc.

To demonstrate this, I will take two strategies:

  • Strategy1 – longer term strategy
  • Strategy2 – shorter term strategy

(Yes… I realize that I am being very vague about the strategies at this point, more on the strategy details later in the post.)

Here are the outcomes of each strategy using quantstrat to backtest.

Strategy 1

6.599 -36.358 0.182


Strategy 2

2.637 -9.637 0.274


How does each strategy correlate to eachother?


The chart above shows that Strategy 1 is not very strongly correlated with Strategy 2.

Now for more information on the strategies.

  • Strategy 1 and Strategy 2 both trade the same universe of instruments (“XLY”, “XLP”, “XLE”, “XLF”, “XLV”, “XLI”, “XLK”, “XLB”, “XLU”)
  • Strategy 1 is a 52 week moving average strategy and trades 1000 contracts per trade*
  • Strategy 2 is a RSI(2) on weekly data strategy and trades 100 contracts per trade*
  • *Note on position sizing. Normally I would do a volatility based position sizing, but the RSI(2) strategy took about 20 minutes to complete the test because of the looping in the order sizing function. So for brevity and testing purposes I used fixed contract sizes as stated above for each strategy.

Are you surprised that two strategies that trade the exact same set of instruments would not have a higher correlation? I was!

This example reinforces how diversification can be achieved in more ways than one.

In follow-up posts, I will share the R code for the strategies and show how I plotted the correlations.