EMA5 / EMA21 Crossover Strategy
This code will also input the data, create the indicators, and then create the signals. From the daily return and the buy or sell signals, equity curves are calculated. Last charts are produced to show the performance and draw-down.
Since the EMA21 requires the past 21 days of history before trading can start, the data file used for this contains the last 205 days but trading cannot start until July 23, 2011.
# install.packages(c("quantmod","TTR"))
library(quantmod)
library(TTR)
# Load presorted data
x = last(y,205) #gets the last 205 daily positions from the data
# Calculate the EMA indicators
ema10 <- EMA(Cl(x),10)
ema21 <- EMA(Cl(x),21)
# Create the long (up) and short (dn) signals
sigbuy <- ifelse(ema10 > ema21, 1, 0)
sigsell <- ifelse(ema10 < ema21, -1, 0)
# Lag signals to align with days in market,
# not days signals were generated
sigbuy <- lag(sigbuy,1) # Note k=1 implies a move *forward*
sigsell <- lag(sigsell,1) # Note k=1 implies a move *forward*
# Replace missing signals with no position
# (generally just at beginning of series)
sigbuy[is.na(sigbuy)] <- 0
sigsell[is.na(sigsell)] <- 0
# Combine both signals into one vector
sig <- sigbuy + sigsell
# Calculate Close-to-Close returns
ret <- ROC(Cl(x))
ret[1] <- 0
# Calculate equity curves
eq_up <- exp(cumsum(ret*sigbuy))
eq_dn <- exp(cumsum(ret*sigsell*-1))
eq_all <- exp(cumsum(ret*sig))
# Equity Chart
png("EMAcross.png",width=720,height=720)
plot.zoo( cbind(eq_up, eq_dn),
ylab=c("Long","Short"), col=c("green","red"),
main="EMA5-EMA21 Crossover Strategy: 07-23-2011 to 01-22-2012" )
dev.off()
png(filename="emacross.png",width=720,height=720)
plot.zoo( cbind(eq_up, eq_dn), plot.type="single", ylab=c("Long","Short"), col=c("green","red"), main="EMA Crossover Strategy:\n 2011-07-23 through 2012-01-22" )
dev.off()
# Create a chart showing mtgoxUSD
png("EMAcrosschart.png",width=720,height=720)
chartSeries(x, subset="last 184 days", type="line")
# Add the total equity line
addTA(eq_all)
dev.off()
# Evaluate the Strategy
# install.packages("PerformanceAnalytics")
require(PerformanceAnalytics)
# chart equity curve, daily performance, and drawdowns
png("performance-EMAcross.png",height=720,width=720)
charts.PerformanceSummary(ret)
dev.off()