滑动平均线,本程序解决了如何在matplotlib中使用中文显示,环境python2.7 最好使用 anaconda 环境
使用sns似使得图片更加美观,不多说,上代码import tushare as tsimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib import rcrc('mathtext', default='regular')from matplotlib import datesimport matplotlib as mplimport seaborn as snssns.set_style('dark')%matplotlib inlinefont =mpl.font_manager.FontProperties(fname=r"c:\windows\fonts\simsun.ttc",size=14)stock_data = ts.get_k_data("600600")# 将数据按照交易日期从远到近排序stock_data.sort_values('date', inplace=True)# ========== 计算移动平均线# 分别计算5日、20日、60日的移动平均线# 计算简单算术移动平均线MA - 注意:stock_data['close']为股票每天的收盘价ma_list = [5, 10, 20, 60]for ma in ma_list: stock_data['ma' + str(ma)] = stock_data.close.rolling(window=ma, center=False).mean()# 计算指数平滑移动平均线EMAfor ma in ma_list: stock_data['ema' + str(ma)] = stock_data.close.ewm(ignore_na=False,span=ma,min_periods=0,adjust=True).mean()bar_data = stock_data[['date','volume','close','ma5','ma10','ma20','ma60','ema5','ema10','ema20','ema60']]bar_data = bar_data[60:60+340]bar_data.index = range(len(bar_data))fig = plt.figure(figsize=(14,10))fig.set_tight_layout(True)ax1 = fig.add_subplot(211)ax1.bar(bar_data.index, bar_data.volume, align='center', width=0.4)ax2 = ax1.twinx()ax2.plot(bar_data.index, bar_data.close, '-', color='r')ax2.plot(bar_data.index, bar_data.ma5, '-', color='w')ax2.plot(bar_data.index, bar_data.ma10, '-', color='y')ax2.plot(bar_data.index, bar_data.ma20, '-', color='m')ax2.plot(bar_data.index, bar_data.ma60, '-', color='g')ax1.set_ylabel(u"成交量(万)",fontproperties=font, fontsize=16)ax2.set_ylabel(u"均线 ",fontproperties=font, fontsize=16)ax1.set_title(u"蓝色柱子(左轴)为成交量,曲线为均线",fontproperties=font,fontsize=16)# plt.xticks(bar_data.index.values, bar_data.barNo.values)ax1.set_xlabel(u"平均线",fontproperties=font, fontsize=16)ax1.set_xlim(left=-1, right=len(bar_data))ax2.set_ylim(bottom=-0.5*max(bar_data.close))ax1.grid()ax1 = fig.add_subplot(212)ax1.bar(bar_data.index, bar_data.volume, align='center', width=0.4)ax2 = ax1.twinx()ax2.plot(bar_data.index, bar_data.ema5, '--', color='w')ax2.plot(bar_data.index, bar_data.ema10, '--', color='y')ax2.plot(bar_data.index, bar_data.ema20, '--', color='m')ax2.plot(bar_data.index, bar_data.ema60, '--', color='g')ax1.set_ylabel(u"成交量(万)",fontproperties=font, fontsize=16)ax2.set_ylabel(u"滑动平均线",fontproperties=font, fontsize=16)ax1.set_title(u"蓝色柱子(左轴)为成交量,曲线为滑动平均线",fontproperties=font, fontsize=16)# plt.xticks(bar_data.index.values, bar_data.barNo.values)ax1.set_xlabel(u"滑动平均线",fontproperties=font,fontsize=16)ax1.set_xlim(left=-1,right=len(bar_data))# ax2.set_ylim(bottom=-0.5*max(bar_data.smartS))ax1.grid()
运行结果如下
![](http://upload-images.jianshu.io/upload_images/3802398-60726f47efa167da.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
结果图
作者:readilen链接:http://www.jianshu.com/p/2050d6c54d59來源:简书著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。