Python ATR计算

时间:2018-02-16 06:44:53

标签: python

出错了。

在下面的代码中,我正在计算S& P 500的1天,3天,5天ATR。但是,我有一些错误,我无法弄清楚。

任何帮助将不胜感激。

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 个答案:

答案 0 :(得分:0)

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)

通过更改 iloc 参数,您可以获得所需数量的 ATR