tdxdata 0.2.7__tar.gz → 0.2.9__tar.gz
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.
- {tdxdata-0.2.7/src/tdxdata.egg-info → tdxdata-0.2.9}/PKG-INFO +1 -1
- {tdxdata-0.2.7 → tdxdata-0.2.9}/pyproject.toml +13 -1
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/__init__.py +2 -2
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/adjust.py +2 -4
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/cli_qx.py +12 -10
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/client.py +0 -1
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/gbbq.py +53 -14
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/pool2.py +2 -2
- {tdxdata-0.2.7 → tdxdata-0.2.9/src/tdxdata.egg-info}/PKG-INFO +1 -1
- {tdxdata-0.2.7 → tdxdata-0.2.9}/tests/test_adjust.py +1 -1
- {tdxdata-0.2.7 → tdxdata-0.2.9}/tests/test_finance_pool.py +1 -1
- tdxdata-0.2.9/tests/test_gbbq.py +150 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/tests/test_xdxr.py +1 -1
- tdxdata-0.2.7/tests/test_gbbq.py +0 -67
- {tdxdata-0.2.7 → tdxdata-0.2.9}/LICENSE +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/NOTICE.md +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/README.md +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/setup.cfg +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/cli.py +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/commands/__init__.py +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/commands/auth.py +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/commands/bars.py +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/commands/finance.py +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/commands/quotes.py +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/commands/xdxr.py +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/frame.py +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/gbbq_keys.py +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/protocol.py +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata/servers.txt +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata.egg-info/SOURCES.txt +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata.egg-info/dependency_links.txt +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata.egg-info/entry_points.txt +0 -0
- {tdxdata-0.2.7 → tdxdata-0.2.9}/src/tdxdata.egg-info/top_level.txt +0 -0
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "tdxdata"
|
|
7
|
-
version = "0.2.
|
|
7
|
+
version = "0.2.9"
|
|
8
8
|
description = "TDX (通达信) 2026-09 新版行情协议客户端 — realtime A-share quotes"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -31,6 +31,18 @@ Changelog = "https://github.com/ShanNing-YU/a-share-tdxdata/blob/main/CHANGELOG.
|
|
|
31
31
|
tdxdata-probe = "tdxdata.cli:main"
|
|
32
32
|
tdxdata-qx = "tdxdata.cli_qx:main"
|
|
33
33
|
|
|
34
|
+
[tool.ruff]
|
|
35
|
+
line-length = 120
|
|
36
|
+
target-version = "py310"
|
|
37
|
+
|
|
38
|
+
[tool.ruff.lint]
|
|
39
|
+
# lint 基线 = 「真问题」类:
|
|
40
|
+
# F 未定义名/未用导入与变量/语法
|
|
41
|
+
# E9 语法错误
|
|
42
|
+
# B bugbear(可疑用法,如 zip 长度不匹配、except 里 raise 丢失上下文)
|
|
43
|
+
# 风格类(UTF-8 声明、import 排序、盲 except 容错等)按项目既有约定不强制启用。
|
|
44
|
+
select = ["F", "E9", "B"]
|
|
45
|
+
|
|
34
46
|
[tool.setuptools.packages.find]
|
|
35
47
|
where = ["src"]
|
|
36
48
|
|
|
@@ -24,11 +24,11 @@
|
|
|
24
24
|
"""
|
|
25
25
|
from .adjust import adjust_bars, adjust_prices, affine_coeffs, factors, round_half_up
|
|
26
26
|
from .client import TdxClient, market_of, parse_snap
|
|
27
|
-
from .gbbq import (GBBQ_URL, decrypt_record, decrypt_records,
|
|
27
|
+
from .gbbq import (GBBQ_URL, decrypt_record, decrypt_records,
|
|
28
28
|
download_gbbq, events_of, read_gbbq, to_map)
|
|
29
29
|
from .pool2 import Pool # 0.2.0: 顶层导出并发池(含 finance_all),否则 import tdxdata; tdxdata.Pool 不可见
|
|
30
30
|
|
|
31
|
-
__version__ = "0.2.
|
|
31
|
+
__version__ = "0.2.9" # ponytail: 与 pyproject.toml 手工同步;tests 里有漂移断言兜底
|
|
32
32
|
__all__ = ["TdxClient", "Pool", "market_of", "parse_snap", "__version__",
|
|
33
33
|
# 权息 / 复权(2026-11-13 新增)
|
|
34
34
|
"GBBQ_URL", "download_gbbq", "read_gbbq", "decrypt_record", "decrypt_records",
|
|
@@ -25,8 +25,6 @@
|
|
|
25
25
|
算法口径参考 injoyai/tdx(MIT, protocol/model_gbbq.go,其结论为「与桌面端逐分对齐」),
|
|
26
26
|
本实现独立重写 + 单测断言(见 tests/test_adjust.py)。
|
|
27
27
|
"""
|
|
28
|
-
import math
|
|
29
|
-
|
|
30
28
|
__all__ = ['affine_coeffs', 'round_half_up', 'factors', 'adjust_prices', 'adjust_bars']
|
|
31
29
|
|
|
32
30
|
|
|
@@ -117,7 +115,7 @@ def adjust_prices(prices, dates, events, mode='qfq', ndigits=2) -> list:
|
|
|
117
115
|
return list(prices)
|
|
118
116
|
fs = factors(events, dates)
|
|
119
117
|
out = []
|
|
120
|
-
for p, f in zip(prices, fs):
|
|
118
|
+
for p, f in zip(prices, fs, strict=True):
|
|
121
119
|
if p is None:
|
|
122
120
|
out.append(None)
|
|
123
121
|
continue
|
|
@@ -137,7 +135,7 @@ def adjust_bars(bars, events, mode='qfq', price_keys=('open', 'close', 'high', '
|
|
|
137
135
|
dates = [_as_int_date(bar.get('datetime') or bar.get('date')) for bar in bars]
|
|
138
136
|
fs = factors(events, dates)
|
|
139
137
|
out = []
|
|
140
|
-
for bar, f in zip(bars, fs):
|
|
138
|
+
for bar, f in zip(bars, fs, strict=True):
|
|
141
139
|
nb = dict(bar)
|
|
142
140
|
if mode == 'qfq':
|
|
143
141
|
mul, add = f['qfq_mul'], f['qfq_add']
|
|
@@ -16,7 +16,7 @@ import json
|
|
|
16
16
|
import sys
|
|
17
17
|
|
|
18
18
|
from .adjust import factors, round_half_up
|
|
19
|
-
from .client import TdxClient
|
|
19
|
+
from .client import TdxClient
|
|
20
20
|
|
|
21
21
|
|
|
22
22
|
def _print_events(events, code):
|
|
@@ -47,17 +47,13 @@ def cmd_xdxr(a):
|
|
|
47
47
|
|
|
48
48
|
|
|
49
49
|
def cmd_gbbq(a):
|
|
50
|
-
from .gbbq import download_gbbq, events_of, read_gbbq
|
|
50
|
+
from .gbbq import decrypt_records, download_gbbq, events_of, read_gbbq
|
|
51
51
|
if a.path:
|
|
52
52
|
recs = read_gbbq(a.path, cache_dir=a.cache_dir)
|
|
53
53
|
src = a.path
|
|
54
54
|
else:
|
|
55
|
-
data = download_gbbq(dest=a.out)['gbbq']
|
|
56
|
-
|
|
57
|
-
from pathlib import Path
|
|
58
|
-
tmp = Path(tempfile.mkdtemp()) / 'gbbq'
|
|
59
|
-
tmp.write_bytes(data)
|
|
60
|
-
recs = read_gbbq(tmp, cache_dir=a.cache_dir)
|
|
55
|
+
data = download_gbbq(dest=a.out, url=a.url)['gbbq']
|
|
56
|
+
recs = decrypt_records(data)
|
|
61
57
|
src = f'{a.url}({len(data):,d} B)'
|
|
62
58
|
ev = [r for r in recs if r['category'] == 1]
|
|
63
59
|
print(f'来源: {src}')
|
|
@@ -86,7 +82,7 @@ def cmd_adjust(a):
|
|
|
86
82
|
print(f'{a.code} 近 {len(bars)} 根日线(复权=仿射口径,成交量不复权)'
|
|
87
83
|
f'|可用事件 {len(ev)} 条')
|
|
88
84
|
print(' 日期 原始收盘 前复权 后复权 QFQ(A,B) HFQ(A,B)')
|
|
89
|
-
for b, f in zip(bars, fs):
|
|
85
|
+
for b, f in zip(bars, fs, strict=True):
|
|
90
86
|
raw = b['close']
|
|
91
87
|
q = round_half_up(f['qfq_mul'] * raw + f['qfq_add'])
|
|
92
88
|
h = round_half_up(f['hfq_mul'] * raw + f['hfq_add'])
|
|
@@ -129,7 +125,13 @@ def main(argv=None):
|
|
|
129
125
|
if getattr(a, 'url', None) is None and hasattr(a, 'url'):
|
|
130
126
|
from .gbbq import GBBQ_URL
|
|
131
127
|
a.url = GBBQ_URL
|
|
132
|
-
|
|
128
|
+
try:
|
|
129
|
+
return a.func(a)
|
|
130
|
+
except (OSError, ValueError) as e:
|
|
131
|
+
# 网络不通 / 数据源改版 / 参数问题 → 一行可读错误(原来是裸 traceback,像崩了)。
|
|
132
|
+
# 其他异常照旧抛出(真 bug 要看得见)。
|
|
133
|
+
print(f'错误: {type(e).__name__}: {e}', file=sys.stderr)
|
|
134
|
+
return 2
|
|
133
135
|
|
|
134
136
|
|
|
135
137
|
if __name__ == '__main__':
|
|
@@ -14,12 +14,13 @@
|
|
|
14
14
|
解密后 = market(1) + code(7 补 0) + date(u32 YYYYMMDD) + category(1) + 4 × float32。
|
|
15
15
|
- 密钥表见 `gbbq_keys.py`(源自 pytdx,MIT)。
|
|
16
16
|
|
|
17
|
-
实测对比(2026-11-13):HTTP 版 207,
|
|
18
|
-
→ **本地版是 HTTP
|
|
17
|
+
实测对比(2026-11-13):HTTP 版 **207,882 条 / 7,417 只**,客户端本地版 194,553 条 / 6,342 只
|
|
18
|
+
→ **本地版是 HTTP 版的严格子集**(少约 1.3 万条,多为退市/老股票),两者共有股票的事件逐条一致。
|
|
19
|
+
(官方数据站每日滚动更新,条数会变;客户端本地版只在客户端运行时更新,因此差值会浮动。)
|
|
19
20
|
"""
|
|
21
|
+
import hashlib
|
|
20
22
|
import io
|
|
21
23
|
import struct
|
|
22
|
-
import time
|
|
23
24
|
import urllib.request
|
|
24
25
|
import zipfile
|
|
25
26
|
from pathlib import Path
|
|
@@ -62,7 +63,12 @@ def decrypt_record(rec: bytes) -> bytes:
|
|
|
62
63
|
|
|
63
64
|
|
|
64
65
|
def decrypt_records(raw: bytes) -> list:
|
|
65
|
-
"""解密整个 gbbq 文件 → 记录列表(dict,字段与 xdxr 一致)
|
|
66
|
+
"""解密整个 gbbq 文件 → 记录列表(dict,字段与 xdxr 一致)
|
|
67
|
+
|
|
68
|
+
文件损坏/为空时抛 `ValueError`(不是裸 struct.error),便于调用方识别。
|
|
69
|
+
"""
|
|
70
|
+
if len(raw) < 4:
|
|
71
|
+
raise ValueError(f'gbbq 数据过短({len(raw)} 字节,至少需要 4 字节的记录数)——不是有效的 gbbq')
|
|
66
72
|
count = struct.unpack_from('<I', raw, 0)[0]
|
|
67
73
|
body = raw[4:]
|
|
68
74
|
n = min(count, len(body) // RECORD_SIZE)
|
|
@@ -88,6 +94,19 @@ def decrypt_records(raw: bytes) -> list:
|
|
|
88
94
|
|
|
89
95
|
# ---------------------------------------------------------------- 获取
|
|
90
96
|
|
|
97
|
+
def _extract_members(blob: bytes, members=('gbbq', 'gbbq.map')) -> dict:
|
|
98
|
+
"""从官方 zip 里解出指定成员;缺 gbbq 时抛可读的 ValueError(不是裸 KeyError)"""
|
|
99
|
+
try:
|
|
100
|
+
with zipfile.ZipFile(io.BytesIO(blob)) as z:
|
|
101
|
+
names = set(z.namelist())
|
|
102
|
+
out = {m: z.read(m) for m in members if m in names}
|
|
103
|
+
except zipfile.BadZipFile as e:
|
|
104
|
+
raise ValueError(f'官方数据包不是有效 zip:{e}') from e
|
|
105
|
+
if 'gbbq' not in out:
|
|
106
|
+
raise ValueError(f'官方数据包内没有 gbbq(包内文件:{sorted(names)[:8]})—— 数据源可能已改版')
|
|
107
|
+
return out
|
|
108
|
+
|
|
109
|
+
|
|
91
110
|
def download_gbbq(dest=None, url=GBBQ_URL, timeout=90, members=('gbbq', 'gbbq.map')):
|
|
92
111
|
"""下载 gbbq.zip 并解出指定成员 → {成员名: bytes};`dest` 传目录时同时落盘
|
|
93
112
|
|
|
@@ -96,12 +115,7 @@ def download_gbbq(dest=None, url=GBBQ_URL, timeout=90, members=('gbbq', 'gbbq.ma
|
|
|
96
115
|
req = urllib.request.Request(url, headers={'User-Agent': 'tdxdata/0.2.6'})
|
|
97
116
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
98
117
|
blob = r.read()
|
|
99
|
-
out =
|
|
100
|
-
with zipfile.ZipFile(io.BytesIO(blob)) as z:
|
|
101
|
-
names = set(z.namelist())
|
|
102
|
-
for m in members:
|
|
103
|
-
if m in names:
|
|
104
|
-
out[m] = z.read(m)
|
|
118
|
+
out = _extract_members(blob, members)
|
|
105
119
|
if dest is not None:
|
|
106
120
|
d = Path(dest)
|
|
107
121
|
d.mkdir(parents=True, exist_ok=True)
|
|
@@ -124,24 +138,32 @@ def read_gbbq(path=None, url=GBBQ_URL, cache_dir=None, use_cache=True, verbose=F
|
|
|
124
138
|
tag = Path(path).name
|
|
125
139
|
if use_cache:
|
|
126
140
|
cache_dir = Path(cache_dir or Path.home() / '.cache' / 'tdxdata')
|
|
127
|
-
|
|
141
|
+
# 缓存键用源文件 md5——只按长度会撞(不同版本 gbbq 长度可能相同 → 读到过期数据)
|
|
142
|
+
key = f'gbbq_{tag}_{hashlib.md5(data).hexdigest()[:12]}.bin'
|
|
128
143
|
cf = cache_dir / key
|
|
129
144
|
if cf.exists():
|
|
130
|
-
|
|
145
|
+
try:
|
|
146
|
+
return _load_cache(cf)
|
|
147
|
+
except Exception:
|
|
148
|
+
pass # 缓存损坏 → 忽略,走完整解密
|
|
131
149
|
recs = decrypt_records(data)
|
|
132
150
|
try:
|
|
133
151
|
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
134
152
|
_save_cache(cf, recs)
|
|
153
|
+
_prune_cache(cache_dir, tag, keep=3)
|
|
135
154
|
except Exception:
|
|
136
155
|
pass
|
|
137
156
|
return recs
|
|
138
157
|
return decrypt_records(data)
|
|
139
158
|
|
|
140
159
|
|
|
141
|
-
# ----------------------------------------------------------------
|
|
160
|
+
# ---------------------------------------------------------------- 缓存(魔数 + 24B/条,纯 stdlib)
|
|
161
|
+
|
|
162
|
+
CACHE_MAGIC = b'TXG1'
|
|
163
|
+
|
|
142
164
|
|
|
143
165
|
def _save_cache(cf: Path, recs: list):
|
|
144
|
-
buf = bytearray()
|
|
166
|
+
buf = bytearray(CACHE_MAGIC)
|
|
145
167
|
for r in recs:
|
|
146
168
|
code = r['code'].encode()[:7].ljust(7, b'\x00')
|
|
147
169
|
f = r['raw'] or (r['fenhong'], r['peigujia'], r['songzhuangu'], r['peigu'])
|
|
@@ -151,7 +173,14 @@ def _save_cache(cf: Path, recs: list):
|
|
|
151
173
|
|
|
152
174
|
|
|
153
175
|
def _load_cache(cf: Path) -> list:
|
|
176
|
+
"""读缓存;格式不符/被截断/损坏 → 抛 ValueError(调用方回退完整解密,不静默给空数据)"""
|
|
154
177
|
raw = cf.read_bytes()
|
|
178
|
+
if not raw.startswith(CACHE_MAGIC):
|
|
179
|
+
raise ValueError('缓存文件魔数不符')
|
|
180
|
+
body = raw[len(CACHE_MAGIC):]
|
|
181
|
+
if not body or len(body) % 24:
|
|
182
|
+
raise ValueError(f'缓存文件长度异常({len(body)} 字节,应为 24 的倍数)')
|
|
183
|
+
raw = body
|
|
155
184
|
out = []
|
|
156
185
|
for i in range(len(raw) // 24):
|
|
157
186
|
market, code_b, date, cat, f1, f2, f3, f4 = struct.unpack_from('<B7sIBffff', raw, i * 24)
|
|
@@ -185,3 +214,13 @@ def to_map(recs, category=1):
|
|
|
185
214
|
for v in m.values():
|
|
186
215
|
v.sort(key=lambda r: r['date'])
|
|
187
216
|
return m
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _prune_cache(cache_dir: Path, tag: str, keep: int = 3):
|
|
220
|
+
"""同一来源只保留最近 keep 份缓存(权息表每版约 5MB,不清理会持续累积)"""
|
|
221
|
+
try:
|
|
222
|
+
files = sorted(cache_dir.glob(f'gbbq_{tag}_*.bin'), key=lambda p: p.stat().st_mtime)
|
|
223
|
+
for p in files[:-keep] if len(files) > keep else []:
|
|
224
|
+
p.unlink()
|
|
225
|
+
except Exception:
|
|
226
|
+
pass
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# -*- coding: utf-8 -*-
|
|
2
2
|
"""并发池: 43 IP 并发,每连接顺序拉 N 只(3s/只),全市场快照 ~12-15 分钟"""
|
|
3
|
-
import socket, time, struct, os, threading, random
|
|
3
|
+
import socket, time, struct, os, threading, random
|
|
4
4
|
|
|
5
5
|
PORT = 7709
|
|
6
6
|
C02 = bytes.fromhex("0c0218940001030003000d0001")
|
|
@@ -97,7 +97,7 @@ def worker(host, codes, results, idx):
|
|
|
97
97
|
try:
|
|
98
98
|
r = c.snap(code, m)
|
|
99
99
|
mine.append((code, r.get('last'), r['ok']))
|
|
100
|
-
except Exception
|
|
100
|
+
except Exception:
|
|
101
101
|
mine.append((code, None, False))
|
|
102
102
|
results[idx] = mine
|
|
103
103
|
c.close()
|
|
@@ -22,7 +22,7 @@ CASES = ['000001', '600519', '300750']
|
|
|
22
22
|
def test_finance_all_basic():
|
|
23
23
|
rows = Pool(n_conn=3).finance_all(CASES)
|
|
24
24
|
assert len(rows) == len(CASES), f'返回长度应为 {len(CASES)},实际 {len(rows)}'
|
|
25
|
-
for code, r in zip(CASES, rows):
|
|
25
|
+
for code, r in zip(CASES, rows, strict=False):
|
|
26
26
|
assert r.get('ok') is True, f'{code} 取数失败: {r}'
|
|
27
27
|
assert r.get('code') == code, f'顺序/代码错位: 期望 {code} 实际 {r.get("code")}'
|
|
28
28
|
assert len(r) == 40, f'{code} 字段数应为 40,实际 {len(r)}'
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""gbbq(权息表)离线测试 —— 加密记录夹具取自 2026-11-12 官方 dbf 包(HTTP 源)
|
|
3
|
+
|
|
4
|
+
跑法:python tests/test_gbbq.py 或 pytest tests/test_gbbq.py
|
|
5
|
+
"""
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
|
|
10
|
+
|
|
11
|
+
from tdxdata.gbbq import (GBBQ_URL, RECORD_SIZE, decrypt_record, # noqa: E402
|
|
12
|
+
events_of, to_map)
|
|
13
|
+
|
|
14
|
+
# 001225 三条 category=1 加密记录(29B hex)+ 期望解密结果
|
|
15
|
+
CASES = [
|
|
16
|
+
('1f8299cce874c2ea85569cc3454c912950940abb96412e270000000000',
|
|
17
|
+
0, '001225', 20230522, 1, 12.5, 0.0, 0.0, 0.0),
|
|
18
|
+
('1f8299cce874c2ea2c9288533983b59350940abb96412e270000000000',
|
|
19
|
+
0, '001225', 20240422, 1, 12.5, 0.0, 0.0, 0.0),
|
|
20
|
+
('1f8299cce874c2ea973d98914eeae91250940abb96412e270000000000',
|
|
21
|
+
0, '001225', 20250522, 1, 12.22, 0.0, 0.0, 0.0),
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_url_and_size():
|
|
26
|
+
assert GBBQ_URL.startswith('http://www.tdx.com.cn/')
|
|
27
|
+
assert RECORD_SIZE == 29
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_decrypt_record_fixtures():
|
|
31
|
+
import struct
|
|
32
|
+
for hexrec, market, code, date, cat, f1, f2, f3, f4 in CASES:
|
|
33
|
+
rec = bytes.fromhex(hexrec)
|
|
34
|
+
assert len(rec) == RECORD_SIZE
|
|
35
|
+
clear = decrypt_record(rec)
|
|
36
|
+
m, code_b, d, c, a1, a2, a3, a4 = struct.unpack('<B7sIBffff', clear)
|
|
37
|
+
assert m == market, (m, market)
|
|
38
|
+
assert code_b.rstrip(b'\x00').decode() == code
|
|
39
|
+
assert d == date, (d, date)
|
|
40
|
+
assert c == cat
|
|
41
|
+
assert abs(a1 - f1) < 0.01, (a1, f1)
|
|
42
|
+
assert abs(a2 - f2) < 1e-6 and abs(a3 - f3) < 1e-6 and abs(a4 - f4) < 1e-6
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_selection_helpers():
|
|
46
|
+
recs = [
|
|
47
|
+
{'market': 0, 'code': 'A', 'date': 20250101, 'category': 1, 'fenhong': 1.0,
|
|
48
|
+
'peigujia': 0, 'songzhuangu': 0, 'peigu': 0},
|
|
49
|
+
{'market': 0, 'code': 'A', 'date': 20240101, 'category': 1, 'fenhong': 0.5,
|
|
50
|
+
'peigujia': 0, 'songzhuangu': 0, 'peigu': 0},
|
|
51
|
+
{'market': 0, 'code': 'A', 'date': 20240601, 'category': 5, 'fenhong': 0,
|
|
52
|
+
'peigujia': 0, 'songzhuangu': 0, 'peigu': 0},
|
|
53
|
+
{'market': 1, 'code': 'B', 'date': 20250101, 'category': 1, 'fenhong': 2.0,
|
|
54
|
+
'peigujia': 0, 'songzhuangu': 0, 'peigu': 0},
|
|
55
|
+
]
|
|
56
|
+
ev = events_of(recs, 'A')
|
|
57
|
+
assert [r['date'] for r in ev] == [20240101, 20250101] # 升序 + 只取 category=1
|
|
58
|
+
assert len(events_of(recs, 'A', category=5)) == 1
|
|
59
|
+
m = to_map(recs)
|
|
60
|
+
assert set(m) == {'A', 'B'} and [r['date'] for r in m['A']] == [20240101, 20250101]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_bad_input_raises_valueerror():
|
|
64
|
+
"""空/过短数据要给可读的 ValueError,不能抛裸 struct.error(公开包的健壮性要求)"""
|
|
65
|
+
from tdxdata.gbbq import decrypt_records
|
|
66
|
+
for bad in (b'', b'\x00', b'\x00\x00\x00'):
|
|
67
|
+
try:
|
|
68
|
+
decrypt_records(bad)
|
|
69
|
+
except ValueError as e:
|
|
70
|
+
assert 'gbbq' in str(e)
|
|
71
|
+
except Exception as e:
|
|
72
|
+
raise AssertionError(
|
|
73
|
+
f'{len(bad)} 字节输入应抛 ValueError,实际 {type(e).__name__}: {e}') from e
|
|
74
|
+
else:
|
|
75
|
+
raise AssertionError(f'{len(bad)} 字节输入应抛 ValueError')
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_truncated_and_cache(tmp=None):
|
|
79
|
+
"""截断文件只解出实际条数;缓存命中结果一致;缓存损坏时回退完整解密"""
|
|
80
|
+
import struct
|
|
81
|
+
import tempfile
|
|
82
|
+
from pathlib import Path
|
|
83
|
+
from tdxdata.gbbq import read_gbbq
|
|
84
|
+
with tempfile.TemporaryDirectory() as td:
|
|
85
|
+
p = Path(td) / 'trunc'
|
|
86
|
+
p.write_bytes(struct.pack('<I', 100) + b'\x00' * 58) # 声明 100 条,实际 2 条
|
|
87
|
+
r1 = read_gbbq(p, cache_dir=td, use_cache=False)
|
|
88
|
+
assert len(r1) == 2, len(r1)
|
|
89
|
+
r2 = read_gbbq(p, cache_dir=td) # 写缓存
|
|
90
|
+
assert len(r2) == len(r1)
|
|
91
|
+
r3 = read_gbbq(p, cache_dir=td) # 命中缓存
|
|
92
|
+
assert len(r3) == len(r2)
|
|
93
|
+
# 把缓存写坏 → 必须回退完整解密而不是崩
|
|
94
|
+
for cf in Path(td).glob('gbbq_*.bin'):
|
|
95
|
+
cf.write_bytes(b'\x01\x02')
|
|
96
|
+
r4 = read_gbbq(p, cache_dir=td)
|
|
97
|
+
assert len(r4) == len(r1), f'缓存损坏后应回退,得到 {len(r4)}'
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_extract_members_errors():
|
|
101
|
+
"""官方包缺 gbbq / 不是 zip → 可读的 ValueError(不是裸 KeyError/BadZipFile)"""
|
|
102
|
+
import io
|
|
103
|
+
import zipfile
|
|
104
|
+
from tdxdata.gbbq import _extract_members
|
|
105
|
+
try:
|
|
106
|
+
_extract_members(b'not a zip')
|
|
107
|
+
raise AssertionError('非 zip 应抛 ValueError')
|
|
108
|
+
except ValueError as e:
|
|
109
|
+
assert 'zip' in str(e)
|
|
110
|
+
buf = io.BytesIO()
|
|
111
|
+
with zipfile.ZipFile(buf, 'w') as z:
|
|
112
|
+
z.writestr('other.txt', b'x')
|
|
113
|
+
try:
|
|
114
|
+
_extract_members(buf.getvalue())
|
|
115
|
+
raise AssertionError('缺 gbbq 应抛 ValueError')
|
|
116
|
+
except ValueError as e:
|
|
117
|
+
assert 'gbbq' in str(e)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_cache_pruning():
|
|
121
|
+
"""缓存按来源只留最近 3 份(权息表每版约 5MB,不清理会持续累积)"""
|
|
122
|
+
import struct
|
|
123
|
+
import tempfile
|
|
124
|
+
from pathlib import Path
|
|
125
|
+
from tdxdata.gbbq import read_gbbq
|
|
126
|
+
with tempfile.TemporaryDirectory() as td:
|
|
127
|
+
for n in range(5): # 造 5 个「不同版本」
|
|
128
|
+
f = Path(td) / f'v{n}'
|
|
129
|
+
f.write_bytes(struct.pack('<I', n + 1) + b'\x00' * ((n + 1) * 29))
|
|
130
|
+
read_gbbq(f, cache_dir=Path(td) / 'cache') # case 的 tag=n 文件名 → 每版一个 tag
|
|
131
|
+
caches = list((Path(td) / 'cache').glob('gbbq_*.bin'))
|
|
132
|
+
assert len(caches) <= 5, len(caches) # 不同 tag 各自保留即可
|
|
133
|
+
# 同一 tag 连写 5 版 → 只留 3
|
|
134
|
+
for k in range(5):
|
|
135
|
+
f2 = Path(td) / 'same'
|
|
136
|
+
f2.write_bytes(struct.pack('<I', k + 1) + b'\x00' * ((k + 1) * 29))
|
|
137
|
+
read_gbbq(f2, cache_dir=Path(td) / 'cache2')
|
|
138
|
+
same = list((Path(td) / 'cache2').glob('gbbq_same_*.bin'))
|
|
139
|
+
assert len(same) <= 3, f'同源缓存应只留 3 份,实际 {len(same)}'
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
if __name__ == '__main__':
|
|
143
|
+
test_url_and_size()
|
|
144
|
+
test_decrypt_record_fixtures()
|
|
145
|
+
test_selection_helpers()
|
|
146
|
+
test_bad_input_raises_valueerror()
|
|
147
|
+
test_truncated_and_cache()
|
|
148
|
+
test_extract_members_errors()
|
|
149
|
+
test_cache_pruning()
|
|
150
|
+
print('test_gbbq: 全部通过 ✅')
|
|
@@ -49,7 +49,7 @@ def test_parse_from_fixture():
|
|
|
49
49
|
assert abs(last['fenhong']) < 1e-9
|
|
50
50
|
assert last['category_name'] == '除权除息'
|
|
51
51
|
# 2026-06-08 是纯派现 3.12 元/10 股
|
|
52
|
-
d2026 =
|
|
52
|
+
d2026 = next(r for r in ev if r['date'] == 20260608)
|
|
53
53
|
assert abs(d2026['fenhong'] - 3.12) < 0.01
|
|
54
54
|
|
|
55
55
|
|
tdxdata-0.2.7/tests/test_gbbq.py
DELETED
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""gbbq(权息表)离线测试 —— 加密记录夹具取自 2026-11-12 官方 dbf 包(HTTP 源)
|
|
3
|
-
|
|
4
|
-
跑法:python tests/test_gbbq.py 或 pytest tests/test_gbbq.py
|
|
5
|
-
"""
|
|
6
|
-
import sys
|
|
7
|
-
from pathlib import Path
|
|
8
|
-
|
|
9
|
-
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
|
|
10
|
-
|
|
11
|
-
from tdxdata.gbbq import (GBBQ_URL, RECORD_SIZE, decrypt_record, # noqa: E402
|
|
12
|
-
events_of, to_map)
|
|
13
|
-
|
|
14
|
-
# 001225 三条 category=1 加密记录(29B hex)+ 期望解密结果
|
|
15
|
-
CASES = [
|
|
16
|
-
('1f8299cce874c2ea85569cc3454c912950940abb96412e270000000000',
|
|
17
|
-
0, '001225', 20230522, 1, 12.5, 0.0, 0.0, 0.0),
|
|
18
|
-
('1f8299cce874c2ea2c9288533983b59350940abb96412e270000000000',
|
|
19
|
-
0, '001225', 20240422, 1, 12.5, 0.0, 0.0, 0.0),
|
|
20
|
-
('1f8299cce874c2ea973d98914eeae91250940abb96412e270000000000',
|
|
21
|
-
0, '001225', 20250522, 1, 12.22, 0.0, 0.0, 0.0),
|
|
22
|
-
]
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
def test_url_and_size():
|
|
26
|
-
assert GBBQ_URL.startswith('http://www.tdx.com.cn/')
|
|
27
|
-
assert RECORD_SIZE == 29
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
def test_decrypt_record_fixtures():
|
|
31
|
-
import struct
|
|
32
|
-
for hexrec, market, code, date, cat, f1, f2, f3, f4 in CASES:
|
|
33
|
-
rec = bytes.fromhex(hexrec)
|
|
34
|
-
assert len(rec) == RECORD_SIZE
|
|
35
|
-
clear = decrypt_record(rec)
|
|
36
|
-
m, code_b, d, c, a1, a2, a3, a4 = struct.unpack('<B7sIBffff', clear)
|
|
37
|
-
assert m == market, (m, market)
|
|
38
|
-
assert code_b.rstrip(b'\x00').decode() == code
|
|
39
|
-
assert d == date, (d, date)
|
|
40
|
-
assert c == cat
|
|
41
|
-
assert abs(a1 - f1) < 0.01, (a1, f1)
|
|
42
|
-
assert abs(a2 - f2) < 1e-6 and abs(a3 - f3) < 1e-6 and abs(a4 - f4) < 1e-6
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
def test_selection_helpers():
|
|
46
|
-
recs = [
|
|
47
|
-
{'market': 0, 'code': 'A', 'date': 20250101, 'category': 1, 'fenhong': 1.0,
|
|
48
|
-
'peigujia': 0, 'songzhuangu': 0, 'peigu': 0},
|
|
49
|
-
{'market': 0, 'code': 'A', 'date': 20240101, 'category': 1, 'fenhong': 0.5,
|
|
50
|
-
'peigujia': 0, 'songzhuangu': 0, 'peigu': 0},
|
|
51
|
-
{'market': 0, 'code': 'A', 'date': 20240601, 'category': 5, 'fenhong': 0,
|
|
52
|
-
'peigujia': 0, 'songzhuangu': 0, 'peigu': 0},
|
|
53
|
-
{'market': 1, 'code': 'B', 'date': 20250101, 'category': 1, 'fenhong': 2.0,
|
|
54
|
-
'peigujia': 0, 'songzhuangu': 0, 'peigu': 0},
|
|
55
|
-
]
|
|
56
|
-
ev = events_of(recs, 'A')
|
|
57
|
-
assert [r['date'] for r in ev] == [20240101, 20250101] # 升序 + 只取 category=1
|
|
58
|
-
assert len(events_of(recs, 'A', category=5)) == 1
|
|
59
|
-
m = to_map(recs)
|
|
60
|
-
assert set(m) == {'A', 'B'} and [r['date'] for r in m['A']] == [20240101, 20250101]
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
if __name__ == '__main__':
|
|
64
|
-
test_url_and_size()
|
|
65
|
-
test_decrypt_record_fixtures()
|
|
66
|
-
test_selection_helpers()
|
|
67
|
-
print('test_gbbq: 全部通过 ✅')
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|