def get_tushare(code,start,end):
import pandas as pd
import mplfinance as mpf
import tushare as ts
import numpy as np
import matplotlib.pyplot as plt
ts.set_token('8669a5830b42cf76db5e9f0241e1a8993657c5ee1118412469f9f43d')
pro=ts.pro_api()
data=pro.daily(ts_code=code,start_date=start,end_date=end)
data_name=["trade_data",'open','high','low','close','vol']
data['trade_date']=pd.to_datetime(data['trade_date'])
data=data.dropna()
data.index =data['trade_date']
data.sort_index()
data.to_excel('data6.1.xls')
df=pd.read_excel('data6.1.xls').sort_values('trade_date')
df.rename(columns={'trade_date':'Date','open':'Open','high':'High','low':'Low','close':'Close','vol':'Volume'},inplace=True)
df.set_index('Date',inplace=True)
change = df.change
up = pd.Series(index=df.index,data=change[change>0]) #设置涨幅数列(数列中非涨幅的数值则设为0)
up = up.fillna(0)
down = pd.Series(index=change.index,data=-change[change<0]) #设置跌幅数列(要取正值;数列中非跌幅的数值则设为0)
down = down.fillna(0)
#计算14日平均涨跌幅
up_mean14 = []
down_mean14 = []
for i in range(15,len(up)+1):
up_mean14.append(np.mean(up.values[i-14:i]))
down_mean14.append(np.mean(down.values[i-14:i]))
#计算14日RSI
rsi14 = []
for i in range(len(up_mean14)):
rsi14.append(100*up_mean14[i]/(up_mean14[i]+down_mean14[i]))
rsi14_series = pd.Series(index = df.index[14:],data = rsi14)
#计算24日平均涨跌幅
up_mean24 = []
down_mean24 = []
for i in range(25,len(up)+1):
up_mean24.append(np.mean(up.values[i-24:i]))
down_mean24.append(np.mean(down.values[i-24:i]))
#计算24日RSI
rsi24 = []
for i in range(len(up_mean24)):
rsi24.append(100*up_mean24[i]/(up_mean24[i]+down_mean24[i]))
rsi24_series = pd.Series(index = df.index[24:],data = rsi24)
plt.rcParams['font.sans-serif'] = 'SimHei' #matplotlib默认不支持中文和符号和字符,加入这两行代码,使其能够显示中文和符号
plt.rcParams['axes.unicode_minus'] = False
fig = plt.figure() #创建一个figure对象,相当于一个画板
fig,axes = plt.subplots(nrows=3,ncols=1) #3行1列
ax0,ax1,ax2 = axes.flatten()
ax0.set(title="思创医惠2020年的收盘价") #添加标题、横纵轴标签
ax0.plot(df.index,df['Close'],color='blue', linestyle='-')
ax0.set_ylabel('收盘价')
ax0.set_xlabel('交易日期')
ax0.grid() #添加网格线
ax1.set(title="思创医惠2020年的14日RSI")
ax1.axhline(50, color='red') #在水平方向上画线
ax1.plot(rsi14_series,color='blue', linestyle='-')
ax1.set_ylabel('RSI')
ax1.set_xlabel('交易日期')
ax1.grid() #添加网格线
ax2.set(title="思创医惠2020年的24日RSI")
ax2.axhline(50, color='red')
ax2.plot(rsi14_series,color='blue', linestyle='-')
ax2.set_ylabel('RSI')
ax2.set_xlabel('交易日期')
ax2.grid() #添加网格线
fig.tight_layout() #自动调整子绘图参数
plt.show()