How to calculate Heikin Ashi candles in Python for trading | by Gianluca Malato | 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.
Quantitative traders know that they need to extract as much information as possible from price charts. Price action is a very useful technique to spot trading opportunities, but it’s sometimes difficult to read because candlestick charts might be messy or noisy. So, traders need a tool to smooth price action and remove noise. Heikin Ashi candles can help us. Let’s see how.
Heikin Ashi candles (sometimes called Heiken Ashi) are a particular kind of candlestick chart that tries to remove noise from price action. Particularly, in this kind of chart, there are no gaps.
Let’s see a chart of S&P 500 with plain candlesticks.
As you can see, there are a lot of daily gaps and the shadows of the candles are sometimes wide and make it difficult to decide what to do.
Heikin Ashi candles are calculated this way:
Open: (Open (previous candle) + Close (previous candle))/2
Close: (Open + Low + Close + High)/4
High: the same of the actual candle
Low: the same of the actual candle
As you can see, the calculation of today’s HA candle uses data from both today's and yesterday’s candles. This way, HA candles smooth price action.
The result, applied to the same chart is:
As you can see, there are no gaps and the chart is easier to read.
Using HA charts is very simple. First of all, we can see that before an important reversal we can detect some spinning top patterns, that are candles with very small real body and large shadows of almost the same size. This is an important way to detect a trend reversal.
Then, we can see that when the trend is strong, the opposite shadow is almost absent (i.e. in a strong bullish trend, lower shadows are invisible and in a strong bearish trend, upper shadows are invisible). This gives us a clear overview of the strength of a trend. Finally, a color change is very often used as a confirmation that the trend has changed direction and may be used as an operative signal.
These are all useful items for building a trading strategy and we don’t need to be able to catch several types of patterns like in candlestick charts, but we only need to spot spinning tops and color changes.
The drawback of Heikin Ashi candles is that, like any other kind of moving average, they catch the trend reversal with some delay. So, their signals are always a confirmation of something that has already happened. Thus, they are useful only then you have to work with long-term strategies because the delay in the signal will always make you enter and exit late. However, HA candles are a very useful tool, especially when you work with scalping and need to smooth very noisy price action. Just like any other indicator, it’s useful to use it with another signal, for example with moving averages.
Let’s now see how to calculate Heikin Ashi candles in Python.
For this example, we’re going to analyze S&P 500 data from December 15, 2020 to April 15, 2021. You can find the whole code here on GitHub.
First, let’s install some useful libraries:
!pip install yfinance!pip install mpl_finance
Then, let’s import them and apply some graphical enhancements:
import pandas as pdimport yfinancefrom mpl_finance import candlestick_ohlcimport matplotlib.pyplot as pltplt.rcParams['figure.figsize'] = [12, 7]plt.rc('font', size=14)
Now we can download S&P 500 data and replace the date with a sequential index
name = 'SPY'ticker = yfinance.Ticker(name)df = ticker.history(interval="1d",start="2020-12-15",end="2021-04-15")df['Date'] = range(df.shape[0])df = df.loc[:,['Date', 'Open', 'High', 'Low', 'Close']]
Let’s create a simple function to draw the chart of a data frame:
def plot_chart(df):  fig, ax = plt.subplots()  candlestick_ohlc(ax,df.values,width=0.6, \                   colorup='green', colordown='red', alpha=0.8)  fig.tight_layout()fig.show()
Now, let’s see the original candlestick chart:
plot_chart(df)
As you can see, it’s full of gaps and long tails.
Now, let’s calculate Heikin Ashi candles according to the original formula. Since we need to check the previous candle, we have to skip the first row.
We’ll store the result in a new data frame called df_ha. We copy the original data of the candles in order to keep the same highs and lows. Then, we remove the first line.
df_ha = df.copy()for i in range(df_ha.shape[0]):  if i > 0:    df_ha.loc[df_ha.index[i],'Open'] = (df['Open'][i-1] + df['Close'][i-1])/2    df_ha.loc[df_ha.index[i],'Close'] = (df['Open'][i] + df['Close'][i] + df['Low'][i] +  df['High'][i])/4df_ha = df_ha.iloc[1:,:]
We can now plot the result:
plot_chart(df_ha)
As we can see, gaps disappeared and the spinning top HA candles are able to predict a trend inversion quite well.
Heikin Ashi candles are a very useful tool for any kind of trader and it has to be present in every investor’s toolbox. Just don't forget that smoothing price action has the price of a delayed signal.
Gianluca Malato is an Italian Data Scientist and a fiction author. He is the founder of YourDataTeacher.com, an online school of data science, machine learning and data analysis.