pythonpython-3.xfinanceta-libtechnical-indicator

ta-lib library ATR calculate wrong


I wrote a simple program for calculate daily ATR with ta-lib library. I compare result with ATR indicator in Tradingview and them are very different. Code is: `

def ohlcv(symbol, tf, bars_back=MAX_BAR_BACK):
    ohlc = exchange.fetch_ohlcv(symbol, timeframe=tf, limit=bars_back)
    ohlc_df = pd.DataFrame(ohlc, columns=['datetime', 'open', 'high', 'low', 'close', 'volume'])
    ohlc_df['datetime'] = pd.to_datetime(ohlc_df['datetime'], unit='ms')
    return ohlc_df


def ATR(symbol, tf, period=MAX_BAR_BACK):
    data = ohlcv(symbol, tf)
    close = data['close'].values
    high = data['high'].values
    low = data['low'].values
    data.dropna(inplace=True)
    return ta.ATR(high, low, close, timeperiod=period)[-1]

tradingview = ta.ATR on BTCUSDT ==> 278.7 MyCode = ATR() on BTCUSDT ==> 1275.0

Sorry, my English is poor. Please F1 me!!!

Which one is correct? and What is fault of My code??????


Solution

  • ATR is a Wilders smoothing over TR.

    1. TradingView calculates TR for ATR a bit differently. In TA-Lib TR for 1st day is undefined. TradingView uses high-low for day 1. That affect results a bit but not so big as in your case.
    2. Wilders smoothing (RMA in Trading View or Wilders in TD Ameritrade) is a kind of EMA. EMA has memory effect. It depends on a starting point of calculation. I mean if you have 14-day period EMA and calculate it since the beginning of the month till today, since the brginning of the year till today and since the beginning of the historical data (date of the first trade of your ticker) - you will get 3 different results. And these results might defer a lot. The shorter calculation period the bigger effect has starting point and difference is bigger. So, when you started ATR calculation? And when TradingView started their ATR calculation?
      Related discussion is: https://github.com/mrjbq7/ta-lib/issues/560