Backtrader: Working with Heikin Ashi

If you have ever pulled up a Heikin Ashi chart on a trading platform, you were probably awed at the beauty of the candles. They seem to capture the ups and downs of the price action with long swathes of green or red. Better still, the Heikin Ashi bars appear to really capture turning points in a trend. These turning points often follow with a lengthy run in the other direction. As a result, I would place a bet that most people who have seen the Heikin Ashi bars have considered a simple strategy of buying on green can selling on red. Unfortunately, life is never quite as simple as that, and as we will see later, good entry and exits on a Heikin-Ashi chart do not always result in great trades in the real world.

Heikin

Heikin-Ashi Background

As you might be able to guess from the name, the concept of Heikin Ashi candlesticks was born in Japan. What might surprise you though is that the normal OHLC candlestick also originated from the land of the rising sun. As such, it is not a case of our friends in the east doing things differently, Heikin Ashi candles are actually derivatives of the standard OHLC candlestick. They start with the same OHLC data and apply a formula to it in order to take out some of the noise from the price action. With that in mind, let’s take a little look at how a Heikin Ashi candle is calculated. (Full credit: Wikipedia)

  • Close = (open + high + low + close) / 4
  • High = maximum of high, open, or close (whichever is highest)
  • Low = minimum of low, open, or close (whichever is lowest)
  • Open = (open of previous bar + close of previous bar) / 2

The detectives among us might have already noticed that Heikin Ashi candles do not simply recalculate one bar of OHLC data, they need two bars. This means to you cannot accurately calculate a Heikin Ashi candle until you have at least 1 bar of historical data.

Another important difference between a standard candle and a Heikin Ashi is that theopenandcloseof the candles are not the same (as well as the high and the low). This might sound like stating the obvious after looking a the formula, but it has some repercussions on the accuracy of your backtest and results.

A comparison of normal candles vs heikin ashi candles

Adding Heikin Ashi Candles

Now that we have the background out of the way, let’s fire up Backtrader and get some Heikin Ashi bars on our charts! If you have previously plotted candlesticks before, you can be forgiven for thinking that you can change the line:

cerebro.plot(style='candlestick')

to:

cerebro.plot(style='heikinashi')

That would appear to be quite a logical way to do things. However, even if it did work, it would only display data in a Heikin style after the test is complete (since plotting is the last thing we do). For Heikin Ashi candles to influence our logic, we need to have the Heikin version of the open, high,lowandclosedata available during the test. To do this in we need to use Backtrader’s Data Filterto create Heikin Ashi data from our input source. (The official filter docs are here: https://www.backtrader.com/docu/filters.html)

A data filter essentially massages the data before it is fed into cerebro. A common use case is to filter out any out-of-hours/out-of-session bars that are in your data feed. With Heikin Ashi bars, the filter is still massaging/editing the data. The only difference is it is not removing anything.

Example Code

The example code below will allow you to see how to add a Heikin Ashi data filter to a strategy.

Important Note: The data in this tutorial uses the Quandl API. With this API you are limited to the number calls you can make per day. To have unlimited access to their free data, sign up for an API key here and add the apikeykeyword to the Quandl data call like so:

Reference: https://www.quandl.com/?modal=register

The Result

Running the code above should result in a chart which looks like this:

Heikin Ashi Candles in Backtrader

Ok, Job done…Not so fast!

Heikin Ashi’s are not real prices

We might now have Heikin Ashi bars on our chart but running a strategy on this data is going to cause you to suffer from unrealistic expectations. As we learned in the background section Heikin Ashi prices are not real prices. Therefore, your entry and exit prices will be different to real candles. To further compound things, the highs and lows are also different which can result in completely different outcomes when trailing stops are used. You can end up being in a trade for a completely different length of time.

To see this for yourself run the example code below.

Example Code

The example code above can be run in two modes. The first mode uses real prices and the second using Heikin prices (select the --heikinswitch when running the script). The strategy itself is designed to open and close the position at an arbitrary bar number. This is so that we can see the issue of unrealistic expectations first hand. Imagine if two traders and a monkey are trading. One trader is looking at a Heikin Ashi chart and the other is looking at a normal chart and the monkey is looking at a banana. If they all open and close a trade at exactly the same time, you would still expect all three to have the same PnL. That would be a realistic expectation of the outcome. However, you will see in this script that even though the trades are opened and closed at the same time, the outcome is different. This is because Backtrader does not track the real world when calculating PnL. It has no concept of what is “real”, it just calculates the PnL from whatever data feed you give it.

Result

The first result is using real data:

The second result is using Heikin candles:

As you can see, it resulted in an extra $3 dollars profit. The problem is that the $3 dollars never existed! We opened and closed at exactly the same point in time.

Taking it a step further

For a bit of fun, let’s take the example a step further and implement the strategy mentioned at the start of the post. As a recap, I was talking about the temptation to buy on green candles and sell on red. After this example, I hope we will start to see just how inaccurate your results can be if you do not setup correctly.

Example Code

The code above is only really meant to be run with the --heikinflag so you can take a look at what the PnL would be when setup incorrectly. Without the --heikinflag, the strategy will still work. It will just trade on colour changes for normalOHLCdata.

Result

So running the code with the --Heikinflag results in some very nice profits indeed. Over $1279. Looking at the chart is enough to get you excited too. Look at how consistently we are buying the dips and selling the highs.

Buy Green, Sell Red Strategy Heikin data only

So it looks good at first glance. So now we need to see what would the real returns be if you bought and sold at exactly the same times but using actual prices. To solve that problem we need to develop a method to look at Heikin Ashi candles but to trade on real data.

Heikin Ashi Solution

To tackle this we should only use Hiekin-Ashi data to decide when to enter and exit a position. Then we use a second data feed containing real prices to enter/exit the position. The following code presents just one solution to the problem. It is good enough to get the job done but can certainly be improved upon!

Example Code

Code Commentary

We start by obtaining two versions of the same data feed. Once we have two copies of the data feed, we filter one of them, turning it into Heikin Ashi data and then add both feeds under different names.

Once loaded, the strategy will then provide an alias to the added data feeds during the __init_()call. This will help us easily reference the correct datafeed on subsequent calls of next().

Finally during next()we check to see if the Heikin feed closed above the open. If it did, then we have a green candle and go long. If it closed lower, then we have a red candle and we go short. Notice that when we enter a position we provide it with the aliasself.real. This is to ensure the trade is placed on the correct data feed and thus the correct/real price data is used.

The Result

Expected output of Example 3

And the real world performance……$51.65! Quite a departure from the $1279 we got earlier. Hopefully, this demonstrates the importance of making sure you setup correctly when playing with Heikin Bars or you could be in for some real disappointment when you take your code live. Don’t get me wrong though, I am not suggesting Heikin Ashi’s are bad or misleading. After all, this strategy was not exactly designed for stellar performance and it still returned a real-world profit!