python 实时获取股票行情脚本 协程版

编程入门 行业动态 更新时间:2024-10-27 23:27:59

python 实时获取股票行情<a href=https://www.elefans.com/category/jswz/34/1771291.html style=脚本 协程版"/>

python 实时获取股票行情脚本 协程版

震惊!一名中年韭菜竟然打算使用python来翻身?

震惊!!某中年韭菜竟然又打算使用Python的协程翻身?

震惊三部曲之终篇,本篇主要优化爬取数据脚本,使用协程加快速度。

1. aiohttp介绍

Async HTTP client/server for asyncio and Python. 

asyncio和Python的异步HTTP客户端/服务器,其实aiohttp就是基于asyncio实现的HTTP框架。

由于脚本中获取数据是需要访问http接口的,所以加上这个HTTP框架,会显得高大上。

2. 用法

首先,官方推荐使用ClientSession来管理会话。asyncio实现单线程并发IO操作

复习一下asyncio的用法

3. 实现

首先将访问接口的方法定义为协程函数,使用ClientSession管理会话

然后将需要访问的链接做好处理,传入getData(),加入任务列表

最后启动协程异步操作任务,完成!码:

import json
import time
import asyncio
import aiohttp
import pymysqlnow = lambda :time.time()code_list = []dbconf = {'host':'127.0.0.1','port':3306,'user':'root','password':'root','db':'shares','charset':'utf8mb4','cursorclass':pymysql.cursors.DictCursor}def execsql(sql, databaseconf):'''connect mysql return result'''try:conn = pymysql.connect(**databaseconf)with conn.cursor() as cursor:try:cursor.execute(sql)connmit()# print('Commit!')except Exception as e:print(e)conn.close()except Exception as e:print(e)async def getData(url):async with aiohttp.ClientSession() as session:try:async with session.get(url,timeout=60) as r:shares = await r.text()share = json.loads(shares[9:-1])data = share["Value"]if len(data) > 0:date = data[49][:-9]sql = 'insert into share_copy1(name,code,now,rise,changehands,amplitude,priceearnings,marketrate,date) values("{name}","{code}","{now}","{rise}","{changehands}","{amplitude}","{priceearnings}","{marketrate}","{date}")'.format(name=data[2],code=data[1],now=data[25],rise=data[29],changehands=data[37],amplitude=data[50],priceearnings=data[38],marketrate=data[43],date=date)
await execsql(sql,dbconf)print(sql)else :print(f'已退市或板块代码:{url}')except Exception as e:print(f'访问超时:{url}\n'+ str(e))def share_code():with open('sh_info.txt', 'rU') as file:for code in file.readlines():code_list.append(code.strip())def main():share_code()start = now()tasks = []try:for code in code_list:if code[:2] == '60':sh_url = '.ashx?id={code}1'.format(code=code)tasks.append(asyncio.ensure_future(getData(sh_url)))else:sz_url = '.ashx?id={code}2'.format(code=code)tasks.append(asyncio.ensure_future(getData(sz_url)))except Exception as e:print(e)loop=asyncio.get_event_loop()finished, unfinished = loop.run_until_complete(asyncio.wait(tasks,return_when=asyncio.ALL_COMPLETED))fin = len(finished)unfin = len(unfinished)loop.close()print(f'完成:{fin},未完成:{unfin}')print('Time:',now() - start)if __name__=="__main__":main()

执行结果:

嗯,78s,比之前快好几倍了,暂时够用。

代码比较简陋,功能也单一,但用来练手还是可以的。有条件的同学可以找下其他更好用的接口。

最近市场震荡不停,还是且买且看看。

 

 

扫码关注,获取精选资源

更多推荐

python 实时获取股票行情脚本 协程版

本文发布于:2024-03-06 06:07:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1714561.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   实时   股票行情   python   协程版

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!