easyquotation:实时股票数据获取
easyquotation库,是一个非常好用的实时股票数据获取库,可以实时获取新浪、腾讯的免费股票行情,集思路的分级基金行情
安装
项目地址:https://github.com/shidenggui/easyquotation.git
shell
pip install easyquotation
用法
python
import easyquotation
quotation = easyquotation.use('sina') # 新浪 ['sina'] 腾讯 ['tencent', 'qq']
#获取所有股票行情
quotation.market_snapshot(prefix=True) # prefix 参数指定返回的行情字典中的股票代码 key 是否带 sz/sh 前缀
#获取单支股票
quotation.real('162411') # 支持直接指定前缀,如 'sh000001'
#获取多支股票
quotation.stocks(['000001', '162411'])
#同时获取股票和行情
quotation.stocks(['sh000001', 'sz000001'], prefix=True)
#获取集思路行情
quotation = easyquotation.use('jsl') # ['jsl']
quotation.set_cookie('从浏览器获取的集思录 Cookie')
quotation.funda() # 参数可选择利率、折价率、交易量、有无下折、是否永续来过滤
quotation.fundb() # 参数如上
#获取腾讯分时图数据
quotation = easyquotation.use("timekline")
data = quotation.real(['603828'], prefix=True)
#获取日k数据
quotation = easyquotation.use("daykline")
data = quotation.real(['00001','00700'])
#获取港股数据
quotation = easyquotation.use("hkquote")
data = quotation.real(['00001','00700'])
bug
获取港股数据,easyquotation传数字股票代码没问题,如果获取指数数据如恒生指数(HSI),传入HSI后,返回数据为空,bug原因是返回的response封装,正则表达式只匹配了数字,所以传入字母代码后没有进行封装。
代码bug
在easyquotation库的HKQuote类中,format_response_data函数的正则表达式:r'v_r_hk\d+=".*?"',\d匹配了数字股票代码,港股的指数代码是字母的,所以将\d改成 .
python
def format_response_data(self, rep_data, **kwargs):
stocks_detail = "".join(rep_data)
stock_dict = {}
for raw_quotation in re.findall(r'v_r_hk\d+=".*?"', stocks_detail):
quotation = re.search('"(.*?)"', raw_quotation).group(1).split("~")
stock_dict[quotation[2]] = dict(
lotSize=float(quotation[0]),
name=quotation[1],
price=float(quotation[3]),
lastPrice=float(quotation[4]),
openPrice=float(quotation[5]),
amount=float(quotation[6]),
time=quotation[30],
dtd=float(quotation[32]),
high=float(quotation[33]),
low=float(quotation[34]),
)
return stock_dict
bug修改方式
继承HKQuote类,重写format_response_data函数,然后如果要获取港股数据,使用自己的类
python
import re
from easyquotation.hkquote import HKQuote
class IHKQuote(HKQuote):
def format_response_data(self, rep_data, **kwargs):
stocks_detail = "".join(rep_data)
stock_dict = {}
for raw_quotation in re.findall(r'v_r_hk.+=".*?"', stocks_detail):
quotation = re.search('"(.*?)"', raw_quotation).group(1).split("~")
stock_dict[quotation[2]] = dict(
lotSize=float(quotation[0]),
name=quotation[1],
price=float(quotation[3]),
lastPrice=float(quotation[4]),
openPrice=float(quotation[5]),
amount=float(quotation[6]),
time=quotation[30],
dtd=float(quotation[32]),
high=float(quotation[33]),
low=float(quotation[34]),
)
return stock_dict
调用方式
python
from amend_easyquotation import IHKQuote
quotation = IHKQuote()
stock = quotation.stocks(['HSI'])