ATR Calculation in python

Hi Team,

I calculated ATR using the below code but it’s not matching with the chart

def atr(df, period=14):
high_low = df[‘High’] - df[‘Low’]
high_close = np.abs(df[‘High’] - df[‘Close’].shift())
low_close = np.abs(df[‘Low’] - df[‘Close’].shift())
tr = pd.DataFrame({‘high_low’: high_low, ‘high_close’: high_close, ‘low_close’: low_close})
true_range = tr.max(axis=1)
return true_range.rolling(window=period).mean()

I reffered to many codes on internet even took help from chatgpt but the values are not matching on chart, I request someone to help me with the code or formula of which values will match accurately on the chart

hi @Lobster346
Use Talib library for ATR, the values will match

1 Like

@Tradehull_Imran Sir, I tried everything TALIB, Pandas Ta, even few codes from chatgpt as well but nothing is accurattely matching with the values on the chart, don’t know whats wrong with ATR

df[‘atr_talib’] = talib.ATR(df[‘High’],df[‘Low’],df[‘Close’])
df[‘atr_pandas’] = ta.atr(df[‘High’],df[‘Low’],df[‘Close’],length=14)

If I make the period as 1 then it perfectly matches but with other periods it’s not matching. It would be so helpful if you can help me get the accurate values or atleast show with some sample code and output if the values are accurately matching or not

Try this snippet …true_range.ewm(span=period, min_periods=period, adjust=False).mean()

It all depends on what type of moving average is used while calculating the ATR.

If you are comparing ATR value you have calculated with tradingview, then make sure same MA is used.

In your scenario, you are using a simple moving average but tradingview uses RMA by default. You can go to settings and change RMA to SMA. Then it should match your calculation.

Hope this helps.

1 Like

Thank you so much @ekveer @AmitKAswani and @Tradehull_Imran!!!

The code for ATR is working fine with RMA :))

1 Like

I need your help with OBV and Twiggs Money Flow Index now - If you can help me with the code that returns values which matches on the chart - I’m figuring out but values are not matching

Hi @Tradehull_Imran

Can you help me with Twiggs money flow Index

def calculate_tmf2(df, period):
    """
    Calculates Twiggs Money Flow (TMF) for a given DataFrame with OHLCV data.
    """
    # Shift the 'Close' column to get the previous day's close
    df['Prev_Close'] = df['Close'].shift(1)
    
    # Calculate True Range High (TRH) and True Range Low (TRL)
    df['TRH'] = df[['High', 'Prev_Close']].max(axis=1)
    df['TRL'] = df[['Low', 'Prev_Close']].min(axis=1)

    # Calculate True Range (TR)
    df['TR'] = df['TRH'] - df['TRL']

    # Calculate Volume Multiplier (VM)
    df['VM'] = np.where(
        df['TR'] != 0,
        ((df['Close'] - df['TRL']) - (df['TRH'] - df['Close'])) / df['TR'],
        0
    )

    # Calculate Accumulation Distribution (AD)
    df['AD'] = df['Volume'] * df['VM']

    # Wilder's EMA calculation function
    def wilders_ema(series, period):
        return series.ewm(alpha=1/period, adjust=False).mean()

    # Apply smoothing to AD and Volume
    df['AD_EMA'] = wilders_ema(df['AD'], period)
    df['Volume_EMA'] = wilders_ema(df['Volume'], period)

    # Calculate TMF and normalize it (between -1 and 1)
    df['TMF'] = np.where(df['Volume_EMA'] != 0, df['AD_EMA'] / df['Volume_EMA'], 0)

    # Clip the TMF values to ensure it stays between -1 and 1
    df['TMF'] = df['TMF'].clip(-1, 1)

    # Return the DataFrame with TMF values
    return df

The above code is working fine on Day candle that too if I pass 365 Days data, but when I change it lower timeframes on a full length data it is not showing incorrect values. Don’t know what to do, if someone can help it would be great