滑动平均线,本程序解决了如何在matplotlib中使用中文显示,环境python2.7 最好使用 anaconda 环境
使用sns似使得图片更加美观,很少说,上代码python
import tushare as ts import pandas as pd import matplotlib.pyplot as plt from matplotlib import rc rc('mathtext', default='regular') from matplotlib import dates import matplotlib as mpl import seaborn as sns sns.set_style('dark') %matplotlib inline font =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() # 计算指数平滑移动平均线EMA for 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()
运行结果以下windows
做者:readilen
连接:http://www.jianshu.com/p/2050d6c54d59
來源:简书
著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。python2.7