Here's an implementation of the basic moving average cross system. It should be trivial to adjust it to fit your needs.
library(quantmod)
library(tseries) # for maxdrawdown if you want it
x <- getSymbols("SPY", src="yahoo", from="2012-01-01", to="2012-12-31", auto.assign=FALSE)
n1 <- 20 # for short term moving average
n2 <- 50 # for long term moving average
x$ma1 <- SMA(Ad(x), n1) # add a short term MA
x$ma2 <- SMA(Ad(x), n2) # add a long term MA
x$spd <- x$ma1 - x$ma2 # difference between the two
x$spd[1:n2] <- 0 # flat until we have enough data to calculate both MAs
x$cross <- c(0, diff(x$spd > 0, na.pad=FALSE)) # short cross long
x$pos <- NA # Position
x$pos[x$cross == 1] <- 1 # long where it crosses from below
x$pos[x$cross == -1] <- -1 # short where it crosses from above
# fill forward your position until you get the next signal. Also, you have to
# lag your signal because today's return will be a result of yesterday's position
x$pos <- c(0, lag(na.locf(x$pos), na.pad=FALSE))
x$pos[is.na(x$pos)] <- 0
x$ret <- c(0, ROC(Ad(x), na.pad=FALSE))
x$cumret <- cumsum(x$pos * x$ret)
out <- data.frame(n1=n1, n2=n2, cumret=as.numeric(last(x$cumret)),
mdd=maxdrawdown(x$cumret)$maxdrawdown, ntrades=sum(abs(x$cross)))
out
tail(x)
Edit
Ok then, using your data
library(quantmod) # for Lag. Also loads zoo which is needed for na.locf, and
# TTR which is needed for ROC
x <- Data[, 1:3]
x$pos <- NA
x$pos[with(x, nSignal >= 0.7 & Trend < 0)] <- -1
x$pos[with(x, nSignal >= 0.7 & Trend > 0)] <- 1
x$pos <- na.locf(x$pos)
x$pos[is.na(x$pos)] <- 0 # first few rows are NA; replace with 0 meaning "no position"
x$ret <- ROC(x$PriceTao) * Lag(x$pos) # yesterdays position * return from yesterday to today
x
Note that you are using a data.frame
which is slower than a matrix
. Also, you do not have any dates or times associated with your data. IMHO xts
or zoo
would be a better data structure if you actually have time series data.