0
votes

Getting something wrong.

In the below code I'm calculating the 1 day, 3 days, 5 days ATR for S&P 500. However, there is something wrong that I'm unable to figure out.

any help will be much appreciated.

import pandas_datareader as pd
from datetime import date as d
import matplotlib.pyplot as plt
import numpy as np
import pandas as p
start = d(2018,1,16)
end = d.today() 
ticker = '^GSPC'
data_source = 'yahoo'
stock_data = pd.DataReader(ticker, data_source, start, end)
def atr_calc(stock_data):
    stock_data['ATR1'] = abs (stock_data['High'] - stock_data['Low'])
    stock_data['ATR2'] = abs (stock_data['High'] - stock_data['Close'].shift())
    stock_data['ATR3'] = abs (stock_data['Low'] - stock_data['Close'].shift())
    stock_data['TrueRange'] = stock_data[['ATR1', 'ATR2', 'ATR3']].max(axis=1)
    return stock_data 
atr_calc(stock_data)
#print(stock_data['TrueRange'].mean())  #This is to calculate the average of True Range over the above given timeframe 
#print(stock_data.info())
totalentries = len(stock_data.index)  # To display the total number of elements in this dataframe over the above given timeframe
#x1 = stock_data['TrueRange'].iloc[-1]
i = -1
x1 = stock_data['TrueRange'].iloc[i]
y = 4
x3 = 0
for i in range(y):
 print(i)   
 print(stock_data['TrueRange'].iloc[-i])    
 x3 = x3 + stock_data['TrueRange'].iloc[-i]
# i = i+1
print('1 day True Range:',  x1)
print('3 days True Range:', x3) #the aboe for loop not working - it should calculate the average of last 3 days true range value but it is still taking the firstday value that is it's still taking 16'Jan TR value as well
#print('5 days True Range': x5)
#print('7 days True Range': x7)
#print('10 days True Range': x10)
#print('15 days True Range': x15)
#print('20 days True Range': x20)
#print('30 days - 1 Month True Range': x30)
#print('45 days True Range': x45)   
#print('60 days - 2 months True Range': x60)    
#print('75 days - 2 and Half Months True Range': x75)
#print('90 days - 3 Months True Range': x90)
#print('180 days - 6 Months True Range': x180)
#print('360 days - 1 Year True Range': x360)    
1
Could you give a hint about what exactly you mean when you say "something is wrong". Do you get an error running your code? Does it not give the output you desire? If so, please provide sample data and expected output, so we can help you - FlyingTeller
It is giving me the output but when the 3days ATR is calculated, it is also taking the 1st day TR(i.e, of date 16'Jan) into the calculation which I don't want. Basically, I want the 3 days ATR as of 15'Feb, 14'Feb, and 13'Feb. - Joe

1 Answers

0
votes
period = 14
tr1 = abs(df['bidhigh'] - df['bidlow'])
tr2 = abs(df['bidhigh'] - df['bidclose'].shift())
tr3 = abs(df['bidlow'] - df['bidclose'].shift())
ranges = pd.concat([tr1, tr2, tr3], axis=1)
tr = ranges.max(axis=1)
atr_all = tr.rolling(period).sum()/period
atr = round(atr_all.iloc[-1], 5)

By changing iloc parameters you can get a required number of ATRs