Golden Cross Trading System in R code

I wanted to try and post my first piece of R code on the site. I am having a few problems with the HTML of the code so here goes a first try. I am rookie coder with R and any other language for that matter. What this code does is goes and downloads more than 60 years of S&P 500 daily data, it then observes when the gold cross takes place, i.e. 50 day moving average crosses the 200 day moving average. In this instance there is a long signal. When the 50 day cross the 200 day to the downside it is a signal to close out the long trade. The system does not enter short trades and is exceptional relative to the traditional buy and hold strategy.

    require(quantmod)
    require(PerformanceAnalytics)
     
    #get the data and fill out the MA
    getSymbols(‘SPY’, from=’1950-01-01′)
    SPY$ma200 <- SMA(Cl(SPY), 200)
    SPY$ma50 <- SMA(Cl(SPY), 50)
     
    #lets look at it from 2000 to 2015
    spy <- SPY['1950/2015']
     
    #our baseline, unfiltered results
    ret <- ROC(Cl(spy))
     
    #our comparision, filtered result
    ma_sig <- Lag(ifelse(SPY$ma50 > SPY$ma200, 1, 0))
    ma_ret <- ROC(Cl(spy)) * ma_sig
     
    golden<- cbind(ma_ret,ret)
    colnames(golden) = c(‘GoldCross’,’Buy&Hold’)
     
    #Plot to visually see the actual moving averages
    chartSeries(spy,
    type = “line,
    name = “Moving Average : Golden Cross”,
    TA= c(addSMA(50, col = ‘yellow’), addSMA(200)))
     
    maxDrawdown(golden)
    table.AnnualizedReturns(golden, Rf= 0.02/252)
    charts.PerformanceSummary(golden, Rf = 0.02, main=”Golden Cross”,geometric=FALSE)

    Created by Pretty R at inside-R.org

    Rplot

    Rplot01

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