Tushare 获取股票实时数据
自己实现了一个能获取股票实时交易数据的脚本,功能是每3秒钟获取当前大盘涨跌,和自己添加股票的价格和涨跌幅
原理是通过获取Tushare 平台提供的api,来获取股票数据,可以通过
https://tushare.pro/register?reg=376628
访问平台,第一次访问需要注册
运行前需要安装python包
使用以下命令:
pip install tushare -i https://pypi.tuna.tsinghua.edu.cn/simple
codes就表示要实时监控的股票代码,sh表示上证指数,sz表示深成指数,cyb就是创业板的指数,后面是我加的两个自选股,如果想加其他的,在后边依次添加代码就好
codes = ['sh', 'sz', 'cyb', '000100', '002958']
运行后会显示如下:
完整代码如下:
import tushare as ts
import time
import oscodes = ['sh', 'sz', 'cyb', '000100', '002958']while 1:data = ts.get_realtime_quotes(codes)# print(len(data))sh_price = round(float(data['price'].values[0]), 2)sh_pre_close = round(float(data['pre_close'].values[0]), 2)sz_price = round(float(data['price'].values[1]), 2)sz_pre_close = round(float(data['pre_close'].values[1]), 2)cyb_price = round(float(data['price'].values[2]), 2)cyb_pre_close = round(float(data['pre_close'].values[2]), 2)sh = round(sh_price - sh_pre_close, 2)sz = round(sz_price - sz_pre_close, 2)cyb = round(cyb_price - cyb_pre_close, 2)sh_percent = round(sh / sh_pre_close * 100, 2)sz_percent = round(sz / sz_pre_close * 100, 2)cyb_percent = round(cyb / cyb_pre_close * 100, 2)# print('(', sh_price, sh, sh_percent, ')', '(', sz_price, sz, sz_percent, ')', '(', cyb_price, cyb, cyb_percent, ')')print('(%.2f %.2f %.2f) (%.2f %.2f %.2f) (%.2f %.2f %.2f)'%(sh_price, sh, sh_percent, sz_price, sz, sz_percent, cyb_price, cyb, cyb_percent))for i in range(3, len(data)):price = float(data['price'].values[i])pre_close = float(data['pre_close'].values[i])print(data.name.values[i], data.open.values[i], data.price.values[i], round((price-pre_close)/pre_close*100, 2))time.sleep(3)