2

I am building a simple trading strategy using a dual moving average crossover on a monthly basis. I am using the simple 2-month MA and the 10-month MA. If 2Ma crosses above the 10Ma, then buy if it crosses below, then sell. The problem is that my equity curve is not right. In order to get the monthly moving averages, I converted the daily prices to monthly. This seems to work well when computing the moving averages but when I applied the signals to my prices in the backtesting environment, it looks like it considers daily data so the signals are not matching the dates.

I got this warning:

> data$weight[] = ifelse(as.integer(SMA_2>SMA_10)==1,1,0)  #If price of SPY is above the SMA then buy
Warning message:
 In NextMethod(.Generic) :
 number of items to replace is not a multiple of replacement length

And then:

> models$dmac2_10 = bt.run.share(data, trade.summary=T)
Error in which(tstart[, i]) : argument to 'which' is not logical
Called from: which(tstart[, i])
Browse[1]>

Here is the code:

### Simple Dual Moving Average Crossover

#Load the required packages
load.packages('quantmod')
require(RCurl)
sit = getURLContent('https://github.com/systematicinvestor/SIT/raw/master/sit.gz', binary=TRUE, followlocation = TRUE, ssl.verifypeer = FALSE)
con = gzcon(rawConnection(sit, 'rb'))
source(con)
close(con)
data <- new.env()

# Load historical data and adjusts for splits and dividends
tickers = spl('^GSPC')
getSymbols(tickers, src = 'yahoo', from = '2000-01-01', env = data, auto.assign = T)
for(i in ls(data)) data[[i]] = adjustOHLC(data[[i]], use.Adjusted=T) 


#Sets backtesting environment and convert to monthly prices
bt.prep(data, align='remove.na', fill.gaps = T) 
prices = data$prices  
prices = prices[ endpoints(prices, on="months", k=1), ]


#Create a empty list for attaching the models to at a later stage
models = list()


#Calculate the moving averages- not considered: lag them one day to prevent lookback bias
SMA_2 <- SMA(prices,2)
SMA_10 <- SMA(prices,10)  


#Specify the weights to be used in the backtest
data$weight[] = NA #Zero out any weights from previous
data$weight[] = ifelse(as.integer(SMA_2>SMA_10)==1,1,0)  #If price of 2SMA is above the 10SMA then buy

#Call the function to run the backtest given the data, which contains the prices and weights.
#models$dmac2_10 = bt.run.share(data, trade.summary=T)
models$dmac2_10 = bt.run.share(data, clean.signal=T)


#Plot equity curve 
plot(models$dmac2_10$equity, main="Equity Curve")

Not sure if I am doing something else wrong but I'd appreciate your help.

Thanks, Marya

marya
  • 31
  • 3

0 Answers0