1

I'm trying to get EMA using Talib and pandas, but they are totally different from tradingview. I don't know what is wrong.

My code is like this:

import pandas as pd
import requests
import talib

pd.set_option('display.width', 300)
pd.set_option("display.max_rows", None, "display.max_columns", None)

binance = requests.get('https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1d&limit=200')
e = binance.json()
df = pd.DataFrame(e, columns=['timestamp', 'open', 'high', 'low','close','volume','Kline Close time','Quote asset volume','Number of trades','Taker buy base asset volume','Taker buy quote asset volume','ignore'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')

# EMA 20 and 50 and 100 using pandas ewn
df['EMA20'] = df['close'].ewm(span=20,min_periods=20,adjust=False,ignore_na=False).mean()
df['EMA50'] = df['close'].ewm(span=50,min_periods=50,adjust=False,ignore_na=False).mean()
df['EMA100'] = df['close'].ewm(span=100,min_periods=100,adjust=False,ignore_na=False).mean()

# EMA 20 and 50 and 100 using talib
df["EMA20_talib"] = talib.EMA(df.close, 20)
df["EMA50_talib"] = talib.EMA(df.close, 50)
df["EMA100_talib"] = talib.EMA(df.close, 100)
df = pd.DataFrame(df,columns=['timestamp', 'open', 'high', 'low','close','EMA20','EMA50','EMA100','EMA20_talib','EMA50_talib','EMA100_talib'])
print(df.tail(1))

Result:

     timestamp         EMA20         EMA50        EMA100   EMA20_talib   EMA50_talib  EMA100_talib
199 2022-12-23  16954.726361  17406.537793  18459.035371  16954.726365  17404.356357  18333.684938

Tradingview EMA (EMA20: RED, EMA50: Pink, EMA100: yellow)

tradingview ema

One boy
  • 216
  • 1
  • 7

1 Answers1

1

If you would look at df.head(25) you would see that a very first value of EMA(20) mismatchs too. That means TA-Lib's EMA calculates the first value differently than pandas. But TA-Lib has 3 compatibility modes: Classic/Metastock/Tradestation. And few indecators really use them. One of them is EMA and it has 2 variants of very first value calculation: Classic and "Other" (Metastock for ex.). Details could be found in its code: https://github.com/TA-Lib/ta-lib/blob/master/src/ta_func/ta_EMA.c#L285
And if you try another compatibility mode - the values will match with pandas.
All you need is to add:
talib.set_compatibility(1)
before calling talib.EMA().

You may also switch compatibility back after that with talib.set_compatibility(0)

truf
  • 2,843
  • 26
  • 39