Re: Python function to calculate Heikin-Ashi candles
[code]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)
[/code]