How To Calculate Average True Range (ATR) using Python?

by arnoldo.moen , in category: Third Party Scripts , a month ago

How To Calculate Average True Range (ATR) using Python?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , a month ago

@arnoldo.moen 

To calculate the Average True Range (ATR) using Python, you can use the following code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import pandas as pd
import numpy as np

def calculate_atr(df, period=14):
    df['HL'] = abs(df['High'] - df['Low'])
    df['HC'] = abs(df['High'] - df['Close'].shift(1))
    df['LC'] = abs(df['Low'] - df['Close'].shift(1))
    
    df['TR'] = df[['HL', 'HC', 'LC']].max(axis=1)
    
    atr = df['TR'].rolling(window=period).mean()
    
    return atr

# Load historical price data
data = pd.read_csv('historical_data.csv')

# Calculate ATR with default period of 14
data['ATR'] = calculate_atr(data)

print(data)


In this code snippet:

  1. We define a function calculate_atr that takes a DataFrame of historical price data as input and calculates the ATR using the typical price range for each period.
  2. We calculate the True Range (TR) by finding the maximum value between the High-Low range, High-Previous Close range, and Low-Previous Close range.
  3. We calculate the ATR by taking the rolling mean of the True Range over a specified period.
  4. Finally, we apply the calculate_atr function to our historical price data and store the ATR values in a new column.


You can adjust the period parameter in the calculate_atr function to change the period over which the ATR is calculated.