import tushare as ts
import matplotlib.pyplot as plt
import mpl_finance as mpf
from matplotlib.pylab import date2num
import datetime
df=ts.get_k_data(code='000002',start='2019-06-01',end='2019-09-30')
def date_to_num(dates):
num_time=[]
for date in dates:
date_time=datetime.datetime.strptime(date,'%Y-%m-%d')
num_date=date2num(date_time)
num_time.append(num_date)
return num_time
df_arr=df.values
df_arr[:,0]=date_to_num(df_arr[:,0])
fig,ax=plt.subplots(figsize=(15,6))
mpf.candlestick_ochl(ax,df_arr,width=0.6,colorup='r',colordown='g',alpha=1.0)
df['MA5']=df['close'].rolling(5).mean()
df['MA10']=df['close'].rolling(10).mean()
plt.plot(df_arr[:,0],df['MA5'])
plt.plot(df_arr[:,0],df['MA10'])
plt.grid(True)
plt.rcParams['font.sans-serif']=['SimHei']
plt.title('每日数据')
ax.xaxis_date()
plt.show()
以上是实现的过程源码,但是同时运行过程中出现如下提示,该如何简化此过程来实现同样视觉效果呢
WARNING: mpl_finance
is deprecated:
Please use `mplfinance` instead (no hyphen, no underscore).
To install: `pip install --upgrade mplfinance`
For more information, see: https://pypi.org/project/mplfinance/
首先,你需要升级mplfinace,如警告信息所提示的那样,然后精简修改代码,不需用matplotlib,直接用mpl.plot就可绘制出k线图了。精简后的代码如下:
import tushare as ts
import mplfinance as mpf
import datetime
import pandas as pd
df = ts.get_k_data(code='000002', start='2019-06-01', end='2019-09-30')
df=df.iloc[:,:6]
df=df.rename(columns={x:x.title() for x in df.columns})
df=df.set_index(df['Date']).drop('Date',axis=1)
df.index=pd.DatetimeIndex(df.index)
mpf.plot(df,type='candle', mav=(2, 5, 10), volume=True)
如有帮助,请点采纳。
参考:https://blog.csdn.net/wuwei_201/article/details/105781844