A Simple Breakout Trading Strategy in Python | by Sofien Kaabar, CFA | Towards Data Science

Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
I have just published a new book after the success of New Technical Indicators in Python. It features a more complete description and addition of complex trading strategies with a Github page dedicated to the continuously updated code. If you feel that this interests you, feel free to visit the below link, or if you prefer to buy the PDF version, you could contact me on Linkedin.
www.amazon.com
Trading is divided into many different strategies that rely on trend-following, mean reversion, volatility, or other factors. Successful strategies rely on the current market state, for example, when markets are strongly trending, mean reversion strategies tend to fail and therefore we always have to adapt our market approach accordingly. Below is a breakout strategy that uses an indicator called the Donchian Channel. The basic idea is to make ranges as objective as we can (i.e. measurable) and then trade on the breakout (i.e. the start of a trend). The goal of the article is therefore to see whether this indicator can add value into our overall trading system or not. Does it provide good signals? Are the triggers to be taken seriously?
Created by Richard Donchian, this simple and great indicator is used to identify breakouts and reversals. Just like the Bollinger bands, it is used in an almost similar fashion. Our goal is to determine objectively a range exit by the surpass or break of any of the barriers. The way it is formed is by first calculating the maximum of the last n-period highs and the minimum of the last n-period lows, then calculating the average of them both. This gives us three measures: The Donchian upper band, the lower band, and the middle band. Here’s the mathematical formula followed later by the Python code used on an OHLC data structure.
def donchian(Data, low, high, where_up, where_down, median, period):        for i in range(len(Data)):        try:            Data[i, where_up] = max(Data[i - period:i + 1, 1])        except ValueError:            pass    for i in range(len(Data)):        try:            Data[i, where_down] = min(Data[i - period:i + 1, 2])         except ValueError:            pass            for i in range(len(Data)):         try:            Data[i, median] = (Data[i, where_up] + Data[i, where_down]) / 2         except ValueError:            passdonchian(Data, 2, 1, 4, 5, 6, 20)'''plt.plot(Data[-500:, 3], color = 'black')plt.plot(Data[-500:, 4])plt.plot(Data[-500:, 5])plt.plot(Data[-500:, 6])plt.grid()'''
Visually, the Donchian channel seems to envelop prices and that is understandable because the it takes into account the current extreme and therefore the market never lies outside of the channel.
The basic strategy of the Donchian channel is the breakout strategy. It is intuitive and clear, below are the rules:
Buy whenever the market surpasses the last upper channel.
Sell (go short) whenever the market breaks the last lower channel.
def donchian_signals(Data, onwhat, donch_up, donch_down):        for i in range(len(Data)):                  if Data[i, where_close] > Data[i - 1, donch_up]:              Data[i, 6] = 1                   elif Data[i, where_close] < Data[i - 1, donch_down]:              Data[i, 7] = -1                   return Data# Note: The onwhat variable is the closing price
We choose the last Donchian level because we want to know when we break our last high or low. Remember, the formula takes into account the current high and low and therefore the current price will never break them.
The conditions chosen for the back-test were more of a longer-term breakout in that we are using daily charts with a Donchian period of 60 days. This means that if the market surpasses the upper donchian channel of the last 60 days, then we buy into the trend. I have incorporated a simple stop-loss order of 100 pips over the three tested currency pairs below. I have chosen three major pairs as a proxy for this strategy, they are EURUSD, USDCHF, and GBPUSD. The next charts show the signal charts on the three back-tests.
The equity curve following a 0.5 pip per trade on a $10,000 lot size for comparison reasons. The starting balance is $1,000 and hence, a 1:100 leverage.
If you are also interested by more technical indicators and using Python to create strategies, then my best-selling book on Technical Indicators may interest you:
www.amazon.com
Visibly, it needs some improvements and the Donchian channels should have another indicator alongside them to confirm the signals or to add a volatility factor and stabilize the results.
There is another strategy that can be employed here. It relies on the middle band. We can try to develop a strategy based on them using the same back-testing conditions as the above. We know from the above introduction that the middle band is simply the average of the upper and lower bands and as such it can be compared to the moving average of the Bollinger bands. If you are interested in knowing more about the Bollinger bands, you can check this article where I provide more back-tests:
medium.com
The rules of the middle band strategy are therefore:
Buy whenever the market surpasses the middle band.
Sell (go short) whenever the market breaks the middle band.
def donchian_signals_middle(Data, onwhat, donch_middle, buy, sell):        for i in range(len(Data)):                  if Data[i, onwhat] > Data[i, donch_middle] and Data[i - 1, onwhat]  < \              Data[i, donch_middle]:              Data[i, buy] = 1                   elif Data[i, onwhat] < Data[i, donch_middle] and Data[i - 1, onwhat] > \              Data[i, donch_middle]:              Data[i, sell] = -1# Note: The buy and sell variables are the triggers (equivalent to column 6 and 7 in the first strategy code)
The signal charts of the second strategy are the below:
The equity curve is much less impressive.
Although the first strategy showed some potential, the second one failed to impress. It is clear that there is much to be done with the Donchian channel but it is good to know that we can attempt to quantify ranges and trade on their breakouts.