RSI 为1978年美国作者Welles Wilder JR.在著作(New Concepts in Technical Trading Systems)中所提出的交易方法之一,所谓RSI英文全名为(Relative Strenth Index)中文名称为相当强弱指标。RSI的基本原理是在一个正常的股市中,多空买卖双方的力道必须取得均衡,股价才能稳定;而RSI是对于固定期间内,股价上涨总幅度平均指占总幅度平均值的比例。
买卖原则:
1. RSI值于0-100之间呈常态分配,
2. 当6日RSI值在80%以上时,股市呈超买现象,若出现M头,为卖出时机。
3. 当6日RSI值在20%以下时,股市呈超卖现象,若出现W底为买进时机。
4. RSI一般选用6天;12天,24天作为参考基期,基期越长越有趋势性-慢速RSI,基期越短越有敏感性-快速RSI,
5. 当快速RSI由下往上突破慢速RSI时,为买进时机;当快速RSI由上往下跌破慢速RSI时,为卖出时机
talib_rsi.py
# -*- 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_rsi.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'] > '2022-12-01']
if len(df) <15:
print(" len(df) <15 ")
sys.exit(2)
# 求ma7日均线
df['ma7'] = df['close'].rolling(window=7).mean()
df.index = pd.to_datetime(df.date)
# RSI:相对强弱指标
df['rsi_6'] = talib.RSI(df.close, timeperiod=6)
df['rsi14'] = talib.RSI(df.close, timeperiod=14)
print("rsi_6={0:.1f} , rsi14={1:.1f}".format(df['rsi_6'][-1], df['rsi14'][-1]))
#print(df[ df['rsi_6'] > 80])
#print(df[ df['rsi_6'] < 20])
# RSI 超买 overbuy , 超卖 oversold
rsi_overbuy = df['rsi_6'] > 80
rsi_oversold= df['rsi_6'] < 20
df.loc[rsi_overbuy[(rsi_overbuy==True)&(rsi_overbuy.shift()==False)].index, 'overBuy']='oB'
df.loc[rsi_oversold[(rsi_oversold==True)&(rsi_oversold.shift()==False)].index, 'overSold']='oS'
print(df[ df['overBuy']=='oB'])
print(df[ df['overSold']=='oS'])
df = df[ df['date'] > '2023-01-01']
#print(df.head())
# 画股票收盘价图
fig,axes = plt.subplots(2,1)
df[['close', 'ma7']].plot(ax=axes[0], grid=True, title=code)
# 画 RSI 曲线图
df[['rsi_6', 'rsi14']].plot(ax=axes[1], grid=True)
plt.legend(loc='best', shadow=True)
plt.show()
df.to_csv(f"/stock/rsi_{code}.csv")
运行 python talib_rsi.py 6位股票代码