feat: DataFrame 直出(df="polars"/"pandas")+ 0.7.0 (#12)

* feat: DataFrame 直出(df="polars"/"pandas")+ 版本 0.7.0

TdxData 新增构造参数 df:
- None(默认)→ 行为与 0.6.x 完全一致,返回 list[dataclass]
- "polars"/"pandas" → 42 个表格型接口直接返回 DataFrame

转换层 src/pytdxdata/frames.py:
- 列计划按模型缓存,列式采集(不做逐行 asdict)
- 时间列替换:year/month/day/hour/minute → datetime + trading_date;Xdxr 给 date
- 嵌套定型:bid/ask 展开 10 列、fields 字典 JSON 化、codes 保持列表
- 容器展开:get_indicators 合并指标、get_index_trade_stats 展开 minutes、
  get_kline_batch/get_minute_batch 纵向拼接
- ContextVar 层次标记:批量/别名方法内层不二次转换,并发互不干扰
- 后端惰性加载:缺包抛 FrameBackendError(带安装命令),构造时即失败

依赖:新增 extras pandas/polars/dataframe,核心包仍零依赖;dev 组加 pandas+polars
测试:tests/test_frames.py 40 项(双后端×双格式);全量 401 项通过
文档:新增 docs/dataframe.md,同步 API_REFERENCE/SKILL/llms.txt/README/mkdocs

* perf(kline): 按日期取K线贴最新时走倒推,1分钟 4.2s → 82ms

问题:start_date/end_date 一律走「探总根数 + 二分定位」。1 分钟 K 线历史
二十万根量级 = 6 次翻倍探测 + 2 次方向探测 + 两次各 ~18 次跳转,共 36+ 次
串行往返。「取今天」这个最常见的调用要 4.2 秒。

改法(_bars_backtrack 快路径):
- 右端离最新不超过 _BACKTRACK_GRACE(10 天) 时,直接 start=0, count=N
  拿最新 N 根再裁剪;N 按时间跨度估(_BARS_PER_DAY),一天内一次命中,
  不够才翻倍,放大到 _BACKTRACK_MAX_BARS 仍不够则回落二分
- 历史中段仍走二分,结果口径完全一致(已逐条比对基准)

两个关键细节:
- 偏移方向是通道级属性而非标的属性,首次探测后缓存在实例上
  (_kline_dir_cache)——全市场 5,225 只批量只付一次探测成本
- K线 hour/minute 是周期**结束**时刻,最新一根可能比 now() 略大(14:29
  那根还在走),「右端贴最新」必须留周期容差,否则 end_date=now() 被误判
  成历史中段

实测(1 分钟,冷启动):
  取今天        4,208ms → 82ms
  2天前~now     2,211ms → 75ms
  最近3天       2,000ms+ → 239ms
  历史中段      1,512ms → 285ms
  全市场5225只取今天 32.1s(1,140,699 根,精确当天口径)

注:route_for 让 MIN_1 一律走 MAC(0x122E),所以按通道做方向缓存而不是按
「标准/扩展」写死分支。

测试:新增 tests/test_kline_date.py 6 项(倒推次数上界、结束时刻容差、
中段回落二分、未来区间、反向通道、与 count 路径口径一致);全量 407 项通过

* perf(kline): 全市场1分钟K线改多连接流水线抓取(43.6s → 5~7s,盘中 2s)

瓶颈其实是**往返次数**不是带宽:单只K线一请求一标的,串行 33ms/只 ≈ 1 个 RTT。
同一台服务器 16 连接 × 深度 8 实测能跑 5.2 MB/s(此前「单 IP 限流 1.5MB/s」
是浅流水下的假象)。

- get_bars 新增 pipeline 参数(None=按单请求字节自适应 8~32,1=关闭走逐只)
- 多标的(≥16 只)走 _bulk_bars:多连接 work-stealing + 单连接 execute_pipeline
- 只用实测最快的 12 台:池里 24 台全用反而被慢节点拖长尾
- 盘中按交易时段只拉已走过的根数(10:00 → 35 根,数据量差 7 倍)
- 标准通道(日线不复权)同样走批量:全市场 49~72s → 13s
- 修 pipeline 失败时队列剩余标的静默丢失(实测 20 只只回 16 只)
- 修 test_future_range_returns_empty_quickly 时间炸弹(固定日期会漂进 _BACKTRACK_GRACE)
- conftest 关闭后台测速 task,避免污染「往返次数」类断言

实测(5,225 只):count=2 → 2.7s;count=35 → 2.2s;count=240 → 6.9s。
逐根一致性 30/30 相同。新增 tests/test_bulk_kline.py 12 项,合计 419 项全绿。

* test: 批量K线测试的时间锚点改用真实 now(CI 是 UTC,固定日期会漂到别的时段分支)

* fix(ex): EX 通道 K 线回填成交额与结算价(0x23FF 槽位按市场分两类)

报告:EX 通道 get_bars 返回的 SecurityBar.amount 恒为 0.0。
定位属实,但实际情况比报告更细 —— 32B 记录里那 28B 行情只有**一个** 4B 槽位
可复用,语义按市场分两类(全市场实测,用 成交额/(close×vol) 逐条校验):

| 市场 | 槽位5 | 槽位6 | 槽位7 |
|---|---|---|---|
| 港股主板31/港股基金49 | 成交额(f) | 量(手=100股) | 未知 |
| 港股创业板48/新三板44/美股74 | 成交额(f) | 量(股) | 0 |
| 期货/期权 7/8/9/47… | 持仓量(I) | 量 | 结算价(f) |

改前 amount 硬编码 0.0、第 7 个 float 用 `_` 丢弃 —— 于是港股/美股/新三板
明明帧内有成交额却全为 0,期货期权的结算价也拿不到。

- 新增 SecurityBar.settle(结算价,float|None):仅 EX 期货/期权日线有值,
  分钟线该槽位恒 0 已归一化为 None,其它通道恒 None。
- 权益类市场回填真实 amount;港股主板/基金的 vol 单位是手(=100股),
  amount/vol 是均价的 100 倍,已写进模型注释与量纲表。
- 期货/期权的 amount 仍是 0.0(帧内确实没有成交额,协议限制),
  已在 SecurityBar / API_REFERENCE / llms.txt / SKILL.md 写清,
  避免使用者再按旧文档判断成调用方 bug。
- 港股指数27/中证指数62 该槽位量级对不上(既非额也非结算价),保守保持 0.0。
- SecurityBar.__setstate__ 兜底旧磁盘缓存:缓存键无 schema 版本,升级后读旧
  pickle 缺 settle 槽位,默认反序列化不补默认值 → AttributeError,已容错;
  EX K 线缓存键额外加 @v2,让 amount 恒 0 的旧缓存自然失效。
- K 线 DataFrame 因此多一列 settle(0.7.0 未发布,列清单同步更新)。

测试:tests/test_ex_bars_fields.py 16 项(解析层双布局、日内 settle 归零、
API 透传、旧 pickle 兼容);全套 435 项通过。

* docs: 0.7.0 全站口径同步(DataFrame 出口 + EX 成交额限制 + 构造参数表)

- 首页:特性表补「DataFrame 直出」与 K 线批量性能,导航新增 DataFrame 卡片,
  统一方法数按实测修正为 35(+33 别名 = 68 个公开方法)
- 安装页:补 extras(polars/pandas/dataframe)与 df 用法;构造参数表补
  df / std_pool_cap / ex_pool_cap,并把 pool_max 默认值从 12 修正为 24(实际值)
- 场景示例:`转成 pandas` 一节改为先推 df= 开关,手动转换降级为局部场景
- 数据模型页:不再说「刻意不提供 DataFrame」,改为 dataclass 与 DataFrame
  是同一份数据、两种容器
- AI 接入页:返回值约定补 `df=` 开关的说法
- README:K 线列注释补 settle;已知限制补 EX 通道成交额/结算价的协议口径
- CHANGELOG:新增「升级」小节(升级命令、旧缓存无需清理)

---------

Co-authored-by: openbot-coder <openbot-coder@users.noreply.github.com>
This commit is contained in:
openbotandopenbot-coder authored and GitHub committed 2026-10-28 18:22:13 +08:00
1 parent 2cf3657f4b
commit 04e0c57569
24 files changed
+3022 -496

No files matched your search

+234
View File
@@ -0,0 +1,234 @@
"""K线批量流水线路径(多连接 × 单连接流水线)。
背景:单只K线一请求一标的,全市场 5,000 只就是 5,000 次往返。串行时每只固定付
一个 RTT(实测 33ms),实测 24 台 × 8 流水能把全市场 1 分钟K线取当天从 43.6s
压到 5s 级。这里用替身验证「路径选择」与「结果口径」,不依赖网络。
"""
from __future__ import annotations
import datetime
import pytest
from pytdxdata import TdxData
from pytdxdata.api import _auto_pipeline, _bars_for_range, _elapsed_trading_minutes
from pytdxdata.models import KlinePeriod, SecurityBar
# 替身的时间锚点必须跟着**真实 now** 走:API 内部用 ``datetime.now()`` 判断「是不是今天」,
# 用固定日期会在 CI(UTC 时区,与本地差 8 小时)上漂到别的时段分支,断言时绿时红。
NEWEST = datetime.datetime.now().replace(microsecond=0) # noqa: DTZ001
def _bar(when: datetime.datetime, close: float = 10.0) -> SecurityBar:
return SecurityBar(
market=1, code="600000", open=10.0, high=10.1, low=9.9, close=close,
vol=1000, amount=10000, year=when.year, month=when.month, day=when.day,
hour=when.hour, minute=when.minute)
class _MacFakeConn:
"""MAC 通道语义替身:**offset 0 = 最新一根**,偏移越大越老。"""
seen: list[tuple[str, int, int, bool]] = [] # (命令名, start, count, 是否流水线)
fail_pipeline = False
def __init__(self, host="m1", port=7709, timeout=10.0):
self.host = host
self._alive = True
@property
def alive(self) -> bool:
return self._alive
async def connect(self) -> None:
pass
async def close(self) -> None:
self._alive = False
def _rows(self, cmd, *, record: bool = True):
if record:
type(self).seen.append(
(type(cmd).__name__, getattr(cmd, "start", 0),
getattr(cmd, "count", 0), False))
if "MacKlineCmd" not in type(cmd).__name__:
return []
out = []
for off in range(cmd.start, cmd.start + cmd.count):
if off > 20_000:
continue
when = NEWEST - datetime.timedelta(minutes=off)
out.append(_bar(when, 10.0 + (20_000 - off) * 0.001))
return out
async def execute(self, cmd):
return self._rows(cmd)
async def execute_pipeline(self, cmds, **kwargs):
if type(self).fail_pipeline:
raise ConnectionError("流水线炸了")
for c in cmds:
type(self).seen.append(
(type(c).__name__, getattr(c, "start", 0), getattr(c, "count", 0), True))
return [self._rows(c, record=False) for c in cmds]
def _syms(n: int) -> list[str]:
"""n 只沪市股票代码(互不相同,避免按 symbol 归并时互相覆盖)。"""
return [f"sh60{i:04d}" for i in range(n)]
async def _run(n: int, period=KlinePeriod.MIN_1, **kw):
_MacFakeConn.seen = []
_MacFakeConn.fail_pipeline = False
with pytest.MonkeyPatch.context() as mp:
mp.setattr("pytdxdata.api.get_mac_hosts", lambda: ["m1", "m2"])
mp.setattr("pytdxdata.pool.pool.TdxConnection",
lambda h, p=7709, t=10.0: _MacFakeConn(h))
td = TdxData(cache_dir=None, pool_min=1, pool_max=4)
await td.start()
try:
bars = await td.get_bars(_syms(n), period, **kw)
finally:
await td.close()
return bars
def _data_calls() -> list[tuple[str, int, int, bool]]:
"""只看真正的数据请求(排除建连探针:count=100 那条)。"""
return [c for c in _MacFakeConn.seen if c[2] != 100]
@pytest.mark.asyncio
async def test_bulk_path_uses_pipeline_for_many_symbols():
bars = await _run(20, count=240)
data = _data_calls()
assert data, "应该有数据请求"
assert all(via_pipe for *_, via_pipe in data), "20 只必须走流水线"
assert len(data) == 20
assert len(bars) == 20 * 240
@pytest.mark.asyncio
async def test_small_batch_falls_back_to_single():
"""低于阈值走逐只:不经过流水线,结果不变。"""
bars = await _run(5, count=240)
data = _data_calls()
assert data and not any(via_pipe for *_, via_pipe in data)
assert len(bars) == 5 * 240
@pytest.mark.asyncio
async def test_pipeline_1_disables_bulk():
bars = await _run(20, count=240, pipeline=1)
data = _data_calls()
assert data and not any(via_pipe for *_, via_pipe in data)
assert len(bars) == 20 * 240
@pytest.mark.asyncio
async def test_result_order_follows_input_order():
"""返回按入参标的顺序拼接(组内升序)。"""
bars = await _run(20, count=30)
seen: list[str] = []
for b in bars:
if not seen or seen[-1] != b.symbol:
seen.append(b.symbol)
assert seen == _syms(20)
# 组内按时间正序
head = [b.datetime for b in bars if b.symbol == _syms(20)[0]]
assert head == sorted(head)
@pytest.mark.asyncio
async def test_long_count_is_paged_inside_pipeline():
"""count 超过单请求上限时按页切分,且页也走流水线(不是逐只串行翻页)。"""
bars = await _run(20, count=1600, pipeline=8)
data = _data_calls()
assert all(via_pipe for *_, via_pipe in data)
assert len(data) == 20 * 3 # 700 + 700 + 200
assert {c[2] for c in data} == {700, 200}
assert len(bars) == 20 * 1600
@pytest.mark.asyncio
async def test_pipeline_failure_falls_back_to_single_per_symbol():
"""流水线失败 → 该批交回逐只重试,结果不丢。"""
_MacFakeConn.seen = []
_MacFakeConn.fail_pipeline = True
with pytest.MonkeyPatch.context() as mp:
mp.setattr("pytdxdata.api.get_mac_hosts", lambda: ["m1", "m2"])
mp.setattr("pytdxdata.pool.pool.TdxConnection",
lambda h, p=7709, t=10.0: _MacFakeConn(h))
td = TdxData(cache_dir=None, pool_min=1, pool_max=4)
await td.start()
try:
bars = await td.get_bars(_syms(20), KlinePeriod.MIN_1, count=240)
finally:
await td.close()
assert len(bars) == 20 * 240
@pytest.mark.asyncio
async def test_dated_range_bulk_trims_to_start_date():
"""日期区间走批量时,区间左端仍然精确裁剪。"""
start = NEWEST - datetime.timedelta(minutes=30)
bars = await _run(20, start_date=start)
assert bars
assert all(b.datetime >= start for b in bars)
assert all(b.symbol in set(_syms(20)) for b in bars)
@pytest.mark.asyncio
async def test_dated_future_range_returns_empty_without_requests():
future = NEWEST + datetime.timedelta(days=5)
bars = await _run(20, start_date=future)
assert bars == []
# ---------------- 纯函数 ----------------
def test_elapsed_trading_minutes():
def at(h, m):
return datetime.datetime(2026, 10, 28, h, m) # noqa: DTZ001
assert _elapsed_trading_minutes(at(9, 0)) == 0
assert _elapsed_trading_minutes(at(9, 30)) == 0
assert _elapsed_trading_minutes(at(10, 0)) == 30
assert _elapsed_trading_minutes(at(11, 45)) == 120 # 午休
assert _elapsed_trading_minutes(at(13, 30)) == 150
assert _elapsed_trading_minutes(at(15, 0)) == 240
assert _elapsed_trading_minutes(at(20, 0)) == 240 # 收盘后
def test_bars_for_range_shrinks_intraday():
"""盘中只需已走完的根数,不是一整天 240 根。"""
morning = datetime.datetime(2026, 10, 28, 10, 0) # noqa: DTZ001
midnight = datetime.datetime(2026, 10, 28, 0, 0) # noqa: DTZ001
# 10:00 走了 30 分钟 → 30 + 余量,远小于 240
assert 30 <= _bars_for_range(KlinePeriod.MIN_1, midnight, morning) <= 40
# 收盘后回到一整天的量级
close = datetime.datetime(2026, 10, 28, 16, 0) # noqa: DTZ001
assert _bars_for_range(KlinePeriod.MIN_1, midnight, close) >= 245
def test_bars_for_range_past_days():
now = datetime.datetime(2026, 10, 28, 16, 0) # noqa: DTZ001
start = now - datetime.timedelta(days=5)
n = _bars_for_range(KlinePeriod.DAY, start, now)
assert 5 <= n <= 12 # 5 个自然日 × 1.6 余量
def test_auto_pipeline():
# 每根 32B:小 count 用深流水,大 count 用浅流水(在途字节数恒定)
assert _auto_pipeline(2, None) == 32
assert _auto_pipeline(240, None) == 8
assert _auto_pipeline(240, 4) == 4 # 显式指定优先
assert _auto_pipeline(2, 1) == 2 # 夹到最小值 2