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

+37
View File
@@ -2,6 +2,43 @@
本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/)。 本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
## [0.6.6] - 2026-10-22
### 改进
- **价格小数位改用协议自带的权威值,前缀规则降为兜底**。
0.6.5 修好债券/回购标度时,采用的是「按代码前缀推断」+「用全量清单做离线校验」。
但同一份证券清单接口(`get_universe`,底层 `GetSecurityListCmd`)本来就**返回**
`SecurityInfo.decimal_point`(外加自描述浮点的 `pre_close`)——权威值一直就在手上,
只是没接进取数路径。本次把它接进来:
| 位置 | 说明 |
|---|---|
| `price_decimal_digits` | 查找顺序改为 **权威表 → 静态前缀规则**,未同步时行为与 0.6.5 完全一致 |
| `decimal_sync`(新模块) | 每日后台同步一次 + 磁盘缓存(`%LOCALAPPDATA%\pytdxdata\decimal-points.json`) |
| `TdxData.sync_decimal_points()` | 手动强制刷新(排障 / 立刻要权威表) |
| `TdxData.decimal_point_status()` | 状态:`source` / `stock` / `mixed_prefixes` / `syncing` |
**对用户仍无感**:`start()` 命中当日缓存就直接装表(实测 60 ms、零网络),
未命中则挂后台 task(实测首次 50 s,含沪 27,520 + 深 24,462 条清单),
不阻塞 `start()`(`start()` 仍 1.5 s);`close()` 会取消未完成的同步。
**表结构刻意做小**:全量 5 万只标的只产生 **129 个**「三位前缀 → 小数位」映射,
内存里就是 129 条。若将来某段代码混用两种小数位,该前缀自动退化为**逐代码表**,
只存例外代码(`mixed_prefixes` 会 > 0,可据此发现),不会静默算错。
为什么保留前缀规则:`get_quotes` 解析是纯同步、无网络的路径,解析那一刻可能还没
同步过清单;离线 / 首次安装也必须能出价格。实测两者在全量清单上**零分歧**
(51,982 条逐条比对,不一致 0 条),并存不会造成口径冲突。
开关:`PYPYTDX_DATA_DISABLE_DECIMAL_SYNC=1` 关闭后台同步(CI / 测试用)。
### 说明
- 新增回归测试 16 项(权威表优先级 / 混合前缀退化 / 缓存跨日失效 / 损坏容错 /
后台任务取消),测试总数 **289 → 306**。
## [0.6.5] - 2026-10-22 ## [0.6.5] - 2026-10-22
### 新增 ### 新增
+3 -1
View File
@@ -47,7 +47,9 @@ from pytdxdata import (
| 方法 | 返回 | 说明 | | 方法 | 返回 | 说明 |
|------|------|------| |------|------|------|
| `get_universe(market=None)` | `list[SecurityInfo]` | 跨市场标的清单(A 股+港股+美股+期货/期权) | | `get_universe(market=None)` | `list[SecurityInfo]` | 跨市场标的清单(A 股+港股+美股+期货/期权);每条带协议自带的 `decimal_point`(价格小数位)与 `pre_close` |
| `sync_decimal_points(markets=("sh","sz"))` | `dict` | 从证券清单同步**权威价格小数位表**(`SecurityInfo.decimal_point`),灌进 `price_decimal_digits` 的运行时表;`start()` 已自动做(当日缓存命中则零网络),此方法用于强制刷新/排障 |
| `decimal_point_status()` | `dict` | 小数位表状态:`source`(`cache`/`universe`/空)、`stock`、`mixed_prefixes`、`syncing` |
#### 报价 #### 报价
+4
View File
@@ -48,6 +48,10 @@ asyncio.run(main())
- **K 线**:`get_bars`(自动并发分页、支持复权与日期区间、多标的并发) - **K 线**:`get_bars`(自动并发分页、支持复权与日期区间、多标的并发)
- **技术指标**:`get_indicators`(K线 + MACD/KDJ/RSI/BOLL/MA/EMA) - **技术指标**:`get_indicators`(K线 + MACD/KDJ/RSI/BOLL/MA/EMA)
- **报价**:`get_quotes`(五档,>80 只自动切批)、`get_snapshot`(个股特征)、`get_market_stat` - **报价**:`get_quotes`(五档,>80 只自动切批)、`get_snapshot`(个股特征)、`get_market_stat`
- 价格标度:协议给的是整数,真实价 = `整数 / 10**小数位`。小数位由 `price_decimal_digits` 决定,
优先用**权威表**(证券清单自带的 `SecurityInfo.decimal_point`,`start()` 每日后台同步一次,
也可 `await td.sync_decimal_points()` 强制刷新),未同步时退回静态前缀规则。
债券/回购是 **4 位**、沪市 B 股 3 位 —— 这里错过两次(整批价格差 100 倍/10 倍)。
- **逐笔 / 分时**:`get_ticks`(含 `trade_count`,支持历史日期,返回按时间升序;`vol`/`trade_count` 为约 3 秒切片增量而非累计;已剔除 `bs_flag=8` 竞价委托;**指数**的 `vol` 是百元、`trade_count` 是均价×1000)、`get_minutes`(`sampling=True` 取缩略采样;`hour` 恒为合法时钟值 0~23,美股一个交易日跨两个北京自然日,按交易日聚合用 `MinuteBar.trading_date`、取时刻用 `MinuteBar.datetime`) - **逐笔 / 分时**:`get_ticks`(含 `trade_count`,支持历史日期,返回按时间升序;`vol`/`trade_count` 为约 3 秒切片增量而非累计;已剔除 `bs_flag=8` 竞价委托;**指数**的 `vol` 是百元、`trade_count` 是均价×1000)、`get_minutes`(`sampling=True` 取缩略采样;`hour` 恒为合法时钟值 0~23,美股一个交易日跨两个北京自然日,按交易日聚合用 `MinuteBar.trading_date`、取时刻用 `MinuteBar.datetime`)
- **财务 / 除权**:`get_finance`(最新快照)、`get_xdxr`、`get_price_limits`(本地计算涨跌停) - **财务 / 除权**:`get_finance`(最新快照)、`get_xdxr`、`get_price_limits`(本地计算涨跌停)
- **F10**:`get_f10`(公司资料目录 + 正文) - **F10**:`get_f10`(公司资料目录 + 正文)
+1 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "pytdxdata" name = "pytdxdata"
version = "0.6.5" version = "0.6.6"
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"
+1 -1
View File
@@ -18,7 +18,7 @@ from .models import (
XdxrRecord, XdxrRecord,
) )
__version__ = "0.6.5" __version__ = "0.6.6"
__all__ = [ __all__ = [
"TdxData", "TdxData",
"Market", "Market",
+40
View File
@@ -30,6 +30,7 @@ from datetime import date as _date, datetime
from pathlib import Path from pathlib import Path
from typing import Sequence from typing import Sequence
from . import decimal_sync
from .cache.disk import DiskCache from .cache.disk import DiskCache
from .cache.key import CacheKey from .cache.key import CacheKey
from .cache.manager import CacheManager from .cache.manager import CacheManager
@@ -285,6 +286,7 @@ class TdxData:
self._paginator_std = Paginator(self._std_pool) self._paginator_std = Paginator(self._std_pool)
self._paginator_mac = Paginator(self._mac_pool) self._paginator_mac = Paginator(self._mac_pool)
self._started = False self._started = False
self._decimal_task: asyncio.Task | None = None
async def start(self) -> None: async def start(self) -> None:
await self._std_pool.start() await self._std_pool.start()
@@ -292,8 +294,13 @@ class TdxData:
await self._ex_pool.start() await self._ex_pool.start()
await self._cache.start() await self._cache.start()
self._started = True self._started = True
# 权威价格小数位表:当日缓存命中则同步装表(无网络),否则挂后台同步。
# 不阻塞 start(),失败静默退回静态前缀规则。
self._decimal_task = decimal_sync.schedule(self)
async def close(self) -> None: async def close(self) -> None:
await decimal_sync.cancel(self._decimal_task)
self._decimal_task = None
await self._std_pool.close() await self._std_pool.close()
await self._mac_pool.close() await self._mac_pool.close()
await self._ex_pool.close() await self._ex_pool.close()
@@ -331,6 +338,39 @@ class TdxData:
out.extend(await self._universe_cn(mkt)) out.extend(await self._universe_cn(mkt))
return out 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]: async def _universe_cn(self, market: int) -> list[SecurityInfo]:
key = CacheKey("list", market) 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_VERSION = 1
_PROBE_CACHE_NAME = "hosts-today.json" _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 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: def probe_disabled() -> bool:
"""是否已通过 ``PYPYTDX_DATA_DISABLE_PROBE`` 关闭当日测速缓存。""" """是否已通过 ``PYPYTDX_DATA_DISABLE_PROBE`` 关闭当日测速缓存。"""
return os.environ.get("PYPYTDX_DATA_DISABLE_PROBE", "").strip().lower() in { 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 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`` 解析时拿不到证券清单)。真正的权威来源 def install_decimal_map(
是证券列表里协议自带的 ``SecurityInfo.decimal_point`` 字段——2026-10-22 拉取 items: "list[tuple[int, str, int]] | tuple[tuple[int, str, int], ...]",
全量 51,982 只(沪 27,520 + 深 24,462)逐条比对,本函数与之一一吻合、**零例外**。 *,
能对上是因为「三位前缀 → 小数位」在全量清单里没有任何一个前缀出现混合小数位。 source: str = "",
) -> dict[str, int]:
"""用证券清单灌入权威小数位表。
历史修正(两次都是同一类错误:把某段前缀想当然地归错档): ``items`` 为 ``(market, code, decimal_point)`` 序列(直接来自
``SecurityInfo``)。按**三位代码前缀**归并成一个极小的表(全量 5 万只标的
只产生数百个前缀);若某个前缀出现**不同**小数位,则该前缀退化为逐代码查表,
只把这些例外代码存进 ``_DECIMAL_CODE``——这样即使将来交易所新增代码段,
也不会因为前缀规则过时而算错价格。
- **2026-10-21**:沪市 ``000``/``8`` 被判成 3 位 → 上证指数/上证50/科创50/ 返回统计:``{"prefixes", "codes", "mixed_prefixes", "stock"}``。
板块指数**价格少 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") 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 market == 1: # 沪市
if code.startswith("5"): if code.startswith("5"):
return 3 # 基金/ETF/LOF(50/51/52/56/58 系) return 3 # 基金/ETF/LOF(50/51/52/56/58 系)
@@ -56,6 +119,48 @@ def price_decimal_digits(market: int, code: str) -> int:
return 2 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: def format_server_time(raw: int) -> str:
"""服务器时间编码:小时 + 百万分之一小时。14999212 -> 14:59:57.163""" """服务器时间编码:小时 + 百万分之一小时。14999212 -> 14:59:57.163"""
hours, fractional_hour = divmod(raw, 1_000_000) hours, fractional_hour = divmod(raw, 1_000_000)
+22
View File
@@ -0,0 +1,22 @@
"""测试全局隔离。
默认关掉**权威小数位表的后台同步** —— 否则任何调用 ``TdxData.start()`` 的用例都会
顺手发起证券清单请求(26 + 25 个分页),测试会变慢且依赖网络。
需要验证同步行为本身的用例(``test_decimal_sync.py``)自己 ``delenv`` 后再测。
"""
from __future__ import annotations
import os
import pytest
@pytest.fixture(autouse=True, scope="session")
def _disable_decimal_sync():
old = os.environ.get("PYPYTDX_DATA_DISABLE_DECIMAL_SYNC")
os.environ["PYPYTDX_DATA_DISABLE_DECIMAL_SYNC"] = "1"
yield
if old is None:
os.environ.pop("PYPYTDX_DATA_DISABLE_DECIMAL_SYNC", None)
else:
os.environ["PYPYTDX_DATA_DISABLE_DECIMAL_SYNC"] = old
+21
View File
@@ -324,6 +324,27 @@ async def test_universe_and_quotes(td):
assert len(qex) == 1 assert len(qex) == 1
async def test_decimal_point_sync(td, tmp_path, monkeypatch):
"""权威小数位表同步:把证券清单的 decimal_point 灌进价格标度表。"""
for name in ("sync_decimal_points", "decimal_point_status"):
_use(name)
from pytdxdata.protocol.commands.quotes import clear_decimal_map, price_decimal_digits
# 缓存目录指向临时目录,避免把 mock 数据写进用户真实缓存
monkeypatch.setenv("PYPYTDX_DATA_CACHE_DIR", str(tmp_path))
before = price_decimal_digits(1, "600000")
try:
st = await td.sync_decimal_points()
assert set(st) >= {"prefixes", "codes", "mixed_prefixes", "stock"}
assert st["stock"] >= 0
status = await td.decimal_point_status()
assert isinstance(status, dict) and "source" in status
finally:
clear_decimal_map()
# 清空后回到静态规则,不受本用例污染
assert price_decimal_digits(1, "600000") == before
async def test_snapshot_auction_flow(td): async def test_snapshot_auction_flow(td):
for name in ("get_snapshot", "get_auction", "get_capital_flow"): for name in ("get_snapshot", "get_auction", "get_capital_flow"):
_use(name) _use(name)
+233
View File
@@ -0,0 +1,233 @@
"""权威价格小数位表(decimal_sync)单元测试。
覆盖点:
- 权威表(来自 ``SecurityInfo.decimal_point``)**优先于**静态前缀规则
- 某前缀出现混合小数位 → 自动退化为逐代码查表,不误伤同前缀其它代码
- 清空权威表 → 回到静态规则(与 0.6.5 行为一致)
- 磁盘缓存:写入 / 读取 / 跨日失效 / 损坏容错,均不回退到网络
- ``PYPYTDX_DATA_DISABLE_DECIMAL_SYNC=1`` → 完全不动作
- 证券清单里 ``decimal_point == 0`` 的脏条目被忽略
- 后台 task 可取消,且 ``close()`` 后不再改写表
(全部注入假 ``TdxData``,不连真实网络)
"""
from __future__ import annotations
import asyncio
import json
from types import SimpleNamespace
import pytest
from pytdxdata import decimal_sync
from pytdxdata.protocol.commands.quotes import (
clear_decimal_map,
decimal_map_stats,
install_decimal_map,
price_decimal_digits,
)
# ---------------------------------------------------------------------- #
# 夹具
# ---------------------------------------------------------------------- #
@pytest.fixture(autouse=True)
def _isolate(tmp_path, monkeypatch):
"""每个用例独立缓存目录 + 干净的内存状态。"""
monkeypatch.setenv("PYPYTDX_DATA_CACHE_DIR", str(tmp_path))
monkeypatch.delenv("PYPYTDX_DATA_DISABLE_DECIMAL_SYNC", raising=False)
decimal_sync.reset()
yield
decimal_sync.reset()
def _info(code: str, dp: int) -> SimpleNamespace:
return SimpleNamespace(code=code, decimal_point=dp, market=1)
class FakeTd:
"""只有 ``get_universe`` 的假客户端(记录调用次数,便于断言"没走网络")。"""
def __init__(self, tables: dict[str, list[tuple[str, int]]] | None = None) -> None:
self.tables = tables or {}
self.calls: list[str] = []
async def get_universe(self, market: str | None = None):
self.calls.append(market or "all")
return [_info(c, d) for c, d in self.tables.get(market, [])]
# ---------------------------------------------------------------------- #
# 权威表优先级
# ---------------------------------------------------------------------- #
def test_authoritative_map_overrides_static_rule():
# 静态规则说 sh019742 是 4 位;权威表说 3 位 → 必须听权威表的
assert price_decimal_digits(1, "019742") == 4
install_decimal_map([(1, "019742", 3)], source="test")
assert price_decimal_digits(1, "019742") == 3
def test_codes_outside_map_still_use_static_rule():
install_decimal_map([(1, "019742", 3)], source="test")
assert price_decimal_digits(1, "600000") == 2 # 股票
assert price_decimal_digits(1, "510300") == 3 # ETF
assert price_decimal_digits(0, "131810") == 4 # 深回购(表里没有)
def test_mixed_prefix_falls_back_to_per_code_lookup():
"""同一前缀出现两种小数位 → 该前缀不进前缀表,只把例外代码存进逐代码表。"""
stats = install_decimal_map(
[(1, "110001", 4), (1, "110002", 4), (1, "110003", 3)], source="test")
assert stats["mixed_prefixes"] == 1
assert stats["codes"] == 3 # 混合前缀下所有代码都进逐代码表
assert price_decimal_digits(1, "110001") == 4
assert price_decimal_digits(1, "110003") == 3
def test_clear_map_restores_static_rules():
install_decimal_map([(1, "019742", 3)], source="test")
assert price_decimal_digits(1, "019742") == 3
clear_decimal_map()
assert decimal_map_stats()["stock"] == 0
assert price_decimal_digits(1, "019742") == 4
def test_reinstall_replaces_previous_map():
install_decimal_map([(1, "019742", 3)], source="a")
install_decimal_map([(1, "019742", 4)], source="b")
assert price_decimal_digits(1, "019742") == 4
assert decimal_map_stats()["prefixes"] == 1
# ---------------------------------------------------------------------- #
# 同步
# ---------------------------------------------------------------------- #
def test_refresh_installs_and_writes_cache(tmp_path):
td = FakeTd({"sh": [("019742", 4), ("600000", 2)],
"sz": [("000001", 2), ("131810", 4)]})
stats = asyncio.run(decimal_sync.refresh(td))
assert td.calls == ["sh", "sz"]
assert stats["stock"] == 4
assert price_decimal_digits(1, "600000") == 2
assert price_decimal_digits(0, "131810") == 4
raw = json.loads((tmp_path / "decimal-points.json").read_text(encoding="utf-8"))
assert raw["markets"]["1"]["019742"] == 4
assert raw["markets"]["0"]["131810"] == 4
def test_refresh_skips_zero_decimal_point():
td = FakeTd({"sh": [("019742", 0), ("600000", 2)]})
stats = asyncio.run(decimal_sync.refresh(td, ("sh",)))
assert stats["stock"] == 1
def test_refresh_ignores_unknown_market():
td = FakeTd({"hk": [("00700", 3)]})
stats = asyncio.run(decimal_sync.refresh(td, ("hk",)))
assert stats["stock"] == 0
assert not (decimal_sync.cache_file()).exists()
def test_load_cached_roundtrip(tmp_path):
td = FakeTd({"sh": [("019742", 4)]})
asyncio.run(decimal_sync.refresh(td))
decimal_sync.reset()
assert decimal_map_stats()["stock"] == 0
assert decimal_sync.load_cached() == 1
assert price_decimal_digits(1, "019742") == 4
def test_cache_expires_across_days(tmp_path):
td = FakeTd({"sh": [("019742", 4)]})
asyncio.run(decimal_sync.refresh(td))
decimal_sync.reset()
path = tmp_path / "decimal-points.json"
payload = json.loads(path.read_text(encoding="utf-8"))
payload["date"] = "2000-01-01"
path.write_text(json.dumps(payload), encoding="utf-8")
assert decimal_sync.load_cached() == 0
def test_corrupt_cache_is_ignored(tmp_path):
path = tmp_path / "decimal-points.json"
path.write_text("{not json", encoding="utf-8")
assert decimal_sync.load_cached() == 0
# ---------------------------------------------------------------------- #
# 调度
# ---------------------------------------------------------------------- #
def test_schedule_disabled_by_env(monkeypatch):
monkeypatch.setenv("PYPYTDX_DATA_DISABLE_DECIMAL_SYNC", "1")
td = FakeTd({"sh": [("019742", 4)]})
async def run():
task = decimal_sync.schedule(td)
return task
assert asyncio.run(run()) is None
assert td.calls == []
def test_schedule_loads_cache_without_network(tmp_path):
td = FakeTd({"sh": [("019742", 4)]})
asyncio.run(decimal_sync.refresh(td))
decimal_sync.reset()
quiet = FakeTd({"sh": [("019742", 4)]})
async def run():
return decimal_sync.schedule(quiet)
assert asyncio.run(run()) is None # 缓存命中 → 不起 task
assert quiet.calls == [] # 也没走网络
assert price_decimal_digits(1, "019742") == 4
def test_schedule_runs_background_sync_without_cache():
td = FakeTd({"sh": [("019742", 4)]})
async def run():
task = decimal_sync.schedule(td)
assert task is not None
await task
return decimal_sync.status()
st = asyncio.run(run())
assert st["source"] == "universe"
assert st["syncing"] is False
assert td.calls == ["sh", "sz"] # 默认两市
def test_cancel_stops_background_task():
class SlowTd:
def __init__(self) -> None:
self.calls = 0
async def get_universe(self, market=None):
self.calls += 1
await asyncio.sleep(5)
return []
td = SlowTd()
async def run():
task = decimal_sync.schedule(td)
await asyncio.sleep(0.01)
await decimal_sync.cancel(task)
return task.done() or task.cancelled()
assert asyncio.run(run()) is True
def test_status_shape():
st = decimal_sync.status()
assert set(st) >= {"loaded", "source", "syncing", "prefixes", "codes",
"mixed_prefixes", "stock"}
Generated
+1 -1
View File
@@ -535,7 +535,7 @@ wheels = [
[[package]] [[package]]
name = "pytdxdata" name = "pytdxdata"
version = "0.6.5" version = "0.6.6"
source = { editable = "." } source = { editable = "." }
[package.optional-dependencies] [package.optional-dependencies]