rquote 0.2.7__py3-none-any.whl → 0.2.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rquote/__init__.py CHANGED
@@ -10,6 +10,6 @@ Copyright (c) 2021 Roi ZHAO
10
10
  from .main import get_price, get_stock_concepts, get_concept_stocks, get_bk_stocks
11
11
  from .main import get_all_concepts, get_all_industries
12
12
  from .main import get_cn_stock_list, get_hk_stocks_hsi, get_hk_stocks_ggt, get_hk_stocks_500
13
- from .main import get_cn_future_list, get_us_stocks_biggest, get_cn_fund_list
13
+ from .main import get_cn_future_list, get_us_stocks, get_cn_fund_list
14
14
  from .utils import WebUtils, BasicFactors
15
15
  from .plots import PlotUtils
rquote/main.py CHANGED
@@ -12,9 +12,9 @@ from .utils import WebUtils, hget, logger
12
12
  def get_cn_stock_list(money_min=2e8):
13
13
  ret = []
14
14
  try:
15
- ret = get_cn_stock_list_eastmoney(money_min)
16
- except Exception as e:
17
15
  ret = get_cn_stock_list_qq(money_min)
16
+ except Exception as e:
17
+ ret = get_cn_stock_list_eastmoney(money_min)
18
18
  return ret
19
19
 
20
20
  def get_cn_stock_list_eastmoney(money_min=2e8):
@@ -45,12 +45,11 @@ def get_cn_stock_list_qq(money_min=2e8):
45
45
  df = []
46
46
  while not df or float(df[-1]['turnover'])*1e4 > money_min:
47
47
  a = hget(
48
- f'https://proxy.finance.qq.com/cgi/cgi-bin/rank/hs/getBoardRankList?_appver=11.17.0'+
48
+ 'https://proxy.finance.qq.com/cgi/cgi-bin/rank/hs/getBoardRankList?_appver=11.17.0'+
49
49
  f'&board_code=aStock&sort_type=turnover&direct=down&offset={offset}&count={count}'
50
50
  )
51
51
  if a:
52
52
  a = json.loads(a.text)
53
- print('===',a)
54
53
  if a['data']['rank_list']:
55
54
  df.extend(a['data']['rank_list'])
56
55
  offset += count
@@ -68,18 +67,18 @@ def get_hk_stocks_500():
68
67
  return a
69
68
 
70
69
 
71
- def get_us_stocks_biggest(k=60):
70
+ def get_us_stocks(k=100):
72
71
  # return list of [symbol, name, price, volume, mktcap, pe]
73
72
  uscands = []
74
- a = hget(
75
- "https://stock.finance.sina.com.cn/usstock/api/jsonp.php/IO.XSRV2."+
76
- "CallbackList['f0j3ltzVzdo2Fo4p']/US_CategoryService.getList?page=1"+
77
- "&num=60&sort=&asc=0&market=&id=", headers=WebUtils.headers()).text
78
- if a:
79
- uslist = json.loads(a.split('(',1)[1][:-2])['data']
80
- # Warning: symbol not fitted
81
- uscands = [('us' + i['symbol'], i['name'], i['price'], i['volume'],
82
- i['mktcap']) for i in uslist]
73
+ page_n = k//20 + 1
74
+ for page in range(1, page_n+1):
75
+ a = hget(
76
+ "https://stock.finance.sina.com.cn/usstock/api/jsonp.php/IO.XSRV2."+
77
+ f"CallbackList['f0j3ltzVzdo2Fo4p']/US_CategoryService.getList?page={page}"+
78
+ "&num=20&sort=&asc=0&market=&id=").text
79
+ if a:
80
+ uslist = json.loads(a.split('(',1)[1][:-2])['data']
81
+ uscands.extend(uslist)
83
82
  return uscands
84
83
 
85
84
 
@@ -115,6 +114,29 @@ def get_cn_future_list():
115
114
  return futurelist_active
116
115
 
117
116
 
