5 Commits
Author SHA1 Message Date
openbotandopenbot-coder 76644919de feat: 价格小数位改用协议权威值(SecurityInfo.decimal_point) (#7)
0.6.5 用「代码前缀推断 + 全量清单离线校验」修好了债券/回购标度,但同一份证券
清单接口本来就返回 decimal_point,权威值一直没接进取数路径。本次接进来:

- price_decimal_digits:查找顺序改为 权威表 -> 静态前缀规则(兜底)
- decimal_sync(新模块):每日后台同步一次 + 磁盘缓存 + 原子写
- TdxData.sync_decimal_points() / decimal_point_status()
- start() 不阻塞:当日缓存命中直接装表(60ms 零网络),否则挂后台 task
- PYPYTDX_DATA_DISABLE_DECIMAL_SYNC=1 关闭

表按三位前缀归并(全量 5 万只 -> 129 条);若某前缀出现混合小数位则自动退化为
逐代码表,只存例外,mixed_prefixes 可观测。

实测:全量 51,982 条权威表与静态规则零分歧;首次同步 50s(后台),
热缓存 60ms。测试 289 -> 306。

Co-authored-by: openbot-coder <openbot-coder@users.noreply.github.com>
2026-10-22 16:25:09 +08:00
openbotandopenbot-coder b84a6c8a1b feat: 指数成分成交汇总 + 债券/回购价格标度修复 + 美股分时 hour 修复 (0.6.5) (#6)
* feat: 指数成分成交汇总 + 债券/回购价格标度修复 + 美股分时 hour 修复

新增
- get_index_members / get_index_trade_stats / get_index_trade_stats_multi:
  由成分股逐笔累加出指数的每分钟成交量与成交笔数(协议里指数本身没有笔数,
  trade_count 实为均价*1000)
- CLI: tdx index-stats

修复
- price_decimal_digits 补齐债券/回购 4 位小数档:沪市少 100 倍、深市少 10 倍,
  沪市 B 股 900xxx 改为 3 位。已用全量 51982 只标的的 SecurityInfo.decimal_point
  逐条比对,零例外
- MinuteBar.hour 对美股(EX)出现 24~27:改为 hour%=24 + day_offset,
  新增 datetime / trading_date 只读属性;A股/港股零行为变化

测试 217 -> 289

* chore: bump version 0.6.5

---------

Co-authored-by: openbot-coder <openbot-coder@users.noreply.github.com>
2026-10-22 13:54:35 +08:00
openbotandopenbot-coder ca24521d2c chore: bump version 0.6.4 (#5)
Co-authored-by: openbot-coder <openbot-coder@users.noreply.github.com>
2026-10-22 09:11:50 +08:00
openbotandopenbot-coder 8344ed6e6b fix: 修复沪市指数价格少10倍 + 逐笔竞价委托污染(Σvol 虚高/跨主机不稳定) (#3)
核对 sh000016 上证50 与 50 只成分股的 tick 汇总时,发现三个口径
(快照/分时/逐笔)互不一致,追查到 5 个缺陷。

1. 沪市指数价格整体少 10 倍
   price_decimal_digits 把沪市 000xxx(上证/上证50/沪深300/科创50)与
   8xxxxx(板块指数)判为 3 位小数,实际协议是 2 位。
   上证指数 3713 -> 371、上证50 2747 -> 274。
   实证 6 只指数 + 2 只板块指数全部 ×10,而 ETF/股票/科创板/深市全类 ×1 正确。
   改法:沪市仅 ETF(5开头) 保留 3 位,其余 2 位。

2. get_ticks 把 bs_flag=8 竞价委托当成成交
   该记录是 09:15~09:25 / 14:57~15:00 竞价段的撮合委托快照,
   vol 是累计值(可被后续覆盖),不是成交增量。
   - Σvol 虚高:sh600000 含 b8 = 668,693 vs 快照 462,562(1.4456);
     剔 b8 = 462,634(1.000156,精确一致)
   - 跨主机不稳定:干净主机 0 条、脏主机 135 条 -> 同一 start 落到不同真实成交
   改法:分页后统一剔除 b8。

3. A股逐笔改单连接串行游标(_ticks_cn_serial)
   并发分页各页来自不同主机,而 0x122F 的 start 是「从最新往回数」的相对锚点,
   主机间 b8 收录差异导致页边界既重叠(冗余 116 条)又漏条(13:03 附近丢 59 条)。
   逐笔单日仅 5~6 页,串行开销可忽略。

4. trade_count 有符号解析(前序)、返回列表时间序(前序)保留。

- sh000016 三口径闭合:快照 vol/amount 比值 1.00000061/0.99999997;
  指数逐笔 Σvol = 分时 Σvol = 1,045,584,467(完全相等)
- 6 只标的 Σvol/快照 vol 全部回到 1.0001~1.0007
- 跨主机公共时间窗逐条一致(5/5 标的,条数差 0)
- 测试 194 -> 217 passed(+20 小数位、+3 逐笔回归)

- TransactionRecord 类注释 + get_ticks docstring 明示指数语义:
  vol 单位「百元」(成交额/100)、trade_count 为「均价×1000」而非笔数
- API_REFERENCE / llms.txt 同步

Co-authored-by: openbot-coder <openbot-coder@users.noreply.github.com>
2026-10-22 09:06:40 +08:00
openbotandopenbot-coder dfd6fab3af fix: 补齐 v0.6.3 遗漏的版本号(__init__.py / uv.lock) (#4)
## 问题
v0.6.3 的 bump 提交只改了 pyproject.toml 一处,漏掉:
- src/pytdxdata/__init__.py 的 __version__
- uv.lock 的 pytdxdata 条目版本

后果(远端 main 已复现):
- CI 两个 job 全部失败:`uv sync --locked` 报
  "The lockfile at `uv.lock` needs to be updated, but `--locked` was provided"
- Docs / Release 同样失败
- v0.6.3 tag 已打,但 PyPI 上 0.6.3 仍是 404(发布没成功)

## 修复
补齐两处版本号,四处对齐:pyproject.toml / __init__.py / uv.lock / CHANGELOG.md

## 验证
- `uv sync --locked` 退出码 0
- `pytdxdata.__version__` = `importlib.metadata.version()` = 0.6.3

Co-authored-by: openbot-coder <openbot-coder@users.noreply.github.com>
2026-10-22 08:52:19 +08:00
22 changed files with 1394 additions and 497 deletions

No files matched your search

+237 -10
View File
@@ -2,21 +2,248 @@
本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
## [0.6.7] - 2026-10-22
## [0.6.6] - 2026-10-22
### 新增
- `get_index_members` / `get_index_trade_stats` / `get_index_trade_stats_multi`:指数成分股与逐笔聚合统计(分钟级增量;北交所成分无笔数自动剔除)
- `sync_decimal_points` / `decimal_point_status`:权威价格小数位表运行时同步(报价标度不再依赖硬编码前缀规则),`start()` 自动装载
- `decimal_sync` 模块
### 改进
### 修复
- **指数/ETF/LOF 逐笔的 `trade_count` 语义修正**:协议字段在指数上是「均价×1000」、ETF/LOF 上是「价格×1000」,**不是笔数**;新增 `TransactionRecord.trade_count_available`(判定见 `symbols.has_order_count`),CLI 对无笔数口径标的显示 `(-)` 而非假笔数
- 集合竞价委托(bs_flag=8)不再混入逐笔结果(会被覆盖、Σvol 虚高 20%~160%、不同主机条数不一致)
- 缓存管理器 / 连接池 / 分页调度若干健壮性修复
- **价格小数位改用协议自带的权威值,前缀规则降为兜底**。
0.6.5 修好债券/回购标度时,采用的是「按代码前缀推断」+「用全量清单做离线校验」。
但同一份证券清单接口(`get_universe`,底层 `GetSecurityListCmd`)本来就**返回**
`SecurityInfo.decimal_point`(外加自描述浮点的 `pre_close`)——权威值一直就在手上,
只是没接进取数路径。本次把它接进来:
| 位置 | 说明 |
|---|---|
| `price_decimal_digits` | 查找顺序改为 **权威表 → 静态前缀规则**,未同步时行为与 0.6.5 完全一致 |
| `decimal_sync`(新模块) | 每日后台同步一次 + 磁盘缓存(`%LOCALAPPDATA%\pytdxdata\decimal-points.json`) |
| `TdxData.sync_decimal_points()` | 手动强制刷新(排障 / 立刻要权威表) |
| `TdxData.decimal_point_status()` | 状态:`source` / `stock` / `mixed_prefixes` / `syncing` |
**对用户仍无感**:`start()` 命中当日缓存就直接装表(实测 60 ms、零网络),
未命中则挂后台 task(实测首次 50 s,含沪 27,520 + 深 24,462 条清单),
不阻塞 `start()`(`start()` 仍 1.5 s);`close()` 会取消未完成的同步。
**表结构刻意做小**:全量 5 万只标的只产生 **129 个**「三位前缀 → 小数位」映射,
内存里就是 129 条。若将来某段代码混用两种小数位,该前缀自动退化为**逐代码表**,
只存例外代码(`mixed_prefixes` 会 > 0,可据此发现),不会静默算错。
为什么保留前缀规则:`get_quotes` 解析是纯同步、无网络的路径,解析那一刻可能还没
同步过清单;离线 / 首次安装也必须能出价格。实测两者在全量清单上**零分歧**
(51,982 条逐条比对,不一致 0 条),并存不会造成口径冲突。
开关:`PYPYTDX_DATA_DISABLE_DECIMAL_SYNC=1` 关闭后台同步(CI / 测试用)。
### 说明
- 0.6.4~0.6.6 为中间迭代,未单独发版记录;本次合并 PyPI sdist 与仓库,源码恢复双仓一致
- 新增回归测试 16 项(权威表优先级 / 混合前缀退化 / 缓存跨日失效 / 损坏容错 /
后台任务取消),测试总数 **289 → 306**。
## [0.6.5] - 2026-10-22
### 新增
- **指数成分成交汇总:一条接口拿到「某指数下全部股票的成交量与成交笔数」**
(`get_index_members` / `get_index_trade_stats` / `get_index_trade_stats_multi`)。
起因是一个绕不开的协议事实:**指数本身没有成交笔数**。指数逐笔(`sh000001`)的
`trade_count` 字段实际是「当时均价 × 1000」(2026-10-21 已验证),`get_minutes` /
`get_market_stat` / `SecurityBar` / `get_quotes` 的 160 个字段位里也都**没有**笔数
(扫描 0x122C 全字段位确认,`0x8`/`0x9` 是外盘/内盘手数)。所以「指数笔数」唯一可行
的口径是**把成分股的逐笔笔数累加**。
```python
async with TdxData() as td:
st = await td.get_index_trade_stats("000300") # 沪深300,约 10 s
for hhmm, cum in st.cum_trade_count(): # 截止该分钟的累计笔数
print(hhmm, cum)
st.minutes[0] # MinuteTradeStat(time='09:25', volume=…, trade_count=…)
st.total_volume # 手
st.total_trade_count # 笔
```
| 方法 | 作用 |
|---|---|
| `get_index_members(index, *, fields=None, count=100000)` | 指数成分股(含实时报价)。裸 6 位按**指数语义**解析:`000001`=上证指数,不是平安银行 |
| `get_index_trade_stats(index, date=None, *, concurrency=24, batch_size=50, members=None, skip_errors=True, on_progress=None)` | 成分逐笔 → 每分钟成交量/笔数;`date` 支持历史 |
| `get_index_trade_stats_multi(index, dates, *, ...)` | 多日批量(成分只请求一次),用于「近 N 日同时点均值」基准 |
**口径校验(2026-10-22 实测)**:``total_amount`` 是**成分股**合计。对「成分 = 指数
覆盖面」的指数,它与指数快照 ``amount`` 完全相等 —— 说明成分清单与量能口径一致。
| 指数 | 成分 | 成分合计 | 指数快照 | 比值 | 耗时 |
|---|---|---|---|---|---|
| `sh000016` 上证50 | 50 | 661.38 亿 | 661.34 亿 | 1.0001 | 5.8 s |
| `sh000300` 沪深300 | 300 | 2373.98 亿 | 2373.98 亿 | 1.0000 | 9.7 s |
| `sh000001` 上证指数 | 2230 | 3907.00 亿 | 4111.56 亿 | 0.9503 | 35.6 s |
历史日期同样成立(2026-10-21 收盘数据):`sh000016` 1046.29 / 1045.59 亿(1.0007)、
`sh000300` 3881.65 / 3879.30 亿(1.0006)。
单只股票级别的口径更硬:`Σ(逐笔价 × 手 × 100)` 与日线 `amount` 比值
**1.0000~1.0004**(`sh600000` / `sz000001` / `sh601398` / `bj920002` / `bj920015`
全部吻合),`Σvol` 与快照 `vol` 比值 1.0000。
CLI 同步新增:`tdx index-stats 000300 --top 10`。
**三个必须知道的限制**:
1. **深市 `399xxx` 的指数成交额是「全板块」口径**,不是样本股 —— 实测
`sz399001` 快照 5081.40 亿 = 深市 2908 只股票合计 5081.01 亿,`sz399006`
2568.60 亿 = 创业板全部股票合计。所以拿它跟 `total_amount` 比会得到 0.43 这种
无意义比值,不是数据错。**`get_index_trade_stats` 返回的始终是成分口径。**
2. **北交所(`899xxx`)没有笔数字段** —— 逐笔 `trade_count` 恒为 0,此时
`trade_count_available` 为 `False`,只有成交量可用。
3. **成分表比全市场滞后** —— 上证指数返回 2230 只,而 `get_universe("sh")` 里
股票段共 2360 只,差 130 只(新上市尚未纳入服务端板块),这正是上表
0.9503 的来源;`sh000016`/`sh000300` 这类固定样本指数不受影响。
需要精确覆盖时可自行传 `members=[...]`。
### 修复
- **债券与回购价格全线偏差:沪市少 100 倍、深市少 10 倍**(`get_quotes`)。
`price_decimal_digits` 只覆盖了「股票 2 位 / 基金 3 位」两档,债券与回购没有对应
分支,落到默认档位。它们实际是 **4 位小数**,于是被读大了两个数量级:
| 标的 | 真实价 | 修复前 | 偏差 |
|---|---|---|---|
| `sh019742` 国债 24特国01 | 110.2280 | 11022.8000 | ×100 |
| `sh110077` 可转债 洪城转债 | 199.2790 | 19927.9000 | ×100 |
| `sh204001` 回购 GC001 | 1.3850 | 138.5000 | ×100 |
| `sh900901` B股 云赛B股 | 0.5670 | 5.6700 | ×10 |
| `sz123107` 可转债 温氏转债 | 112.1890 | 1121.8900 | ×10 |
| `sz131810` 回购 R-001 | 1.3800 | 13.8000 | ×10 |
沪市 `010/018/019/020/1xx/2xx` 与深市 `10x-14x/19x/50x/52x/56x` 全部改为 4 位;
沪市 B 股 `900xxx` 另改为 3 位(与深市 `200xxx` 的 2 位不同,两市不一致)。
股票 / ETF / 指数 / 板块的行为**不变**。
**验证方式(可作为该函数的验收标准)**:拿 `pre_close`(五档快照口径,走
`price_decimal_digits`)除以上一交易日**日线收盘**(K线口径,走独立的 `/1000`
路径),比值 1.0 即两口径一致。修复后 15 类标的全数为 1.0000,零偏差。
**权威来源已确认**:证券列表里协议**自带** `SecurityInfo.decimal_point` 字段。
2026-10-22 拉取全量 **51,982 只**(沪 27,520 + 深 24,462)逐条比对,本函数与
协议字段**完全一致、零例外**——因为全量清单里没有任何一个「三位前缀」出现混合
小数位。`get_quotes` 解析时拿不到证券清单,故仍用前缀推断;需要权威值时读
`SecurityInfo.decimal_point`。
- **美股(EX 通道)分时的 `hour` 是非法时钟值**(`get_minutes("usAAPL")`)。
EX 分时的 `minutes` 字段是**自开盘起的连续分钟数**,不是「当天的分钟数」。
旧代码直接 `minutes // 60`,于是 390 条里 **240 条** 的 `hour` ≥ 24:
```
修复前: 21:30, 21:31, ..., 23:59, 24:00, 24:01, ..., 27:59 ← hour=27 不存在
修复后: 21:30, 21:31, ..., 23:59, 00:00, 00:01, ..., 03:59 ← 真实北京时间
```
任何 `datetime(...)` 拼接都会因 `hour=27` 抛 `ValueError`,按小时聚合也会把
凌晨段错误地归到同一个自然日。
**修法**:`MinuteBar.__post_init__` 把越界的 `hour` 拆成
「`hour %= 24` + `day_offset += hour // 24`」,并新增两个只读属性:
| 属性 | 用途 |
|---|---|
| `MinuteBar.datetime` | 该分时点的时刻(北京时间,已含跨日偏移) |
| `MinuteBar.trading_date` | 归属的交易日 `YYYY-MM-DD`。美股一个交易日横跨两个北京自然日(21:30~次日 04:00),**按交易日聚合必须用它**,与 `SecurityBar.trading_date` 口径一致 |
A股(合成时间 09:30~15:00)/ 港股(09:30~16:00)/ 期货的 `hour` 本就合法
→ **零行为变化**,`day_offset` 恒为 0。
实测(2026-10-22):`usAAPL` / `usTSLA` / `usNVDA` 各 390 条,修复后
`hour` 全在 0~23、时间轴严格单调、`trading_date` 收敛为单一交易日;
`hk00700` 90 条无任何变化。
### 说明
- 新增回归测试:债券/回购/B股小数位 ×29、美股分时跨日 ×6、指数成分成交汇总 ×34、
全接口 ×1,测试总数 **217 → 289**。
## [0.6.4] - 2026-10-22
### 修复
- **`get_ticks()` 返回列表不是时间序,每 `page_size` 处时间回跳一次**。
`0x122F`(A股逐笔)与 EX 逐笔通道的偏移量 `start` 都是**从最新一笔往回数**的:
实测 `sh600000`,`start=0` 返回 `14:07:48..15:20:16`(当天最新 1000 条),
`start=4000` 返回 `09:15:03..09:41:18`(当天最早)。而 `paginator` 按 `start`
升序拼接,于是拼出"新的块在前、旧的块在后"的倒序结构:
| | 修复前 | 修复后 |
|---|---|---|
| `sh600000` 时间轴 | 4 处逆序跳跃(index 999 / 1999 / 2999) | 严格升序 |
| `hk00700` 时间轴 | 21 处逆序跳跃(每 1800 条一次) | 严格升序 |
修复分两层:① `PageSpec.newest_first=True` 让 `paginator` 反页序拼装(页内本身升序,
只翻页序),这条能力保留给将来需要按"最新优先"锚点分页的命令;② A股逐笔最终改为
**单连接串行游标**(见下一条),从根上避开多主机锚点错位。
**`start` 参数语义同时明确**:它是"从最新往回数的偏移",不是"从最早往后数的偏移",
`docstring` 已补充。注意这修正的是**顺序**,数据本身无缺口、无重复(4304 条唯一时间戳)。
- **`TransactionRecord.trade_count` 在集合竞价段被读成 42 亿量级脏值**。
该字段在协议里是**有符号** `int32`,但解析格式串写的是无符号 `I`。集合竞价段
(`bs_flag=8`)真实值为负数,按 uint32 解出 `4294966422`:
```
原始 18 字节: 17820000 0ad71b41 d9000000 96fcffff 0800
修复前: trade_count = 4294966422
修复后: trade_count = -874 ← 0xfffffc96 的 int32 补码
```
实测 `sh600000` 全天 4304 条中有 **38 条**命中(占 0.88%),全部落在 09:15~09:25
集合竞价段;正常交易段(`bs_flag` 0/1/2/5)**无一条为负**。旧行为会让
`max()` / `mean()` 等统计直接失真(曾算出 `mean=37,920,247`)。
格式串由 `<IfIIH` 改为 `<IfIiH`。**注意负值语义尚未确证**(可能是撤单量/净委托),
目前只是如实保留符号,未做业务解释。
- **`get_quotes()` 沪市指数价格整体少 10 倍**。
`price_decimal_digits` 把沪市 `000`(如 000001/000016/000300/000688)与 `8`
开头(如板块指数 880001/880305)一律判成 3 位小数(除 1000),但协议原始整数
实际是 **2 位**(除 100)→ 上证指数 3713 被读成 371、上证50 2747 被读成 274。
实证(2026-10-21):沪市指数 6 只 + 板块 2 只全部 `分时中位价 / 快照价 = 10.0`,
而沪市 ETF(510300/588000/511010/501018)、股票(60/601)、科创板(688)、
深市指数/股票/创业板/ETF 全部 `= 1.0` 正确。修法是**把沪市 `000`/`8` 从 3 位改回 2 位**,
其余前缀(`5` ETF/基金、深市 `1` 基金转债)保持 3 位不变。回归测试覆盖 21 组代码。
- **`get_ticks()` 把集合竞价**委托**(`bs_flag=8`)当成成交计入,导致 Σvol 虚高且跨主机不稳定**。
`0x122F` 第 5 字段 `bs_flag=8` 的记录是 **09:15~09:25 / 14:57~15:00 竞价段的撮合委托
快照**,`vol` 是**累计值**(可被同段后续记录覆盖),根本不是成交增量。旧代码把它一并
返回,两个后果:
1. **Σvol 比真值虚高**:`sh600000` 全天 Σvol 含 b8 时 = 668,693,快照 vol = 462,562,
比值 1.4456;剔掉 b8 后 Σvol = 462,634,比值 **1.000156**(与快照精确一致)。
2. **跨主机不稳定**:干净主机不收录 b8(0 条)、脏主机收录 135 条。并发分页时各页
来自不同主机,同一 `start`(从最新往回数的相对锚点)在不同主机落到**不同的真实成交**
上 → 页边界既**重叠**(sh600000 冗余 116 条)又**漏条**(13:03 附近丢 59 条),
同一查询两次调用结果不同。
修复:① 分页拼装后**统一剔除 `bs_flag=8`**;② A股逐笔改用**单连接串行游标翻页**
(`_ticks_cn_serial`),彻底消除跨主机锚点错位。修复后单主机 1.0002、剔 b8 后跨主机
公共时间窗**逐条一致**。
- **文档化指数逐笔字段的量纲差异**(非 bug,是数据源固有语义)。
指数(如 `sh000016`)的 `vol` 单位是**百元**(成交额/100),`trade_count` 是**均价×1000**
(不是笔数),与个股完全不同。实测 `快照amount / Σtick.vol = 100.0002`、`tc/1000` 与分时
`avg_price` 差 < 1.1。已写进 `TransactionRecord` 类注释与 `get_ticks` docstring,
避免用户把指数 Σvol 直接和成分股成交量比(会误得 ~26 倍)。
### 说明
- 新增回归测试:价格小数位 ×20(19 组参数化 + 1 组去 NUL)、`get_ticks` 剔 b8 /
单连接串行 / 多页无重叠 ×3,测试总数 **194 → 217**。
## [0.6.3] - 2026-10-18
- fix(pool): ExPool acquire 背压等待(Condition 排队,默认 30s 超时)替代 3x0.05s 快速失败;超时异常带池状态
- feat(api): 新增 ex_pool_cap 参数(默认 2),单 EX 服务器场景不再静默退化为 1 并发(fixes #1)
+6 -1
View File
@@ -149,6 +149,8 @@ await td.get_bars("cffex:IFL0", KlinePeriod.DAY, count=700) # 期货合约
| 除权除息 / 财务快照 | `get_xdxr(symbols)` / `get_finance(symbols)` |
| F10 公司资料 | `get_f10(symbol, section)` |
| 板块列表 / 成分股 / 涨跌排行 | `get_boards` / `get_board_members` / `get_board_ranking` |
| **指数的成交量 + 成交笔数**(每分钟曲线) | `get_index_trade_stats(index, date)` → `.cum_trade_count()` |
| **指数成分股** | `get_index_members(index)`(裸 `000001` 按指数语义解析) |
| 个股所属板块 | `get_board_of(symbols)` |
| 集合竞价 / 异动 / 资金流 | `get_auction` / `get_unusual` / `get_capital_flow` |
| 个股特征快照 | `get_snapshot(symbols)` |
@@ -167,7 +169,8 @@ await td.get_bars("cffex:IFL0", KlinePeriod.DAY, count=700) # 期货合约
- **K 线时间戳统一为北京时间**(v0.6.2 起)。美股原始报文里日期是美东交易日、时分是北京时间(两个时区拼在一起),库已自动归一化,`bar.datetime` 可直接排序 / 比较 / 过滤。但**美股一个交易日横跨两个北京自然日**,按交易日聚合(分钟线合成日线、日内统计)必须用 `bar.trading_date`。
- **`count` 很大时会自动多连接并发分页**,无需手动翻页。但标准通道 K 线 `count < 100` 部分服务器会返回空——内部已强制 `min_page=100` 规避。
- **`get_quotes` 一次 >80 只自动切批**;走 MAC 字段位通道(`fields=`)时上限为 80 只/次。
- **历史逐笔没有笔数字段**,只有当日逐笔的 `trade_count` 有效。
- **指数本身没有成交笔数**。`get_ticks("sh000001")` 的 `trade_count` 是「当时均价×1000」、`vol` 单位是百元(成交额/100)。要笔数只能用 `get_index_trade_stats(index)`(成分股逐笔累加,2230 只约 36-60 s)。北交所成分无笔数字段,该方法会返回 `trade_count_available=False`。
- **历史逐笔有笔数**(MAC `0x122F` 支持历史日期,实测可回溯最近 5 个交易日;更早返回空)。
- 板块文件(`block_*.dat`)/ 行业(`tdxhy.cfg`)/ 财报(`gpcw*.zip`)是**服务器上的静态文件**,解析后是普通 dataclass,**落 JSON 后完全脱网可用**——适合做离线快照。
## 陷阱清单
@@ -185,6 +188,8 @@ await td.get_bars("cffex:IFL0", KlinePeriod.DAY, count=700) # 期货合约
| 循环里逐个 `await get_bars` | 慢 | 用列表传多个标的,自动并发 |
| 港股/美股五档 bid/ask | 没有(协议不支持) | `fields` 字段位通道有 name 但无五档 |
| 美股分钟线用 `datetime.date()` 分组做日聚合 | 一个交易日被拆成两天(美股跨北京零点) | 用 `bar.trading_date`;`bar.datetime` 是归一化后的北京时间 |
| 拿指数逐笔的 `trade_count` 当笔数 | 拿到的是「均价×1000」,数值荒谬 | 用 `get_index_trade_stats(index)` 由成分累加 |
| 拿深市 `399xxx` 的 `amount` 校验成分合计 | 比值 0.43,误以为数据错 | 深市指数 amount 是**全板块**口径(`sz399001`=深市全部 5081 亿),不是样本股 |
| 依赖实时性做信号 | 数据是 15 分钟前的 | 换券商实时源 |
| 手动改包内 `servers.json` / 写死 IP | 容器只读、升级被覆盖、快节点捞不回来 | 日常靠内置的**当日测速缓存**自动选路;要强制指定就用 `PYPYTDX_DATA_{STANDARD,MAC,EX}_HOSTS` 环境变量 |
+8 -18
View File
@@ -47,7 +47,9 @@ from pytdxdata import (
| 方法 | 返回 | 说明 |
|------|------|------|
| `get_universe(market=None)` | `list[SecurityInfo]` | 跨市场标的清单(A 股+港股+美股+期货/期权) |
| `get_universe(market=None)` | `list[SecurityInfo]` | 跨市场标的清单(A 股+港股+美股+期货/期权);每条带协议自带的 `decimal_point`(价格小数位)与 `pre_close` |
| `sync_decimal_points(markets=("sh","sz"))` | `dict` | 从证券清单同步**权威价格小数位表**(`SecurityInfo.decimal_point`),灌进 `price_decimal_digits` 的运行时表;`start()` 已自动做(当日缓存命中则零网络),此方法用于强制刷新/排障 |
| `decimal_point_status()` | `dict` | 小数位表状态:`source`(`cache`/`universe`/空)、`stock`、`mixed_prefixes`、`syncing` |
#### 报价
@@ -69,7 +71,7 @@ from pytdxdata import (
| 方法 | 返回 | 说明 |
|------|------|------|
| `get_ticks(symbols, *, date=None, start=0, count=None, concurrency=6)` | `list[TransactionRecord]` | 跨市场逐笔成交 |
| `get_ticks(symbols, *, date=None, start=0, count=None, concurrency=6)` | `list[TransactionRecord]` | 跨市场逐笔成交。返回按时间升序;`start` **从最新一笔往回数**;`vol`/`trade_count` 为约 3 秒切片的增量值(非累计)。**已剔除 `bs_flag=8` 竞价委托**(非成交,`vol` 为累计撮合量)。**指数**:`vol` 单位是百元(成交额/100)、`trade_count` 是均价×1000,均非股票语义 |
| `get_minutes(symbols, *, date=None, sampling=False, concurrency=6)` | `list[MinuteBar]` | 跨市场分时(sampling=True 取缩略采样:A股由 0x122D 派生,扩展市场 0x254D) |
#### 公司信息/文件/板块
@@ -81,21 +83,9 @@ from pytdxdata import (
| `get_boards(kind="all", *, count=10000)` | `list[BoardInfo]` | 板块列表 |
| `get_board_members(board, *, fields=None, count=100000)` | `list[SecurityQuote]` | 板块成分股报价(归一模型) |
| `get_board_of(symbols)` | `list[BelongBoard]` | 个股所属板块 |
#### 指数成分与统计(v0.6.7)
| 方法 | 返回 | 说明 |
|------|------|------|
| `get_index_members(index, *, count=100000, fields=None)` | `list[SecurityQuote]` | 指数成分股含实时报价(MAC 0x122C,指数码→板块码映射) |
| `get_index_trade_stats(index, *, date=None, members=None, batch_size=50, concurrency=24, skip_errors=True)` | `IndexTradeStats` | 指数逐笔聚合统计(分钟级增量 vol/trade_count/amount;北交所成分无笔数自动剔除) |
| `get_index_trade_stats_multi(index, dates, *, concurrency=24, batch_size=50, skip_errors=True, on_progress=None)` | `dict[int, IndexTradeStats]` | 多日批量版(按日期键) |
#### 价格小数位(v0.6.7)
| 方法 | 返回 | 说明 |
|------|------|------|
| `sync_decimal_points(markets=("sh","sz"))` | `dict[str, int]` | 从证券清单同步权威价格小数位表(`start()` 已自动处理,此为手动刷新口) |
| `decimal_point_status()` | `dict` | 小数位表当前状态(source/stock/syncing,排障用) |
| `get_index_members(index, *, fields=None, count=100000)` | `list[SecurityQuote]` | **指数成分股**报价。裸 6 位按**指数语义**解析(`000001`=上证指数,不是平安银行):`000/999/880`→沪、`399`→深、`899`→北交所 |
| `get_index_trade_stats(index, date=None, *, concurrency=24, batch_size=50, members=None, skip_errors=True, on_progress=None)` | `IndexTradeStats` | **指数成分逐笔汇总**成每分钟成交量/成交笔数。协议里指数本身没有笔数(`trade_count` 是均价×1000),故由成分股逐笔累加;`.cumulative()` 取「截止该分钟累计」,`.cum_trade_count()` 直接给 `[(HH:MM, 累计笔数)]`。2230 只(上证)约 36-60 s |
| `get_index_trade_stats_multi(index, dates, *, ...)` | `list[IndexTradeStats]` | 多日批量版(成分只请求一次),用于「近 N 日同时点累计均值」基准 |
### 2.2 K线(旧接口,共 6 个) {#legacy-kline}
@@ -214,7 +204,7 @@ from pytdxdata import (
| `SecurityQuote` | price/pre_close/OHLC/vol/amount/s_vol/b_vol/`bid[5]`/`ask[5]`/server_time/trading_status/cur_vol/rise_speed/limit_up/limit_down/decimal_point/open_amount |
| `SecurityInfo` | market/code/name/volunit/decimal_point/pre_close |
| `TransactionRecord` | market/code/time/price/vol/`trade_count`/bs_flag |
| `MinuteBar` | price/vol/avg_price/hour/minute |
| `MinuteBar` | price/vol/avg_price/hour/minute/day_offset + `datetime`/`trading_date` 只读属性(hour 恒为合法时钟值 0~23;美股一个交易日跨两个北京自然日,按交易日聚合用 `trading_date`) |
| `XdxrRecord` | 分红送转/配股/缩股/行权 + 股本变动 + `date` 属性 |
| `FinanceRecord` | 股本/资产/负债/营收/利润等 36 个字段(万元/万股) |
| `BoardInfo` | 板块 + 领涨股信息 |
+5 -1
View File
@@ -48,7 +48,11 @@ asyncio.run(main())
- **K 线**:`get_bars`(自动并发分页、支持复权与日期区间、多标的并发)
- **技术指标**:`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` 取缩略采样)
- 价格标度:协议给的是整数,真实价 = `整数 / 10**小数位`。小数位由 `price_decimal_digits` 决定,
优先用**权威表**(证券清单自带的 `SecurityInfo.decimal_point`,`start()` 每日后台同步一次,
也可 `await td.sync_decimal_points()` 强制刷新),未同步时退回静态前缀规则。
债券/回购是 **4 位**、沪市 B 股 3 位 —— 这里错过两次(整批价格差 100 倍/10 倍)。
- **逐笔 / 分时**:`get_ticks`(含 `trade_count`,支持历史日期,返回按时间升序;`vol`/`trade_count` 为约 3 秒切片增量而非累计;已剔除 `bs_flag=8` 竞价委托;**指数**的 `vol` 是百元、`trade_count` 是均价×1000)、`get_minutes`(`sampling=True` 取缩略采样;`hour` 恒为合法时钟值 0~23,美股一个交易日跨两个北京自然日,按交易日聚合用 `MinuteBar.trading_date`、取时刻用 `MinuteBar.datetime`)
- **财务 / 除权**:`get_finance`(最新快照)、`get_xdxr`、`get_price_limits`(本地计算涨跌停)
- **F10**:`get_f10`(公司资料目录 + 正文)
- **板块**:`get_boards`、`get_board_members`、`get_board_of`、`get_board_summary`、
+6 -23
View File
@@ -1,24 +1,14 @@
[project]
name = "pytdxdata"
version = "0.6.7"
version = "0.6.6"
description = "通达信(TongDaXin)行情数据客户端:动态连接池 + 双层TTL缓存 + 3连接并发分页,纯asyncio零运行时依赖,支持A股/港股/美股/期货/期权"
readme = "README.md"
requires-python = ">=3.11"
license = "MIT"
license-files = ["LICENSE"]
keywords = [
"tdx",
"trading",
"stock",
"kline",
"quote",
"通达信",
"A股",
"港股",
"美股",
"期货",
"asyncio",
"quant",
keywords = ["tdx", "trading", "stock", "kline", "quote", "通达信", "A股", "港股", "美股", "期货", "asyncio", "quant"]
authors = [
{ name = "openbot-coder", email = "openbot-coder@users.noreply.github.com" }
]
classifiers = [
"Development Status :: 4 - Beta",
@@ -34,10 +24,6 @@ classifiers = [
]
dependencies = []
[[project.authors]]
name = "openbot-coder"
email = "openbot-coder@users.noreply.github.com"
[project.urls]
Homepage = "https://github.com/openbot-coder/pytdxdata"
Repository = "https://github.com/openbot-coder/pytdxdata"
@@ -45,11 +31,7 @@ Documentation = "https://openbot-coder.github.io/pytdxdata/"
[project.optional-dependencies]
uvloop = ["uvloop>=0.21"]
dev = [
"pytest>=8.0",
"pytest-asyncio>=0.24",
"ruff>=0.6",
]
dev = ["pytest>=8.0", "pytest-asyncio>=0.24", "ruff>=0.6"]
[project.scripts]
tdx = "pytdxdata.cli:main"
@@ -77,3 +59,4 @@ docs = [
"ruff>=0.6",
"jieba>=0.42",
]
+108
View File
@@ -0,0 +1,108 @@
"""可复现核查:指数成分逐笔汇总的口径是否与官方日线一致。
用法::
python scripts/verify_index_stats.py # 当日
python scripts/verify_index_stats.py --date 20261021 # 历史某日
python scripts/verify_index_stats.py --indices 000001 000300
两段校验:
1. **单股级**:``Σ(逐笔价 × 手 × 100)`` 对**当日日线 amount**。比值 1.0000~1.0002
说明逐笔没漏条、价格与单位都对(``bj`` 也行)。
2. **指数级**:成分股合计成交额对**该指数的日线 amount**。相等说明成分清单与
指数的量能口径一致;明显偏小则是成分表滞后(新上市未纳入)。
⚠️ **深市 `399xxx` 的指数 amount 是「全板块」口径**,不是样本股:实测
`sz399001` 5081.40 亿 = 深市 2908 只股票合计,`sz399006` 2568.60 亿 = 创业板
全部股票合计。所以这两个指数的比值天然远离 1(约 0.43),**不是数据错**。
为什么不用快照做基准:快照只有「此刻」,历史日期对不上。日线 amount 两者都能给。
注意 ``bj``(北交所)逐笔**没有笔数字段**(``trade_count`` 恒 0),脚本会打出
``有笔数`` 列便于识别。
"""
from __future__ import annotations
import argparse
import asyncio
from datetime import date as _date
def _ymd(bar) -> int:
return bar.year * 10000 + bar.month * 100 + bar.day
async def _daily_amount(td, symbol: str, ymd: int) -> float | None:
from pytdxdata import KlinePeriod
bars = await td.get_bars(symbol, KlinePeriod.DAY, count=10)
for b in bars:
if _ymd(b) == ymd:
return b.amount
return None
async def check_symbols(td, symbols: list[str], ymd: int) -> None:
print(f"## 单股级({ymd})\n")
print("| 标的 | Σ(p×手×100) / 日线amount | 笔数 |")
print("|---|---|---|")
for sym in symbols:
try:
ticks = await td.get_ticks(sym, date=ymd)
ref = await _daily_amount(td, sym, ymd)
except Exception as exc: # noqa: BLE001
print(f"| {sym} | ERR {type(exc).__name__} | - |")
continue
if not ticks:
print(f"| {sym} | 无逐笔(非交易日?) | - |")
continue
sa = sum(t.price * t.vol * 100 for t in ticks)
tc = sum(t.trade_count for t in ticks)
ratio = sa / ref if ref else 0.0
print(f"| {sym} | {ratio:.4f} | {tc:,} |")
print()
async def check_indices(td, indices: list[str], ymd: int, day: int | None) -> None:
print(f"## 指数级({ymd})\n")
print("| 指数 | 成分 | 有成交 | 有笔数 | 成分合计 | 日线amount | 比值 | 耗时 |")
print("|---|---|---|---|---|---|---|---|")
for idx in indices:
try:
st = await td.get_index_trade_stats(idx, day)
ref = await _daily_amount(td, st.index, ymd)
except Exception as exc: # noqa: BLE001
print(f"| {idx} | ERR {type(exc).__name__}: {exc} | - | - | - | - | - | - |")
continue
ratio = st.total_amount / ref if ref else 0.0
print(f"| {st.index} | {st.member_count} | {st.active_members} | "
f"{st.trade_count_members} | {st.total_amount / 1e8:,.2f} 亿 | "
f"{(ref or 0) / 1e8:,.2f} 亿 | {ratio:.4f} | {st.elapsed:.1f}s |")
print()
print("提示:`399xxx` 的比值天然远离 1 —— 深市指数的 amount 字段是全板块口径。")
print()
async def main() -> None:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--symbols", nargs="*",
default=["sh600000", "sz000001", "sh601398"])
ap.add_argument("--indices", nargs="*", default=["000016", "000300"])
ap.add_argument("--date", default=None, help="YYYYMMDD(缺省=当日)")
ap.add_argument("--skip-symbols", action="store_true")
args = ap.parse_args()
from pytdxdata import TdxData
ymd = int(args.date) if args.date else int(_date.today().strftime("%Y%m%d"))
day = int(args.date) if args.date else None
async with TdxData(cache_dir=None, timeout=10.0) as td:
if not args.skip_symbols:
await check_symbols(td, args.symbols, ymd)
if args.indices:
await check_indices(td, args.indices, ymd, day)
if __name__ == "__main__":
asyncio.run(main())
+1 -1
View File
@@ -18,7 +18,7 @@ from .models import (
XdxrRecord,
)
__version__ = "0.6.7"
__version__ = "0.6.6"
__all__ = [
"TdxData",
"Market",
+23 -152
View File
@@ -25,7 +25,6 @@ import logging
import re
import time
import warnings
from collections import deque
from collections.abc import Callable
from datetime import date as _date, datetime
from pathlib import Path
@@ -148,7 +147,6 @@ _KLINE_MAX_BARS: dict[KlinePeriod, int] = {
# 自定义字段报价(0x122B/0x122C)基础字段位:昨收/开/高/低/现价/量/量比/额
_QUOTE_BITS = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]
_QUOTE_PAGE = 80 # 0x122B/0x122C 单次上限 80 只
_QUOTE_PIPE_CHUNK = 3 # 单连接流水线一次取几片(实测 3 片 + 每台 2 连接最稳)
_EX_PAGE = 1000 # EX 商品列表单页
_TICK_PAGE = 1000 # MAC 逐笔单页
_EX_TICK_PAGE = 1800 # 港股逐笔单页
@@ -239,7 +237,7 @@ class TdxData:
default_adjust: Adjust = Adjust.NONE,
max_inflight: int = 64,
pool_min: int = 3,
pool_max: int = 24,
pool_max: int = 12,
mac_pool_cap: int = 4,
std_pool_cap: int = 4,
ex_pool_cap: int = 2,
@@ -444,9 +442,7 @@ class TdxData:
# ================================================================== #
async def get_quotes(self, symbols: str | Sequence[str], *,
fields: Sequence[int] | None = None,
concurrency: int | None = None,
pipeline: bool = True
fields: Sequence[int] | None = None
) -> list[SecurityQuote]:
"""报价,一次可跨市场、跨通道混合查询。
@@ -456,11 +452,6 @@ class TdxData:
fields: 可选自定义字段位(如 ``[0x00, 0x04, 0x38]``)。给了就走 MAC/EX 的
0x122B 字段位通道(有 ``name``,无五档);不给时 A股走标准通道
(**有五档 bid/ask、买卖量、涨跌停价,无 name**),扩展市场走 0x122B。
concurrency: 连接并发数(默认取连接池上限)。协议硬上限 80 只/请求,
全市场约 5,200 只 A股需切 66 片;调小可降低对服务器的压力。
pipeline: 是否启用**单连接流水线**(默认开启)。开启后一条连接可一次发出
多个分片、只付一次往返,全市场 5,200 只 A股由 ~4s 降到 **~0.3s**;
个股或小批量不受影响。个别服务器不支持流水线时会自动降级为逐片。
返回:
``list[SecurityQuote]``,按入参顺序排列(各记录带 ``symbol``)。
@@ -471,155 +462,50 @@ class TdxData:
bits = [int(b) for b in fields] if fields else None
tag = "mac:" + _fields_tag(bits) if bits else "std"
key = CacheKey.quote_key([s.as_pair() for s in syms], tag=tag)
quotes = await self._cache.get_or_fetch_obj(
key,
lambda: self._fetch_quotes(syms, bits, concurrency, pipeline),
pack=pack_payload, unpack=unpack_payload)
payload = await self._cache.get_or_fetch(
key, lambda: self._fetch_quotes(syms, bits))
quotes = unpack_payload(payload)
order = {s.as_pair(): i for i, s in enumerate(syms)}
quotes.sort(key=lambda q: order.get((int(q.market), q.code), len(order)))
return quotes
async def _fetch_quotes(self, syms: list[Symbol], bits: list[int] | None,
concurrency: int | None = None,
pipeline: bool = True) -> list[SecurityQuote]:
async def _fetch_quotes(self, syms: list[Symbol], bits: list[int] | None) -> bytes:
out: list[SecurityQuote] = []
cn = [s for s in syms if not s.is_ex]
ex = [s for s in syms if s.is_ex]
if bits is None:
if cn:
out.extend(await self._quotes_std(
cn, concurrency=concurrency, pipeline=pipeline))
out.extend(await self._quotes_std(cn))
if ex:
rows = await self._execute_ex(
MacSymbolQuotesCmd([s.as_pair() for s in ex], None))
out.extend(_quote_from_member(m) for m in rows)
else:
batches = [syms[i:i + _QUOTE_PAGE]
for i in range(0, len(syms), _QUOTE_PAGE)]
sem = asyncio.Semaphore(self._quote_concurrency(concurrency))
async def one(batch: list[Symbol]) -> list[SecurityQuote]:
async with sem:
for i in range(0, len(syms), _QUOTE_PAGE):
batch = syms[i:i + _QUOTE_PAGE]
pairs = [s.as_pair() for s in batch]
cn_pairs = [p for p, s in zip(pairs, batch) if not s.is_ex]
ex_pairs = [p for p, s in zip(pairs, batch) if s.is_ex]
got: list[SecurityQuote] = []
if cn_pairs:
rows = await self._execute_mac(
MacSymbolQuotesCmd(cn_pairs, bits))
got.extend(_quote_from_member(m) for m in rows)
rows = await self._execute_mac(MacSymbolQuotesCmd(cn_pairs, bits))
out.extend(_quote_from_member(m) for m in rows)
if ex_pairs:
rows = await self._execute_ex(
MacSymbolQuotesCmd(ex_pairs, bits))
got.extend(_quote_from_member(m) for m in rows)
return got
rows = await self._execute_ex(MacSymbolQuotesCmd(ex_pairs, bits))
out.extend(_quote_from_member(m) for m in rows)
return pack_payload(out)
if batches:
for got in await asyncio.gather(*(one(b) for b in batches)):
out.extend(got)
return out
def _quote_concurrency(self, requested: int | None) -> int:
"""连接并发数:显式指定优先,否则按「每台服务器 2 连接」估算。
实测(5,227 只 A股 / 66 片,11 台服务器):
========== ===== ====== ====== ======
并发 每台连接 流水深度 p50 max
========== ===== ====== ====== ======
11 1 6 455ms 464ms
12 1~2 3 457ms 523ms
**22** **2** **3** **325ms** **334ms**
33 3 2 328ms 345ms
========== ===== ====== ====== ======
结论:每台 2 连接 × 流水 3 片最稳;再多连接只是把同一台的队列搬个位置,
对整体无益反增抖动。池 ``per_server_cap`` 默认 4,2 连接仍留有余量。
"""
if requested is not None and requested > 0:
return max(1, int(requested))
n = len(self._std_pool.servers)
return max(1, min(self._std_pool.max_size, (n or 1) * 2))
async def _quotes_std(self, syms: list[Symbol], *,
concurrency: int | None = None,
pipeline: bool = True) -> list[SecurityQuote]:
"""A股标准通道五档报价(协议上限 80 只/请求,超出自动切批)。
切片多于 1 片时把各片**按轮转分给若干条连接**,每条连接内部用流水线
一次发出(1 次往返拿多片),不再逐片往返。
"""
if not syms:
return []
def stamp(rows: list[SecurityQuote]) -> list[SecurityQuote]:
async def _quotes_std(self, syms: list[Symbol]) -> list[SecurityQuote]:
"""A股标准通道五档报价(>80 只自动切批)。"""
out: list[SecurityQuote] = []
for i in range(0, len(syms), MAX_QUOTES):
batch = syms[i:i + MAX_QUOTES]
cmd = GetSecurityQuotesCmd([s.as_pair() for s in batch])
rows = await self._execute_standard(cmd)
for q in rows:
q.symbol = format_symbol(q.market, q.code)
return rows
batches = [syms[i:i + MAX_QUOTES]
for i in range(0, len(syms), MAX_QUOTES)]
if len(batches) == 1:
cmd = GetSecurityQuotesCmd([s.as_pair() for s in batches[0]])
return stamp(await self._execute_standard(cmd))
conc = min(self._quote_concurrency(concurrency), len(batches))
# 首次大批量:先把连接并发建好,否则 acquire 会在池锁里串行握手
# (22 路并发首次调用实测多花 5~6s)
await self._std_pool.warm(conc)
if not pipeline:
sem = asyncio.Semaphore(conc)
async def one(batch: list[Symbol]) -> list[SecurityQuote]:
async with sem:
cmd = GetSecurityQuotesCmd([s.as_pair() for s in batch])
return stamp(await self._execute_standard(cmd))
groups = await asyncio.gather(*(one(b) for b in batches))
return [q for g in groups for q in g]
# 工作窃取:连接做完一批就回来再取,快的多干、慢的少干。
# 平均分配(每台固定几片)会被最慢的一台拖住 —— 实测 11 台平均分
# 时 p50 在 400~580ms 之间抖,改窃取后波动收窄。
queue = deque(batches)
gate = asyncio.Lock()
async def worker() -> list[SecurityQuote]:
got: list[SecurityQuote] = []
while True:
async with gate:
if not queue:
return got
take = min(_QUOTE_PIPE_CHUNK, len(queue))
chunk = [queue.popleft() for _ in range(take)]
for rows in await self._execute_std_pipeline(chunk):
got.extend(stamp(rows))
out: list[SecurityQuote] = []
for part in await asyncio.gather(*(worker() for _ in range(conc))):
out.extend(part)
out.extend(rows)
return out
async def _execute_std_pipeline(
self, batches: list[list[Symbol]]
) -> list[list[SecurityQuote]]:
"""一条连接流水线执行多片报价;节点不支持流水线时降级为逐片。"""
cmds = [GetSecurityQuotesCmd([s.as_pair() for s in b]) for b in batches]
pc = await self._std_pool.acquire()
try:
rows = await pc.execute_pipeline(cmds)
except Exception:
# 流水线中断后响应流已错配,连接必须废弃;改用逐片(每条独立借还)
await self._std_pool.release(pc, broken=True)
fallback: list[list[SecurityQuote]] = []
for cmd in cmds:
fallback.append(await self._execute_standard(cmd))
return fallback
await self._std_pool.release(pc)
return rows
async def get_snapshot(self, symbols: str | Sequence[str]) -> list[SymbolSnapshot]:
"""个股特征快照(当日/换手/活跃度等,仅 A股)。"""
syms = parse_symbols(symbols)
@@ -974,10 +860,6 @@ class TdxData:
- ``vol`` 单位是**百元**(成交额/100),不是手。
- ``trade_count`` 是**当时均价 × 1000**,不是笔数。
**ETF / LOF 同样没有笔数**:``trade_count`` 是「价格 × 1000」(货币 ETF 恒为 0),
这类记录的 ``trade_count_available`` 为 ``False`` 且 ``trade_count`` 已置 0。
判定规则见 :func:`~pytdxdata.symbols.has_order_count`。
详见 :class:`~pytdxdata.models.TransactionRecord` 的类注释。
"""
syms = parse_symbols(symbols)
@@ -1124,7 +1006,6 @@ class TdxData:
trade_count=0,
bs_flag=int(row.get("direction", 0) or 0),
fields=fields,
trade_count_available=False, # 扩展市场逐笔不带笔数字段
)
async def get_minutes(
@@ -1511,14 +1392,6 @@ class TdxData:
注意:返回的是**当前**成分,指数调仓后历史日期不适用。
⚠️ **综合指数的成员名单不完整**(实测 2026-10-22):``sh000001`` 只返回
2230 只(2190 A + 40 B),而当日沪市 A 股实有 2318 只;缺的 128 只
(多为近期科创板/主板新股)当日成交 282 亿,正好对上「指数日线 amount −
成员日线 amount」的 297 亿(残差 4.9%)。因此
:meth:`get_index_trade_stats` 对**综合指数**会系统性低估约 4.6%;
样本指数 ``sh000016``(50 只)/ ``sh000300``(300 只)实测比值
**1.000000**,不受影响。要精确汇总综指成交,请自行用全市场股票列表。
用法::
members = await td.get_index_members("000300")
@@ -1635,12 +1508,10 @@ class TdxData:
for t in ticks:
hhmm = t.time[:5]
vol_by_min[hhmm] = vol_by_min.get(hhmm, 0.0) + t.vol
# 成分里若混入 ETF/LOF(协议无笔数),不能把占位值累加进笔数
if getattr(t, "trade_count_available", True):
tc_by_min[hhmm] = tc_by_min.get(hhmm, 0) + t.trade_count
amt_by_min[hhmm] = amt_by_min.get(hhmm, 0.0) + t.price * t.vol * 100.0
active.add(t.symbol)
if getattr(t, "trade_count_available", True) and t.trade_count:
if t.trade_count:
with_tc.add(t.symbol)
done += len(batch)
if on_progress is not None:
-32
View File
@@ -90,38 +90,6 @@ class CacheManager:
# 确保清理锁(即使 fetcher 异常也清理,避免无限增长)
self._locks.pop(ks, None)
async def get_or_fetch_obj(
self,
key: CacheKey,
fetcher: Callable[[], Awaitable[Any]],
*,
pack: Callable[[Any], bytes],
unpack: Callable[[bytes], Any],
) -> Any:
"""同 :meth:`get_or_fetch`,但**回源时直接返回新取到的对象**。
用于「一次取回上千条记录」的场景(如全市场报价):常规路径对冷数据
会先 ``pack`` 再立刻 ``unpack`` 一次,纯属往返浪费 —— 5,200 条报价实测
白烧约 90ms。这里命中缓存才解序列化,回源则把对象原样返回,只在写缓存时打包。
"""
ks = key.to_str()
cached = await self.get(key)
if cached is not None:
return unpack(cached)
lock = self._locks.setdefault(ks, asyncio.Lock())
try:
async with lock:
cached = await self.get(key)
if cached is not None:
return unpack(cached)
async with self._semaphore:
obj = await fetcher()
await self.set(key, pack(obj))
return obj
finally:
self._locks.pop(ks, None)
async def invalidate(self, category: str, *, market: int | None = None,
code: str | None = None) -> int:
"""按前缀批量失效,返回失效条数。"""
+13 -63
View File
@@ -38,7 +38,6 @@ from .api import TdxData
from dataclasses import asdict
from .models import Adjust, ExMarket, KlinePeriod, Market
from .protocol.commands.quotes import price_decimal_digits
PERIODS = {
"min1": KlinePeriod.MIN_1, "min5": KlinePeriod.MIN_5, "min15": KlinePeriod.MIN_15,
@@ -108,40 +107,6 @@ def _pct(price: float, pre: float) -> str:
return "%+.2f%%" % ((price / pre - 1) * 100)
def _price_fmt(dp: int) -> str:
"""按品种小数位生成右对齐格式串。
股票 2 位、**可转债/ETF 3 位**、债券/回购 4 位。固定写 ``%8.2f`` 会把
可转债的 128.891 打成 128.89(少一位有效报价)。
"""
dp = max(0, min(int(dp or 2), 4))
return "%%%d.%df" % (6 + dp, dp)
# 可转债后缀(解码 4 位,但交易所报价步长 0.001 元,第 4 位恒为 0)
_CB_PREFIX = {1: ("110", "111", "113", "118"), 0: ("123", "127", "128")}
def _display_dp(market: int, code: str) -> int:
"""报价**显示**小数位。
注意 ``price_decimal_digits`` 给的是**解码位数**(原始整数 / 10**dp),
可转债是 4 位;但真实报价是 0.001 元的步长,第 4 位恒为 0,
按 4 位打印只会多一个 ``0``(``128.8920``)。
"""
dp = price_decimal_digits(market, code)
if str(code).startswith(_CB_PREFIX.get(int(market), ())):
return 3
return dp
def _dp_of(sym) -> int:
"""Symbol -> 价格小数位(非 A 股/指数一律 2 位)。"""
if getattr(sym, "kind", "") == "cn":
return _display_dp(sym.market, sym.code)
return 2
# ------------------------------------------------------------------ #
# 各子命令
# ------------------------------------------------------------------ #
@@ -155,31 +120,24 @@ async def cmd_quotes(td: TdxData, symbols: list[str]) -> None:
def _print_quote(q) -> None:
pct = (q.price / q.pre_close - 1) * 100 if q.pre_close else 0
mkt = {31: "港股", 74: "美股"}.get(q.market, "")
if q.market in (0, 1):
dp = _display_dp(q.market, q.code)
else:
dp = getattr(q, "decimal_point", 2) or 2
print("=" * 58)
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.*f 涨跌 %+8.*f (%+.2f%%)" % (dp, q.price, dp, q.price - q.pre_close, pct)))
print((" 今开 %-10.*f 最高 %.*f 最低 %.*f" % (dp, q.open, dp, q.high, dp, q.low)))
print((" 昨收 %-10.*f 成交量 %s 成交额 %s" % (dp, q.pre_close, _fmt_num(q.vol), _fmt_num(q.amount))))
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 成交量 %s 成交额 %s" % (q.pre_close, _fmt_num(q.vol), _fmt_num(q.amount)))
if q.bid and q.ask:
print(" " + "-" * 56)
pf = _price_fmt(dp)
for i in range(max(len(q.bid), len(q.ask))):
b = q.bid[i] if i < len(q.bid) else (0, 0)
a = q.ask[i] if i < len(q.ask) else (0, 0)
print((" 买%-1d " + pf + " %10s | 卖%-1d " + pf + " %10s") % (
print(" 买%-1d %8.2f %10s | 卖%-1d %8.2f %10s" % (
i + 1, b[0], _fmt_num(b[1]), i + 1, a[0], _fmt_num(a[1])))
print()
async def cmd_kline(td: TdxData, sym: str, period: KlinePeriod, count: int,
start: int, adjust: Adjust) -> None:
s = parse_symbol(sym)
pf = _price_fmt(_dp_of(s))
bars = await td.get_bars(sym, period, start=start, count=count, adjust=adjust)
print("%s K线 (%s, %d根):" % (sym, period.name, len(bars)))
print(" %-12s %8s %8s %8s %8s %12s" % ("日期", "开盘", "最高", "最低", "收盘", "成交量"))
@@ -187,38 +145,30 @@ async def cmd_kline(td: TdxData, sym: str, period: KlinePeriod, count: int,
dt = "%04d-%02d-%02d" % (b.year, b.month, b.day)
if b.hour:
dt += " %02d:%02d" % (b.hour, b.minute)
print((" %-12s " + " ".join([pf] * 4) + " %12s") % (
print(" %-12s %8.2f %8.2f %8.2f %8.2f %12s" % (
dt, b.open, b.high, b.low, b.close, _fmt_num(b.vol)))
async def cmd_transactions(td: TdxData, sym: str, count: int, date: int | None) -> None:
s = parse_symbol(sym)
pf = _price_fmt(_dp_of(s))
tx = await td.get_ticks(sym, date=date, count=count)
tx = await td.get_transactions(Market(s.market), s.code, date=date, count=count)
print("%s 逐笔成交 (%d条):" % (sym, len(tx)))
print(" 时间 价格 成交量 方向")
for t in tx:
bs = "买" if getattr(t, "bs_flag", 0) == 1 else "卖" if getattr(t, "bs_flag", 0) == 2 else "-"
if not getattr(t, "trade_count_available", True):
tc = " (-)" # 指数/ETF/LOF:协议不提供笔数
elif getattr(t, "trade_count", 0):
tc = " (%d笔)" % t.trade_count
else:
tc = ""
print((" %-10s " + pf + " %10s %s%s") % (
t.time, t.price, _fmt_num(t.vol), bs, tc))
tc = getattr(t, "trade_count", 0)
print(" %-10s %8.2f %10s %s%s" % (t.time, t.price, _fmt_num(t.vol), bs,
" (%d笔)" % tc if tc else ""))
async def cmd_minute(td: TdxData, sym: str, date: int | None) -> None:
s = parse_symbol(sym)
pf = _price_fmt(_dp_of(s))
bars = await td.get_minutes(sym, date=date)
bars = await td.get_minute(Market(s.market), s.code, date=date)
print("%s 分时 (%d条):" % (sym, len(bars)))
print(" 时间 价格 均价 成交量")
for b in bars:
# 用 bar 自带时间:早期按序号推算会打成 00:00~03:59
print((" %02d:%02d " + pf + " " + pf + " %10s") % (
b.hour, b.minute, b.price, b.avg_price, _fmt_num(b.vol)))
for i, b in enumerate(bars):
print(" %02d:%02d %8.2f %8.2f %10s" % (
i // 60, i % 60, b.price, b.avg_price, _fmt_num(b.vol)))
async def cmd_board(td: TdxData, args) -> None:
+5 -30
View File
@@ -117,8 +117,8 @@ class SecurityBar:
high: float
low: float
close: float
vol: float # 股票=股 / 转债=手(1 手=10 张,与 vipdoc 一致)
amount: float # 元。⚠️ amount/vol 只在股票上等于均价;转债还要再 /10(手=10张)
vol: float # 股票=股 / 转债=手(与vipdoc一致)
amount: float # 元
year: int
month: int
day: int
@@ -247,42 +247,17 @@ class TransactionRecord:
- ``trade_count`` **不是笔数**,而是**当时均价 × 1000**(实测 tc/1000 与分时
``avg_price`` 的差 < 1.1)。指数没有「成交笔数」概念。
- ``bs_flag`` 语义不成立(实测返回 2,而模型只定义 0=卖 / 1=买)。
**场内基金同样没有笔数**(ETF / 多数 LOF,见
:func:`~pytdxdata.symbols.has_order_count`):
- ``trade_count`` 是 ``价格 × 1000``(实测 ``sh510310`` 收盘 tc=3994,
当时价 3.989 → 3989,偏差 σ≈2;货币 ETF ``sh511990`` 恒为 0)。
- ``vol`` 仍是**手**,``bs_flag`` 正常。
- 这类标的的 :attr:`trade_count_available` 为 ``False``,``trade_count`` 已被
置 ``0``,不要拿去求和/求均值。
``trade_count_available=False`` 表示该品种**协议上就不带笔数**,
与「本切片恰好 0 笔」不是一回事。
**可转债(110/111/113/118/123/127/128/132)三样都是真的**(实测 2026-10-22,
16 只 A股可转债当日 + 8 只历史日全部自洽):
- ``vol`` 单位是**手**(1 手 = 10 张),与股票逐笔一致;``trade_count`` 是**真实成交笔数**
(``sh111000`` 3631 条切片 / 20443 笔,可转债在
:func:`~pytdxdata.symbols.has_order_count` 里判为**可用**)。
- ``Σvol`` 与**日线** ``SecurityBar.vol`` **1:1 相等**(比值 1.000000)——
这点和股票相反:股票逐笔是「手」、日线是「股」,Σ比值是 **0.01**。
- ⚠️ 但**日线** ``amount / vol`` **不等于**均价,而是均价的 **10 倍**(``vol`` 的「手」= 10 张)。
要算可转债均价须用 ``amount / vol / 10``;股票则是 ``amount / vol`` 直接就对。
实测:``sz127025`` 逐笔 VWAP 105.9063 vs ``amount/vol`` 1059.0957,比值 10.0003。
"""
market: int
code: str
time: str # HH:MM:SS(扩展市场为 HH:MM)
price: float
vol: float # 股票/转债=手;指数=百元(成交额/100),见类注释
trade_count: int # 股票=笔数增量;指数/基金=占位值,见类注释
vol: float # 股票=手;指数=百元(成交额/100),见类注释
trade_count: int # 股票=笔数增量;指数=均价×1000,见类注释
bs_flag: int # 1=主动买 0=主动卖 2=中性 5=盘后固定价(指数语义不成立)
symbol: str = ""
fields: dict[str, float] = field(default_factory=dict) # 扩展市场额外字段(增仓等)
trade_count_available: bool = True # 指数/ETF/LOF 为 False(协议无笔数字段)
@dataclass(slots=True)
@@ -293,7 +268,7 @@ class MinuteBar:
:attr:`datetime` / :attr:`trading_date`,不要自己拿 ``hour`` 拼日期。
"""
price: float
vol: float # 手(股票/转债同);Σ分时vol 与当日日线 vol 同口径
vol: float
avg_price: float = 0.0 # 均价(协议第2字段)
hour: int = 0
minute: int = 0
-54
View File
@@ -3,7 +3,6 @@ from __future__ import annotations
import asyncio
import time
from collections.abc import Sequence
from typing import Generic, TypeVar
from ..protocol.commands.base import BaseCommand
@@ -23,7 +22,6 @@ class TdxConnection(Generic[T]):
self._reader: asyncio.StreamReader | None = None
self._writer: asyncio.StreamWriter | None = None
self._last_result: T | None = None
self._pipeline_result: list[T] = []
@property
def alive(self) -> bool:
@@ -109,58 +107,6 @@ class TdxConnection(Generic[T]):
body = decompress_body(header, raw_body)
self._last_result: T = cmd.parse_response(body)
async def execute_pipeline(
self, cmds: Sequence[BaseCommand[T]], *, timeout: float | None = None
) -> list[T]:
"""单连接**流水线**:一次性发出全部请求,再按序读取全部响应。
通达信协议是自描述长度帧(16 字节帧头 + body),且服务器**按序**应答,
因此可以在同一 TCP 连接上连续下发多条请求、省掉 ``(N-1)`` 次往返。
实测 66 个「80 只报价」请求:逐条 7,372ms → 流水线 526ms(14 倍)。
与 :meth:`execute` 的关键差异:``execute`` 逐条严格配对,失败可小范围重试;
流水线一旦中途失败,**响应流已错配**,剩余响应无法再与请求对齐,
故此处强制断开连接(上层应换连接重试)。
参数:
cmds: 同一连接的请求序列(通常为同一类命令的不同分片)。
timeout: 整体超时(默认 ``self.timeout * 2``,流水线耗时随条数增长)。
返回:
与 ``cmds`` **等长且同序**的结果列表。
"""
if not cmds:
return []
if not self.alive:
raise ConnectionError(f"连接未建立或已关闭: {self.host}")
assert self._reader is not None and self._writer is not None
budget = timeout if timeout is not None else self.timeout * 2
try:
try:
await asyncio.wait_for(self._io_pipeline(cmds), budget)
except asyncio.TimeoutError:
self._force_close()
raise ConnectionError(
f"流水线超时 {self.host} ({budget:.1f}s, {len(cmds)} 条)") from None
except (ConnectionError, OSError) as e:
self._force_close()
raise ConnectionError(f"流水线错误 {self.host}: {e}") from e
except (ConnectionError, OSError):
raise
return self._pipeline_result
async def _io_pipeline(self, cmds: Sequence[BaseCommand[T]]) -> None:
assert self._reader is not None and self._writer is not None
self._writer.write(b"".join(c.build_request() for c in cmds))
await self._writer.drain()
results: list[T] = []
for cmd in cmds:
header_buf = await self._recv_exact(HEADER_SIZE)
header = parse_header(header_buf)
raw_body = await self._recv_exact(header.zipsize)
results.append(cmd.parse_response(decompress_body(header, raw_body)))
self._pipeline_result: list[T] = results
async def _send_setup(self) -> None:
"""按序发送3条握手命令并丢弃响应。"""
assert self._reader is not None and self._writer is not None
-45
View File
@@ -59,11 +59,6 @@ class PooledConnection:
self.last_used = time.monotonic()
return await self.conn.execute(cmd)
async def execute_pipeline(self, cmds, *, timeout: float | None = None):
"""在同一条连接上流水线执行多条命令(见 TdxConnection.execute_pipeline)。"""
self.last_used = time.monotonic()
return await self.conn.execute_pipeline(cmds, timeout=timeout)
async def close(self) -> None:
self.alive = False
try:
@@ -278,46 +273,6 @@ class DynamicPool:
]
return random.choice(alive) if alive else None
async def warm(self, n: int) -> None:
"""并发预建连接至 ``n`` 条(最多到 ``max_size``)。
:meth:`acquire` 建连时持有池锁,**一次只能建一条**——22 路并发首次
调用会排队 22×握手时间(实测全市场首拉多花 5~6s)。大批量请求前先调
本方法把连接并发建好,首拉只多付一次握手。
失败静默忽略:缺的连接后续由 ``acquire`` 按需补齐。
"""
if self._closed:
return
need = min(n, self.max_size) - self._total
if need <= 0:
return
# 用局部计数挑 host,避免并发建连时反复选中同一台
counts = dict(self._server_count)
ranked = self.health.rank(self.servers)
hosts: list[str] = []
for _ in range(need):
host = next((h for h in ranked
if not self.health.in_cooldown(h)
and counts.get(h, 0) < self.per_server_cap), None)
if host is None:
break
hosts.append(host)
counts[host] = counts.get(host, 0) + 1
if not hosts:
return
results = await asyncio.gather(
*(self._new_conn(h) for h in hosts), return_exceptions=True)
async with self._lock:
for pc in results:
if isinstance(pc, PooledConnection):
self._total += 1
self.stats.total = self._total
if not self._closed and pc.alive:
self._idle.append(pc)
async def release(self, pc: PooledConnection, *, broken: bool = False) -> None:
if self.stats.borrowed > 0:
self.stats.borrowed -= 1
+5 -15
View File
@@ -5,7 +5,6 @@ import struct
from ..._binary import unpack_from
from ...models import TransactionRecord
from ...symbols import has_order_count
from ..datetime_ import get_time
from ..mac_frame import build_mac_request
from ..price import get_price
@@ -33,8 +32,6 @@ class GetTransactionDataCmd(BaseCommand[list[TransactionRecord]]):
pos = 2
last_price = 0
records: list[TransactionRecord] = []
code = self.code.decode("utf-8")
has_tc = has_order_count(self.market, code)
for _ in range(num):
hour, minute, pos = get_time(body, pos)
price_diff, pos = get_price(body, pos)
@@ -44,12 +41,10 @@ class GetTransactionDataCmd(BaseCommand[list[TransactionRecord]]):
_unknown, pos = get_price(body, pos)
last_price += price_diff
records.append(TransactionRecord(
market=self.market, code=code,
market=self.market, code=self.code.decode("utf-8"),
time=f"{hour:02d}:{minute:02d}:00",
price=last_price / 100.0, vol=float(vol),
# 指数/ETF/LOF 该字段是「价格×1000」占位,不是笔数
trade_count=int(num_orders) if has_tc else 0,
bs_flag=bs_flag, trade_count_available=has_tc,
trade_count=int(num_orders), bs_flag=bs_flag,
))
return records
@@ -73,7 +68,6 @@ class GetHistoryTransactionDataCmd(BaseCommand[list[TransactionRecord]]):
pos = 6 # 2(num) + 4(skip)
last_price = 0
records: list[TransactionRecord] = []
code = self.code.decode("utf-8")
for _ in range(num):
hour, minute, pos = get_time(body, pos)
price_diff, pos = get_price(body, pos)
@@ -82,11 +76,10 @@ class GetHistoryTransactionDataCmd(BaseCommand[list[TransactionRecord]]):
_unknown, pos = get_price(body, pos)
last_price += price_diff
records.append(TransactionRecord(
market=self.market, code=code,
market=self.market, code=self.code.decode("utf-8"),
time=f"{hour:02d}:{minute:02d}:00",
price=last_price / 100.0, vol=float(vol),
trade_count=0, bs_flag=bs_flag,
trade_count_available=False, # 历史通道整条链路都没有笔数字段
trade_count=0, bs_flag=bs_flag, # 历史无笔数
))
return records
@@ -115,7 +108,6 @@ class MacTransactionCmd(BaseCommand[list[TransactionRecord]]):
def parse_response(self, body: bytes) -> list[TransactionRecord]:
(count,) = unpack_from("<H", body, 29, "mac transaction count")
records: list[TransactionRecord] = []
has_tc = has_order_count(self.market, self.code)
for i in range(count):
offset = 39 + i * 18
try:
@@ -132,8 +124,6 @@ class MacTransactionCmd(BaseCommand[list[TransactionRecord]]):
market=self.market, code=self.code,
time=f"{h:02d}:{m:02d}:{s:02d}",
price=price, vol=float(volume),
# 指数/ETF/LOF 该字段是「价格×1000」占位,不是笔数
trade_count=int(trade_count) if has_tc else 0,
bs_flag=bs_flag, trade_count_available=has_tc,
trade_count=int(trade_count), bs_flag=bs_flag,
))
return records
-50
View File
@@ -238,53 +238,3 @@ def is_cn_index(market: int, code: str) -> bool:
or (code.startswith("000") and int(market) == int(Market.SH))
or (code.startswith("399") and int(market) == int(Market.SZ))
)
def has_order_count(market: int, code: str) -> bool:
"""该标的的逐笔 ``trade_count`` 是否是**真实成交笔数**。
通达信对**指数**和**多数场内基金**不提供笔数,但那 4 字节里仍塞了值:
- 指数:``当时均价 × 1000``(见 :class:`~pytdxdata.models.TransactionRecord`)
- ETF / LOF:``价格 × 1000``;货币 ETF(如 ``sh511990``)恒为 ``0``
直接当笔数用会得到 3994 这种荒谬值(实测 ``sh510310``)。
实测覆盖(2026-10-22,按代码前缀各取样 1~7 只):
================== ========================== ==========
品种 前缀 笔数可用
================== ========================== ==========
沪股票/科创 600/601/603/605/688/689 是
沪 LOF 501/502/506 是
沪 ETF/LOF 51/52/56/58 **否**
沪指数 000/88 否
沪可转债 110/111/113/118 是
沪 EB(可交换债) 132 是
沪逆回购 204 是
深股票 000/001/002/003/300/301 是
深 ETF 159 **否**
深 LOF/基金 15/16/17/18 **否**
深指数 399 否
深可转债 123/127/128 是
================== ========================== ==========
``501x/502x/506x``(沪市 LOF)实测**有**真实笔数,所以不能用「沪市 5 开头
一律当基金」的粗规则;必须按上面这组前缀精确判定。
可转债(沪 110/111/113/118/132、深 123/127/128)**走的是兜底分支**——
它们既不在沪市 ``51/52/56/58`` 里,也不在深市 ``159/15/16/17/18`` 里,
所以两个分支都落到「是」。这不是巧合而是设计:兜底按「**排除法**」认定
基金/指数,其余一律当普通品种。实测验证(2026-10-22,16 只当日 + 8 只历史日):
笔数合计与日线量级吻合(``sh111000`` 3631 条切片 / 20443 笔,
``sz128136`` 1939 条 / 14593 笔),且 ``Σvol`` 与日线 ``vol`` 比值 **1.000000**。
"""
code = str(code)
if is_cn_index(market, code):
return False
m = int(market)
if m == int(Market.SH):
return code[:2] not in ("51", "52", "56", "58")
if m == int(Market.SZ):
return not (code[:3] == "159" or code[:2] in ("15", "16", "17", "18"))
return True
+22
View File
@@ -0,0 +1,22 @@
"""测试全局隔离。
默认关掉**权威小数位表的后台同步** —— 否则任何调用 ``TdxData.start()`` 的用例都会
顺手发起证券清单请求(26 + 25 个分页),测试会变慢且依赖网络。
需要验证同步行为本身的用例(``test_decimal_sync.py``)自己 ``delenv`` 后再测。
"""
from __future__ import annotations
import os
import pytest
@pytest.fixture(autouse=True, scope="session")
def _disable_decimal_sync():
old = os.environ.get("PYPYTDX_DATA_DISABLE_DECIMAL_SYNC")
os.environ["PYPYTDX_DATA_DISABLE_DECIMAL_SYNC"] = "1"
yield
if old is None:
os.environ.pop("PYPYTDX_DATA_DISABLE_DECIMAL_SYNC", None)
else:
os.environ["PYPYTDX_DATA_DISABLE_DECIMAL_SYNC"] = old
+39
View File
@@ -324,6 +324,27 @@ async def test_universe_and_quotes(td):
assert len(qex) == 1
async def test_decimal_point_sync(td, tmp_path, monkeypatch):
"""权威小数位表同步:把证券清单的 decimal_point 灌进价格标度表。"""
for name in ("sync_decimal_points", "decimal_point_status"):
_use(name)
from pytdxdata.protocol.commands.quotes import clear_decimal_map, price_decimal_digits
# 缓存目录指向临时目录,避免把 mock 数据写进用户真实缓存
monkeypatch.setenv("PYPYTDX_DATA_CACHE_DIR", str(tmp_path))
before = price_decimal_digits(1, "600000")
try:
st = await td.sync_decimal_points()
assert set(st) >= {"prefixes", "codes", "mixed_prefixes", "stock"}
assert st["stock"] >= 0
status = await td.decimal_point_status()
assert isinstance(status, dict) and "source" in status
finally:
clear_decimal_map()
# 清空后回到静态规则,不受本用例污染
assert price_decimal_digits(1, "600000") == before
async def test_snapshot_auction_flow(td):
for name in ("get_snapshot", "get_auction", "get_capital_flow"):
_use(name)
@@ -457,6 +478,24 @@ async def test_boards(td):
assert isinstance(chg, list)
async def test_index_trade_stats(td):
"""指数成分成交汇总:成分 → 逐笔 → 每分钟量/笔数。"""
for name in ("get_index_members", "get_index_trade_stats",
"get_index_trade_stats_multi"):
_use(name)
mem = await td.get_index_members("000016")
assert isinstance(mem, list) and mem and mem[0].symbol
st = await td.get_index_trade_stats("000016")
assert st.index == "sh000016"
assert st.member_count >= 1
assert st.minutes and st.minutes[0].time == "09:30"
assert st.total_trade_count >= 1
assert st.cum_trade_count()[-1][1] == st.total_trade_count
multi = await td.get_index_trade_stats_multi("000016", [20261020, None])
assert len(multi) == 2
assert multi[0].date == 20261020 and multi[1].date is None
# --------------------------------------------------------------------------- #
# 六、服务器文件
# --------------------------------------------------------------------------- #
+211 -1
View File
@@ -8,7 +8,13 @@ import unittest.mock as mock
import pytest
from pytdxdata.api import TdxData
from pytdxdata.models import KlinePeriod, Market, MinuteBar, SecurityBar
from pytdxdata.models import (
KlinePeriod,
Market,
MinuteBar,
SecurityBar,
TransactionRecord,
)
from pytdxdata.protocol.commands.mac_tick import MacTickChartCmd
from pytdxdata.scheduler.paginator import PageSpec, Paginator
@@ -243,6 +249,70 @@ async def test_paginator_start_offset_default_zero():
assert result[0].close == 10.0 # 从 offset 0 开始
# ---------- Paginator 逆序偏移(服务端 start 从最新往回数) ----------
class NewestFirstConn:
"""模拟 0x122F 真实行为:start=0 返回**最新**的一页,start 越大越旧。
实测依据(2026-10-21,sh600000):
start=0 -> 14:07:48 .. 15:20:16(当天最新 1000 条)
start=4000 -> 09:15:03 .. 09:41:18(当天最早)
每页内部按时间升序,页与页之间是倒序。
"""
def __init__(self, total: int, page_size: int):
self.total = total
self.page_size = page_size
self.executed: list[tuple[int, int]] = []
async def execute(self, cmd):
start, count = cmd
self.executed.append((start, count))
# 服务端语义:偏移 start 是从"最新"往回数,所以取倒数区间
end_from_oldest = self.total - start
begin_from_oldest = max(0, end_from_oldest - count)
return [_make_bar(i) for i in range(begin_from_oldest, end_from_oldest)]
@pytest.mark.asyncio
async def test_paginator_newest_first_offset_returns_chronological():
"""服务端 start 从最新往回数时,交付列表必须仍是时间升序(BUG 回归)。"""
conns = [NewestFirstConn(3000, 1000) for _ in range(3)]
pool = FakePool(conns)
pag = Paginator(pool, concurrency=3) # type: ignore[arg-type]
def factory(s, c):
return (s, c)
result = await pag.fetch_all(
factory, PageSpec(page_size=1000, total=3000, newest_first=True))
assert len(result) == 3000
# 时间升序:close 随 index 单调递增
closes = [b.close for b in result]
assert closes == sorted(closes), "返回列表必须按时间升序拼接"
assert result[0].close == pytest.approx(10.0)
assert result[-1].close == pytest.approx(10.0 + 2999 * 0.01)
@pytest.mark.asyncio
async def test_paginator_newest_first_respects_start_offset():
"""newest_first + start_offset:只取最近 N 条里的后段。"""
conns = [NewestFirstConn(3000, 1000) for _ in range(3)]
pool = FakePool(conns)
pag = Paginator(pool, concurrency=3) # type: ignore[arg-type]
def factory(s, c):
return (s, c)
result = await pag.fetch_all(
factory,
PageSpec(page_size=1000, total=1000, newest_first=True, start_offset=0))
assert len(result) == 1000
# 只取了最新的 1000 条 → 是 2000..2999 这一段
assert result[0].close == pytest.approx(10.0 + 2000 * 0.01)
assert result[-1].close == pytest.approx(10.0 + 2999 * 0.01)
# ---------- get_kline 日期过滤 ----------
class DateBarApiConn(FakeApiConn):
@@ -329,3 +399,143 @@ async def test_get_kline_since():
assert bars[-1].year == 2027
finally:
await td.close()
# ---------- A股逐笔:b8 过滤 + 单连接串行游标(回归) ----------
class TickApiConn(FakeApiConn):
"""模拟 0x122F:服务端 start 从**最新**往回数,且可注入 bs_flag=8 委托记录。"""
# 类级:[(time, price, vol, trade_count, bs_flag), ...],时间升序(最早在前)
rows: list[tuple] = []
calls: list[tuple[int, int]] = []
async def execute(self, cmd):
if "MacTransactionCmd" not in type(cmd).__name__:
return await super().execute(cmd)
TickApiConn.calls.append((cmd.start, cmd.count))
# 从最新往回数:start 偏移落在末尾,往前取 count 条
end = len(TickApiConn.rows) - cmd.start
begin = max(0, end - cmd.count)
chunk = TickApiConn.rows[begin:end]
return [TransactionRecord(market=1, code="600000", time=t, price=p,
vol=v, trade_count=tc, bs_flag=bs)
for (t, p, v, tc, bs) in chunk]
def _build_tick_rows(n_trade: int = 25, n_b8: int = 7) -> list[tuple]:
"""构造 n_trade 条正常成交 + n_b8 条竞价委托(穿插在中间)。"""
rows: list[tuple] = []
for i in range(n_trade):
rows.append((f"09:{30 + i // 60:02d}:{i % 60:02d}", 10.0 + i * 0.01,
100.0 + i, 3 + i, 1 if i % 2 else 0))
if i % 4 == 0 and len([r for r in rows if r[4] == 8]) < n_b8:
# 竞价委托:(time, price, vol, tc, bs=8),vol 是累计值、不计入成交
rows.append((f"09:15:{i:02d}", 10.0, 9999.0, -1, 8))
return rows
@pytest.mark.asyncio
async def test_get_ticks_filters_auction_orders():
"""bs_flag=8 是竞价**委托**快照,不是成交 → 必须从 get_ticks 结果中剔除。
实测(2026-10-21 sh600000):b8 的 vol 是累计撮合量(可被覆盖),
计入后 Σvol 比快照 vol 虚高 20%~160%,且不同主机的 b8 集合不同。
"""
TickApiConn.rows = _build_tick_rows(n_trade=25, n_b8=7)
TickApiConn.calls = []
assert sum(1 for r in TickApiConn.rows if r[4] == 8) == 7
with mock.patch("pytdxdata.api.get_standard_hosts", return_value=["s1"]), \
mock.patch("pytdxdata.api.get_mac_hosts", return_value=["m1"]), \
mock.patch("pytdxdata.pool.pool.TdxConnection",
side_effect=lambda h, p=7709, t=10.0: TickApiConn(h)):
td = TdxData(cache_dir=None, pool_min=1, pool_max=2)
await td.start()
try:
out = await td.get_ticks("sh600000")
finally:
await td.close()
assert out, "应返回成交记录"
assert all(r.bs_flag != 8 for r in out), "bs_flag=8 竞价委托必须被剔除"
assert len(out) == 25
assert sum(r.vol for r in out) == sum(100.0 + i for i in range(25))
@pytest.mark.asyncio
async def test_get_ticks_pages_on_single_connection():
"""翻页必须走**同一连接**:并发多主机会让页边界错位(重叠 + 漏条)。"""
TickApiConn.rows = _build_tick_rows(n_trade=25, n_b8=0)
TickApiConn.calls = []
with mock.patch("pytdxdata.api.get_standard_hosts", return_value=["s1"]), \
mock.patch("pytdxdata.api.get_mac_hosts", return_value=["m1", "m2", "m3"]), \
mock.patch("pytdxdata.pool.pool.TdxConnection",
side_effect=lambda h, p=7709, t=10.0: TickApiConn(h)):
td = TdxData(cache_dir=None, pool_min=1, pool_max=4)
await td.start()
try:
out = await td.get_ticks("sh600000")
finally:
await td.close()
# 单页装得下 → 只发一次请求
assert len(TickApiConn.calls) == 1
assert len(out) == 25
# 时间升序
times = [r.time for r in out]
assert times == sorted(times)
@pytest.mark.asyncio
async def test_get_ticks_multi_page_uses_one_connection_and_no_overlap():
"""多页(>_TICK_PAGE):同一连接、游标按 len(rows) 推进、页间不重叠不漏条。
回归:并发分页时各页来自不同主机,而 0x122F 的 start 是「从最新往回数」的
相对锚点 —— 各主机对 bs_flag=8 收录不同,同一 start 落到不同真实成交上,
结果页边界既重叠又漏条(实测 sh600000 冗余 116 条、13:03 附近丢 59 条)。
"""
from pytdxdata.api import _TICK_PAGE
n = _TICK_PAGE * 2 + 137 # 3 页,末页短页 → 触发 stop_when_short
TickApiConn.rows = [
(f"{9 + i // 3600:02d}:{i // 60 % 60:02d}:{i % 60:02d}",
10.0 + i * 0.001, 1.0 + i, 1 + i, 1)
for i in range(n)
]
TickApiConn.calls = []
with mock.patch("pytdxdata.api.get_standard_hosts", return_value=["s1"]), \
mock.patch("pytdxdata.api.get_mac_hosts", return_value=["m1", "m2", "m3"]), \
mock.patch("pytdxdata.pool.pool.TdxConnection",
side_effect=lambda h, p=7709, t=10.0: TickApiConn(h)):
td = TdxData(cache_dir=None, pool_min=1, pool_max=4)
await td.start()
try:
out = await td.get_ticks("sh600000")
finally:
await td.close()
# 恰好 3 页:0 / 1000 / 2000,游标按实际返回条数推进
assert TickApiConn.calls == [(0, _TICK_PAGE),
(_TICK_PAGE, _TICK_PAGE),
(_TICK_PAGE * 2, _TICK_PAGE)]
assert len(out) == n, f"必须无重叠、无漏条:期望 {n},实得 {len(out)}"
vols = [r.vol for r in out]
assert len(set(vols)) == n, "vol 全唯一(无重复记录)"
assert vols == sorted(vols), "时间升序"
# count 参数:游标逐页扣减
TickApiConn.calls = []
with mock.patch("pytdxdata.api.get_standard_hosts", return_value=["s1"]), \
mock.patch("pytdxdata.api.get_mac_hosts", return_value=["m1", "m2", "m3"]), \
mock.patch("pytdxdata.pool.pool.TdxConnection",
side_effect=lambda h, p=7709, t=10.0: TickApiConn(h)):
td = TdxData(cache_dir=None, pool_min=1, pool_max=4)
await td.start()
try:
out2 = await td.get_ticks("sh600000", count=_TICK_PAGE + 50)
finally:
await td.close()
assert len(out2) == _TICK_PAGE + 50
assert TickApiConn.calls[1][1] == 50, "末页只补足剩余 50 条"
+233
View File
@@ -0,0 +1,233 @@
"""权威价格小数位表(decimal_sync)单元测试。
覆盖点:
- 权威表(来自 ``SecurityInfo.decimal_point``)**优先于**静态前缀规则
- 某前缀出现混合小数位 → 自动退化为逐代码查表,不误伤同前缀其它代码
- 清空权威表 → 回到静态规则(与 0.6.5 行为一致)
- 磁盘缓存:写入 / 读取 / 跨日失效 / 损坏容错,均不回退到网络
- ``PYPYTDX_DATA_DISABLE_DECIMAL_SYNC=1`` → 完全不动作
- 证券清单里 ``decimal_point == 0`` 的脏条目被忽略
- 后台 task 可取消,且 ``close()`` 后不再改写表
(全部注入假 ``TdxData``,不连真实网络)
"""
from __future__ import annotations
import asyncio
import json
from types import SimpleNamespace
import pytest
from pytdxdata import decimal_sync
from pytdxdata.protocol.commands.quotes import (
clear_decimal_map,
decimal_map_stats,
install_decimal_map,
price_decimal_digits,
)
# ---------------------------------------------------------------------- #
# 夹具
# ---------------------------------------------------------------------- #
@pytest.fixture(autouse=True)
def _isolate(tmp_path, monkeypatch):
"""每个用例独立缓存目录 + 干净的内存状态。"""
monkeypatch.setenv("PYPYTDX_DATA_CACHE_DIR", str(tmp_path))
monkeypatch.delenv("PYPYTDX_DATA_DISABLE_DECIMAL_SYNC", raising=False)
decimal_sync.reset()
yield
decimal_sync.reset()
def _info(code: str, dp: int) -> SimpleNamespace:
return SimpleNamespace(code=code, decimal_point=dp, market=1)
class FakeTd:
"""只有 ``get_universe`` 的假客户端(记录调用次数,便于断言"没走网络")。"""
def __init__(self, tables: dict[str, list[tuple[str, int]]] | None = None) -> None:
self.tables = tables or {}
self.calls: list[str] = []
async def get_universe(self, market: str | None = None):
self.calls.append(market or "all")
return [_info(c, d) for c, d in self.tables.get(market, [])]
# ---------------------------------------------------------------------- #
# 权威表优先级
# ---------------------------------------------------------------------- #
def test_authoritative_map_overrides_static_rule():
# 静态规则说 sh019742 是 4 位;权威表说 3 位 → 必须听权威表的
assert price_decimal_digits(1, "019742") == 4
install_decimal_map([(1, "019742", 3)], source="test")
assert price_decimal_digits(1, "019742") == 3
def test_codes_outside_map_still_use_static_rule():
install_decimal_map([(1, "019742", 3)], source="test")
assert price_decimal_digits(1, "600000") == 2 # 股票
assert price_decimal_digits(1, "510300") == 3 # ETF
assert price_decimal_digits(0, "131810") == 4 # 深回购(表里没有)
def test_mixed_prefix_falls_back_to_per_code_lookup():
"""同一前缀出现两种小数位 → 该前缀不进前缀表,只把例外代码存进逐代码表。"""
stats = install_decimal_map(
[(1, "110001", 4), (1, "110002", 4), (1, "110003", 3)], source="test")
assert stats["mixed_prefixes"] == 1
assert stats["codes"] == 3 # 混合前缀下所有代码都进逐代码表
assert price_decimal_digits(1, "110001") == 4
assert price_decimal_digits(1, "110003") == 3
def test_clear_map_restores_static_rules():
install_decimal_map([(1, "019742", 3)], source="test")
assert price_decimal_digits(1, "019742") == 3
clear_decimal_map()
assert decimal_map_stats()["stock"] == 0
assert price_decimal_digits(1, "019742") == 4
def test_reinstall_replaces_previous_map():
install_decimal_map([(1, "019742", 3)], source="a")
install_decimal_map([(1, "019742", 4)], source="b")
assert price_decimal_digits(1, "019742") == 4
assert decimal_map_stats()["prefixes"] == 1
# ---------------------------------------------------------------------- #
# 同步
# ---------------------------------------------------------------------- #
def test_refresh_installs_and_writes_cache(tmp_path):
td = FakeTd({"sh": [("019742", 4), ("600000", 2)],
"sz": [("000001", 2), ("131810", 4)]})
stats = asyncio.run(decimal_sync.refresh(td))
assert td.calls == ["sh", "sz"]
assert stats["stock"] == 4
assert price_decimal_digits(1, "600000") == 2
assert price_decimal_digits(0, "131810") == 4
raw = json.loads((tmp_path / "decimal-points.json").read_text(encoding="utf-8"))
assert raw["markets"]["1"]["019742"] == 4
assert raw["markets"]["0"]["131810"] == 4
def test_refresh_skips_zero_decimal_point():
td = FakeTd({"sh": [("019742", 0), ("600000", 2)]})
stats = asyncio.run(decimal_sync.refresh(td, ("sh",)))
assert stats["stock"] == 1
def test_refresh_ignores_unknown_market():
td = FakeTd({"hk": [("00700", 3)]})
stats = asyncio.run(decimal_sync.refresh(td, ("hk",)))
assert stats["stock"] == 0
assert not (decimal_sync.cache_file()).exists()
def test_load_cached_roundtrip(tmp_path):
td = FakeTd({"sh": [("019742", 4)]})
asyncio.run(decimal_sync.refresh(td))
decimal_sync.reset()
assert decimal_map_stats()["stock"] == 0
assert decimal_sync.load_cached() == 1
assert price_decimal_digits(1, "019742") == 4
def test_cache_expires_across_days(tmp_path):
td = FakeTd({"sh": [("019742", 4)]})
asyncio.run(decimal_sync.refresh(td))
decimal_sync.reset()
path = tmp_path / "decimal-points.json"
payload = json.loads(path.read_text(encoding="utf-8"))
payload["date"] = "2000-01-01"
path.write_text(json.dumps(payload), encoding="utf-8")
assert decimal_sync.load_cached() == 0
def test_corrupt_cache_is_ignored(tmp_path):
path = tmp_path / "decimal-points.json"
path.write_text("{not json", encoding="utf-8")
assert decimal_sync.load_cached() == 0
# ---------------------------------------------------------------------- #
# 调度
# ---------------------------------------------------------------------- #
def test_schedule_disabled_by_env(monkeypatch):
monkeypatch.setenv("PYPYTDX_DATA_DISABLE_DECIMAL_SYNC", "1")
td = FakeTd({"sh": [("019742", 4)]})
async def run():
task = decimal_sync.schedule(td)
return task
assert asyncio.run(run()) is None
assert td.calls == []
def test_schedule_loads_cache_without_network(tmp_path):
td = FakeTd({"sh": [("019742", 4)]})
asyncio.run(decimal_sync.refresh(td))
decimal_sync.reset()
quiet = FakeTd({"sh": [("019742", 4)]})
async def run():
return decimal_sync.schedule(quiet)
assert asyncio.run(run()) is None # 缓存命中 → 不起 task
assert quiet.calls == [] # 也没走网络
assert price_decimal_digits(1, "019742") == 4
def test_schedule_runs_background_sync_without_cache():
td = FakeTd({"sh": [("019742", 4)]})
async def run():
task = decimal_sync.schedule(td)
assert task is not None
await task
return decimal_sync.status()
st = asyncio.run(run())
assert st["source"] == "universe"
assert st["syncing"] is False
assert td.calls == ["sh", "sz"] # 默认两市
def test_cancel_stops_background_task():
class SlowTd:
def __init__(self) -> None:
self.calls = 0
async def get_universe(self, market=None):
self.calls += 1
await asyncio.sleep(5)
return []
td = SlowTd()
async def run():
task = decimal_sync.schedule(td)
await asyncio.sleep(0.01)
await decimal_sync.cancel(task)
return task.done() or task.cancelled()
assert asyncio.run(run()) is True
def test_status_shape():
st = decimal_sync.status()
assert set(st) >= {"loaded", "source", "syncing", "prefixes", "codes",
"mixed_prefixes", "stock"}
+303
View File
@@ -0,0 +1,303 @@
"""指数成分成交汇总(get_index_members / get_index_trade_stats)单元测试。
全部离线:成分与逐笔都用实例属性打补丁,不建立任何真实连接。
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
from pytdxdata import TdxData
from pytdxdata.models import (
IndexTradeStats,
MemberQuote,
MinuteTradeStat,
TransactionRecord,
)
# ---------- _index_pair:裸代码按指数语义解析 ----------
@pytest.mark.parametrize("text,expect", [
("000001", (1, "000001")), # 上证指数(不是平安银行!)
("sh000001", (1, "000001")),
("000300", (1, "000300")),
("sh000300", (1, "000300")),
("000905", (1, "000905")),
("999999", (1, "999999")),
("880305", (1, "880305")),
("399001", (0, "399001")), # 深证成指
("sz399006", (0, "399006")),
("899050", (2, "899050")), # 北证50
("bj899050", (2, "899050")),
("sh.000300", (1, "000300")), # 点号/冒号都容忍
("sz:399001", (0, "399001")),
])
def test_index_pair_parses(text, expect):
assert TdxData._index_pair(text) == expect
@pytest.mark.parametrize("text", [
"", "600000", "sz000001x", "sh12345", "12345", "abc", "zzz000001",
])
def test_index_pair_rejects(text):
with pytest.raises(ValueError):
TdxData._index_pair(text)
def test_index_pair_rejects_non_index_cn_code():
"""000001 之外的普通股票段(如 600xxx)不是指数,裸写必须报错。"""
with pytest.raises(ValueError):
TdxData._index_pair("600000")
# ---------- 模型:累计曲线 ----------
def test_index_trade_stats_cumulative():
st = IndexTradeStats(
index="sh000300", date=None, member_count=2, active_members=2,
trade_count_members=2,
minutes=[
MinuteTradeStat("09:30", 100.0, 10, 1000.0),
MinuteTradeStat("09:31", 200.0, 20, 2000.0),
MinuteTradeStat("09:32", 50.0, 5, 500.0),
],
total_volume=350.0, total_trade_count=35, total_amount=3500.0,
)
cum = st.cumulative()
assert [c.time for c in cum] == ["09:30", "09:31", "09:32"]
assert [c.volume for c in cum] == [100.0, 300.0, 350.0]
assert [c.trade_count for c in cum] == [10, 30, 35]
assert [c.amount for c in cum] == [1000.0, 3000.0, 3500.0]
# 累计必须是新对象,不污染原始增量
assert st.minutes[1].volume == 200.0
assert st.cum_trade_count() == [("09:30", 10), ("09:31", 30), ("09:32", 35)]
def test_index_trade_stats_trade_count_available():
ok = IndexTradeStats(index="sh000300", date=None, member_count=1,
active_members=1, trade_count_members=1)
assert ok.trade_count_available is True
bj = IndexTradeStats(index="bj899050", date=None, member_count=1,
active_members=1, trade_count_members=0)
assert bj.trade_count_available is False
# ---------- get_index_members:分页终止 ----------
def _member(market: int, code: str, name: str = "") -> MemberQuote:
return MemberQuote(market=market, code=code, name=name,
fields={"0x0": 9.9, "0x5": 1000.0, "0x7": 99000.0})
@pytest.mark.asyncio
async def test_get_index_members_pages_until_short_batch():
"""短页(不足 80 条)即视为最后一页,不再多发一次空请求。"""
calls: list[int] = []
async def fake_exec(cmd):
calls.append(cmd.start)
if cmd.start == 0:
return [_member(1, "600000"), _member(1, "600004")]
return []
td = TdxData(cache_dir=None)
td._execute_mac = fake_exec
members = await td.get_index_members("000016")
assert [m.symbol for m in members] == ["sh600000", "sh600004"]
assert calls == [0]
@pytest.mark.asyncio
async def test_get_index_members_continues_on_full_page():
"""满页(80 条)后继续翻页,直到空页。"""
calls: list[int] = []
async def fake_exec(cmd):
calls.append(cmd.start)
if cmd.start == 0:
return [_member(1, "600000")] * cmd.page_size
return []
td = TdxData(cache_dir=None)
td._execute_mac = fake_exec
members = await td.get_index_members("000016")
assert len(members) == 80
assert calls == [0, 80]
@pytest.mark.asyncio
async def test_get_index_members_respects_count_cap():
async def fake_exec(cmd):
# 永远返回满页,验证 count 能截断结果
return [_member(1, "600000")] * cmd.page_size
td = TdxData(cache_dir=None)
td._execute_mac = fake_exec
members = await td.get_index_members("000016", count=5)
assert len(members) == 5
# ---------- get_index_trade_stats:按分钟聚合 ----------
def _tick(sym: str, hhmm: str, price: float, vol: float, tc: int) -> TransactionRecord:
market, code = (1, sym[2:]) if sym.startswith("sh") else (0, sym[2:])
return TransactionRecord(market=market, code=code, time=f"{hhmm}:00",
price=price, vol=vol, trade_count=tc, bs_flag=1,
symbol=sym)
@pytest.mark.asyncio
async def test_get_index_trade_stats_aggregates_minutes():
async def fake_ticks(symbols, date=None, concurrency=6, **kw):
out = []
for s in symbols:
if s == "sh600000":
out += [_tick(s, "09:30", 10.0, 100.0, 10),
_tick(s, "09:30", 10.0, 50.0, 5),
_tick(s, "09:31", 11.0, 200.0, 20)]
else:
out += [_tick(s, "09:30", 5.0, 1000.0, 7)]
return out
td = TdxData(cache_dir=None)
td.get_ticks = fake_ticks
st = await td.get_index_trade_stats(
"000016", members=["sh600000", "sz000001"])
assert st.index == "sh000016"
assert st.member_count == 2
assert st.active_members == 2
assert st.trade_count_members == 2
assert st.trade_count_available is True
assert st.failed_members == 0
m = {x.time: x for x in st.minutes}
assert sorted(m) == ["09:30", "09:31"]
assert m["09:30"].volume == 1150.0 # 100 + 50 + 1000
assert m["09:30"].trade_count == 22 # 10 + 5 + 7
assert m["09:31"].volume == 200.0
# amount = Σ(price × 手 × 100)
assert m["09:30"].amount == pytest.approx(
10.0 * 100 * 100 + 10.0 * 50 * 100 + 5.0 * 1000 * 100)
assert st.total_volume == 1350.0
assert st.total_trade_count == 42
assert st.total_amount == pytest.approx(
10.0 * 100 * 100 + 10.0 * 50 * 100 + 5.0 * 1000 * 100 + 11.0 * 200 * 100)
assert st.cum_trade_count() == [("09:30", 22), ("09:31", 42)]
@pytest.mark.asyncio
async def test_get_index_trade_stats_bj_has_no_trade_count():
"""北交所成分返回 trade_count=0 → trade_count_available False。"""
async def fake_ticks(symbols, date=None, concurrency=6, **kw):
return [_tick("sh600000", "09:30", 10.0, 100.0, 0)]
td = TdxData(cache_dir=None)
td.get_ticks = fake_ticks
st = await td.get_index_trade_stats("899050", members=["sh600000"])
assert st.trade_count_members == 0
assert st.trade_count_available is False
assert st.total_volume == 100.0
@pytest.mark.asyncio
async def test_get_index_trade_stats_retries_per_symbol_on_batch_failure():
"""整批失败 → 退化为逐只重试,只有真正失败的计入 failed_members。"""
async def fake_ticks(symbols, date=None, concurrency=6, **kw):
single = isinstance(symbols, str)
if not single:
raise ConnectionError("批量炸了")
if symbols == "sh600004":
raise ConnectionError("这只也炸了")
return [_tick(symbols, "09:30", 10.0, 100.0, 3)]
td = TdxData(cache_dir=None)
td.get_ticks = fake_ticks
st = await td.get_index_trade_stats(
"000016", members=["sh600000", "sh600004", "sh600006"])
assert st.failed_members == 1
assert st.active_members == 2
assert st.total_trade_count == 6
@pytest.mark.asyncio
async def test_get_index_trade_stats_raises_when_not_skip_errors():
async def fake_ticks(symbols, date=None, concurrency=6, **kw):
raise ConnectionError("boom")
td = TdxData(cache_dir=None)
td.get_ticks = fake_ticks
with pytest.raises(ConnectionError):
await td.get_index_trade_stats(
"000016", members=["sh600000"], skip_errors=False)
@pytest.mark.asyncio
async def test_get_index_trade_stats_progress_callback():
seen: list[tuple[int, int]] = []
async def fake_ticks(symbols, date=None, concurrency=6, **kw):
return [_tick(s, "09:30", 10.0, 1.0, 1) for s in symbols]
td = TdxData(cache_dir=None)
td.get_ticks = fake_ticks
st = await td.get_index_trade_stats(
"000016", members=[f"sh60000{i}" for i in range(5)],
batch_size=2, on_progress=lambda d, t: seen.append((d, t)))
assert seen == [(2, 5), (4, 5), (5, 5)]
assert st.member_count == 5
@pytest.mark.asyncio
async def test_get_index_trade_stats_fetches_members_when_absent():
asked: list[str] = []
async def fake_members(code):
asked.append(code)
return [SimpleNamespace(symbol="sh600000")]
async def fake_ticks(symbols, date=None, concurrency=6, **kw):
return [_tick(s, "09:30", 10.0, 1.0, 1) for s in symbols]
td = TdxData(cache_dir=None)
td.get_index_members = fake_members
td.get_ticks = fake_ticks
await td.get_index_trade_stats("sh000300")
assert asked == ["000300"]
@pytest.mark.asyncio
async def test_get_index_trade_stats_rejects_empty_members():
td = TdxData(cache_dir=None)
async def fake_members(code):
return []
td.get_index_members = fake_members
with pytest.raises(ValueError, match="没有取到成分股"):
await td.get_index_trade_stats("000300")
@pytest.mark.asyncio
async def test_get_index_trade_stats_multi_reuses_members():
member_calls: list[str] = []
tick_dates: list[int | None] = []
async def fake_members(code):
member_calls.append(code)
return [SimpleNamespace(symbol="sh600000")]
async def fake_ticks(symbols, date=None, concurrency=6, **kw):
tick_dates.append(date)
return [_tick(s, "09:30", 10.0, 1.0, 2) for s in symbols]
td = TdxData(cache_dir=None)
td.get_index_members = fake_members
td.get_ticks = fake_ticks
out = await td.get_index_trade_stats_multi(
"000300", [20261020, 20261021, None])
assert len(out) == 3
assert member_calls == ["000300"] # 成分只取一次
assert tick_dates == [20261020, 20261021, None]
assert all(s.total_trade_count == 2 for s in out)
+168
View File
@@ -12,6 +12,7 @@ from pytdxdata.protocol.commands.ex_proto import GetExInstrumentBarsCmd
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.quotes import price_decimal_digits
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
@@ -181,6 +182,30 @@ def test_mac_transaction_parse():
assert recs[1].trade_count == 1
def test_mac_transaction_parse_negative_trade_count_auction():
"""集合竞价段 trade_count 是有符号 int32,负数不能被读成 42 亿(BUG 回归)。
实测(2026-10-21,sh600000 09:15:03):18 字节为
17820000 0ad71b41 d9000000 96fcffff 0800
最后四字节前的 96fcffff = int32 -874,旧解析按 uint32 得 4294966422。
"""
body = bytearray(39 + 2 * 18)
struct.pack_into("<H", body, 29, 2)
# 第1条:集合竞价,trade_count = -874
struct.pack_into("<IfIiH", body, 39, 33303, 9.74, 217, -874, 8)
# 第2条:正常交易,trade_count = 3
struct.pack_into("<IfIiH", body, 39 + 18, 34200, 9.75, 100, 3, 1)
cmd = MacTransactionCmd(1, "600000", 20261021, 0, 100)
recs = cmd.parse_response(bytes(body))
assert len(recs) == 2
assert recs[0].trade_count == -874, "负值必须保留符号,不能变成 4294966422"
assert recs[0].bs_flag == 8
assert recs[1].trade_count == 3
# 正常交易段的量级不受影响
assert max(r.trade_count for r in recs) == 3
# ---------- 跨时区时间戳归一化(美股 EX 通道) ----------
#
# 通达信 EX 通道对美股返回的时间戳把两个时区拼在一起:日期字段是**美东交易日**、
@@ -286,3 +311,146 @@ def test_finish_bars_sorts_us_session_chronologically():
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"}
# ---------- 报价小数位:沪市指数必须 2 位(回归:曾整体少 10 倍) ----------
@pytest.mark.parametrize("market,code,expect", [
# 沪市指数:回归 bug —— 曾被判 3 位,导致价格少 10 倍
(1, "000001", 2), # 上证指数
(1, "000016", 2), # 上证50
(1, "000300", 2), # 沪深300
(1, "000688", 2), # 科创50
(1, "880001", 2), # 板块指数(8 开头,曾被判 3 位)
(1, "880305", 2),
# 沪市 ETF/基金:仍是 3 位
(1, "510300", 3),
(1, "588000", 3),
(1, "511010", 3),
(1, "501018", 3),
# 沪市股票:2 位
(1, "600000", 2),
(1, "601398", 2),
(1, "688111", 2), # 科创板
# 深市
(0, "399001", 2), # 深证成指
(0, "399006", 2), # 创业板指
(0, "000001", 2), # 平安银行(不是指数!)
(0, "300750", 2),
(0, "159915", 3), # 深市 ETF
# 债券/回购:2026-10-22 修正(沪市曾少 100 倍、深市曾少 10 倍)
(1, "019742", 4), # 沪市国债 24特国01(110.228,曾读成 11022.8)
(1, "019547", 4), # 沪市国债
(1, "010706", 4), # 沪市老国债 07国债06
(1, "018014", 4), # 沪市 018 段
(1, "020812", 4), # 沪市贴债
(1, "110077", 4), # 沪市可转债 洪城转债(199.279,曾读成 19927.9)
(1, "113616", 4), # 沪市可转债 韦尔转债
(1, "118031", 4), # 沪市可转债
(1, "111000", 4), # 沪市 111 段
(1, "132024", 4), # 沪市可交换债
(1, "184832", 4), # 沪市 184 段
(1, "204001", 4), # 沪市国债逆回购 GC001(1.385,曾读成 138.5)
(1, "204028", 4),
(0, "123107", 4), # 深市可转债 温氏转债(112.189,曾读成 1121.89)
(0, "128136", 4), # 深市可转债 立讯转债
(0, "127025", 4), # 深市可转债
(0, "131810", 4), # 深市国债逆回购 R-001(1.38,曾读成 13.8)
(0, "148004", 4), # 深市 148 段
(0, "112001", 4), # 深市公司债
(0, "101917", 4), # 深市国债
(0, "520261", 4), # 深市 520 段
# 沪市 B 股:3 位(2026-10-22 修正,曾按 2 位少 10 倍)
(1, "900901", 3), # 云赛B股
(1, "900948", 3),
# 深市 B 股:2 位(与沪市不同!)
(0, "200011", 2), # 深物业B
(0, "200488", 2),
# 边界:999xxx 是「指数」,不能被 9 开头当成 B 股
(1, "999999", 2), # 上证指数
(1, "999998", 2), # A股指数
])
def test_price_decimal_digits(market, code, expect):
assert price_decimal_digits(market, code) == expect
def test_price_decimal_digits_strips_nul():
assert price_decimal_digits(1, "000016\x00\x00") == 2
# ---------- 美股分时跨日:hour 必须是合法时钟值(回归:曾出现 hour=27) ----------
def _us_minutes(n: int = 390) -> list:
"""构造 usAAPL 的 390 条分时:从北京 21:30 起连续 n 分钟。"""
from pytdxdata.models import MinuteBar
start = 21 * 60 + 30
return [
MinuteBar(price=100.0 + i * 0.01, vol=1.0,
hour=(start + i) // 60, minute=(start + i) % 60,
market=74, code="AAPL", date=20261022)
for i in range(n)
]
def test_minute_bar_us_hour_is_valid_clock_value():
"""EX 分时的 minutes 是「自开盘起的连续分钟数」,直接 //60 会得到 hour=27。"""
bars = _us_minutes()
assert all(0 <= b.hour < 24 for b in bars)
# 归一化前的原始值确实越界(21:30 + 390min = 28:00)
assert max(b.hour + b.day_offset * 24 for b in bars) > 23
def test_minute_bar_us_day_offset_marks_next_day():
bars = _us_minutes()
assert bars[0].day_offset == 0 # 21:30 当晚
assert bars[-1].day_offset == 1 # 03:59 次日
assert (bars[-1].hour, bars[-1].minute) == (3, 59)
def test_minute_bar_us_datetime_is_monotonic_across_midnight():
bars = _us_minutes()
dts = [b.datetime for b in bars]
assert dts == sorted(dts)
assert dts[0] == datetime(2026, 10, 22, 21, 30)
assert dts[-1] == datetime(2026, 10, 23, 3, 59)
def test_minute_bar_us_trading_date_spans_two_calendar_days():
"""一个美股交易日的分时横跨两个北京自然日,trading_date 必须都是同一天。"""
bars = _us_minutes()
tds = {b.trading_date for b in bars}
assert tds == {"2026-10-22"}
# 而 datetime.date() 会给出两天 —— 这正是不能用它的原因
assert len({b.datetime.date() for b in bars}) == 2
def test_minute_bar_cn_unchanged():
"""A股/港股分时 hour 本就合法,归一化必须零行为变化。"""
from pytdxdata.models import MinuteBar
for hour, minute in ((9, 30), (11, 29), (13, 0), (14, 59)):
b = MinuteBar(price=10.0, vol=1.0, hour=hour, minute=minute,
market=1, code="600000", date=20261022)
assert (b.hour, b.minute) == (hour, minute)
assert b.day_offset == 0
assert b.datetime == datetime(2026, 10, 22, hour, minute)
assert b.trading_date == "2026-10-22"
def test_minute_bar_cn_datetime_monotonic_full_session():
"""A股全天 240 条(09:30~11:29 + 13:00~14:59)时间轴严格递增。"""
from pytdxdata.models import MinuteBar
bars = []
for idx in range(240):
if idx < 120:
hour, minute = 9 + (30 + idx) // 60, (30 + idx) % 60
else:
hour, minute = 13 + (idx - 120) // 60, (idx - 120) % 60
bars.append(MinuteBar(price=10.0, vol=1.0, hour=hour, minute=minute,
market=1, code="600000", date=20261022))
dts = [b.datetime for b in bars]
assert dts == sorted(dts)
assert dts[0] == datetime(2026, 10, 22, 9, 30)
assert dts[-1] == datetime(2026, 10, 22, 14, 59)
assert {b.trading_date for b in bars} == {"2026-10-22"}
Generated
+1 -1
View File
@@ -535,7 +535,7 @@ wheels = [
[[package]]
name = "pytdxdata"
version = "0.6.2"
version = "0.6.6"
source = { editable = "." }
[package.optional-dependencies]