你們是否留意到《Python實戰-構建基於股票的量化交易系統》小冊子的介紹中有一副圖:bash
接下來,咱們手把手教你們如何來繪製標記着上證指數漲跌週期的圖片。此處會涉及到matplotlib、pandas、tushare、numpy等Python第三方庫的使用。函數
首先使用tushare的ts.get_k_data
接口獲取上證綜指2008年至2019的日交易數據。ui
#獲取上證綜指2008年至2019的日交易數據
sh=ts.get_k_data('sh',start='2008-1-1', end='2019-1-1')
print(sh.head())
date open close high low volume code
183 2008-10-06 2267.39 2173.74 2267.39 2172.57 60938100.0 sh
184 2008-10-07 2101.09 2157.84 2183.00 2072.90 56902600.0 sh
185 2008-10-08 2095.91 2092.22 2127.08 2059.09 50759500.0 sh
186 2008-10-09 2125.57 2074.58 2130.87 2063.41 45071000.0 sh
187 2008-10-10 1995.96 2000.57 2027.83 1963.18 54077500.0 sh
複製代碼
使用matplotlib的plot()
函數繪製上證指數的收盤價。spa
sh['close'].plot(figsize=(16,8))
複製代碼
從圖中能夠看到2014年開始的那一輪牛市,從2014年7月持續到2015年6月,這11個月指數竟然從2075.48點漲到了5178.19點。咱們使用matplotlib的annotate ()
函數在圖表中標註下牛市的起點和終點。3d
plt.annotate('牛市起點',
xy=('2014-7-1',2054),
xytext=('2014-3-1',2500),
bbox = dict(boxstyle = 'round,pad=0.5',
fc = 'yellow', alpha = 0.5),
arrowprops=dict(facecolor='red',
shrink=0.05),fontsize=12)
複製代碼
接下來用matplotlib的axhline()
函數將指數中位值設置爲水平參考線(horizontal),用matplotlib的axvline()
函數將指數最小值所在交易日設置爲垂直參考線(vertical)。code
plt.axhline(y=sh['close'].median(), c='r', ls='--', lw=2)
plt.axvline(x=sh[sh['close'].values == sh['close'].min()].index, c='g', ls='-.', lw=2)
複製代碼
接下來用matplotlib的axhspan()
函數將牛市的起始點位設置爲平行於x軸 的參考區域(horizontal),用matplotlib的axvspan ()
函數將牛市的起始交易日設置爲平行於y軸的參考區域 (vertical)。cdn
plt.axhspan(ymin=2075.48, ymax=5178.19, facecolor='purple', alpha=0.3)
plt.axvspan(xmin='2014-7-1', xmax='2015-6-15', facecolor='g', alpha=0.3)
複製代碼
接下來咱們對圖表的樣式細節進行調整。好比去掉圖形上邊和右側的邊框、設置座標軸上的刻度線位置、將刻度線放在座標軸內側。blog
# 樣式調整
# spines設置圖表left\right\bottom\top邊框,此處去掉圖形上邊和右側的邊框
for spine in plt.gca().spines.keys():
print(spine)
if spine == 'top' or spine == 'right':
plt.gca().spines[spine].set_color('none')
# 設置座標軸上的刻度線位置(其實這裏的設置跟默認同樣)
plt.gca().xaxis.set_ticks_position('bottom')
plt.gca().yaxis.set_ticks_position('left')
# 將刻度線放在座標軸內側
plt.tick_params(direction = 'in')
複製代碼
關於完整代碼能夠加入小冊交流羣獲取。更多的量化交易內容歡迎你們訂閱小冊閱讀!!接口