Calculating Average True Range (ATR) on OHLC data with Python

That's not the right calculation for TR see - ATR, but here is how I would do it:

Where alpha = 2 / (span+1)

df['ATR'] = df['TR'].ewm(span = 10).mean()

Otherwise you should be able to easily do you're own smoothing like this:

df['ATR'] = ( df['ATR'].shift(1)*13 + df['TR'] ) / 14

Pandas ewm


For anyone else looking on how to do this, here is my answer.

def wwma(values, n):
    """
     J. Welles Wilder's EMA 
    """
    return values.ewm(alpha=1/n, adjust=False).mean()

def atr(df, n=14):
    data = df.copy()
    high = data[HIGH]
    low = data[LOW]
    close = data[CLOSE]
    data['tr0'] = abs(high - low)
    data['tr1'] = abs(high - close.shift())
    data['tr2'] = abs(low - close.shift())
    tr = data[['tr0', 'tr1', 'tr2']].max(axis=1)
    atr = wwma(tr, n)
    return atr