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

About these ads

10 thoughts on “Strategy Diversification in R – follow up

    • This should work.
      Just start an R session and copy paste the following code.

      install.packages(“quantstrat”, repos= c(“http://R-Forge.R-project.org”, getOption(“repos”)))

  1. Nice article. I would like to do something similar. Any suggestions on good tutorials on R one can read and packages they should become familiar with? I am new to R but has prior experience with trading and programming.

    • pie,

      The packages to know are quantstrat and PerformanceAnalytics. The quantstrat package comes with some really good examples that helped me get started with it. Another great resource is R-sig-finance mailing list, I highly recommend you join it. Also, check out r-bloggers for other blogs that use R for econometrics and backtesting.

      Ross

  2. Hi – When I try to execute either strategy1.R or strategy2.R, I get the following error. I identified the statement that is causing the error and noticed that the error happens only when working with weekly data (and not with monthly data). I am wondering do I need to set some environmental variable or is it a bug in the R library.
    =====================
    Error:
    [1] “Strategy Loop:”
    Time difference of 2.657506 mins
    Error in if (length(c(year, month, day, hour, min, sec)) == 6 && c(year, :
    missing value where TRUE/FALSE needed
    =====================
    Code statement -
    updatePortf(Portfolio = portfolio_st,Dates = paste(‘::’,as.Date(Sys.time()),sep = ”))
    =====================
    Note: I don’t know what the relation is but if I change following line
    x<-to.weekly(x,indexAt='lastof',drop.time=TRUE)
    to convert to monthly data then program goes thru.

      • I did not make any changes and tried to run files as is. When I got error, I made following 2 changes in both strategy1.R and strategy2.R. I will try to find another program (demo?) that use weekly time frame to verify if cause is with the environment.
        ===========
        x<-to.monthly(x,indexAt='lastof',drop.time=TRUE)
        # x<-to.weekly(x,indexAt='lastof',drop.time=TRUE)
        ==========
        write.zoo(strategy1_eclogret, file = "strategy1.csv", sep=",")
        #write.zoo(weekly_timing_eclogret, file = "~/R/strats_for_cor/strategy1.csv", sep=",")

  3. Forgot to mention, after I made the above two changes, I could run all the three R files. So problem is only when it is weekly time frame.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s