Oh no! Where's the JavaScript?
Your Web browser does not have JavaScript enabled or does not support JavaScript. Please enable JavaScript on your Web browser to properly view this Web site, or upgrade to a Web browser that does support JavaScript.

Python function to calculate Heikin-Ashi candles

Last updated on 2 days ago
K
karthikJunior Member
Posted 2 days ago
Heikin-Ashi Formula:

Given standard candlesticks with Open, High, Low, Close (OHLC):

HA_Close = (Open + High + Low + Close) / 4
HA_Open = (Previous HA_Open + Previous HA_Close) / 2
HA_High = max(High, HA_Open, HA_Close)
HA_Low = min(Low, HA_Open, HA_Close)
K
karthikJunior Member
Posted 2 days ago
import pandas as pd

def calculate_heikin_ashi(df):
 """
 Calculates Heikin-Ashi candles from OHLC data.
 
 Parameters:
 df (DataFrame): Pandas DataFrame with columns ['Open', 'High', 'Low', 'Close']
 
 Returns:
 DataFrame: New DataFrame with Heikin-Ashi candles ['HA_Open', 'HA_High', 'HA_Low', 'HA_Close']
 """

 ha_df = df.copy() # Create a copy to avoid modifying the original DataFrame

 # Calculate HA_Close
 ha_df["HA_Close"] = (ha_df["Open"] + ha_df["High"] + ha_df["Low"] + ha_df["Close"]) / 4

 # Initialize HA_Open with the first Open value
 ha_df["HA_Open"] = 0
 ha_df.iloc[0, ha_df.columns.get_loc("HA_Open")] = (ha_df.iloc[0]["Open"] + ha_df.iloc[0]["Close"]) / 2

 # Calculate HA_Open for the rest of the rows
 for i in range(1, len(ha_df)):
 ha_df.iloc[i, ha_df.columns.get_loc("HA_Open")] = (
 ha_df.iloc[i - 1]["HA_Open"] + ha_df.iloc[i - 1]["HA_Close"]
 ) / 2

 # Calculate HA_High and HA_Low
 ha_df["HA_High"] = ha_df[["High", "HA_Open", "HA_Close"]].max(axis=1)
 ha_df["HA_Low"] = ha_df[["Low", "HA_Open", "HA_Close"]].min(axis=1)

 return ha_df[["HA_Open", "HA_High", "HA_Low", "HA_Close"]]

# Example Usage:
# Create sample OHLC data
data = {
 "Open": [100, 102, 104, 106, 108],
 "High": [103, 105, 107, 109, 111],
 "Low": [99, 101, 103, 105, 107],
 "Close": [102, 104, 106, 108, 110],
}

df = pd.DataFrame(data)

# Calculate Heikin-Ashi candles
ha_df = calculate_heikin_ashi(df)
print(ha_df)
You can view all discussion threads in this forum.
You cannot start a new discussion thread in this forum.
You cannot reply in this discussion thread.
You cannot start on a poll in this forum.
You cannot upload attachments in this forum.
You cannot download attachments in this forum.
Sign In
Not a member yet? Click here to register.
Forgot Password?
Users Online Now
Guests Online 6
Members Online 0

Total Members: 14
Newest Member: Frank_nKansas