KDJ是通過一個特定的周期(常見為9天)內出現的最高價、最低價和最後交易日的收市價,以及三者之間的比例關係,計出未成熟隨機值(Raw Stochastic Value,RSV),再根據平滑移動平均線(又名「指數移動平均線」,EMA) 的方法計出K值、D值和J值。
今天就來講解如何用python計算KDJ值。
1.首先匯入相關套件:
import yfinance as yf
import pandas as pd
2.下載特斯拉(美股代號:TSLA) 最近30天的股價資料,(列出最後5日資料查看):
3.計算 KDJ 值,以最後收盤日2024/03/08 與看盤軟體Tiger trade驗證:
4.將股票名稱,最後收盤價,KDJ值放入list
5.寫一個函數將list轉成 DataFrame 格式,欄位有:名稱(Name),最後收盤價格(Price),K,D,J,並且以股票名稱"Name"當作索引欄,並傳回DataFrame:
6.最後將上面的程式寫成3個函數,
(1)計算KDJ:calc_kdj()
(2)取得股價的資料:get_ticker_price()
(3)list轉換dataframe:list_conv_matrix()
7.我用蘋果(AAPL),輝達(NVDA),特斯拉(TSLA) 這3支股票來計算 KDJ,執行結果如下:
8.最後如果要將 dataframe 存成 csv 檔可以用下面的指令:
kdj_df.to_csv(file_name, sep=',') # 用逗點分隔的csv檔
完整程式碼如下:
import yfinance as yf
import pandas as pd
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[-1], 2)
k = round(df[-1:]['K'][0], 2)
d = round(df[-1:]['D'][0], 2)
j = round(df[-1:]['J'][0], 2)
price = round(df[-1:]['Close'][0], 2) # 最後一日收盤價
return price, r, k, d, j
def get_ticker_price(ticker_list):
price_data = []
for ticker in ticker_list:
df = yf.download(ticker, period='30d')
price, r, k, d, j = calc_kdj(df)
date = df.index[-1].strftime('%Y-%m-%d')
data_list = [date, ticker, price, r, k, d, j]
price_data.append(data_list)
return price_data, date
def list_conv_matrix(lst):
data, data_matrix = [], []
for val in lst:
data_matrix.append(val)
cols = ['Date', 'NAME', 'Price', 'RSV', 'K', 'D', 'J']
return pd.DataFrame(data_matrix, columns=cols).set_index('Date')
ticker_list = ['AAPL', 'NVDA', 'TSLA']
data, date = get_ticker_price(ticker_list)
kdj_df = list_conv_matrix(data)
print(kdj_df)
你可以參考下一篇:
沒有留言:
張貼留言