1 Commits
Author SHA1 Message Date
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
33 changed files with 2789 additions and 1270 deletions

No files matched your search

+65 -1
View File
@@ -2,6 +2,69 @@
本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/)。 本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
## [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 +160,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
+10 -9
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())
@@ -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/ # 127 个测试用例(协议 / 池 / 缓存 / 分页 / 全接口回归 / 文件解析 / CLI / 文档漂移)
uv sync --group docs # 文档站依赖(mkdocs-material + mkdocstrings) uv sync --group docs # 文档站依赖(mkdocs-material + mkdocstrings)
uv run mkdocs serve # 本地预览文档站 uv run mkdocs serve # 本地预览文档站
``` ```
+49 -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,9 @@ 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)` 自动切换。
- **`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,14 +173,16 @@ 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 但无五档 |
| 依赖实时性做信号 | 数据是 15 分钟前的 | 换券商实时源 | | 依赖实时性做信号 | 数据是 15 分钟前的 | 换券商实时源 |
## 深入参考 ## 深入参考
+61 -17
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 取缩略采样) |
#### 公司信息/文件/板块
| 方法 | 返回 | 说明 |
|------|------|------|
| `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,16 +93,16 @@ 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}
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
@@ -68,7 +111,7 @@ from pytdxdata import (
| `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 0x254D) |
### 2.4 证券列表(共 3 个) ### 2.5 证券列表(旧接口,共 3 个) {#legacy-list}
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
@@ -76,13 +119,13 @@ 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` | 板块文件**原始字节**(先查元数据再分块下载) |
@@ -99,7 +142,7 @@ from pytdxdata import (
> 解析层独立于网络层:解析器位于 `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`)
+10 -9
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,10 +38,11 @@ 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")) # 统一接口只接受字符串标的,不接受元组
df = bars.to_dataframe() # 返回值是 list[dataclass],没有这个方法 td.get_bars("sh600000") # 忘了 await,且没在 async with 内
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)。
## 关键细节 ## 关键细节
+9 -5
View File
@@ -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 万条) |
## 下一步 ## 下一步
+11 -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` |
+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())
+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/>。
+30 -33
View File
@@ -6,7 +6,7 @@
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
``` ```
## 全市场日线批量落库 ## 全市场日线批量落库
@@ -16,23 +16,22 @@ from pytdxdata.models import Adjust, ExMarket, KlinePeriod, Market
```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,12 +112,10 @@ 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*.zip`,含多报告期)走文件接口:
@@ -173,14 +170,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 +188,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 +216,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]
``` ```
+4 -3
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())
@@ -35,7 +35,7 @@ asyncio.run(main())
| ⚡ **并发分页** | 把大请求拆成显式 `start` 偏移的页,多连接并行拉取、按序拼接、失败换连接重试 | | ⚡ **并发分页** | 把大请求拆成显式 `start` 偏移的页,多连接并行拉取、按序拼接、失败换连接重试 |
| 🔀 **双通道整合** | 标准通道(经典行情)+ MAC 通道(逐笔 / 复权 / 1分钟K线),按命令自动选路 | | 🔀 **双通道整合** | 标准通道(经典行情)+ MAC 通道(逐笔 / 复权 / 1分钟K线),按命令自动选路 |
| 📄 **服务器文件解析** | 板块 `block_*.dat` / 行业 `tdxhy.cfg` / 历史财报 `gpcw*.zip` **下载即解析**成 dataclass(纯 stdlib),无需自己拆二进制 | | 📄 **服务器文件解析** | 板块 `block_*.dat` / 行业 `tdxhy.cfg` / 历史财报 `gpcw*.zip` **下载即解析**成 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)
@@ -138,6 +138,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>
+5 -4
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,6 +21,7 @@ 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 # 服务器清单加载(servers.json)
├── indicator.py # 技术指标(纯函数,无依赖) ├── indicator.py # 技术指标(纯函数,无依赖)
@@ -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 移除),老代码在兼容窗口内仍可用 |
## 下一步 ## 下一步
+1 -1
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)
]) ])
``` ```
+4 -6
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}
@@ -66,13 +66,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)。
## 下一步 ## 下一步
+24 -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,24 @@ 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。
## CLI ## CLI
@@ -102,6 +108,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**。其中 `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.0"
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.0"
__all__ = [ __all__ = [
"TdxData", "TdxData",
"Market", "Market",
+1318 -925
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))
+50 -7
View File
@@ -94,7 +94,7 @@ class Adjust(IntEnum):
@dataclass(slots=True) @dataclass(slots=True)
class SecurityBar: class SecurityBar:
"""K线记录(价格单位:元)""" """K线记录(价格单位:元)。跨市场统一模型(A股/港股/美股/期货共用)。"""
market: int market: int
code: str code: str
open: float open: float
@@ -108,6 +108,7 @@ class SecurityBar:
day: int day: int
hour: int = 0 hour: int = 0
minute: int = 0 minute: int = 0
symbol: str = "" # 规范化标的串(sz000001 / hk00700),由 API 层填充
@property @property
def datetime(self) -> datetime: def datetime(self) -> datetime:
@@ -120,9 +121,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 +162,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 +231,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 +279,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 +300,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 +325,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 +335,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 +348,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 +369,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 +403,7 @@ class CapitalFlow:
sell5: float sell5: float
big5: float big5: float
mid5: float mid5: float
symbol: str = ""
# ===== 服务器文件解析模型(板块/行业/历史专业财报) ===== # ===== 服务器文件解析模型(板块/行业/历史专业财报) =====
+8 -3
View File
@@ -211,6 +211,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 +248,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
+35 -23
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,22 +73,27 @@ 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:
await self.pool.release(pc) if s.pc is not None:
pc, s.pc = s.pc, None
await self.pool.release(pc)
return self._assemble(out, spec.ordered) return self._assemble(out, spec.ordered)
def _plan_starts(self, spec: PageSpec) -> list[tuple[int, int]]: def _plan_starts(self, spec: PageSpec) -> list[tuple[int, int]]:
@@ -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:
+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))
)
+597
View File
@@ -0,0 +1,597 @@
"""全接口回归: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=10.0, vol=100.0, hour=9, minute=30)]
if n == "SymbolTickChartCmd":
return [{"minutes": 570, "price": 10.0, "vol": 100.0, "avg": 10.0,
"momentum": 0.1}]
if n == "MacChartSamplingCmd":
return [10.0, 10.1, 10.2]
# ---- 公司信息 ----
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()
# --------------------------------------------------------------------------- #
# 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.get_probe_cache",
return_value=mock.MagicMock(ensure_probe=mock.AsyncMock())):
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
# --------------------------------------------------------------------------- #
# 七、废弃别名(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"]
assert await td.get_financial_records("tdxfin/gpcw.txt") == b"abcd"
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") == [10.0, 10.1, 10.2]
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}"
+7 -7
View File
@@ -252,7 +252,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 +263,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 +274,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 +284,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 +294,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 +303,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 +313,7 @@ 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
Generated
+1 -1
View File
@@ -535,7 +535,7 @@ wheels = [
[[package]] [[package]]
name = "pytdxdata" name = "pytdxdata"
version = "0.5.0" version = "0.6.0"
source = { editable = "." } source = { editable = "." }
[package.optional-dependencies] [package.optional-dependencies]