I cant seem to get this python formula working correctly for me. Maybe I am just not understanding how it works.
As you can see I feed in the last 16days of data. I want to take the average, of the last 15 days of data for true range. The part I don’t understand is the formula for true range takes the previous days close. So I can’t just feed in 15 days of data because I need the 16th days closing price.
It seems to be partially working, its give me the rolling average true range, but I only want the average of 15 days. Not the 16 days I’m feeding in. Remember I am only feeding in 16 days because the 15th day needs that previous day.
Does that make sense? What am I doing wrong?
def calculate_atr(symbol, period, start_date, end_date):
# Fetch the data
data2 = df[df['TickerSymbolCSI'] == symbol]
#print(data2)
data = data2.sort_values('Date', ascending=False).head(16)
#print(data)
#print(data['Date'])
# Calculate True Range
data['High-Low'] = abs(data['High'] - data['Low'])
#print(data['High-Low'])
data['High-PrevClose'] = abs(data['High'] - data['Close'].shift(-1))
#print(data['High-PrevClose'])
data['Low-PrevClose'] = abs(data['Low'] - data['Close'].shift(-1))
#print(data['Low-PrevClose'])
data['True Range'] = data[['High-Low', 'High-PrevClose', 'Low-PrevClose']].max(axis=1)
#print(data['True Range'])
# Calculate ATR
data['ATR'] = data['True Range'].rolling(window=period).mean()
#print(data['ATR'])
return data