@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:
You can adjust the period parameter in the calculate_atr function to change the period over which the ATR is calculated.