* 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>
176 lines
6.7 KiB
Python
176 lines
6.7 KiB
Python
"""EX 0x23FF K线的字段语义:``amount`` / ``settle`` 按市场分别回填。
|
||
|
||
背景(2026-10-28 实测):0x23FF 每条 32B = 4B 时间戳 + **28B 行情**,这 28B 只有
|
||
**一个** 4B 槽位可复用,语义随市场变化 ——
|
||
|
||
* 权益类(港股主板/创业板/基金、新三板、美股):该槽位是**成交额**,
|
||
校验 ``成交额 / (close × vol)`` ≈ 100(港股主板/基金,vol 单位是手)或 ≈ 1(其余,vol 是股);
|
||
* 期货期权类:该槽位是**结算价**,成交额在帧内根本不存在(恒 0.0)。
|
||
|
||
改之前 ``amount`` 被硬编码成 0.0、末位 float 直接丢弃,于是港股/美股拿不到成交额、
|
||
期货期权拿不到结算价。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import pickle
|
||
import struct
|
||
|
||
import pytest
|
||
|
||
from pytdxdata.api import TdxData
|
||
from pytdxdata.models import SecurityBar
|
||
from pytdxdata.protocol.commands.ex_proto import (
|
||
_EX_AMOUNT_MARKETS,
|
||
GetExInstrumentBarsCmd,
|
||
)
|
||
from pytdxdata.symbols import parse_symbols
|
||
|
||
DAY = 20261028
|
||
|
||
|
||
def _f2u(value: float) -> int:
|
||
"""float32 -> 其位模式的 uint32(用来拼「同一槽位两种解释」的报文)。"""
|
||
return struct.unpack("<I", struct.pack("<f", value))[0]
|
||
|
||
|
||
def _ex_body(rows: list[tuple[int, ...]], category: int = 4) -> bytes:
|
||
"""拼 0x23FF 响应体:20B 头(count@18)+ N × 32B(时间4B + 7×4B)。"""
|
||
body = bytearray(20 + 32 * len(rows))
|
||
struct.pack_into("<H", body, 18, len(rows))
|
||
for i, words in enumerate(rows):
|
||
off = 20 + i * 32
|
||
struct.pack_into("<I", body, off, DAY)
|
||
struct.pack_into("<7I", body, off + 4, *words)
|
||
return bytes(body)
|
||
|
||
|
||
def _equity_words(close: float, amount: float, vol: int) -> tuple[int, ...]:
|
||
"""权益类布局:OHLC + 成交额(float) + 成交量(uint) + 保留(float)。"""
|
||
return (_f2u(close), _f2u(close), _f2u(close), _f2u(close),
|
||
_f2u(amount), vol, _f2u(0.0))
|
||
|
||
|
||
def _derivative_words(close: float, position: int, vol: int,
|
||
settle: float) -> tuple[int, ...]:
|
||
"""期货/期权布局:OHLC + 持仓量(uint) + 成交量(uint) + 结算价(float)。"""
|
||
return (_f2u(close), _f2u(close), _f2u(close), _f2u(close),
|
||
position, vol, _f2u(settle))
|
||
|
||
|
||
# ---------- 解析层 ----------
|
||
|
||
@pytest.mark.parametrize("market", [31, 48, 49, 44, 74])
|
||
def test_equity_markets_read_amount_from_fifth_slot(market: int) -> None:
|
||
cmd = GetExInstrumentBarsCmd(market, "00700", 4, 0, 1)
|
||
rows = cmd.parse_response(_ex_body([_equity_words(10.2, 2_040_000.0, 2000)]))
|
||
|
||
assert len(rows) == 1
|
||
assert rows[0]["amount"] == pytest.approx(2_040_000.0)
|
||
assert rows[0]["trade"] == 2000 # 成交量不受影响
|
||
assert rows[0]["position"] == 0 # 权益类无持仓量概念
|
||
assert rows[0]["settle"] is None
|
||
|
||
|
||
@pytest.mark.parametrize("market", [7, 8, 9, 47])
|
||
def test_derivative_markets_read_settle_from_seventh_slot(market: int) -> None:
|
||
cmd = GetExInstrumentBarsCmd(market, "IFL0", 4, 0, 1)
|
||
rows = cmd.parse_response(_ex_body([_derivative_words(4021.0, 49_772, 25_392, 4047.8)]))
|
||
|
||
assert rows[0]["amount"] == 0.0 # 帧内没有成交额,不是解析漏读
|
||
assert rows[0]["position"] == 49_772
|
||
assert rows[0]["trade"] == 25_392
|
||
assert rows[0]["settle"] == pytest.approx(4047.8)
|
||
|
||
|
||
def test_intraday_settle_zero_normalized_to_none() -> None:
|
||
"""结算价是日终量:分钟线该槽位恒 0,归一化成 None 而不是 0.0。"""
|
||
cmd = GetExInstrumentBarsCmd(47, "IFL0", 7, 0, 1)
|
||
rows = cmd.parse_response(_ex_body([_derivative_words(4054.6, 49_490, 260, 0.0)], 7))
|
||
|
||
assert rows[0]["settle"] is None
|
||
|
||
|
||
def test_index_markets_kept_out_of_amount_table() -> None:
|
||
"""港股指数(27)/中证指数(62) 该槽位既非成交额也非结算价 —— 不能猜,保持 0.0。"""
|
||
assert 27 not in _EX_AMOUNT_MARKETS
|
||
assert 62 not in _EX_AMOUNT_MARKETS
|
||
cmd = GetExInstrumentBarsCmd(27, "HSI", 4, 0, 1)
|
||
rows = cmd.parse_response(_ex_body([_equity_words(23041.32, 178_348.0, 17_835)]))
|
||
assert rows[0]["amount"] == 0.0
|
||
|
||
|
||
# ---------- API 层透传 ----------
|
||
|
||
def _fake_api(rows_for: dict[int, list[dict]]) -> TdxData:
|
||
td = TdxData(cache_dir=None, pool_min=1, pool_max=2)
|
||
seen: list[tuple[int, str]] = []
|
||
|
||
async def fake(make_cmd, spec): # noqa: ANN001 — 与真实签名同形
|
||
cmd = make_cmd(0, spec.page_size)
|
||
seen.append((cmd.market, cmd.code))
|
||
return rows_for[cmd.market]
|
||
|
||
td._fetch_paginated_ex = fake # type: ignore[method-assign]
|
||
td._seen_ex = seen # type: ignore[attr-defined]
|
||
return td
|
||
|
||
|
||
def _row(market: int, code: str, **kw) -> dict:
|
||
base = {"year": 2026, "month": 10, "day": 28, "hour": 15, "minute": 0,
|
||
"open": 10.0, "high": 10.5, "low": 9.5, "close": 10.2,
|
||
"amount": 0.0, "position": 0, "trade": 2000, "settle": None}
|
||
base.update(kw)
|
||
return base
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_bars_ex_backfills_amount_for_hk() -> None:
|
||
td = _fake_api({31: [_row(31, "00700", amount=2_040_000.0)]})
|
||
bars = await td.get_bars("hk00700", count=1)
|
||
|
||
assert len(bars) == 1
|
||
assert bars[0].amount == pytest.approx(2_040_000.0)
|
||
assert bars[0].vol == 2000
|
||
assert bars[0].settle is None
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_bars_ex_backfills_settle_for_futures() -> None:
|
||
td = _fake_api({47: [_row(47, "IFL0", position=49_772, trade=25_392, settle=4047.8)]})
|
||
bars = await td.get_bars("cffex_futures:IFL0", count=1)
|
||
|
||
assert bars[0].settle == pytest.approx(4047.8)
|
||
assert bars[0].amount == 0.0
|
||
|
||
|
||
# ---------- 旧磁盘缓存兼容 ----------
|
||
|
||
def test_legacy_pickle_without_settle_still_loads() -> None:
|
||
"""升级前写下的缓存没有 settle 槽位;默认反序列化不会补默认值,读它必崩。"""
|
||
bar = SecurityBar(market=1, code="600000", open=1.0, high=2.0, low=0.5,
|
||
close=1.5, vol=100.0, amount=150.0,
|
||
year=2026, month=10, day=28, settle=12.3)
|
||
_, slots = bar.__getstate__()
|
||
legacy = dict(slots)
|
||
legacy.pop("settle")
|
||
|
||
revived = SecurityBar.__new__(SecurityBar)
|
||
revived.__setstate__((None, legacy))
|
||
|
||
assert revived.settle is None
|
||
assert revived.close == 1.5
|
||
|
||
|
||
def test_new_pickle_roundtrip_keeps_settle() -> None:
|
||
bar = SecurityBar(market=47, code="IFL0", open=4021.0, high=4060.0, low=4010.0,
|
||
close=4054.6, vol=25_618.0, amount=0.0,
|
||
year=2026, month=10, day=28, settle=4052.6)
|
||
|
||
assert pickle.loads(pickle.dumps(bar)).settle == pytest.approx(4052.6)
|
||
|
||
|
||
def test_ex_symbols_route_to_ex_path() -> None:
|
||
"""守住前提:上面对 31/47 的断言确实走的是 EX 通道。"""
|
||
assert parse_symbols(["hk00700"])[0].is_ex
|
||
assert parse_symbols(["cffex_futures:IFL0"])[0].is_ex
|