导入 tushare并连接API获取股票数据
import tushare as ts
ts.set_token('Your token')
pro = ts.pro_api()
df= pro.daily(ts_code='600809.SH', start_date='20220401', end_date='20220701')
导入需要的包
import pandas as pd
import numpy as np
import mplfinance as mpf
import matplotlib.pyplot as plt
import talib
from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY,YEARLY
df1=df
mplfinance对数据格式有要求需做一定的处理
def getData(df):
df=pd.DataFrame(df)
df.rename(columns={'trade_date':'Date','open':'Open','high':'High','low':'Low','close':'Close','vol':'Volume'},inplace=True)
df=df[['Date','Open','High','Low','Close','Volume']]
df['Date']=pd.to_datetime(df['Date'])
df.set_index(['Date'],inplace=True)
df=df.sort_index()
return df
df=getData(df)
设置自己的绘画风格
#设置绘画风格
mystyle = dict(style_name = 'style',
base_mpl_style= 'fast',
marketcolors = {'candle' : {'up':'w', 'down':'g'}, #填充颜色
'edge' : {'up':'r', 'down':'g'}, #边缘颜色
'wick' : {'up':'r', 'down':'g'}, #灯芯颜色
'ohlc' : {'up':'r', 'down':'g'},
'volume' : {'up':'r', 'down':'g'}, #交易量颜色
'vcdopcod': True,
'alpha' : 1.0,
},
mavcolors = ['#ef5714','#ef5714','#9f4878','#9f4878'], #均线颜色
y_on_right = False,
gridcolor = '#a0a0a0',
gridstyle = '--',
facecolor = 'w',
rc = [ ('axes.edgecolor' , 'white' ),
('axes.linewidth' , 1.5 ),
('axes.labelsize' , 'large' ),
('axes.labelweight', 'semibold'),
('axes.grid' , True ),
('axes.grid.axis' , 'y' ),
('grid.linewidth' , 0.4 ),
('lines.linewidth' , 2.0 ),
('font.weight' , 'medium' ),
('font.size' , 10.0 ),
('figure.titlesize', 'x-large' ),
('figure.titleweight','semibold'),
],
base_mpf_style= 'charles')
#加上字体的设置,否则中文会乱码
normal_font = {'fontname':'STZhongsong',
'size': '12',
'color': 'green',
'va': 'bottom',
'ha': 'left'}
获得K线数据
#获得均线
def MA(df,k):
close = [float(x) for x in df['Close']]
x=talib.MA(np.array(close), timeperiod=k)
return x
df1['MA3']=MA(df,3)
df1['MA10']=MA(df,10)
df1['MA21']=MA(df,21)
画图
#选择自己的绘画风格
fig = mpf.figure(figsize=(10, 6),style=mystyle)
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2, sharex=ax1)
fig.subplots_adjust(hspace=0) #子图之间没有间隔
plt.xlabel('date',fontsize=10) #指定X轴标签和大小
plt.tick_params(labelsize=6)#指定X轴刻度字体大小
#为子图1添加均线
ax1.plot(df1['Date'],df1['MA3'],label='MA3',color='slategray')
ax1.plot(df1['Date'],df1['MA10'],label='MA10',color='skyblue')
ax1.plot(df1['Date'],df1['MA21'],label='MA21',color='#ef5714')
ax1.legend(fontsize=7)
#用mplfinance画出蜡烛图
mpf.plot(df, type='candle',ylabel='Candle', axtitle='my style',ax=ax1,volume=ax2)
结果如图: