# Modified Donchian Band Trend Follower using R, Quantmod, TTR

**Intelligent Trading**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

I’ve been toying around with the examples given on the FOSS trading site for some of the great work they’ve put together in the Quantmod and TTR packages. Those viewers who are looking for a nice (and free) backtesting suite to possibly complement some of your other results or work in say, Weka, should familiarize yourselves with R. Not only can it serve as a canvas to simulate ideas and concepts, but can process the backend results towards more trader oriented metrics, than using something like Weka as a standalone tool. As you gain more proficiency in data mining and machine learning concepts in Weka, you can also make the move to integrate the tools inside of R, as R contains the majority of machine learning schemes inside of various packages.

Fig 1. Modified Donchian Channel System Simulation

As an example of how to use some of their tools (along with traditional R packages) for fast prototyping, I put together an example of a modified Donchian Channel trend following system along with how you might simulate it using R. The typical Donchian Channel Bands are used as breakout entry and exit signals. I.e. once an n period high has been breached you go long, then exit when the n period low has been breached — visa versa for short. In this example, however, we simply enter long on the average line break and stay long as long as it is above. A short signal is entered on the average line break to the downside. Unlike a price/moving average type system, there wasn’t a lot of choppiness causing false starts around the average line, which is a plus.

I am still trying to familiarize myself more with the tools, and am still at the point where I like how simple and fast the static vector computations work (similar to numpy in Python), but I am wondering how fast more sophisticated entry/exits requiring loops will work. I still expect to work on some of these types of scenarios, as I am really enjoying the capabilities of R along with some of these trading oriented packages.

Although the system (using QQQQ as an example) is in no way optimized nor analyzed for robustness, it returned a respectable 60% versus a buy and hold loss over the past roughly two years (showing a simple example of trend type trading).

Here is the complete code for you to replicate (I used the R version 2.7.10.1).

Note: if some of it looks familiar to the FOSS RSI example, it is exactly because I used that example as a starting point, so there will be some overlap in comments and actions.

# We will need the quantmod package for charting and pulling

# data and the TTR package to calculate Donchian Bands.

# You can install packages via: install.packages(“packageName”)

# install.packages(c(“quantmod”,”TTR”))

# See Foss Trading Blog for RSI template

library(quantmod)

library(TTR)

tckr<-"QQQQ"

tckr_obj<-QQQQ
start<-"2008-01-01"

end<- "2010-03-08"
# Pull tckr index data from Yahoo! Finance

getSymbols(tckr, from=start, to=end)

QQQQ.cl<-QQQQ[,6]

QQQQ.H<-QQQQ[,2]

QQQQ.L<-QQQQ[,3]

dc<-DonchianChannel(cbind(QQQQ.H,QQQQ.L),n=80)
#Plotting Donchian Channel

ymin=25

ymax=55

par(mfrow=c(2,2), oma=c(2,2,2,2))

# max, avg, min <- red, blue, green

plot(dc[,1],col=”red”,ylim=c(ymin,ymax),main=””)

par(new=T)

plot(dc[,2],col=”blue”,ylim=c(ymin,ymax),main=””)

par(new=T)

plot(dc[,3],col=”green”,ylim=c(ymin,ymax),main=””)

par(new=T)

plot(QQQQ.cl,ylim=c(ymin,ymax),pch=15,main=”donchian bands max/avg/min”)

lines(QQQQ.cl,ylim(ymin,ymax))

###################################################

# Create the long (up) and short (dn) signals

sigup <-ifelse(QQQQ.cl > dc[,2],1,0)

sigdn <-ifelse(QQQQ.cl < dc[,2],-1,0)
# Lag signals to align with days in market,

# not days signals were generated

sigup <- lag(sigup,1) # Note k=1 implies a move *forward*

sigdn <- lag(sigdn,1) # Note k=1 implies a move *forward*
# Replace missing signals with no position

# (generally just at beginning of series)

sigup[is.na(sigup)] <- 0

sigdn[is.na(sigdn)] <- 0
# Combine both signals into one vector

sig <- sigup + sigdn
# Calculate Close-to-Close returns

ret <- ROC(tckr_obj[,6])

ret[1] <- 0
# Calculate equity curves

eq_up <- cumprod(1+ret*sigup)

eq_dn <- cumprod(1+ret*sigdn)

eq_all <- cumprod(1+ret*sig)
#graphics

mfg=c(1,2)

plot(eq_up,ylab=”Long”,col=”green”)

mfg=c(2,2)

plot(eq_all,ylab=”Combined”,col=”blue”,main=”combined L/S equity”)

mfg=c(2,1)

plot(eq_dn,ylab=”Short”,col=”red”)

title(“Modified Donchian Band Trend Following System (intelligenttradingtech.blogspot.com)”, outer = TRUE)

##############################################################################################################

P.S. As always, please use your own due diligence in all work borrowed from this site. There are some areas that I believe are not quite correct in the simulation framework, needless to say, you have a complete script to start your own examples and backtesting.

**leave a comment**for the author, please follow the link and comment on their blog:

**Intelligent Trading**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.