Algorithmic Trading & Indicators Beginner

Convert Standard OHLC Candles to Heikin-Ashi Candles in Python

Noise-free trend detection in Python by converting standard OHLCV DataFrames into smoothed Heikin-Ashi candlesticks with automated trend flip signals.

#pandas#numpy

Problem Statement

Standard candlesticks produce false reversal wicks during strong trends. Converting OHLC into Heikin-Ashi smooths price action so trend-following bots stay in winning trades longer.

Formula / Core Logic

HA_Close = (Open + High + Low + Close) / 4 HA_Open_t = (HA_Open_{t-1} + HA_Close_{t-1}) / 2

Installation

pip install pandas numpy
heikin-ashi-candlestick-conversion-python-pandas.py
import pandas as pd
import numpy as np

def to_heikin_ashi(df):
    ha = df.copy()
    ha['HA_Close'] = (df['Open'] + df['High'] + df['Low'] + df['Close']) / 4.0
    ha_open = np.zeros(len(df))
    ha_open[0] = (df['Open'].iloc[0] + df['Close'].iloc[0]) / 2.0
    for i in range(1, len(df)):
        ha_open[i] = (ha_open[i - 1] + ha['HA_Close'].iloc[i - 1]) / 2.0
    ha['HA_Open'] = ha_open
    ha['HA_High'] = ha[['High', 'HA_Open', 'HA_Close']].max(axis=1)
    ha['HA_Low'] = ha[['Low', 'HA_Open', 'HA_Close']].min(axis=1)
    ha['HA_Bullish'] = np.where(ha['HA_Close'] > ha['HA_Open'], 1, -1)
    return ha

Get the Complete 100+ Python Quant & Automation Bundle

Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).

Buy Full Bundle on Gumroad ($19) →

Frequently Asked Questions

Q: Should orders be executed at Heikin-Ashi Close or real Close?

Always execute backtest fills at the real market Close (`df['Close']`), as `HA_Close` is a synthetic average price.