feat: 价格小数位改用协议权威值(SecurityInfo.decimal_point) (#7)

0.6.5 用「代码前缀推断 + 全量清单离线校验」修好了债券/回购标度,但同一份证券
清单接口本来就返回 decimal_point,权威值一直没接进取数路径。本次接进来:

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

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

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

Co-authored-by: openbot-coder <openbot-coder@users.noreply.github.com>
This commit is contained in:
openbotandopenbot-coder authored and GitHub committed 2026-10-22 16:25:09 +08:00
1 parent b84a6c8a1b
commit 76644919de
13 files changed
+723 -23

No files matched your search

+1 -1
View File
@@ -18,7 +18,7 @@ from .models import (
XdxrRecord,
)
__version__ = "0.6.5"
__version__ = "0.6.6"
__all__ = [
"TdxData",
"Market",
+40
View File
@@ -30,6 +30,7 @@ from datetime import date as _date, datetime
from pathlib import Path
from typing import Sequence
from . import decimal_sync
from .cache.disk import DiskCache
from .cache.key import CacheKey
from .cache.manager import CacheManager
@@ -285,6 +286,7 @@ class TdxData:
self._paginator_std = Paginator(self._std_pool)
self._paginator_mac = Paginator(self._mac_pool)
self._started = False
self._decimal_task: asyncio.Task | None = None
async def start(self) -> None:
await self._std_pool.start()
@@ -292,8 +294,13 @@ class TdxData:
await self._ex_pool.start()
await self._cache.start()
self._started = True
# 权威价格小数位表:当日缓存命中则同步装表(无网络),否则挂后台同步。
# 不阻塞 start(),失败静默退回静态前缀规则。
self._decimal_task = decimal_sync.schedule(self)
async def close(self) -> None:
await decimal_sync.cancel(self._decimal_task)
self._decimal_task = None
await self._std_pool.close()
await self._mac_pool.close()
await self._ex_pool.close()
@@ -331,6 +338,39 @@ class TdxData:
out.extend(await self._universe_cn(mkt))
return out
async def sync_decimal_points(self, markets: Sequence[str] = ("sh", "sz")
) -> dict[str, int]:
"""从证券清单同步**权威价格小数位表**,返回统计。
报价接口返回的是整数,真实价格 = ``整数 / 10**小数位``。小数位不随报价下发,
但证券清单接口自带权威值 ``SecurityInfo.decimal_point`` —— 本方法把它灌进
:func:`~pytdxdata.protocol.commands.quotes.price_decimal_digits` 使用的运行时表,
从此价格标度不再依赖硬编码前缀规则(新增代码段也不会算错)。
``start()`` 已自动处理:当日缓存命中就直接装表,否则挂后台同步,**不用手动调**。
这个方法用于「立刻要权威表」「排障时强制刷新」。
参数:
markets: 拉哪些市场,默认 ``("sh", "sz")``。证券清单走 ``get_universe``,
其本身已有缓存层,重复调用只花一次网络。
返回:
``{"prefixes", "codes", "mixed_prefixes", "stock"}`` —— 已覆盖的三位前缀数、
例外代码数、出现混合小数位的前缀数、总条目数。
``mixed_prefixes`` > 0 说明某段代码混用了不同小数位(已自动退化为逐代码查表)。
用法::
async with TdxData() as td:
print(await td.sync_decimal_points()) # {'prefixes': 300+, 'codes': 0, ...}
q = await td.get_quotes("sh019742") # 110.228(4 位小数)
"""
return await decimal_sync.refresh(self, tuple(markets))
async def decimal_point_status(self) -> dict:
"""权威小数位表当前状态(``source`` / ``stock`` / ``syncing`` 等,排障用)。"""
return decimal_sync.status()
async def _universe_cn(self, market: int) -> list[SecurityInfo]:
key = CacheKey("list", market)
+13
View File
@@ -33,6 +33,7 @@ _SERVERS_FILE = Path(__file__).resolve().parent / "servers.json" # 包内清单
# 当日测速缓存(结构变更时递增,旧版本缓存自动失效)
PROBE_CACHE_VERSION = 1
_PROBE_CACHE_NAME = "hosts-today.json"
_DECIMAL_CACHE_NAME = "decimal-points.json"
# ---------- 包内清单(只读基线) ----------
@@ -97,6 +98,18 @@ def probe_cache_file() -> Path:
return probe_cache_dir() / _PROBE_CACHE_NAME
def decimal_cache_file() -> Path:
"""权威价格小数位表缓存路径(每次调用重新解析,便于测试改环境变量后生效)。"""
return probe_cache_dir() / _DECIMAL_CACHE_NAME
def decimal_sync_disabled() -> bool:
"""是否已通过 ``PYPYTDX_DATA_DISABLE_DECIMAL_SYNC`` 关闭小数位后台同步。"""
return os.environ.get("PYPYTDX_DATA_DISABLE_DECIMAL_SYNC", "").strip().lower() in {
"1", "true", "yes", "on",
}
def probe_disabled() -> bool:
"""是否已通过 ``PYPYTDX_DATA_DISABLE_PROBE`` 关闭当日测速缓存。"""
return os.environ.get("PYPYTDX_DATA_DISABLE_PROBE", "").strip().lower() in {
+223
View File
@@ -0,0 +1,223 @@
"""权威价格小数位表的同步与缓存(对用户无感)。
为什么需要它
------------
``get_quotes`` 解析报价时,协议给的是**整数**,真实价格 = ``整数 / 10**小数位``。
小数位在协议里**不是**随报价一起下发的,只能靠推断(见
:func:`pytdxdata.protocol.commands.quotes.price_decimal_digits`)。
但证券清单接口(``get_universe``,底层 ``GetSecurityListCmd``)**自带**这个字段:
``SecurityInfo.decimal_point``,同时还带 ``pre_close``。这就是权威来源。本模块把它
灌进 ``price_decimal_digits`` 使用的运行时表,使价格标度不再依赖硬编码前缀规则。
行为
----
- **当日首次启动**检查缓存文件(``decimal-points.json``):命中就直接装表(纯内存,
无网络、约 10 ms);未命中则挂一个**后台 task** 拉证券清单并写缓存,
当天不再重复。
- 后台 task 不阻塞 ``start()``,不打印、不抛异常(取消除外),失败只落 debug 日志。
- 未同步成功时 ``price_decimal_digits`` 静默退回静态前缀规则,行为与 0.6.5 一致。
- 证券清单本身已被 ``cache/`` 层缓存,因此同步的实际网络开销只在**首次**
(约 26 + 25 个分页请求)。
开关
----
- ``PYPYTDX_DATA_DISABLE_DECIMAL_SYNC=1`` 关闭后台同步(CI / 测试用,保证确定性)。
- ``PYPYTDX_DATA_CACHE_DIR`` 覆盖缓存目录(测试指向临时目录)。
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
from datetime import date
from pathlib import Path
from typing import TYPE_CHECKING, Any
from .config import decimal_cache_file, decimal_sync_disabled
from .protocol.commands.quotes import (
clear_decimal_map,
decimal_map_source,
decimal_map_stats,
install_decimal_map,
)
if TYPE_CHECKING: # pragma: no cover
from .api import TdxData
log = logging.getLogger(__name__)
#: 同步哪些市场(只对 A 股有意义:扩展市场报价本身不含标度歧义)
DEFAULT_MARKETS: tuple[str, ...] = ("sh", "sz")
_CN_NAME = {"sh": 1, "sz": 0}
_state: dict[str, Any] = {"loaded": "", "task": None}
# ---------------------------------------------------------------------- #
# 磁盘缓存
# ---------------------------------------------------------------------- #
def cache_file() -> Path:
"""缓存文件路径(每次重新解析,便于测试改环境变量)。"""
return decimal_cache_file()
def _read_cache(path: Path | None = None) -> dict[str, dict[str, int]] | None:
"""读缓存 → ``{"1": {code: dp}}``;缺失 / 损坏 → ``None``。"""
target = Path(path) if path is not None else cache_file()
try:
raw = json.loads(target.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
if not isinstance(raw, dict):
return None
if raw.get("date") != date.today().isoformat():
return None
markets = raw.get("markets")
if not isinstance(markets, dict) or not markets:
return None
out: dict[str, dict[str, int]] = {}
for k, v in markets.items():
if not isinstance(v, dict):
continue
try:
out[str(int(k))] = {str(c): int(d) for c, d in v.items() if int(d) > 0}
except (TypeError, ValueError):
continue
return out or None
def load_cached(path: Path | None = None) -> int:
"""把当日缓存装进权威表;成功返回覆盖条目数,否则 0。"""
if decimal_sync_disabled():
return 0
markets = _read_cache(path)
if not markets:
return 0
items = [(int(m), c, d) for m, codes in markets.items() for c, d in codes.items()]
stats = install_decimal_map(items, source="cache")
_state["loaded"] = date.today().isoformat()
log.debug("小数位表已从缓存加载: %s", stats)
return int(stats["stock"])
def _write_cache(markets: dict[str, dict[str, int]], path: Path | None = None) -> None:
"""原子写缓存(tmp + ``os.replace``),失败只落 debug 日志。"""
target = Path(path) if path is not None else cache_file()
payload = {"date": date.today().isoformat(), "markets": markets}
tmp = target.with_suffix(".tmp")
try:
target.parent.mkdir(parents=True, exist_ok=True)
tmp.write_text(
json.dumps(payload, ensure_ascii=False, separators=(",", ":")),
encoding="utf-8",
)
os.replace(tmp, target)
except OSError as e: # pragma: no cover - 磁盘不可写等
log.debug("小数位表缓存写入失败: %s", e)
try:
tmp.unlink(missing_ok=True)
except OSError:
pass
# ---------------------------------------------------------------------- #
# 同步
# ---------------------------------------------------------------------- #
async def refresh(td: "TdxData", markets: tuple[str, ...] = DEFAULT_MARKETS,
*, path: Path | None = None) -> dict[str, int]:
"""拉证券清单 → 装表 + 写缓存。返回统计。
证券清单走 ``get_universe``(含 ``cache/`` 层缓存),只有首次真正发请求。
"""
tables: dict[str, dict[str, int]] = {}
items: list[tuple[int, str, int]] = []
for name in markets:
m = _CN_NAME.get(name)
if m is None:
continue
rows = await td.get_universe(name)
table: dict[str, int] = {}
for it in rows:
dp = int(getattr(it, "decimal_point", 0) or 0)
code = str(getattr(it, "code", "") or "").strip().rstrip("\x00")
if dp <= 0 or not code:
continue
table[code] = dp
items.append((m, code, dp))
if table:
tables[str(m)] = table
stats = install_decimal_map(items, source="universe")
_state["loaded"] = date.today().isoformat()
if tables:
_write_cache(tables, path)
log.debug("小数位表同步完成: %s", stats)
return stats
async def _run(td: "TdxData") -> dict[str, int]:
try:
return await refresh(td)
except asyncio.CancelledError:
raise
except Exception as e: # pragma: no cover - 网络/解析异常都不该影响用户
log.debug("小数位表后台同步失败: %s", e)
return {}
def schedule(td: "TdxData") -> asyncio.Task | None:
"""[内部] 需要时把同步挂到后台并返回 Task(调用方持有 / 取消)。
- 已关闭(``PYPYTDX_DATA_DISABLE_DECIMAL_SYNC=1``)→ ``None``
- 当日缓存命中 → 立即装表(同步、无网络),返回 ``None``
- 否则创建后台 task;进程内单例,重复调用复用同一个 task
"""
if decimal_sync_disabled():
return None
if decimal_map_stats()["stock"] and _state["loaded"] == date.today().isoformat():
return None
if load_cached():
return None
task = _state.get("task")
if task is not None and not task.done():
return task
task = asyncio.get_running_loop().create_task(_run(td), name="pytdxdata-decimal-sync")
_state["task"] = task
return task
async def cancel(task: asyncio.Task | None) -> None:
"""取消并等待后台同步 task(供 ``TdxData.close()`` 调用)。"""
if task is None or task.done():
return
task.cancel()
try:
await task
except (asyncio.CancelledError, Exception): # noqa: BLE001 - 关闭路径不抛
pass
def status() -> dict[str, Any]:
"""当前状态快照(排障 / 测试用)。"""
task = _state.get("task")
return {
"loaded": _state["loaded"],
"source": decimal_map_source(),
"syncing": bool(task is not None and not task.done()),
**decimal_map_stats(),
}
def reset() -> None:
"""清空内存状态(测试用;不动磁盘缓存)。"""
task = _state.get("task")
if task is not None and not task.done():
task.cancel()
_state["task"] = None
_state["loaded"] = ""
clear_decimal_map()
+124 -19
View File
@@ -12,30 +12,93 @@ from .base import BaseCommand
MAX_QUOTES = 80
def price_decimal_digits(market: int, code: str) -> int:
"""推断报价的小数位:**协议原始整数除以 ``10**该值``** 才是真实价格。
# ====================================================================== #
# 权威小数位表(由证券清单 SecurityInfo.decimal_point 灌入)
# ====================================================================== #
# 查找顺序:**权威表 → 静态前缀规则**。权威表来自 ``get_universe`` 返回的
# ``SecurityInfo.decimal_point``(协议自带,见 protocol/commands/security_list.py),
# 由 ``pytdxdata.decimal_sync`` 在后台每日同步一次;未同步时静默退回静态规则,
# 行为与 0.6.5 完全一致。
_DECIMAL_PREFIX: dict[tuple[int, str], int] = {}
_DECIMAL_CODE: dict[tuple[int, str], int] = {}
_DECIMAL_MIXED: set[tuple[int, str]] = set()
_DECIMAL_SOURCE: str = ""
四档:股票/指数/板块 ``2``、基金/ETF/B股 ``3``、债券/回购 ``4``。
该函数只是**离线推断**(``get_quotes`` 解析时拿不到证券清单)。真正的权威来源
是证券列表里协议自带的 ``SecurityInfo.decimal_point`` 字段——2026-10-22 拉取
全量 51,982 只(沪 27,520 + 深 24,462)逐条比对,本函数与之一一吻合、**零例外**。
能对上是因为「三位前缀 → 小数位」在全量清单里没有任何一个前缀出现混合小数位。
def install_decimal_map(
items: "list[tuple[int, str, int]] | tuple[tuple[int, str, int], ...]",
*,
source: str = "",
) -> dict[str, int]:
"""用证券清单灌入权威小数位表。
历史修正(两次都是同一类错误:把某段前缀想当然地归错档):
``items`` 为 ``(market, code, decimal_point)`` 序列(直接来自
``SecurityInfo``)。按**三位代码前缀**归并成一个极小的表(全量 5 万只标的
只产生数百个前缀);若某个前缀出现**不同**小数位,则该前缀退化为逐代码查表,
只把这些例外代码存进 ``_DECIMAL_CODE``——这样即使将来交易所新增代码段,
也不会因为前缀规则过时而算错价格。
- **2026-10-21**:沪市 ``000``/``8`` 被判成 3 位 → 上证指数/上证50/科创50/
板块指数**价格少 10 倍**(3713 读成 371)。它们实际是 2 位。
- **2026-10-22**:债券与回购全线偏差 —— 沪市 ``010/018/019/020/1xx/2xx``
与深市 ``10x/11x/12x/13x/14x/19x/50x/52x/56x`` 实际是 **4 位**,原先
沪市落到 2 位(**少 100 倍**)、深市落到 3 位(**少 10 倍**)。实测例:
``sh019742`` 110.228 读成 11022.8、``sh204001`` 1.385 读成 138.5、
``sz131810`` 1.38 读成 13.8。同时沪市 B 股 ``900xxx`` 是 3 位(原先 2 位)。
实证方法:拿 ``pre_close``(快照口径)除以上一交易日**日线收盘**(K线口径,
走 ``/1000`` 独立路径),比值即标度误差 —— 1.0 正确、10 少 10 倍、100 少 100 倍。
返回统计:``{"prefixes", "codes", "mixed_prefixes", "stock"}``。
"""
code = (code or "").strip().rstrip("\x00")
global _DECIMAL_SOURCE
votes: dict[tuple[int, str], dict[int, int]] = {}
per_code: dict[tuple[int, str], int] = {}
for market, code, dp in items:
c = str(code or "").strip().rstrip("\x00")
if len(c) < 3:
continue
m = int(market)
if m not in (0, 1):
continue
d = int(dp)
if d <= 0:
continue
per_code[(m, c)] = d
key = (m, c[:3])
bucket = votes.setdefault(key, {})
bucket[d] = bucket.get(d, 0) + 1
_DECIMAL_PREFIX.clear()
_DECIMAL_CODE.clear()
_DECIMAL_MIXED.clear()
for key, bucket in votes.items():
if len(bucket) == 1:
_DECIMAL_PREFIX[key] = next(iter(bucket))
else:
_DECIMAL_MIXED.add(key)
for (m, c), d in per_code.items():
if (m, c[:3]) in _DECIMAL_MIXED:
_DECIMAL_CODE[(m, c)] = d
_DECIMAL_SOURCE = source or "universe"
return decimal_map_stats()
def clear_decimal_map() -> None:
"""清空权威表(回到纯静态前缀规则;测试与排障用)。"""
global _DECIMAL_SOURCE
_DECIMAL_PREFIX.clear()
_DECIMAL_CODE.clear()
_DECIMAL_MIXED.clear()
_DECIMAL_SOURCE = ""
def decimal_map_stats() -> dict[str, int]:
"""权威表状态:已覆盖前缀数 / 例外代码数 / 混合前缀数 / 总条目数。"""
return {
"prefixes": len(_DECIMAL_PREFIX),
"codes": len(_DECIMAL_CODE),
"mixed_prefixes": len(_DECIMAL_MIXED),
"stock": len(_DECIMAL_PREFIX) + len(_DECIMAL_CODE),
}
def decimal_map_source() -> str:
"""权威表来源标记(``universe`` / ``cache`` / ``""``=未加载)。"""
return _DECIMAL_SOURCE
def _decimal_digits_static(market: int, code: str) -> int:
"""静态前缀规则(**兜底**,权威表缺失时使用)。"""
if market == 1: # 沪市
if code.startswith("5"):
return 3 # 基金/ETF/LOF(50/51/52/56/58 系)
@@ -56,6 +119,48 @@ def price_decimal_digits(market: int, code: str) -> int:
return 2
def price_decimal_digits(market: int, code: str) -> int:
"""报价小数位:**协议原始整数除以 ``10**该值``** 才是真实价格。
查找顺序:
1. **权威表**(:func:`install_decimal_map` 灌入)—— 来自证券清单里协议自带的
``SecurityInfo.decimal_point``,由 ``pytdxdata.decimal_sync`` 每日后台同步一次。
2. **静态前缀规则**(:func:`_decimal_digits_static`)—— 权威表未就绪时兜底。
四档:股票/指数/板块 ``2``、基金/ETF/B股 ``3``、债券/回购 ``4``。
为什么还要静态规则:``get_quotes`` 解析是**纯同步、无网络**的路径,解析那一刻
可能还没同步过证券清单;而现网首次安装/离线环境也必须能算出价格。
权威表与静态规则的一致性:2026-10-22 拉取全量 51,982 只(沪 27,520 + 深 24,462)
逐条比对,静态规则与 ``decimal_point`` **一一吻合、零例外**——因为全量清单里
没有任何一个三位前缀出现混合小数位。因此两者并存不会产生口径冲突。
历史修正(两次都是同一类错误:把某段前缀想当然地归错档):
- **2026-10-21**:沪市 ``000``/``8`` 被判成 3 位 → 上证指数/上证50/科创50/
板块指数**价格少 10 倍**(3713 读成 371)。它们实际是 2 位。
- **2026-10-22**:债券与回购全线偏差 —— 沪市 ``010/018/019/020/1xx/2xx``
与深市 ``10x/11x/12x/13x/14x/19x/50x/52x/56x`` 实际是 **4 位**,原先
沪市落到 2 位(**少 100 倍**)、深市落到 3 位(**少 10 倍**)。实测例:
``sh019742`` 110.228 读成 11022.8、``sh204001`` 1.385 读成 138.5、
``sz131810`` 1.38 读成 13.8。同时沪市 B 股 ``900xxx`` 是 3 位(原先 2 位)。
实证方法:拿 ``pre_close``(快照口径)除以上一交易日**日线收盘**(K线口径,
走 ``/1000`` 独立路径),比值即标度误差 —— 1.0 正确、10 少 10 倍、100 少 100 倍。
"""
code = (code or "").strip().rstrip("\x00")
m = int(market)
if m in (0, 1):
hit = _DECIMAL_PREFIX.get((m, code[:3]))
if hit is not None:
return hit
hit = _DECIMAL_CODE.get((m, code))
if hit is not None:
return hit
return _decimal_digits_static(m, code)
def format_server_time(raw: int) -> str:
"""服务器时间编码:小时 + 百万分之一小时。14999212 -> 14:59:57.163"""
hours, fractional_hour = divmod(raw, 1_000_000)