程式小專題 – 計算ATR #8 打包收尾

總算進入實操階段,這也就代表這個小專題要收尾啦,以下為稍作修改後的程式碼:

import requests
import pandas as pd
client_id = '你的Consumer Key' #要註冊才會有

tickers = ['SE','AAPL','NTDOY','SHOP'] #看上股票的tickers
metrics = ['ATR','close'] #我們現在計算的指標
df_result = pd.DataFrame(index=tickers, columns=metrics) #來一個空的DataFrame,row放ticker column放指標

w=21 #window for ATR calculation
i=0 #放在外面,放在裡面i+=1就沒用了

for t in tickers: #用for loop來重複執行計算,按照tickers list的順序
    endpoint = r"https://api.tdameritrade.com/v1/marketdata/{}/pricehistory".format(tickers[i])
    payload ={'apikey':client_id,
         'periodType':'month',
         'period':'2',
         'frequencyType':'daily',
         'frequency':'1',
         'needExtendedHoursData':'true'}
 
    content = requests.get(url= endpoint, params = payload)
    data = content.json() #把json轉成字典
 
    df = pd.DataFrame(data['candles']) #把candles字典裝進DataFrame
    df_cal = df.tail(23).copy() #取最後23天的資料,用copy的原因是因為python可能分不出來是view還是copy,會回報警告
    df_cal.index = range(23) #把index改成0到22 

    PreviousClose = df_cal.close.shift(1).copy() 
    df_cal.loc[:,'PreviousClose'] = PreviousClose

    TrueRange = df_cal[['PreviousClose','high']].max(axis=1).copy()-df_cal[['PreviousClose','low']].min(axis=1).copy()
    df_cal.loc[:,'TrueRange']= TrueRange

    PreAvgTR = df_cal['TrueRange'].rolling(window=w).mean().shift().copy() 
    df_cal.loc[:,'PreAvgTR'] = PreAvgTR

    ATR = (df_cal['PreAvgTR'].copy()*(w-1) + df_cal['TrueRange'].copy())/w 
    df_cal.loc[:,'ATR'] = ATR
    
    result_ATR = df_cal[-1:]['ATR'].copy()
    df_result.loc[tickers[i],metrics[0]] = float(result_ATR) #把計算的結果放進一開始的空DataFrame,因為result似乎是個DataFrame,所以就用了float把它轉成value
    
    result_close = df_cal[-1:]['close'].copy()
    df_result.loc[tickers[i],metrics[1]] = float(result_close)
    
    i+=1

print(df_result) 
df_result.to_excel("ATR.xlsx")
            ATR  close
SE      1.03212   39.3
AAPL    4.31844  289.8
NTDOY  0.816372     50
SHOP    15.6881    408

發表留言