Quantitative research, trading strategy ideas, and backtesting for the FX and equity markets

Main menu

Monthly Archives: August 2012

Time really flies… it is hard to believe that it has been over a month since my last post. Work and life in general have consumed much of my time lately and left little time for research and blog posts. Anyway, on to the post!

This post will be the first in a series of to cover a momentum strategy using R.

One of my favorite strategies is a momentum or relative strength strategy. Here are just a few of the reasons why I like momentum:

Simple to implement

Long only or long/short portfolios

Many ways to define the strength or momentum measure

It just works

Also, a momentum strategy lends itself well to potential for diversification. The universe of instruments can be infinite, but the instruments traded are finite. Think about it this way… Investor A looks at 10 instruments and invests $1000 in the top 5 instruments ranked by momentum. Investor B looks at 100 instruments and invests $1000 in the top 5 instruments ranked by momentum. Investor A is limiting his potential for diversification by only having a universe of 10 instruments. Investor B has a much larger universe of instruments and can in theory be more diversified. Theoretically speaking, you can trade an infinite number of instruments with a finite amount of trading capital using a momentum or relative strength strategy.

Note that the for loop converts the data to monthly and subsets the data so that the only column we keep is the adjusted close column. We now have four objects (XLY, XLP, XLE, XLF) that have the Adjusted Close price.

That will wrap up this first post for a quick and easy way to rank assets based on 3 month simple returns. Future posts will explore other methods for ranking and using quantstrat to backtest momentum.

Here is the code in full.

require(quantstrat)#Load ETFs from yahoo
currency("USD")symbols = c("XLY","XLP","XLE","XLF")
stock(symbols, currency="USD",multiplier=1)
getSymbols(symbols, src='yahoo', index.class=c("POSIXt","POSIXct"), from='2000-01-01')#Convert to monthly and drop all columns except Adjusted Closefor(symbolinsymbols){
x <- get(symbol)
x <- to.monthly(x,indexAt='lastof',drop.time=TRUE)
indexFormat(x) <- '%Y-%m-%d'colnames(x) <- gsub("x",symbol,colnames(x))
x <- x[,6]#drops all columns except Adjusted Close which is 6th columnassign(symbol,x)}#merge the symbols into a single object with just the close prices
symbols_close <- do.call(merge,lapply(symbols,get))#xts object of the 3 period ROC of each column in the close object#The 3 period ROC will be used as the ranking factor
roc <- ROC(symbols_close, n = 3, type = "discrete")#xts object with ranks#symbol with a rank of 1 has the highest ROC
r <- as.xts(t(apply(-roc,1,rank)))