117
+ def _check_date_format(date_str):
118
+ # 允许格式: 2099-01-01
119
+ if not re.match(r'^\d{4}-\d{2}-\d{2}$', date_str):
120
+ # 尝试转换
121
+ try:
122
+ # 常见格式尝试
123
+ t_struct = None
124
+ for fmt in ("%Y/%m/%d", "%Y%m%d", "%Y.%m.%d", "%Y_%m_%d", "%Y-%m-%d"):
125
+ try:
126
+ t_struct = time.strptime(date_str, fmt)
127
+ break
128
+ except Exception:
129
+ continue
130
+ if t_struct is None:
131
+ raise ValueError(f"date format not recognized: {date_str}")
132
+ # 转换为标准格式
133
+ date_str_std = time.strftime("%Y-%m-%d", t_struct)
134
+ return date_str_std
135
+ except Exception as e:
136
+ raise ValueError(f"date format error: {date_str}, {e}")
137
+ return date_str
138
+
139
+
118
140
  def get_price(i, sdate='', edate='', freq='day', days=320, fq='qfq',
119
141
  dd=None) -> (str, str, pd.DataFrame):
120
142
  '''
@@ -132,6 +154,12 @@ def get_price(i, sdate='', edate='', freq='day', days=320, fq='qfq',
132
154
  logger.debug('loading price from dd {}'.format(i))
133
155
  return i, n, d
134
156
  logger.debug('fetching price of {}'.format(i))
157
+
158
+ # 检查sdate和edate格式
159
+ sdate = _check_date_format(sdate) if sdate else ''
160
+ edate = _check_date_format(edate) if edate else ''
161
+
162
+
135
163
  qtimg_stock = 'http://web.ifzq.gtimg.cn/appstock/app/newfqkline/get?param=' + \
136
164
  '{},{},{},{},{},{}'
137
165
  qtimg_stock_hk = 'http://web.ifzq.gtimg.cn/appstock/app/hkfqkline/get?' + \
@@ -153,8 +181,7 @@ def get_price(i, sdate='', edate='', freq='day', days=320, fq='qfq',
153
181
  'Emc2VjaWQ9OTAu').decode() + i +
154
182
  '&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5' +
155
183
  '&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58' +
156
- '&klt=101&fqt=0&beg=19900101&end=20990101&_=1',
157
- headers=WebUtils.headers())
184
+ '&klt=101&fqt=0&beg=19900101&end=20990101&_=1')
158
185
  if not a:
159
186
  logger.warning('{} hget failed: {}'.format(i, a))
160
187
  return i, 'None', pd.DataFrame([])
@@ -175,8 +202,7 @@ def get_price(i, sdate='', edate='', freq='day', days=320, fq='qfq',
175
202
 
176
203
  if i[:2] == 'fu':
177
204
  try:
178
- ix = i[2:] if i[-1]=='0' else i[2:-4]
179
- if ix == 'btc' or ix == 'BTC':
205
+ if i[2:5].lower() == 'btc':
180
206
  url = sina_btc
181
207
  d = json.loads(hget(url).text)['result']['data'].split('|')
182
208
  d = pd.DataFrame([i.split(',') for i in d],
@@ -202,7 +228,7 @@ def get_price(i, sdate='', edate='', freq='day', days=320, fq='qfq',
202
228
  elif i[:2] == 'us':
203
229
  url = qtimg_stock_us.format(i, freq, sdate, edate, days, fq)
204
230
  else:
205
- raise ValueError('target market not supported')
231
+ raise ValueError(f'target market not supported: {i}')
206
232
  a = hget(url)
207
233
  #a = json.loads(a.text.replace('kline_dayqfq=', ''))['data'][i]
208
234
  a = json.loads(a.text)['data'][i]
@@ -432,4 +458,8 @@ def get_hk_stocks_hsi():
432
458
 
433
459
 
434
460
 
461
+ if __name__ == "__main__":
462
+ # print(get_cn_stock_list())
463
+ # print(get_price('fuBTC'))
464
+ print(get_price('sz000001', sdate='20240101', edate='20250101'))
435
465
 
rquote/utils.py CHANGED
@@ -4,7 +4,6 @@ import time
4
4
  import random
5
5
  import logging
6
6
  import httpx
7
- import numpy as np
8
7
  import pandas as pd
9
8
  import uuid
10
9
 
@@ -0,0 +1,285 @@
1
+ Metadata-Version: 2.4
2
+ Name: rquote
3
+ Version: 0.2.9
4
+ Summary: Mostly day quotes of cn/hk/us/fund/future markets, side with quote list fetch
5
+ Requires-Python: >=3.6.1
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: httpx>=0.20.0
8
+ Requires-Dist: pandas>=1.0.0
9
+ Requires-Dist: setuptools>=42
10
+ Requires-Dist: twine>=3.8.0
11
+
12
+ # rquote
13
+
14
+ `rquote` 是一个提供 A股/港股/美股/ETF基金/期货 历史数据获取的Python库
15
+
16
+ ## 主要功能
17
+
18
+ ### 历史价格数据获取
19
+
20
+ #### `get_price(i, sdate='', edate='', freq='day', days=320, fq='qfq', dd=None)`
21
+
22
+ 获取股票、基金、期货的历史价格数据
23
+
24
+ **参数:**
25
+ - `i`: 股票代码,使用新浪/腾讯的id形式
26
+ - `sdate`: 开始日期 (可选)
27
+ - `edate`: 结束日期 (可选)
28
+ - `freq`: 频率,默认'day' (日线)
29
+ - `days`: 获取天数,默认320天
30
+ - `fq`: 复权方式,默认'qfq' (前复权)
31
+ - `dd`: 本地缓存字典 (可选)
32
+
33
+ **代码格式说明:**
34
+ - A股: `sh000001`表示上证指数,`sz000001`表示深市000001股票`平安银行`
35
+ - ETF: `sh510050`表示上证50指数ETF
36
+ - 港股: `hk00700`表示港股腾讯
37
+ - 期货: 需加`fu`前缀,如`fuAP2110`,`fuBTC`表示比特币
38
+ - 美股: 需加对应交易所后缀,如`usBABA.N`,`usC.N`,`usAAPL.OQ`等
39
+ - 比特币:使用`fuBTC`代码
40
+
41
+ **示例:**
42
+ ```python
43
+ from rquote import get_price
44
+
45
+ # 获取上证指数数据
46
+ sid, nm, df = get_price('sh000001')
47
+ print(df.head()) # 数据为pandas dataframe
48
+
49
+ # 获取指定日期范围的数据
50
+ sid, nm, df = get_price('sz000001', sdate='2024-01-01', edate='2024-02-01')
51
+
52
+ # 获取比特币数据
53
+ sid, nm, df = get_price('fuBTC')
54
+ ```
55
+
56
+ **返回数据格式:**
57
+ | date | open | close | high | low | vol |
58
+ |------------|---------|---------|---------|---------|------------|
59
+ | 2024-02-06 | 2680.48 | 2789.49 | 2802.93 | 2669.67 | 502849313 |
60
+ | 2024-02-07 | 2791.51 | 2829.70 | 2829.70 | 2770.53 | 547117439 |
61
+ | 2024-02-08 | 2832.49 | 2865.90 | 2867.47 | 2827.90 | 531108893 |
62
+ | 2024-02-19 | 2886.59 | 2910.54 | 2910.54 | 2867.71 | 458967704 |
63
+ | 2024-02-20 | 2902.88 | 2922.73 | 2927.31 | 2887.47 | 350138735 |
64
+
65
+ #### `get_price_longer(i, l=2, dd={})`
66
+
67
+ 获取更长时间的历史数据,默认获取2年数据
68
+
69
+ ```python
70
+ from rquote import get_price_longer
71
+
72
+ # 获取2年的历史数据
73
+ sid, nm, df = get_price_longer('sh000001', l=3) # 获取3年数据
74
+ ```
75
+
76
+ ### 股票列表获取
77
+
78
+ #### `get_cn_stock_list(money_min=2e8)`
79
+
80
+ 获取A股股票列表,按成交额排序,默认筛选成交额大于2亿的股票
81
+
82
+ ```python
83
+ from rquote import get_cn_stock_list
84
+
85
+ # 获取成交额大于5亿的股票列表
86
+ stocks = get_cn_stock_list(money_min=5e8)
87
+ # 返回格式: [{code, name, pe_ttm, volume, turnover/亿, ...}, ...]
88
+ # 如 {"code":"sh600519","hsl":"0.28","lb":"0.94","ltsz":"17946.80","name":"贵州茅台","pe_ttm":"20.16","pn":"6.95","speed":"0.02","state":"","stock_type":"GP-A","turnover":"499068","volume":"34816.00","zd":"2.66","zdf":"0.19","zdf_d10":"-5.16","zdf_d20":"-9.58","zdf_d5":"0.12","zdf_d60":"-9.22","zdf_w52":"-3.22","zdf_y":"-6.26","zf":"1.47","zljlr":"16268.84","zllc":"263511.99","zllc_d5":"1295957.54","zllr":"279780.83","zllr_d5":"1264966.39","zsz":"17946.80","zxj":"1428.66"}
89
+ ```
90
+
91
+ #### `get_hk_stocks_500()`
92
+
93
+ 获取港股前500只股票列表
94
+
95
+ ```python
96
+ from rquote import get_hk_stocks_500
97
+
98
+ stocks = get_hk_stocks_500()
99
+ # 返回格式: [[code, name, price, turnover, ...], ...]
100
+ # 如 ['00700', '腾讯控股', '505.50', '1.51', '7.50', '505.50', '505.50', '20622275.00', '10364144211.54', '504.50', '498.00', '505.50', '496.00', '0.22']
101
+ ```
102
+
103
+ #### `get_hk_stocks_hsi()`
104
+
105
+ 获取恒生指数成分股列表
106
+
107
+ ```python
108
+ from rquote import get_hk_stocks_hsi
109
+
110
+ hsi_stocks = get_hk_stocks_hsi()
111
+ ```
112
+
113
+ #### `get_hk_stocks_ggt()`
114
+
115
+ 获取港股通股票列表
116
+
117
+ ```python
118
+ from rquote import get_hk_stocks_ggt
119
+
120
+ ggt_stocks = get_hk_stocks_ggt()
121
+ ```
122
+
123
+ #### `get_us_stocks(k=100)`
124
+
125
+ 获取美股最大市值的k支股票列表
126
+
127
+ ```python
128
+ from rquote import get_us_stocks_biggest
129
+
130
+ us_stocks = get_us_stocks_biggest(k=100) # 获取前100只
131
+ # 返回格式: [{name, symbol, market, mktcap, pe, ...}, ...]
132
+ # 如 {"name":"Microsoft Corp.","cname":"微软公司","category":"软件","symbol":"MSFT","price":"480.24","diff":"2.20","chg":"0.46","preclose":"478.04","open":"478.00","high":"481.00","low":"474.46","amplitude":"1.37%","volume":"17526452","mktcap":"3569404793144","pe":"36.94153771","market":"NASDAQ","category_id":"14"}
133
+ ```
134
+
135
+ ### 基金和期货
136
+
137
+ #### `get_cn_fund_list()`
138
+
139
+ 获取A股ETF基金列表,按成交额排序
140
+
141
+ ```python
142
+ from rquote import get_cn_fund_list
143
+
144
+ funds = get_cn_fund_list()
145
+ # 返回格式: [code, name, change, amount, price]
146
+ ```
147
+
148
+ #### `get_cn_future_list()`
149
+
150
+ 获取国内期货合约列表
151
+
152
+ ```python
153
+ from rquote import get_cn_future_list
154
+
155
+ futures = get_cn_future_list()
156
+ # 返回格式: ['fuSC2109', 'fuRB2110', 'fuHC2110', ...]
157
+ ```
158
+
159
+ ### 板块和概念
160
+
161
+ #### `get_all_industries()`
162
+
163
+ 获取所有行业板块列表
164
+
165
+ ```python
166
+ from rquote import get_all_industries
167
+
168
+ industries = get_all_industries()
169
+ # 返回格式: [code, name, change, amount, price]
170
+ ```
171
+
172
+ #### `get_all_concepts()`
173
+
174
+ 获取所有概念板块列表
175
+
176
+ ```python
177
+ from rquote import get_all_concepts
178
+
179
+ concepts = get_all_concepts()
180
+ # 返回格式: [code, name, change, amount, price]
181
+ ```
182
+
183
+ #### `get_stock_concepts(i)`
184
+
185
+ 获取指定股票所属的概念板块
186
+
187
+ ```python
188
+ from rquote import get_stock_concepts
189
+
190
+ # 获取平安银行的概念板块
191
+ concepts = get_stock_concepts('sz000001')
192
+ # 返回概念代码列表,如 ['BK0420', 'BK0900', ...]
193
+ ```
194
+
195
+ #### `get_concept_stocks(bkid, dc=None)`
196
+
197
+ 获取指定概念板块的股票列表
198
+
199
+ ```python
200
+ from rquote import get_concept_stocks
201
+
202
+ # 获取概念板块BK0420的股票
203
+ stocks = get_concept_stocks('BK0420')
204
+ # 返回格式: [code, name, change, amount, mktcap]
205
+ ```
206
+
207
+ #### `get_bk_stocks(bkid)`
208
+
209
+ 获取指定板块的股票列表
210
+
211
+ ```python
212
+ from rquote import get_bk_stocks
213
+
214
+ # 获取板块股票
215
+ stocks = get_bk_stocks('BK0420')
216
+ ```
217
+
218
+ #### `get_industry_stocks(bkid)`
219
+
220
+ 获取指定行业板块的股票列表
221
+
222
+ ```python
223
+ from rquote import get_industry_stocks
224
+
225
+ # 获取行业板块股票
226
+ stocks = get_industry_stocks('BK0420')
227
+ ```
228
+
229
+ ### 实时行情
230
+
231
+ #### `get_tick(tgts=[])`
232
+
233
+ 获取实时行情数据
234
+
235
+ ```python
236
+ from rquote import get_tick
237
+
238
+ # 获取美股实时行情
239
+ tick_data = get_tick(['AAPL', 'GOOGL'])
240
+ # 返回格式: [{'name': 'Apple Inc', 'price': '150.25', 'price_change_rate': '1.2%', ...}]
241
+ ```
242
+
243
+ ### 可视化工具
244
+
245
+ #### `PlotUtils.plot_candle(i, sdate='', edate='', dsh=False, vol=True)`
246
+
247
+ 绘制K线图
248
+
249
+ ```python
250
+ from rquote import PlotUtils
251
+
252
+ # 绘制平安银行的K线图
253
+ data, layout = PlotUtils.plot_candle('sz000001', sdate='2024-01-01', edate='2024-02-01')
254
+
255
+ # 使用plotly显示
256
+ import plotly.graph_objs as go
257
+ fig = go.Figure(data=data, layout=layout)
258
+ fig.show()
259
+ ```
260
+
261
+ ### 工具类
262
+
263
+ #### `WebUtils`
264
+
265
+ 网络请求工具类
266
+
267
+ #### `BasicFactors`
268
+
269
+ 基础因子计算工具类
270
+
271
+ ## 安装
272
+
273
+ ```bash
274
+ pip install rquote
275
+ ```
276
+
277
+ ## 注意事项
278
+
279
+ 1. 数据来源于新浪财经、腾讯财经、东方财富等公开数据源
280
+ 2. 建议合理控制请求频率,避免被限制访问
281
+ 3. 期货代码需要加`fu`前缀,如`fuAP2110`
282
+ 4. 美股代码需要加对应后缀,如`usAAPL.OQ` (OQ->NASDAQ, N->NYSE, AM->ETF)
283
+
284
+
285
+
@@ -0,0 +1,8 @@
1
+ rquote/__init__.py,sha256=PB620yEq2QZyfDweKY_8qMEsZMKhskGfhmfDkch_0j0,462
2
+ rquote/main.py,sha256=SiMpjcs9zvcRzvSMPByX_ZpLQuYRyx2AUEeHJnj8uE4,18272
3
+ rquote/plots.py,sha256=N8uvD6ju9tow0DllPQiXiM7EoPC2bK8X7QF6NQainKs,2342
4
+ rquote/utils.py,sha256=4Neb9_R-EKAd6s1Qj4O_vs9jXWyvroxEEhdqH35vxVE,6808
5
+ rquote-0.2.9.dist-info/METADATA,sha256=QG0nVFxI0ePdTK7894Ajq8H4R2X-PbiRoLMG-h75Q3M,7273
6
+ rquote-0.2.9.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
+ rquote-0.2.9.dist-info/top_level.txt,sha256=CehAiaZx7Fo8HGoV2zd5GhILUW1jQEN8YS-cWMlrK9Y,7
8
+ rquote-0.2.9.dist-info/RECORD,,
@@ -1,40 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: rquote
3
- Version: 0.2.7
4
- Summary: Mostly day quotes of cn/hk/us/fund/future markets, side with quote list fetch
5
- Home-page: https://github.com/kids/rquote
6
- Author: Roizhao
7
- Author-email: roizhao@gmail.com
8
- Requires-Python: >=3.6.1
9
- Description-Content-Type: text/markdown
10
- Requires-Dist: httpx>=0.20.0
11
- Requires-Dist: pandas>=1.0.0
12
- Requires-Dist: setuptools>=59.6.0
13
- Requires-Dist: twine>=3.8.0
14
- Dynamic: author
15
- Dynamic: author-email
16
- Dynamic: home-page
17
- Dynamic: requires-python
18
-
19
- # rquote
20
-
21
- `get_price`方法提供 A股/港股/美股/ETF基金/期货 日线历史数据获取
22
-
23
- 使用新浪/腾讯的id形式,如`sh000001`表示上证指数,`sz000001`表示深市000001股票`平安银行`,`sh510050`表示上证50指数ETF,`hk00700`表示港股腾讯。
24
- 期货代码需加`fu`前缀,如`fuAP2110`,美股需加对应交易所后缀,如`usBABA.N`,`usC.N`,`usAAPL.OQ`等
25
- BTC/USD也放在fu下面,i.d.`fuBTC`
26
-
27
- e.g.
28
- ```
29
- from rquote import get_price
30
- sid, nm, df = get_price('sh000001')
31
- df.head() # 数据为pandas dataframe
32
- ```
33
- > open close high low vol
34
- > date
35
- > 2024-02-06 2680.48 2789.49 2802.93 2669.67 502849313.0
36
- > 2024-02-07 2791.51 2829.70 2829.70 2770.53 547117439.0
37
- > 2024-02-08 2832.49 2865.90 2867.47 2827.90 531108893.0
38
- > 2024-02-19 2886.59 2910.54 2910.54 2867.71 458967704.0
39
- > 2024-02-20 2902.88 2922.73 2927.31 2887.47 350138735.0
40
-
@@ -1,8 +0,0 @@
1
- rquote/__init__.py,sha256=owCwRRDJoYUuR7-NKb_Nj3-2CCsL7TtrRVp6px_8RGA,470
2
- rquote/main.py,sha256=BrY6TnYcW2NhphHHD0FBsBTr3C4cFaKUAgM1nQ097-o,17322
3
- rquote/plots.py,sha256=N8uvD6ju9tow0DllPQiXiM7EoPC2bK8X7QF6NQainKs,2342
4
- rquote/utils.py,sha256=v8j8R2xoXyTsHSAWXD7x2FUV7w1a4xgfswfSDdfg5p8,6827
5
- rquote-0.2.7.dist-info/METADATA,sha256=8Ztlu-8Inaa7fw9URPv_eaqw6k3h2yZx64RiEP3elOs,1457
6
- rquote-0.2.7.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
- rquote-0.2.7.dist-info/top_level.txt,sha256=CehAiaZx7Fo8HGoV2zd5GhILUW1jQEN8YS-cWMlrK9Y,7
8
- rquote-0.2.7.dist-info/RECORD,,
File without changes