用tushare獲取股票歷史資料
阿新 • • 發佈:2018-12-31
我們運用python進行量化分析的時候需要載入證券資料,tushare為我們提供了證券市場資料介面。
tushare是以新浪財經、騰訊財經、上交所資料、深交所資料為基礎提供的Python介面。
安裝方法為
pip install tushare
也可以到tushare的官網去下載,並且官網上有介面各個呼叫函式的詳細說明
安裝完成之後,在spyder中匯入tushare包
import tushare as ts
如果出現lxml庫缺少etree包,則需要開啟Anaconda更新lxml包至最新版即可
大功告成之後,tushare就可以放心使用了
接下來我們利用tushare提供的介面匯入中國平安(000001)的歷史資料,繪製各種圖形,並且計算收益率
# -*- coding: utf-8 -*- #%% 匯入包 import tushare as ts import pandas as pd import matplotlib.pyplot as plt #%% 獲取中國平安三年內K線資料 ZGPA=ts.get_hist_data('000001') ZGPA.index=pd.to_datetime(ZGPA.index) #%% 相關指數 print(ZGPA.tail()) plt.plot(ZGPA['close'],label='收盤價') plt.plot(ZGPA['ma5'],label='MA5') plt.plot(ZGPA['ma20'],label='MA20') plt.legend() plt.xlabel('日期') plt.ylabel('股價') plt.title('中國平安收盤價,MA5,MA20時間序列') #%% 獲取中國平安全部歷史資料 ZGPA_all=ts.get_h_data('000001',start='2006-01-01') ZGPA_all.index=pd.to_datetime(ZGPA_all.index) #%% 相關指數 print(ZGPA_all.tail()) plt.plot(ZGPA_all['close'],label='收盤價') plt.legend() plt.xlabel('日期') plt.ylabel('股價') plt.title('中國平安收盤價時間序列(2006至今)') #%% 計算收益率 ZPGA_Return=((ZGPA_all['close']-ZGPA_all['close'].shift(1))/ZGPA_all\ ['close'].shift(1)).dropna() #收益率 plt.plot(ZPGA_Return) print('中國平安的平均日收益率:',ZPGA_Return.mean(),'\n中國平安的收益率標準差:',\ ZPGA_Return.std())
利用以上程式碼,我們就得到了中國平安三年內的日收盤價、MA5、MA20的時間序列圖,並且我們計算了從2006年至今中國平安的日收益率
是不是很方便快捷,那就點個贊吧