did i calculating MACD indicator values wrongly?

56 views Asked by At

I try calculating MACD indicator values(MACD Line - MACD signal) via ccxt data. i wrote code below. problem is my results is not same with trading view MACD indicator. Where is my mistake? Please help if anyone can. Thanks

import ccxt
import pandas as pd

def calculate_ema(data, window):
    return data.ewm(span=window, adjust=False).mean()

# Calculating MACD line & MACD Signal
def calculate_macd(df, short_window=12, long_window=26, signal_window=9):
    # Calculating EMA 12 & EMA 26
    short_ema = calculate_ema(df['close'], short_window)
    long_ema = calculate_ema(df['close'], long_window)

    # Calculating MACD line
    macd_line = short_ema - long_ema

    # calculating MACD signal line
    signal_line = calculate_ema(macd_line, signal_window)

    return macd_line, signal_line


# connect to exchane
exchange = ccxt.binance()
symbol = 'BTC/USDT'
timeframe = '15m'
limit = 26

# Fetch_ohlcv
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
print(df)
print()


macd_line, signal_line = calculate_macd(df)

# printing result
print("MACD Line:")
print(macd_line.tail())

print("\nSignal Line:")
print(signal_line.tail())
1

There are 1 answers

0
John On

Exponential moving averages require some run up time. I usually use the rule of thumb of a run in period of at least the length of the longest smoothing.

For MACD this would be 26 for the long average and 9 for the signal calc, so results should converge on popularly accepted values after 35 periods. It helps to seed the initial values with something reasonable like the last price of the first period.

The wiki article discusses the proper math to find the minimum run in time.

https://en.wikipedia.org/wiki/Exponential_smoothing