Skip to content

Commit

Permalink
添加港股行情时时获取
Browse files Browse the repository at this point in the history
  • Loading branch information
wangyu190810 committed Nov 29, 2017
1 parent 3999965 commit 59cc0f7
Show file tree
Hide file tree
Showing 4 changed files with 162 additions and 3 deletions.
46 changes: 44 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,8 @@ quotation.etfindex(index_id="", min_volume=0, max_discount=None, min_discount=No

*[腾讯分时图地址](http://data.gtimg.cn/flashdata/hushen/minute/sz000001.js)*

```
```python

quotation = easyquotation.use("timekline")
data = quotation.market_snapshot(prefix=True)

Expand All @@ -380,7 +381,8 @@ data = quotation.market_snapshot(prefix=True)
##### 港股日k线图
*[腾讯日k线图](http://web.ifzq.gtimg.cn/appstock/app/hkfqkline/get?_var=kline_dayqfq&param=hk00700,day,,,350,qfq&r=0.7773272375526847)*

```
```python

import easyquotation
quotation = easyquotation.use("daykline")
data = quotation.get_stock_data(stock_list=['00001','00700'])
Expand All @@ -401,3 +403,43 @@ print(data)
}
```

##### 腾讯港股时时行情
*[腾讯控股时时行情](http://sqt.gtimg.cn/utf8/q=r_hk00700)*
```python

import easyquotation
quotation = easyquotation.use("hkquote")
data = quotation.get_stock_data(stock_list=['00001','00700'])
print(data)
```

```
{
'00001':
{
'stock_code': '00001', # 股票代码
'lotSize': '"100', # 每手数量
'name': '长和', # 股票名称
'price': '97.20', # 股票当前价格
'lastPrice': '97.75', # 股票昨天收盘价格
'openPrice': '97.75', # 股票今天开盘价格
'amount': '1641463.0', # 股票成交量
'time': '2017/11/29 15:38:58', # 当前时间
'high': '98.05', # 当天最高价格
'low': '97.15' # 当天最低价格
},
'00700':
{
'stock_code': '00700',
'lotSize': '"100',
'name': '腾讯控股',
'price': '413.20',
'lastPrice': '419.20',
'openPrice': '422.20',
'amount': '21351010.0',
'time': '2017/11/29 15:39:01',
'high': '422.80',
'low': '412.40'
}
}
```
4 changes: 4 additions & 0 deletions easyquotation/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from .tencent import Tencent
from .timekline import TimeKline
from .daykline import DayKline
from .hkqoute import HKQuote

PY_VERSION = sys.version_info[:2]
if PY_VERSION < (3, 5):
Expand All @@ -29,3 +30,6 @@ def use(source):
return TimeKline()
if source in ['daykline']:
return DayKline()
if source in ['hkquote']:
return HKQuote()

104 changes: 104 additions & 0 deletions easyquotation/hkqoute.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# coding:utf8
import re
import time
import json

import aiohttp
import asyncio
import easyutils
import yarl
from .basequotation import BaseQuotation

"""
url = "http://sqt.gtimg.cn/utf8/q=r_hk00981"
url 参数改动
股票代码 q=r_hk00981
"""


class HKQuote(BaseQuotation):
"""腾讯免费行情获取"""
stock_api = "http://sqt.gtimg.cn/utf8/q=r_hk%s"
max_num = 1

def format_response_data(self, rep_data, prefix=False):
stocks_detail = ''.join(rep_data)
stock_detail_split = stocks_detail.split('v_r_hk')
stock_dict = dict()
for data in stock_detail_split:
_stmt = {}
try:
stock_code,stock_data= data.split("=")
_stmt["stock_code"] = stock_code
except Exception as e:
print(e)
continue
try:
stock_data_split = stock_data.split("~")
row = stock_data_split
_stmt_data = dict(
lotSize = row[0],
name = row[1],
price = row[3],
lastPrice = row[4],
openPrice= row[5],
amount = row[6],
time = row[30],
high = row[33],
low = row[34],
)
_stmt.update(_stmt_data)
except expression as identifier:
continue


stock_dict[stock_code] = _stmt

return stock_dict

async def get_stocks_by_range(self, *params):
if self._session is None:
self._session = aiohttp.ClientSession()
headers = {
'Accept-Encoding': 'gzip, deflate, sdch',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.100 Safari/537.36'
}
print(params)
stock_code = params[0]
url = yarl.URL(self.stock_api %(stock_code), encoded=True)
print(url)
try:
async with self._session.get(url, timeout=10, headers=headers) as r:
asyncio.sleep(0.1)
response_text = await r.text()
# print(response_text)
return response_text
except asyncio.TimeoutError:
return ''

def get_stock_data(self, stock_list, **kwargs):
coroutines = []
for params in stock_list:
coroutine = self.get_stocks_by_range(params)
coroutines.append(coroutine)
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
res = loop.run_until_complete(asyncio.gather(*coroutines))
return self.format_response_data([x for x in res if x is not None], **kwargs)

def stock_data():
try:
import ConfigParser as config

except Exception as e:
import configparser as config
data = config.ConfigParser("./hk_stock_codes.conf")
stock_codes = data.get("stock_code")


if __name__ == "__main__":
pass
11 changes: 10 additions & 1 deletion example/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ def test_daykline():
# data = quotation.get_stock_data(stock_list=['hk00700'])
print(data)

def test_hkquote():
import easyquotation
quotation = easyquotation.use("hkquote")
# data = quotation.get_stock_data(stock_list=['00001'])
data = quotation.get_stock_data(stock_list=['00001','00700'])
print(data)


if __name__ == "__main__":
test_daykline()
test_hkquote()


0 comments on commit 59cc0f7

Please sign in to comment.