talib_kdj.py 计算 KDJ 求发出买入信号日期
Buy:买入,close:收盘价,rate:收益率
# -*- coding: utf-8 -*-
import os, sys
import tushare as ts
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import talib
if len(sys.argv) ==2:
code = sys.argv[1]
else:
print('usage: python talib_kdj.py stockcode ')
sys.exit(1)
if len(code) !=6:
print('stock code length: 6')
sys.exit(2)
df = ts.get_k_data(code)
if df.empty ==True:
print(" df is empty ")
sys.exit(2)
df = df[ df['date'] >'2021-01-01']
if len(df) <10:
print(" len(df) <10 ")
sys.exit(2)
# DataFrame 重建索引
df = df.reset_index(drop=True)
dw = pd.DataFrame()
# KDJ 值对应的函数是 STOCH
dw['slowk'], dw['slowd'] = talib.STOCH(
df['high'].values,
df['low'].values,
df['close'].values,
fastk_period=9,
slowk_period=3,
slowk_matype=0,
slowd_period=3,
slowd_matype=0)
# 求出J值,J = (3*K) - (2*D)
dw['slowj'] = list(map(lambda x,y: 3*x-2*y, dw['slowk'], dw['slowd']))
dw.index = range(len(dw))
print('df.len=',len(df),'dw.len=',len(dw))
blist =[] # 求发出买入信号日期
for i in range(len(dw)-30,len(dw)):
if dw.loc[i, 'slowk'] <20 and dw.loc[i, 'slowj'] <0:
blist.append(i)
print(list(dw.iloc[i]))
print('blist=',blist)
close = df['close'].values
# 遍历 DataFrame
for index,row in df.iterrows():
if index in blist:
print(list(row.values))
print('Buy {0} ,close:{1} ,rate: {2:.2f}%'.format(close[index],close[-1],(close[-1]/close[index]-1)*100))
df['ma10'] = df['close'].rolling(window=10).mean()
df.index = pd.to_datetime(df.date)
# 画股票收盘价图
fig,axes = plt.subplots(2,1)
df[['close', 'ma10']].plot(ax=axes[0], grid=True, title=code)
# 画 KDJ 曲线图
dw[['slowk','slowd','slowj']].plot(ax=axes[1], grid=True)
plt.legend(loc='best', shadow=True)
plt.show()
运行 python talib_kdj.py 002558
df.len= 175 dw.len= 175
[17.560588233009796, 29.291261834651213, -5.9007589702730385]
alist= [161]
['2021-08-31', 10.01, 10.11, 10.19, 9.9, 76531.0, '002558']
Buy 10.11 ,close:11.0 , rate: 8.80%