Heikin-Ashi in Python — Coding the Candles from Scratch (pandas)

The averaging chain, and why HA_Open needs a loop

Heikin-Ashi computed in Python
Heikin-Ashi computed in Python

Heikin-Ashi is mostly straightforward arithmetic — except for one column that refuses to vectorize cleanly, because each value depends on the one before it. Let’s build it right, including that recursive bit. See the explainer for what the candles mean.

What you’ll need

  • Python 3.9+, pandas/numpy
  • open, high, low, close series.

From scratch

import numpy as np
import pandas as pd


def heikin_ashi(df):
    ha = pd.DataFrame(index=df.index)

    # HA_Close is a pure per-bar average — fully vectorized.
    ha["close"] = (df["open"] + df["high"] + df["low"] + df["close"]) / 4

    # HA_Open is recursive: each value needs the PREVIOUS HA_Open and HA_Close.
    ha_open = np.empty(len(df))
    ha_open[0] = (df["open"].iloc[0] + df["close"].iloc[0]) / 2   # seed the first bar
    for i in range(1, len(df)):
        ha_open[i] = (ha_open[i - 1] + ha["close"].iloc[i - 1]) / 2
    ha["open"] = ha_open

    # HA_High / HA_Low use the real high/low plus the HA open/close.
    ha["high"] = pd.concat([df["high"], ha["open"], ha["close"]], axis=1).max(axis=1)
    ha["low"]  = pd.concat([df["low"],  ha["open"], ha["close"]], axis=1).min(axis=1)

    return ha

Three of the four columns are trivial vectorized averages. HA_Open is the exception: it’s a running average of its own prior value and the prior HA_Close, so it needs a loop (or a numba/Cython accelerator). This chaining is exactly what smooths the series.

The one gotcha that matters: seeding

The first bar has no “previous” HA candle. The standard seed is HA_Open[0] = (Open[0] + Close[0]) / 2. Some libraries instead seed with the raw Open[0], or with the first HA_Close. The choice only affects the first handful of bars — because HA_Open is a repeated average, the seed’s influence halves every bar and is gone within ~10 bars. But it’s why two “correct” Heikin-Ashi implementations can disagree on the far-left edge of the chart. Don’t panic when they converge.

Why you can’t just use ewm or shift

It’s tempting to try ha["open"] = (ha["open"].shift() + ha["close"].shift()) / 2, but that’s wrong: shift() reads the raw prior value in one pass, whereas HA_Open must read its own already-computed prior value. That self-reference is the definition of a recursive series, and pandas won’t do it in a vectorized shift. The loop is correct; resist the clever one-liner.

Plotting it

import mplfinance as mpf
ha = heikin_ashi(df)
mpf.plot(ha, type="candle", style="charles", title="Heikin-Ashi")

That reproduces the smoothed candles from the output chart — clean runs of colour where the raw candles were choppy.

Gotchas

  • HA_Open is recursive. It needs its own previous value; a plain shift gives the wrong answer.
  • Seed the first bar. (Open[0] + Close[0]) / 2 is the convention; different seeds differ only at the extreme left.
  • The prices are averages. Don’t feed HA_Close into anything expecting a real traded price (order fills, gap stats).
  • Colour is HA_Close >= HA_Open. That’s the up/down test, not the real close vs real open.

The lazy one-liner

import pandas_ta as ta
ha = df.ta.ha()   # returns HA_open, HA_high, HA_low, HA_close

Same candles elsewhere: MQL5, Pine Script, EasyLanguage, NinjaScript. Then test a Heikin-Ashi rule in AlgoGen.


This post is educational, not financial advice. Indicators describe the past; they don’t predict the future. Backtest anything before you risk real money on it.

Sources and further reading

  1. Windowing operations (pandas documentation)

Historical research from the Algogen archive. Not investment advice.

Blog

Have a strategy idea?

Describe it in plain English, preview where your rules fire, then decide whether the evidence is worth a backtest.

Keep me postedHow it works