續上一篇:Python 計算股價 KDJ,這篇把它完備一點,再加上前一日收盤價格,今日收盤價格,差異和百分比:
我定義一個函數來取得最後日和前一日的收盤價格資料,並計算差異百分比,最後將結果傳回:
# 取得最後一天收盤資料
def last_day_data(name, df):
date = df.index[-1].strftime('%Y-%m-%d') # 取出最後一筆日期
price = round(df.Close[-1], 2) # 當日收盤價
pre_price = round(df.Close[-2], 2) # 前一日收盤價
diff = round(df.Close[-1] - df.Close[-2], 2) # 價格差異
percent = round(float(diff) * 100 / pre_price, 2) # 差異百分比
high = round(df.High[-1], 2) # 當日最高
low = round(df.Low[-1], 2) # 當日最低
return [date, name, pre_price, price, diff, percent, high, low]
完整程式碼如下:
import yfinance as yf
import pandas as pd
# 計算KDJ,以9日週期計算
def calc_kdj(df, n=9):
low_list = df['Low'].rolling(window=n).min()
low_list.fillna(value=df['Low'].expanding().min(), inplace=True)
high_list = df['High'].rolling(window=n).max()
high_list.fillna(value=df['High'].expanding().max(), inplace=True)
rsv = (df['Close'] - low_list) / (high_list - low_list) * 100
df['K'] = rsv.ewm(com=2).mean()
df['D'] = df['K'].ewm(com=2).mean()
df['J'] = 3 * df['K'] - 2 * df['D']
r = round(rsv.iloc[-1], 2)
k = round(df.iloc[-1].K, 2)
d = round(df.iloc[-1].D, 2)
j = round(df.iloc[-1].J, 2)
return [r, k, d, j]
# 取得最後一天收盤資料
def last_day_data(name, df):
date = df.index[-1].strftime('%Y-%m-%d') # 取出最後一筆日期
price = round(df.Close[-1], 2) # 當日收盤價
pre_price = round(df.Close[-2], 2) # 前一日收盤價
diff = round(df.Close[-1] - df.Close[-2], 2) # 價格差異
percent = round(float(diff) * 100 / pre_price, 2) # 差異百分比
high = round(df.High[-1], 2) # 當日最高
low = round(df.Low[-1], 2) # 當日最低
return [date, name, pre_price, price, diff, percent, high, low]
def list_conv_matrix(lst):
data, data_matrix = [], []
for val in lst:
data_matrix.append(val)
cols = ['Date', 'Name', '前一日', '收盤價', '差異', '%', '當日最高', '當日最低',
'RSV', 'K', 'D', 'J']
return pd.DataFrame(data_matrix, columns=cols).set_index('Date')
def get_ticker_data(ticker_list):
data = []
for ticker in ticker_list:
df = yf.download(ticker, period='30d')
kdj_list = calc_kdj(df) # 計算KDJ
data_list = last_day_data(ticker, df) # 取得最後一天收盤資料
date_str = data_list[0] # 取出日期
data_list.extend(kdj_list)
data.append(data_list)
return data
ticker_list = ['AAPL', 'AMZN', 'GOOGL']
df = list_conv_matrix(get_ticker_data(ticker_list))
df
執行結果:
你可以參考上一篇:
Python 計算股價 KDJ (1)