用tushare获取股票历史数据

来源:互联网 发布:无锡网络教育学历 编辑:程序博客网 时间:2024/04/28 18:09

我们运用python进行量化分析的时候需要载入证券数据,tushare为我们提供了证券市场数据接口。

tushare是以新浪财经、腾讯财经、上交所数据、深交所数据为基础提供的Python接口。

安装方法为

pip install tushare

也可以到tushare的官网去下载,并且官网上有接口各个调用函数的详细说明

http://tushare.org/index.html#id5

安装完成之后,在spyder中导入tushare包

import tushare as ts

如果出现lxml库缺少etree包,则需要打开Anaconda更新lxml包至最新版即可

大功告成之后,tushare就可以放心使用了吐舌头


接下来我们利用tushare提供的接口导入中国平安(000001)的历史数据,绘制各种图形,并且计算收益率

# -*- coding: utf-8 -*-#%% 导入包import tushare as tsimport pandas as pdimport 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年至今中国平安的日收益率

是不是很方便快捷,那就点个赞吧




原创粉丝点击