基于python + tushare 实现股票盯盘
tushare ID:499871
tushare简介
Tushare是一个免费、开源的python财经数据接口包。主要实现对股票等金融数据从数据采集、清洗加工 到 数据存储的过程,能够为金融分析人员提供快速、整洁、和多样的便于分析的数据,为他们在数据获取方面极大地减轻工作量,使他们更加专注于策略和模型的研究与实现上。考虑到Python pandas包在金融量化分析中体现出的优势,Tushare返回的绝大部分的数据格式都是pandas DataFrame类型,非常便于用pandas/NumPy/Matplotlib进行数据分析和可视化。当然,如果您习惯了用Excel或者关系型数据库做分析,您也可以通过Tushare的数据存储功能,将数据全部保存到本地后进行分析。应一些用户的请求,从0.2.5版本开始,Tushare同时兼容Python 2.x和Python 3.x,对部分代码进行了重构,并优化了一些算法,确保数据获取的高效和稳定。
设计思路
- 输入股票代码
- 调用 tushare 接口获取股票昨日收盘价格、开盘价格、当前价格等数据
- 计算涨跌幅
核心代码实现
通过 tushare 库的 get_realtime_quotes() 接口获取股票实时数据,根据昨日收盘价格和当前价格计算涨跌幅
def startCheck(stock_id):
rate = 100
while True:
stock_info = tushare.get_realtime_quotes(stock_id)
current_float_rate = (float(stock_info['price'][0]) - float(stock_info['pre_close'][0])) / float(stock_info['pre_close'][0])
current_int_rate = int(current_float_rate*100)
if current_int_rate != rate:
rate = current_int_rate
notifyWx(stock_id, stock_info)
time.sleep(2)
else:
subject = stock_info['name'][0] + "[" + stock_id + "]"
content = "涨幅不明显" + "\n"
content = content + "当前涨跌幅:" + str(round(current_float_rate * 100, 2)) + "%"
print(subject, "\n", content)
time.sleep(10)
加点细节
使用 chinese_calendar 库,判断当前是否处于开盘时间
def isOpenTime():
datetime_now = datetime.datetime.now().date()
openStatus = 0
if is_workday(datetime_now):
# 开始时间
morning_start_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '9:30', '%Y-%m-%d%H:%M')
morning_end_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '11:30', '%Y-%m-%d%H:%M')
afternoon_start_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '13:00', '%Y-%m-%d%H:%M')
afternoon_end_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '15:30', '%Y-%m-%d%H:%M')
# 当前时间
now_time = datetime.datetime.now()
# 判断当前时间是否在范围内
if morning_start_time < now_time < morning_end_time or afternoon_start_time < now_time < afternoon_end_time :
openStatus = 1
return openStatus
配合企业微信应用,做到实时推送通知,具体细节可查看企业微信的文档
def notifyWx(stock_id, stock_info):
subject = stock_info['name'][0] + "[" + stock_id + "]"
content = ""
content = content + "是否开盘:"
if isOpenTime():
content = content + "是"
else:
content = content + "否"
content = content + "\n" + "昨日收盘价格:" + str(stock_info['pre_close'][0])
content = content + "\n" + "开盘价格:" + str(stock_info['open'][0])
content = content + "\n" + "当前价格:" + str(stock_info['price'][0])
content = content + "\n"
current_float_rate = (float(stock_info['price'][0])-float(stock_info['pre_close'][0]))/float(stock_info['pre_close'][0])
content = content + "当前涨跌幅:" + str(round(current_float_rate * 100, 2)) + "%"
sendTextData(subject, content)
结束语
Tushare运行三年多以来,数据从广度和深度都得到了提升,Pro版正是在此基础上做了更大的改进。数据内容将扩大到包含股票、基金、期货、债券、外汇、行业大数据,同时包括了数字货币行情等区块链数据的全数据品类的金融大数据平台,为各类金融投资和研究人员提供适用的数据和工具。