14 Commits
Author SHA1 Message Date
openbot 0618062e54 chore: bump version 0.6.3 2026-10-18 16:12:51 +08:00
openbot 9c97fea71b fix(pool): ExPool acquire backpressure + ex_pool_cap (fixes #1)
- acquire(): replace 3x0.05s fast-fail with Condition-based queueing
  (default acquire_timeout=30s); timeout error carries pool state
  (idle/total/servers/per_server_cap)
- api: expose ex_pool_cap (default 2, aligned with std/mac pool caps);
  single-server scenario no longer silently capped at 1 concurrent
2026-10-18 16:10:15 +08:00
openbot-coder 2d62d82b51 feat: 新增3台EX扩展行情服务器(connect.cfg官方扩展市场,handshake=login),全量复测30/36可用 2026-10-16 13:53:19 +08:00
openbot-coder 7e72f70eb2 chore: 离线探针复测写回 servers.json(2026-10-16,可达25→27,117.34.114.13/.14 复活) 2026-10-16 12:51:12 +08:00
openbotandopenbot-coder b2f899df49 fix(models): 修复美股分钟K线 datetime 时区拼接错位,还原为北京时间 (#2)
通达信 EX 通道对美股返回的分钟级 K线把两个时区拼进同一个五元组:日期分量是
美东交易日(zipday),时分分量是北京时间(tminutes)。直拼出的 datetime 会把
同一交易日的下午半场排到上午半场之前——单日 390 根首末颠倒,且全部落在同一个
北京自然日里,导致排序 / count 切片 / 日期区间二分与过滤 / 增量水位线全部不可用。

在 SecurityBar.__post_init__ 统一归一化为北京时间(凌晨段日期 +1 天,含月末与
年末进位),EX 的两条 K线命令路径(_bars_ex 的 0x23FF 与二分所依赖的 MAC 0x122E)
因此共用同一口径,不会出现"取数按一套时间、二分按另一套时间"的错位。

新增两个只读属性:trading_date(归属交易日;美股一个交易日横跨两个北京自然日,
按交易日聚合必须用它,不能用 datetime.date())与 is_us。

实测(安装 wheel 0.6.2,非源码树):10-06 ~ 10-12 五个完整交易日各 390 根、
严格单调,首根 open / 末根 close 与日线逐位相同,成交量差 <= 1;A股 / 港股零回归。

- 版本 0.6.1 -> 0.6.2(pyproject / __init__ / uv.lock)
- tests/test_protocol.py 新增 9 项回归测试(分界点 / 月末年末进位 / 390 根整日单调性 / MAC 路径),全量 191 passed
- CHANGELOG / README / SKILL.md / docs(faq、llms.txt、api/models)同步口径说明

遗留(本版未含,待决策):EX 分时对美股返回的 MinuteBar.hour 是未取模的连续分钟数
(实测可达 27,即次日 03:xx),且 MinuteBar 无日期分量可承载跨日信息。

Co-authored-by: openbot-coder <openbot-coder@users.noreply.github.com>
2026-10-13 16:47:57 +08:00
openbot-coder 8193d560da Revert "fix(models): 修复美股分钟K线 datetime 时区拼接错位,还原为北京时间"
This reverts commit 5408903a4c.
2026-10-13 16:42:41 +08:00
openbot-coder 5408903a4c fix(models): 修复美股分钟K线 datetime 时区拼接错位,还原为北京时间
通达信 EX 通道对美股返回的分钟级 K线把两个时区拼进同一个五元组:日期分量是
美东交易日(zipday),时分分量是北京时间(tminutes)。直拼出的 datetime 会把
同一交易日的下午半场排到上午半场之前——单日 390 根首末颠倒,且全部落在同一个
北京自然日里,导致排序 / count 切片 / 日期区间二分与过滤 / 增量水位线全部不可用。

在 SecurityBar.__post_init__ 统一归一化为北京时间(凌晨段日期 +1 天,含月末与
年末进位),EX 的两条 K线命令路径(_bars_ex 的 0x23FF 与二分所依赖的 MAC 0x122E)
因此共用同一口径,不会出现"取数按一套时间、二分按另一套时间"的错位。

新增两个只读属性:trading_date(归属交易日;美股一个交易日横跨两个北京自然日,
按交易日聚合必须用它,不能用 datetime.date())与 is_us。

实测(安装 wheel 0.6.2,非源码树):10-06 ~ 10-12 五个完整交易日各 390 根、
严格单调,首根 open / 末根 close 与日线逐位相同,成交量差 <= 1;A股 / 港股零回归。

- 版本 0.6.1 -> 0.6.2(pyproject / __init__ / uv.lock)
- tests/test_protocol.py 新增 9 项回归测试(分界点 / 月末年末进位 / 390 根整日单调性 / MAC 路径),全量 191 passed
- CHANGELOG / README / SKILL.md / docs(faq、llms.txt、api/models)同步口径说明

遗留(本版未含,待决策):EX 分时对美股返回的 MinuteBar.hour 是未取模的连续分钟数
(实测可达 27,即次日 03:xx),且 MinuteBar 无日期分量可承载跨日信息。
2026-10-13 15:10:22 +08:00
openbot-coder 8951ec2678 fix(api,codec): 修复 BUG-1 分时采样走错命令 + BUG-2 财务文件名纠正
BUG-1: A股 get_minutes(sampling=True) 原走 MacChartSamplingCmd(0x254D)
这是 EX 协议命令,7709 主机无响应(3×8s 超时≈24s)。
修复:A股采样由 MacTickChartCmd(0x122D) 分时数据派生,
EX 市场(hk)仍走 0x254D。4 个 A股 场景均<0.1s 返回 240 点。

BUG-2: tdxfin/gpcw.txt 索引声明 gpcwYYYYMMDD.zip,
但服务器实际只有 tdxfin/gpcwYYYYMMDD.dat(未压缩,~13MB),
.zip 请求返回 0-1 字节空壳。
修复:_fetch_financial_dat() 自动候选回退
tdxfin/*.zip → tdxfin/*.dat → 原始文件名,加 looks_like_gpcw_dat 校验。
实测 gpcw20260630.zip→5568 条,gpcw20260331.zip→5547 条。

新增 codec/financial.py: looks_like_gpcw_dat, extract_gpcw_dat(含 zip/未压缩双通道)。
同步更新 README/API_REFERENCE/docs/cli/cookbook/CHANGELOG 共 6 处文档。
tests: +18(总 182),ruff 无新增 findings,MkDocs strict 通过。
2026-09-21 20:47:48 +08:00
openbot-coder b78d0fabf5 docs: 修正 servers.json 清理后遗留的过时描述(含一处事实反转)
servers.json 复测后三池台数已变(standard 9 / mac 22 / ex 4),但 README 与部分文档
仍停留在旧口径,且有一处因果结论被实测推翻:

- README.md
  - 测试用例数 127 → 164(并补「当日测速缓存」到用例分组说明)
  - 「已知限制」补测速缓存详情的文档站链接
- docs/internals/routing.md
  - 三池台数:标准池「数十台」→ 9 台、MAC 池「数台」→ 22 台(EX 池 4 台不变),
    并标注为 2026-09-21 离线探针实测可达数、实际以当日测速缓存为准
  - **事实反转修正**:原文「MAC 池远小于标准池,这解释了逐笔/分时并发弱于日线」
    与实测不符(mac 22 > standard 9)→ 已改为陈述实测台数,
    并指出两通道单台连接上限默认相同(均 4)
- docs/internals/cache-pool.md
  - 「为什么 MAC 池更小」小节前提已不成立 → 改为「MAC 通道的单台连接上限」,
    保留 mac_pool_cap=4 的可用信息,删除错误因果
- docs/refactor-audit.md
  - 历史快照的 127 passed 标注「审查当时」,避免误读为当前基线

验证:scripts/check_docs.py exit 0;mkdocs build --strict exit 0(无告警)
2026-09-21 19:42:06 +08:00
openbot-coder d422385877 chore(servers): 离线探针复测重写 servers.json,并给探针工具补 --discover
servers.json(真数据复测 2026-09-21,两轮零漂移)
- 剔除历史脏记录 s1;刷新 status/latency/checked_at/checked_date/fast_pool
- 可达 25/33:standard 9 台、mac 22 台、ex 4 台(旧文件 mac 只标了 10 台)
- 关键发现:14 台服务器 0x010C 标准 K 线已成空响应(回 2 字节空壳),
  但同端口同主机的 0x122E MAC 帧正常 → 据实测把 protocols 由 standard/mac 收窄为 mac
- 8 台不可达:华林 4 台(218.106.92.182/183, 220.178.55.71/86)、159.75.55.232、
  117.34.114.13/14/30 → status=fail
- 117.34.114.17 实测 standard+mac 均通(此前只申报 standard)

server_probe.py
- 新增 --discover:三种协议全测并据实修正 protocols(顺带剔除 ip 非法记录)
- 失败重试一次再判定不支持(单次抖动会误删协议,且收窄后不会自动恢复)
- EX 握手模式申报错时换另一种再试(login <=> setup)
- 补写 checked_date / fast_pool / 顶层 version·note,入池规则与运行时缓存一致

验证:164 passed;servers.json 跑测前后 sha 不变;check_docs.py + mkdocs --strict 通过
2026-09-21 19:05:32 +08:00
openbot-coder 7e830c7579 docs: 补齐测速缓存相关文档,并修掉 0.6.0 遗留的过时描述
上一提交只补了 getting-started / routing / llms.txt / SKILL.md 四处,本轮把其余
教程类页面与接口清单补齐,并顺手修正 v0.6.0 统一接口改造后遗留的过时说明。

补齐(当日测速缓存):

- README「已知限制」:说明当日首次启动会自动后台测速并缓存
- FAQ 新增「启动时会变慢吗?会不会在后台偷偷联网?」:无感保证 + 三个环境变量开关
- FAQ「连不上服务器怎么办」:加入"删当日测速缓存 / 环境变量指定主机"两条前置排查
- API_REFERENCE 四、辅助模块:config 补全当日测速相关函数与优先级链说明,
  新增 pytdxdata.pool.probe_cache 一节(ProbeCache / schedule_probe / get_probe_cache)
- internals/architecture.md 目录树:config.py、probe_cache.py 的职责注释更新
- internals/cache-pool.md「下一步」:补「服务器是怎么选出来的」交叉链接

修正(v0.6.0 遗留过时描述):

- FAQ / api/enums.md:删掉「所有接口的第一个参数都是 market」——统一接口已改为字符串标的
- FAQ / cookbook:`*_batch` 已并入 `get_bars`(多标的),不再作为批量入口
- FAQ / getting-started「自建服务器清单」:`standard_servers` 实际是 Sequence[str]
  而非 (host, port) 元组(端口由统一的 port= 指定);原示例照抄会取到错的主机名
  (已实测:字符串写法正确,元组写法不会被解析)

校验:check_docs.py exit 0;mkdocs build --strict 无告警;新增交叉链接
#当日自动测速无感 / #daily-probe 均正确渲染且目标锚点存在;全量 164 项通过;
src/pytdxdata/servers.json 跑测前后逐字节不变。
2026-09-21 18:26:37 +08:00
openbot-coder c7c6c70333 chore(release): 版本号升至 0.6.1
在 v0.6.0 基线上发布当日测速缓存重写(见上一提交)。

版本号四处对齐:pyproject.toml / src/pytdxdata/__init__.py / uv.lock / CHANGELOG.md。
uv lock --check 通过(lockfile 与 pyproject 一致)。

同时修正 0.6.0 全接口回归测试与本次改动的集成冲突:
tests/test_all_interfaces.py 的 td fixture 原先替身 pool.pool.get_probe_cache,
而本次已把池内探针入口改为 pool.pool.schedule_probe,导致 fixture setup 抛
AttributeError(17 个用例 ERROR + 1 个 FAILED)。改为替身 schedule_probe 并返回 None
(与"无事件循环时不排期"的真实语义一致),单测既不再因属性缺失报错,也不会真的发起后台测速。

全量 164 项通过;mkdocs build --strict 通过;src/pytdxdata/servers.json 跑测前后逐字节不变。
2026-09-21 18:05:11 +08:00
openbot-coder 18d9e9a006 fix(pool): 重写当日测速缓存:全量候选 + 用户级缓存 + 真实数据探针
原实现在 v0.5.0 已随包发布,但有三处会"静默失效"的缺陷,等于没真正生效:

- 候选集自指:连接池把自己已过滤后的成员当探针输入,实测只重测了 9 台,
  另外 20+ 台候选(含快节点)永远测不到。改为由 probe_cache 自行枚举
  全量候选(包内清单 ∪ 代码常量 ∪ env),不再接受调用方传入的"当前池成员"。
- 写回安装目录:结果写回 src/pytdxdata/servers.json,容器/系统级安装下只读会
  静默失败、多用户共用一个安装会互相覆盖,且污染随包分发的数据。改为写入
  用户级缓存目录(Win %LOCALAPPDATA% / macOS ~/Library/Caches / Linux $XDG_CACHE_HOME),
  运行时绝不再改写包内清单。
- 探测太弱:只做握手,测不出「握手正常但 K 线空响应」的坏节点。改为发真实业务
  命令并要求返回非空(标准 GetSecurityBarsCmd / MAC MacKlineCmd / EX GetExInstrumentBarsCmd),
  EX 池(4 台,7727)也一并纳入。

无感保证:后台 task 不阻塞 start()、日志全 debug 级、绝不抛异常(取消除外)、
原子写 tmp + os.replace、进程内单例 + asyncio.Lock 单飞;全不可达时不写缓存
(否则"今天全挂"会被缓存一整天)。close() 会取消并 await 后台探针,
避免解释器退出时报 "Task was destroyed but it is pending"。

新增环境变量 PYPYTDX_DATA_CACHE_DIR(覆盖缓存目录)、
PYPYTDX_DATA_DISABLE_PROBE=1(关闭测速)。新增 tests/test_probe_cache.py(37 项)。
2026-09-21 17:54:29 +08:00
openbot-coder 3e0beb27a6 release: v0.6.0(统一对外接口重构)
按「数据类型」合并同类查询接口:一个数据类型 = 一个方法,跨市场自动选路。

- 28 个统一接口(get_universe/get_quotes/get_bars/get_indicators/get_ticks/
  get_minutes/get_f10/get_file/get_boards/get_board_of/get_snapshot 等),
  标的统一字符串写法(sz000001 / hk00700 / usAAPL / cffex:IFL0);
  同名旧方法不再兼容 (market, code) 元组。
- 旧 51 个按通道/市场分裂的接口:33 个保留为 deprecated 别名(1.0 移除),
  18 个同名升级为统一接口。公开方法共 63 个。
- 新增库层标的解析 pytdxdata.symbols;数据模型追加 symbol/name/fields 兜底字段。
- 修复:分页器连接泄漏、日期区间 K线返回 0 条(偏移方向探测)、池子全冷却死等。
- 文档/README/SKILL/llms.txt 全量同步;新增 docs/refactor-audit.md 审查报告。
- 测试 127 个用例全绿(含 tests/test_all_interfaces.py 全 63 方法回归)。
2026-09-17 11:34:52 +08:00
45 changed files with 5052 additions and 1664 deletions

No files matched your search

+168 -1
View File
@@ -2,6 +2,172 @@
本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/)。 本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
## [0.6.3] - 2026-10-18
- fix(pool): ExPool acquire 背压等待(Condition 排队,默认 30s 超时)替代 3x0.05s 快速失败;超时异常带池状态
- feat(api): 新增 ex_pool_cap 参数(默认 2),单 EX 服务器场景不再静默退化为 1 并发(fixes #1)
## [0.6.2] - 2026-10-13
### 修复
- **美股分钟级 K 线的 `datetime` 全部错位**(`get_bars("usAAPL", KlinePeriod.MIN_1)`)。
通达信 EX 通道返回的美股分钟线时间戳,把**两个时区拼进了同一个五元组**:日期分量是
**美东交易日**(协议里的 `zipday`),时分分量却是**北京时间**(`tminutes`)。直拼出的
`datetime` 会把同一交易日的**下午半场排到上午半场之前**——单日 390 根不仅首末颠倒,
而且全部落在同一个北京自然日里。于是任何依赖 `datetime` 的行为都是错的:排序、
`count` 切片("取最新 N 根")、日期区间二分与过滤、增量更新水位线。
| 观测项 | 修复前 | 修复后 |
|---|---|---|
| 单日 390 根的日期分布 | **全部**落在 10-12(hour 0~23 混在一起) | 10-12 的 21:31~23:59(149 根)+ 10-13 的 00:00~04:00(241 根) |
| 时间轴 | 上午半场被排到下午半场**之前** | 严格单调递增 |
| `count=30` 是否取到真正最新的 30 根 | 否(拿到上一交易日的 23:30~23:59) | 是(当日收盘段 03:31~04:00) |
| 每组首根 `open` / 末根 `close` 对日线 | 对不上 | **逐位相同**(10-07/08/09/12 四个交易日实测) |
现在 `SecurityBar.datetime` **统一为北京时间**:美股凌晨段(北京 hour < 12)的日期
自动 +1 天(含月末 / 年末进位)。A股 / 港股 / 期货原始即为北京时间,**零行为变化**。
新增两个只读属性:
| 属性 | 用途 |
|---|---|
| `SecurityBar.trading_date` | 该 bar 归属的交易日 `YYYY-MM-DD`。美股一个交易日横跨两个北京自然日,**按交易日聚合(分钟线合成日线、日内统计)必须用它,不能用 `datetime.date()`** |
| `SecurityBar.is_us` | 是否美股(EX 通道 `US_STOCK`) |
归一化在 `SecurityBar.__post_init__` 中实现,因此 **EX 的两条 K 线命令路径**
(`_bars_ex` 的 0x23FF 与日期区间二分所依赖的 MAC 0x122E)自动共用同一份口径,
不会出现"取数按一套时间、二分按另一套时间"的错位。
### 说明
- 分钟线缓存 TTL 为 **60 秒**,升级后旧缓存最多残留 1 分钟即自然失效,**无需手动清理**;
日线(`period >= DAY`)不受本缺陷影响。
- 本版只修 K 线。**同日发现的同类问题未包含在内**:EX 分时(`get_minutes`)对美股返回的
`MinuteBar.hour` 是**未取模的连续分钟数**(实测可达 27,即次日 03:xx),且 `MinuteBar`
无日期分量可承载跨日信息——修法涉及"是否新增字段 / 日期如何归属"的取舍,留待下一版决策。
- 新增 9 项针对性回归测试(分界点、月末与年末进位、390 根整日单调性、MAC 路径同样归一化)。
## [0.6.1] - 2026-09-21
### 变更
- **重写「当日首次启动测速缓存」,改为对用户完全无感**。原实现在 v0.5.0 已随包发布,但存在
三个会让它**静默失效**的缺陷,本次一并修正:
| 缺陷 | 原实现 | 现在 |
|---|---|---|
| 候选集自指 | 连接池只把自己**已过滤后的成员**交给探针 → 只重测了 9 台,另外 20+ 台候选(含快节点)永远测不到 | 探针内部取**全部候选**(包内清单 ∪ 代码常量 ∪ env) |
| 写回安装目录 | 结果写回 `src/pytdxdata/servers.json` → 容器 / 系统级安装只读、多用户互相覆盖 | 改写入**用户级缓存目录**,包内清单运行时**绝不被改写** |
| 探测太弱 | 只做握手(`TdxConnection.test`),测不出「握手正常但 K 线空响应」的坏节点 | 发**真实业务命令**并要求返回非空(标准 / MAC / EX 各一) |
| EX 池漏测 | EX 的 4 台从未被探测 | EX 一并纳入(7727 + 各自握手模式) |
- 测速结果按**实测延迟升序**被 `config.get_standard_hosts()` 等采用;当天已有缓存则**不再刷新**。
后台执行,不阻塞 `start()`、不打印、失败静默降级。
- 本版基于 **0.6.0 的统一对外接口**构建(`get_bars` + 字符串标的);同时把 0.6.0
全接口回归测试里对旧探针入口(`pool.get_probe_cache`)的替身改为新入口(`pool.schedule_probe`),
保证单测不触发真实网络测速。
### 修复
- **A股分时缩略采样 100% 失败**(`get_minutes(sampling=True)` / `get_chart_sampling()`):
旧实现走 `MacChartSamplingCmd`(**0x254D**),但该 opcode 属于 **EX 协议**,7709 标准 /
MAC 主机对它一律不响应——实测 3 台主机各 10s 超时,叠加连接池 3 次重试约 24s 才抛错。
现改为**由分时(0x122D)数据派生**价格点(分时本身就是 240 点,语义一致),
实测 4 个 A股 场景均在 0.1s 内返回 240 点;EX 通道仍用 0x254D(84 点)。
- **历史专业财报整条链路不可用**(`get_financial_records_parsed()`):
`tdxfin/gpcw.txt` 索引里写的是裸 `gpcwYYYYMMDD.zip`,而服务器**实际只提供未压缩的**
`tdxfin/gpcwYYYYMMDD.dat`。旧实现把索引名直接丢给 `zipfile` → 必然 `BadZipFile`;
废弃别名 `get_financial_records()` 更危险,会**静默返回 0~1 字节空壳**而不报错。
现按候选名(`tdxfin/*.zip` → `tdxfin/*.dat` → 原名)逐个尝试并校验数据形态,
zip 与未压缩 dat 都支持。实测 `gpcw20260630.zip` → **5568 条**、
`gpcw20260331.zip` → **5547 条**(样本 000001,584 个 float 字段),
别名返回 **13,068,116 字节**真实数据;尚未生成的占位条目
(如 `gpcw20260930.zip`,filesize=164)优雅返回空列表而非报错。
### 新增
- `codec.financial` 新增 `looks_like_gpcw_dat()` / `extract_gpcw_dat()`:
财报字节的形态判定与「zip / 未压缩 dat」统一提取(纯标准库,可脱网单测)
- 环境变量 `PYPYTDX_DATA_CACHE_DIR`(覆盖测速缓存目录)、
`PYPYTDX_DATA_DISABLE_PROBE`(关闭测速,CI / 测试用)
- `tests/test_probe_cache.py`(37 项):当日缓存不刷新、跨日重测、
原子写入且不留 tmp、**不改写包内 `servers.json`(逐字节校验)**、
单飞并发、非法主机过滤、`DISABLE_PROBE`、池 `start()` 不阻塞 / `close()` 取消后台探针
### 文档
- [安装与配置](https://openbot-coder.github.io/pytdxdata/getting-started/#当日自动测速无感):
新增「当日自动测速(无感)」小节——缓存路径、优先级链、环境变量一览
- [通道与数据源](https://openbot-coder.github.io/pytdxdata/internals/routing/#daily-probe):
新增「运行时:当日测速缓存」小节,逐条说明必须踩对的实现要点与反例
## [0.6.0] - 2026-09-16
### 新增
- **统一对外接口**:一个数据类型 = 一个方法,跨市场自动选路。
标的统用字符串写法(`sz000001` / `hk00700` / `usAAPL` / `cffex:IFL0`),
A股/港股/美股/期货/期权混合查询一次返回。旧的 51 个按通道/市场分裂的接口中,
33 个保留为 deprecated 别名(运行时发出 `DeprecationWarning`,**1.0 移除**),
另 18 个(`get_quotes` / `get_xdxr` / `get_finance` / `get_auction` / `get_capital_flow` /
`get_market_stat` / `get_unusual` / `get_server_info` / `get_kline_offset` /
`get_board_members` / `get_board_summary` / `get_board_ranking` / `get_board_change_ranking` /
`get_block_parsed` / `get_industry_map` / `get_financial_file_infos` /
`get_financial_records_parsed` / `get_price_limits`)同名升级为统一接口。
| 数据类型 | 新接口 | 合并掉的旧接口 |
|----------|--------|----------------|
| 标的清单 | `get_universe(market)` | get_security_count + get_security_list + get_security_list_all + get_goods_count + get_goods_list |
| 报价 | `get_quotes(symbols, *, fields)` | get_quotes + get_stock_quotes + get_goods_quotes + get_goods_quotes_list |
| K线 | `get_bars(symbols, period, ...)` | get_kline + get_index_kline + get_kline_batch + get_kline_since |
| 指标 | `get_indicators(symbols, indicators, ...)` | get_stock_kline_with_indicators |
| 逐笔 | `get_ticks(symbols, *, date)` | get_transactions + get_goods_transaction + get_goods_transaction_all |
| 分时 | `get_minutes(symbols, *, date, sampling)` | get_minute + get_minute_batch + get_chart_sampling + get_goods_chart_sampling + get_goods_tick_chart |
| F10 | `get_f10(symbol, section)` | get_company_info_category + get_company_info_content |
| 文件 | `get_file(name)` | get_block_info + get_report_file + get_file_meta + download_file |
| 财务文件 | `get_financial_file_infos()` / `get_financial_records_parsed(fn)` | get_financial_file_list + get_financial_records |
| 板块列表 | `get_boards(kind)` | get_board_list |
| 板块成员 | `get_board_members(board)` → 归一 `SecurityQuote` | get_board_members + get_stock_quotes_list(分类报价) |
| 个股板块 | `get_board_of(symbols)` | get_belong_board |
| 快照 | `get_snapshot(symbols)` | get_symbol_info |
> `TdxData` 公开方法 63 个 = **28 个统一接口** + 33 个 deprecated 别名 + `start`/`close`。
> 统一接口一律只接受字符串标的;同名旧方法不再兼容 `(market, code)` 元组写法。
- **库层标的解析** `pytdxdata.symbols`(原仅 CLI 内有):`parse_symbol` / `format_symbol` /
`parse_symbols` / `market_targets` / `is_cn_index`;裸 6 位数字视为沪市指数。
- **归一数据模型**:`SecurityBar` / `SecurityQuote` / `TransactionRecord` / `MinuteBar` /
`SecurityInfo` 等均新增 `symbol`(规范化标的串)/ `name` / `fields`(原始字段位兜底),
老构造写法不受影响(新字段有默认值)。
- `IndicatorSet` dataclass(`get_indicators` 返回单元:`bars + indicators` 组合)。
- `CacheKey.quote_key(..., tag=)` 支持按取数口径(标准五档 / MAC 字段位)隔离缓存。
### 修复
- **分页器连接泄漏**:`Paginator._worker` 换连接后旧连接不释放、池子被耗干
(`_Slot` 包装 + 归还时按槽释放)。
- **日期区间 K线返回 0 条**:标准通道 `start` 偏移方向是递减(0=最新),旧的二分
假设递增。改为运行时探测方向再二分(`_offset_descending` / `_bisect_offset`)。
- **池子全冷却死等**:所有服务器进冷却后 `acquire` 排队 30s 超时。
补 `ignore_cooldown=True` 兜底,避免无人持有连接时永久等待。
- `HealthEngine.COOLDOWN_SECONDS` 保持 120s(旧的 FAIL_STREAK_COOLDOWN=1 意味着
任意一次通信失败即冷却,实测下正常服务器不应被冷却,保留该行为)。
### 变更
- **`docs/api/index.md` 接口总览**重新组织:统一接口(推荐)优先于旧接口列表。
- `scripts/check_docs.py`:`docs/api/index.md` 从 `MUST_LIST_ALL` 移到
`MUST_NOT_BE_STALE`(只列推荐的统一接口,旧方法不强制出现在总览页)。
- CLI `tdx quotes` 改为统一 `td.get_quotes(symbols)`(跨市场混合报价)。
- CLI `tdx kline` 改为统一 `td.get_bars(sym, period)`。
- 测试 127 个用例全绿(新增 codec mock `get_file` 适配 + check_docs 新方法列表 +
`tests/test_all_interfaces.py` 全接口回归:mock 连接逐个调用全部 63 个公开方法,
并以「覆盖哨兵」断言无方法遗漏)。
## [0.5.0] - 2026-09-15 ## [0.5.0] - 2026-09-15
### 新增 ### 新增
@@ -97,7 +263,8 @@
- 初始版本:动态连接池 + 双层 TTL 缓存 + 3 连接并发分页 + 双通道(标准 / MAC)+ 扩展市场(港股 / 美股 / 期货 / 期权) - 初始版本:动态连接池 + 双层 TTL 缓存 + 3 连接并发分页 + 双通道(标准 / MAC)+ 扩展市场(港股 / 美股 / 期货 / 期权)
[Unreleased]: https://github.com/openbot-coder/pytdxdata/compare/v0.5.0...HEAD [Unreleased]: https://github.com/openbot-coder/pytdxdata/compare/v0.6.0...HEAD
[0.6.0]: https://github.com/openbot-coder/pytdxdata/compare/v0.5.0...v0.6.0
[0.5.0]: https://github.com/openbot-coder/pytdxdata/compare/v0.4.0...v0.5.0 [0.5.0]: https://github.com/openbot-coder/pytdxdata/compare/v0.4.0...v0.5.0
[0.4.0]: https://github.com/openbot-coder/pytdxdata/compare/v0.3.2...v0.4.0 [0.4.0]: https://github.com/openbot-coder/pytdxdata/compare/v0.3.2...v0.4.0
[0.3.2]: https://github.com/openbot-coder/pytdxdata/compare/v0.3.1...v0.3.2 [0.3.2]: https://github.com/openbot-coder/pytdxdata/compare/v0.3.1...v0.3.2
+17 -11
View File
@@ -29,19 +29,19 @@ pip install "pytdxdata[uvloop]"
```python ```python
import asyncio import asyncio
from pytdxdata import TdxData from pytdxdata import TdxData
from pytdxdata.models import Market, KlinePeriod, Adjust from pytdxdata.models import KlinePeriod, Adjust
async def main(): async def main():
async with TdxData() as td: # 自动建连接池 + 缓存 async with TdxData() as td: # 自动建连接池 + 缓存
# 日K线(count 超过单页大小会自动多连接并发分页) # 日K线(count 超过单页大小会自动多连接并发分页)
bars = await td.get_kline(Market.SH, "600000", KlinePeriod.DAY, count=240) bars = await td.get_bars(["sz000001"], KlinePeriod.DAY, count=240)
# 前复权(自动走 MAC 通道) # 前复权(自动走 MAC 通道)
qfq = await td.get_kline(Market.SZ, "300308", KlinePeriod.DAY, qfq = await td.get_bars(["sz300308"], KlinePeriod.DAY,
count=500, adjust=Adjust.QFQ) count=500, adjust=Adjust.QFQ)
# 五档报价(传 (market, code) 元组列表,>80 只自动切批) # 跨市场报价:A股+港股+美股一次拿全
quotes = await td.get_quotes([(Market.SH, "600000"), (Market.SZ, "000001")]) quotes = await td.get_quotes(["sh600000", "hk00700", "usAAPL"])
# 逐笔成交(MAC 通道,支持历史日期) # 逐笔成交(MAC 通道,支持历史日期)
ticks = await td.get_transactions(Market.SZ, "000001", date=20260811) ticks = await td.get_ticks(["sz000001"], date=20260811)
print(bars[-1].close, quotes[0].price, len(ticks)) print(bars[-1].close, quotes[0].price, len(ticks))
asyncio.run(main()) asyncio.run(main())
@@ -65,7 +65,7 @@ df = pd.DataFrame([asdict(b) for b in bars])
| 🔀 双通道整合 | 标准通道(经典行情)+ MAC 通道(逐笔 / 复权 / 1 分钟 K 线),按命令自动选路 | | 🔀 双通道整合 | 标准通道(经典行情)+ MAC 通道(逐笔 / 复权 / 1 分钟 K 线),按命令自动选路 |
| 📦 零重型依赖 | 纯 asyncio + stdlib(socket / zlib / struct / sqlite3) | | 📦 零重型依赖 | 纯 asyncio + stdlib(socket / zlib / struct / sqlite3) |
| 📊 全市场覆盖 | A股、港股、美股、期货、期权(46 个扩展市场) | | 📊 全市场覆盖 | A股、港股、美股、期货、期权(46 个扩展市场) |
| 📄 服务器文件解析 | 板块 `block_*.dat` / 行业 `tdxhy.cfg` / 财报 `gpcw*.zip` **下载即解析**成 dataclass | | 📄 服务器文件解析 | 板块 `block_*.dat` / 行业 `tdxhy.cfg` / 财报 `gpcw*` **下载即解析**成 dataclass(索引名与服务器实际文件名不一致时自动纠正) |
| 🤖 AI 助手友好 | 内置 [`SKILL.md`](https://github.com/openbot-coder/pytdxdata/blob/main/SKILL.md) 与 [`llms.txt`](https://openbot-coder.github.io/pytdxdata/llms.txt) | | 🤖 AI 助手友好 | 内置 [`SKILL.md`](https://github.com/openbot-coder/pytdxdata/blob/main/SKILL.md) 与 [`llms.txt`](https://openbot-coder.github.io/pytdxdata/llms.txt) |
## 文档导航 ## 文档导航
@@ -78,7 +78,8 @@ df = pd.DataFrame([asdict(b) for b in bars])
| 搞清枚举该填几 | [枚举速查](https://openbot-coder.github.io/pytdxdata/api/enums/) | | 搞清枚举该填几 | [枚举速查](https://openbot-coder.github.io/pytdxdata/api/enums/) |
| 看协议二进制格式、三池路由、缓存策略 | [深入原理](https://openbot-coder.github.io/pytdxdata/internals/architecture/) | | 看协议二进制格式、三池路由、缓存策略 | [深入原理](https://openbot-coder.github.io/pytdxdata/internals/architecture/) |
| 用命令行 | [命令行工具](https://openbot-coder.github.io/pytdxdata/cli/) | | 用命令行 | [命令行工具](https://openbot-coder.github.io/pytdxdata/cli/) |
| 完整接口清单(51 个数据方法) | [`docs/API_REFERENCE.md`](https://openbot-coder.github.io/pytdxdata/API_REFERENCE/) | | 完整接口清单(28 个统一方法 + 33 个废弃别名) | [`docs/API_REFERENCE.md`](https://openbot-coder.github.io/pytdxdata/API_REFERENCE/) |
| 重构审查(数据一致性 / 遗漏对账) | [接口重构审查](https://openbot-coder.github.io/pytdxdata/refactor-audit/) |
| 版本变更 | [`CHANGELOG.md`](https://github.com/openbot-coder/pytdxdata/blob/main/CHANGELOG.md) | | 版本变更 | [`CHANGELOG.md`](https://github.com/openbot-coder/pytdxdata/blob/main/CHANGELOG.md) |
> 本 README 只做**入口层**。深度内容一律在文档站,避免两处维护造成漂移。 > 本 README 只做**入口层**。深度内容一律在文档站,避免两处维护造成漂移。
@@ -86,7 +87,7 @@ df = pd.DataFrame([asdict(b) for b in bars])
## 给 AI 助手用 ## 给 AI 助手用
仓库根的 [`SKILL.md`](https://github.com/openbot-coder/pytdxdata/blob/main/SKILL.md) 是一份可直接加载的技能:三条必守约定、`KlinePeriod` 等枚举取值表、 仓库根的 [`SKILL.md`](https://github.com/openbot-coder/pytdxdata/blob/main/SKILL.md) 是一份可直接加载的技能:三条必守约定、`KlinePeriod` 等枚举取值表、
「想做什么 → 用哪个方法」决策表、以及 9 条真实陷阱。AI 编程助手读完就能一次写对,不必翻源码。 「想做什么 → 用哪个方法」决策表、以及 11 条真实陷阱。AI 编程助手读完就能一次写对,不必翻源码。
```bash ```bash
# 丢进你所用 AI 助手的 skills 目录即可 # 丢进你所用 AI 助手的 skills 目录即可
@@ -103,7 +104,7 @@ curl -o ~/.workbuddy/skills/pytdxdata/SKILL.md --create-dirs \
```bash ```bash
uv sync # 建虚拟环境 + 注册 tdx 命令 uv sync # 建虚拟环境 + 注册 tdx 命令
uv run pytest tests/ # 109 个测试用例(协议 / 池 / 缓存 / 分页 / API / 文件解析 / CLI / 文档漂移) uv run pytest tests/ # 191 个测试用例(协议 / 池 / 缓存 / 分页 / 全接口回归 / 文件解析 / CLI / 文档漂移 / 当日测速缓存)
uv sync --group docs # 文档站依赖(mkdocs-material + mkdocstrings) uv sync --group docs # 文档站依赖(mkdocs-material + mkdocstrings)
uv run mkdocs serve # 本地预览文档站 uv run mkdocs serve # 本地预览文档站
``` ```
@@ -113,7 +114,12 @@ uv run mkdocs serve # 本地预览文档站
- 行情来自通达信公开服务器,**15 分钟延时**;需实时数据请使用券商行情 - 行情来自通达信公开服务器,**15 分钟延时**;需实时数据请使用券商行情
- 标准通道 K 线 `count < 100` 部分服务器返回空 → 分页器已强制 `min_page=100` 规避 - 标准通道 K 线 `count < 100` 部分服务器返回空 → 分页器已强制 `min_page=100` 规避
- 港股 / 美股期权在通达信协议内无数据 - 港股 / 美股期权在通达信协议内无数据
- 服务器可用性随时间变化,可用 `python -m pytdxdata.server_probe` 重新探测 - **K 线时间戳统一为北京时间**(v0.6.2 起)。美股原始报文把「美东交易日日期」与「北京时间时分」
拼在一起,库已自动归一化,`bar.datetime` 可直接排序 / 过滤;但**美股一个交易日横跨两个北京
自然日**,按交易日聚合请用 `SecurityBar.trading_date`,不要用 `datetime.date()`
- 服务器可用性随时间变化。**当日首次启动会自动在后台测速并缓存**(对调用方无感,当天不再重测);
也可用 `python -m pytdxdata.server_probe` 离线重生成随包清单。
缓存路径与三个开关见 [安装与配置 → 当日自动测速](https://openbot-coder.github.io/pytdxdata/getting-started/#当日自动测速无感)
## 免责声明 ## 免责声明
+52 -44
View File
@@ -18,20 +18,24 @@ description: 用 pytdxdata 拉取通达信行情数据——A股(沪/深/北)、
from pytdxdata import TdxData from pytdxdata import TdxData
async with TdxData() as td: # 自动 start(探测服务器 + 预建连接 + 建缓存) async with TdxData() as td: # 自动 start(探测服务器 + 预建连接 + 建缓存)
bars = await td.get_kline(...) bars = await td.get_bars(["sz000001"], KlinePeriod.DAY, count=240)
# 退出即 close # 退出即 close
``` ```
不要直接 `await TdxData().get_kline(...)`——没 `start()` 就没有连接池。 不要直接 `await TdxData().get_bars(...)`——没 `start()` 就没有连接池。
**2. `market` 传的是整数枚举值,不是字符串** **2. 标的写法是字符串,不是元组**
这是最高频的错误来源。**不要传 `"sh"` / `"SH"` / `"1"`**,要用枚举(它就是 `IntEnum`,所以传 `1` 也能跑,但可读性差): 这是 v0.6 的最重要变化。**不要传 `(Market.SH, "600000")` 元组**,用字符串:
```python ```python
from pytdxdata.models import Market, KlinePeriod, Adjust # 旧写法(deprecated,会发出 DeprecationWarning):
bars = await td.get_kline(Market.SH, "600000", KlinePeriod.DAY, count=240)
await td.get_kline(Market.SH, "600000", KlinePeriod.DAY, count=240) # 新写法(推荐):
bars = await td.get_bars(["sz000001"], KlinePeriod.DAY, count=240)
# 港股/美股/期货也一样:
bars = await td.get_bars(["hk00700", "usAAPL", "cffex:IFL0"], KlinePeriod.DAY, count=240)
``` ```
**3. 返回 `list[dataclass]`,不是 DataFrame** **3. 返回 `list[dataclass]`,不是 DataFrame**
@@ -55,34 +59,34 @@ pip install pytdxdata # 或 uv add pytdxdata
```python ```python
import asyncio import asyncio
from pytdxdata import TdxData from pytdxdata import TdxData
from pytdxdata.models import Market, KlinePeriod, Adjust from pytdxdata.models import KlinePeriod, Adjust
async def main(): async def main():
async with TdxData() as td: async with TdxData() as td:
# 日K线,240 根(count 超过单页大小会自动多连接并发分页) # 日K线,240 根(count 超过单页大小会自动多连接并发分页)
bars = await td.get_kline(Market.SH, "600000", KlinePeriod.DAY, count=240) bars = await td.get_bars(["sz000001"], KlinePeriod.DAY, count=240)
print(bars[-1].close, bars[-1].datetime) print(bars[-1].close, bars[-1].datetime)
# 前复权日线(复权自动走 MAC 通道) # 前复权日线(复权自动走 MAC 通道)
qfq = await td.get_kline(Market.SZ, "300308", KlinePeriod.DAY, qfq = await td.get_bars(["sz300308"], KlinePeriod.DAY,
count=500, adjust=Adjust.QFQ) count=500, adjust=Adjust.QFQ)
# 五档报价:入参是 (market, code) 元组列表,一次可传多只(>80 只自动切批) # 跨市场报价:A股+港股+美股一次拿全
quotes = await td.get_quotes([(Market.SH, "600000"), (Market.SZ, "000001")]) quotes = await td.get_quotes(["sz000001", "hk00700", "usAAPL"])
print(quotes[0].price, quotes[0].bid[0], quotes[0].ask[0]) print(quotes[0].price, quotes[1].name, quotes[2].amount)
# 逐笔成交(MAC 通道,支持历史日期,含 trade_count 成交笔数) # 逐笔成交(MAC 通道,支持历史日期,含 trade_count 成交笔数)
ticks = await td.get_transactions(Market.SZ, "000001", date=20260811) ticks = await td.get_ticks(["sz000001"], date=20260811)
print(sum(r.trade_count for r in ticks)) # 当日总成交笔数 print(sum(r.trade_count for r in ticks))
# 分时(MAC 通道,今日或历史) # 分时(MAC 通道,今日或历史)
minute = await td.get_minute(Market.SH, "600000") minutes = await td.get_minutes(["sz000001"])
# 批量 K 线:多股票自动并发,池子会分配到不同服务器 # 批量 K 线:多股票自动并发,池子会分配到不同服务器
batch = await td.get_kline_batch( batch = await td.get_bars(
[(Market.SH, "600000"), (Market.SZ, "000001")], ["sz000001", "sh600000"],
KlinePeriod.DAY, count=240, KlinePeriod.DAY, count=240,
) # -> {"600000": [...], "000001": [...]} ) # 平铺返回,每条带 .symbol 字段
asyncio.run(main()) asyncio.run(main())
``` ```
@@ -121,38 +125,37 @@ asyncio.run(main())
**`ExMarket`** — 扩展市场(港股 / 美股 / 期货 / 期权,共 46 个成员,走独立 EX 通道) **`ExMarket`** — 扩展市场(港股 / 美股 / 期货 / 期权,共 46 个成员,走独立 EX 通道)
常用几个:`HK_MAIN_BOARD=31`、`US_STOCK=74`、`CFFEX_FUTURES=47`、`SH_STOCK_OPTION=8`、`SZ_STOCK_OPTION=9`。 v0.6 起统一接口用**字符串前缀**指定扩展市场,一般不再需要 `ExMarket`:
完整表见 <https://openbot-coder.github.io/pytdxdata/api/enums/>。
```python ```python
from pytdxdata.models import ExMarket await td.get_bars("hk00700", KlinePeriod.DAY, count=700) # 港股(5 位代码)
await td.get_bars("usAAPL", KlinePeriod.DAY, count=700) # 美股(ticker)
await td.get_kline(ExMarket.HK_MAIN_BOARD, "00700", KlinePeriod.DAY, count=700) # 港股,5 位代码 await td.get_bars("cffex:IFL0", KlinePeriod.DAY, count=700) # 期货合约
await td.get_kline(ExMarket.US_STOCK, "AAPL", KlinePeriod.DAY, count=700) # 美股,ticker
await td.get_kline(ExMarket.CFFEX_FUTURES, "IFL0", KlinePeriod.DAY, count=700) # 期货合约
``` ```
常用前缀:`hk` / `us` / `cffex` / `shf` / `dl` / `zz` / `gz`;完整表见 <https://openbot-coder.github.io/pytdxdata/api/enums/>。
## 想做什么 → 用哪个方法 ## 想做什么 → 用哪个方法
| 需求 | 方法 | | 需求 | 方法 |
|---|---| |---|---|
| 日/周/月/分钟 K 线 | `get_kline(market, code, period, *, count, adjust)` | | 全市场标的清单(A股+港股+期货…) | `get_universe(market=None)` |
| 增量更新(从某天往后) | `get_kline_since(market, code, period, since, adjust)` | | 日/周/月/分钟 K 线(任意市场) | `get_bars(symbols, period, *, count, adjust, start_date, end_date)` |
| 一次拉多只股票 K 线 | `get_kline_batch(stocks, period, *, count, adjust, concurrency)` | | K 线 + MACD/KDJ/RSI/BOLL | `get_indicators(symbols, indicators, ...)` |
| 指数 K 线 | `get_index_kline(market, code, period, *, count)` | | 实时五档报价(A股)/ 基础报价(港股/美股/期货) | `get_quotes(symbols, *, fields=None)` |
| K 线 + MACD/KDJ/RSI/BOLL | `get_stock_kline_with_indicators(market, code, indicators, ...)` | | 逐笔成交(任意市场) | `get_ticks(symbols, *, date)` |
| 实时五档报价 | `get_quotes(stocks)` | | 分时图 / 缩略采样 | `get_minutes(symbols, *, date, sampling=True)` |
| 逐笔成交 | `get_transactions(market, code, *, date)` | | 全市场股票列表(缓存 1 天) | `get_universe("sz")` / `get_universe("sh")` |
| 分时图 | `get_minute(market, code, *, date)` | | 除权除息 / 财务快照 | `get_xdxr(symbols)` / `get_finance(symbols)` |
| 全市场股票列表 | `get_security_list_all(market)`(缓存 1 天) | | F10 公司资料 | `get_f10(symbol, section)` |
| 除权除息 / 财务快照 | `get_xdxr(...)` / `get_finance(...)` | | 板块列表 / 成分股 / 涨跌排行 | `get_boards` / `get_board_members` / `get_board_ranking` |
| 板块列表 / 成分股 / 涨跌排行 | `get_board_list` / `get_board_members` / `get_board_ranking` | | 个股所属板块 | `get_board_of(symbols)` |
| 个股所属板块 | `get_belong_board(market, code)` |
| 集合竞价 / 异动 / 资金流 | `get_auction` / `get_unusual` / `get_capital_flow` | | 集合竞价 / 异动 / 资金流 | `get_auction` / `get_unusual` / `get_capital_flow` |
| 个股特征快照 | `get_snapshot(symbols)` |
| **板块成分文件**(离线快照) | `get_block_parsed("block_gn.dat")` | | **板块成分文件**(离线快照) | `get_block_parsed("block_gn.dat")` |
| **行业分类**(通达信 + 申万) | `get_industry_map()` | | **行业分类**(通达信 + 申万) | `get_industry_map()` |
| **历史专业财报**(gpcw 全字段) | `get_financial_file_infos()` + `get_financial_records_parsed(fn)` | | **历史专业财报**(gpcw 全字段) | `get_financial_file_infos()` + `get_financial_records_parsed(fn)` |
| 涨跌停价 | `get_price_limits(market, code, name, pre_close, listed_days)`(本地算,无网络) | | 涨跌停价 | `get_price_limits(symbol, name, pre_close, listed_days)`(本地算,无网络) |
| 全市场涨跌家数/成交额 | `get_market_stat()` | | 全市场涨跌家数/成交额 | `get_market_stat()` |
## 通道与数据特性(影响你能拿到什么) ## 通道与数据特性(影响你能拿到什么)
@@ -160,9 +163,10 @@ await td.get_kline(ExMarket.CFFEX_FUTURES, "IFL0", KlinePeriod.DAY, count=700)
库内部有**标准通道**和 **MAC 通道**两条链路,会**按命令自动选路**,你不用管。但有几件事必须知道: 库内部有**标准通道**和 **MAC 通道**两条链路,会**按命令自动选路**,你不用管。但有几件事必须知道:
- **数据有 15 分钟延时**(通达信公开服务器特性)。要实时数据请用券商行情。 - **数据有 15 分钟延时**(通达信公开服务器特性)。要实时数据请用券商行情。
- **复权 K 线与 1 分钟 K 线走 MAC 通道**。`get_kline(..., adjust=Adjust.QFQ)` 自动切换。 - **复权 K 线与 1 分钟 K 线走 MAC 通道**。`get_bars(..., adjust=Adjust.QFQ)` 自动切换。
- **K 线时间戳统一为北京时间**(v0.6.2 起)。美股原始报文里日期是美东交易日、时分是北京时间(两个时区拼在一起),库已自动归一化,`bar.datetime` 可直接排序 / 比较 / 过滤。但**美股一个交易日横跨两个北京自然日**,按交易日聚合(分钟线合成日线、日内统计)必须用 `bar.trading_date`。
- **`count` 很大时会自动多连接并发分页**,无需手动翻页。但标准通道 K 线 `count < 100` 部分服务器会返回空——内部已强制 `min_page=100` 规避。 - **`count` 很大时会自动多连接并发分页**,无需手动翻页。但标准通道 K 线 `count < 100` 部分服务器会返回空——内部已强制 `min_page=100` 规避。
- **`get_quotes` 一次 >80 只自动切批**;而 MAC 的 `get_stock_quotes` 上限就是 80 只/次。 - **`get_quotes` 一次 >80 只自动切批**;走 MAC 字段位通道(`fields=`)时上限为 80 只/次。
- **历史逐笔没有笔数字段**,只有当日逐笔的 `trade_count` 有效。 - **历史逐笔没有笔数字段**,只有当日逐笔的 `trade_count` 有效。
- 板块文件(`block_*.dat`)/ 行业(`tdxhy.cfg`)/ 财报(`gpcw*.zip`)是**服务器上的静态文件**,解析后是普通 dataclass,**落 JSON 后完全脱网可用**——适合做离线快照。 - 板块文件(`block_*.dat`)/ 行业(`tdxhy.cfg`)/ 财报(`gpcw*.zip`)是**服务器上的静态文件**,解析后是普通 dataclass,**落 JSON 后完全脱网可用**——适合做离线快照。
@@ -170,15 +174,19 @@ await td.get_kline(ExMarket.CFFEX_FUTURES, "IFL0", KlinePeriod.DAY, count=700)
| 坑 | 后果 | 正确做法 | | 坑 | 后果 | 正确做法 |
|---|---|---| |---|---|---|
| `market` 传 `"sh"` 字符串 | 直接报错或路由到错误市场 | 用 `Market.SH` 枚举 | | 统一方法(`get_quotes`/`get_bars`…)传 `(Market.SH, "600000")` 元组或市场号 | v0.6 起直接报错 | 用字符串 `"sh600000"` |
| 以为 `KlinePeriod.DAY == 0` | 拿到的是 5 分钟线 | `DAY=4`,对照上面的表 | | 旧别名(`get_kline`/`get_transactions`…)传 `(market, code)` | 能跑,但发出 `DeprecationWarning` | 迁移到统一方法 + 字符串 |
| 忘了 `async with` / `start()` | 无连接池,运行时报错 | 一律 `async with TdxData() as td:` | | 忘了 `async with` / `start()` | 无连接池,运行时报错 | 一律 `async with TdxData() as td:` |
| `KlinePeriod.DAY == 0` | 拿到的是 5 分钟线 | `DAY=4`,对照枚举表 |
| 等在返回值上找 `.to_dataframe()` | 不存在 | `pd.DataFrame([asdict(x) for x in bars])` | | 等在返回值上找 `.to_dataframe()` | 不存在 | `pd.DataFrame([asdict(x) for x in bars])` |
| 把 `close` 当成分 | 数值差 100 倍 | 价格单位是**元**(float) | | 把 `close` 当成分 | 数值差 100 倍 | 价格单位是**元**(float) |
| `SH 000001` 当成平安银行 | 拿到的是上证指数 | **代码不唯一**:`(Market.SH, "000001")`=上证指数,`(Market.SZ, "000001")`=平安银行 | | `sh000001` 当成平安银行 | 拿到的是上证指数 | **代码不唯一**:`sh000001`=上证指数,`sz000001`=平安银行 |
| 用 `get_block_info` 又自己拆二进制 | 白写解析器 | 用 `get_block_parsed`,已经解析好了 | | 用 `get_block_info` 又自己拆二进制 | 白写解析器 | 用 `get_block_parsed`,已经解析好了 |
| 循环里逐个 `await get_kline` | 慢 | 用 `get_kline_batch` 让它并发 | | 循环里逐个 `await get_bars` | 慢 | 用列表传多个标的,自动并发 |
| 港股/美股五档 bid/ask | 没有(协议不支持) | `fields` 字段位通道有 name 但无五档 |
| 美股分钟线用 `datetime.date()` 分组做日聚合 | 一个交易日被拆成两天(美股跨北京零点) | 用 `bar.trading_date`;`bar.datetime` 是归一化后的北京时间 |
| 依赖实时性做信号 | 数据是 15 分钟前的 | 换券商实时源 | | 依赖实时性做信号 | 数据是 15 分钟前的 | 换券商实时源 |
| 手动改包内 `servers.json` / 写死 IP | 容器只读、升级被覆盖、快节点捞不回来 | 日常靠内置的**当日测速缓存**自动选路;要强制指定就用 `PYPYTDX_DATA_{STANDARD,MAC,EX}_HOSTS` 环境变量 |
## 深入参考 ## 深入参考
+89 -26
View File
@@ -1,6 +1,6 @@
# pytdxdata 对外接口清单 # pytdxdata 对外接口清单
> 以 `src/pytdxdata` 源码为准整理(v0.5.0)。分四类:Python API / 数据模型 / 辅助模块 / CLI。 > 以 `src/pytdxdata` 源码为准整理(v0.6.0)。分四类:Python API / 数据模型 / 辅助模块 / CLI。
> >
> 方法与代码的一致性由 `scripts/check_docs.py` 在 CI 中校验。 > 方法与代码的一致性由 `scripts/check_docs.py` 在 CI 中校验。
@@ -39,7 +39,50 @@ from pytdxdata import (
| `async close()` | 关闭全部池与缓存 | | `async close()` | 关闭全部池与缓存 |
| `async with TdxData() as td:` | 上下文管理器,自动 start/close | | `async with TdxData() as td:` | 上下文管理器,自动 start/close |
### 2.1 K线(共 6 个) ### 2.1 统一接口(v0.6+ 推荐){#unified}
以下方法在 v0.6 新增,标的一律用字符串(`sz000001` / `hk00700` / `usAAPL` / `cffex:IFL0`)。
#### 标的清单
| 方法 | 返回 | 说明 |
|------|------|------|
| `get_universe(market=None)` | `list[SecurityInfo]` | 跨市场标的清单(A 股+港股+美股+期货/期权) |
#### 报价
| 方法 | 返回 | 说明 |
|------|------|------|
| `get_quotes(symbols, *, fields=None)` | `list[SecurityQuote]` | 跨市场混合报价(A 股标准五档;给了 fields 走 MAC/EX 字段位有 name) |
| `get_snapshot(symbols)` | `list[SymbolSnapshot]` | 个股特征快照(A 股) |
| `get_auction(symbols)` | `list[AuctionItem]` | 集合竞价(A 股) |
| `get_capital_flow(symbols)` | `list[CapitalFlow]` | 个股资金流向(A 股) |
#### K线
| 方法 | 返回 | 说明 |
|------|------|------|
| `get_bars(symbols, period=DAY, *, start=0, count=800, adjust=None, start_date=None, end_date=None, concurrency=6)` | `list[SecurityBar]` | 跨市场 K 线(自动判指数、复权走 MAC、并发分页、日期区间二分) |
| `get_indicators(symbols, indicators, *, period=DAY, count=30, adjust=None, params=None)` | `list[IndicatorSet]` | K 线+技术指标(MACD/KDJ/RSI/BOLL/MA/EMA) |
#### 逐笔与分时
| 方法 | 返回 | 说明 |
|------|------|------|
| `get_ticks(symbols, *, date=None, start=0, count=None, concurrency=6)` | `list[TransactionRecord]` | 跨市场逐笔成交 |
| `get_minutes(symbols, *, date=None, sampling=False, concurrency=6)` | `list[MinuteBar]` | 跨市场分时(sampling=True 取缩略采样:A股由 0x122D 派生,扩展市场 0x254D) |
#### 公司信息/文件/板块
| 方法 | 返回 | 说明 |
|------|------|------|
| `get_f10(symbol, section=None, *, offset=0, length=65535)` | `list \| str` | F10 公司资料 |
| `get_file(name)` | `bytes` | 服务器文件原始字节(自动选通道) |
| `get_boards(kind="all", *, count=10000)` | `list[BoardInfo]` | 板块列表 |
| `get_board_members(board, *, fields=None, count=100000)` | `list[SecurityQuote]` | 板块成分股报价(归一模型) |
| `get_board_of(symbols)` | `list[BelongBoard]` | 个股所属板块 |
### 2.2 K线(旧接口,共 6 个) {#legacy-kline}
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
@@ -50,25 +93,25 @@ from pytdxdata import (
| `get_stock_kline_with_indicators(market, code, indicators, *, period=DAY, count=30, adjust=None, params=None)` | `dict` | K线+技术指标(MACD/KDJ/RSI/BOLL/MA/EMA) | | `get_stock_kline_with_indicators(market, code, indicators, *, period=DAY, count=30, adjust=None, params=None)` | `dict` | K线+技术指标(MACD/KDJ/RSI/BOLL/MA/EMA) |
| `get_kline_offset(offset=0, count=1)` | `tuple[int, int]` | K线偏移信息(MAC) | | `get_kline_offset(offset=0, count=1)` | `tuple[int, int]` | K线偏移信息(MAC) |
### 2.2 报价(共 4 个) ### 2.3 报价(旧接口,共 4 个) {#legacy-quote}
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
| `get_quotes(stocks)` | `list[SecurityQuote]` | 五档报价;>80 只自动切批;TTL 5s | | `get_quotes(symbols, *, fields=None)` | `list[SecurityQuote]` | 五档报价;>80 只自动切批;TTL 5s |
| `get_stock_quotes(stocks, bits=None)` | `list[MemberQuote]` | MAC 自定义字段报价(≤80只/次) | | `get_stock_quotes(stocks, bits=None)` | `list[MemberQuote]` | MAC 自定义字段报价(≤80只/次) |
| `get_stock_quotes_list(category, *, start=0, count=80, sort_type=0)` | `list[MemberQuote]` | 市场分类报价(0沪A/2深A/6全A/8科创/14创业) | | `get_stock_quotes_list(category, *, start=0, count=80, sort_type=0)` | `list[MemberQuote]` | 市场分类报价(0沪A/2深A/6全A/8科创/14创业) |
| `get_market_stat()` | `MarketStat` | 全市场统计(涨跌家数/总额/市值/涨跌停数) | | `get_market_stat()` | `MarketStat` | 全市场统计(涨跌家数/总额/市值/涨跌停数) |
### 2.3 逐笔成交 / 分时(共 4 个) ### 2.4 逐笔成交 / 分时(旧接口,共 4 个) {#legacy-tick}
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
| `get_transactions(market, code, *, date=None, start=0, count=2000)` | `list[TransactionRecord]` | 逐笔成交(MAC,含 trade_count),支持历史日期 | | `get_transactions(market, code, *, date=None, start=0, count=2000)` | `list[TransactionRecord]` | 逐笔成交(MAC,含 trade_count),支持历史日期 |
| `get_minute(market, code, *, date=None)` | `list[MinuteBar]` | 分时(MAC 0x122D,可历史) | | `get_minute(market, code, *, date=None)` | `list[MinuteBar]` | 分时(MAC 0x122D,可历史) |
| `get_minute_batch(stocks, *, date=None, concurrency=6)` | `dict[str, list[MinuteBar]]` | 批量分时 | | `get_minute_batch(stocks, *, date=None, concurrency=6)` | `dict[str, list[MinuteBar]]` | 批量分时 |
| `get_chart_sampling(market, code)` | `list[float]` | 分时缩略采样(A股,MAC 0x254D) | | `get_chart_sampling(market, code)` | `list[float]` | 分时缩略采样(A股由 MAC **0x122D** 派生;0x254D 仅 EX 通道可用) |
### 2.4 证券列表(共 3 个) ### 2.5 证券列表(旧接口,共 3 个) {#legacy-list}
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
@@ -76,30 +119,30 @@ from pytdxdata import (
| `get_security_list(market, *, start=0, count=None)` | `list[SecurityInfo]` | count=None=全部(先查总数防死循环) | | `get_security_list(market, *, start=0, count=None)` | `list[SecurityInfo]` | count=None=全部(先查总数防死循环) |
| `get_security_list_all(market)` | `list[SecurityInfo]` | 全市场列表(高并发一次拉完,缓存 1 天) | | `get_security_list_all(market)` | `list[SecurityInfo]` | 全市场列表(高并发一次拉完,缓存 1 天) |
### 2.5 除权 / 财务 / F10 / 文件(共 15 个) ### 2.6 除权 / 财务 / F10 / 文件(旧接口,共 15 个) {#file-methods}
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
| `get_xdxr(market, code)` | `list[XdxrRecord]` | 除权除息历史(标准) | | `get_xdxr(symbols)` | `list[XdxrRecord]` | 除权除息历史(标准) |
| `get_finance(market, code)` | `FinanceRecord \| None` | 财务快照(标准) | | `get_finance(symbols)` | `list[FinanceRecord]` | 财务快照(标准;无数据的标的跳过) |
| `get_price_limits(market, code, name, pre_close, listed_days=9999)` | `tuple[float\|None, float\|None]` | 涨跌停价(本地计算) | | `get_price_limits(symbol, name=None, pre_close=None, listed_days=9999)` | `tuple[float\|None, float\|None]` | 涨跌停价(本地计算) |
| `get_company_info_category(market, code)` | `list` | F10 目录(标准) | | `get_company_info_category(market, code)` | `list` | F10 目录(标准) |
| `get_company_info_content(market, code, filename, offset=0, length=65535)` | `str` | F10 内容(分块) | | `get_company_info_content(market, code, filename, offset=0, length=65535)` | `str` | F10 内容(分块) |
| `get_block_info(filename)` | `bytes` | 板块文件**原始字节**(先查元数据再分块下载) | | `get_block_info(filename)` | `bytes` | 板块文件**原始字节**(先查元数据再分块下载) |
| `get_report_file(filename)` | `bytes` | 报告/财务文件**原始字节**(标准 0x06B9) | | `get_report_file(filename)` | `bytes` | 报告/财务文件**原始字节**(标准 0x06B9) |
| `get_financial_file_list()` | `list[str]` | 财务文件列表**原始行**(tdxfin/gpcw.txt) | | `get_financial_file_list()` | `list[str]` | 财务文件列表**原始行**(tdxfin/gpcw.txt) |
| `get_financial_records(filename)` | `bytes` | 财务文件内容(gpcw*.zip 原始字节) | | `get_financial_records(filename)` | `bytes` | 财报 `.dat` 原始字节(索引写 `.zip` 但服务器只有 `.dat` 时自动回退;取不到返回 `b""`) |
| `get_file_meta(filename)` | `FileMeta` | 远程文件元信息(MAC 0x1215) | | `get_file_meta(filename)` | `FileMeta` | 远程文件元信息(MAC 0x1215) |
| `download_file(filename, filesize=0)` | `bytes` | 下载完整远程文件(MAC 0x1217,分块) | | `download_file(filename, filesize=0)` | `bytes` | 下载完整远程文件(MAC 0x1217,分块) |
| **`get_block_parsed(filename)`** | `list[TdxBlock]` | 板块文件**下载+解析**为板块成分(category 按文件名推断:0行业/2概念/3风格) | | **`get_block_parsed(filename)`** | `list[TdxBlock]` | 板块文件**下载+解析**为板块成分(category 按文件名推断:0行业/2概念/3风格) |
| **`get_industry_map()`** | `dict[str, IndustryInfo]` | tdxhy.cfg **下载+解析**:`{代码: 通达信行业+申万行业}` | | **`get_industry_map()`** | `dict[str, IndustryInfo]` | tdxhy.cfg **下载+解析**:`{代码: 通达信行业+申万行业}` |
| **`get_financial_file_infos()`** | `list[FinancialFileInfo]` | gpcw.txt **下载+解析**:文件名/MD5/大小 | | **`get_financial_file_infos()`** | `list[FinancialFileInfo]` | gpcw.txt **下载+解析**:文件名/MD5/大小 |
| **`get_financial_records_parsed(filename)`** | `list[FinancialRecord]` | gpcw*.zip **解压+解析**:每股原始 float 字段(报告期取自文件名,缺失回退头部) | | **`get_financial_records_parsed(filename)`** | `list[FinancialRecord]` | 财报**解析**:每股原始 float 字段。可直接传 `get_financial_file_infos()` 的 `filename`——自动纠正服务器实际文件名(`.zip`/`.dat` 两种形态都支持);报告期取自文件名,缺失回退头部 |
> 解析层独立于网络层:解析器位于 `pytdxdata.codec`(纯标准库 `struct`/`zipfile`),可脱网单测; > 解析层独立于网络层:解析器位于 `pytdxdata.codec`(纯标准库 `struct`/`zipfile`),可脱网单测;
> 原 `get_*` 返回 `bytes`/`list[str]` 的方法保持**向后兼容**,解析版为**新增**方法。 > 原 `get_*` 返回 `bytes`/`list[str]` 的方法保持**向后兼容**,解析版为**新增**方法。
### 2.6 板块(共 6 个) ### 2.7 板块(旧接口,共 6 个) {#legacy-board}
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
@@ -110,17 +153,17 @@ from pytdxdata import (
| `get_board_ranking(board_type=1, top_n=20)` | `list[dict]` | 板块涨跌幅排行 | | `get_board_ranking(board_type=1, top_n=20)` | `list[dict]` | 板块涨跌幅排行 |
| `get_board_change_ranking(board_type=1, days=20, top_n=20)` | `list[dict]` | 板块 N 日涨跌幅排行(板块指数K线) | | `get_board_change_ranking(board_type=1, days=20, top_n=20)` | `list[dict]` | 板块 N 日涨跌幅排行(板块指数K线) |
### 2.7 MAC 扩展:竞价 / 异动 / 快照 / 资金流 / 服务器(共 5 个) ### 2.8 MAC 扩展:竞价 / 异动 / 快照 / 资金流 / 服务器(旧接口,共 5 个) {#legacy-mac}
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
| `get_auction(market, code)` | `list[AuctionItem]` | 集合竞价 | | `get_auction(symbols)` | `list[AuctionItem]` | 集合竞价 |
| `get_unusual(market, start=0, count=600)` | `list[UnusualItem]` | 市场异动 | | `get_unusual(market="all", *, start=0, count=600)` | `list[UnusualItem]` | 市场异动 |
| `get_symbol_info(market, code)` | `SymbolSnapshot` | 个股特征快照 | | `get_symbol_info(market, code)` | `SymbolSnapshot` | 个股特征快照 |
| `get_capital_flow(market, code)` | `CapitalFlow` | 个股资金流向 | | `get_capital_flow(symbols)` | `list[CapitalFlow]` | 个股资金流向 |
| `get_server_info()` | `ServerInfo` | 服务器交易时段信息 | | `get_server_info()` | `ServerInfo` | 服务器交易时段信息 |
### 2.8 EX 扩展市场(港股/美股/期货/期权,共 8 个) ### 2.9 EX 扩展市场(旧接口,港股/美股/期货/期权,共 8 个) {#legacy-ex}
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
@@ -133,7 +176,8 @@ from pytdxdata import (
| `get_goods_transaction(market, code, *, ymd=0, start=0, count=1800)` | `list[dict]` | 扩展市场逐笔(港股 0x23FC/0x2406) | | `get_goods_transaction(market, code, *, ymd=0, start=0, count=1800)` | `list[dict]` | 扩展市场逐笔(港股 0x23FC/0x2406) |
| `get_goods_transaction_all(market, code, ymd=0)` | `list[dict]` | 港股全量逐笔(自动翻页,≤50页/9万条) | | `get_goods_transaction_all(market, code, ymd=0)` | `list[dict]` | 港股全量逐笔(自动翻页,≤50页/9万条) |
**合计:`TdxData` 公开异步方法 51 个**(另有 `_execute_standard/_execute_mac/_execute_ex` 等内部执行方法)。 **合计:`TdxData` 公开异步方法 63 个** = 28 个统一接口 + 33 个 deprecated 别名 + `start`/`close`
(另有 `_execute_standard` / `_execute_mac` / `_execute_ex` 等内部执行方法)。
## 三、数据模型(`pytdxdata.models`) ## 三、数据模型(`pytdxdata.models`)
@@ -188,17 +232,36 @@ from pytdxdata import (
| `boll(values, period=20, mult=2.0)` | 布林带 | | `boll(values, period=20, mult=2.0)` | 布林带 |
| `compute_indicators(high, low, close, indicators, params=None, tail=None)` | 统一入口(被 `get_stock_kline_with_indicators` 调用) | | `compute_indicators(high, low, close, indicators, params=None, tail=None)` | 统一入口(被 `get_stock_kline_with_indicators` 调用) |
**`pytdxdata.config`**(服务器清单) **`pytdxdata.config`**(服务器清单与选路)
| 函数 | 说明 | 主机来源优先级链(各协议独立):`PYPYTDX_DATA_*_HOSTS` 环境变量 → **当日测速缓存** →
包内清单 `fast_pool` → 包内清单 → 代码内置常量。
| 函数 / 常量 | 说明 |
|------|------| |------|------|
| `get_standard_hosts()` | 标准通道服务器列表 | | `get_standard_hosts()` | 标准通道服务器列表(按上述优先级链解析) |
| `get_mac_hosts()` | MAC 通道服务器列表 | | `get_mac_hosts()` | MAC 通道服务器列表 |
| `get_ex_hosts()` | EX 扩展市场服务器列表 | | `get_ex_hosts()` | EX 扩展市场服务器列表 |
| `get_ex_handshakes()` | EX 握手方式映射 | | `get_ex_handshakes()` | EX 握手方式映射 |
| `all_probe_candidates()` | 全量候选主机 `{standard, mac, ex}`(清单 ∪ 常量 ∪ env,**不按状态过滤**) |
| `is_valid_host(host)` | 主机名合法性校验(挡 mock 脏数据 / 非法条目) |
| `probe_cache_dir()` / `probe_cache_file()` | 用户级当日测速缓存目录 / 文件路径 |
| `load_probe_cache(today=None, path=None)` | 读当日测速缓存;缺失 / 损坏 / 非今日 / 版本不符 → `None` |
| `probe_disabled()` | 是否已用 `PYPYTDX_DATA_DISABLE_PROBE` 关闭测速 |
| `PROBE_CACHE_VERSION` | 测速缓存 payload 版本号 |
**`pytdxdata.server_probe`**(服务器探测,可 `python -m pytdxdata.server_probe` 运行) **`pytdxdata.pool.probe_cache`**(当日测速:后台执行、对用户无感)
`load_servers()` / `save_servers(cfg)` / `SERVERS_FILE`
| 符号 | 说明 |
|------|------|
| `ProbeCache` | 进程内协调器;`ensure_probe()` 为幂等入口(单飞 + 原子写) |
| `schedule_probe(hosts=None)` | 连接池用:挂后台 task 并返回该 task;无事件循环时返回 `None` |
| `get_probe_cache()` | 取进程级单例 |
**`pytdxdata.server_probe`**(离线服务器探测,`python -m pytdxdata.server_probe`)
`load_servers()` / `save_servers(cfg)` / `SERVERS_FILE` / `probe_one(server, timeout, discover)`
CLI 开关:`--discover`(三种协议全测并据实修正 `protocols`,同时剔除脏记录)/
`--group standard|mac|ex` / `--refresh`(只重测 `status=ok` 的)/ `--timeout`
## 五、CLI(`tdx` 命令,来自 `python -m pytdxdata.cli`) ## 五、CLI(`tdx` 命令,来自 `python -m pytdxdata.cli`)
@@ -220,7 +283,7 @@ from pytdxdata import (
| `tdx block [filename] [--limit 30] [--codes]` | 板块文件 下载+解析(block_*.dat → 成分股) | | `tdx block [filename] [--limit 30] [--codes]` | 板块文件 下载+解析(block_*.dat → 成分股) |
| `tdx industry [codes...] [--limit 30] [--search 词]` | 行业分类 下载+解析(tdxhy.cfg) | | `tdx industry [codes...] [--limit 30] [--search 词]` | 行业分类 下载+解析(tdxhy.cfg) |
| `tdx financial-list [--limit 30]` | 历史专业财报文件索引(gpcw.txt) | | `tdx financial-list [--limit 30]` | 历史专业财报文件索引(gpcw.txt) |
| `tdx financial <filename> [--code X] [--limit 5] [--fields 4]` | 历史专业财报记录 下载+解析(gpcw*.zip) | | `tdx financial <filename> [--code X] [--limit 5] [--fields 4]` | 历史专业财报记录 下载+解析(文件名自动纠正,见 `get_financial_records_parsed`) |
| `tdx server-info` | 服务器交易时段 | | `tdx server-info` | 服务器交易时段 |
| `tdx market-stat` | 市场统计 | | `tdx market-stat` | 市场统计 |
+9 -8
View File
@@ -6,7 +6,7 @@ pytdxdata 的枚举取值**完全没有直觉**(`KlinePeriod.DAY` 是 `4` 不
| 文件 | 面向 | 内容 | | 文件 | 面向 | 内容 |
|---|---|---| |---|---|---|
| [`llms.txt`](https://openbot-coder.github.io/pytdxdata/llms.txt) | AI 爬虫 / 问答型模型 | 心智模型、能力分组、关键陷阱,自动随站点发布 | | [`llms.txt`](https://openbot-coder.github.io/pytdxdata/llms.txt) | AI 爬虫 / 问答型模型 | 心智模型、能力分组、关键陷阱,自动随站点发布 |
| [`SKILL.md`](https://github.com/openbot-coder/pytdxdata/blob/main/SKILL.md) | AI **编程**助手 | 必守约定、枚举取值表、可运行模板、任务→方法决策表、9 条陷阱 | | [`SKILL.md`](https://github.com/openbot-coder/pytdxdata/blob/main/SKILL.md) | AI **编程**助手 | 必守约定、枚举取值表、可运行模板、任务→方法决策表、11 条陷阱 |
`llms.txt` 解决「这个库能干什么」,`SKILL.md` 解决「代码该怎么写对」。 `llms.txt` 解决「这个库能干什么」,`SKILL.md` 解决「代码该怎么写对」。
@@ -25,12 +25,12 @@ curl -o ~/.workbuddy/skills/pytdxdata/SKILL.md \
## 里面有什么 ## 里面有什么
- **三条必守约定** —— 唯一入口是 `TdxData` 且必须 `async with`;`market` 是整数枚举而不是字符串; - **三条必守约定** —— 唯一入口是 `TdxData` 且必须 `async with`;标的是字符串(如 `sh600000`)
返回值是 `list[dataclass]` 而不是 DataFrame 而不是 `(market, code)` 元组;返回值是 `list[dataclass]` 而不是 DataFrame
- **枚举取值表** —— `Market` / `KlinePeriod` / `Adjust` / `ExMarket` 的准确取值 - **枚举取值表** —— `Market` / `KlinePeriod` / `Adjust` / `ExMarket` 的准确取值
- **可运行模板** —— K 线、复权、报价、逐笔、分时、批量,全部是能直接跑的代码 - **可运行模板** —— K 线、复权、报价、逐笔、分时、批量,全部是能直接跑的代码
- **「想做什么 → 用哪个方法」决策表** —— 21 个常见需求的直接映射 - **「想做什么 → 用哪个方法」决策表** —— 18 个常见需求的直接映射
- **9 条真实陷阱** —— 每条都注明后果和正确做法(如 `SH 000001` 是上证指数、`SZ 000001` 才是平安银行) - **11 条真实陷阱** —— 每条都注明后果和正确做法(如 `sh000001` 是上证指数、`sz000001` 才是平安银行)
## 为什么值得让 AI 读 ## 为什么值得让 AI 读
@@ -38,9 +38,10 @@ curl -o ~/.workbuddy/skills/pytdxdata/SKILL.md \
这些都不是「读一眼签名就能猜到」的信息。不加载技能,AI 通常会写出: 这些都不是「读一眼签名就能猜到」的信息。不加载技能,AI 通常会写出:
```python ```python
# ❌ 三种典型错误 # ❌ 几种典型错误
await td.get_kline("sh", "600000", 0, count=240) # market 传字符串;0 是 5 分钟线不是日线 await td.get_bars("sh600000", 4, count=240) # 4 是数字字面量;应用 KlinePeriod.DAY
td.get_kline(1, "600000", KlinePeriod.DAY) # 忘了 await,且没在 async with 内 await td.get_bars((Market.SH, "600000")) # 统一接口只接受字符串标的,不接受元组
td.get_bars("sh600000") # 忘了 await,且没在 async with 内
df = bars.to_dataframe() # 返回值是 list[dataclass],没有这个方法 df = bars.to_dataframe() # 返回值是 list[dataclass],没有这个方法
``` ```
+1 -1
View File
@@ -26,7 +26,7 @@ blocks = parse_block_dat(open("block_gn.dat", "rb").read(), "block_gn.dat")
如果不想自己管下载,直接用封装好的方法(内部就是调这些解析器): 如果不想自己管下载,直接用封装好的方法(内部就是调这些解析器):
`get_block_parsed()` / `get_industry_map()` / `get_financial_file_infos()` / `get_financial_records_parsed()` `get_block_parsed()` / `get_industry_map()` / `get_financial_file_infos()` / `get_financial_records_parsed()`
— 见 [接口总览 → 除权 / 财务 / F10 / 文件](index.md#file-methods)。 — 见 [完整接口清单 → 除权 / 财务 / F10 / 文件](../API_REFERENCE.md#file-methods)。
## 关键细节 ## 关键细节
+11 -7
View File
@@ -18,8 +18,8 @@ from pytdxdata.models import Adjust, ExMarket, KlinePeriod, Market
| `Market.BJ` | `2` | 北京(北交所) | | `Market.BJ` | `2` | 北京(北交所) |
!!! warning "代码不唯一" !!! warning "代码不唯一"
**市场 + 代码**才唯一。`(SH, "000001")` 是上证指数,`(SZ, "000001")` 是平安银行。 **市场 + 代码**才唯一。`sh000001` 是上证指数,`sz000001` 是平安银行。
所有接口的第一个参数都是 `market`,就是为了消歧。 统一接口用**字符串标的**把两者一起表达(前缀即市场),避免只写 6 位数字时的歧义。
## KlinePeriod — K 线周期 ## KlinePeriod — K 线周期
@@ -85,14 +85,18 @@ KlinePeriod.DAY.is_minute # False
| `ExMarket.US_STOCK` | `74` | **美股(最常用)** | | `ExMarket.US_STOCK` | `74` | **美股(最常用)** |
```python ```python
from pytdxdata.models import ExMarket, KlinePeriod from pytdxdata.models import KlinePeriod
await td.get_kline(ExMarket.HK_MAIN_BOARD, "00700", KlinePeriod.DAY, count=700) # 腾讯 # 统一接口用字符串前缀指定扩展市场(推荐):
await td.get_kline(ExMarket.US_STOCK, "AAPL", KlinePeriod.DAY, count=700) # 苹果 await td.get_bars("hk00700", KlinePeriod.DAY, count=700) # 腾讯
await td.get_kline(ExMarket.CFFEX_FUTURES, "IFL0", KlinePeriod.DAY, count=700) # 股指期货 await td.get_bars("usAAPL", KlinePeriod.DAY, count=700) # 苹果
await td.get_kline(ExMarket.SH_STOCK_OPTION, "10010971", KlinePeriod.DAY, count=700) await td.get_bars("cffex:IFL0", KlinePeriod.DAY, count=700) # 股指期货
await td.get_bars("sh_stock_option:10010971", KlinePeriod.DAY, count=700) # 沪股票期权
``` ```
> 上表的 `ExMarket` 枚举值用于查阅与内部协议;统一接口不再直接传枚举,改用字符串前缀
> (短前缀 `hk` / `us` / `cffex` …,无短别名的成员用枚举名小写 + 冒号,如 `sh_stock_option:10010971`)。
### 完整成员列表 ### 完整成员列表
以下由 `mkdocstrings` 从源码实时渲染,**以源码为准**: 以下由 `mkdocstrings` 从源码实时渲染,**以源码为准**:
+54 -69
View File
@@ -1,8 +1,9 @@
# 接口总览 # 接口总览
对外唯一入口是 **`TdxData`** 类,共 **51 个数据方法** 对外唯一入口是 **`TdxData`** 类,所有方法都可直接 `await`,返回标准库 `dataclass` 组成的 `list`。
(另有 `start()` / `close()` 两个生命周期方法,以及 `__aenter__` / `__aexit__`)。
所有方法都可以直接 `await`,返回的是标准库 `dataclass` 组成的 `list`,没有自定义容器类型。 **v0.6+** 推荐使用**统一接口**(一个数据类型 = 一个方法,跨市场自动选路);
旧的按通道/市场分裂的接口仍可调用,但会发出 `DeprecationWarning`,**1.0 移除**。
```python ```python
from pytdxdata import TdxData from pytdxdata import TdxData
@@ -21,100 +22,84 @@ from pytdxdata import TdxData
| `async close()` | 关闭全部连接池与缓存 | | `async close()` | 关闭全部连接池与缓存 |
| `async with TdxData() as td:` | 上下文管理器,自动 start / close | | `async with TdxData() as td:` | 上下文管理器,自动 start / close |
## K 线(6) ---
## 统一接口(v0.6+ 推荐){#unified}
标的一律用**字符串写法**(`sz000001` / `hk00700` / `usAAPL` / `cffex:IFL0`,
裸 6 位数字 = 沪市指数)。跨市场按通道自动分组并发,返回值统一带 `symbol` 字段。
### 标的清单
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
| `get_kline(market, code, period, *, start, count, adjust, start_date, end_date)` | `list[SecurityBar]` | 主接口。`count > 页大小` 自动并发分页;复权走 MAC;支持日期区间(内部二分定位) | | `get_universe(market=None)` | `list[SecurityInfo]` | 跨市场标的清单(A 股 + 港股 + 美股 + 期货/期权),EX 通道结果一次拉全后内存过滤 |
| `get_kline_since(market, code, period, since, adjust)` | `list[SecurityBar]` | 增量便捷方法(≥`since`,含当天) |
| `get_kline_batch(stocks, period, *, start, count, adjust, concurrency)` | `dict[str, list[SecurityBar]]` | 多股票并发,返回 `{code: bars}` |
| `get_index_kline(market, code, period, *, start, count)` | `list[SecurityBar]` | 指数 K 线(多涨跌家数字段已处理) |
| `get_stock_kline_with_indicators(market, code, indicators, ...)` | `dict` | K 线 + 技术指标(MACD / KDJ / RSI / BOLL / MA / EMA) |
| `get_kline_offset(offset, count)` | `tuple[int, int]` | K 线偏移信息(MAC) |
## 报价(4) ### 报价
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
| `get_quotes(stocks)` | `list[SecurityQuote]` | 五档报价;`>80` 只自动切批;TTL 5s | | `get_quotes(symbols, *, fields=None)` | `list[SecurityQuote]` | 跨市场混合报价(A 股标准通道有五档 bid/ask + 涨跌停价;给了 `fields` 走 MAC/EX 字段位通道有 name) |
| `get_stock_quotes(stocks, bits)` | `list[MemberQuote]` | MAC 自定义字段报价(≤80 只/次) | | `get_snapshot(symbols)` | `list[SymbolSnapshot]` | 个股特征快照(当日/换手/活跃度,A 股) |
| `get_stock_quotes_list(category, *, start, count, sort_type)` | `list[MemberQuote]` | 市场分类报价列表(0沪A / 6全A / 8科创 / 14创业) | | `get_auction(symbols)` | `list[AuctionItem]` | 集合竞价(A 股) |
| `get_capital_flow(symbols)` | `list[CapitalFlow]` | 个股资金流向(A 股) |
| `get_market_stat()` | `MarketStat` | 全市场统计(涨跌家数 / 总额 / 市值 / 涨跌停数) | | `get_market_stat()` | `MarketStat` | 全市场统计(涨跌家数 / 总额 / 市值 / 涨跌停数) |
## 逐笔与分时(4) ### K 线
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
| `get_transactions(market, code, *, date, start, count)` | `list[TransactionRecord]` | 逐笔成交(MAC,**含 `trade_count` 成交笔数**),支持历史回溯 | | `get_bars(symbols, period, *, start, count, adjust, start_date, end_date, concurrency)` | `list[SecurityBar]` | 跨市场 K 线(自动判指数、复权走 MAC、并发分页、日期区间二分定位,支持混合 A 股+港股+期货) |
| `get_minute(market, code, *, date)` | `list[MinuteBar]` | 分时(今日 / 历史,MAC `0x122D`) | | `get_indicators(symbols, indicators, *, period, count, adjust, params)` | `list[IndicatorSet]` | K 线 + 技术指标(MACD / KDJ / RSI / BOLL / MA / EMA),返回 `bars + indicators` 组合 |
| `get_minute_batch(stocks, *, date, concurrency)` | `dict[str, list[MinuteBar]]` | 批量分时 |
| `get_chart_sampling(market, code)` | `list[float]` | 分时缩略采样(A 股走 MAC `0x254D`) |
## 证券列表(3) ### 逐笔与分时
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
| `get_security_count(market)` | `int` | 市场证券数量 | | `get_ticks(symbols, *, date, start, count, concurrency)` | `list[TransactionRecord]` | 跨市场逐笔成交(A 股 MAC `0x122F` 含 `trade_count`;港股 EX `0x23FC` / `0x2406`;其他扩展市场 MAC) |
| `get_security_list(market, *, start, count)` | `list[SecurityInfo]` | `count=None` = 全部(先查总数防死循环) | | `get_minutes(symbols, *, date, sampling, concurrency)` | `list[MinuteBar]` | 跨市场分时(A 股 MAC `0x122D` 支持历史;`sampling=True` 取缩略采样约 240 点) |
| `get_security_list_all(market)` | `list[SecurityInfo]` | 全市场列表(高并发一次拉完,缓存 1 天) |
## 除权 / 财务 / F10 / 文件(15) {#file-methods} ### 公司信息 / 除权 / 财务 / 文件
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
| `get_xdxr(market, code)` | `list[XdxrRecord]` | 除权除息历史(标准) | | `get_f10(symbol, section=None, *, offset, length)` | `list \| str` | F10 公司资料(`section=None` 返回目录,给了返回正文) |
| `get_finance(market, code)` | `FinanceRecord \| None` | 财务快照(标准) | | `get_xdxr(symbols)` | `list[XdxrRecord]` | 除权除息历史(A 股) |
| `get_price_limits(market, code, name, pre_close, listed_days)` | `tuple[float \| None, float \| None]` | 涨跌停价(**本地计算**,无网络) | | `get_finance(symbols)` | `list[FinanceRecord]` | 财务快照(A 股,返回列表,无数据的标的跳过) |
| `get_company_info_category(market, code)` | `list` | F10 目录 | | `get_price_limits(symbol, name, pre_close, listed_days)` | `tuple[float\|None, float\|None]` | 涨跌停价(本地计算,无网络) |
| `get_company_info_content(market, code, filename, offset, length)` | `str` | F10 内容(分块) | | `get_file(name)` | `bytes` | 服务器文件原始字节(`block_*.dat` / `tdxhy.cfg` / `tdxfin/*` / MAC 远程文件) |
| `get_block_info(filename)` | `bytes` | 板块文件**原始字节** | | `get_block_parsed(filename)` | `list[TdxBlock]` | 板块文件**下载 + 解析**为成分股 |
| `get_report_file(filename)` | `bytes` | 报告 / 财务文件**原始字节** | | `get_industry_map()` | `dict[str, IndustryInfo]` | `tdxhy.cfg` **下载 + 解析** |
| `get_financial_file_list()` | `list[str]` | 财务文件列表**原始行** | | `get_financial_file_infos()` | `list[FinancialFileInfo]` | `gpcw.txt` **下载 + 解析** |
| `get_financial_records(filename)` | `bytes` | 财务文件内容**原始字节** | | `get_financial_records_parsed(filename)` | `list[FinancialRecord]` | `gpcw*.zip` **解压 + 解析** |
| `get_file_meta(filename)` | `FileMeta` | 远程文件元信息(MAC `0x1215`) |
| `download_file(filename, filesize)` | `bytes` | 下载完整远程文件(MAC `0x1217`,分块) |
| **`get_block_parsed(filename)`** | `list[TdxBlock]` | 板块文件**下载 + 解析**为成分股 |
| **`get_industry_map()`** | `dict[str, IndustryInfo]` | `tdxhy.cfg` **下载 + 解析**:通达信 + 申万行业 |
| **`get_financial_file_infos()`** | `list[FinancialFileInfo]` | `gpcw.txt` **下载 + 解析**:文件名 / MD5 / 大小 |
| **`get_financial_records_parsed(filename)`** | `list[FinancialRecord]` | `gpcw*.zip` **解压 + 解析**:每股原始字段 |
!!! note "原始字节通道保留" ### 市场 / 板块
返回 `bytes` 的那 4 个方法**保持向后兼容**,解析版是**新增**方法而不是替换。
解析器在 `pytdxdata.codec`,纯标准库,可以脱网单独复用(见 [文件解析器](codec.md))。
## 板块(6)
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
| `get_board_list(board_type, count)` | `list[BoardInfo]` | 板块列表(0全部 / 1行业 / 2概念) | | `get_unusual(market="all", *, start, count)` | `list[UnusualItem]` | 市场异动(A 股,`"all"` = 深 + 沪) |
| `get_board_members(board_symbol, count, sort_type)` | `list[MemberQuote]` | 板块成分股报价(如 `881001`) | | `get_server_info()` | `ServerInfo` | 服务器交易时段信息 |
| `get_belong_board(market, code)` | `list[BelongBoard]` | 个股所属板块 | | `get_kline_offset(offset, count)` | `tuple[int, int]` | K 线偏移信息(MAC) |
| `get_board_summary(board_symbol)` | `dict` | 成分数 / 成交额 / 主力净流入 / 涨跌家数 | | `get_boards(kind="all", *, count)` | `list[BoardInfo]` | 板块列表(`"all"` / `"industry"` / `"concept"` / `"style"`) |
| `get_board_ranking(board_type, top_n)` | `list[dict]` | 板块涨跌幅排行 | | `get_board_members(board, *, fields, count)` | `list[SecurityQuote]` | 板块成分股报价(返回归一报价模型) |
| `get_board_change_ranking(board_type, days, top_n)` | `list[dict]` | 板块 N 日涨跌幅排行 | | `get_board_of(symbols)` | `list[BelongBoard]` | 个股所属板块(A 股) |
| `get_board_summary(board)` | `dict` | 板块汇总(成分数 / 成交额 / 主力净流入 / 涨跌家数) |
| `get_board_ranking(kind="industry", *, top_n)` | `list[dict]` | 板块当日涨跌幅排行 |
| `get_board_change_ranking(kind="industry", *, days, top_n)` | `list[dict]` | 板块 N 日涨跌幅排行 |
## 竞价 / 异动 / 快照 / 资金流 / 服务器(5) ---
| 方法 | 返回 | 说明 | ## 旧接口(deprecated,1.0 移除){#legacy}
|------|------|------|
| `get_auction(market, code)` | `list[AuctionItem]` | 集合竞价 |
| `get_unusual(market, start, count)` | `list[UnusualItem]` | 市场异动 |
| `get_symbol_info(market, code)` | `SymbolSnapshot` | 个股特征快照 |
| `get_capital_flow(market, code)` | `CapitalFlow` | 个股资金流向(主力 / 散户 + 5 档) |
| `get_server_info()` | `ServerInfo` | 服务器交易时段 |
## 扩展市场 EX:港股 / 美股 / 期货 / 期权(8) 旧接口按通道/市场分裂(33 个 deprecated 别名),保留向后兼容但仍可用。
完整旧方法列表见 `docs/API_REFERENCE.md`。
| 方法 | 返回 | 说明 | !!! warning "迁移建议"
|------|------|------| 各通道独立方法(如 `get_kline` / `get_transactions`)在 v0.6 内仍可调用,且仍接受
| `get_goods_list(market, start, count)` | `list[dict]` | 扩展市场商品列表(`0x23F5`,二分定位市场) | `(market, code)` 写法,但会发出 `DeprecationWarning`。
| `get_goods_count(market)` | `int` | 商品数量(`None` = 全市场) | 统一接口(`get_quotes` / `get_bars` / `get_ticks` / `get_xdxr` / `get_finance` /
| `get_goods_quotes(stocks, bits)` | `list[MemberQuote]` | 扩展市场报价(`0x122B`) | `get_auction` / `get_capital_flow` 等)一律只接受字符串标的(如 `"sz000001"`)。
| `get_goods_quotes_list(market, count)` | `list[MemberQuote]` | 商品列表 + 报价组合 | 迁移对照见 [更新日志](../changelog.md)。
| `get_goods_chart_sampling(market, code)` | `list[float]` | 扩展市场分时采样(`0x254D`) |
| `get_goods_tick_chart(market, code, ymd)` | `list[dict]` | 扩展市场分时 tick |
| `get_goods_transaction(market, code, *, ymd, start, count)` | `list[dict]` | 扩展市场逐笔(港股 `0x23FC` / `0x2406`) |
| `get_goods_transaction_all(market, code, ymd)` | `list[dict]` | 港股全量逐笔(自动翻页,≤50 页 / 9 万条) |
## 下一步 ## 下一步
+27 -11
View File
@@ -28,25 +28,25 @@ from pytdxdata.models import BoardInfo, MemberQuote, AuctionItem, CapitalFlow
| 模型 | 代表什么 | 从哪来 | | 模型 | 代表什么 | 从哪来 |
|---|---|---| |---|---|---|
| `SecurityBar` | 一根 K 线 | `get_kline` / `get_kline_batch` | | `SecurityBar` | 一根 K 线 | `get_bars` / `get_indicators` |
| `IndexBar` | 指数 K 线(继承 `SecurityBar`) | `get_index_kline` | | `IndexBar` | 指数 K 线(继承 `SecurityBar`) | `get_bars` |
| `SecurityQuote` | 五档报价快照 | `get_quotes` | | `SecurityQuote` | 五档报价快照 | `get_quotes` / `get_board_members` |
| `SecurityInfo` | 证券列表条目(代码 / 名称 / 前收) | `get_security_list` | | `SecurityInfo` | 证券列表条目(代码 / 名称 / 前收) | `get_universe` |
| `TransactionRecord` | 一笔成交 | `get_transactions` | | `TransactionRecord` | 一笔成交 | `get_ticks` |
| `MinuteBar` | 一分钟分时点 | `get_minute` | | `MinuteBar` | 一分钟分时点 | `get_minutes` |
| `XdxrRecord` | 一次除权除息事件 | `get_xdxr` | | `XdxrRecord` | 一次除权除息事件 | `get_xdxr` |
| `FinanceRecord` | 财务**快照**(最新一期,36 字段) | `get_finance` | | `FinanceRecord` | 财务**快照**(最新一期,36 字段) | `get_finance` |
| `FinancialRecord` | 历史专业财报(`gpcw*.zip`,多报告期) | `get_financial_records_parsed` | | `FinancialRecord` | 历史专业财报(`gpcw*.zip`,多报告期) | `get_financial_records_parsed` |
| `FinancialFileInfo` | 财报文件索引条目 | `get_financial_file_infos` | | `FinancialFileInfo` | 财报文件索引条目 | `get_financial_file_infos` |
| `TdxBlock` | 一个板块及其成分股 | `get_block_parsed` | | `TdxBlock` | 一个板块及其成分股 | `get_block_parsed` |
| `IndustryInfo` | 一只股票的行业归属 | `get_industry_map` | | `IndustryInfo` | 一只股票的行业归属 | `get_industry_map` |
| `BoardInfo` | 板块列表条目(含领涨股) | `get_board_list` | | `BoardInfo` | 板块列表条目(含领涨股) | `get_boards` |
| `MemberQuote` | 成分股报价(自定义字段) | `get_board_members` / `get_stock_quotes` | | `MemberQuote` | 成分股报价(MAC 原始字段) | 旧 `get_stock_quotes` / `get_stock_quotes_list` |
| `BelongBoard` | 个股所属板块 | `get_belong_board` | | `BelongBoard` | 个股所属板块 | `get_board_of` |
| `AuctionItem` | 集合竞价撮合点 | `get_auction` | | `AuctionItem` | 集合竞价撮合点 | `get_auction` |
| `UnusualItem` | 一笔市场异动 | `get_unusual` | | `UnusualItem` | 一笔市场异动 | `get_unusual` |
| `SymbolSnapshot` | 个股特征快照 | `get_symbol_info` | | `SymbolSnapshot` | 个股特征快照 | `get_snapshot` |
| `GoodsItem` | 扩展市场商品 | `get_goods_list` | | `GoodsItem` | 扩展市场商品 | 旧 `get_goods_list` |
| `ServerInfo` | 服务器交易时段 | `get_server_info` | | `ServerInfo` | 服务器交易时段 | `get_server_info` |
| `CapitalFlow` | 个股资金流向 | `get_capital_flow` | | `CapitalFlow` | 个股资金流向 | `get_capital_flow` |
| `MarketStat` | 全市场统计 | `get_market_stat` | | `MarketStat` | 全市场统计 | `get_market_stat` |
@@ -62,6 +62,22 @@ from pytdxdata.models import BoardInfo, MemberQuote, AuctionItem, CapitalFlow
| 结构 | 具名属性(`zongguben`、`jingzichan` ...) | `fields: list[float]`,原始字段数组 | | 结构 | 具名属性(`zongguben`、`jingzichan` ...) | `fields: list[float]`,原始字段数组 |
| 单位 | 万元 / 万股 | 原始 float,需自行按字段语义换算 | | 单位 | 万元 / 万股 | 原始 float,需自行按字段语义换算 |
!!! tip "`SecurityBar.datetime` 的时间戳口径(v0.6.2 起)"
时间统一为**北京时间**。A股 / 港股 / 期货的原始时间戳即为北京时间;美股的原始报文
混用了「美东交易日日期」与「北京时间时分」两个时区,库在构造时已自动归一化
(凌晨段日期 +1 天),因此 `bar.datetime` 可直接排序 / 比较 / 过滤。
但要注意**美股一个交易日横跨两个北京自然日**,按交易日聚合请用 `bar.trading_date`:
```python
bars = await td.get_bars("usAAPL", KlinePeriod.MIN_1, count=390)
bars[0].datetime # 2026-10-12 21:31:00(北京时间)
bars[-1].datetime # 2026-10-13 04:00:00(次日)
bars[0].trading_date # "2026-10-12" —— 归属的美东交易日
```
`bar.is_us` 可判定是否美股。详见 [常见问题 → 美股分钟 K 线](../faq.md)。
## 完整字段定义 ## 完整字段定义
以下由 `mkdocstrings` 从源码实时渲染(**以源码为准**): 以下由 `mkdocstrings` 从源码实时渲染(**以源码为准**):
+2 -2
View File
@@ -8,11 +8,11 @@
```python ```python
import asyncio import asyncio
from pytdxdata import TdxData from pytdxdata import TdxData
from pytdxdata.models import KlinePeriod, Market from pytdxdata.models import KlinePeriod
async def main(): async def main():
async with TdxData() as td: async with TdxData() as td:
bars = await td.get_kline(Market.SH, "600000", KlinePeriod.DAY, count=240) bars = await td.get_bars("sh600000", KlinePeriod.DAY, count=240)
print(bars[-1]) print(bars[-1])
asyncio.run(main()) asyncio.run(main())
+1 -1
View File
@@ -97,7 +97,7 @@ tdx industry --limit 30 # 只看前 30 条
# 历史专业财报 # 历史专业财报
tdx financial-list # 索引:文件名 / MD5 / 大小(gpcw.txt) tdx financial-list # 索引:文件名 / MD5 / 大小(gpcw.txt)
tdx financial gpcw20260331.zip --limit 5 # 下载 + 解压 + 解析 tdx financial gpcw20260331.zip --limit 5 # 下载 + 解析(服务器实际给 .dat 时自动回退)
tdx financial gpcw20260331.zip --code 600000 --fields 8 # 只取指定股票、打印更多字段 tdx financial gpcw20260331.zip --code 600000 --fields 8 # 只取指定股票、打印更多字段
``` ```
+6 -6
View File
@@ -94,8 +94,8 @@ git push origin feat/xxx
3. 提交并 push 到 `main` 3. 提交并 push 到 `main`
4. 打标签并推送: 4. 打标签并推送:
```bash ```bash
git tag v0.5.0 git tag v0.6.0
git push origin v0.5.0 git push origin v0.6.0
``` ```
推 tag 会自动触发 GitHub Actions:**test → build(含版本号一致性校验)→ OIDC 免密钥发布到 PyPI**。 推 tag 会自动触发 GitHub Actions:**test → build(含版本号一致性校验)→ OIDC 免密钥发布到 PyPI**。
@@ -105,12 +105,12 @@ git push origin feat/xxx
同名 tag **不能直接重推**(push 无变化,workflow 不会触发)。先删再推: 同名 tag **不能直接重推**(push 无变化,workflow 不会触发)。先删再推:
```bash ```bash
git push --delete origin v0.5.0 git push --delete origin v0.6.0
git tag -d v0.5.0 && git tag v0.5.0 git tag -d v0.6.0 && git tag v0.6.0
git push origin v0.5.0 git push origin v0.6.0
``` ```
或直接手动触发:`gh workflow run release.yml --ref v0.5.0` 或直接手动触发:`gh workflow run release.yml --ref v0.6.0`
文档站由 `.github/workflows/docs.yml` 在 push `main` 时自动部署到 文档站由 `.github/workflows/docs.yml` 在 push `main` 时自动部署到
<https://openbot-coder.github.io/pytdxdata/>。 <https://openbot-coder.github.io/pytdxdata/>。
+45 -35
View File
@@ -6,33 +6,32 @@
import asyncio import asyncio
from pathlib import Path from pathlib import Path
from pytdxdata import TdxData from pytdxdata import TdxData
from pytdxdata.models import Adjust, ExMarket, KlinePeriod, Market from pytdxdata.models import Adjust, KlinePeriod
``` ```
## 全市场日线批量落库 ## 全市场日线批量落库
连接池会把不同股票分配到不同服务器,这是 `*_batch` 存在的意义。 传多标的时,连接池会把不同股票分配到不同服务器——这正是它比逐个 `await` 快的原因。
```python ```python
async def dump_all_daily(): async def dump_all_daily():
async with TdxData(cache_dir=Path("./tdx_cache")) as td: async with TdxData(cache_dir=Path("./tdx_cache")) as td:
codes = await td.get_security_list_all(Market.SZ) # 缓存 1 天 infos = await td.get_universe("sz") # 缓存 1 天
symbols = [(Market.SZ, s.code) for s in codes] symbols = [i.symbol for i in infos] # ["sz000001", ...]
bars = await td.get_kline_batch( bars = await td.get_bars(
symbols, symbols,
KlinePeriod.DAY, KlinePeriod.DAY,
count=800, count=800,
adjust=Adjust.QFQ, adjust=Adjust.QFQ,
concurrency=12, concurrency=12,
) )
print(f"{len(bars)} / {len(symbols)} 只拿到数据") got = {b.symbol for b in bars}
print(f"{len(got)} / {len(symbols)} 只拿到数据")
for code, rows in bars.items(): # bars 是扁平 list[SecurityBar](按标的/时间排序),落库 / 写 parquet 都行
if not rows: if bars:
continue print(bars[-1].symbol, bars[-1].datetime, bars[-1].close)
# 落库 / 写 parquet 都行,这里只演示
print(code, len(rows), rows[-1].datetime, rows[-1].close)
``` ```
!!! tip "分页与并发的取舍" !!! tip "分页与并发的取舍"
@@ -41,12 +40,12 @@ async def dump_all_daily():
## 分钟线增量更新 ## 分钟线增量更新
只拉「上次之后」的部分,用 `get_kline_since` 省掉全量重拉。 只拉「上次之后」的部分,用 `get_bars(start_date=...)` 省掉全量重拉。
```python ```python
async def update_minute(code: str, last_dt): async def update_minute(symbol: str, last_dt):
async with TdxData(cache_dir=Path("./tdx_cache")) as td: async with TdxData(cache_dir=Path("./tdx_cache")) as td:
rows = await td.get_kline_since(Market.SZ, code, KlinePeriod.MIN_1, since=last_dt) rows = await td.get_bars(symbol, KlinePeriod.MIN_1, start_date=last_dt)
return [r for r in rows if r.datetime > last_dt] return [r for r in rows if r.datetime > last_dt]
``` ```
@@ -75,7 +74,7 @@ async def poll_quotes(symbols, interval=5.0):
async def sector_rotation(): async def sector_rotation():
async with TdxData() as td: async with TdxData() as td:
# 近 5 日概念板块涨幅排行 # 近 5 日概念板块涨幅排行
top = await td.get_board_change_ranking(board_type=2, days=5, top_n=10) top = await td.get_board_change_ranking(kind="concept", days=5, top_n=10)
for row in top: for row in top:
print(row) print(row)
@@ -92,18 +91,18 @@ async def sector_rotation():
## 个股所属板块(反向查询) ## 个股所属板块(反向查询)
```python ```python
async def belong(code: str): async def belong(symbol: str):
async with TdxData() as td: async with TdxData() as td:
for b in await td.get_belong_board(Market.SH, code): for b in await td.get_board_of(symbol):
print(b) print(b)
``` ```
## 逐笔复盘 ## 逐笔复盘
```python ```python
async def review_transactions(code: str, ymd: int): async def review_transactions(symbol: str, ymd: int):
async with TdxData() as td: async with TdxData() as td:
rows = await td.get_transactions(Market.SZ, code, date=ymd, count=2000) rows = await td.get_ticks(symbol, date=ymd, count=2000)
total = sum(r.trade_count or 0 for r in rows) total = sum(r.trade_count or 0 for r in rows)
buy = sum(r.vol for r in rows if r.bs_flag == 0) # 主动买 buy = sum(r.vol for r in rows if r.bs_flag == 0) # 主动买
sell = sum(r.vol for r in rows if r.bs_flag == 1) # 主动卖 sell = sum(r.vol for r in rows if r.bs_flag == 1) # 主动卖
@@ -113,15 +112,26 @@ async def review_transactions(code: str, ymd: int):
## 财务因子快照 ## 财务因子快照
```python ```python
async def finance_snapshot(codes): async def finance_snapshot(symbols):
async with TdxData() as td: async with TdxData() as td:
for mkt, code in codes: for fin in await td.get_finance(symbols): # 标准通道,最新快照
fin = await td.get_finance(mkt, code) # 标准通道,最新快照 print(fin.symbol, fin)
if fin:
print(code, fin)
``` ```
历史专业财报(`gpcw*.zip`,含多报告期)走文件接口: 历史专业财报(`gpcw*`,含多报告期)走文件接口。
!!! warning "索引里的文件名与服务器实际不一致"
`tdxfin/gpcw.txt` 索引里写的是 `gpcwYYYYMMDD.zip`,但服务器实际只提供**未压缩的**
`tdxfin/gpcwYYYYMMDD.dat` —— 这些差异已由 `get_financial_records_parsed()` 内部处理,
直接把索引里的 `filename` 传进去即可。
另外索引里**含有尚未生成的占位条目**(`filesize` 只有百来字节),取它们会得到空列表。
想拿最新一期可用数据,先按体积过滤:
```python
usable = [fi for fi in infos if fi.filesize > 500_000] # 排除占位条目
records = await td.get_financial_records_parsed(usable[0].filename)
```
```python ```python
async def history_financials(code: str): async def history_financials(code: str):
@@ -173,14 +183,14 @@ async def snapshot_blocks():
```python ```python
async def ex_markets(): async def ex_markets():
async with TdxData() as td: async with TdxData() as td:
hk = await td.get_kline(ExMarket.HK_MAIN_BOARD, "00700", KlinePeriod.DAY, count=700) hk = await td.get_bars("hk00700", KlinePeriod.DAY, count=700)
us = await td.get_kline(ExMarket.US_STOCK, "AAPL", KlinePeriod.DAY, count=700) us = await td.get_bars("usAAPL", KlinePeriod.DAY, count=700)
fut = await td.get_kline(ExMarket.CFFEX_FUTURES, "IFL0", KlinePeriod.DAY, count=700) fut = await td.get_bars("cffex:IFL0", KlinePeriod.DAY, count=700)
opt = await td.get_kline(ExMarket.SH_STOCK_OPTION, "10010971", KlinePeriod.DAY, count=700) opt = await td.get_bars("sh_stock_option:10010971", KlinePeriod.DAY, count=700)
print(len(hk), len(us), len(fut), len(opt)) print(len(hk), len(us), len(fut), len(opt))
# 港股全量逐笔(自动翻页,≤50 页 / 9 万条) # 港股全量逐笔(自动翻页,≤50 页 / 9 万条)
ticks = await td.get_goods_transaction_all(ExMarket.HK_MAIN_BOARD, "00700") ticks = await td.get_ticks("hk00700", count=None)
print(len(ticks)) print(len(ticks))
``` ```
@@ -191,9 +201,9 @@ async def ex_markets():
```python ```python
import pandas as pd import pandas as pd
async def to_dataframe(code: str): async def to_dataframe(symbol: str):
async with TdxData() as td: async with TdxData() as td:
bars = await td.get_kline(Market.SH, code, KlinePeriod.DAY, count=800) bars = await td.get_bars(symbol, KlinePeriod.DAY, count=800)
df = pd.DataFrame([{ df = pd.DataFrame([{
"dt": b.datetime, "open": b.open, "high": b.high, "dt": b.datetime, "open": b.open, "high": b.high,
"low": b.low, "close": b.close, "vol": b.vol, "amount": b.amount, "low": b.low, "close": b.close, "vol": b.vol, "amount": b.amount,
@@ -219,10 +229,10 @@ async def lifespan(app: FastAPI):
app = FastAPI(lifespan=lifespan) app = FastAPI(lifespan=lifespan)
@app.get("/kline/{code}") @app.get("/kline/{symbol}")
async def kline(code: str, request: Request): async def kline(symbol: str, request: Request):
td = request.app.state.td td = request.app.state.td
bars = await td.get_kline(Market.SH, code, KlinePeriod.DAY, count=30) bars = await td.get_bars(symbol, KlinePeriod.DAY, count=30)
return [{"dt": str(b.datetime), "close": b.close} for b in bars] return [{"dt": str(b.datetime), "close": b.close} for b in bars]
``` ```
+50 -9
View File
@@ -19,7 +19,8 @@
| SH | `000001` | 上证指数 | | SH | `000001` | 上证指数 |
| SZ | `000001` | 平安银行 | | SZ | `000001` | 平安银行 |
代码不唯一,**市场 + 代码**才唯一。这也是为什么所有接口的第一个参数都是 `market`。 代码不唯一,**市场 + 代码**才唯一。统一接口用**字符串标的**把两者一起表达
(`sh000001` / `sz000001`),避免只写 6 位数字时的歧义。
??? question "为什么报价格式有时候是 2 位小数,有时候是 3 位?" ??? question "为什么报价格式有时候是 2 位小数,有时候是 3 位?"
价格小数位按**品种**推断:股票 2 位,指数 / ETF / 可转债 3 位。 价格小数位按**品种**推断:股票 2 位,指数 / ETF / 可转债 3 位。
@@ -28,17 +29,40 @@
## 连接与网络 ## 连接与网络
??? question "连不上服务器 / 全部超时怎么办?" ??? question "连不上服务器 / 全部超时怎么办?"
服务器可用性会随时间变化(下线、换 IP、封禁)。按顺序排查: 服务器可用性会随时间变化(下线、换 IP、封禁)。本包**当日首次启动会自动后台测速**并把
可达主机按延迟排序缓存,多数情况下无需手工干预。按顺序排查:
1. 重新探测:`python -m pytdxdata.server_probe` 1. **删掉当日测速缓存**,让下次启动重新测速——缓存里可能存着今天刚挂掉的节点
2. 手工指定清单绕过探测结果: (路径见 [安装与配置](getting-started.md#当日自动测速无感))。
```python 2. 手工指定主机。优先级最高,**直接跳过测速与缓存**:
async with TdxData(standard_servers=[("1.2.3.4", 7709)]) as td: ... ```bash
PYPYTDX_DATA_STANDARD_HOSTS=1.2.3.4,5.6.7.8 python your_script.py
``` ```
3. 检查出口网络策略——标准 / MAC 端口 **7709**、EX 端口 **7727** 需要放通。
4. 若在用代理软件,注意有些本地代理会劫持回环 TCP,导致 asyncio 建事件循环都卡住 或在代码里传入(**只填主机名**,端口由 `port=` 统一指定):
```python
async with TdxData(standard_servers=["1.2.3.4"]) as td: ...
```
3. 离线重生成随包清单(该脚本会真实拉一段 K 线,剔除「握手正常但返回空」的坏节点):
```bash
python -m pytdxdata.server_probe
```
4. 检查出口网络策略——标准 / MAC 端口 **7709**、EX 端口 **7727** 需要放通。
5. 若在用代理软件,注意有些本地代理会劫持回环 TCP,导致 asyncio 建事件循环都卡住
(见下方「在 Windows 上测试卡死」)。 (见下方「在 Windows 上测试卡死」)。
??? question "启动时会变慢吗?会不会在后台偷偷联网?"
会有一次**当日首次启动测速**,但完全在后台,对调用方无感:
- **不阻塞** `start()`、**不打印**任何东西、失败**静默降级**(绝不抛给调用方)
- 结果只缓存到用户级目录(**不写安装目录**),**当天后续启动直接复用、不再重测**
- 覆盖**全部候选**主机(含暂时被挤下去的),所以「上次慢、这次快」的节点能回来
三个开关:`PYPYTDX_DATA_DISABLE_PROBE=1` 关掉测速、
`PYPYTDX_DATA_CACHE_DIR` 改缓存位置、
`PYPYTDX_DATA_{STANDARD,MAC,EX}_HOSTS` 强制指定主机。
详见 [安装与配置 → 当日自动测速](getting-started.md#当日自动测速无感)。
??? question "公司网络 / 代理环境下失败" ??? question "公司网络 / 代理环境下失败"
通达信协议是裸 TCP,不走 HTTP 代理。如果环境强制走代理,需要把 `7709` / `7727` 通达信协议是裸 TCP,不走 HTTP 代理。如果环境强制走代理,需要把 `7709` / `7727`
配成直连(bypass)。云服务器上常见问题是安全组只放通了 80/443。 配成直连(bypass)。云服务器上常见问题是安全组只放通了 80/443。
@@ -49,7 +73,7 @@
| 场景 | 建议 | | 场景 | 建议 |
|---|---| |---|---|
| 偶发查询、CLI | 默认即可 | | 偶发查询、CLI | 默认即可 |
| 批量落库(`*_batch`) | `pool_max=16`、`concurrency=8~16` | | 批量落库(`get_bars` 传多标的) | `pool_max=16`、`concurrency=8~16` |
| Web 服务多并发 | `pool_max=24`,并确保单实例复用 | | Web 服务多并发 | `pool_max=24`,并确保单实例复用 |
再大只是排队,不会更快——瓶颈是对端服务器的连接上限。 再大只是排队,不会更快——瓶颈是对端服务器的连接上限。
@@ -75,6 +99,23 @@
2. **是否含未收盘的那根** —— 盘中最后一根是动态的 2. **是否含未收盘的那根** —— 盘中最后一根是动态的
3. 分钟线注意**数据来源深度**不同 3. 分钟线注意**数据来源深度**不同
??? question "美股分钟 K 线的时间为什么跨了两个日期?"
**已在上游修好(v0.6.2)**。通达信 EX 通道对美股返回的原生时间戳把两个时区拼在一起:
日期分量是**美东交易日**、时分分量是**北京时间**。修复前,同一交易日的 390 根会全部
落在同一个北京自然日里,并且下午半场被排在上午半场**之前**。
现在 `SecurityBar.datetime` 已统一为**北京时间**(凌晨段日期自动 +1 天),可直接排序 /
过滤 / 做增量水位线。但要注意**美股一个交易日横跨两个北京自然日**:
```python
bars = await td.get_bars("usAAPL", KlinePeriod.MIN_1, count=390)
print(bars[0].datetime, bars[-1].datetime) # 2026-10-12 21:31:00 → 2026-10-13 04:00:00
print({b.trading_date for b in bars}) # {'2026-10-12'} —— 同一个交易日
```
按**交易日**聚合(分钟线合成日线、日内统计)请用 `b.trading_date`,不要用
`b.datetime.date()`。A股 / 港股 / 期货原始即为北京时间,不受影响。
??? question "缓存会不会返回过期数据?" ??? question "缓存会不会返回过期数据?"
缓存按数据类型分级 TTL,不会返回超出 TTL 的数据: 缓存按数据类型分级 TTL,不会返回超出 TTL 的数据:
+45 -2
View File
@@ -96,12 +96,16 @@ asyncio.run(main())
```python ```python
async with TdxData( async with TdxData(
standard_servers=[("1.2.3.4", 7709), ("5.6.7.8", 7709)], standard_servers=["1.2.3.4", "5.6.7.8"],
mac_servers=[("9.10.11.12", 7709)], mac_servers=["9.10.11.12"],
port=7709,
) as td: ) as td:
... ...
``` ```
主机元素**只填主机名**,端口由构造参数 `port=` 统一指定(不写在主机元素里)。
等价的免代码写法是环境变量 `PYPYTDX_DATA_STANDARD_HOSTS` / `…_MAC_HOSTS`(逗号分隔)。
## 服务器清单 ## 服务器清单
内置清单随包发布(`src/pytdxdata/servers.json`),由探测脚本生成: 内置清单随包发布(`src/pytdxdata/servers.json`),由探测脚本生成:
@@ -121,6 +125,45 @@ from pytdxdata.config import get_standard_hosts, get_mac_hosts, get_ex_hosts
print(len(get_standard_hosts()), len(get_mac_hosts()), len(get_ex_hosts())) print(len(get_standard_hosts()), len(get_mac_hosts()), len(get_ex_hosts()))
``` ```
### 当日自动测速(无感)
除随包发布的静态清单外,`TdxData` 还在**当日首次启动**时做一次**后台全量测速**:
- 覆盖**全部候选**(包内清单 ∪ 代码内置常量 ∪ 环境变量覆盖),而不是只测当前池里的少数节点
——否则「上次慢、这次快」的节点永远捞不回来
- 用**真实 K 线命令**判定可达(标准 / MAC / EX 各发一条业务命令并要求非空),
能剔除「握手正常但返回空数据」的坏节点
- 结果按**实测延迟升序**写入**用户级缓存**,当天后续启动直接复用、**不再重测**
- 全程在后台进行:**不打印、不阻塞 `start()`、失败静默降级**,对调用方完全无感
缓存位置(可用 `PYPYTDX_DATA_CACHE_DIR` 覆盖):
| 平台 | 路径 |
|---|---|
| Windows | `%LOCALAPPDATA%\pytdxdata\hosts-today.json` |
| macOS | `~/Library/Caches/pytdxdata/hosts-today.json` |
| Linux / 其他 | `$XDG_CACHE_HOME/pytdxdata/hosts-today.json`(默认 `~/.cache/…`) |
主机选择的优先级(各协议独立):
1. `PYPYTDX_DATA_STANDARD_HOSTS` / `…_MAC_HOSTS` / `…_EX_HOSTS` 环境变量(手工指定,最高优先)
2. **当日测速缓存**中该协议实测可达的主机(按延迟升序)
3. 包内清单里 `status=ok` 的 `fast_pool` 主机
4. 包内清单里 `status=ok` 的主机
5. 代码内置常量
!!! note "缓存绝不写回安装目录"
测速结果只写入上面的**用户级缓存目录**。`site-packages` 在容器 / 系统级安装 / `pipx`
下可能只读,多用户共用一个安装时还会互相覆盖,因此包内 `servers.json` 不会被运行时改写。
环境变量一览:
| 变量 | 作用 |
|---|---|
| `PYPYTDX_DATA_STANDARD_HOSTS` / `…_MAC_HOSTS` / `…_EX_HOSTS` | 逗号分隔,手工指定主机(优先级最高,直接跳过测速缓存) |
| `PYPYTDX_DATA_CACHE_DIR` | 覆盖当日测速缓存目录 |
| `PYPYTDX_DATA_DISABLE_PROBE=1` | 关闭当日测速与缓存(CI / 测试用,保证确定性) |
## 生命周期 ## 生命周期
`TdxData` 必须在 `async with` 内使用,或手动 `await td.start()` / `await td.close()`: `TdxData` 必须在 `async with` 内使用,或手动 `await td.start()` / `await td.close()`:
+7 -5
View File
@@ -20,7 +20,7 @@ from pytdxdata.models import KlinePeriod
async def main(): async def main():
async with TdxData() as td: # 自动探测服务器 + 建池 + 建缓存 async with TdxData() as td: # 自动探测服务器 + 建池 + 建缓存
bars = await td.get_kline(1, "600000", KlinePeriod.DAY, count=2400) bars = await td.get_bars("sh600000", KlinePeriod.DAY, count=2400)
print(bars[-1].datetime, bars[-1].close) print(bars[-1].datetime, bars[-1].close)
asyncio.run(main()) asyncio.run(main())
@@ -34,8 +34,8 @@ asyncio.run(main())
| 🗄️ **双层 TTL 缓存** | 内存 LRU + 磁盘 SQLite(WAL);TTL 分级:报价 5s / 分钟K线 60s / 日线当天 / 复权K线 1天 / 历史逐笔永久;`single-flight` 同键并发去重;缓存「已解析记录」,重复请求 0 网络 0 解析 | | 🗄️ **双层 TTL 缓存** | 内存 LRU + 磁盘 SQLite(WAL);TTL 分级:报价 5s / 分钟K线 60s / 日线当天 / 复权K线 1天 / 历史逐笔永久;`single-flight` 同键并发去重;缓存「已解析记录」,重复请求 0 网络 0 解析 |
| ⚡ **并发分页** | 把大请求拆成显式 `start` 偏移的页,多连接并行拉取、按序拼接、失败换连接重试 | | ⚡ **并发分页** | 把大请求拆成显式 `start` 偏移的页,多连接并行拉取、按序拼接、失败换连接重试 |
| 🔀 **双通道整合** | 标准通道(经典行情)+ MAC 通道(逐笔 / 复权 / 1分钟K线),按命令自动选路 | | 🔀 **双通道整合** | 标准通道(经典行情)+ MAC 通道(逐笔 / 复权 / 1分钟K线),按命令自动选路 |
| 📄 **服务器文件解析** | 板块 `block_*.dat` / 行业 `tdxhy.cfg` / 历史财报 `gpcw*.zip` **下载即解析**成 dataclass(纯 stdlib),无需自己拆二进制 | | 📄 **服务器文件解析** | 板块 `block_*.dat` / 行业 `tdxhy.cfg` / 历史财报 `gpcw*` **下载即解析**成 dataclass(纯 stdlib),无需自己拆二进制;文件名与索引不一致时自动纠正 |
| 🚀 **批量下载** | `get_kline_batch` / `get_minute_batch`,多股票自动并发,连接池分配到不同服务器 | | 🚀 **批量下载** | `get_bars` / `get_minutes` 传标的列表即多股票并发,连接池自动分配到不同服务器 |
| 📦 **零重型依赖** | 返回 `list[dataclass]`,pandas / polars 由调用方按需转换 | | 📦 **零重型依赖** | 返回 `list[dataclass]`,pandas / polars 由调用方按需转换 |
## 从这里开始 ## 从这里开始
@@ -70,7 +70,7 @@ asyncio.run(main())
--- ---
51 个数据方法(另有 `start` / `close`),从 docstring 实时生成,不会过期。 28 个统一方法(+ 33 个 deprecated 别名),从 docstring 实时生成,不会过期。
[:octicons-arrow-right-24: API 参考](api/index.md) [:octicons-arrow-right-24: API 参考](api/index.md)
@@ -104,7 +104,8 @@ asyncio.run(main())
## 数据来源与限制 ## 数据来源与限制
- 行情来自通达信**公开**行情服务器(无需账号),**15 分钟延时**;需实时数据请使用券商行情 - 行情来自通达信**公开**行情服务器(无需账号),**15 分钟延时**;需实时数据请使用券商行情
- 服务器清单由 `python -m pytdxdata.server_probe` 探测生成,可用性随时间变化 - 服务器清单由 `python -m pytdxdata.server_probe` 探测生成;运行时**当日首次启动会自动在后台测速并缓存**
(对调用方无感,当天不再重测),可用性随时间变化
- 港股 / 美股 / 期货 / 期权走通达信 EX 通道(端口 7727),部分市场(美股期权、港股期权)协议内无数据 - 港股 / 美股 / 期货 / 期权走通达信 EX 通道(端口 7727),部分市场(美股期权、港股期权)协议内无数据
完整清单见 [常见问题](faq.md)。 完整清单见 [常见问题](faq.md)。
@@ -138,6 +139,7 @@ asyncio.run(main())
- [AI 助手接入](ai.md) - [AI 助手接入](ai.md)
- [常见问题](faq.md) - [常见问题](faq.md)
- [更新日志](changelog.md) - [更新日志](changelog.md)
- [接口重构审查](refactor-audit.md)
- [参与贡献](contributing.md) - [参与贡献](contributing.md)
</div> </div>
+7 -6
View File
@@ -6,7 +6,7 @@
```mermaid ```mermaid
flowchart TD flowchart TD
A["api.py — TdxData<br/>唯一对外入口,51 个公开方法"] --> B["router.py<br/>按命令选通道"] A["api.py — TdxData<br/>唯一对外入口,28 个统一方法 + 33 个废弃别名"] --> B["router.py<br/>按命令选通道"]
B --> C["pool/ — 动态连接池<br/>标准池 / MAC 池 / EX 池"] B --> C["pool/ — 动态连接池<br/>标准池 / MAC 池 / EX 池"]
B --> D["scheduler/ — 并发分页调度<br/>Paginator"] B --> D["scheduler/ — 并发分页调度<br/>Paginator"]
C --> E["protocol/ — 协议层<br/>帧 / 变长整数 / 价格 / 日期 / 命令"] C --> E["protocol/ — 协议层<br/>帧 / 变长整数 / 价格 / 日期 / 命令"]
@@ -21,8 +21,9 @@ flowchart TD
``` ```
src/pytdxdata/ src/pytdxdata/
├── api.py # 统一接口 TdxData(对外唯一入口) ├── api.py # 统一接口 TdxData(对外唯一入口)
├── symbols.py # 标的解析:字符串 → Symbol(parse_symbol / format_symbol / market_targets)
├── router.py # 标准 / MAC / EX 通道选路 ├── router.py # 标准 / MAC / EX 通道选路
├── config.py # 服务器清单加载(servers.json) ├── config.py # 服务器清单加载 + 选路优先级链 + 用户级测速缓存路径
├── indicator.py # 技术指标(纯函数,无依赖) ├── indicator.py # 技术指标(纯函数,无依赖)
├── server_probe.py # 服务器探测,可 python -m 运行 ├── server_probe.py # 服务器探测,可 python -m 运行
├── protocol/ # 协议层 ├── protocol/ # 协议层
@@ -38,7 +39,7 @@ src/pytdxdata/
│ ├── pool.py # 标准 / MAC 动态池 │ ├── pool.py # 标准 / MAC 动态池
│ ├── ex_pool.py # EX 池 │ ├── ex_pool.py # EX 池
│ ├── health.py # 健康分与选路 │ ├── health.py # 健康分与选路
│ └── probe_cache.py # 探测结果缓存 │ └── probe_cache.py # 当日全量测速 + 用户级缓存(后台、无感)
├── scheduler/ ├── scheduler/
│ └── paginator.py # 并发分页调度(3 连接并行) │ └── paginator.py # 并发分页调度(3 连接并行)
├── cache/ ├── cache/
@@ -55,7 +56,7 @@ src/pytdxdata/
└── financial.py # gpcw.txt / gpcw*.zip └── financial.py # gpcw.txt / gpcw*.zip
``` ```
## 一次 `get_kline` 的完整路径 ## 一次 `get_bars` 的完整路径
```mermaid ```mermaid
sequenceDiagram sequenceDiagram
@@ -66,7 +67,7 @@ sequenceDiagram
participant P as pool/ participant P as pool/
participant S as scheduler/ participant S as scheduler/
U->>A: get_kline(SH, 600000, DAY, count=2400) U->>A: get_bars("sh600000", DAY, count=2400)
A->>A: 规范化缓存键 A->>A: 规范化缓存键
A->>C: 查缓存 A->>C: 查缓存
alt 命中 alt 命中
@@ -99,7 +100,7 @@ sequenceDiagram
|---|---| |---|---|
| **零运行时依赖** | 用 `socket` / `zlib` / `struct` / `sqlite3` / `asyncio` 全部搞定,避免依赖地狱和版本冲突 | | **零运行时依赖** | 用 `socket` / `zlib` / `struct` / `sqlite3` / `asyncio` 全部搞定,避免依赖地狱和版本冲突 |
| **返回 `list[dataclass]`** | 不让调用方被 pandas 绑架;需要 DataFrame 自己转一行 | | **返回 `list[dataclass]`** | 不让调用方被 pandas 绑架;需要 DataFrame 自己转一行 |
| **API 向后兼容** | 新增能力用新方法名(`get_block_parsed` 而不是改 `get_block_info` 的返回类型),老代码永不失效 | | **API 向后兼容** | 一个数据类型收敛为一个跨市场统一方法;旧方法名保留为 deprecated 别名(1.0 移除),老代码在兼容窗口内仍可用 |
## 下一步 ## 下一步
+6 -5
View File
@@ -44,7 +44,7 @@
# 100 个协程同时请求同一只股票的同一段 K 线 # 100 个协程同时请求同一只股票的同一段 K 线
# → 只发 1 次网络请求 # → 只发 1 次网络请求
results = await asyncio.gather(*[ results = await asyncio.gather(*[
td.get_kline(Market.SH, "600000", KlinePeriod.DAY, count=800) td.get_bars("sh600000", KlinePeriod.DAY, count=800)
for _ in range(100) for _ in range(100)
]) ])
``` ```
@@ -81,11 +81,11 @@ results = await asyncio.gather(*[
EWMA(指数加权移动平均)延迟让选路对「最近变慢」敏感,而不是被历史均值拖住。 EWMA(指数加权移动平均)延迟让选路对「最近变慢」敏感,而不是被历史均值拖住。
### 为什么 MAC 池更小 ### MAC 通道的单台连接上限
MAC 通道可用服务器只有数台(见 [通道与数据源](routing.md#server-groups)), `mac_pool_cap` 默认 `4`,与标准池的 `std_pool_cap` 一致——这是**对端单台连接限制**,
所以 `mac_pool_cap` 默认只有 `4`——这是**对端限制**,不是本项目的选择。 不是本项目的选择。两个通道的可用台数见 [通道与数据源](routing.md#server-groups):
逐笔 / 分时的并发能力天然弱于日线,原因就在这里。 实测可达台数会随服务器上下线变化,以**当日测速缓存**为准。
## 并发分页 ## 并发分页
@@ -110,4 +110,5 @@ count=2400 → 3 页 → 3 个连接并行 → 按序拼接
## 下一步 ## 下一步
- [架构总览](architecture.md) — 这些模块在整体里的位置 - [架构总览](architecture.md) — 这些模块在整体里的位置
- [通道与数据源](routing.md#daily-probe) — 服务器是怎么选出来的(当日测速缓存)
- [常见问题](../faq.md) — 缓存与超时的排查 - [常见问题](../faq.md) — 缓存与超时的排查
+55 -10
View File
@@ -20,7 +20,7 @@
| 港股 / 美股 / 期货 / 期权 | **EX**(7727) | 完全不同的协议栈 | | 港股 / 美股 / 期货 / 期权 | **EX**(7727) | 完全不同的协议栈 |
!!! note "只请求,不改语义" !!! note "只请求,不改语义"
路由是**内部实现细节**。同一个 `get_kline()` 调用,传不传 `adjust` 会走不同通道, 路由是**内部实现细节**。同一个 `get_bars()` 调用,传不传 `adjust` 会走不同通道,
但返回类型和字段完全一致——你不需要写 `if adjust:` 分支。 但返回类型和字段完全一致——你不需要写 `if adjust:` 分支。
## 三组服务器 {#server-groups} ## 三组服务器 {#server-groups}
@@ -29,10 +29,13 @@
| 池 | 数量级 | 用途 | | 池 | 数量级 | 用途 |
|---|---|---| |---|---|---|
| **标准池** | 数十台 | 报价 / K线 / 列表 / 财务 | | **标准池** | 9 台 | 报价 / K线 / 列表 / 财务 |
| **MAC 池** | 数台 | 逐笔 / 分时 / 复权 / 板块 / 资金流 | | **MAC 池** | 22 台 | 逐笔 / 分时 / 复权 / 板块 / 资金流 |
| **EX 池** | 4 台 | 港股 / 美股 / 期货 / 期权 | | **EX 池** | 4 台 | 港股 / 美股 / 期货 / 期权 |
> 上表为 2026-09-21 离线探针(`python -m pytdxdata.server_probe --discover`)实测**可达**台数。
> 服务器会下线、换 IP 或变更协议,**实际台数以当日测速缓存为准**(见下方「运行时:当日测速缓存」)。
EX 池内部还要再分两类,因为握手方式不同: EX 池内部还要再分两类,因为握手方式不同:
| 类型 | 数量 | 握手 | | 类型 | 数量 | 握手 |
@@ -42,7 +45,7 @@ EX 池内部还要再分两类,因为握手方式不同:
这就是 `config.get_ex_handshakes()` 存在的原因——EX 的 4 台机器不是同一种握手。 这就是 `config.get_ex_handshakes()` 存在的原因——EX 的 4 台机器不是同一种握手。
MAC 池远小于标准池,这也解释了为什么逐笔 / 分时的并发能力天然弱于日线。 注意 MAC 池实测**并不比标准池小**(22 台 vs 9 台)。早期版本曾按「MAC 可用节点很少」来解释逐笔 / 分时并发弱于日线,实测已推翻该前提——两者的单台连接上限(`mac_pool_cap` / `std_pool_cap`)默认相同,都是 `4`。
## 为什么这些服务器会被「探测」 ## 为什么这些服务器会被「探测」
@@ -51,12 +54,56 @@ MAC 池远小于标准池,这也解释了为什么逐笔 / 分时的并发能
`server_probe` 的探测逻辑**不是只看 TCP 连通性**,而是真实请求一段 K 线并校验内容: `server_probe` 的探测逻辑**不是只看 TCP 连通性**,而是真实请求一段 K 线并校验内容:
```bash ```bash
python -m pytdxdata.server_probe python -m pytdxdata.server_probe # 按申报协议全量探测
python -m pytdxdata.server_probe --discover # 三种协议全测,并据实修正 protocols
python -m pytdxdata.server_probe --group ex # 只测 EX
python -m pytdxdata.server_probe --refresh # 只重测当前 status=ok 的
``` ```
普通「只 ping 握手」的探测会把这类坏节点放进来,症状是**偶发的空返回**—— 普通「只 ping 握手」的探测会把这类坏节点放进来,症状是**偶发的空返回**——
比直接连不上更难查。所以探测必须校验数据。 比直接连不上更难查。所以探测必须校验数据。
写回字段:`status` / `latency` / `checked_at` / `checked_date` / `fast_pool`,
以及顶层 `version` / `checked_date` / `note`。其中 `fast_pool` 与运行时缓存里的 `fast`
用同一条规则(整体延迟前 10 名,或延迟 < 200ms),用于**还没有当日缓存时**的冷启动排序。
### 为什么需要 `--discover`
「申报协议」会过期。实测(2026-09-21)有一批服务器的 **`0x010C` 标准 K 线变成空响应
(返回 2 字节空壳),但同端口同主机的 `0x122E` MAC 帧正常**——它们从 `standard` 退化成了
`mac`-only。只测申报协议的话,这类退化永远发现不了,标准池会一直含着一批死节点。
`--discover` 对每台主机把三种协议都测一遍,并据实测结果重写 `protocols`;
配套两个必须处理的细节:
- **失败必须重试一次**再判定不支持。单次抖动会误删协议,而 `protocols` 被收窄后不会自动恢复。
- **EX 握手模式**申报可能错,探测失败时换另一种(`login` ⇄ `setup`)再试。
- 无任何协议可达时**不动 `protocols`**,只把 `status` 置 `fail`——保留"它申报过什么"的信息。
- 顺带剔除 `ip` 非法的脏记录(历史遗留如 `"s1"`)。
## 运行时:当日测速缓存 {#daily-probe}
`python -m pytdxdata.server_probe` 是**离线**重生成随包清单的工具;运行时还有一条**在线**的
轻量路径——`TdxData.start()` 会异步触发一次全量测速,把结果缓存到**用户级目录**
(`…/pytdxdata/hosts-today.json`),当天后续启动直接复用,不再重测。
设计与几个必须踩对的点:
| 关注点 | 正确做法 | 反例(会静默出错) |
|---|---|---|
| 候选集 | 取**全部候选**(清单 ∪ 常量 ∪ env) | 只把「当前池成员」丢给探针 → 上次慢的节点永远捞不回来 |
| 可达判定 | 发**真实 K 线命令**并要求非空 | 只握手 / 只读报文头 → 测不出「空响应」坏节点 |
| 写盘位置 | 用户级缓存目录 | 写回包内 `servers.json` → 容器只读、多用户互相覆盖 |
| 对调用方 | 后台 task + debug 日志 + 绝不抛异常 | 在 `start()` 里 `await` 或打印 → 启动变慢、污染用户输出 |
| 并发 | 进程内单例 + `asyncio.Lock` | 三个池各测一遍 → 三倍流量 |
| 写入 | 临时文件 + `os.replace` 原子替换 | 直接覆写 → 并发进程读到半截 JSON |
全部不可达时**不写缓存**——否则「今天全挂了」会被缓存一整天,明天也不重试。
缓存存在时,`config.get_standard_hosts()` 等按**实测延迟升序**返回该协议的可达主机;
缓存缺失 / 跨日 / 版本不符 / 已损坏时,才回落到包内清单。开关见
[安装与配置 → 环境变量](../getting-started.md#当日自动测速无感)。
## EX 通道细节 ## EX 通道细节
- 端口固定 **7727**,与标准 / MAC 的 7709 不同 - 端口固定 **7727**,与标准 / MAC 的 7709 不同
@@ -66,13 +113,11 @@ python -m pytdxdata.server_probe
- 美股期权 / 港股期权**协议内无数据** - 美股期权 / 港股期权**协议内无数据**
```python ```python
from pytdxdata.models import ExMarket, KlinePeriod await td.get_bars("hk00700", KlinePeriod.DAY, count=700)
await td.get_bars("usAAPL", KlinePeriod.DAY, count=700)
await td.get_kline(ExMarket.HK_MAIN_BOARD, "00700", KlinePeriod.DAY, count=700)
await td.get_kline(ExMarket.US_STOCK, "AAPL", KlinePeriod.DAY, count=700)
``` ```
`ExMarket` 的完整成员见 [枚举速查](../api/enums.md#exmarket)。 扩展市场用字符串前缀(`hk` / `us` / `cffex` …)指定;`ExMarket` 的完整成员见 [枚举速查](../api/enums.md#exmarket)。
## 下一步 ## 下一步
+41 -17
View File
@@ -14,11 +14,11 @@ pip install pytdxdata # 或 uv add pytdxdata;要求 Python >= 3.11
```python ```python
import asyncio import asyncio
from pytdxdata import TdxData from pytdxdata import TdxData
from pytdxdata.models import KlinePeriod, Market from pytdxdata.models import KlinePeriod
async def main(): async def main():
async with TdxData() as td: # 自动探测服务器、建连接池、初始化缓存 async with TdxData() as td: # 自动探测服务器、建连接池、初始化缓存
bars = await td.get_kline(Market.SH, "600000", KlinePeriod.DAY, count=2400) bars = await td.get_bars("sh600000", KlinePeriod.DAY, count=2400)
print(bars[-1].datetime, bars[-1].close) print(bars[-1].datetime, bars[-1].close)
asyncio.run(main()) asyncio.run(main())
@@ -26,10 +26,11 @@ asyncio.run(main())
## 心智模型(AI 必读) ## 心智模型(AI 必读)
1. **入口只有一个类**:`TdxData`。所有数据获取都是它的公开异步方法(51 个数据方法, 1. **入口只有一个类**:`TdxData`。所有数据获取都是它的公开异步方法(v0.6 起为 **28 个统一方法**,
另有 `start()` / `close()` 生命周期方法),必须在 `async with` 内使用。 另有 33 个 deprecated 别名与 `start()` / `close()` 生命周期方法),必须在 `async with` 内使用。
2. **标的需要「市场 + 代码」两个参数**。同一个 6 位代码在不同市场含义不同: 2. **标的用字符串**,形如 `sz000001` / `sh600000` / `hk00700` / `usAAPL` / `cffex:IFL0`。
`(SH, "000001")` 是上证指数,`(SZ, "000001")` 是平安银行。 同一个 6 位代码在不同市场含义不同:`sh000001` 是上证指数,`sz000001` 是平安银行;
裸 6 位数字(如 `000001`)视为沪市指数。统一接口不再接受 `(market, code)` 元组。
3. **枚举取值没有直觉,必须用枚举成员,不要写数字字面量**: 3. **枚举取值没有直觉,必须用枚举成员,不要写数字字面量**:
- `Market`: SZ=0 / SH=1 / BJ=2 - `Market`: SZ=0 / SH=1 / BJ=2
- `KlinePeriod`: MIN_5=0, MIN_15=1, MIN_30=2, MIN_60=3, **DAY=4**, WEEK=5, MONTH=6, **MIN_1=7**, MIN_3=8, YEAR=9, SEASON=10, YEAR_ALT=11 - `KlinePeriod`: MIN_5=0, MIN_15=1, MIN_30=2, MIN_60=3, **DAY=4**, WEEK=5, MONTH=6, **MIN_1=7**, MIN_3=8, YEAR=9, SEASON=10, YEAR_ALT=11
@@ -39,19 +40,37 @@ asyncio.run(main())
5. **实例要复用**:连接池与缓存都挂在 `TdxData` 实例上。长驻进程(Web 服务)应只创建一个实例, 5. **实例要复用**:连接池与缓存都挂在 `TdxData` 实例上。长驻进程(Web 服务)应只创建一个实例,
不要每请求新建,否则等于每请求重建连接池且缓存全部失效。 不要每请求新建,否则等于每请求重建连接池且缓存全部失效。
## 主要能力分组 ## 主要能力分组(统一接口)
- **K 线**:`get_kline`(主接口,自动并发分页、支持复权与日期区间)、`get_kline_batch`(多股票并发)、 标的一律用字符串;以下均为 v0.6 统一接口,跨市场自动选路。
`get_kline_since`(增量)、`get_index_kline`、`get_stock_kline_with_indicators`
- **报价**:`get_quotes`(五档,>80 只自动切批)、`get_stock_quotes_list`、`get_market_stat` - **标的清单**:`get_universe`(A股 + 港股 + 美股 + 期货/期权)
- **逐笔 / 分时**:`get_transactions`(含 `trade_count` 成交笔数,支持历史日期)、`get_minute`、`get_minute_batch` - **K 线**:`get_bars`(自动并发分页、支持复权与日期区间、多标的并发)
- **证券列表**:`get_security_count`、`get_security_list`、`get_security_list_all` - **技术指标**:`get_indicators`(K线 + MACD/KDJ/RSI/BOLL/MA/EMA)
- **报价**:`get_quotes`(五档,>80 只自动切批)、`get_snapshot`(个股特征)、`get_market_stat`
- **逐笔 / 分时**:`get_ticks`(含 `trade_count`,支持历史日期)、`get_minutes`(`sampling=True` 取缩略采样)
- **财务 / 除权**:`get_finance`(最新快照)、`get_xdxr`、`get_price_limits`(本地计算涨跌停) - **财务 / 除权**:`get_finance`(最新快照)、`get_xdxr`、`get_price_limits`(本地计算涨跌停)
- **板块**:`get_board_list`、`get_board_members`、`get_board_ranking`、`get_board_change_ranking`、`get_belong_board` - **F10**:`get_f10`(公司资料目录 + 正文)
- **服务器文件(下载 + 解析一步到位)**:`get_block_parsed`(板块成分)、`get_industry_map`(通达信+申万行业)、 - **板块**:`get_boards`、`get_board_members`、`get_board_of`、`get_board_summary`、
`get_financial_file_infos`、`get_financial_records_parsed`(历史专业财报) `get_board_ranking`、`get_board_change_ranking`
- **扩展市场**:`get_goods_list`、`get_goods_quotes`、`get_goods_transaction_all` 等,配合 `ExMarket` 使用 - **服务器文件(下载 + 解析一步到位)**:`get_file`(原始字节)、`get_block_parsed`(板块成分)、
- **批量**:`get_kline_batch` / `get_minute_batch`,多股票并发且连接池会分配到不同服务器 `get_industry_map`(通达信+申万行业)、`get_financial_file_infos`、`get_financial_records_parsed`(历史专业财报)
> 旧的分通道/市场方法(`get_kline` / `get_transactions` / `get_goods_*` 等共 33 个)保留为
> deprecated 别名,1.0 移除;完整对照见[接口重构审查](https://openbot-coder.github.io/pytdxdata/refactor-audit/)与 CHANGELOG。
## 服务器与配置
服务器主机来源有一条优先级链(各协议独立):环境变量 → **当日测速缓存** → 包内清单
`fast_pool` → 包内清单 → 代码内置常量。
- `TdxData.start()` 会在**当日首次启动**后台触发一次全量测速,用**真实 K 线命令**判定可达
(不是只握手),结果按延迟升序写入**用户级缓存**(Windows `%LOCALAPPDATA%\pytdxdata`、
macOS `~/Library/Caches/pytdxdata`、Linux `$XDG_CACHE_HOME/pytdxdata`),当天复用、不再重测。
- 该操作对调用方**完全无感**:后台执行、不打印、不阻塞 `start()`、失败静默降级。
运行时**绝不改写包内 `servers.json`**。
- 环境变量:`PYPYTDX_DATA_STANDARD_HOSTS` / `…_MAC_HOSTS` / `…_EX_HOSTS`(逗号分隔,手工指定,最高优先)、
`PYPYTDX_DATA_CACHE_DIR`(覆盖缓存目录)、`PYPYTDX_DATA_DISABLE_PROBE=1`(关闭测速)。
## CLI ## CLI
@@ -74,6 +93,10 @@ tdx financial gpcw20260331.zip --limit 5
- **`KlinePeriod.MIN_1` 走 MAC 通道并单连接串行分页**,这是刻意设计:并发分页在多服务器 - **`KlinePeriod.MIN_1` 走 MAC 通道并单连接串行分页**,这是刻意设计:并发分页在多服务器
历史深度不一致时会产生非确定性数据空洞。不要试图"优化"成并发。 历史深度不一致时会产生非确定性数据空洞。不要试图"优化"成并发。
- **复权 K 线走 MAC 通道**,标准通道不提供复权数据。 - **复权 K 线走 MAC 通道**,标准通道不提供复权数据。
- **K 线 `datetime` 统一为北京时间**(v0.6.2 起)。美股原始报文的日期分量是美东交易日、
时分分量是北京时间,库已自动归一化,`bar.datetime` 可直接排序 / 比较 / 过滤。
但**美股一个交易日横跨两个北京自然日**:按交易日聚合(分钟线合成日线、日内统计)
用 `bar.trading_date`,不要用 `bar.datetime.date()`。`bar.is_us` 判定美股。
- **标准通道部分服务器在 `count < 100` 时返回空**,分页器已强制 `min_page=100` 规避。 - **标准通道部分服务器在 `count < 100` 时返回空**,分页器已强制 `min_page=100` 规避。
- **本地 Windows 上 `asyncio.new_event_loop()` 可能永久挂起**,根因是回环 `socket.socketpair()` - **本地 Windows 上 `asyncio.new_event_loop()` 可能永久挂起**,根因是回环 `socket.socketpair()`
被本地代理/安全软件拦截。异步测试请在 Linux/WSL 运行。 被本地代理/安全软件拦截。异步测试请在 Linux/WSL 运行。
@@ -102,6 +125,7 @@ tdx financial gpcw20260331.zip --limit 5
- [SKILL.md](https://raw.githubusercontent.com/openbot-coder/pytdxdata/main/SKILL.md):面向 AI **编程**助手的技能文件(必守约定 / 枚举取值表 / 决策表 / 陷阱清单),比本文件更适合指导写代码 - [SKILL.md](https://raw.githubusercontent.com/openbot-coder/pytdxdata/main/SKILL.md):面向 AI **编程**助手的技能文件(必守约定 / 枚举取值表 / 决策表 / 陷阱清单),比本文件更适合指导写代码
- [完整接口清单](https://openbot-coder.github.io/pytdxdata/API_REFERENCE/):手工维护的全量清单,含参数默认值 - [完整接口清单](https://openbot-coder.github.io/pytdxdata/API_REFERENCE/):手工维护的全量清单,含参数默认值
- [接口重构审查](https://openbot-coder.github.io/pytdxdata/refactor-audit/):统一接口 / 废弃别名全清单 + 数据一致性与遗漏对账
- [更新日志](https://github.com/openbot-coder/pytdxdata/blob/main/CHANGELOG.md) - [更新日志](https://github.com/openbot-coder/pytdxdata/blob/main/CHANGELOG.md)
- [GitHub 仓库](https://github.com/openbot-coder/pytdxdata) - [GitHub 仓库](https://github.com/openbot-coder/pytdxdata)
- [PyPI](https://pypi.org/project/pytdxdata/) - [PyPI](https://pypi.org/project/pytdxdata/)
+148
View File
@@ -0,0 +1,148 @@
# 接口重构审查报告
> 范围:v0.6 统一接口重构(`TdxData` 对外方法 51 → 63)的**数据一致性**与**遗漏审查**。
> 结论基于对旧实现(`git show HEAD:src/pytdxdata/api.py`)与新实现的逐字段 / 逐方法对照。
## 一、结论速览
| 维度 | 结论 |
|------|------|
| 数据一致性(旧接口 vs 统一接口) | ✅ 55 条断言全部通过,无字段差异 |
| 方法丢失 | ✅ 无。旧 53 个公开方法 100% 保留 |
| 文档覆盖 | ✅ `scripts/check_docs.py` 三条硬约束通过 |
| 标的写法 | ✅ 统一接口一律只接受字符串,已无元组软兼容 |
| 公开方法计数 | `28 统一 + 33 别名 + start/close = 63` |
---
## 二、数据一致性(旧接口 vs 新统一接口)
逐字段对照 24+ 组、**55 条断言全部通过**,覆盖:
- K 线(各周期 / 复权 / 日期区间)
- 实时报价(五档 bid/ask、买卖量、涨跌停价)
- 逐笔成交(含 `trade_count`)
- 分时
- 除权除息
- 财务快照
- F10(目录 + 正文)
- 服务器文件(板块 / 行业 / 财报)
- 板块(列表 / 成员 / 归属 / 汇总 / 排行)
唯一 1 条「失败」经核实为 **mock 假象**:`security_count` 的 mock 返回固定值 100,而
`get_universe` 走真实分页逻辑,两者口径不同;**并非真实数据差异**,逐字段比较全部相等。
---
## 三、遗漏审查(方法级)
对旧 / 新 `api.py` 的公开方法集合做 AST 级 diff:
| 指标 | 数量 |
|------|------|
| 旧公开方法 | 53(51 数据 + `start` / `close`) |
| 新公开方法 | 63(61 数据 + `start` / `close`) |
| **旧有新无(丢失)** | **0** |
| 新增 | 10(全部为统一入口) |
**数值闭合**:
- `28 统一 + 33 废弃别名 + start/close = 63`
- `18 旧名升级 + 33 转别名 = 51 旧数据方法`
- `51 旧 + 10 新入口 = 61 数据方法`
---
## 四、统一接口清单(28 个数据接口)
标的写法:`"sz000001"` / `"hk00700"` / `"usAAPL"` / `"cffex:IFL0"`;裸 6 位数字 = 沪市指数。
### 4.1 新入口(10,v0.6 新增)
| 方法 | 签名 | 返回 | 吸收的旧接口 |
|------|------|------|--------------|
| `get_universe` | `(market=None)` | `list[SecurityInfo]` | get_security_count / get_security_list / get_security_list_all / get_goods_list / get_goods_count |
| `get_bars` | `(symbols, period=DAY, *, start=0, count=800, adjust=None, start_date=None, end_date=None, concurrency=6)` | `list[SecurityBar]` | get_kline / get_kline_since / get_kline_batch / get_index_kline |
| `get_indicators` | `(symbols, indicators, *, period=DAY, count=30, adjust=None, params=None)` | `list[IndicatorSet]` | get_stock_kline_with_indicators |
| `get_ticks` | `(symbols, *, date=None, start=0, count=None, concurrency=6)` | `list[TransactionRecord]` | get_transactions / get_goods_transaction / get_goods_transaction_all |
| `get_minutes` | `(symbols, *, date=None, sampling=False, concurrency=6)` | `list[MinuteBar]` | get_minute / get_minute_batch / get_chart_sampling / get_goods_chart_sampling / get_goods_tick_chart |
| `get_snapshot` | `(symbols)` | `list[SymbolSnapshot]` | get_symbol_info |
| `get_f10` | `(symbol, section=None, *, offset=0, length=65535)` | `list \| str` | get_company_info_category / get_company_info_content |
| `get_file` | `(name)` | `bytes` | get_block_info / get_report_file / get_file_meta / download_file / get_financial_file_list / get_financial_records |
| `get_boards` | `(kind="all", *, count=10000)` | `list[BoardInfo]` | get_board_list |
| `get_board_of` | `(symbols)` | `list[BelongBoard]` | get_belong_board |
### 4.2 旧名升级(18,同名泛化为统一接口)
| 方法 | 签名 | 返回 |
|------|------|------|
| `get_quotes` | `(symbols, *, fields=None)` | `list[SecurityQuote]` |
| `get_auction` | `(symbols)` | `list[AuctionItem]` |
| `get_capital_flow` | `(symbols)` | `list[CapitalFlow]` |
| `get_xdxr` | `(symbols)` | `list[XdxrRecord]` |
| `get_finance` | `(symbols)` | `list[FinanceRecord]` |
| `get_price_limits` | `(symbol, name=None, pre_close=None, listed_days=9999)` | `tuple[float\|None, float\|None]` |
| `get_market_stat` | `()` | `MarketStat` |
| `get_unusual` | `(market="all", *, start=0, count=600)` | `list[UnusualItem]` |
| `get_server_info` | `()` | `ServerInfo` |
| `get_kline_offset` | `(offset=0, count=1)` | `tuple[int, int]` |
| `get_board_members` | `(board, count=100000, sort_type=0, *, fields=None)` | `list[SecurityQuote]` |
| `get_board_summary` | `(board)` | `dict` |
| `get_board_ranking` | `(kind="industry", *, top_n=20)` | `list[dict]` |
| `get_board_change_ranking` | `(kind="industry", *, days=20, top_n=20)` | `list[dict]` |
| `get_block_parsed` | `(filename)` | `list[TdxBlock]` |
| `get_industry_map` | `()` | `dict[str, IndustryInfo]` |
| `get_financial_file_infos` | `()` | `list[FinancialFileInfo]` |
| `get_financial_records_parsed` | `(filename)` | `list[FinancialRecord]` |
> 另有生命周期方法 `start()` / `close()`,合计 30 个非别名公开方法。
---
## 五、废弃别名清单(33 个,1.0 移除)
别名运行时发出 `DeprecationWarning`;**仍接受 `(market, code)` 写法**(这是别名与统一接口的关键差异)。
| 目标统一接口 | 数量 | 废弃别名 |
|--------------|------|----------|
| `get_bars` | 4 | `get_kline`、`get_kline_since`、`get_kline_batch`、`get_index_kline` |
| `get_indicators` | 1 | `get_stock_kline_with_indicators` |
| `get_quotes` | 3 | `get_stock_quotes`、`get_goods_quotes`、`get_goods_quotes_list` |
| `get_board_members` | 1 | `get_stock_quotes_list` |
| `get_ticks` | 3 | `get_transactions`、`get_goods_transaction`、`get_goods_transaction_all` |
| `get_minutes` | 3 | `get_minute`、`get_minute_batch`、`get_goods_tick_chart` |
| `get_minutes(sampling=True)` | 2 | `get_chart_sampling`、`get_goods_chart_sampling` |
| `get_universe` | 5 | `get_security_count`、`get_security_list`、`get_security_list_all`、`get_goods_list`、`get_goods_count` |
| `get_f10` | 2 | `get_company_info_category`、`get_company_info_content` |
| `get_file` | 4 | `get_block_info`、`get_report_file`、`get_file_meta`、`download_file` |
| `get_financial_file_infos` | 1 | `get_financial_file_list` |
| `get_financial_records_parsed` | 1 | `get_financial_records` |
| `get_boards` | 1 | `get_board_list` |
| `get_board_of` | 1 | `get_belong_board` |
| `get_snapshot` | 1 | `get_symbol_info` |
| **合计** | **33** | |
---
## 六、标的写法统一(字符串化)
统一接口**只接受字符串标的**,已移除所有 `(market, code)` 元组软兼容:
- 删除模块级 `_as_symbols()`;`get_quotes` / `get_xdxr` / `get_finance` / `get_auction` /
`get_capital_flow` 去掉 `code` 位置参数,统一走 `parse_symbols()`。
- `get_price_limits` 去掉 `(market, code, …)` 旧参形式检测。
- `get_unusual` 去掉整数市场号检测。
- 调用方(CLI、示例)同步改为字符串;`get_finance` / `get_capital_flow` 的返回类型改为 `list`。
!!! note "保留项"
`get_boards(kind)` 仍接受数字板块类别(`0/1/2/3`)。这是**板类别选择器**、非标的,
文档已明示「也接受数字」,旧别名 `get_board_list(board_type=0)` 依赖它。
---
## 七、验证
- `pytest`:**127 passed**(审查当时的快照;当前基线为 164 passed)。其中 `tests/test_all_interfaces.py` 为全接口回归:mock 连接逐个
调用 63 个公开方法,并以「覆盖哨兵」断言无遗漏(7 条告警为别名测试的预期 `DeprecationWarning`)。
- `scripts/check_docs.py`:`MUST_LIST_ALL` + `MUST_NOT_BE_STALE` 全部 `[OK]`。
- 签名核对:统一接口签名与返回类型与本文一致;全仓无 `_as_symbols` 及元组式调用残留。
+5 -4
View File
@@ -4,18 +4,19 @@
python examples/quickstart.py python examples/quickstart.py
说明:数据来自通达信公开行情服务器(无需账号,15 分钟延时)。 说明:数据来自通达信公开行情服务器(无需账号,15 分钟延时)。
标的一律用字符串(``sh600000`` / ``sz000001`` / ``hk00700`` / ``usAAPL`` / ``cffex:IFL0``)。
""" """
import asyncio import asyncio
from pytdxdata import KlinePeriod, Market, TdxData from pytdxdata import TdxData
async def main() -> None: async def main() -> None:
# TdxData 为异步上下文管理器:进入时建连,退出时释放 # TdxData 为异步上下文管理器:进入时建连,退出时释放
async with TdxData() as td: async with TdxData() as td:
# 1) 批量五档报价(可一次传多只,超过 80 只自动切批) # 1) 批量五档报价(可一次传多只,超过 80 只自动切批)
quotes = await td.get_quotes([(Market.SH, "600000"), (Market.SZ, "000001")]) quotes = await td.get_quotes(["sh600000", "sz000001"])
print("== 报价 ==") print("== 报价 ==")
for q in quotes: for q in quotes:
print( print(
@@ -24,7 +25,7 @@ async def main() -> None:
) )
# 2) 日K线(最近 10 根) # 2) 日K线(最近 10 根)
bars = await td.get_kline(Market.SH, "600000", KlinePeriod.DAY, count=10) bars = await td.get_bars("sh600000", count=10)
print("\n== 日K(最近 3 根)==") print("\n== 日K(最近 3 根)==")
for b in bars[-3:]: for b in bars[-3:]:
print( print(
@@ -33,7 +34,7 @@ async def main() -> None:
) )
# 3) 当日分时 # 3) 当日分时
minutes = await td.get_minute(Market.SH, "600000") minutes = await td.get_minutes("sh600000")
latest = minutes[-1].price if minutes else "-" latest = minutes[-1].price if minutes else "-"
print(f"\n== 分时 ==\n共 {len(minutes)} 个点,最新价={latest}") print(f"\n== 分时 ==\n共 {len(minutes)} 个点,最新价={latest}")
+1
View File
@@ -64,6 +64,7 @@ nav:
- 其他: - 其他:
- 常见问题: faq.md - 常见问题: faq.md
- 更新日志: changelog.md - 更新日志: changelog.md
- 接口重构审查: refactor-audit.md
- 参与贡献: contributing.md - 参与贡献: contributing.md
plugins: plugins:
+1 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "pytdxdata" name = "pytdxdata"
version = "0.5.0" version = "0.6.3"
description = "通达信(TongDaXin)行情数据客户端:动态连接池 + 双层TTL缓存 + 3连接并发分页,纯asyncio零运行时依赖,支持A股/港股/美股/期货/期权" description = "通达信(TongDaXin)行情数据客户端:动态连接池 + 双层TTL缓存 + 3连接并发分页,纯asyncio零运行时依赖,支持A股/港股/美股/期货/期权"
readme = "README.md" readme = "README.md"
requires-python = ">=3.11" requires-python = ">=3.11"
+4 -2
View File
@@ -32,12 +32,12 @@ PKG_DIR = ROOT / "src" / "pytdxdata"
# 必须**列全**所有公开方法的文档(漏写 = 漂移) # 必须**列全**所有公开方法的文档(漏写 = 漂移)
MUST_LIST_ALL = [ MUST_LIST_ALL = [
ROOT / "docs" / "api" / "index.md",
ROOT / "docs" / "API_REFERENCE.md", ROOT / "docs" / "API_REFERENCE.md",
] ]
# 只需**不提到已删除的方法**的文档: # 只需**不提到已删除的方法**的文档:
# 这些是入口 / 教程 / 精选清单,本来就不要求列全,但绝不能引用已不存在的方法 # 这些是入口 / 教程 / 精选清单 / 接口总览(只列推荐的统一接口,旧方法不强制列出),
# 但绝不能引用已不存在的方法
MUST_NOT_BE_STALE = [ MUST_NOT_BE_STALE = [
ROOT / "SKILL.md", ROOT / "SKILL.md",
ROOT / "README.md", ROOT / "README.md",
@@ -48,6 +48,8 @@ MUST_NOT_BE_STALE = [
ROOT / "docs" / "faq.md", ROOT / "docs" / "faq.md",
ROOT / "docs" / "cli.md", ROOT / "docs" / "cli.md",
ROOT / "docs" / "ai.md", ROOT / "docs" / "ai.md",
ROOT / "docs" / "api" / "index.md",
ROOT / "docs" / "refactor-audit.md",
] ]
+1 -1
View File
@@ -16,7 +16,7 @@ from .models import (
XdxrRecord, XdxrRecord,
) )
__version__ = "0.5.0" __version__ = "0.6.2"
__all__ = [ __all__ = [
"TdxData", "TdxData",
"Market", "Market",
+1365 -919
View File
File diff suppressed because it is too large. Load diff
+8 -3
View File
@@ -40,7 +40,12 @@ class CacheKey:
) )
@classmethod @classmethod
def quote_key(cls, stocks: Sequence[tuple[int, str]]) -> "CacheKey": def quote_key(cls, stocks: Sequence[tuple[int, str]],
"""报价键:对股票集规范化排序,顺序无关可命中。""" tag: str = "") -> "CacheKey":
"""报价键:对股票集规范化排序,顺序无关可命中。
``tag`` 区分取数口径(标准五档 / MAC·EX 字段位),不同口径不互相命中。
"""
norm = sorted(f"{m}:{c}" for m, c in stocks) norm = sorted(f"{m}:{c}" for m, c in stocks)
return cls(category="quote", extra=",".join(norm)) extra = ",".join(norm)
return cls(category="quote", extra=f"{tag}#{extra}" if tag else extra)
+19 -55
View File
@@ -111,26 +111,17 @@ def _pct(price: float, pre: float) -> str:
# ------------------------------------------------------------------ # # ------------------------------------------------------------------ #
async def cmd_quotes(td: TdxData, symbols: list[str]) -> None: async def cmd_quotes(td: TdxData, symbols: list[str]) -> None:
cn, ex = [], [] quotes = await td.get_quotes(symbols)
for sym in symbols: for q in quotes:
s = parse_symbol(sym) _print_quote(q)
if s.kind == "cn":
cn.append((Market(s.market), s.code))
else:
ex.append((s.market, s.code))
for q in await td.get_quotes(cn):
_print_cn_quote(q)
if ex:
from .protocol.commands.ex_proto import GetExInstrumentQuoteCmd
for market, code in ex:
q = await td._execute_ex(GetExInstrumentQuoteCmd(market, code))
_print_ex_quote(market, code, q)
def _print_cn_quote(q) -> None: def _print_quote(q) -> None:
pct = (q.price / q.pre_close - 1) * 100 if q.pre_close else 0 pct = (q.price / q.pre_close - 1) * 100 if q.pre_close else 0
mkt = {31: "港股", 74: "美股"}.get(q.market, "")
print("=" * 58) print("=" * 58)
print(" %s %s" % (q.code, q.server_time or datetime.now().strftime("%H:%M:%S"))) label = "%s %s" % (mkt, q.code) if mkt else "%s %s" % (q.code, q.server_time or datetime.now().strftime("%H:%M:%S"))
print(" %s" % label)
print(" 最新 %-10.2f 涨跌 %+8.2f (%+.2f%%)" % (q.price, q.price - q.pre_close, pct)) print(" 最新 %-10.2f 涨跌 %+8.2f (%+.2f%%)" % (q.price, q.price - q.pre_close, pct))
print(" 今开 %-10.2f 最高 %.2f 最低 %.2f" % (q.open, q.high, q.low)) print(" 今开 %-10.2f 最高 %.2f 最低 %.2f" % (q.open, q.high, q.low))
print(" 昨收 %-10.2f 成交量 %s 成交额 %s" % (q.pre_close, _fmt_num(q.vol), _fmt_num(q.amount))) print(" 昨收 %-10.2f 成交量 %s 成交额 %s" % (q.pre_close, _fmt_num(q.vol), _fmt_num(q.amount)))
@@ -144,31 +135,9 @@ def _print_cn_quote(q) -> None:
print() print()
def _print_ex_quote(market: int, code: str, q: dict | None) -> None:
if not q:
print(" %s: 无报价数据" % code)
return
price, pre = q.get("price") or 0, q.get("pre_close") or 0
mkt = {31: "港股", 74: "美股"}.get(market, "扩展")
print("=" * 58)
print(" %s %s" % (mkt, code))
print(" 最新 %-10.2f 涨跌 %+8.2f (%s)" % (price, price - pre, _pct(price, pre)))
print(" 今开 %-10.2f 最高 %.2f 最低 %.2f" % (
q.get("open") or 0, q.get("high") or 0, q.get("low") or 0))
print(" 昨收 %-10.2f 总量 %s" % (pre, _fmt_num(q.get("zongliang") or 0)))
print()
async def cmd_kline(td: TdxData, sym: str, period: KlinePeriod, count: int, async def cmd_kline(td: TdxData, sym: str, period: KlinePeriod, count: int,
start: int, adjust: Adjust) -> None: start: int, adjust: Adjust) -> None:
s = parse_symbol(sym) bars = await td.get_bars(sym, period, start=start, count=count, adjust=adjust)
if s.kind == "cn":
bars = await td.get_kline(Market(s.market), s.code, period, start=start,
count=count, adjust=adjust)
elif s.kind == "index":
bars = await td.get_index_kline(Market(s.market), s.code, period, start=start, count=count)
else:
bars = await td.get_kline(ExMarket(s.market), s.code, period, start=start, count=count)
print("%s K线 (%s, %d根):" % (sym, period.name, len(bars))) print("%s K线 (%s, %d根):" % (sym, period.name, len(bars)))
print(" %-12s %8s %8s %8s %8s %12s" % ("日期", "开盘", "最高", "最低", "收盘", "成交量")) print(" %-12s %8s %8s %8s %8s %12s" % ("日期", "开盘", "最高", "最低", "收盘", "成交量"))
for b in bars: for b in bars:
@@ -256,8 +225,7 @@ async def cmd_list(td: TdxData, market: str, count: int) -> None:
async def cmd_auction(td: TdxData, sym: str) -> None: async def cmd_auction(td: TdxData, sym: str) -> None:
s = parse_symbol(sym) items = await td.get_auction(sym)
items = await td.get_auction(Market(s.market), s.code)
print("%s 集合竞价 (%d条):" % (sym, len(items))) print("%s 集合竞价 (%d条):" % (sym, len(items)))
for a in items: for a in items:
print(" %s 价格=%.3f 量=%d %s" % ( print(" %s 价格=%.3f 量=%d %s" % (
@@ -266,7 +234,7 @@ async def cmd_auction(td: TdxData, sym: str) -> None:
async def cmd_unusual(td: TdxData, market: str, count: int) -> None: async def cmd_unusual(td: TdxData, market: str, count: int) -> None:
items = await td.get_unusual(MARKET_NAMES[market], count=count) items = await td.get_unusual(market, count=count)
print("市场异动 (%d条):" % len(items)) print("市场异动 (%d条):" % len(items))
for u in items: for u in items:
print(" %s %s %s" % (getattr(u, "code", ""), getattr(u, "name", ""), print(" %s %s %s" % (getattr(u, "code", ""), getattr(u, "name", ""),
@@ -274,8 +242,7 @@ async def cmd_unusual(td: TdxData, market: str, count: int) -> None:
async def cmd_xdxr(td: TdxData, sym: str) -> None: async def cmd_xdxr(td: TdxData, sym: str) -> None:
s = parse_symbol(sym) items = await td.get_xdxr(sym)
items = await td.get_xdxr(Market(s.market), s.code)
print("%s 除权除息 (%d条):" % (sym, len(items))) print("%s 除权除息 (%d条):" % (sym, len(items)))
for x in items[:20]: for x in items[:20]:
print(" %s 送%g 配%g 派%g" % ( print(" %s 送%g 配%g 派%g" % (
@@ -284,23 +251,20 @@ async def cmd_xdxr(td: TdxData, sym: str) -> None:
async def cmd_finance(td: TdxData, sym: str) -> None: async def cmd_finance(td: TdxData, sym: str) -> None:
s = parse_symbol(sym) fins = await td.get_finance(sym)
f = await td.get_finance(Market(s.market), s.code) if not fins:
if not f:
print("无财务数据") print("无财务数据")
return return
for k, v in asdict(f).items(): for k, v in asdict(fins[0]).items():
print(" %-24s %s" % (k, v)) print(" %-24s %s" % (k, v))
async def cmd_flow(td: TdxData, sym: str) -> None: async def cmd_flow(td: TdxData, sym: str) -> None:
s = parse_symbol(sym) flows = await td.get_capital_flow(sym)
f = await td.get_capital_flow(Market(s.market), s.code) if not flows:
if isinstance(f, dict): print("无资金流向数据")
items = f.items() return
else: for k, v in asdict(flows[0]).items():
items = asdict(f).items()
for k, v in items:
print(" %-20s %s" % (k, v)) print(" %-20s %s" % (k, v))
+59 -3
View File
@@ -17,13 +17,19 @@
""" """
from __future__ import annotations from __future__ import annotations
import io
import struct import struct
import zipfile
from ..models import FinancialFileInfo, FinancialRecord from ..models import FinancialFileInfo, FinancialRecord
_HEADER_FMT = "<1hI1H3L" _HEADER_FMT = "<1hI1H3L"
_INDEX_FMT = "<6sBL" _INDEX_FMT = "<6sBL"
_HEADER_SIZE = struct.calcsize(_HEADER_FMT)
_INDEX_SIZE = struct.calcsize(_INDEX_FMT)
_ZIP_MAGIC = b"PK\x03\x04"
def parse_financial_file_list(data: bytes) -> list[FinancialFileInfo]: def parse_financial_file_list(data: bytes) -> list[FinancialFileInfo]:
"""解析 tdxfin/gpcw.txt 内容(每行 ``filename,md5hash,filesize``)。""" """解析 tdxfin/gpcw.txt 内容(每行 ``filename,md5hash,filesize``)。"""
@@ -46,8 +52,58 @@ def parse_financial_file_list(data: bytes) -> list[FinancialFileInfo]:
return out return out
def looks_like_gpcw_dat(data: bytes) -> bool:
"""粗略判定字节流是否为 gpcw ``.dat``(校验 20 字节 header 的自洽性)。
用于把「真的取到了财报数据」与「服务器对不存在的文件名回的 0/1 字节空壳」区分开:
空壳要么长度不足、要么 header 全零,一律判否。
Args:
data: 待判定的字节流。
Returns:
可疑时返回 True。
"""
if len(data) < _HEADER_SIZE:
return False
_unknown, _date, max_count, _u1, report_size, _u2 = struct.unpack(
_HEADER_FMT, data[:_HEADER_SIZE]
)
if max_count <= 0 or report_size <= 0 or report_size % 4 != 0:
return False
# 索引区必须放得下 max_count 条 11 字节条目
return _HEADER_SIZE + max_count * _INDEX_SIZE <= len(data)
def extract_gpcw_dat(data: bytes) -> bytes:
"""从「zip 包」或「未压缩 dat」中取出 ``.dat`` 字节;无法识别时返回 ``b""``。
服务器**实际只提供未压缩的** ``tdxfin/gpcwYYYYMMDD.dat``,而 ``tdxfin/gpcw.txt``
索引里写的是 ``gpcwYYYYMMDD.zip``,因此两种形态都要能走通。
Args:
data: zip 包字节或未压缩 ``.dat`` 字节。
Returns:
内层 / 原始的 ``.dat`` 字节;不是有效财报数据时返回 ``b""``。
"""
if not data:
return b""
if data.startswith(_ZIP_MAGIC):
try:
with zipfile.ZipFile(io.BytesIO(data)) as zf:
names = [n for n in zf.namelist() if n.lower().endswith(".dat")]
if not names:
return b""
inner = zf.read(names[0])
except (zipfile.BadZipFile, OSError, KeyError):
return b""
return inner if looks_like_gpcw_dat(inner) else b""
return data if looks_like_gpcw_dat(data) else b""
def parse_financial_dat(data: bytes, report_date: int = 0) -> list[FinancialRecord]: def parse_financial_dat(data: bytes, report_date: int = 0) -> list[FinancialRecord]:
"""解析 gpcw*.zip 内的 .dat 二进制。 """解析 gpcw ``.dat`` 二进制(zip 内的或服务器直接给的未压缩形式都行)。
Args: Args:
data: .dat 文件完整字节。 data: .dat 文件完整字节。
@@ -56,7 +112,7 @@ def parse_financial_dat(data: bytes, report_date: int = 0) -> list[FinancialReco
Returns: Returns:
FinancialRecord 列表;数据不足或字段非法时返回空列表。 FinancialRecord 列表;数据不足或字段非法时返回空列表。
""" """
header_size = struct.calcsize(_HEADER_FMT) header_size = _HEADER_SIZE
if len(data) < header_size: if len(data) < header_size:
return [] return []
@@ -72,7 +128,7 @@ def parse_financial_dat(data: bytes, report_date: int = 0) -> list[FinancialReco
if num_fields <= 0: if num_fields <= 0:
return [] return []
index_size = struct.calcsize(_INDEX_FMT) index_size = _INDEX_SIZE
report_fmt = f"<{num_fields}f" report_fmt = f"<{num_fields}f"
report_pack_size = struct.calcsize(report_fmt) report_pack_size = struct.calcsize(report_fmt)
+178 -13
View File
@@ -1,12 +1,28 @@
"""服务器清单与默认配置 """服务器清单与默认配置
服务器清单存于包内 servers.json,由 server_probe.py 导入时自动探测可用性与延时。 服务器清单存于包内 ``servers.json`` —— 它是**随包分发的基线清单,运行期只读**。
config.py 加载时只采用 status="ok" 的服务器;环境变量可覆盖;代码内嵌清单为兜底。 每日首次启动的后台测速结果写入**用户级缓存目录**,运行期优先采用当日实测结果。
主机选取优先级(每个协议独立)::
环境变量 PYPYTDX_DATA_*_HOSTS > 当日测速缓存 > 包内清单 fast_pool
> 包内清单 ok > 代码内嵌常量
相关环境变量:
- ``PYPYTDX_DATA_CACHE_DIR`` 覆盖用户级缓存目录(默认见 :func:`probe_cache_dir`)
- ``PYPYTDX_DATA_DISABLE_PROBE`` 置真值时既不读当日缓存也不测速(CI / 测试用,保证确定性)
为什么不把测速结果写回包内 ``servers.json``:安装目录可能是只读的(容器 / 系统级
site-packages / pipx),且多用户共用一份安装时彼此覆盖,运行期改写分发数据本身也不妥。
""" """
from __future__ import annotations from __future__ import annotations
import ipaddress
import json import json
import os import os
import sys
from datetime import date
from pathlib import Path from pathlib import Path
DEFAULT_PORT = 7709 DEFAULT_PORT = 7709
@@ -14,19 +30,29 @@ DEFAULT_TIMEOUT = 10.0
_SERVERS_FILE = Path(__file__).resolve().parent / "servers.json" # 包内清单(随包分发) _SERVERS_FILE = Path(__file__).resolve().parent / "servers.json" # 包内清单(随包分发)
# 当日测速缓存(结构变更时递增,旧版本缓存自动失效)
PROBE_CACHE_VERSION = 1
_PROBE_CACHE_NAME = "hosts-today.json"
# ---------- 包内清单(只读基线) ----------
def _read_servers_json() -> dict:
"""读取包内清单;文件缺失 / 内容损坏 / 顶层非对象 → 空 dict。"""
try:
cfg = json.loads(_SERVERS_FILE.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return cfg if isinstance(cfg, dict) else {}
def _load_ok_hosts(protocol: str, *, fast_only: bool = False) -> list[str]: def _load_ok_hosts(protocol: str, *, fast_only: bool = False) -> list[str]:
"""从 servers.json 加载 status=ok 且支持指定协议的服务器。 """从 servers.json 加载 status=ok 且支持指定协议的服务器。
fast_only=True 时只返回当日测速入池(fast_pool)的服务器(排名前N或延迟<阈值), fast_only=True 时只返回测速入池(fast_pool)的服务器(排名前N或延迟<阈值),
用于动态连接池优先使用优质节点。 用于动态连接池优先使用优质节点。
""" """
try:
cfg = json.loads(_SERVERS_FILE.read_text(encoding="utf-8"))
except (OSError, ValueError):
return []
out = [] out = []
for s in cfg.get("servers", []): for s in _read_servers_json().get("servers", []):
if s.get("status") != "ok": if s.get("status") != "ok":
continue continue
if protocol not in s.get("protocols", []): if protocol not in s.get("protocols", []):
@@ -38,13 +64,90 @@ def _load_ok_hosts(protocol: str, *, fast_only: bool = False) -> list[str]:
def _load_ex_handshakes() -> dict[str, str]: def _load_ex_handshakes() -> dict[str, str]:
try: """包内清单里 EX 服务器的握手模式。"""
cfg = json.loads(_SERVERS_FILE.read_text(encoding="utf-8")) return {s["ip"]: s.get("handshake", "setup")
except (OSError, ValueError): for s in _read_servers_json().get("servers", [])
return {}
return {s["ip"]: s.get("handshake", "setup") for s in cfg.get("servers", [])
if "ex" in s.get("protocols", []) and s.get("status") == "ok"} if "ex" in s.get("protocols", []) and s.get("status") == "ok"}
# ---------- 用户级当日测速缓存 ----------
def probe_cache_dir() -> Path:
"""用户级缓存目录(保证可写,绝不指向安装目录)。
``PYPYTDX_DATA_CACHE_DIR`` 可覆盖(测试指向临时目录)。按平台约定:
- Windows: ``%LOCALAPPDATA%\\pytdxdata``
- macOS: ``~/Library/Caches/pytdxdata``
- 其他: ``$XDG_CACHE_HOME/pytdxdata`` 或 ``~/.cache/pytdxdata``
"""
env = (os.environ.get("PYPYTDX_DATA_CACHE_DIR") or "").strip()
if env:
return Path(env).expanduser()
if os.name == "nt":
base = os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA")
return (Path(base) if base else Path.home() / "AppData" / "Local") / "pytdxdata"
if sys.platform == "darwin":
return Path.home() / "Library" / "Caches" / "pytdxdata"
base = os.environ.get("XDG_CACHE_HOME")
return (Path(base) if base else Path.home() / ".cache") / "pytdxdata"
def probe_cache_file() -> Path:
"""当日测速缓存文件路径(每次调用重新解析,便于测试改环境变量后立即生效)。"""
return probe_cache_dir() / _PROBE_CACHE_NAME
def probe_disabled() -> bool:
"""是否已通过 ``PYPYTDX_DATA_DISABLE_PROBE`` 关闭当日测速缓存。"""
return os.environ.get("PYPYTDX_DATA_DISABLE_PROBE", "").strip().lower() in {
"1", "true", "yes", "on",
}
def load_probe_cache(today: str | None = None,
path: str | Path | None = None) -> dict | None:
"""读取**当日**测速缓存;缺失 / 损坏 / 非今日 / 版本不符 → ``None``。
返回非 None 即表示"今天已经测过速了",调用方应直接复用而不再刷新。
``path`` 可显式指定缓存文件(默认 :func:`probe_cache_file`),便于注入与测试。
"""
if probe_disabled():
return None
target = Path(path) if path is not None else probe_cache_file()
try:
cfg = json.loads(target.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
if not isinstance(cfg, dict) or cfg.get("version") != PROBE_CACHE_VERSION:
return None
if str(cfg.get("date", "")) != (today or date.today().isoformat()):
return None
results = cfg.get("results")
if not isinstance(results, dict) or not results:
return None
return cfg
def _load_cached_hosts(protocol: str) -> list[str]:
"""当日测速缓存中该协议**实测可达**的主机,按延迟升序(越快越靠前)。"""
cfg = load_probe_cache()
if cfg is None:
return []
rows: list[tuple[float, str]] = []
for ip, per_proto in cfg["results"].items():
if not isinstance(per_proto, dict):
continue
lat = per_proto.get(protocol)
if isinstance(lat, bool) or not isinstance(lat, (int, float)):
continue
if lat < 0:
continue
rows.append((float(lat), str(ip)))
rows.sort(key=lambda kv: (kv[0], kv[1]))
return [ip for _, ip in rows]
# ---------- 代码内嵌兜底清单 ----------
# 标准行情服务器 —— 真实K线探测验证可用(2026-08-12, GetSecurityBarsCmd 600000 日K) # 标准行情服务器 —— 真实K线探测验证可用(2026-08-12, GetSecurityBarsCmd 600000 日K)
# 27台可用 = pytdxwrapper券商服务器(国泰君安/中信短线宝/华林/安信等) + 通达信官方主站 # 27台可用 = pytdxwrapper券商服务器(国泰君安/中信短线宝/华林/安信等) + 通达信官方主站
# 来源①: pytdxwrapper config.py TDX_HOSTS(券商+官方, 51台探测27可用) # 来源①: pytdxwrapper config.py TDX_HOSTS(券商+官方, 51台探测27可用)
@@ -91,10 +194,66 @@ EX_HANDSHAKES: dict[str, str] = {
} }
# ---------- 测速候选枚举 ----------
def is_valid_host(host: object) -> bool:
"""是否是可用作服务器地址的合法主机(IPv4/IPv6 字面量,或含点的域名)。
用于挡住测试 mock 混进来的伪主机名(如 ``"s1"``)被写进缓存 / 清单。
"""
if not isinstance(host, str):
return False
h = host.strip()
if not h or len(h) > 253 or any(c.isspace() for c in h):
return False
try:
ipaddress.ip_address(h)
return True
except ValueError:
pass
return "." in h and all(
part and part[0] != "-" and part[-1] != "-" and part.replace("-", "").isalnum()
for part in h.split(".")
)
def all_probe_candidates() -> dict[str, list[str]]:
"""[测速用] 返回 ``{协议: [候选主机]}`` 全量清单(已校验、去重、保序)。
来源 = 包内清单申报的协议 ∪ 代码内嵌常量 ∪ 环境变量覆盖。
与 ``get_*_hosts()`` 的关键区别:这里**不做 status / 延迟过滤**。
测速必须能看到全部候选,否则"上次慢、这次快"的节点永远捞不回来,
形成自指循环(只重测已在池里的少数节点,其余记录一直过期)。
"""
out: dict[str, list[str]] = {"standard": [], "mac": [], "ex": []}
for s in _read_servers_json().get("servers", []):
ip = s.get("ip")
for protocol in s.get("protocols", []):
if protocol in out:
out[protocol].append(ip)
out["standard"] += STANDARD_HOSTS
out["mac"] += MAC_HOSTS
out["ex"] += EX_HOSTS
for protocol, var in (("standard", "PYPYTDX_DATA_STANDARD_HOSTS"),
("mac", "PYPYTDX_DATA_MAC_HOSTS"),
("ex", "PYPYTDX_DATA_EX_HOSTS")):
env = os.environ.get(var)
if env:
out[protocol] += env.split(",")
return {
protocol: [h for h in dict.fromkeys(hosts) if is_valid_host(h)]
for protocol, hosts in out.items()
}
# ---------- 对外取主机 ----------
def get_standard_hosts() -> list[str]: def get_standard_hosts() -> list[str]:
env = os.environ.get("PYPYTDX_DATA_STANDARD_HOSTS") env = os.environ.get("PYPYTDX_DATA_STANDARD_HOSTS")
if env: if env:
return [h.strip() for h in env.split(",") if h.strip()] return [h.strip() for h in env.split(",") if h.strip()]
cached = _load_cached_hosts("standard")
if cached:
return cached
fast = _load_ok_hosts("standard", fast_only=True) fast = _load_ok_hosts("standard", fast_only=True)
if fast: if fast:
return fast return fast
@@ -106,6 +265,9 @@ def get_mac_hosts() -> list[str]:
env = os.environ.get("PYPYTDX_DATA_MAC_HOSTS") env = os.environ.get("PYPYTDX_DATA_MAC_HOSTS")
if env: if env:
return [h.strip() for h in env.split(",") if h.strip()] return [h.strip() for h in env.split(",") if h.strip()]
cached = _load_cached_hosts("mac")
if cached:
return cached
fast = _load_ok_hosts("mac", fast_only=True) fast = _load_ok_hosts("mac", fast_only=True)
if fast: if fast:
return fast return fast
@@ -117,6 +279,9 @@ def get_ex_hosts() -> list[str]:
env = os.environ.get("PYPYTDX_DATA_EX_HOSTS") env = os.environ.get("PYPYTDX_DATA_EX_HOSTS")
if env: if env:
return [h.strip() for h in env.split(",") if h.strip()] return [h.strip() for h in env.split(",") if h.strip()]
cached = _load_cached_hosts("ex")
if cached:
return cached
from_json = _load_ok_hosts("ex") from_json = _load_ok_hosts("ex")
return from_json or list(EX_HOSTS) return from_json or list(EX_HOSTS)
+97 -8
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import struct import struct
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import datetime from datetime import date, datetime, timedelta
from enum import IntEnum from enum import IntEnum
from typing import Any from typing import Any
@@ -92,9 +92,25 @@ class Adjust(IntEnum):
HFQ = 2 # 后复权 HFQ = 2 # 后复权
# 扩展市场中「时间戳跨时区拼接」的市场号:通达信 EX 通道对美股返回的分钟级 K线
# 里,日期字段是**美东交易日**、时分字段是**北京时间**,两个时区被拼进同一个
# 五元组,必须归一化(见 SecurityBar.__post_init__)。
_US_EX_MARKETS: frozenset[int] = frozenset({int(ExMarket.US_STOCK)})
# 归一化判据:北京时间 hour >= 12 的 bar 与美东交易日属同一自然日。美股常规时段
# 09:30~16:00 EDT = 北京 21:30~次日 04:00(冬令时 22:30~次日 05:00),夏令时/
# 冬令时下分界都稳定落在 12 点。
_US_DAY_SPLIT_HOUR = 12
@dataclass(slots=True) @dataclass(slots=True)
class SecurityBar: class SecurityBar:
"""K线记录(价格单位:元)""" """K线记录(价格单位:元)。跨市场统一模型(A股/港股/美股/期货共用)。
时间戳口径**统一为北京时间**:A股/港股/期货原始即为北京时间;美股原始是
「日期=美东交易日 + 时分=北京时间」的混合值,构造时已还原为真实北京时间
(见 ``__post_init__``)。该 bar 归属的交易日见 :attr:`trading_date`。
"""
market: int market: int
code: str code: str
open: float open: float
@@ -108,11 +124,42 @@ class SecurityBar:
day: int day: int
hour: int = 0 hour: int = 0
minute: int = 0 minute: int = 0
symbol: str = "" # 规范化标的串(sz000001 / hk00700),由 API 层填充
def __post_init__(self) -> None:
"""美股(EX 通道)时间戳归一化:还原成真实北京时间。
原始报文里 ``zipday`` 是**美东交易日**、``tminutes`` 是**北京时间分钟数**,
直拼出的 ``datetime`` 会把同一交易日的下午半场(北京 00:00~04:00)排到
上午半场(北京 21:30~23:59)**之前** —— 单日 390 根全部错位、首末颠倒。
这里把凌晨段(北京 hour < 12)的日期 +1 天,得到严格单调的北京时间序列。
"""
if self.market in _US_EX_MARKETS and self.hour < _US_DAY_SPLIT_HOUR:
d = date(self.year, self.month, self.day) + timedelta(days=1)
self.year, self.month, self.day = d.year, d.month, d.day
@property
def is_us(self) -> bool:
"""是否美股(EX 通道 ``US_STOCK``)。"""
return self.market in _US_EX_MARKETS
@property @property
def datetime(self) -> datetime: def datetime(self) -> datetime:
"""bar 的时刻(北京时间)。"""
return datetime(self.year, self.month, self.day, self.hour, self.minute) return datetime(self.year, self.month, self.day, self.hour, self.minute)
@property
def trading_date(self) -> str:
"""该 bar 归属的交易日,``YYYY-MM-DD``。
美股:``datetime`` 已还原为北京时间,凌晨段(北京 hour < 12)属于**前一天**
的美东交易日,故回退一天;A股/港股/期货的交易日即自然日。按交易日聚合
(如分钟线合成日线)时应当用本字段,而不是 ``datetime.date()``。
"""
if self.is_us and self.hour < _US_DAY_SPLIT_HOUR:
return (date(self.year, self.month, self.day) - timedelta(days=1)).isoformat()
return f"{self.year:04d}-{self.month:02d}-{self.day:02d}"
@dataclass(slots=True) @dataclass(slots=True)
class IndexBar(SecurityBar): class IndexBar(SecurityBar):
@@ -120,9 +167,26 @@ class IndexBar(SecurityBar):
pass pass
@dataclass(slots=True)
class IndicatorSet:
"""K线 + 技术指标组合(``TdxData.get_indicators`` 的返回单元)。
``indicators`` 里每个序列与 ``bars`` 等长、尾部对齐;预热期为 ``None`` 的指标
(如 BOLL 前三档)保留 ``None``。
"""
symbol: str
bars: list[SecurityBar] = field(default_factory=list)
indicators: dict[str, list[float | None]] = field(default_factory=dict)
@dataclass(slots=True) @dataclass(slots=True)
class SecurityQuote: class SecurityQuote:
"""实时五档报价""" """报价(跨市场统一模型)。
A股(标准通道):五档 ``bid``/``ask`` + 买卖量 + 涨跌停价齐全,``name`` 为空。
A股(``fields=[...]`` 走 MAC 0x122B):``name`` 与 ``fields`` 齐全,五档为空。
扩展市场(港股/美股/期货):``name`` + 基础价量在属性上,其余字段位在 ``fields``。
"""
market: int market: int
code: str code: str
price: float price: float
@@ -144,39 +208,51 @@ class SecurityQuote:
limit_down: float = 0.0 # 跌停价 limit_down: float = 0.0 # 跌停价
decimal_point: int = 2 # 价格小数位 decimal_point: int = 2 # 价格小数位
open_amount: float = 0.0 # 开盘金额(个股) open_amount: float = 0.0 # 开盘金额(个股)
symbol: str = "" # 规范化标的串
name: str = "" # 名称(仅 MAC/EX 通道有)
fields: dict[str, float] = field(default_factory=dict) # 原始字段位("0x7" 等)
@dataclass(slots=True) @dataclass(slots=True)
class SecurityInfo: class SecurityInfo:
"""证券列表条目""" """标的清单条目(跨市场统一模型:A股证券列表 + 扩展市场商品列表)"""
market: int market: int
code: str code: str
name: str name: str
volunit: int volunit: int
decimal_point: int decimal_point: int
pre_close: float pre_close: float
symbol: str = "" # 规范化标的串
kind: str = "" # 分类描述(扩展市场的 category/desc)
@dataclass(slots=True) @dataclass(slots=True)
class TransactionRecord: class TransactionRecord:
"""逐笔成交(MAC通道含 trade_count=成交笔数)""" """逐笔成交(跨市场统一模型;A股 MAC 通道含 trade_count=成交笔数)"""
market: int market: int
code: str code: str
time: str # HH:MM:SS time: str # HH:MM:SS(扩展市场为 HH:MM)
price: float price: float
vol: float # 手(MAC逐笔) vol: float # 手(MAC逐笔)
trade_count: int # 成交笔数(MAC=逐笔记录字段;标准当日逐笔协议也有但需单独解析) trade_count: int # 成交笔数(MAC=逐笔记录字段;标准当日逐笔协议也有但需单独解析)
bs_flag: int # 1=主动买 0=主动卖 bs_flag: int # 1=主动买 0=主动卖
symbol: str = ""
fields: dict[str, float] = field(default_factory=dict) # 扩展市场额外字段(增仓等)
@dataclass(slots=True) @dataclass(slots=True)
class MinuteBar: class MinuteBar:
"""分时数据""" """分时(跨市场统一模型;A股 MAC 0x122D / 扩展市场 0x122D 同构)"""
price: float price: float
vol: float vol: float
avg_price: float = 0.0 # 均价(协议第2字段) avg_price: float = 0.0 # 均价(协议第2字段)
hour: int = 0 hour: int = 0
minute: int = 0 minute: int = 0
symbol: str = ""
market: int = 0
code: str = ""
date: int = 0 # YYYYMMDD
fields: dict[str, float] = field(default_factory=dict) # 扩展市场额外字段(动量等)
@dataclass(slots=True) @dataclass(slots=True)
@@ -201,6 +277,7 @@ class XdxrRecord:
qian_zongguben: float = 0.0 qian_zongguben: float = 0.0
panhou_liutong: float = 0.0 panhou_liutong: float = 0.0
hou_zongguben: float = 0.0 hou_zongguben: float = 0.0
symbol: str = ""
@property @property
def date(self) -> str: def date(self) -> str:
@@ -248,6 +325,7 @@ class FinanceRecord:
weifen_lirun: float = 0.0 weifen_lirun: float = 0.0
meigujing_zichan: float = 0.0 meigujing_zichan: float = 0.0
reserve2: float = 0.0 reserve2: float = 0.0
symbol: str = ""
# ===== MAC 扩展命令模型 ===== # ===== MAC 扩展命令模型 =====
@@ -268,15 +346,21 @@ class BoardInfo:
symbol_price: float = 0.0 symbol_price: float = 0.0
symbol_rise_speed: float = 0.0 symbol_rise_speed: float = 0.0
symbol_pre_close: float = 0.0 symbol_pre_close: float = 0.0
symbol: str = "" # 规范化标的串(板块码,如 sh881001)
@dataclass(slots=True) @dataclass(slots=True)
class MemberQuote: class MemberQuote:
"""板块成分股报价(MAC自定义字段)""" """板块成分/自定义字段报价的**协议层原始记录**。
API 层会把它归一成 :class:`SecurityQuote`(``fields`` 原样保留、基础字段位
填进属性),所以普通调用不会看到本类。
"""
market: int market: int
code: str code: str
name: str name: str
fields: dict[str, float] = field(default_factory=dict) fields: dict[str, float] = field(default_factory=dict)
symbol: str = ""
@dataclass(slots=True) @dataclass(slots=True)
@@ -287,6 +371,7 @@ class BelongBoard:
board_name: str board_name: str
close: float close: float
pre_close: float pre_close: float
symbol: str = "" # 被查询的个股(非板块)
@dataclass(slots=True) @dataclass(slots=True)
@@ -296,6 +381,7 @@ class AuctionItem:
price: float price: float
matched: int matched: int
unmatched: int unmatched: int
symbol: str = ""
@dataclass(slots=True) @dataclass(slots=True)
@@ -308,6 +394,7 @@ class UnusualItem:
desc: str desc: str
value: float value: float
time: str time: str
symbol: str = ""
@dataclass(slots=True) @dataclass(slots=True)
@@ -328,6 +415,7 @@ class SymbolSnapshot:
amount: float amount: float
turnover: float turnover: float
avg_price: float avg_price: float
symbol: str = ""
@dataclass(slots=True) @dataclass(slots=True)
@@ -361,6 +449,7 @@ class CapitalFlow:
sell5: float sell5: float
big5: float big5: float
mid5: float mid5: float
symbol: str = ""
# ===== 服务器文件解析模型(板块/行业/历史专业财报) ===== # ===== 服务器文件解析模型(板块/行业/历史专业财报) =====
+81 -32
View File
@@ -1,4 +1,11 @@
"""EX扩展市场连接池(简化版:固定连接数,借还+坏连接重建+login自动)""" """EX扩展市场连接池(固定连接数,借还+坏连接重建+login自动)。
与标准池 pool.py 的背压语义对齐:acquire 在无空闲连接且无法扩容时,
基于 asyncio.Condition 排队等待 release 唤醒(默认 acquire_timeout=30s),
而不是快速失败。per_server_cap 限制单台服务器连接数;单服务器场景下
有效并发 = servers × per_server_cap(默认 1),通过 TdxData(ex_pool_cap=N)
可对同一 EX 主机开多连接。
"""
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
@@ -9,6 +16,23 @@ from .ex_connection import ExTdxConnection
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
DEFAULT_ACQUIRE_TIMEOUT = 30.0
class ExPoolTimeoutError(ConnectionError):
"""acquire 等待超时(携带池状态快照,便于排障)。"""
def __init__(self, pool: "ExPool", timeout: float) -> None:
idle = len(pool._idle)
total = pool._total
servers = len(pool.servers)
cap = pool.per_server_cap
super().__init__(
f"EX连接池获取超时(等了 {timeout:.1f}s):"
f"idle={idle} total={total} servers={servers} per_server_cap={cap} "
f"有效并发={servers * cap}"
)
class ExPool: class ExPool:
"""EX通道连接池(港股/期货,端口7727,连接时自动login)。""" """EX通道连接池(港股/期货,端口7727,连接时自动login)。"""
@@ -16,6 +40,7 @@ class ExPool:
def __init__(self, servers: list[str], *, timeout: float = 10.0, def __init__(self, servers: list[str], *, timeout: float = 10.0,
min_size: int = 2, max_size: int = 6, min_size: int = 2, max_size: int = 6,
per_server_cap: int = 1, per_server_cap: int = 1,
acquire_timeout: float | None = None,
handshake: str = "login", handshake: str = "login",
handshake_map: dict | None = None) -> None: handshake_map: dict | None = None) -> None:
self.servers = servers self.servers = servers
@@ -25,14 +50,17 @@ class ExPool:
self.min_size = min_size self.min_size = min_size
self.max_size = max_size self.max_size = max_size
self.per_server_cap = max(1, per_server_cap) # 一台服务器最多几个连接(默认1=单连接) self.per_server_cap = max(1, per_server_cap) # 一台服务器最多几个连接(默认1=单连接)
self.acquire_timeout = (
DEFAULT_ACQUIRE_TIMEOUT if acquire_timeout is None else acquire_timeout
)
self._idle: list[tuple[str, ExTdxConnection]] = [] self._idle: list[tuple[str, ExTdxConnection]] = []
self._server_count: dict[str, int] = {} self._server_count: dict[str, int] = {}
self._total = 0 self._total = 0
self._closed = False self._closed = False
self._lock = asyncio.Lock() self._cond = asyncio.Condition()
async def start(self) -> None: async def start(self) -> None:
async with self._lock: async with self._cond:
for host in self.servers[: self.min_size]: for host in self.servers[: self.min_size]:
if self._server_count.get(host, 0) >= self.per_server_cap: if self._server_count.get(host, 0) >= self.per_server_cap:
continue continue
@@ -47,7 +75,7 @@ class ExPool:
async def close(self) -> None: async def close(self) -> None:
self._closed = True self._closed = True
async with self._lock: async with self._cond:
for _, conn in self._idle: for _, conn in self._idle:
try: try:
await conn.close() await conn.close()
@@ -56,48 +84,61 @@ class ExPool:
self._idle.clear() self._idle.clear()
self._total = 0 self._total = 0
self._server_count.clear() self._server_count.clear()
self._cond.notify_all()
async def acquire(self) -> ExTdxConnection: async def acquire(self, timeout: float | None = None) -> ExTdxConnection:
for _ in range(3): """借出一条连接;无空闲且无法扩容时排队等待 release 唤醒。
stale_conn = None
new_conn = None timeout 默认取 self.acquire_timeout(30s);传 None 表示无限等待。
new_host = None """
async with self._lock: if timeout is None:
timeout = self.acquire_timeout
deadline = None if timeout is None else time.monotonic() + timeout
async with self._cond:
while True:
# 1. 优先借用空闲连接(过期则丢弃,槽位在锁内回收)
if self._idle: if self._idle:
_, conn = self._idle.pop() _, conn = self._idle.pop()
fresh = time.monotonic() - conn.last_used < 30.0 fresh = time.monotonic() - conn.last_used < 30.0
if conn.alive and fresh: if conn.alive and fresh:
return conn return conn
# 连接空闲过久(login会话可能失效)→ 丢弃重连 # 连接空闲过久(login会话可能失效)→ 丢弃,槽位让给扩容
self._total = max(0, self._total - 1) self._total = max(0, self._total - 1)
self._server_count[conn.host] = max(0, self._server_count.get(conn.host, 0) - 1) self._server_count[conn.host] = max(0, self._server_count.get(conn.host, 0) - 1)
stale_conn = conn self._schedule_close(conn)
# 扩容:在锁内预留槽位,锁外执行网络IO
elif self._total < self.max_size and self.servers: # 2. 可扩容 → 锁内预留槽位,锁外建连
new_conn = None
new_host = None
if self._total < self.max_size and self.servers:
host = self._next_available_server() host = self._next_available_server()
if host: if host is not None:
self._total += 1 self._total += 1
self._server_count[host] = self._server_count.get(host, 0) + 1 self._server_count[host] = self._server_count.get(host, 0) + 1
new_conn = ExTdxConnection(host, 7727, self.timeout, self.handshake_map.get(host, self.handshake)) new_conn = ExTdxConnection(host, 7727, self.timeout, self.handshake_map.get(host, self.handshake))
new_host = host new_host = host
# 锁外:关闭过期连接、建立新连接
if stale_conn is not None:
try:
await stale_conn.close()
except Exception:
pass
if new_conn is not None: if new_conn is not None:
# 锁外网络 IO:连接失败回滚槽位后继续等待
try: try:
await new_conn.connect() await new_conn.connect()
return new_conn return new_conn
except Exception as e: except Exception as e:
log.warning("EX扩容失败 %s: %s", new_host, str(e)[:60]) log.warning("EX扩容失败 %s: %s", new_host, str(e)[:60])
# 连接失败,回滚预留槽位 async with self._cond:
async with self._lock:
self._total = max(0, self._total - 1) self._total = max(0, self._total - 1)
self._server_count[new_host] = max(0, self._server_count.get(new_host, 0) - 1) self._server_count[new_host] = max(0, self._server_count.get(new_host, 0) - 1)
await asyncio.sleep(0.05)
raise ConnectionError("EX连接池无可用连接") # 3. 池满:排队等待 release 唤醒(或超时)
now = time.monotonic()
if deadline is not None and now >= deadline:
raise ExPoolTimeoutError(self, timeout)
try:
if deadline is None:
await self._cond.wait()
else:
await asyncio.wait_for(self._cond.wait(), timeout=deadline - now)
except asyncio.TimeoutError:
raise ExPoolTimeoutError(self, timeout)
def _next_available_server(self) -> str | None: def _next_available_server(self) -> str | None:
for h in self.servers: for h in self.servers:
@@ -105,15 +146,23 @@ class ExPool:
return h return h
return None return None
async def release(self, conn: ExTdxConnection, *, broken: bool = False) -> None: def _schedule_close(self, conn: ExTdxConnection) -> None:
if broken or not conn.alive: async def _close():
async with self._lock:
self._total = max(0, self._total - 1)
self._server_count[conn.host] = max(0, self._server_count.get(conn.host, 0) - 1)
try: try:
await conn.close() await conn.close()
except Exception: except Exception:
pass pass
return try:
async with self._lock: asyncio.get_running_loop().create_task(_close())
except RuntimeError:
pass
async def release(self, conn: ExTdxConnection, *, broken: bool = False) -> None:
async with self._cond:
if broken or not conn.alive:
self._total = max(0, self._total - 1)
self._server_count[conn.host] = max(0, self._server_count.get(conn.host, 0) - 1)
self._schedule_close(conn)
else:
self._idle.append((conn.host, conn)) self._idle.append((conn.host, conn))
self._cond.notify_all()
+26 -12
View File
@@ -6,8 +6,9 @@
- 动态:支持运行时 add() 新服务器;支持后台全量测速入库(当日首次启动)。 - 动态:支持运行时 add() 新服务器;支持后台全量测速入库(当日首次启动)。
- 单连接约束(核心需求):per_server_cap 默认 1 —— 一台服务器只允许建立 1 个连接, - 单连接约束(核心需求):per_server_cap 默认 1 —— 一台服务器只允许建立 1 个连接,
不允许多开,避免对单一券商服务器造成并发压力被限流/封禁。 不允许多开,避免对单一券商服务器造成并发压力被限流/封禁。
- 后台测速(核心需求):当日首次启动时,在后台对全量候选服务器测速,按 - 后台测速(核心需求):当日首次启动时,在后台对**全量候选**服务器测速(覆盖标准/MAC/EX
「排名前 FAST_POOL_TOP_N 或 延迟 < FAST_POOL_MAX_LATENCY」筛选入库,结果写回 servers.json。 三个协议,而不是只测当前池内节点),结果缓存到用户级缓存目录;当天已有缓存则跳过、不再刷新。
全程不阻塞 start()、不打印、不抛错(对用户无感)。详见 pool/probe_cache.py。
- 弹性:空闲连接超时后由 reaper 缩容回 min_size;支持 stats 统计。 - 弹性:空闲连接超时后由 reaper 缩容回 min_size;支持 stats 统计。
""" """
from __future__ import annotations from __future__ import annotations
@@ -19,7 +20,7 @@ import time
from .connection import TdxConnection from .connection import TdxConnection
from .health import HealthEngine from .health import HealthEngine
from .probe_cache import get_probe_cache from .probe_cache import schedule_probe
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@@ -101,6 +102,7 @@ class DynamicPool:
self._lock = asyncio.Lock() self._lock = asyncio.Lock()
self._cond = asyncio.Condition(self._lock) self._cond = asyncio.Condition(self._lock)
self._reaper_task: asyncio.Task | None = None self._reaper_task: asyncio.Task | None = None
self._probe_task: asyncio.Task | None = None
# ---------- 生命周期 ---------- # ---------- 生命周期 ----------
async def start(self) -> None: async def start(self) -> None:
@@ -108,13 +110,11 @@ class DynamicPool:
return return
self._started = True self._started = True
# 需求①:当日首次启动 → 后台全量测速入库(不阻塞主流程) # 需求①:当日首次启动 → 后台全量测速(不阻塞主流程;当天已有缓存则自动跳过)
# 候选清单由 probe_cache 自行枚举全量主机(本池的 servers 只是其中一个子集,
# 不能直接当作测速输入,否则只会重测已在池内的少数节点、其余记录永久过期)。
if self.auto_probe: if self.auto_probe:
hosts = list(self.servers) self._probe_task = schedule_probe()
asyncio.create_task(
get_probe_cache().ensure_probe(hosts),
name="pytdxdata-daily-probe",
)
targets = self._pick_servers(self.min_size) targets = self._pick_servers(self.min_size)
for host in targets: for host in targets:
@@ -175,6 +175,15 @@ class DynamicPool:
if self._reaper_task is not None: if self._reaper_task is not None:
self._reaper_task.cancel() self._reaper_task.cancel()
self._reaper_task = None self._reaper_task = None
# 后台测速仍可能持有 socket;取消并等它退场,避免事件循环关闭时冒出
# "Task was destroyed but it is pending"(那会破坏"无感")
if self._probe_task is not None:
self._probe_task.cancel()
try:
await self._probe_task
except (asyncio.CancelledError, Exception):
pass
self._probe_task = None
async with self._lock: async with self._lock:
for pc in list(self._conns): for pc in list(self._conns):
try: try:
@@ -211,6 +220,10 @@ class DynamicPool:
# 2. 可扩容(未达上限且有可用服务器)→ 新建连接 # 2. 可扩容(未达上限且有可用服务器)→ 新建连接
if self._total < self.max_size: if self._total < self.max_size:
host = self._next_available_server() host = self._next_available_server()
if host is None:
# 兜底:全部服务器都在冷却中,而池子未满 —— 此时等 release
# 永远等不到(没人持有),只能挑最健康的一台顶着冷却重试
host = self._next_available_server(ignore_cooldown=True)
if host: if host:
try: try:
pc = await self._new_conn(host) pc = await self._new_conn(host)
@@ -244,18 +257,19 @@ class DynamicPool:
break break
return out return out
def _next_available_server(self) -> str | None: def _next_available_server(self, *, ignore_cooldown: bool = False) -> str | None:
ranked = self.health.rank(self.servers) ranked = self.health.rank(self.servers)
# 1. 优先选未冷却且未达并发上限的服务器 # 1. 优先选未冷却且未达并发上限的服务器
for h in ranked: for h in ranked:
if self.health.in_cooldown(h): if self.health.in_cooldown(h) and not ignore_cooldown:
continue continue
if self._server_count.get(h, 0) < self.per_server_cap: if self._server_count.get(h, 0) < self.per_server_cap:
return h return h
# 2. 兜底:仅从「未冷却」的已占用服务器里随机复用(避免反复打坏服务器) # 2. 兜底:仅从「未冷却」的已占用服务器里随机复用(避免反复打坏服务器)
alive = [ alive = [
h for h in ranked h for h in ranked
if not self.health.in_cooldown(h) and self._server_count.get(h, 0) > 0 if (ignore_cooldown or not self.health.in_cooldown(h))
and self._server_count.get(h, 0) > 0
] ]
return random.choice(alive) if alive else None return random.choice(alive) if alive else None
+272 -112
View File
@@ -1,162 +1,322 @@
"""当日首次启动的全量服务器测速与入库缓存。 """当日首次启动的全量服务器测速与缓存(对用户完全无感)。
设计要点: 行为
- 仅在"当日首次启动"时触发一次后台全量测速(按本地日期判断是否已探测)。 ----
- 测速采用真实握手连通(TdxConnection.test),比单纯 ping 更能反映通达信可用性。 - **当日首次启动**触发一次后台全量测速;当天已有缓存则直接复用,**不再刷新**。
- 入库规则:延迟排名前 FAST_POOL_TOP_N(10) **或** 延迟 < FAST_POOL_MAX_LATENCY(0.2s) 的服务器 - 测速覆盖**全部候选**(包内清单 ∪ 代码常量 ∪ env 覆盖,见
才标记为 status="ok" 并写入 servers.json,其余降权(保留但不优先)。 :func:`pytdxdata.config.all_probe_candidates`),而不是只测当前已在池里的少数节点 ——
- 结果持久化到 servers.json,供 config / 连接池直接使用。 否则"上次慢、这次快"的节点永远捞不回来。
- 用**真实业务命令**判定可达(标准: GetSecurityBarsCmd / MAC: MacKlineCmd /
EX: GetExInstrumentBarsCmd)并要求返回非空数据,而不是只做握手回显:
存在"握手正常但 K线空响应"的坏节点(见 ``config.py`` 注释),只有真数据能测出来。
- 结果写入**用户级缓存目录**(见 :func:`pytdxdata.config.probe_cache_file`),
不写安装目录:site-packages 在容器 / 系统级安装 / pipx 下可能只读,
多用户共用一份安装时还会互相覆盖。
- 结果被 :func:`pytdxdata.config.get_standard_hosts` 等按**实测延迟升序**采用。
无感保证
--------
- 不打印任何东西;日志一律 ``debug`` 级(默认不输出)。
- 不抛异常(取消除外);失败只落 debug 日志,下次启动自然重试。
- 由连接池以后台 task 方式调用,不阻塞 ``start()`` 与任何用户请求。
一致性与并发
------------
- 进程内单例 + ``asyncio.Lock``:标准 / MAC / EX 三个池共用一次真正测速。
- 原子写入(tmp + ``os.replace``):进程被杀或多进程并发都不会读到半截 JSON。
- 全部不可达时**不写缓存**,避免把"全挂"状态缓存一整天。
开关
----
- ``PYPYTDX_DATA_DISABLE_PROBE=1`` 关闭(CI / 测试用,保证确定性)。
- ``PYPYTDX_DATA_CACHE_DIR`` 覆盖缓存目录(测试指向临时目录)。
""" """
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
import json import json
import logging import logging
import os
import time import time
from collections import defaultdict
from collections.abc import Awaitable, Callable
from datetime import date from datetime import date
from pathlib import Path from pathlib import Path
from ..config import _SERVERS_FILE from ..config import (
PROBE_CACHE_VERSION,
all_probe_candidates,
get_ex_handshakes,
is_valid_host,
load_probe_cache,
probe_cache_file,
probe_disabled,
)
from ..models import Adjust, KlinePeriod
from ..protocol.commands.ex_proto import GetExInstrumentBarsCmd
from ..protocol.commands.kline import GetSecurityBarsCmd
from ..protocol.commands.mac import MacKlineCmd
from .connection import TdxConnection
from .ex_connection import ExTdxConnection
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
# 入池阈值 # 入池阈值(仅用于缓存里的 fast 诊断标记;运行时按实测延迟整体排序,不做硬切)
FAST_POOL_TOP_N = 10 # 延迟排名前 N FAST_POOL_TOP_N = 10
FAST_POOL_MAX_LATENCY = 0.2 # 延迟 < 200ms(秒)也可入池 FAST_POOL_MAX_LATENCY = 0.2
# 探针参数
PROBE_PORT = 7709 PROBE_PORT = 7709
EX_PORT = 7727
PROBE_TIMEOUT = 3.0 PROBE_TIMEOUT = 3.0
PROBE_CONCURRENCY = 24 PROBE_CONCURRENCY = 12
PROBE_BUDGET = 60.0 # 整轮测速硬上限(秒),防止极端网络下长期占着后台
ProbeFn = Callable[[str, float], Awaitable[float | None]]
# ---------- 三个协议各自的真实数据探针 ----------
async def _probe_standard(host: str, timeout: float) -> float | None:
"""标准通道 7709:取 600000 日K,非空才算可达。"""
conn = TdxConnection(host, PROBE_PORT, timeout)
t0 = time.monotonic()
try:
await conn.connect()
bars = await conn.execute(GetSecurityBarsCmd(1, "600000", KlinePeriod.DAY, 0, 100))
return time.monotonic() - t0 if bars else None
except Exception:
return None
finally:
await conn.close()
async def _probe_mac(host: str, timeout: float) -> float | None:
"""MAC 通道 7709:MAC 帧与标准帧不同,用 MacKlineCmd 取日K。"""
conn = TdxConnection(host, PROBE_PORT, timeout)
t0 = time.monotonic()
try:
await conn.connect()
bars = await conn.execute(
MacKlineCmd(1, "600000", KlinePeriod.DAY, Adjust.NONE, 0, 100)
)
return time.monotonic() - t0 if bars else None
except Exception:
return None
finally:
await conn.close()
async def _probe_ex(host: str, timeout: float) -> float | None:
"""EX 扩展市场 7727:取港股 00700,握手模式按主机取(login / setup)。"""
conn = ExTdxConnection(host, EX_PORT, timeout, get_ex_handshakes().get(host, "setup"))
t0 = time.monotonic()
try:
await conn.connect()
bars = await conn.execute(GetExInstrumentBarsCmd(31, "00700", 0, 0, 5))
return time.monotonic() - t0 if bars else None
except Exception:
return None
finally:
await conn.close()
_DEFAULT_PROBERS: dict[str, ProbeFn] = {
"standard": _probe_standard,
"mac": _probe_mac,
"ex": _probe_ex,
}
class ProbeCache: class ProbeCache:
"""管理当日测速缓存与 servers.json 入库。 """当日全量测速的进程内协调器。
一台服务器不论协议(standard/mac/ex),测速结果共享: 一台主机不论申报几个协议,都按协议分别探测;缓存里记录
只要任一端口可达即视为该主机可用,并以最快端口延迟作为延迟基准。 ``{host: {protocol: 延迟或 None}}``,``None`` 表示该协议本次不可达。
参数(后 5 个主要供测试注入):
cache_file: 显式指定缓存文件;``None`` 时按 config 的平台规则解析。
probers: 协议 → 探针函数;默认使用真实网络探针。
today_fn: 返回 ``YYYY-MM-DD``;测试可注入假日期来验证跨日重测。
""" """
def __init__(self, servers_file: Path | None = None) -> None: def __init__(self, cache_file: Path | str | None = None, *,
self._file = servers_file or _SERVERS_FILE timeout: float = PROBE_TIMEOUT,
concurrency: int = PROBE_CONCURRENCY,
budget: float = PROBE_BUDGET,
probers: dict[str, ProbeFn] | None = None,
today_fn: Callable[[], str] | None = None) -> None:
self._file = Path(cache_file) if cache_file is not None else None
self._timeout = timeout
self._concurrency = concurrency
self._budget = budget
self._probers = dict(probers or _DEFAULT_PROBERS)
self._today_fn = today_fn or (lambda: date.today().isoformat())
self._lock = asyncio.Lock() self._lock = asyncio.Lock()
self._last_probe_date: str | None = None self._handled = False # 本进程是否已处理过今日测速(含"已有缓存,跳过")
self._probed_today = False self._task: asyncio.Task | None = None
# ---------- 路径与状态 ----------
def cache_file(self) -> Path:
"""缓存文件路径(构造时显式传入的优先,否则按平台规则解析)。"""
return self._file if self._file is not None else probe_cache_file()
def today(self) -> str:
return self._today_fn()
def read_cache(self) -> dict | None:
"""读取当日缓存;``None`` 表示"今天还没测过"。"""
return load_probe_cache(self.today(), self.cache_file())
# ---- 公开 API ----
def needs_probe_today(self) -> bool: def needs_probe_today(self) -> bool:
"""是否有必要在今日执行一次全量测速(文件不存在 / 日期不符 / 无 ok 项)。""" """今日是否仍需测速(缓存缺失 / 非今日 / 损坏 / 版本不符 / 无任何可用项)。"""
if not self._file.exists(): if probe_disabled():
return True
try:
cfg = json.loads(self._file.read_text(encoding="utf-8"))
except (OSError, ValueError):
return True
checked = str(cfg.get("checked_date", ""))
today = date.today().isoformat()
if checked != today:
return True
servers = cfg.get("servers", [])
if not any(s.get("status") == "ok" for s in servers):
return True
return False return False
return self.read_cache() is None
async def ensure_probe(self, hosts: list[str]) -> None: def reset(self) -> None:
"""若今日尚未测速,则后台执行一次全量测速并入库(幂等)。""" """清除"本进程已处理"标记(仅供测试复用单例)。"""
self._handled = False
# ---------- 主入口 ----------
async def ensure_probe(self, hosts: list[str] | None = None) -> None:
"""幂等入口:当日尚未测速则测一次;当天已有缓存则立即返回。
- 不阻塞调用方:正常由连接池以后台 task 调用。
- 绝不抛异常(``CancelledError`` 除外):测速 / 写盘失败只落 debug 日志。
- ``hosts``:为兼容旧签名保留,作为**额外的标准通道候选**并入,
且必须通过 :func:`~pytdxdata.config.is_valid_host` 校验(挡住 mock 脏数据)。
"""
async with self._lock: async with self._lock:
if self._probed_today: if self._handled:
return return
self._handled = True # 先占位:并发调用方不必排队等网络
if not self.needs_probe_today(): if not self.needs_probe_today():
self._probed_today = True log.debug("当日测速缓存已存在,跳过测速: %s", self.cache_file())
return return
self._probed_today = True
# 在锁外执行(耗时网络 IO),允许并发进入的调用方共享本次结果
try: try:
await self._run_full_probe(hosts) payload = await self._run_probe(hosts)
except Exception as e: # 测速失败不能阻塞主流程 if payload is not None:
log.warning("后台全量测速失败,沿用既有清单: %s", str(e)[:80]) self._write(payload)
except asyncio.CancelledError:
raise
except Exception as exc: # 测速绝不能影响主流程
log.debug("后台测速失败,沿用既有清单: %s", str(exc)[:120])
# ---- 内部实现 ---- # ---------- 内部实现 ----------
async def _run_full_probe(self, hosts: list[str]) -> None: async def _run_probe(self, extra_hosts: list[str] | None = None) -> dict | None:
from .connection import TdxConnection """全量并发测速,返回待写入的缓存 payload;无任何可达主机时返回 None。"""
candidates = all_probe_candidates()
if extra_hosts:
extra = [h.strip() for h in extra_hosts
if isinstance(h, str) and is_valid_host(h)]
if extra:
candidates["standard"] = list(dict.fromkeys(candidates["standard"] + extra))
jobs = [(proto, ip) for proto, ips in candidates.items() for ip in ips]
if not jobs:
log.debug("无测速候选,跳过")
return None
log.info("开始当日全量服务器测速 (%d 台)...", len(hosts)) log.debug("开始当日全量测速: %d 台主机 / %d 个协议探针",
sem = asyncio.Semaphore(PROBE_CONCURRENCY) len({ip for _, ip in jobs}), len(jobs))
results: dict[str, float | None] = {} sem = asyncio.Semaphore(self._concurrency)
# {host: {protocol: 延迟或 None}}
results: dict[str, dict[str, float | None]] = defaultdict(dict)
async def _probe_one(host: str) -> None: async def _one(protocol: str, host: str) -> None:
async with sem: async with sem:
try: try:
# 使用连接自带的 ping():建连+握手+发1条命令测往返延迟 lat = await asyncio.wait_for(
conn = TdxConnection(host, PROBE_PORT, PROBE_TIMEOUT) self._probers[protocol](host, self._timeout),
dt = await asyncio.wait_for(conn.ping(), timeout=PROBE_TIMEOUT + 1.0) timeout=self._timeout + 2.0,
results[host] = dt # 失败时为 None )
except Exception: except Exception:
results[host] = None lat = None
results[host][protocol] = lat
await asyncio.gather(*(_probe_one(h) for h in hosts)) t0 = time.monotonic()
ok_hosts = {h: lt for h, lt in results.items() if lt is not None}
# 按延迟升序排名
ranked = sorted(ok_hosts.items(), key=lambda kv: kv[1])
fast = set()
for i, (h, lt) in enumerate(ranked):
if i < FAST_POOL_TOP_N or lt < FAST_POOL_MAX_LATENCY:
fast.add(h)
log.info("测速完成: 可用 %d 台, 入池 %d 台 (前%d或<%dms)",
len(ok_hosts), len(fast), FAST_POOL_TOP_N,
int(FAST_POOL_MAX_LATENCY * 1000))
self._write_results(results, fast)
def _write_results(self, results: dict[str, float | None], fast: set[str]) -> None:
try: try:
cfg = json.loads(self._file.read_text(encoding="utf-8")) await asyncio.wait_for(
except (OSError, ValueError): asyncio.gather(*(_one(p, ip) for p, ip in jobs)),
cfg = {"servers": []} timeout=self._budget,
servers = cfg.get("servers", [])
by_ip = {s.get("ip"): s for s in servers}
today = date.today().isoformat()
now = time.strftime("%Y-%m-%d %H:%M:%S")
checked_any = False
for host, lt in results.items():
entry = by_ip.get(host)
if entry is None:
entry = {"ip": host, "name": host, "protocols": ["standard"]}
servers.append(entry)
by_ip[host] = entry
if lt is not None:
checked_any = True
entry["status"] = "ok" if host in fast else "slow"
entry["latency"] = round(lt, 3)
entry["fast_pool"] = host in fast
else:
# 探测不可达:不降级已有 ok(避免误杀),仅标记本次不可达
entry.setdefault("status", "unknown")
entry["latency"] = None
entry["fast_pool"] = False
entry["checked_date"] = today
entry["checked_at"] = now
# 若有 ok 服务器写入可入池日期;否则保留今日以免反复重试
cfg["checked_date"] = today
cfg["note"] = (
f"当日全量测速入库({today}): 入池={len(fast)}台 "
f"(排名前{FAST_POOL_TOP_N}或延迟<{int(FAST_POOL_MAX_LATENCY*1000)}ms)"
) )
if not checked_any: except TimeoutError:
# 全部不可达时不写 checked_date,下次启动重试 # 超时:采用已完成的部分结果(部分可用也强于完全没有)
cfg.pop("checked_date", None) log.debug("测速整体超过 %.0fs 预算,采用已完成的部分结果", self._budget)
except Exception as exc:
log.debug("测速过程异常: %s", str(exc)[:120])
elapsed = time.monotonic() - t0
self._file.write_text( responsive = {
json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8" ip: {p: lat for p, lat in per.items() if lat is not None}
for ip, per in results.items()
}
responsive = {ip: per for ip, per in responsive.items() if per}
if not responsive:
log.debug("测速结束: 无任何可达主机,不写缓存(下次启动重试)")
return None
def _ordered(protocol: str) -> list[str]:
rows = [(per[protocol], ip) for ip, per in responsive.items()
if protocol in per]
rows.sort(key=lambda kv: (kv[0], kv[1]))
return [ip for _, ip in rows]
hosts_by_proto = {p: _ordered(p) for p in ("standard", "mac", "ex")}
overall = sorted(
(min(per.values()), ip) for ip, per in responsive.items()
) )
log.info("测速结果已写入 %s", self._file) fast = {ip for i, (lat, ip) in enumerate(overall)
if i < FAST_POOL_TOP_N or lat < FAST_POOL_MAX_LATENCY}
log.debug("测速完成: 候选 %d 台, 可达 %d 台, fast %d 台, 耗时 %.2fs",
len({ip for _, ip in jobs}), len(responsive), len(fast), elapsed)
return {
"version": PROBE_CACHE_VERSION,
"date": self.today(),
"probed_at": time.strftime("%Y-%m-%d %H:%M:%S"),
"elapsed": round(elapsed, 3),
# 每个协议的完整探测结果(含 None = 本次不可达),便于事后诊断
"results": {ip: dict(per) for ip, per in results.items() if per},
# 按延迟升序的可达主机(运行时即按此顺序取用)
"hosts": hosts_by_proto,
# 诊断用:符合"前N名或<200ms"的可达主机
"fast": {p: [h for h in ips if h in fast]
for p, ips in hosts_by_proto.items()},
}
def _write(self, payload: dict) -> None:
"""原子写入:先写临时文件再 ``os.replace``,避免读到半截 JSON。"""
target = self.cache_file()
tmp = target.with_name(f"{target.name}.tmp{os.getpid()}")
try:
target.parent.mkdir(parents=True, exist_ok=True)
tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2),
encoding="utf-8")
os.replace(tmp, target)
log.debug("当日测速结果已缓存: %s", target)
except OSError as exc:
log.debug("测速结果写入失败(忽略): %s", str(exc)[:120])
try:
tmp.unlink(missing_ok=True)
except OSError:
pass
# 进程级单例(跨池共享,确保当日仅测一次) # 进程级单例(标准 / MAC / EX 三池共享,确保当日只真正测一次)
_probe_cache = ProbeCache() _probe_cache = ProbeCache()
def get_probe_cache() -> ProbeCache: def get_probe_cache() -> ProbeCache:
return _probe_cache return _probe_cache
def schedule_probe(hosts: list[str] | None = None) -> asyncio.Task | None:
"""[连接池用] 把当日测速挂到后台并返回 Task,供调用方持有 / 取消。
返回 ``None`` 表示当前没有运行中的事件循环(此时无法起后台任务)。
"""
try:
return asyncio.create_task(
get_probe_cache().ensure_probe(hosts), name="pytdxdata-daily-probe"
)
except RuntimeError:
return None
+34 -22
View File
@@ -36,6 +36,15 @@ class PageResult:
items: list[Any] items: list[Any]
class _Slot:
"""worker 当前持有的连接槽:失败换连时原地更新,保证最终能精确归还。"""
__slots__ = ("pc",)
def __init__(self, pc: PooledConnection) -> None:
self.pc: PooledConnection | None = pc
class Paginator: class Paginator:
"""用至多 concurrency 个连接并行拉取分页数据。""" """用至多 concurrency 个连接并行拉取分页数据。"""
@@ -64,21 +73,26 @@ class Paginator:
conns = await self.pool.acquire_many(eff_conc) conns = await self.pool.acquire_many(eff_conc)
if not conns: if not conns:
raise PoolTimeoutError("连接池获取超时(无可用连接)") raise PoolTimeoutError("连接池获取超时(无可用连接)")
# 每个 worker 一个连接槽:中途换连会更新槽内引用,
# 归还时按槽归还(否则换掉的新连接会漏还,把池耗干)
slots = [_Slot(pc) for pc in conns]
try: try:
stop = asyncio.Event() stop = asyncio.Event()
out: list[PageResult] = [] out: list[PageResult] = []
out_lock = asyncio.Lock() out_lock = asyncio.Lock()
k = len(conns) k = len(slots)
workers = [ workers = [
asyncio.create_task( asyncio.create_task(
self._worker(wid, conns[wid % k], jobs[wid::k], cmd_factory, self._worker(slots[wid], jobs[wid::k], cmd_factory,
stop, out, out_lock, spec) stop, out, out_lock, spec)
) )
for wid in range(k) for wid in range(k)
] ]
await asyncio.gather(*workers) await asyncio.gather(*workers)
finally: finally:
for pc in conns: for s in slots:
if s.pc is not None:
pc, s.pc = s.pc, None
await self.pool.release(pc) await self.pool.release(pc)
return self._assemble(out, spec.ordered) return self._assemble(out, spec.ordered)
@@ -102,49 +116,47 @@ class Paginator:
return jobs return jobs
async def _worker( async def _worker(
self, wid: int, conn: PooledConnection, jobs: list[tuple[int, int]], self, slot: _Slot, jobs: list[tuple[int, int]],
cmd_factory: Callable[[int, int], Any], stop: asyncio.Event, cmd_factory: Callable[[int, int], Any], stop: asyncio.Event,
out: list[PageResult], out_lock: asyncio.Lock, spec: PageSpec, out: list[PageResult], out_lock: asyncio.Lock, spec: PageSpec,
) -> None: ) -> None:
current = conn
for start, count in jobs: for start, count in jobs:
if stop.is_set(): if stop.is_set() or slot.pc is None:
return return
items, current = await self._fetch_one( items, ok = await self._fetch_one(slot, cmd_factory(start, count), count)
current, cmd_factory(start, count), count) if not ok:
if items is None: return # 换连接失败 → 本 worker 退出(该页留空)
continue # 该页失败(strict=False 时留空)
async with out_lock: async with out_lock:
out.append(PageResult(start=start, count=count, items=items)) out.append(PageResult(start=start, count=count, items=items))
if spec.stop_when_short and len(items) < count: if spec.stop_when_short and len(items) < count:
stop.set() stop.set()
return return
async def _fetch_one(self, conn: PooledConnection, cmd, page_size: int): async def _fetch_one(self, slot: _Slot, cmd, page_size: int):
"""单页拉取,失败换连接重试。 """单页拉取,失败换连接重试。
返回 (items, current_conn) — current_conn 始终指向当前可用连接, 返回 ``(items, ok)``。失败时连接一律 ``broken=True`` 归还并把槽清空,
worker 据此更新自己的连接引用,避免跨页使用已关闭连接。 调用方据此退出,不会留下悬空引用。
""" """
current = conn
for attempt in range(self.retries + 1): for attempt in range(self.retries + 1):
try: try:
result = await current.execute(cmd) result = await slot.pc.execute(cmd) # type: ignore[union-attr]
return (list(result) if result is not None else []), current return (list(result) if result is not None else []), True
except Exception as e: except Exception as e:
if slot.pc is not None:
await self.pool.release(slot.pc, broken=True)
slot.pc = None
if attempt >= self.retries: if attempt >= self.retries:
if self.strict: if self.strict:
raise raise
log.warning("分页拉取失败(strict=False留空): %s", e) log.warning("分页拉取失败(strict=False留空): %s", e)
return None, current return None, False
# 换连接重试
await self.pool.release(current, broken=True)
try: try:
current = await self.pool.acquire(timeout=3.0) slot.pc = await self.pool.acquire(timeout=3.0)
except PoolTimeoutError: except PoolTimeoutError:
log.warning("分页重试获取连接失败,跳过该页: %s", e) log.warning("分页重试获取连接失败,跳过该页: %s", e)
return None, current return None, False
return None, current return None, False
def _assemble(self, results: list[PageResult], ordered: bool) -> list[Any]: def _assemble(self, results: list[PageResult], ordered: bool) -> list[Any]:
if ordered: if ordered:
+113 -39
View File
@@ -3,28 +3,43 @@
读 servers.json → 并发探测每台可用性与延时(标准/MAC用7709、EX用7727)→ 写回状态。 读 servers.json → 并发探测每台可用性与延时(标准/MAC用7709、EX用7727)→ 写回状态。
用法: 用法:
python -m pytdxdata.server_probe # 全量探测 python -m pytdxdata.server_probe # 按申报协议全量探测
python -m pytdxdata.server_probe --discover # 额外测【每种协议】并据实修正 protocols
python -m pytdxdata.server_probe --group ex # 只测EX python -m pytdxdata.server_probe --group ex # 只测EX
python -m pytdxdata.server_probe --refresh # 重新探测(status=ok的) python -m pytdxdata.server_probe --refresh # 只重测status=ok的
写回的字段
----------
``status`` / ``latency`` / ``checked_at`` / ``checked_date`` / ``fast_pool``
以及顶层 ``checked_date`` / ``note``。其中 ``fast_pool`` 与运行时缓存里的 ``fast``
用同一套规则(整体延迟前 10 名,或延迟 < 200ms),供"还没有当日缓存时"的冷启动排序。
``--discover`` 会顺带剔除 ip 非法的脏记录(如历史遗留的 ``"s1"``)。
""" """
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import asyncio import asyncio
import json import json
import sys
import time import time
from pathlib import Path from pathlib import Path
from .config import is_valid_host
from .models import Adjust, KlinePeriod
from .pool.connection import TdxConnection from .pool.connection import TdxConnection
from .pool.ex_connection import ExTdxConnection from .pool.ex_connection import ExTdxConnection
from .protocol.commands.ex_proto import GetExInstrumentBarsCmd
from .protocol.commands.kline import GetSecurityBarsCmd from .protocol.commands.kline import GetSecurityBarsCmd
from .protocol.commands.mac import MacKlineCmd from .protocol.commands.mac import MacKlineCmd
from .protocol.commands.ex_proto import GetExInstrumentBarsCmd
from .models import KlinePeriod, Adjust
SERVERS_FILE = Path(__file__).resolve().parent / "servers.json" SERVERS_FILE = Path(__file__).resolve().parent / "servers.json"
# 与 pool/probe_cache.py 保持同一套入池规则
FAST_POOL_TOP_N = 10
FAST_POOL_MAX_LATENCY = 0.2
ALL_PROTOCOLS = ("standard", "mac", "ex")
def load_servers() -> dict: def load_servers() -> dict:
if not SERVERS_FILE.exists(): if not SERVERS_FILE.exists():
@@ -41,7 +56,7 @@ async def probe_standard(ip: str, timeout: float = 5.0) -> tuple[bool, float]:
t0 = time.monotonic() t0 = time.monotonic()
try: try:
await conn.connect() await conn.connect()
bars = await conn.execute(GetSecurityBarsCmd(1, "600000", 5, 0, 100)) bars = await conn.execute(GetSecurityBarsCmd(1, "600000", KlinePeriod.DAY, 0, 100))
return (bool(bars), time.monotonic() - t0) return (bool(bars), time.monotonic() - t0)
except Exception: except Exception:
return (False, time.monotonic() - t0) return (False, time.monotonic() - t0)
@@ -75,25 +90,51 @@ async def probe_ex(ip: str, handshake: str, timeout: float = 5.0) -> tuple[bool,
await conn.close() await conn.close()
async def probe_one(server: dict, timeout: float) -> dict: async def probe_proto(proto: str, ip: str, handshake: str, timeout: float) -> tuple[bool, float]:
ip = server["ip"] """按协议分派到具体探针。"""
protocols = server.get("protocols", [])
best_lat = None
ok = False
# 逐协议探测(一台多协议: standard/mac同端口可复用连接——简化逐协议测)
for proto in protocols:
if proto == "ex": if proto == "ex":
r, lat = await probe_ex(ip, server.get("handshake", "setup"), timeout) return await probe_ex(ip, handshake, timeout)
elif proto == "mac": if proto == "mac":
r, lat = await probe_mac(ip, timeout) return await probe_mac(ip, timeout)
return await probe_standard(ip, timeout)
async def probe_one(server: dict, timeout: float, discover: bool = False) -> dict:
ip = server["ip"]
declared = server.get("protocols", [])
handshake = server.get("handshake") or "setup"
# discover: 三种协议全测(EX 先按申报握手,失败再试另一种);
# 默认: 只测申报的协议(保持原行为,避免误改人工裁剪的清单)
targets = list(ALL_PROTOCOLS) if discover else list(declared)
per: dict[str, float | None] = {}
for proto in targets:
if proto == "ex":
ok, lat = await probe_ex(ip, handshake, timeout)
if not ok and discover:
# 握手模式申报错的节点:换一种再试(login <-> setup)
alt = "setup" if handshake == "login" else "login"
ok, lat = await probe_ex(ip, alt, timeout)
else: else:
r, lat = await probe_standard(ip, timeout) ok, lat = await probe_proto(proto, ip, handshake, timeout)
if r: if not ok and discover:
ok = True # discover 会据结果**收窄 protocols**,单次抖动就会误删协议 → 失败重试一次
best_lat = lat if best_lat is None else min(best_lat, lat) ok, lat = await probe_proto(proto, ip, handshake, timeout)
server["status"] = "ok" if ok else "fail" if ok:
server["latency"] = round(best_lat, 3) if best_lat is not None else None per[proto] = lat
server["checked_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
if discover and per:
# 据实测结果修正申报协议(保序:standard / mac / ex)
server["protocols"] = [p for p in ALL_PROTOCOLS if p in per]
server["status"] = "ok" if per else "fail"
server["latency"] = round(min(per.values()), 3) if per else None
now = time.strftime("%Y-%m-%d %H:%M:%S")
server["checked_at"] = now
server["checked_date"] = now[:10]
server.setdefault("fast_pool", False)
# 供表格打印用,不落盘
server["_per_proto"] = {p: (round(v, 3) if v is not None else None) for p, v in per.items()}
return server return server
@@ -102,10 +143,21 @@ async def main() -> None:
ap.add_argument("--group", choices=["standard", "mac", "ex"], default=None) ap.add_argument("--group", choices=["standard", "mac", "ex"], default=None)
ap.add_argument("--timeout", type=float, default=5.0) ap.add_argument("--timeout", type=float, default=5.0)
ap.add_argument("--refresh", action="store_true", help="只重测status=ok的") ap.add_argument("--refresh", action="store_true", help="只重测status=ok的")
ap.add_argument("--discover", action="store_true",
help="三种协议全测并据实修正 protocols(同时剔除 ip 非法的脏记录)")
args = ap.parse_args() args = ap.parse_args()
cfg = load_servers() cfg = load_servers()
servers = cfg["servers"] all_servers = cfg["servers"]
# --- 清理:ip 不合法的脏记录(历史遗留,如 "s1") ---
junk = [s.get("ip") for s in all_servers if not is_valid_host(s.get("ip"))]
if junk:
cfg["servers"] = [s for s in all_servers if is_valid_host(s.get("ip"))]
all_servers = cfg["servers"]
print("已剔除 ip 非法记录: %s" % ", ".join(map(str, junk)))
servers = all_servers
if args.group: if args.group:
servers = [s for s in servers if args.group in s.get("protocols", [])] servers = [s for s in servers if args.group in s.get("protocols", [])]
if args.refresh: if args.refresh:
@@ -114,33 +166,55 @@ async def main() -> None:
print("没有待探测的服务器") print("没有待探测的服务器")
return return
print("=" * 90) print("=" * 96)
print("探测 %d 台服务器 (标准/MAC:7709, EX:7727)..." % len(servers)) print("探测 %d 台服务器 (标准/MAC:7709, EX:7727)%s..." % (
print("=" * 90) len(servers), " [discover: 全协议]" if args.discover else ""))
print("=" * 96)
t0 = time.time() t0 = time.time()
results = await asyncio.gather(*[probe_one(s, args.timeout) for s in servers]) results = await asyncio.gather(
*[probe_one(s, args.timeout, args.discover) for s in servers]
)
elapsed = time.time() - t0 elapsed = time.time() - t0
# 写回 # --- 入池标记:与运行时缓存同一规则(前N名 或 <200ms) ---
updated = {s["ip"]: s for s in results} ok_list = [s for s in results if s["status"] == "ok"]
ok_list.sort(key=lambda s: s["latency"])
fast_ips = {s["ip"] for i, s in enumerate(ok_list)
if i < FAST_POOL_TOP_N or s["latency"] < FAST_POOL_MAX_LATENCY}
for s in ok_list:
s["fast_pool"] = s["ip"] in fast_ips
fail_list = [s for s in results if s["status"] == "fail"]
for s in fail_list:
s["fast_pool"] = False
# --- 写回(剔除内部诊断字段) ---
today = time.strftime("%Y-%m-%d")
updated = {s["ip"]: {k: v for k, v in s.items() if not k.startswith("_")} for s in results}
for s in cfg["servers"]: for s in cfg["servers"]:
if s["ip"] in updated: if s["ip"] in updated:
s.update(updated[s["ip"]]) s.update(updated[s["ip"]])
cfg["checked_date"] = today
cfg["version"] = today # 清单基线日期(无代码读取,仅标注本次复测时间)
cfg["note"] = "离线探针复测(%s %s): 可达=%d/%d, 入池fast_pool=%d台" % (
today, time.strftime("%H:%M"), len(ok_list), len(results), len(fast_ips))
save_servers(cfg) save_servers(cfg)
ok_list = [s for s in results if s["status"] == "ok"] print("\n可用: %d/%d (%.1fs) 入池: %d台" % (len(ok_list), len(results), elapsed, len(fast_ips)))
ok_list.sort(key=lambda s: s["latency"]) print("-" * 96)
fail_list = [s for s in results if s["status"] == "fail"]
print("\n可用: %d/%d (%.1fs)" % (len(ok_list), len(results), elapsed))
print("-" * 90)
for s in ok_list: for s in ok_list:
print(" [OK] %-16s %-14s %-28s %.3fs %s" % ( per = s.get("_per_proto", {})
s["ip"], "/".join(s.get("protocols", [])), s["name"], detail = " ".join(
s["latency"], s.get("handshake") or "")) "%s=%s" % (p, ("%.3fs" % v) if v is not None else "-")
for p, v in per.items()
) or "/".join(s.get("protocols", []))
print(" [OK] %-16s %-24s %-24s %.3fs %s%s" % (
s["ip"], "/".join(s.get("protocols", [])), s["name"], s["latency"],
"★" if s["fast_pool"] else " ", detail))
if fail_list: if fail_list:
print("\n不可用: %d台" % len(fail_list)) print("\n不可用: %d台" % len(fail_list))
for s in fail_list: for s in fail_list:
print(" [X] %-16s %s" % (s["ip"], "/".join(s.get("protocols", [])))) print(" [X] %-16s %-24s %s" % (
s["ip"], "/".join(s.get("protocols", [])), s["name"]))
print("\n已写回 %s" % SERVERS_FILE) print("\n已写回 %s" % SERVERS_FILE)
+291 -148
View File
@@ -1,6 +1,6 @@
{ {
"version": "2026-08-12", "version": "2026-10-16",
"note": "当日全量测速入库(2026-09-08): 入池=9台 (排名前10或延迟<200ms)", "note": "离线探针复测(2026-10-16 13:46): 可达=30/36, 入池fast_pool=10台",
"servers": [ "servers": [
{ {
"ip": "139.9.52.158", "ip": "139.9.52.158",
@@ -11,11 +11,15 @@
], ],
"handshake": null, "handshake": null,
"status": "ok", "status": "ok",
"latency": null, "latency": 0.172,
"checked_at": "2026-08-21 11:23:14", "checked_at": "2026-10-16 13:46:17",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": true,
"checked_date": "2026-08-21" "checked_date": "2026-10-16",
"_per_proto": {
"standard": 0.172,
"mac": 0.183
}
}, },
{ {
"ip": "103.251.85.94", "ip": "103.251.85.94",
@@ -25,42 +29,50 @@
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "ok",
"latency": 0.481, "latency": 0.298,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:18",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": true,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"standard": 0.316,
"mac": 0.298
}
}, },
{ {
"ip": "58.67.221.146", "ip": "58.67.221.146",
"name": "中信短线宝21", "name": "中信短线宝21",
"protocols": [ "protocols": [
"standard",
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "ok", "status": "ok",
"latency": 0.254, "latency": 0.236,
"checked_at": "2026-09-08 10:05:12", "checked_at": "2026-10-16 13:46:23",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": true, "fast_pool": true,
"checked_date": "2026-09-08" "checked_date": "2026-10-16",
"_per_proto": {
"mac": 0.236
}
}, },
{ {
"ip": "59.36.5.11", "ip": "59.36.5.11",
"name": "安信", "name": "安信",
"protocols": [ "protocols": [
"standard",
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "ok", "status": "ok",
"latency": 0.254, "latency": 0.213,
"checked_at": "2026-09-08 10:05:12", "checked_at": "2026-10-16 13:46:17",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": true, "fast_pool": true,
"checked_date": "2026-09-08" "checked_date": "2026-10-16",
"_per_proto": {
"mac": 0.213
}
}, },
{ {
"ip": "103.221.142.82", "ip": "103.221.142.82",
@@ -71,12 +83,17 @@
"ex" "ex"
], ],
"handshake": "setup", "handshake": "setup",
"status": "slow", "status": "ok",
"latency": 0.487, "latency": 0.316,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:13",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"standard": 0.316,
"mac": 0.329,
"ex": 0.539
}
}, },
{ {
"ip": "218.106.92.182", "ip": "218.106.92.182",
@@ -85,27 +102,30 @@
"standard" "standard"
], ],
"handshake": null, "handshake": null,
"status": "ok", "status": "fail",
"latency": 0.371, "latency": null,
"checked_at": "2026-09-08 10:05:12", "checked_at": "2026-10-16 13:46:34",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": true, "fast_pool": false,
"checked_date": "2026-09-08" "checked_date": "2026-10-16",
"_per_proto": {}
}, },
{ {
"ip": "60.12.136.251", "ip": "60.12.136.251",
"name": "中信短线宝22", "name": "中信短线宝22",
"protocols": [ "protocols": [
"standard",
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "ok", "status": "ok",
"latency": 0.37, "latency": 0.682,
"checked_at": "2026-09-08 10:05:12", "checked_at": "2026-10-16 13:46:24",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": true, "fast_pool": false,
"checked_date": "2026-09-08" "checked_date": "2026-10-16",
"_per_proto": {
"mac": 0.682
}
}, },
{ {
"ip": "218.106.92.183", "ip": "218.106.92.183",
@@ -114,42 +134,47 @@
"standard" "standard"
], ],
"handshake": null, "handshake": null,
"status": "ok", "status": "fail",
"latency": 0.377, "latency": null,
"checked_at": "2026-09-08 10:05:12", "checked_at": "2026-10-16 13:46:34",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": true, "fast_pool": false,
"checked_date": "2026-09-08" "checked_date": "2026-10-16",
"_per_proto": {}
}, },
{ {
"ip": "60.12.136.250", "ip": "60.12.136.250",
"name": "中信短线宝26", "name": "中信短线宝26",
"protocols": [ "protocols": [
"standard",
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "ok", "status": "ok",
"latency": 0.373, "latency": 0.607,
"checked_at": "2026-09-08 10:05:12", "checked_at": "2026-10-16 13:46:23",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": true, "fast_pool": false,
"checked_date": "2026-09-08" "checked_date": "2026-10-16",
"_per_proto": {
"mac": 0.607
}
}, },
{ {
"ip": "115.238.90.170", "ip": "115.238.90.170",
"name": "中信短线宝23", "name": "中信短线宝23",
"protocols": [ "protocols": [
"standard",
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "ok",
"latency": 0.482, "latency": 1.264,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:24",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"mac": 1.264
}
}, },
{ {
"ip": "220.178.55.86", "ip": "220.178.55.86",
@@ -158,12 +183,13 @@
"standard" "standard"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "fail",
"latency": 0.479, "latency": null,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:34",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {}
}, },
{ {
"ip": "220.178.55.71", "ip": "220.178.55.71",
@@ -172,87 +198,98 @@
"standard" "standard"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "fail",
"latency": 0.47, "latency": null,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:34",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {}
}, },
{ {
"ip": "180.153.18.170", "ip": "180.153.18.170",
"name": "中信短线宝1", "name": "中信短线宝1",
"protocols": [ "protocols": [
"standard",
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "ok",
"latency": 0.438, "latency": 0.612,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:23",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"mac": 0.612
}
}, },
{ {
"ip": "115.238.90.165", "ip": "115.238.90.165",
"name": "杭州J4", "name": "杭州J4",
"protocols": [ "protocols": [
"standard",
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "ok",
"latency": 0.476, "latency": 0.613,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:23",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"mac": 0.613
}
}, },
{ {
"ip": "60.191.117.167", "ip": "60.191.117.167",
"name": "杭州J1", "name": "杭州J1",
"protocols": [ "protocols": [
"standard",
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "ok", "status": "ok",
"latency": 0.362, "latency": 0.624,
"checked_at": "2026-09-08 10:05:12", "checked_at": "2026-10-16 13:46:23",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": true, "fast_pool": false,
"checked_date": "2026-09-08" "checked_date": "2026-10-16",
"_per_proto": {
"mac": 0.624
}
}, },
{ {
"ip": "218.75.126.9", "ip": "218.75.126.9",
"name": "杭州J3", "name": "杭州J3",
"protocols": [ "protocols": [
"standard",
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "ok",
"latency": 0.481, "latency": 0.592,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:23",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"mac": 0.592
}
}, },
{ {
"ip": "115.238.56.198", "ip": "115.238.56.198",
"name": "杭州J2", "name": "杭州J2",
"protocols": [ "protocols": [
"standard",
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "ok", "status": "ok",
"latency": 0.362, "latency": 0.624,
"checked_at": "2026-09-08 10:05:12", "checked_at": "2026-10-16 13:46:23",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": true, "fast_pool": false,
"checked_date": "2026-09-08" "checked_date": "2026-10-16",
"_per_proto": {
"mac": 0.624
}
}, },
{ {
"ip": "117.34.114.16", "ip": "117.34.114.16",
@@ -262,12 +299,16 @@
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "ok",
"latency": 1.575, "latency": 0.306,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:18",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"standard": 0.352,
"mac": 0.306
}
}, },
{ {
"ip": "159.75.55.232", "ip": "159.75.55.232",
@@ -276,26 +317,32 @@
"standard" "standard"
], ],
"handshake": null, "handshake": null,
"status": "ok", "status": "fail",
"latency": 0.244, "latency": null,
"checked_at": "2026-09-08 10:05:12", "checked_at": "2026-10-16 13:46:18",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": true, "fast_pool": false,
"checked_date": "2026-09-08" "checked_date": "2026-10-16",
"_per_proto": {}
}, },
{ {
"ip": "117.34.114.17", "ip": "117.34.114.17",
"name": "国泰君安", "name": "国泰君安",
"protocols": [ "protocols": [
"standard" "standard",
"mac"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "ok",
"latency": 1.573, "latency": 0.307,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:18",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"standard": 0.35,
"mac": 0.307
}
}, },
{ {
"ip": "117.34.114.14", "ip": "117.34.114.14",
@@ -305,12 +352,16 @@
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "ok",
"latency": 0.508, "latency": 0.395,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:18",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"standard": 0.395,
"mac": 0.675
}
}, },
{ {
"ip": "117.34.114.15", "ip": "117.34.114.15",
@@ -320,12 +371,16 @@
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "ok",
"latency": 0.636, "latency": 0.345,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:18",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"standard": 0.345,
"mac": 0.726
}
}, },
{ {
"ip": "117.34.114.13", "ip": "117.34.114.13",
@@ -335,12 +390,16 @@
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "ok",
"latency": 0.608, "latency": 0.326,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:18",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"standard": 0.326,
"mac": 0.743
}
}, },
{ {
"ip": "117.34.114.27", "ip": "117.34.114.27",
@@ -350,12 +409,16 @@
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "ok",
"latency": 1.138, "latency": 0.394,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:18",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"standard": 0.394,
"mac": 0.78
}
}, },
{ {
"ip": "117.34.114.18", "ip": "117.34.114.18",
@@ -365,12 +428,16 @@
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "ok",
"latency": 0.969, "latency": 0.327,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:18",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"standard": 0.327,
"mac": 0.328
}
}, },
{ {
"ip": "117.34.114.20", "ip": "117.34.114.20",
@@ -380,12 +447,16 @@
"mac" "mac"
], ],
"handshake": null, "handshake": null,
"status": "slow", "status": "ok",
"latency": 0.526, "latency": 0.348,
"checked_at": "2026-08-19 15:37:35", "checked_at": "2026-10-16 13:46:18",
"source": "probe-2026-08-12", "source": "probe-2026-08-12",
"fast_pool": false, "fast_pool": false,
"checked_date": "2026-08-19" "checked_date": "2026-10-16",
"_per_proto": {
"standard": 0.348,
"mac": 0.74
}
}, },
{ {
"ip": "117.34.114.30", "ip": "117.34.114.30",
@@ -396,8 +467,11 @@
"handshake": null, "handshake": null,
"status": "fail", "status": "fail",
"latency": null, "latency": null,
"checked_at": "2026-08-12 18:36:21", "checked_at": "2026-10-16 13:46:37",
"source": "probe-2026-08-12" "source": "probe-2026-08-12",
"checked_date": "2026-10-16",
"fast_pool": false,
"_per_proto": {}
}, },
{ {
"ip": "121.37.207.165", "ip": "121.37.207.165",
@@ -407,9 +481,14 @@
], ],
"handshake": null, "handshake": null,
"status": "ok", "status": "ok",
"latency": 0.249, "latency": 0.726,
"checked_at": "2026-08-12 18:36:17", "checked_at": "2026-10-16 13:46:18",
"source": "probe-2026-08-12" "source": "probe-2026-08-12",
"checked_date": "2026-10-16",
"fast_pool": false,
"_per_proto": {
"mac": 0.726
}
}, },
{ {
"ip": "121.36.248.138", "ip": "121.36.248.138",
@@ -419,9 +498,14 @@
], ],
"handshake": null, "handshake": null,
"status": "ok", "status": "ok",
"latency": 0.436, "latency": 0.624,
"checked_at": "2026-08-12 18:36:17", "checked_at": "2026-10-16 13:46:18",
"source": "probe-2026-08-12" "source": "probe-2026-08-12",
"checked_date": "2026-10-16",
"fast_pool": false,
"_per_proto": {
"mac": 0.624
}
}, },
{ {
"ip": "123.60.47.136", "ip": "123.60.47.136",
@@ -431,9 +515,14 @@
], ],
"handshake": null, "handshake": null,
"status": "ok", "status": "ok",
"latency": 0.476, "latency": 0.56,
"checked_at": "2026-08-12 18:36:17", "checked_at": "2026-10-16 13:46:30",
"source": "probe-2026-08-12" "source": "probe-2026-08-12",
"checked_date": "2026-10-16",
"fast_pool": false,
"_per_proto": {
"mac": 0.56
}
}, },
{ {
"ip": "116.205.135.205", "ip": "116.205.135.205",
@@ -443,9 +532,14 @@
], ],
"handshake": "login", "handshake": "login",
"status": "ok", "status": "ok",
"latency": 0.192, "latency": 0.097,
"checked_at": "2026-08-12 18:36:17", "checked_at": "2026-10-16 13:46:21",
"source": "probe-2026-08-12" "source": "probe-2026-08-12",
"checked_date": "2026-10-16",
"fast_pool": true,
"_per_proto": {
"ex": 0.097
}
}, },
{ {
"ip": "121.37.232.167", "ip": "121.37.232.167",
@@ -455,9 +549,14 @@
], ],
"handshake": "login", "handshake": "login",
"status": "ok", "status": "ok",
"latency": 0.194, "latency": 0.097,
"checked_at": "2026-08-12 18:36:17", "checked_at": "2026-10-16 13:46:21",
"source": "probe-2026-08-12" "source": "probe-2026-08-12",
"checked_date": "2026-10-16",
"fast_pool": true,
"_per_proto": {
"ex": 0.097
}
}, },
{ {
"ip": "116.205.143.214", "ip": "116.205.143.214",
@@ -467,22 +566,66 @@
], ],
"handshake": "setup", "handshake": "setup",
"status": "ok", "status": "ok",
"latency": 0.192, "latency": 0.103,
"checked_at": "2026-08-12 18:36:17", "checked_at": "2026-10-16 13:46:21",
"source": "probe-2026-08-12" "source": "probe-2026-08-12",
"checked_date": "2026-10-16",
"fast_pool": true,
"_per_proto": {
"ex": 0.103
}
}, },
{ {
"ip": "s1", "ip": "112.74.214.43",
"name": "s1", "name": "扩展市场深圳双线1",
"protocols": [ "protocols": [
"standard" "ex"
], ],
"status": "unknown", "handshake": "login",
"latency": null, "status": "ok",
"fast_pool": false, "latency": 0.095,
"checked_date": "2026-08-19", "checked_at": "2026-10-16 13:46:21",
"checked_at": "2026-08-19 15:34:45" "source": "connect.cfg",
"fast_pool": true,
"checked_date": "2026-10-16",
"_per_proto": {
"ex": 0.095
}
},
{
"ip": "120.25.218.6",
"name": "扩展市场深圳双线2",
"protocols": [
"ex"
],
"handshake": "login",
"status": "ok",
"latency": 0.101,
"checked_at": "2026-10-16 13:46:21",
"source": "connect.cfg",
"fast_pool": true,
"checked_date": "2026-10-16",
"_per_proto": {
"ex": 0.101
}
},
{
"ip": "47.102.108.214",
"name": "扩展市场上海双线2",
"protocols": [
"ex"
],
"handshake": "login",
"status": "ok",
"latency": 0.149,
"checked_at": "2026-10-16 13:46:22",
"source": "connect.cfg",
"fast_pool": true,
"checked_date": "2026-10-16",
"_per_proto": {
"ex": 0.149
}
} }
], ],
"checked_date": "2026-09-08" "checked_date": "2026-10-16"
} }
+240
View File
@@ -0,0 +1,240 @@
"""标的代码解析:全库唯一的字符串口径。
统一写法(也是 CLI 的写法)::
sz000001 / sh600000 / bj920992 A股(6位代码,必须带市场前缀)
hk00700 港股主板(5位)
usAAPL 美股(ticker)
cffex:IFL0 / zz:AP0 期货(交易所前缀 + 合约,可带冒号)
000001 裸 6 位数字 = 沪市指数
**裸 6 位数字只当作沪市指数**:A股代码不唯一(``000001`` 既是上证指数也是平安银行),
要股票请写全前缀 ``sh000001`` / ``sz000001``。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Sequence
from .models import ExMarket, Market
# 通道:cn=标准/MAC A股通道,ex=扩展市场通道(端口 7727)
CN = "cn"
EX = "ex"
INDEX = "index"
_CN_ALIASES: dict[str, Market] = {
"sz": Market.SZ,
"sh": Market.SH,
"bj": Market.BJ,
}
_CN_PREFIX: dict[int, str] = {int(m): k for k, m in _CN_ALIASES.items()}
# EX 常用别名(短前缀优先;其余成员用枚举名小写,如 hk_gem:08001)
_EX_ALIASES: dict[str, ExMarket] = {
"hk": ExMarket.HK_MAIN_BOARD,
"us": ExMarket.US_STOCK,
"zz": ExMarket.ZZ_FUTURES,
"dl": ExMarket.DL_FUTURES,
"shf": ExMarket.SH_FUTURES,
"cffex": ExMarket.CFFEX_FUTURES,
"gz": ExMarket.GZ_FUTURES,
}
_EX_PREFIX: dict[int, str] = {int(m): k for k, m in _EX_ALIASES.items()}
ALL = "all"
def _ex_by_name(name: str) -> ExMarket | None:
"""按枚举名匹配(hk_main_board / us_stock / ...),保证 format→parse 可往返。"""
key = name.upper()
for member in ExMarket:
if member.name == key:
return member
return None
def _lookup(text: str) -> tuple[int, str] | None:
"""前缀 -> (市场号, 通道)。"""
if text in _CN_ALIASES:
return int(_CN_ALIASES[text]), CN
if text in _EX_ALIASES:
return int(_EX_ALIASES[text]), EX
member = _ex_by_name(text)
if member is not None:
return int(member), EX
return None
def _hint() -> str:
cn = "/".join(sorted(_CN_ALIASES))
ex = "/".join(sorted(_EX_ALIASES))
return f"A股: {cn};扩展市场: {ex}(详见 pytdxdata.models.ExMarket)"
@dataclass(frozen=True, slots=True)
class Symbol:
"""解析后的标的。``kind``: cn=A股 / ex=扩展市场 / index=裸数字指数。"""
market: int
code: str
kind: str
raw: str = ""
@property
def is_ex(self) -> bool:
return self.kind == EX
@property
def is_index(self) -> bool:
return self.kind == INDEX
@property
def channel(self) -> str:
"""路由通道:ex 走扩展市场池,其余走标准/MAC A股池。"""
return EX if self.is_ex else "std"
@property
def text(self) -> str:
"""规范化写法,同时用作记录上的 ``.symbol``。"""
if self.is_index:
return self.code
return format_symbol(self.market, self.code)
def as_pair(self) -> tuple[int, str]:
"""(市场号, 代码) 元组(协议层用)。"""
return self.market, self.code
def __str__(self) -> str:
return self.text
def _prefix_for(market: int) -> str | None:
"""市场号 -> 短前缀;无短别名的扩展市场回退到枚举名小写。"""
m = int(market)
prefix = _CN_PREFIX.get(m) or _EX_PREFIX.get(m)
if prefix is not None:
return prefix
try:
return ExMarket(m).name.lower()
except ValueError:
return None
def format_symbol(market: int, code: str) -> str:
"""(市场号, 代码) -> 规范化字符串(``1, "600000"`` -> ``"sh600000"``)。"""
code = str(code).strip()
if not code:
return ""
prefix = _prefix_for(market)
if prefix is None:
return code
# 2 字母前缀贴代码(hk00700),长前缀用冒号(cffex:IFL0 / hk_gem:08001)
return f"{prefix}:{code}" if len(prefix) > 2 else f"{prefix}{code}"
def market_name(market: int) -> str:
"""市场号 -> 市场选择器字符串(``1`` -> ``"sh"``,``31`` -> ``"hk"``)。
用于把旧接口的市场号参数转成统一接口要的市场选择器。
"""
prefix = _prefix_for(market)
if prefix is None:
raise ValueError(f"未知市场号: {market}")
return prefix
def parse_symbol(text: str) -> Symbol:
"""字符串 -> Symbol。无法识别时抛 ValueError 并列出可用前缀。"""
raw = text
sym = str(text).strip()
if not sym:
raise ValueError("标的为空")
if ":" in sym:
head, code = sym.split(":", 1)
head, code = head.strip().lower(), code.strip()
hit = _lookup(head)
if hit is None:
raise ValueError(f"未知市场前缀: {head}({_hint()})")
if not code:
raise ValueError(f"缺少代码: {raw}")
return Symbol(market=hit[0], code=code.upper(), kind=hit[1], raw=raw)
head, code = sym[:2].lower(), sym[2:]
hit = _lookup(head)
if hit is not None and code:
return Symbol(market=hit[0], code=code.upper(), kind=hit[1], raw=raw)
if sym.isdigit() and len(sym) == 6:
# 裸 6 位 = 沪市指数(A股代码不唯一,股票必须带前缀)
return Symbol(market=int(Market.SH), code=sym, kind=INDEX, raw=raw)
raise ValueError(f"无法识别标的: {raw}({_hint()};裸6位数字=沪市指数)")
def parse_symbols(symbols: str | Sequence[str] | None) -> list[Symbol]:
"""接受单个字符串 / 字符串序列 / Symbol 序列,去重并保持输入顺序。"""
if symbols is None:
raise ValueError("symbols 不能为空")
items: list = [symbols] if isinstance(symbols, str) else list(symbols)
if not items:
raise ValueError("symbols 不能为空")
out: list[Symbol] = []
seen: set[tuple[int, str]] = set()
for item in items:
sym = item if isinstance(item, Symbol) else parse_symbol(item)
if sym.as_pair() in seen:
continue
seen.add(sym.as_pair())
out.append(sym)
return out
def cn_markets() -> list[int]:
"""A股市场号(深/沪/北)。"""
return [int(m) for m in Market]
def ex_markets() -> list[int]:
"""扩展市场号,按枚举值升序。"""
return sorted(int(m) for m in ExMarket)
def market_targets(text: str | None) -> list[tuple[int, str]]:
"""市场选择器 -> [(市场号, 通道)];``None`` / ``"all"`` = 全部市场。
市场号在两条通道里会撞车(``Market.SH=1`` 与 ``ExMarket.TEMP_STOCK=1``),
所以必须带通道一起返回,调用方按通道分别请求。
"""
key = "" if text is None else str(text).strip().lower()
if not key or key == ALL:
return ([(m, CN) for m in cn_markets()]
+ [(m, EX) for m in ex_markets()])
hit = _lookup(key)
if hit is None:
raise ValueError(f"未知市场: {text}({_hint()};全部用 all)")
return [hit]
def parse_market(text: str | None) -> int | None:
"""市场选择器 -> 单个市场号;``None`` / ``"all"`` 返回 None。
只用于「本来就是单市场」的接口(如市场异动)。需要跨市场时用
:func:`market_targets`。
"""
targets = market_targets(text)
return None if len(targets) > 1 else targets[0][0]
def is_cn_index(market: int, code: str) -> bool:
"""A股指数代码判定:88开头板块指数 / 沪市000 / 深市399。
深市股票 000001 不是指数,必须带市场判断。
"""
code = str(code)
return (
code.startswith("88")
or (code.startswith("000") and int(market) == int(Market.SH))
or (code.startswith("399") and int(market) == int(Market.SZ))
)
+673
View File
@@ -0,0 +1,673 @@
"""全接口回归:mock 连接,逐个调用 ``TdxData`` 的每一个公开方法。
目标是「没有接口是死的」——每个公开方法至少被真实调用一次并返回预期形状。
末尾的 ``test_every_public_method_was_exercised`` 用 AST 解析 ``api.py``,
断言覆盖集合与全部公开方法**完全相等**:以后新增方法若没纳入本文件就会失败
(与 ``scripts/check_docs.py`` 的 ``MUST_LIST_ALL`` 互为呼应)。
不连任何网络:标准 / MAC / EX 连接全部被 mock;探测缓存被短路。
"""
from __future__ import annotations
import ast
import datetime
import io
import pathlib
import struct
import time
import zipfile
from unittest import mock
import pytest
from pytdxdata.api import TdxData
from pytdxdata.models import (
AuctionItem,
BelongBoard,
BoardInfo,
CapitalFlow,
FinanceRecord,
MemberQuote,
MinuteBar,
SecurityBar,
SecurityInfo,
SecurityQuote,
ServerInfo,
SymbolSnapshot,
TransactionRecord,
UnusualItem,
XdxrRecord,
)
# --------------------------------------------------------------------------- #
# 覆盖追踪
# --------------------------------------------------------------------------- #
EXERCISED: set[str] = set()
def _use(name: str) -> None:
EXERCISED.add(name)
def _public_methods() -> set[str]:
"""AST 解析 api.py,取 TdxData 的全部公开方法名(与 check_docs 同口径)。"""
src = pathlib.Path(__file__).resolve().parent.parent / "src" / "pytdxdata" / "api.py"
tree = ast.parse(src.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef) and node.name == "TdxData":
return {
item.name
for item in node.body
if isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef)
and not item.name.startswith("_")
}
raise AssertionError("api.py 里找不到 TdxData")
# --------------------------------------------------------------------------- #
# mock 数据
# --------------------------------------------------------------------------- #
_TOTAL_BARS = 2000
_BASE_DATE = datetime.date(2026, 9, 16)
_QUOTE_FIELDS = {
"0x0": 9.8, "0x1": 9.9, "0x2": 10.2, "0x3": 9.7, "0x4": 10.0,
"0x5": 1000.0, "0x6": 1.0, "0x7": 1_000_000.0, "0x38": 5000.0,
}
def _mk_bar(market: int, code: str, offset: int) -> SecurityBar:
"""offset 越大越老(标准通道语义:offset 0 = 最新一根)。"""
d = _BASE_DATE - datetime.timedelta(days=offset)
return SecurityBar(
market=market, code=code, open=10.0, high=10.5, low=9.5,
close=10.0 + (offset % 5) * 0.1, vol=1000.0, amount=10000.0,
year=d.year, month=d.month, day=d.day, hour=9, minute=30,
)
def _bars(start: int, count: int, market: int, code: str) -> list[SecurityBar]:
hi = min(start + count, _TOTAL_BARS)
return [_mk_bar(market, code, i) for i in range(start, hi)]
def _quote(market: int, code: str) -> SecurityQuote:
return SecurityQuote(
market=market, code=code, price=10.0, pre_close=9.8, open=9.9,
high=10.2, low=9.7, vol=1000.0, amount=1_000_000.0, s_vol=10.0,
b_vol=12.0, bid=[9.99] * 5, ask=[10.01] * 5,
)
def _member(market: int, code: str) -> MemberQuote:
return MemberQuote(market=market, code=code, name="测试",
fields=dict(_QUOTE_FIELDS))
class _FileMeta:
"""对应 protocol.commands.mac_ext.FileMeta(避免直接依赖内部类)。"""
__slots__ = ("flag", "md5", "offset", "size")
def __init__(self, offset=0, size=4, flag=0, md5=""):
self.offset, self.size, self.flag, self.md5 = offset, size, flag, md5
class _BlockMeta:
__slots__ = ("filename", "md5", "size")
def __init__(self, size=4, md5="", filename=""):
self.size, self.md5, self.filename = size, md5, filename
def _dispatch(cmd) -> object:
"""按命令类名返回形状正确的数据。"""
n = type(cmd).__name__
market = getattr(cmd, "market", 1)
code = getattr(cmd, "code", "600000")
start = getattr(cmd, "start", 0)
count = getattr(cmd, "count", 100) or 100
if n == "GetSecurityCountCmd":
return 8
if n == "GetSecurityListCmd":
return [SecurityInfo(market=1, code="600000", name="浦发银行",
volunit=100, decimal_point=2, pre_close=10.0)]
# ---- K线 ----
if n in ("GetSecurityBarsCmd", "GetIndexBarsCmd", "MacKlineCmd"):
return _bars(start, count, market, code)
if n == "GetExInstrumentBarsCmd":
return [{"year": 2026, "month": 9, "day": 1, "hour": 9, "minute": 30,
"open": 10.0, "high": 10.5, "low": 9.5, "close": 10.0,
"trade": 1000}]
# ---- 报价 ----
if n == "GetSecurityQuotesCmd":
return [_quote(m, c) for m, c in cmd.stocks]
if n == "MacSymbolQuotesCmd":
return [_member(m, c) for m, c in cmd.stocks]
if n == "MacBoardMembersQuotesCmd":
return [_member(1, "600000")]
# ---- 逐笔 / 分时 ----
if n == "MacTransactionCmd":
return [TransactionRecord(market=market, code=code, time="09:30",
price=10.0, vol=100.0, trade_count=1, bs_flag=0)]
if n in ("GetExTransactionDataCmd", "GetExHistoryTransactionDataCmd"):
return [{"minutes": 570, "price": 10.0, "vol": 100.0, "direction": 0,
"zengcang": 1.0}]
if n == "MacTickChartCmd":
return [MinuteBar(price=p, vol=100.0, hour=9, minute=30 + i)
for i, p in enumerate((10.0, 10.1, 10.2))]
if n == "SymbolTickChartCmd":
return [{"minutes": 570, "price": 10.0, "vol": 100.0, "avg": 10.0,
"momentum": 0.1}]
if n == "MacChartSamplingCmd":
# 刻意与 MacTickChartCmd 的 mock 数据不同:A股由分时派生、EX 用 0x254D,
# 靠返回值即可区分实际走了哪条命令(BUG-1 回归用)。
return [99.0, 98.0]
# ---- 公司信息 ----
if n == "MacSymbolInfoCmd":
return SymbolSnapshot(
market=market, code=code, name="浦发银行", date=20260916, time=930,
activity=1.0, pre_close=9.8, open=9.9, high=10.2, low=9.7,
close=10.0, vol=1000.0, amount=1_000_000.0, turnover=1.0,
avg_price=10.0)
if n == "MacAuctionCmd":
return [AuctionItem(time=93000, price=10.0, matched=100, unmatched=0)]
if n == "MacCapitalFlowCmd":
return CapitalFlow(market=market, code=code, main_buy=1.0, main_sell=1.0,
retail_buy=1.0, retail_sell=1.0, buy5=1.0, sell5=1.0,
big5=1.0, mid5=1.0)
if n == "GetXdxrInfoCmd":
return [XdxrRecord(market=market, code=code, year=2025, month=6, day=1,
category=1, name="除权除息")]
if n == "GetFinanceInfoCmd":
return FinanceRecord(market=market, code=code)
if n == "GetCompanyInfoCategoryCmd":
return [{"name": "最新提示", "filename": "600000.txt", "length": 10}]
if n == "GetCompanyInfoContentCmd":
return "公司资料正文"
# ---- 市场 / 板块 ----
if n == "MacUnusualCmd":
return [UnusualItem(market=1, code="600000", name="测试", type=1,
desc="描述", value=1.0, time=930)]
if n == "MacServerInfoCmd":
return ServerInfo(date=20260916, last_trade_date=20260915,
sessions=[(570, 690)])
if n == "MacKlineOffsetCmd":
return (_TOTAL_BARS, 100)
if n == "MacBoardListCmd":
return [BoardInfo(market=1, code="881001", name="银行", price=110.0,
rise_speed=0.1, pre_close=100.0)]
if n == "MacBelongBoardCmd":
return [BelongBoard(market=market, board_code=20686, board_name="银行",
close=110.0, pre_close=100.0)]
# ---- 文件 ----
if n == "MacFileListCmd":
return _FileMeta(size=4)
if n == "GetBlockInfoMetaCmd":
return _BlockMeta(size=4)
if n in ("GetBlockInfoCmd", "GetReportFileCmd", "MacFileDownloadCmd"):
return b"abcd"
# ---- EX 市场 ----
if n == "GetExInstrumentCountCmd":
return 2
if n == "GetExInstrumentInfoCmd":
return [{"market": 31, "code": "00700", "name": "腾讯控股", "desc": "港股"},
{"market": 74, "code": "AAPL", "name": "苹果", "desc": "美股"}]
return []
class _MockConn:
"""替代 TdxConnection / ExTdxConnection。"""
def __init__(self, host="h", port=7709, timeout=3.0, *args, **kwargs):
self.host = host
self.server = host
self.port = port
self.timeout = timeout
self.alive = True
self.last_used = time.monotonic()
async def connect(self) -> None:
self.alive = True
async def close(self) -> None:
self.alive = False
async def ping(self):
return 0.01
async def execute(self, cmd):
self.last_used = time.monotonic()
return _dispatch(cmd)
# --------------------------------------------------------------------------- #
# 离线文件样本(供 *_parsed / get_file 走通解析路径)
# --------------------------------------------------------------------------- #
_HEADER = 384
def _make_block_dat() -> bytes:
out = bytearray(_HEADER)
out += struct.pack("<H", 1)
rec = bytearray()
rec += "银行".encode("gbk")[:9].ljust(9, b"\x00")
rec += struct.pack("<HH", 1, 1)
area = bytearray(2800)
area[0:7] = "000001".encode("ascii").ljust(7, b"\x00")
rec += area
out += rec
return bytes(out)
def _make_financial_zip() -> bytes:
entry = struct.pack("<6sBL", b"600000", 1, 31)
header = struct.pack("<1hI1H3L", 0, 20260331, 1, 0, 8, 0)
dat = header + entry + struct.pack("<2f", 1.0, 2.0)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("gpcw.dat", dat)
return buf.getvalue()
def _make_financial_dat() -> bytes:
"""未压缩 .dat(服务器实际提供的形式)。"""
entry = struct.pack("<6sBL", b"600000", 1, 31)
header = struct.pack("<1hI1H3L", 0, 20260331, 1, 0, 8, 0)
return header + entry + struct.pack("<2f", 1.0, 2.0)
# --------------------------------------------------------------------------- #
# fixture
# --------------------------------------------------------------------------- #
@pytest.fixture
async def td():
with mock.patch("pytdxdata.api.get_standard_hosts", return_value=["s1"]), \
mock.patch("pytdxdata.api.get_mac_hosts", return_value=["m1"]), \
mock.patch("pytdxdata.api.get_ex_hosts", return_value=["e1"]), \
mock.patch("pytdxdata.pool.pool.TdxConnection", new=_MockConn), \
mock.patch("pytdxdata.pool.ex_pool.ExTdxConnection", new=_MockConn), \
mock.patch("pytdxdata.pool.pool.schedule_probe", return_value=None):
t = TdxData(cache_dir=None, pool_min=1, pool_max=2)
_use("start")
await t.start()
try:
yield t
finally:
_use("close")
await t.close()
# --------------------------------------------------------------------------- #
# 一、标的清单 / 报价 / 快照
# --------------------------------------------------------------------------- #
async def test_universe_and_quotes(td):
for name in ("get_universe", "get_quotes"):
_use(name)
uni = await td.get_universe()
assert isinstance(uni, list) and uni
cn = await td.get_universe("sz")
assert isinstance(cn, list)
ex = await td.get_universe("hk")
assert isinstance(ex, list)
q = await td.get_quotes(["sh600000", "sz000001"])
assert len(q) == 2 and all(x.symbol for x in q)
qf = await td.get_quotes(["sh600000"], fields=[0x00, 0x04])
assert qf[0].name == "测试"
qex = await td.get_quotes(["hk00700"])
assert len(qex) == 1
async def test_snapshot_auction_flow(td):
for name in ("get_snapshot", "get_auction", "get_capital_flow"):
_use(name)
snaps = await td.get_snapshot("sh600000")
assert len(snaps) == 1 and snaps[0].name == "浦发银行"
auc = await td.get_auction("sh600000")
assert len(auc) == 1
flow = await td.get_capital_flow("sh600000")
assert len(flow) == 1 and flow[0].main_buy == 1.0
# --------------------------------------------------------------------------- #
# 二、K线 / 指标
# --------------------------------------------------------------------------- #
async def test_bars(td):
_use("get_bars")
bars = await td.get_bars("sh600000", count=120)
assert len(bars) == 120
assert all(b.symbol == "sh600000" for b in bars)
# 分页(超过单页)
big = await td.get_bars("sh600000", count=2000, concurrency=2)
assert len(big) == 2000
# 复权走 MAC 通道
qfq = await td.get_bars("sh600000", count=200, adjust=None) # NONE -> 标准
assert len(qfq) == 200
from pytdxdata.models import Adjust
mac = await td.get_bars("sh600000", count=200, adjust=Adjust.QFQ)
assert len(mac) == 200
# 多标的并发
multi = await td.get_bars(["sh600000", "sz000001"], count=60)
assert len(multi) == 120
# 日期区间(二分定位路径)
dated = await td.get_bars(
"sh600000", start_date=datetime.datetime(2026, 8, 1),
end_date=datetime.datetime(2026, 8, 31))
assert isinstance(dated, list)
# 扩展市场 K线
exb = await td.get_bars("hk00700", count=60)
assert isinstance(exb, list)
async def test_indicators(td):
_use("get_indicators")
sets = await td.get_indicators("sh600000", ["macd", "kdj", "rsi"], count=30)
assert len(sets) == 1
assert sets[0].symbol == "sh600000"
assert sets[0].indicators # 指标分量名(DIF/DEA/K/D/J/RSI* 等)
# --------------------------------------------------------------------------- #
# 三、逐笔 / 分时
# --------------------------------------------------------------------------- #
async def test_ticks(td):
_use("get_ticks")
rows = await td.get_ticks("sh600000", date=20260811, count=10)
assert isinstance(rows, list) and rows and all(r.symbol for r in rows)
full = await td.get_ticks("sh600000", count=None)
assert isinstance(full, list)
hk = await td.get_ticks("hk00700", count=10)
assert isinstance(hk, list)
async def test_minutes(td):
_use("get_minutes")
rows = await td.get_minutes("sh600000")
assert isinstance(rows, list) and rows
hist = await td.get_minutes("sh600000", date=20260811)
assert isinstance(hist, list)
samp = await td.get_minutes("sh600000", sampling=True)
assert [b.price for b in samp] == [10.0, 10.1, 10.2]
exm = await td.get_minutes("hk00700")
assert isinstance(exm, list)
# --------------------------------------------------------------------------- #
# 四、公司信息 / 市场
# --------------------------------------------------------------------------- #
async def test_company_info(td):
for name in ("get_xdxr", "get_finance", "get_price_limits", "get_f10"):
_use(name)
x = await td.get_xdxr("sh600000")
assert isinstance(x, list) and x
fin = await td.get_finance("sh600000")
assert isinstance(fin, list) and fin and fin[0].symbol == "sh600000"
lo, hi = await td.get_price_limits("sh600000", name="浦发银行", pre_close=10.0)
assert (lo, hi) == (lo, hi) # 本地计算,不连网
cat = await td.get_f10("sh600000")
assert isinstance(cat, list)
body = await td.get_f10("sh600000", section="600000.txt")
assert isinstance(body, str)
async def test_market(td):
for name in ("get_market_stat", "get_unusual", "get_server_info",
"get_kline_offset"):
_use(name)
stat = await td.get_market_stat()
assert stat.up_count == 100 # price 10.0 * 10
un = await td.get_unusual("sh")
assert isinstance(un, list) and un
info = await td.get_server_info()
assert info.date == 20260916
off = await td.get_kline_offset()
assert off == (_TOTAL_BARS, 100)
# --------------------------------------------------------------------------- #
# 五、板块
# --------------------------------------------------------------------------- #
async def test_boards(td):
for name in ("get_boards", "get_board_members", "get_board_of",
"get_board_summary", "get_board_ranking",
"get_board_change_ranking"):
_use(name)
bl = await td.get_boards("all")
assert isinstance(bl, list) and bl
mem = await td.get_board_members("881001")
assert isinstance(mem, list) and mem
of = await td.get_board_of("sh600000")
assert isinstance(of, list) and of
summ = await td.get_board_summary("881001")
assert set(summ) == {"member_count", "amount", "main_net_amount",
"up_count", "down_count"}
rank = await td.get_board_ranking("industry")
assert isinstance(rank, list)
chg = await td.get_board_change_ranking("industry", days=5)
assert isinstance(chg, list)
# --------------------------------------------------------------------------- #
# 六、服务器文件
# --------------------------------------------------------------------------- #
async def test_files(td):
_use("get_file")
raw = await td.get_file("block_gn.dat")
assert raw == b"abcd"
async def test_parsed_files(td):
for name in ("get_block_parsed", "get_industry_map",
"get_financial_file_infos", "get_financial_records_parsed"):
_use(name)
with mock.patch.object(td, "get_file",
new=mock.AsyncMock(return_value=_make_block_dat())):
blocks = await td.get_block_parsed("block_gn.dat")
assert blocks and blocks[0].category == 2
with mock.patch.object(td, "get_file",
new=mock.AsyncMock(
return_value="0|000001|A01|||S01\n".encode("gbk"))):
ind = await td.get_industry_map()
assert ind["000001"].sw_industry == "S01"
with mock.patch.object(td, "get_file",
new=mock.AsyncMock(
return_value=b"gpcw20260331.zip,abc,1024\n")):
infos = await td.get_financial_file_infos()
assert infos[0].filesize == 1024
with mock.patch.object(td, "get_file",
new=mock.AsyncMock(return_value=_make_financial_zip())):
recs = await td.get_financial_records_parsed("tdxfin/gpcw20260331.zip")
assert len(recs) == 1 and recs[0].report_date == 20260331
# --------------------------------------------------------------------------- #
# 六之二、BUG 回归(真实联网实测发现,见 tests 说明)
# --------------------------------------------------------------------------- #
async def test_financial_dat_fallback(td):
"""BUG-2 回归:索引写 ``.zip``,服务器只给未压缩 ``.dat`` 时必须能回退取到。
服务器对**不存在的**文件名不报错,而是回 0~1 字节空壳;旧实现会把空壳直接
丢给 ``zipfile`` → ``BadZipFile``。现在要求按候选名回退到 ``tdxfin/*.dat``。
"""
calls: list[str] = []
async def fake_get_file(name: str) -> bytes:
calls.append(name)
if name == "tdxfin/gpcw20260331.zip":
return b"" # 服务器没有 .zip
if name == "gpcw20260331.zip":
return b"\x00" # 裸名被路由到 MAC 通道 → 1 字节空壳
if name == "tdxfin/gpcw20260331.dat":
return _make_financial_dat()
return b""
with mock.patch.object(td, "get_file", new=fake_get_file):
recs = await td.get_financial_records_parsed("gpcw20260331.zip")
assert "tdxfin/gpcw20260331.dat" in calls, "必须回退尝试未压缩 .dat"
assert len(recs) == 1 and recs[0].report_date == 20260331
assert recs[0].code == "600000"
async def test_financial_records_alias_not_silent(td):
"""BUG-2 回归:废弃别名取不到有效财报数据时应返回 ``b""``,而非 0~1 字节空壳。"""
import warnings
async def empty_get_file(name: str) -> bytes:
return b"\x00"
with mock.patch.object(td, "get_file", new=empty_get_file), warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
got = await td.get_financial_records("gpcw20260331.zip")
assert got == b""
async def test_sampling_derives_from_tick_chart(td):
"""BUG-1 回归:A股 ``sampling=True`` 必须由分时(0x122D)派生。
``MacChartSamplingCmd``(0x254D) 是 **EX 协议**命令,7709 主机对它一律不响应
(实测 3 台各 10s 超时,叠加连接池重试 ≈24s 才报错)。两条路径的 mock 数据刻意
不同,以便从结果区分实际走的是哪条命令。
"""
# A股:得到分时派生值(10.0/10.1/10.2),而非 0x254D 的 99.0/98.0
a_share = await td.get_minutes("sh600000", sampling=True)
a_share_hist = await td.get_minutes("sh600000", date=20260811, sampling=True)
assert [b.price for b in a_share] == [10.0, 10.1, 10.2]
assert [b.price for b in a_share_hist] == [10.0, 10.1, 10.2]
assert all(b.vol == 0.0 and b.avg_price == 0 for b in a_share), "采样点无量/均价"
assert [b.fields["i"] for b in a_share] == [0.0, 1.0, 2.0], "点位序号在 fields['i']"
# EX:仍走 0x254D
ex = await td.get_minutes("hk00700", sampling=True)
assert [b.price for b in ex] == [99.0, 98.0]
# --------------------------------------------------------------------------- #
# 七、废弃别名(33 个)
# --------------------------------------------------------------------------- #
async def test_aliases_kline(td):
for name in ("get_kline", "get_kline_since", "get_kline_batch",
"get_index_kline", "get_stock_kline_with_indicators"):
_use(name)
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
assert len(await td.get_kline(1, "600000", 4, count=60)) == 60
assert len(await td.get_kline_since(
1, "600000", 4, datetime.datetime(2026, 8, 1))) >= 0
batch = await td.get_kline_batch([(1, "600000"), (0, "000001")], 4, count=30)
assert isinstance(batch, dict) and batch
assert len(await td.get_index_kline(1, "000001", 4, count=30)) == 30
withind = await td.get_stock_kline_with_indicators(1, "600000", ["macd"])
assert "bars" in withind and "indicators" in withind
async def test_aliases_quotes_ticks(td):
for name in ("get_stock_quotes", "get_stock_quotes_list", "get_transactions",
"get_minute", "get_minute_batch", "get_chart_sampling"):
_use(name)
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
assert len(await td.get_stock_quotes([(1, "600000")])) == 1
assert isinstance(await td.get_stock_quotes_list(1, count=10), list)
assert isinstance(await td.get_transactions(1, "600000", count=10), list)
assert isinstance(await td.get_minute(0, "000001"), list)
mb = await td.get_minute_batch([(1, "600000")])
assert isinstance(mb, dict)
assert (await td.get_chart_sampling(1, "600000")) == [10.0, 10.1, 10.2]
async def test_aliases_universe(td):
for name in ("get_security_count", "get_security_list",
"get_security_list_all"):
_use(name)
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
assert await td.get_security_count(0) == 8
assert isinstance(await td.get_security_list(0, count=1), list)
assert isinstance(await td.get_security_list_all(0), list)
async def test_aliases_files(td):
for name in ("get_financial_file_list", "get_financial_records",
"get_company_info_category", "get_company_info_content",
"get_block_info", "get_report_file", "get_file_meta",
"download_file"):
_use(name)
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
assert await td.get_financial_file_list() == ["abcd"]
with mock.patch.object(td, "get_file",
new=mock.AsyncMock(
return_value=_make_financial_dat())):
assert await td.get_financial_records(
"gpcw20260331.zip") == _make_financial_dat()
assert isinstance(await td.get_company_info_category(1, "600000"), list)
assert isinstance(await td.get_company_info_content(
1, "600000", "f.txt"), str)
assert await td.get_block_info("block_gn.dat") == b"abcd"
assert await td.get_report_file("tdxhy.cfg") == b"abcd"
assert (await td.get_file_meta("x.dat")).size == 4
assert await td.download_file("x.dat") == b"abcd"
async def test_aliases_boards(td):
for name in ("get_board_list", "get_belong_board", "get_symbol_info"):
_use(name)
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
assert isinstance(await td.get_board_list(0), list)
assert isinstance(await td.get_belong_board(1, "600000"), list)
snap = await td.get_symbol_info(1, "600000")
assert snap is not None and snap.name == "浦发银行"
async def test_aliases_goods(td):
for name in ("get_goods_list", "get_goods_count", "get_goods_quotes",
"get_goods_quotes_list", "get_goods_chart_sampling",
"get_goods_tick_chart", "get_goods_transaction",
"get_goods_transaction_all"):
_use(name)
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
assert isinstance(await td.get_goods_list(31), list)
assert await td.get_goods_count(31) == 1 # 只有 1 条 market=31
assert isinstance(await td.get_goods_quotes([(31, "00700")]), list)
assert isinstance(await td.get_goods_quotes_list(31), list)
assert await td.get_goods_chart_sampling(31, "00700") == [99.0, 98.0]
assert isinstance(await td.get_goods_tick_chart(31, "00700"), list)
assert isinstance(await td.get_goods_transaction(31, "00700"), list)
assert isinstance(await td.get_goods_transaction_all(31, "00700"), list)
# --------------------------------------------------------------------------- #
# 八、覆盖完整性(必须放最后)
# --------------------------------------------------------------------------- #
def test_every_public_method_was_exercised():
expected = _public_methods()
missing = sorted(expected - EXERCISED)
assert not missing, f"以下公开方法未被回归测试覆盖: {missing}"
extra = sorted(EXERCISED - expected)
assert not extra, f"覆盖集合包含非公开方法: {extra}"
+147 -9
View File
@@ -6,14 +6,19 @@ from __future__ import annotations
import io import io
import struct import struct
import unittest.mock as mock
import zipfile import zipfile
from unittest import mock
import pytest import pytest
from pytdxdata.api import TdxData from pytdxdata.api import TdxData
from pytdxdata.codec.block import infer_block_category, parse_block_dat from pytdxdata.codec.block import infer_block_category, parse_block_dat
from pytdxdata.codec.financial import parse_financial_dat, parse_financial_file_list from pytdxdata.codec.financial import (
extract_gpcw_dat,
looks_like_gpcw_dat,
parse_financial_dat,
parse_financial_file_list,
)
from pytdxdata.codec.industry import parse_tdxhy_cfg from pytdxdata.codec.industry import parse_tdxhy_cfg
from pytdxdata.models import FinancialFileInfo, FinancialRecord, IndustryInfo, TdxBlock from pytdxdata.models import FinancialFileInfo, FinancialRecord, IndustryInfo, TdxBlock
@@ -252,7 +257,7 @@ def _new_tdxdata() -> TdxData:
async def test_api_get_block_parsed(): async def test_api_get_block_parsed():
td = _new_tdxdata() td = _new_tdxdata()
raw = _make_block_dat([("银行", ["000001"], 1, 1)]) raw = _make_block_dat([("银行", ["000001"], 1, 1)])
with mock.patch.object(td, "get_block_info", new=mock.AsyncMock(return_value=raw)): with mock.patch.object(td, "get_file", new=mock.AsyncMock(return_value=raw)):
blocks = await td.get_block_parsed("block_gn.dat") blocks = await td.get_block_parsed("block_gn.dat")
assert len(blocks) == 1 assert len(blocks) == 1
assert blocks[0].category == 2 # gn -> 概念 assert blocks[0].category == 2 # gn -> 概念
@@ -263,7 +268,7 @@ async def test_api_get_industry_map():
td = _new_tdxdata() td = _new_tdxdata()
raw = "0|000001|A01|||S01\n".encode("gbk") raw = "0|000001|A01|||S01\n".encode("gbk")
patched = mock.AsyncMock(return_value=raw) patched = mock.AsyncMock(return_value=raw)
with mock.patch.object(td, "get_report_file", new=patched): with mock.patch.object(td, "get_file", new=patched):
result = await td.get_industry_map() result = await td.get_industry_map()
patched.assert_awaited_once_with("tdxhy.cfg") patched.assert_awaited_once_with("tdxhy.cfg")
assert result["000001"].sw_industry == "S01" assert result["000001"].sw_industry == "S01"
@@ -274,7 +279,7 @@ async def test_api_get_financial_file_infos():
td = _new_tdxdata() td = _new_tdxdata()
raw = b"gpcw20260331.zip,abc,1024\n" raw = b"gpcw20260331.zip,abc,1024\n"
patched = mock.AsyncMock(return_value=raw) patched = mock.AsyncMock(return_value=raw)
with mock.patch.object(td, "get_report_file", new=patched): with mock.patch.object(td, "get_file", new=patched):
infos = await td.get_financial_file_infos() infos = await td.get_financial_file_infos()
patched.assert_awaited_once_with("tdxfin/gpcw.txt") patched.assert_awaited_once_with("tdxfin/gpcw.txt")
assert infos[0].filesize == 1024 assert infos[0].filesize == 1024
@@ -284,7 +289,7 @@ async def test_api_get_financial_file_infos():
async def test_api_get_financial_records_parsed(): async def test_api_get_financial_records_parsed():
td = _new_tdxdata() td = _new_tdxdata()
zip_bytes = _make_financial_zip(_valid_two_record_dat()) zip_bytes = _make_financial_zip(_valid_two_record_dat())
with mock.patch.object(td, "get_report_file", with mock.patch.object(td, "get_file",
new=mock.AsyncMock(return_value=zip_bytes)): new=mock.AsyncMock(return_value=zip_bytes)):
recs = await td.get_financial_records_parsed("tdxfin/gpcw20260331.zip") recs = await td.get_financial_records_parsed("tdxfin/gpcw20260331.zip")
assert len(recs) == 2 assert len(recs) == 2
@@ -294,7 +299,7 @@ async def test_api_get_financial_records_parsed():
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_api_get_financial_records_parsed_empty_zip_data(): async def test_api_get_financial_records_parsed_empty_zip_data():
td = _new_tdxdata() td = _new_tdxdata()
with mock.patch.object(td, "get_report_file", with mock.patch.object(td, "get_file",
new=mock.AsyncMock(return_value=b"")): new=mock.AsyncMock(return_value=b"")):
assert await td.get_financial_records_parsed("tdxfin/gpcw20260331.zip") == [] assert await td.get_financial_records_parsed("tdxfin/gpcw20260331.zip") == []
@@ -303,7 +308,7 @@ async def test_api_get_financial_records_parsed_empty_zip_data():
async def test_api_get_financial_records_parsed_no_dat_member(): async def test_api_get_financial_records_parsed_no_dat_member():
td = _new_tdxdata() td = _new_tdxdata()
zip_bytes = _make_financial_zip(b"whatever", inner_name="readme.txt") zip_bytes = _make_financial_zip(b"whatever", inner_name="readme.txt")
with mock.patch.object(td, "get_report_file", with mock.patch.object(td, "get_file",
new=mock.AsyncMock(return_value=zip_bytes)): new=mock.AsyncMock(return_value=zip_bytes)):
assert await td.get_financial_records_parsed("nodate.zip") == [] assert await td.get_financial_records_parsed("nodate.zip") == []
@@ -313,7 +318,140 @@ async def test_api_get_financial_records_parsed_no_date_in_name():
"""文件名无 8 位日期 -> 回退用 .dat 头部报告期。""" """文件名无 8 位日期 -> 回退用 .dat 头部报告期。"""
td = _new_tdxdata() td = _new_tdxdata()
zip_bytes = _make_financial_zip(_valid_two_record_dat()) zip_bytes = _make_financial_zip(_valid_two_record_dat())
with mock.patch.object(td, "get_report_file", with mock.patch.object(td, "get_file",
new=mock.AsyncMock(return_value=zip_bytes)): new=mock.AsyncMock(return_value=zip_bytes)):
recs = await td.get_financial_records_parsed("gpcw.zip") recs = await td.get_financial_records_parsed("gpcw.zip")
assert recs[0].report_date == 20260331 assert recs[0].report_date == 20260331
# --------------------------------------------------------------------------- #
# looks_like_gpcw_dat / extract_gpcw_dat(BUG-2 修复的判据层)
# --------------------------------------------------------------------------- #
def test_looks_like_gpcw_dat_accepts_real_dat():
assert looks_like_gpcw_dat(_valid_two_record_dat()) is True
def test_looks_like_gpcw_dat_rejects_short_shell():
"""服务器对不存在的文件名回的空壳(0~1 字节)必须判否。"""
assert looks_like_gpcw_dat(b"") is False
assert looks_like_gpcw_dat(b"\x00") is False
assert looks_like_gpcw_dat(b"abcd") is False
def test_looks_like_gpcw_dat_rejects_zero_header():
"""长度够但 header 全零(max_count=0 / report_size=0)也要判否。"""
assert looks_like_gpcw_dat(b"\x00" * 64) is False
def test_looks_like_gpcw_dat_rejects_report_size_not_multiple_of_4():
data = _make_dat_raw([(b"600000", 1, 31)], struct.pack("<2f", 1.0, 2.0),
report_size=6)
assert looks_like_gpcw_dat(data) is False
def test_looks_like_gpcw_dat_rejects_truncated_index():
"""header 声称的条目数超出实际长度 -> 判否。"""
data = _make_dat_raw([(b"600000", 1, 31)], struct.pack("<2f", 1.0, 2.0),
max_count=100)
assert looks_like_gpcw_dat(data) is False
def test_extract_gpcw_dat_from_uncompressed():
dat = _valid_two_record_dat()
assert extract_gpcw_dat(dat) == dat
def test_extract_gpcw_dat_from_zip():
dat = _valid_two_record_dat()
assert extract_gpcw_dat(_make_financial_zip(dat)) == dat
def test_extract_gpcw_dat_empty_and_garbage():
assert extract_gpcw_dat(b"") == b""
assert extract_gpcw_dat(b"\x00") == b""
assert extract_gpcw_dat(b"not a financial file") == b""
def test_extract_gpcw_dat_zip_without_dat_member():
assert extract_gpcw_dat(_make_financial_zip(b"x", inner_name="readme.txt")) == b""
def test_extract_gpcw_dat_zip_with_invalid_inner_dat():
"""zip 里虽有 .dat,但内容不是有效财报数据 -> 空。"""
assert extract_gpcw_dat(_make_financial_zip(b"\x00" * 4)) == b""
def test_extract_gpcw_dat_broken_zip():
"""以 PK 开头但不是合法 zip -> 空,不抛异常。"""
assert extract_gpcw_dat(b"PK\x03\x04broken-not-a-zip") == b""
# --------------------------------------------------------------------------- #
# TdxData._fetch_financial_dat 候选回退(BUG-2 回归)
# --------------------------------------------------------------------------- #
@pytest.mark.asyncio
async def test_fetch_financial_dat_falls_back_to_uncompressed_dat():
"""索引名 ``gpcw*.zip`` 取不到时,必须回退到服务器实际的 ``tdxfin/*.dat``。"""
td = _new_tdxdata()
dat = _valid_two_record_dat()
seen: list[str] = []
async def fake(name: str) -> bytes:
seen.append(name)
if name == "tdxfin/gpcw20260331.dat":
return dat
if name == "gpcw20260331.zip":
return b"\x00" # 裸名 -> MAC 路由 -> 1 字节空壳
return b"" # 带前缀的 .zip 不存在
with mock.patch.object(td, "get_file", new=fake):
got = await td._fetch_financial_dat("gpcw20260331.zip")
assert got == dat
assert seen == ["tdxfin/gpcw20260331.zip", "tdxfin/gpcw20260331.dat"]
@pytest.mark.asyncio
async def test_fetch_financial_dat_prefers_declared_zip_when_present():
"""服务器若恢复提供 .zip,应优先用索引声明的那个名字。"""
td = _new_tdxdata()
dat = _valid_two_record_dat()
seen: list[str] = []
async def fake(name: str) -> bytes:
seen.append(name)
return _make_financial_zip(dat)
with mock.patch.object(td, "get_file", new=fake):
got = await td._fetch_financial_dat("tdxfin/gpcw20260331.zip")
assert got == dat
assert seen == ["tdxfin/gpcw20260331.zip"]
@pytest.mark.asyncio
async def test_fetch_financial_dat_skips_raising_candidate():
"""某个候选取回时抛异常,不应中断,继续试后面的候选。"""
td = _new_tdxdata()
dat = _valid_two_record_dat()
async def fake(name: str) -> bytes:
if name.endswith(".zip"):
raise ConnectionError("模拟网络错误")
return dat
with mock.patch.object(td, "get_file", new=fake):
assert await td._fetch_financial_dat("gpcw20260331.zip") == dat
@pytest.mark.asyncio
async def test_fetch_financial_dat_all_candidates_fail_returns_empty():
td = _new_tdxdata()
async def fake(name: str) -> bytes:
return b""
with mock.patch.object(td, "get_file", new=fake):
assert await td._fetch_financial_dat("gpcw20260331.zip") == b""
+116
View File
@@ -0,0 +1,116 @@
"""ExPool 背压/并发语义回归(Issue #1:并发超限 0.15s 秒失败)。
用 mock 连接模拟:单服务器 + per_server_cap=1 时,
- 并发 acquire 超过有效并发 → 排队等待而不是快速失败;
- release 唤醒等待者;
- acquire 超时异常带池状态;
- ex_pool_cap 提升同主机并发。
"""
from __future__ import annotations
import asyncio
import time
import pytest
from pytdxdata.pool.ex_pool import ExPool, ExPoolTimeoutError
class MockConn:
"""Minimal stand-in for ExTdxConnection."""
last_created = 0
def __init__(self, host: str, port: int, timeout: float, handshake: str = "login"):
self.host = host
self.port = port
self.alive = True
self.last_used = time.monotonic()
self.closed = False
MockConn.last_created += 1
async def connect(self) -> None:
await asyncio.sleep(0) # instant "connect"
async def close(self) -> None:
self.closed = True
self.alive = False
@pytest.fixture
def patch_conn(monkeypatch):
monkeypatch.setattr("pytdxdata.pool.ex_pool.ExTdxConnection", MockConn)
MockConn.last_created = 0
async def test_acquire_queues_instead_of_fast_fail(patch_conn):
"""并发 > 有效并发时,后续 acquire 等待 release,而非 0.15s 抛错。"""
pool = ExPool(["e1"], min_size=1, max_size=6, per_server_cap=1)
await pool.start()
c1 = await pool.acquire() # 唯一连接被占用
t0 = time.monotonic()
async def holder():
await asyncio.sleep(0.5) # 持有 0.5s 后归还
await pool.release(c1)
asyncio.create_task(holder())
c2 = await pool.acquire() # 应在 ~0.5s 后拿到,而不是 0.15s 抛错
waited = time.monotonic() - t0
assert waited >= 0.4, f"acquire 没有等待释放(仅 {waited:.2f}s)"
assert c2 is c1 # 归还的是同一条连接
async def test_acquire_timeout_carries_pool_state(patch_conn):
"""超时异常信息带池状态(idle/total/servers/cap)。"""
pool = ExPool(["e1"], min_size=1, max_size=6, per_server_cap=1, acquire_timeout=0.3)
await pool.start()
c1 = await pool.acquire()
with pytest.raises(ExPoolTimeoutError) as ei:
await pool.acquire()
msg = str(ei.value)
assert "total=1" in msg and "per_server_cap=1" in msg and "servers=1" in msg
await pool.release(c1)
async def test_ex_pool_cap_allows_parallel_conns_same_host(patch_conn):
"""per_server_cap=2 时单主机可并发持有 2 条连接。"""
pool = ExPool(["e1"], min_size=1, max_size=6, per_server_cap=2)
await pool.start()
got = await asyncio.gather(pool.acquire(), pool.acquire())
assert len(got) == 2 and got[0] is not got[1]
assert MockConn.last_created == 2
for c in got:
await pool.release(c)
async def test_concurrent_acquire_all_succeed(patch_conn):
"""Issue 场景:单服务器 + cap=2,6 个并发任务应全部拿到连接(排队)而非部分失败。"""
pool = ExPool(["e1"], min_size=2, max_size=6, per_server_cap=2)
await pool.start()
async def task(i):
c = await pool.acquire()
await asyncio.sleep(0.1) # 模拟一次 1m 分页拉取
await pool.release(c)
return i
results = await asyncio.gather(*[task(i) for i in range(6)])
assert sorted(results) == list(range(6)) # 全部成功,零失败
async def test_release_notifies_waiters(patch_conn):
"""broken 归还(连接死亡)也要唤醒等待者(槽位回收后可扩容)。"""
pool = ExPool(["e1"], min_size=1, max_size=1, per_server_cap=1)
await pool.start()
c1 = await pool.acquire()
c1.alive = False
async def broken_release():
await asyncio.sleep(0.2)
await pool.release(c1, broken=True)
asyncio.create_task(broken_release())
c2 = await pool.acquire() # 槽位被回收→扩容新建
assert c2 is not c1
await pool.release(c2)
+365
View File
@@ -0,0 +1,365 @@
"""当日测速缓存单元测试(注入假探针与假日期,不连真实网络)
覆盖点:
- 当日首次启动测一次;当天已有缓存则**不刷新**(探针一次都不发起)
- 跨日 / 缓存损坏 / 版本不符 → 重新测速
- 结果按实测延迟升序被 config 采用
- **绝不改写包内 servers.json**,缓存落在用户级缓存目录
- 全部不可达 → 不写缓存(下次启动重试)
- 并发调用只真正测一次(单飞)
- 非法主机名(测试 mock 混入的 "s1" 等)被挡在测速之外
- 连接池 start() 不阻塞、close() 会取消后台测速
"""
from __future__ import annotations
import asyncio
import json
import time
from datetime import date, timedelta
from pathlib import Path
import pytest
from pytdxdata import config
from pytdxdata.pool.probe_cache import ProbeCache
TODAY = date.today().isoformat()
YESTERDAY = (date.today() - timedelta(days=1)).isoformat()
PROTOS = ("standard", "mac", "ex")
@pytest.fixture(autouse=True)
def isolated_cache(tmp_path, monkeypatch):
"""把用户级缓存目录指到临时目录,并复位所有相关环境变量。"""
monkeypatch.setenv("PYPYTDX_DATA_CACHE_DIR", str(tmp_path))
monkeypatch.delenv("PYPYTDX_DATA_DISABLE_PROBE", raising=False)
for var in ("PYPYTDX_DATA_STANDARD_HOSTS", "PYPYTDX_DATA_MAC_HOSTS",
"PYPYTDX_DATA_EX_HOSTS"):
monkeypatch.delenv(var, raising=False)
return tmp_path
def fake_probers(latencies: dict[str, dict[str, float | None]], calls: list):
"""构造假探针;latencies = {协议: {主机: 延迟或 None}}。"""
def _make(protocol: str):
async def _probe(host: str, timeout: float) -> float | None:
calls.append((protocol, host))
return latencies.get(protocol, {}).get(host)
return _probe
return {p: _make(p) for p in PROTOS}
def patch_candidates(monkeypatch, mapping: dict[str, list[str]]) -> None:
"""把"全量候选"换成受控清单,避免依赖真实服务器清单。"""
monkeypatch.setattr("pytdxdata.pool.probe_cache.all_probe_candidates",
lambda: mapping)
def write_cache(path: Path, day: str, results: dict, version: int = 1) -> None:
path.write_text(json.dumps({"version": version, "date": day, "results": results}),
encoding="utf-8")
# ---------- 是否该测速 ----------
def test_needs_probe_when_no_cache(tmp_path):
pc = ProbeCache(tmp_path / "c.json", today_fn=lambda: TODAY)
assert pc.needs_probe_today() is True
assert pc.read_cache() is None
def test_needs_probe_false_for_today_cache(tmp_path):
cache = tmp_path / "c.json"
write_cache(cache, TODAY, {"1.1.1.1": {"standard": 0.05}})
pc = ProbeCache(cache, today_fn=lambda: TODAY)
assert pc.needs_probe_today() is False
def test_stale_cache_needs_probe(tmp_path):
cache = tmp_path / "c.json"
write_cache(cache, YESTERDAY, {"1.1.1.1": {"standard": 0.05}})
pc = ProbeCache(cache, today_fn=lambda: TODAY)
assert pc.needs_probe_today() is True
def test_version_mismatch_needs_probe(tmp_path):
cache = tmp_path / "c.json"
write_cache(cache, TODAY, {"1.1.1.1": {"standard": 0.05}}, version=999)
pc = ProbeCache(cache, today_fn=lambda: TODAY)
assert pc.needs_probe_today() is True
@pytest.mark.parametrize("content", ["{not json", "[]", '{"version":1}', ""])
def test_broken_cache_is_ignored_not_crash(tmp_path, content):
cache = tmp_path / "c.json"
cache.write_text(content, encoding="utf-8")
pc = ProbeCache(cache, today_fn=lambda: TODAY)
assert pc.read_cache() is None
assert pc.needs_probe_today() is True
# ---------- 核心行为:当天已有缓存就不刷新 ----------
async def test_today_cache_is_not_refreshed(tmp_path, monkeypatch):
cache = tmp_path / "c.json"
write_cache(cache, TODAY, {"1.1.1.1": {"standard": 0.05}})
before = cache.read_text(encoding="utf-8")
calls: list = []
patch_candidates(monkeypatch, {"standard": ["1.1.1.1"], "mac": [], "ex": []})
pc = ProbeCache(cache, probers=fake_probers({}, calls), today_fn=lambda: TODAY)
await pc.ensure_probe()
assert calls == [] # 未发起任何测速
assert cache.read_text(encoding="utf-8") == before # 缓存内容原封不动
async def test_stale_cache_is_refreshed(tmp_path, monkeypatch):
cache = tmp_path / "c.json"
write_cache(cache, YESTERDAY, {"9.9.9.9": {"standard": 9.0}})
calls: list = []
patch_candidates(monkeypatch, {"standard": ["1.1.1.1"], "mac": [], "ex": []})
pc = ProbeCache(cache,
probers=fake_probers({"standard": {"1.1.1.1": 0.02}}, calls),
today_fn=lambda: TODAY)
await pc.ensure_probe()
assert calls == [("standard", "1.1.1.1")]
data = json.loads(cache.read_text(encoding="utf-8"))
assert data["date"] == TODAY and data["version"] == config.PROBE_CACHE_VERSION
assert data["results"] == {"1.1.1.1": {"standard": 0.02}}
assert data["hosts"]["standard"] == ["1.1.1.1"]
assert "9.9.9.9" not in data["results"] # 旧结果被整体替换,不残留
# ---------- 缓存写入 ----------
async def test_write_is_atomic_and_leaves_no_tmp(tmp_path, monkeypatch):
cache = tmp_path / "sub" / "c.json" # 目录不存在也要能建
patch_candidates(monkeypatch, {"standard": ["1.1.1.1"], "mac": [], "ex": []})
pc = ProbeCache(cache,
probers=fake_probers({"standard": {"1.1.1.1": 0.03}}, []),
today_fn=lambda: TODAY)
await pc.ensure_probe()
assert cache.exists()
assert list(cache.parent.glob("*.tmp*")) == []
assert json.loads(cache.read_text(encoding="utf-8"))["probed_at"]
async def test_all_unreachable_writes_nothing(tmp_path, monkeypatch):
cache = tmp_path / "c.json"
patch_candidates(monkeypatch, {"standard": ["1.1.1.1"], "mac": [], "ex": []})
pc = ProbeCache(cache, probers=fake_probers({}, []), today_fn=lambda: TODAY)
await pc.ensure_probe()
assert not cache.exists() # 不把"全挂"缓存一整天
assert pc.needs_probe_today() is True
async def test_never_touches_package_servers_json(tmp_path, monkeypatch):
"""最关键的一条:测速**绝不能**改写随包分发的 servers.json。"""
servers_json = config._SERVERS_FILE
before_bytes = servers_json.read_bytes()
before_mtime = servers_json.stat().st_mtime_ns
patch_candidates(monkeypatch, {"standard": ["1.1.1.1"], "mac": [], "ex": []})
pc = ProbeCache(probers=fake_probers({"standard": {"1.1.1.1": 0.04}}, []),
today_fn=lambda: TODAY)
await pc.ensure_probe()
assert servers_json.read_bytes() == before_bytes
assert servers_json.stat().st_mtime_ns == before_mtime
assert pc.cache_file() == tmp_path / "hosts-today.json" # 落在用户缓存目录
assert Path(config.probe_cache_file()).parent == tmp_path
async def test_results_are_recorded_per_protocol(tmp_path, monkeypatch):
cache = tmp_path / "c.json"
patch_candidates(monkeypatch, {
"standard": ["1.1.1.1", "2.2.2.2"],
"mac": ["1.1.1.1", "2.2.2.2"],
"ex": ["3.3.3.3"],
})
lats = {"standard": {"1.1.1.1": 0.30, "2.2.2.2": 0.10},
"mac": {"1.1.1.1": 0.20}, # 2.2.2.2 的 mac 故意不给 → 应记为 None
"ex": {"3.3.3.3": 0.05}}
pc = ProbeCache(cache, probers=fake_probers(lats, []), today_fn=lambda: TODAY)
await pc.ensure_probe()
data = json.loads(cache.read_text(encoding="utf-8"))
assert data["hosts"]["standard"] == ["2.2.2.2", "1.1.1.1"] # 按延迟升序
assert data["hosts"]["mac"] == ["1.1.1.1"] # 不可达的 2.2.2.2 被排除
assert data["hosts"]["ex"] == ["3.3.3.3"]
# 2.2.2.2 的 mac 探针返回 None,也要如实记录(便于事后诊断)
assert data["results"]["2.2.2.2"]["mac"] is None
# ---------- 单飞 / 开关 / 脏数据 ----------
async def test_concurrent_ensure_probe_runs_once(tmp_path, monkeypatch):
patch_candidates(monkeypatch, {"standard": ["1.1.1.1", "2.2.2.2"], "mac": [], "ex": []})
calls: list = []
pc = ProbeCache(tmp_path / "c.json",
probers=fake_probers({"standard": {"1.1.1.1": 0.01,
"2.2.2.2": 0.02}}, calls),
today_fn=lambda: TODAY)
await asyncio.gather(pc.ensure_probe(), pc.ensure_probe(), pc.ensure_probe())
assert sorted(calls) == [("standard", "1.1.1.1"), ("standard", "2.2.2.2")]
async def test_disabled_env_skips_everything(tmp_path, monkeypatch):
monkeypatch.setenv("PYPYTDX_DATA_DISABLE_PROBE", "1")
calls: list = []
patch_candidates(monkeypatch, {"standard": ["1.1.1.1"], "mac": [], "ex": []})
pc = ProbeCache(tmp_path / "c.json",
probers=fake_probers({"standard": {"1.1.1.1": 0.01}}, calls),
today_fn=lambda: TODAY)
assert pc.needs_probe_today() is False
await pc.ensure_probe()
assert calls == []
assert not (tmp_path / "c.json").exists()
async def test_illegal_hosts_are_filtered_out(tmp_path, monkeypatch):
"""测试 mock 常传入 "s1"/"m1" 这类伪主机名,必须挡在缓存之外。"""
patch_candidates(monkeypatch, {"standard": [], "mac": [], "ex": []})
calls: list = []
pc = ProbeCache(tmp_path / "c.json",
probers=fake_probers({"standard": {"1.1.1.1": 0.01}}, calls),
today_fn=lambda: TODAY)
await pc.ensure_probe(["s1", "m1", "1.1.1.1", ""])
assert calls == [("standard", "1.1.1.1")]
data = json.loads((tmp_path / "c.json").read_text(encoding="utf-8"))
assert "s1" not in data["results"] and "m1" not in data["results"]
async def test_reset_allows_recheck(tmp_path, monkeypatch):
patch_candidates(monkeypatch, {"standard": ["1.1.1.1"], "mac": [], "ex": []})
calls: list = []
pc = ProbeCache(tmp_path / "c.json",
probers=fake_probers({"standard": {"1.1.1.1": 0.01}}, calls),
today_fn=lambda: TODAY)
await pc.ensure_probe()
await pc.ensure_probe()
assert len(calls) == 1 # 第二次被单飞挡掉
pc.reset()
await pc.ensure_probe()
assert len(calls) == 1 # 重置后当天已有缓存,仍不重测
# ---------- config 侧:采用顺序与兜底 ----------
def test_config_getters_prefer_cache_and_order_by_latency(tmp_path, monkeypatch):
monkeypatch.setenv("PYPYTDX_DATA_CACHE_DIR", str(tmp_path))
(tmp_path / "hosts-today.json").write_text(json.dumps({
"version": config.PROBE_CACHE_VERSION, "date": TODAY,
"results": {
"3.3.3.3": {"standard": 0.9},
"1.1.1.1": {"standard": 0.05},
"2.2.2.2": {"standard": 0.4, "mac": 0.1},
"9.9.9.9": {"ex": 0.2},
},
}), encoding="utf-8")
assert config.get_standard_hosts() == ["1.1.1.1", "2.2.2.2", "3.3.3.3"]
assert config.get_mac_hosts() == ["2.2.2.2"]
assert config.get_ex_hosts() == ["9.9.9.9"]
def test_config_getters_fall_back_without_cache(tmp_path, monkeypatch):
monkeypatch.setenv("PYPYTDX_DATA_CACHE_DIR", str(tmp_path))
assert config.get_standard_hosts() == config._load_ok_hosts("standard", fast_only=True)
assert config.get_mac_hosts() == config._load_ok_hosts("mac", fast_only=True)
assert config.get_ex_hosts() == config._load_ok_hosts("ex")
def test_env_override_beats_cache(tmp_path, monkeypatch):
monkeypatch.setenv("PYPYTDX_DATA_CACHE_DIR", str(tmp_path))
(tmp_path / "hosts-today.json").write_text(json.dumps({
"version": config.PROBE_CACHE_VERSION, "date": TODAY,
"results": {"1.1.1.1": {"standard": 0.05}},
}), encoding="utf-8")
monkeypatch.setenv("PYPYTDX_DATA_STANDARD_HOSTS", "8.8.8.8")
assert config.get_standard_hosts() == ["8.8.8.8"]
def test_all_probe_candidates_covers_full_set_not_filtered():
cand = config.all_probe_candidates()
assert set(config.STANDARD_HOSTS) <= set(cand["standard"])
assert set(config.MAC_HOSTS) <= set(cand["mac"])
assert set(config.EX_HOSTS) <= set(cand["ex"])
assert "117.34.114.17" in cand["standard"] # 未申报 MAC 的节点也要被测到
assert "s1" not in cand["standard"] # 包内清单里的脏数据被挡
@pytest.mark.parametrize(("host", "expected"), [
("1.2.3.4", True),
("117.34.114.17", True),
("a.b", True),
("good-host.com", True),
("s1", False),
("m1", False),
("", False),
(" ", False),
("-bad.com", False),
("bad-.com", False),
("has space.com", False),
(123, False),
(None, False),
])
def test_is_valid_host(host, expected):
assert config.is_valid_host(host) is expected
# ---------- 连接池集成 ----------
async def test_pool_start_does_not_block_and_close_cancels_probe(monkeypatch):
from pytdxdata.pool import pool as pool_mod
cancel_seen = asyncio.Event()
created: list[asyncio.Task] = []
async def _hang(hosts=None):
try:
await asyncio.sleep(30) # 模拟耗时测速
except asyncio.CancelledError:
cancel_seen.set()
raise
def _fake_schedule(hosts=None):
task = asyncio.create_task(_hang())
created.append(task)
return task
monkeypatch.setattr(pool_mod, "schedule_probe", _fake_schedule)
p = pool_mod.DynamicPool([], min_size=1, max_size=1)
t0 = time.monotonic()
await p.start()
assert time.monotonic() - t0 < 1.0 # start() 不等测速
assert p._probe_task is created[0]
await asyncio.sleep(0) # 让测速任务真正跑起来再关闭
await p.close()
assert p._probe_task is None
assert created[0].cancelled()
assert cancel_seen.is_set()
async def test_pool_auto_probe_false_schedules_nothing(monkeypatch):
from pytdxdata.pool import pool as pool_mod
def _boom(hosts=None): # pragma: no cover - 不应被调用
raise AssertionError("auto_probe=False 时不应调度测速")
monkeypatch.setattr(pool_mod, "schedule_probe", _boom)
p = pool_mod.DynamicPool([], min_size=1, max_size=1, auto_probe=False)
await p.start()
assert p._probe_task is None
await p.close()
+114 -4
View File
@@ -2,17 +2,20 @@
from __future__ import annotations from __future__ import annotations
import struct import struct
from collections import Counter
from datetime import date, datetime
import pytest import pytest
from pytdxdata.protocol.frame import FrameHeader, decompress_body, parse_header from pytdxdata.models import Adjust, KlinePeriod, SecurityBar
from pytdxdata.protocol.price import get_price, put_price, decode_ohlc_diffs
from pytdxdata.protocol.volume import decode_volume
from pytdxdata.protocol.commands.ex_proto import GetExInstrumentBarsCmd from pytdxdata.protocol.commands.ex_proto import GetExInstrumentBarsCmd
from pytdxdata.protocol.commands.kline import GetSecurityBarsCmd from pytdxdata.protocol.commands.kline import GetSecurityBarsCmd
from pytdxdata.protocol.commands.mac import MacKlineCmd
from pytdxdata.protocol.commands.minute import GetHistoryMinuteTimeDataCmd from pytdxdata.protocol.commands.minute import GetHistoryMinuteTimeDataCmd
from pytdxdata.protocol.commands.transaction import MacTransactionCmd from pytdxdata.protocol.commands.transaction import MacTransactionCmd
from pytdxdata.protocol.frame import FrameHeader, decompress_body, parse_header
from pytdxdata.protocol.price import decode_ohlc_diffs, get_price, put_price
from pytdxdata.protocol.volume import decode_volume
# ---------- 变长有符号整数 ---------- # ---------- 变长有符号整数 ----------
@@ -176,3 +179,110 @@ def test_mac_transaction_parse():
assert recs[0].trade_count == 3 assert recs[0].trade_count == 3
assert recs[0].bs_flag == 1 assert recs[0].bs_flag == 1
assert recs[1].trade_count == 1 assert recs[1].trade_count == 1
# ---------- 跨时区时间戳归一化(美股 EX 通道) ----------
#
# 通达信 EX 通道对美股返回的时间戳把两个时区拼在一起:日期字段是**美东交易日**、
# 时分字段是**北京时间**。直拼出的 datetime 会把同一交易日的下午半场(北京
# 00:00~04:00)排到上午半场(北京 21:30~23:59)之前,单日 390 根全部错位。
def _bar(market: int, y: int, mo: int, d: int, h: int, mi: int) -> SecurityBar:
return SecurityBar(market=market, code="X", open=1.0, high=1.0, low=1.0,
close=1.0, vol=1.0, amount=1.0,
year=y, month=mo, day=d, hour=h, minute=mi)
def test_us_evening_segment_keeps_date():
# 北京 21:31 ~ 23:59 与美东交易日属同一自然日,日期不动
b = _bar(74, 2026, 10, 12, 21, 31)
assert b.datetime == datetime(2026, 10, 12, 21, 31)
assert b.trading_date == "2026-10-12"
def test_us_midnight_segment_rolls_to_next_day():
# 北京次日 00:00 ~ 04:00 实际是美东 12:00~16:00,日期要 +1 天
b = _bar(74, 2026, 10, 12, 4, 0)
assert b.datetime == datetime(2026, 10, 13, 4, 0)
assert (b.hour, b.minute) == (4, 0) # 时分不参与归一化
assert b.trading_date == "2026-10-12" # 仍归属美东 10-12 交易日
def test_us_split_hour_boundary():
assert _bar(74, 2026, 10, 12, 11, 59).day == 13
assert _bar(74, 2026, 10, 12, 12, 0).day == 12
def test_us_month_and_year_rollover():
assert _bar(74, 2026, 10, 31, 4, 0).datetime == datetime(2026, 11, 1, 4, 0)
assert _bar(74, 2026, 12, 31, 4, 0).datetime == datetime(2027, 1, 1, 4, 0)
def test_cn_and_hk_bars_untouched():
cn = _bar(1, 2026, 10, 12, 9, 31) # A股/标准通道
assert (cn.year, cn.month, cn.day) == (2026, 10, 12)
assert cn.trading_date == "2026-10-12"
hk = _bar(31, 2026, 10, 12, 4, 0) # 港股同为 UTC+8,凌晨段不应 +1
assert (hk.year, hk.month, hk.day) == (2026, 10, 12)
assert hk.trading_date == "2026-10-12"
def test_us_full_session_is_monotonic_and_single_trading_day():
# 实测口径:北京 21:31~23:59(149 根)+ 次日 00:00~04:00(241 根)= 390 根
mins = list(range(21 * 60 + 31, 24 * 60)) + list(range(4 * 60 + 1))
assert len(mins) == 390
bars = [_bar(74, 2026, 10, 12, m // 60, m % 60) for m in mins]
bars.sort(key=lambda b: b.datetime)
dts = [b.datetime for b in bars]
assert dts == sorted(dts) # 归一化后严格单调
assert dts[0] == datetime(2026, 10, 12, 21, 31)
assert dts[-1] == datetime(2026, 10, 13, 4, 0)
# 全部归属于同一个美东交易日
assert {b.trading_date for b in bars} == {"2026-10-12"}
# 但横跨两个北京自然日(这正是不能用 datetime.date() 聚合的原因)
by_day = Counter(b.datetime.date() for b in bars)
assert by_day[date(2026, 10, 12)] == 149
assert by_day[date(2026, 10, 13)] == 241
# ---------- MAC 通道 K线(0x122E)同样归一化 ----------
def _mac_bars_body(records: list[tuple[int, int]]) -> bytes:
"""构造 0x122E 响应体:33B头(count@24) + 每条36B(4B ymd + 4B time秒 + 7float)。"""
body = bytearray(33 + len(records) * 36)
struct.pack_into("<HBHI", body, 24, 7, 1, len(records), 0)
for i, (ymd, tsec) in enumerate(records):
struct.pack_into("<II7f", body, 33 + i * 36,
ymd, tsec, 10.0, 10.5, 9.5, 10.2, 0.0, 1000.0, 0.0)
return bytes(body)
def test_mac_kline_us_bar_normalized():
# _probe_bar(日期区间二分依赖它)对美股走的就是这条命令
cmd = MacKlineCmd(74, "AAPL", KlinePeriod.MIN_1, Adjust.NONE, 0, 5)
bars = cmd.parse_response(_mac_bars_body([(20261012, 4 * 3600)])) # 北京 04:00
assert len(bars) == 1
assert bars[0].datetime == datetime(2026, 10, 13, 4, 0)
assert bars[0].trading_date == "2026-10-12"
def test_mac_kline_hk_bar_untouched():
cmd = MacKlineCmd(31, "00700", KlinePeriod.MIN_1, Adjust.NONE, 0, 5)
bars = cmd.parse_response(_mac_bars_body([(20260729, 13 * 3600 + 40 * 60)]))
assert (bars[0].datetime) == datetime(2026, 7, 29, 13, 40)
assert bars[0].trading_date == "2026-07-29"
# ---------- 排序:EX 返回顺序按时间正序(切片取「最新 N 根」依赖它) ----------
def test_finish_bars_sorts_us_session_chronologically():
from pytdxdata.api import TdxData
from pytdxdata.symbols import parse_symbols
sym = parse_symbols("usAAPL")[0]
# 故意按错误的顺序给(凌晨段在前)
out = TdxData._finish_bars([_bar(74, 2026, 10, 12, 4, 0),
_bar(74, 2026, 10, 12, 21, 31)], sym)
assert [b.datetime for b in out] == [datetime(2026, 10, 12, 21, 31),
datetime(2026, 10, 13, 4, 0)]
assert {b.symbol for b in out} == {"usAAPL"}
Generated
+1 -1
View File
@@ -535,7 +535,7 @@ wheels = [
[[package]] [[package]]
name = "pytdxdata" name = "pytdxdata"
version = "0.5.0" version = "0.6.2"
source = { editable = "." } source = { editable = "." }
[package.optional-dependencies] [package.optional-dependencies]