fix(api,codec): 修复 BUG-1 分时采样走错命令 + BUG-2 财务文件名纠正
BUG-1: A股 get_minutes(sampling=True) 原走 MacChartSamplingCmd(0x254D) 这是 EX 协议命令,7709 主机无响应(3×8s 超时≈24s)。 修复:A股采样由 MacTickChartCmd(0x122D) 分时数据派生, EX 市场(hk)仍走 0x254D。4 个 A股 场景均<0.1s 返回 240 点。 BUG-2: tdxfin/gpcw.txt 索引声明 gpcwYYYYMMDD.zip, 但服务器实际只有 tdxfin/gpcwYYYYMMDD.dat(未压缩,~13MB), .zip 请求返回 0-1 字节空壳。 修复:_fetch_financial_dat() 自动候选回退 tdxfin/*.zip → tdxfin/*.dat → 原始文件名,加 looks_like_gpcw_dat 校验。 实测 gpcw20260630.zip→5568 条,gpcw20260331.zip→5547 条。 新增 codec/financial.py: looks_like_gpcw_dat, extract_gpcw_dat(含 zip/未压缩双通道)。 同步更新 README/API_REFERENCE/docs/cli/cookbook/CHANGELOG 共 6 处文档。 tests: +18(总 182),ruff 无新增 findings,MkDocs strict 通过。
This commit is contained in:
1 parent
b78d0fabf5
commit
8951ec2678
10 files changed
+391
-39
No files matched your search
@@ -23,8 +23,28 @@
|
|||||||
全接口回归测试里对旧探针入口(`pool.get_probe_cache`)的替身改为新入口(`pool.schedule_probe`),
|
全接口回归测试里对旧探针入口(`pool.get_probe_cache`)的替身改为新入口(`pool.schedule_probe`),
|
||||||
保证单测不触发真实网络测速。
|
保证单测不触发真实网络测速。
|
||||||
|
|
||||||
|
### 修复
|
||||||
|
|
||||||
|
- **A股分时缩略采样 100% 失败**(`get_minutes(sampling=True)` / `get_chart_sampling()`):
|
||||||
|
旧实现走 `MacChartSamplingCmd`(**0x254D**),但该 opcode 属于 **EX 协议**,7709 标准 /
|
||||||
|
MAC 主机对它一律不响应——实测 3 台主机各 10s 超时,叠加连接池 3 次重试约 24s 才抛错。
|
||||||
|
现改为**由分时(0x122D)数据派生**价格点(分时本身就是 240 点,语义一致),
|
||||||
|
实测 4 个 A股 场景均在 0.1s 内返回 240 点;EX 通道仍用 0x254D(84 点)。
|
||||||
|
|
||||||
|
- **历史专业财报整条链路不可用**(`get_financial_records_parsed()`):
|
||||||
|
`tdxfin/gpcw.txt` 索引里写的是裸 `gpcwYYYYMMDD.zip`,而服务器**实际只提供未压缩的**
|
||||||
|
`tdxfin/gpcwYYYYMMDD.dat`。旧实现把索引名直接丢给 `zipfile` → 必然 `BadZipFile`;
|
||||||
|
废弃别名 `get_financial_records()` 更危险,会**静默返回 0~1 字节空壳**而不报错。
|
||||||
|
现按候选名(`tdxfin/*.zip` → `tdxfin/*.dat` → 原名)逐个尝试并校验数据形态,
|
||||||
|
zip 与未压缩 dat 都支持。实测 `gpcw20260630.zip` → **5568 条**、
|
||||||
|
`gpcw20260331.zip` → **5547 条**(样本 000001,584 个 float 字段),
|
||||||
|
别名返回 **13,068,116 字节**真实数据;尚未生成的占位条目
|
||||||
|
(如 `gpcw20260930.zip`,filesize=164)优雅返回空列表而非报错。
|
||||||
|
|
||||||
### 新增
|
### 新增
|
||||||
|
|
||||||
|
- `codec.financial` 新增 `looks_like_gpcw_dat()` / `extract_gpcw_dat()`:
|
||||||
|
财报字节的形态判定与「zip / 未压缩 dat」统一提取(纯标准库,可脱网单测)
|
||||||
- 环境变量 `PYPYTDX_DATA_CACHE_DIR`(覆盖测速缓存目录)、
|
- 环境变量 `PYPYTDX_DATA_CACHE_DIR`(覆盖测速缓存目录)、
|
||||||
`PYPYTDX_DATA_DISABLE_PROBE`(关闭测速,CI / 测试用)
|
`PYPYTDX_DATA_DISABLE_PROBE`(关闭测速,CI / 测试用)
|
||||||
- `tests/test_probe_cache.py`(37 项):当日缓存不刷新、跨日重测、
|
- `tests/test_probe_cache.py`(37 项):当日缓存不刷新、跨日重测、
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ df = pd.DataFrame([asdict(b) for b in bars])
|
|||||||
| 🔀 双通道整合 | 标准通道(经典行情)+ MAC 通道(逐笔 / 复权 / 1 分钟 K 线),按命令自动选路 |
|
| 🔀 双通道整合 | 标准通道(经典行情)+ MAC 通道(逐笔 / 复权 / 1 分钟 K 线),按命令自动选路 |
|
||||||
| 📦 零重型依赖 | 纯 asyncio + stdlib(socket / zlib / struct / sqlite3) |
|
| 📦 零重型依赖 | 纯 asyncio + stdlib(socket / zlib / struct / sqlite3) |
|
||||||
| 📊 全市场覆盖 | A股、港股、美股、期货、期权(46 个扩展市场) |
|
| 📊 全市场覆盖 | A股、港股、美股、期货、期权(46 个扩展市场) |
|
||||||
| 📄 服务器文件解析 | 板块 `block_*.dat` / 行业 `tdxhy.cfg` / 财报 `gpcw*.zip` **下载即解析**成 dataclass |
|
| 📄 服务器文件解析 | 板块 `block_*.dat` / 行业 `tdxhy.cfg` / 财报 `gpcw*` **下载即解析**成 dataclass(索引名与服务器实际文件名不一致时自动纠正) |
|
||||||
| 🤖 AI 助手友好 | 内置 [`SKILL.md`](https://github.com/openbot-coder/pytdxdata/blob/main/SKILL.md) 与 [`llms.txt`](https://openbot-coder.github.io/pytdxdata/llms.txt) |
|
| 🤖 AI 助手友好 | 内置 [`SKILL.md`](https://github.com/openbot-coder/pytdxdata/blob/main/SKILL.md) 与 [`llms.txt`](https://openbot-coder.github.io/pytdxdata/llms.txt) |
|
||||||
|
|
||||||
## 文档导航
|
## 文档导航
|
||||||
@@ -104,7 +104,7 @@ curl -o ~/.workbuddy/skills/pytdxdata/SKILL.md --create-dirs \
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
uv sync # 建虚拟环境 + 注册 tdx 命令
|
uv sync # 建虚拟环境 + 注册 tdx 命令
|
||||||
uv run pytest tests/ # 164 个测试用例(协议 / 池 / 缓存 / 分页 / 全接口回归 / 文件解析 / CLI / 文档漂移 / 当日测速缓存)
|
uv run pytest tests/ # 182 个测试用例(协议 / 池 / 缓存 / 分页 / 全接口回归 / 文件解析 / CLI / 文档漂移 / 当日测速缓存)
|
||||||
uv sync --group docs # 文档站依赖(mkdocs-material + mkdocstrings)
|
uv sync --group docs # 文档站依赖(mkdocs-material + mkdocstrings)
|
||||||
uv run mkdocs serve # 本地预览文档站
|
uv run mkdocs serve # 本地预览文档站
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ from pytdxdata import (
|
|||||||
| 方法 | 返回 | 说明 |
|
| 方法 | 返回 | 说明 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| `get_ticks(symbols, *, date=None, start=0, count=None, concurrency=6)` | `list[TransactionRecord]` | 跨市场逐笔成交 |
|
| `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_minutes(symbols, *, date=None, sampling=False, concurrency=6)` | `list[MinuteBar]` | 跨市场分时(sampling=True 取缩略采样:A股由 0x122D 派生,扩展市场 0x254D) |
|
||||||
|
|
||||||
#### 公司信息/文件/板块
|
#### 公司信息/文件/板块
|
||||||
|
|
||||||
@@ -109,7 +109,7 @@ from pytdxdata import (
|
|||||||
| `get_transactions(market, code, *, date=None, start=0, count=2000)` | `list[TransactionRecord]` | 逐笔成交(MAC,含 trade_count),支持历史日期 |
|
| `get_transactions(market, code, *, date=None, start=0, count=2000)` | `list[TransactionRecord]` | 逐笔成交(MAC,含 trade_count),支持历史日期 |
|
||||||
| `get_minute(market, code, *, date=None)` | `list[MinuteBar]` | 分时(MAC 0x122D,可历史) |
|
| `get_minute(market, code, *, date=None)` | `list[MinuteBar]` | 分时(MAC 0x122D,可历史) |
|
||||||
| `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 **0x122D** 派生;0x254D 仅 EX 通道可用) |
|
||||||
|
|
||||||
### 2.5 证券列表(旧接口,共 3 个) {#legacy-list}
|
### 2.5 证券列表(旧接口,共 3 个) {#legacy-list}
|
||||||
|
|
||||||
@@ -131,13 +131,13 @@ from pytdxdata import (
|
|||||||
| `get_block_info(filename)` | `bytes` | 板块文件**原始字节**(先查元数据再分块下载) |
|
| `get_block_info(filename)` | `bytes` | 板块文件**原始字节**(先查元数据再分块下载) |
|
||||||
| `get_report_file(filename)` | `bytes` | 报告/财务文件**原始字节**(标准 0x06B9) |
|
| `get_report_file(filename)` | `bytes` | 报告/财务文件**原始字节**(标准 0x06B9) |
|
||||||
| `get_financial_file_list()` | `list[str]` | 财务文件列表**原始行**(tdxfin/gpcw.txt) |
|
| `get_financial_file_list()` | `list[str]` | 财务文件列表**原始行**(tdxfin/gpcw.txt) |
|
||||||
| `get_financial_records(filename)` | `bytes` | 财务文件内容(gpcw*.zip 原始字节) |
|
| `get_financial_records(filename)` | `bytes` | 财报 `.dat` 原始字节(索引写 `.zip` 但服务器只有 `.dat` 时自动回退;取不到返回 `b""`) |
|
||||||
| `get_file_meta(filename)` | `FileMeta` | 远程文件元信息(MAC 0x1215) |
|
| `get_file_meta(filename)` | `FileMeta` | 远程文件元信息(MAC 0x1215) |
|
||||||
| `download_file(filename, filesize=0)` | `bytes` | 下载完整远程文件(MAC 0x1217,分块) |
|
| `download_file(filename, filesize=0)` | `bytes` | 下载完整远程文件(MAC 0x1217,分块) |
|
||||||
| **`get_block_parsed(filename)`** | `list[TdxBlock]` | 板块文件**下载+解析**为板块成分(category 按文件名推断:0行业/2概念/3风格) |
|
| **`get_block_parsed(filename)`** | `list[TdxBlock]` | 板块文件**下载+解析**为板块成分(category 按文件名推断:0行业/2概念/3风格) |
|
||||||
| **`get_industry_map()`** | `dict[str, IndustryInfo]` | tdxhy.cfg **下载+解析**:`{代码: 通达信行业+申万行业}` |
|
| **`get_industry_map()`** | `dict[str, IndustryInfo]` | tdxhy.cfg **下载+解析**:`{代码: 通达信行业+申万行业}` |
|
||||||
| **`get_financial_file_infos()`** | `list[FinancialFileInfo]` | gpcw.txt **下载+解析**:文件名/MD5/大小 |
|
| **`get_financial_file_infos()`** | `list[FinancialFileInfo]` | gpcw.txt **下载+解析**:文件名/MD5/大小 |
|
||||||
| **`get_financial_records_parsed(filename)`** | `list[FinancialRecord]` | gpcw*.zip **解压+解析**:每股原始 float 字段(报告期取自文件名,缺失回退头部) |
|
| **`get_financial_records_parsed(filename)`** | `list[FinancialRecord]` | 财报**解析**:每股原始 float 字段。可直接传 `get_financial_file_infos()` 的 `filename`——自动纠正服务器实际文件名(`.zip`/`.dat` 两种形态都支持);报告期取自文件名,缺失回退头部 |
|
||||||
|
|
||||||
> 解析层独立于网络层:解析器位于 `pytdxdata.codec`(纯标准库 `struct`/`zipfile`),可脱网单测;
|
> 解析层独立于网络层:解析器位于 `pytdxdata.codec`(纯标准库 `struct`/`zipfile`),可脱网单测;
|
||||||
> 原 `get_*` 返回 `bytes`/`list[str]` 的方法保持**向后兼容**,解析版为**新增**方法。
|
> 原 `get_*` 返回 `bytes`/`list[str]` 的方法保持**向后兼容**,解析版为**新增**方法。
|
||||||
@@ -283,7 +283,7 @@ CLI 开关:`--discover`(三种协议全测并据实修正 `protocols`,同
|
|||||||
| `tdx block [filename] [--limit 30] [--codes]` | 板块文件 下载+解析(block_*.dat → 成分股) |
|
| `tdx block [filename] [--limit 30] [--codes]` | 板块文件 下载+解析(block_*.dat → 成分股) |
|
||||||
| `tdx industry [codes...] [--limit 30] [--search 词]` | 行业分类 下载+解析(tdxhy.cfg) |
|
| `tdx industry [codes...] [--limit 30] [--search 词]` | 行业分类 下载+解析(tdxhy.cfg) |
|
||||||
| `tdx financial-list [--limit 30]` | 历史专业财报文件索引(gpcw.txt) |
|
| `tdx financial-list [--limit 30]` | 历史专业财报文件索引(gpcw.txt) |
|
||||||
| `tdx financial <filename> [--code X] [--limit 5] [--fields 4]` | 历史专业财报记录 下载+解析(gpcw*.zip) |
|
| `tdx financial <filename> [--code X] [--limit 5] [--fields 4]` | 历史专业财报记录 下载+解析(文件名自动纠正,见 `get_financial_records_parsed`) |
|
||||||
| `tdx server-info` | 服务器交易时段 |
|
| `tdx server-info` | 服务器交易时段 |
|
||||||
| `tdx market-stat` | 市场统计 |
|
| `tdx market-stat` | 市场统计 |
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -97,7 +97,7 @@ tdx industry --limit 30 # 只看前 30 条
|
|||||||
|
|
||||||
# 历史专业财报
|
# 历史专业财报
|
||||||
tdx financial-list # 索引:文件名 / MD5 / 大小(gpcw.txt)
|
tdx financial-list # 索引:文件名 / MD5 / 大小(gpcw.txt)
|
||||||
tdx financial gpcw20260331.zip --limit 5 # 下载 + 解压 + 解析
|
tdx financial gpcw20260331.zip --limit 5 # 下载 + 解析(服务器实际给 .dat 时自动回退)
|
||||||
tdx financial gpcw20260331.zip --code 600000 --fields 8 # 只取指定股票、打印更多字段
|
tdx financial gpcw20260331.zip --code 600000 --fields 8 # 只取指定股票、打印更多字段
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
+14
-1
@@ -118,7 +118,20 @@ async def finance_snapshot(symbols):
|
|||||||
print(fin.symbol, fin)
|
print(fin.symbol, fin)
|
||||||
```
|
```
|
||||||
|
|
||||||
历史专业财报(`gpcw*.zip`,含多报告期)走文件接口:
|
历史专业财报(`gpcw*`,含多报告期)走文件接口。
|
||||||
|
|
||||||
|
!!! warning "索引里的文件名与服务器实际不一致"
|
||||||
|
`tdxfin/gpcw.txt` 索引里写的是 `gpcwYYYYMMDD.zip`,但服务器实际只提供**未压缩的**
|
||||||
|
`tdxfin/gpcwYYYYMMDD.dat` —— 这些差异已由 `get_financial_records_parsed()` 内部处理,
|
||||||
|
直接把索引里的 `filename` 传进去即可。
|
||||||
|
|
||||||
|
另外索引里**含有尚未生成的占位条目**(`filesize` 只有百来字节),取它们会得到空列表。
|
||||||
|
想拿最新一期可用数据,先按体积过滤:
|
||||||
|
|
||||||
|
```python
|
||||||
|
usable = [fi for fi in infos if fi.filesize > 500_000] # 排除占位条目
|
||||||
|
records = await td.get_financial_records_parsed(usable[0].filename)
|
||||||
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
async def history_financials(code: str):
|
async def history_financials(code: str):
|
||||||
|
|||||||
+1
-1
@@ -34,7 +34,7 @@ asyncio.run(main())
|
|||||||
| 🗄️ **双层 TTL 缓存** | 内存 LRU + 磁盘 SQLite(WAL);TTL 分级:报价 5s / 分钟K线 60s / 日线当天 / 复权K线 1天 / 历史逐笔永久;`single-flight` 同键并发去重;缓存「已解析记录」,重复请求 0 网络 0 解析 |
|
| 🗄️ **双层 TTL 缓存** | 内存 LRU + 磁盘 SQLite(WAL);TTL 分级:报价 5s / 分钟K线 60s / 日线当天 / 复权K线 1天 / 历史逐笔永久;`single-flight` 同键并发去重;缓存「已解析记录」,重复请求 0 网络 0 解析 |
|
||||||
| ⚡ **并发分页** | 把大请求拆成显式 `start` 偏移的页,多连接并行拉取、按序拼接、失败换连接重试 |
|
| ⚡ **并发分页** | 把大请求拆成显式 `start` 偏移的页,多连接并行拉取、按序拼接、失败换连接重试 |
|
||||||
| 🔀 **双通道整合** | 标准通道(经典行情)+ MAC 通道(逐笔 / 复权 / 1分钟K线),按命令自动选路 |
|
| 🔀 **双通道整合** | 标准通道(经典行情)+ MAC 通道(逐笔 / 复权 / 1分钟K线),按命令自动选路 |
|
||||||
| 📄 **服务器文件解析** | 板块 `block_*.dat` / 行业 `tdxhy.cfg` / 历史财报 `gpcw*.zip` **下载即解析**成 dataclass(纯 stdlib),无需自己拆二进制 |
|
| 📄 **服务器文件解析** | 板块 `block_*.dat` / 行业 `tdxhy.cfg` / 历史财报 `gpcw*` **下载即解析**成 dataclass(纯 stdlib),无需自己拆二进制;文件名与索引不一致时自动纠正 |
|
||||||
| 🚀 **批量下载** | `get_bars` / `get_minutes` 传标的列表即多股票并发,连接池自动分配到不同服务器 |
|
| 🚀 **批量下载** | `get_bars` / `get_minutes` 传标的列表即多股票并发,连接池自动分配到不同服务器 |
|
||||||
| 📦 **零重型依赖** | 返回 `list[dataclass]`,pandas / polars 由调用方按需转换 |
|
| 📦 **零重型依赖** | 返回 `list[dataclass]`,pandas / polars 由调用方按需转换 |
|
||||||
|
|
||||||
|
|||||||
+68
-20
@@ -22,6 +22,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
|
import re
|
||||||
import warnings
|
import warnings
|
||||||
from datetime import date as _date, datetime
|
from datetime import date as _date, datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -61,7 +62,7 @@ from .models import (
|
|||||||
)
|
)
|
||||||
from .pool.ex_pool import ExPool
|
from .pool.ex_pool import ExPool
|
||||||
from .pool.health import HealthEngine
|
from .pool.health import HealthEngine
|
||||||
from .pool.pool import DynamicPool
|
from .pool.pool import DynamicPool, PoolTimeoutError
|
||||||
from .protocol.commands import (
|
from .protocol.commands import (
|
||||||
GetFinanceInfoCmd,
|
GetFinanceInfoCmd,
|
||||||
GetIndexBarsCmd,
|
GetIndexBarsCmd,
|
||||||
@@ -75,6 +76,7 @@ from .protocol.commands import (
|
|||||||
MacKlineCmd,
|
MacKlineCmd,
|
||||||
MacTransactionCmd,
|
MacTransactionCmd,
|
||||||
MAX_QUOTES,
|
MAX_QUOTES,
|
||||||
|
TdxDecodeError,
|
||||||
)
|
)
|
||||||
from .protocol.commands.ex_ext import (
|
from .protocol.commands.ex_ext import (
|
||||||
GetExHistoryTransactionDataCmd,
|
GetExHistoryTransactionDataCmd,
|
||||||
@@ -895,8 +897,9 @@ class TdxData:
|
|||||||
|
|
||||||
参数:
|
参数:
|
||||||
date: ``None``=今天;``YYYYMMDD``=历史某日(A股支持历史分时)。
|
date: ``None``=今天;``YYYYMMDD``=历史某日(A股支持历史分时)。
|
||||||
sampling: ``True`` 取缩略采样(约240个价格点,无时间;A股 0x254D,
|
sampling: ``True`` 取缩略采样(约 240 个价格点,无时间),``vol``/
|
||||||
扩展市场同命令),``vol``/``avg_price`` 为 0,点位序号在 ``fields["i"]``。
|
``avg_price`` 为 0,点位序号在 ``fields["i"]``。A股由分时数据派生,
|
||||||
|
扩展市场走 0x254D。
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
``list[MinuteBar]``,按入参标的顺序拼接,每条带 ``symbol``/``market``/
|
``list[MinuteBar]``,按入参标的顺序拼接,每条带 ``symbol``/``market``/
|
||||||
@@ -920,8 +923,17 @@ class TdxData:
|
|||||||
|
|
||||||
async def fetch() -> bytes:
|
async def fetch() -> bytes:
|
||||||
if sampling:
|
if sampling:
|
||||||
run = self._execute_ex if sym.is_ex else self._execute_mac
|
if sym.is_ex:
|
||||||
prices = await run(MacChartSamplingCmd(sym.market, sym.code))
|
prices = await self._execute_ex(
|
||||||
|
MacChartSamplingCmd(sym.market, sym.code))
|
||||||
|
else:
|
||||||
|
# ⚠️ 不能用 MacChartSamplingCmd(0x254D):那是 **EX 协议**命令,
|
||||||
|
# A股/标准通道的 7709 主机对它一律不响应(实测 3 台全 8s 超时,
|
||||||
|
# 叠加连接池 3 次重试 ≈24s 才报错)。改由分时(0x122D)派生价格点:
|
||||||
|
# 分时本身就是 240 点,语义与「缩略采样」一致且天然可用。
|
||||||
|
ticks = await self._execute_mac(
|
||||||
|
MacTickChartCmd(sym.market, sym.code, ymd))
|
||||||
|
prices = [b.price for b in ticks]
|
||||||
bars = [MinuteBar(price=float(p), vol=0.0, symbol=sym.text,
|
bars = [MinuteBar(price=float(p), vol=0.0, symbol=sym.text,
|
||||||
market=sym.market, code=sym.code, date=ymd,
|
market=sym.market, code=sym.code, date=ymd,
|
||||||
fields={"i": float(i)})
|
fields={"i": float(i)})
|
||||||
@@ -1273,28 +1285,60 @@ class TdxData:
|
|||||||
return parse_financial_file_list(await self.get_file("tdxfin/gpcw.txt"))
|
return parse_financial_file_list(await self.get_file("tdxfin/gpcw.txt"))
|
||||||
|
|
||||||
async def get_financial_records_parsed(self, filename: str) -> list[FinancialRecord]:
|
async def get_financial_records_parsed(self, filename: str) -> list[FinancialRecord]:
|
||||||
"""财务 zip(``tdxfin/gpcw*.zip``)解压解析 -> ``list[FinancialRecord]``。
|
"""财报数据解析 -> ``list[FinancialRecord]``。
|
||||||
|
|
||||||
|
可直接把 :meth:`get_financial_file_infos` 条目里的 ``filename`` 原样传进来:
|
||||||
|
内部会自动纠正「索引名与服务器实际文件名不一致」的问题(索引写
|
||||||
|
``gpcwYYYYMMDD.zip`` 且不带 ``tdxfin/`` 前缀,服务器实际只提供未压缩的
|
||||||
|
``tdxfin/gpcwYYYYMMDD.dat``),并兼容 zip 包与未压缩 dat 两种形态。
|
||||||
|
|
||||||
报告期优先取文件名中的 8 位日期,缺失时回退到 .dat 头部内嵌值。
|
报告期优先取文件名中的 8 位日期,缺失时回退到 .dat 头部内嵌值。
|
||||||
"""
|
"""
|
||||||
import io
|
|
||||||
import re
|
|
||||||
import zipfile
|
|
||||||
|
|
||||||
from .codec.financial import parse_financial_dat
|
from .codec.financial import parse_financial_dat
|
||||||
|
|
||||||
zip_data = await self.get_file(filename)
|
dat_data = await self._fetch_financial_dat(filename)
|
||||||
if not zip_data:
|
if not dat_data:
|
||||||
return []
|
return []
|
||||||
with zipfile.ZipFile(io.BytesIO(zip_data)) as zf:
|
match = re.search(r"(\d{8})", str(filename))
|
||||||
dat_names = [n for n in zf.namelist() if n.endswith(".dat")]
|
|
||||||
if not dat_names:
|
|
||||||
return []
|
|
||||||
dat_data = zf.read(dat_names[0])
|
|
||||||
match = re.search(r"(\d{8})", filename)
|
|
||||||
report_date = int(match.group(1)) if match else 0
|
report_date = int(match.group(1)) if match else 0
|
||||||
return parse_financial_dat(dat_data, report_date)
|
return parse_financial_dat(dat_data, report_date)
|
||||||
|
|
||||||
|
async def _fetch_financial_dat(self, filename: str) -> bytes:
|
||||||
|
"""[内部] 取回 gpcw 财报 ``.dat`` 原始字节,自动纠正服务器文件名差异。
|
||||||
|
|
||||||
|
``tdxfin/gpcw.txt`` 索引声明的名字(``gpcwYYYYMMDD.zip``、无目录前缀)与服务器
|
||||||
|
实际提供的文件(``tdxfin/gpcwYYYYMMDD.dat``、未压缩)不一致,且对不存在的名字
|
||||||
|
服务器**不报错、只回 0~1 字节空壳**。这里按候选名逐个尝试,并校验取回的字节
|
||||||
|
是否真的是 ``.dat``,返回第一个有效结果;全部失败返回 ``b""``。
|
||||||
|
|
||||||
|
候选顺序:索引声明的 ``.zip`` → 服务器实际的 ``.dat`` → 调用方原样名字(兜底)。
|
||||||
|
"""
|
||||||
|
from .codec.financial import extract_gpcw_dat
|
||||||
|
|
||||||
|
raw = str(filename).strip().replace("\\", "/")
|
||||||
|
base = raw.rsplit("/", 1)[-1]
|
||||||
|
stem = re.sub(r"\.(?:zip|dat)$", "", base, flags=re.IGNORECASE)
|
||||||
|
candidates = list(dict.fromkeys([
|
||||||
|
f"tdxfin/{stem}.zip",
|
||||||
|
f"tdxfin/{stem}.dat",
|
||||||
|
base,
|
||||||
|
]))
|
||||||
|
for name in candidates:
|
||||||
|
try:
|
||||||
|
blob = await self.get_file(name)
|
||||||
|
except (ConnectionError, OSError, TimeoutError,
|
||||||
|
TdxDecodeError, ValueError, PoolTimeoutError) as exc:
|
||||||
|
# 单个候选取回失败就换下一个(服务器对不存在的名字不一定报错)
|
||||||
|
log.debug("财报候选 %s 取回失败: %s", name, str(exc)[:80])
|
||||||
|
continue
|
||||||
|
dat = extract_gpcw_dat(blob)
|
||||||
|
if dat:
|
||||||
|
log.debug("财报文件命中: %s(%d 字节)", name, len(dat))
|
||||||
|
return dat
|
||||||
|
log.debug("财报候选 %s 非有效 gpcw 数据(%d 字节),继续尝试",
|
||||||
|
name, len(blob))
|
||||||
|
return b""
|
||||||
|
|
||||||
# ================================================================== #
|
# ================================================================== #
|
||||||
# 内部执行(连接池 + 失败换连接 + 分页)
|
# 内部执行(连接池 + 失败换连接 + 分页)
|
||||||
# ================================================================== #
|
# ================================================================== #
|
||||||
@@ -1553,9 +1597,13 @@ class TdxData:
|
|||||||
return [l.strip() for l in text.splitlines() if l.strip()]
|
return [l.strip() for l in text.splitlines() if l.strip()]
|
||||||
|
|
||||||
async def get_financial_records(self, filename: str) -> bytes:
|
async def get_financial_records(self, filename: str) -> bytes:
|
||||||
"""已废弃 -> :meth:`get_financial_records_parsed`。"""
|
"""已废弃 -> :meth:`get_financial_records_parsed`。
|
||||||
|
|
||||||
|
返回 gpcw 财报 ``.dat`` 原始字节(服务器给未压缩 ``.dat`` 时自动回退,
|
||||||
|
不再像旧实现那样静默返回 0~1 字节空壳);取不到时返回 ``b""``。
|
||||||
|
"""
|
||||||
_deprecated("get_financial_records", "get_financial_records_parsed")
|
_deprecated("get_financial_records", "get_financial_records_parsed")
|
||||||
return await self.get_file(filename)
|
return await self._fetch_financial_dat(filename)
|
||||||
|
|
||||||
async def get_company_info_category(self, market, code) -> list:
|
async def get_company_info_category(self, market, code) -> list:
|
||||||
"""已废弃 -> :meth:`get_f10`。"""
|
"""已废弃 -> :meth:`get_f10`。"""
|
||||||
|
|||||||
@@ -17,13 +17,19 @@
|
|||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
import struct
|
import struct
|
||||||
|
import zipfile
|
||||||
|
|
||||||
from ..models import FinancialFileInfo, FinancialRecord
|
from ..models import FinancialFileInfo, FinancialRecord
|
||||||
|
|
||||||
_HEADER_FMT = "<1hI1H3L"
|
_HEADER_FMT = "<1hI1H3L"
|
||||||
_INDEX_FMT = "<6sBL"
|
_INDEX_FMT = "<6sBL"
|
||||||
|
|
||||||
|
_HEADER_SIZE = struct.calcsize(_HEADER_FMT)
|
||||||
|
_INDEX_SIZE = struct.calcsize(_INDEX_FMT)
|
||||||
|
_ZIP_MAGIC = b"PK\x03\x04"
|
||||||
|
|
||||||
|
|
||||||
def parse_financial_file_list(data: bytes) -> list[FinancialFileInfo]:
|
def parse_financial_file_list(data: bytes) -> list[FinancialFileInfo]:
|
||||||
"""解析 tdxfin/gpcw.txt 内容(每行 ``filename,md5hash,filesize``)。"""
|
"""解析 tdxfin/gpcw.txt 内容(每行 ``filename,md5hash,filesize``)。"""
|
||||||
@@ -46,8 +52,58 @@ def parse_financial_file_list(data: bytes) -> list[FinancialFileInfo]:
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def looks_like_gpcw_dat(data: bytes) -> bool:
|
||||||
|
"""粗略判定字节流是否为 gpcw ``.dat``(校验 20 字节 header 的自洽性)。
|
||||||
|
|
||||||
|
用于把「真的取到了财报数据」与「服务器对不存在的文件名回的 0/1 字节空壳」区分开:
|
||||||
|
空壳要么长度不足、要么 header 全零,一律判否。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
data: 待判定的字节流。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
可疑时返回 True。
|
||||||
|
"""
|
||||||
|
if len(data) < _HEADER_SIZE:
|
||||||
|
return False
|
||||||
|
_unknown, _date, max_count, _u1, report_size, _u2 = struct.unpack(
|
||||||
|
_HEADER_FMT, data[:_HEADER_SIZE]
|
||||||
|
)
|
||||||
|
if max_count <= 0 or report_size <= 0 or report_size % 4 != 0:
|
||||||
|
return False
|
||||||
|
# 索引区必须放得下 max_count 条 11 字节条目
|
||||||
|
return _HEADER_SIZE + max_count * _INDEX_SIZE <= len(data)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_gpcw_dat(data: bytes) -> bytes:
|
||||||
|
"""从「zip 包」或「未压缩 dat」中取出 ``.dat`` 字节;无法识别时返回 ``b""``。
|
||||||
|
|
||||||
|
服务器**实际只提供未压缩的** ``tdxfin/gpcwYYYYMMDD.dat``,而 ``tdxfin/gpcw.txt``
|
||||||
|
索引里写的是 ``gpcwYYYYMMDD.zip``,因此两种形态都要能走通。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
data: zip 包字节或未压缩 ``.dat`` 字节。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
内层 / 原始的 ``.dat`` 字节;不是有效财报数据时返回 ``b""``。
|
||||||
|
"""
|
||||||
|
if not data:
|
||||||
|
return b""
|
||||||
|
if data.startswith(_ZIP_MAGIC):
|
||||||
|
try:
|
||||||
|
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
||||||
|
names = [n for n in zf.namelist() if n.lower().endswith(".dat")]
|
||||||
|
if not names:
|
||||||
|
return b""
|
||||||
|
inner = zf.read(names[0])
|
||||||
|
except (zipfile.BadZipFile, OSError, KeyError):
|
||||||
|
return b""
|
||||||
|
return inner if looks_like_gpcw_dat(inner) else b""
|
||||||
|
return data if looks_like_gpcw_dat(data) else b""
|
||||||
|
|
||||||
|
|
||||||
def parse_financial_dat(data: bytes, report_date: int = 0) -> list[FinancialRecord]:
|
def parse_financial_dat(data: bytes, report_date: int = 0) -> list[FinancialRecord]:
|
||||||
"""解析 gpcw*.zip 内的 .dat 二进制。
|
"""解析 gpcw ``.dat`` 二进制(zip 内的或服务器直接给的未压缩形式都行)。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
data: .dat 文件完整字节。
|
data: .dat 文件完整字节。
|
||||||
@@ -56,7 +112,7 @@ def parse_financial_dat(data: bytes, report_date: int = 0) -> list[FinancialReco
|
|||||||
Returns:
|
Returns:
|
||||||
FinancialRecord 列表;数据不足或字段非法时返回空列表。
|
FinancialRecord 列表;数据不足或字段非法时返回空列表。
|
||||||
"""
|
"""
|
||||||
header_size = struct.calcsize(_HEADER_FMT)
|
header_size = _HEADER_SIZE
|
||||||
if len(data) < header_size:
|
if len(data) < header_size:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
@@ -72,7 +128,7 @@ def parse_financial_dat(data: bytes, report_date: int = 0) -> list[FinancialReco
|
|||||||
if num_fields <= 0:
|
if num_fields <= 0:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
index_size = struct.calcsize(_INDEX_FMT)
|
index_size = _INDEX_SIZE
|
||||||
report_fmt = f"<{num_fields}f"
|
report_fmt = f"<{num_fields}f"
|
||||||
report_pack_size = struct.calcsize(report_fmt)
|
report_pack_size = struct.calcsize(report_fmt)
|
||||||
|
|
||||||
|
|||||||
@@ -156,12 +156,15 @@ def _dispatch(cmd) -> object:
|
|||||||
return [{"minutes": 570, "price": 10.0, "vol": 100.0, "direction": 0,
|
return [{"minutes": 570, "price": 10.0, "vol": 100.0, "direction": 0,
|
||||||
"zengcang": 1.0}]
|
"zengcang": 1.0}]
|
||||||
if n == "MacTickChartCmd":
|
if n == "MacTickChartCmd":
|
||||||
return [MinuteBar(price=10.0, vol=100.0, hour=9, minute=30)]
|
return [MinuteBar(price=p, vol=100.0, hour=9, minute=30 + i)
|
||||||
|
for i, p in enumerate((10.0, 10.1, 10.2))]
|
||||||
if n == "SymbolTickChartCmd":
|
if n == "SymbolTickChartCmd":
|
||||||
return [{"minutes": 570, "price": 10.0, "vol": 100.0, "avg": 10.0,
|
return [{"minutes": 570, "price": 10.0, "vol": 100.0, "avg": 10.0,
|
||||||
"momentum": 0.1}]
|
"momentum": 0.1}]
|
||||||
if n == "MacChartSamplingCmd":
|
if n == "MacChartSamplingCmd":
|
||||||
return [10.0, 10.1, 10.2]
|
# 刻意与 MacTickChartCmd 的 mock 数据不同:A股由分时派生、EX 用 0x254D,
|
||||||
|
# 靠返回值即可区分实际走了哪条命令(BUG-1 回归用)。
|
||||||
|
return [99.0, 98.0]
|
||||||
# ---- 公司信息 ----
|
# ---- 公司信息 ----
|
||||||
if n == "MacSymbolInfoCmd":
|
if n == "MacSymbolInfoCmd":
|
||||||
return SymbolSnapshot(
|
return SymbolSnapshot(
|
||||||
@@ -270,6 +273,13 @@ def _make_financial_zip() -> bytes:
|
|||||||
return buf.getvalue()
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _make_financial_dat() -> bytes:
|
||||||
|
"""未压缩 .dat(服务器实际提供的形式)。"""
|
||||||
|
entry = struct.pack("<6sBL", b"600000", 1, 31)
|
||||||
|
header = struct.pack("<1hI1H3L", 0, 20260331, 1, 0, 8, 0)
|
||||||
|
return header + entry + struct.pack("<2f", 1.0, 2.0)
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- #
|
# --------------------------------------------------------------------------- #
|
||||||
# fixture
|
# fixture
|
||||||
# --------------------------------------------------------------------------- #
|
# --------------------------------------------------------------------------- #
|
||||||
@@ -484,6 +494,69 @@ async def test_parsed_files(td):
|
|||||||
assert len(recs) == 1 and recs[0].report_date == 20260331
|
assert len(recs) == 1 and recs[0].report_date == 20260331
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 六之二、BUG 回归(真实联网实测发现,见 tests 说明)
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
async def test_financial_dat_fallback(td):
|
||||||
|
"""BUG-2 回归:索引写 ``.zip``,服务器只给未压缩 ``.dat`` 时必须能回退取到。
|
||||||
|
|
||||||
|
服务器对**不存在的**文件名不报错,而是回 0~1 字节空壳;旧实现会把空壳直接
|
||||||
|
丢给 ``zipfile`` → ``BadZipFile``。现在要求按候选名回退到 ``tdxfin/*.dat``。
|
||||||
|
"""
|
||||||
|
calls: list[str] = []
|
||||||
|
|
||||||
|
async def fake_get_file(name: str) -> bytes:
|
||||||
|
calls.append(name)
|
||||||
|
if name == "tdxfin/gpcw20260331.zip":
|
||||||
|
return b"" # 服务器没有 .zip
|
||||||
|
if name == "gpcw20260331.zip":
|
||||||
|
return b"\x00" # 裸名被路由到 MAC 通道 → 1 字节空壳
|
||||||
|
if name == "tdxfin/gpcw20260331.dat":
|
||||||
|
return _make_financial_dat()
|
||||||
|
return b""
|
||||||
|
|
||||||
|
with mock.patch.object(td, "get_file", new=fake_get_file):
|
||||||
|
recs = await td.get_financial_records_parsed("gpcw20260331.zip")
|
||||||
|
|
||||||
|
assert "tdxfin/gpcw20260331.dat" in calls, "必须回退尝试未压缩 .dat"
|
||||||
|
assert len(recs) == 1 and recs[0].report_date == 20260331
|
||||||
|
assert recs[0].code == "600000"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_financial_records_alias_not_silent(td):
|
||||||
|
"""BUG-2 回归:废弃别名取不到有效财报数据时应返回 ``b""``,而非 0~1 字节空壳。"""
|
||||||
|
import warnings
|
||||||
|
|
||||||
|
async def empty_get_file(name: str) -> bytes:
|
||||||
|
return b"\x00"
|
||||||
|
|
||||||
|
with mock.patch.object(td, "get_file", new=empty_get_file), warnings.catch_warnings():
|
||||||
|
warnings.simplefilter("ignore", DeprecationWarning)
|
||||||
|
got = await td.get_financial_records("gpcw20260331.zip")
|
||||||
|
assert got == b""
|
||||||
|
|
||||||
|
|
||||||
|
async def test_sampling_derives_from_tick_chart(td):
|
||||||
|
"""BUG-1 回归:A股 ``sampling=True`` 必须由分时(0x122D)派生。
|
||||||
|
|
||||||
|
``MacChartSamplingCmd``(0x254D) 是 **EX 协议**命令,7709 主机对它一律不响应
|
||||||
|
(实测 3 台各 10s 超时,叠加连接池重试 ≈24s 才报错)。两条路径的 mock 数据刻意
|
||||||
|
不同,以便从结果区分实际走的是哪条命令。
|
||||||
|
"""
|
||||||
|
# A股:得到分时派生值(10.0/10.1/10.2),而非 0x254D 的 99.0/98.0
|
||||||
|
a_share = await td.get_minutes("sh600000", sampling=True)
|
||||||
|
a_share_hist = await td.get_minutes("sh600000", date=20260811, sampling=True)
|
||||||
|
assert [b.price for b in a_share] == [10.0, 10.1, 10.2]
|
||||||
|
assert [b.price for b in a_share_hist] == [10.0, 10.1, 10.2]
|
||||||
|
assert all(b.vol == 0.0 and b.avg_price == 0 for b in a_share), "采样点无量/均价"
|
||||||
|
assert [b.fields["i"] for b in a_share] == [0.0, 1.0, 2.0], "点位序号在 fields['i']"
|
||||||
|
|
||||||
|
# EX:仍走 0x254D
|
||||||
|
ex = await td.get_minutes("hk00700", sampling=True)
|
||||||
|
assert [b.price for b in ex] == [99.0, 98.0]
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- #
|
# --------------------------------------------------------------------------- #
|
||||||
# 七、废弃别名(33 个)
|
# 七、废弃别名(33 个)
|
||||||
# --------------------------------------------------------------------------- #
|
# --------------------------------------------------------------------------- #
|
||||||
@@ -543,7 +616,11 @@ async def test_aliases_files(td):
|
|||||||
with warnings.catch_warnings():
|
with warnings.catch_warnings():
|
||||||
warnings.simplefilter("ignore", DeprecationWarning)
|
warnings.simplefilter("ignore", DeprecationWarning)
|
||||||
assert await td.get_financial_file_list() == ["abcd"]
|
assert await td.get_financial_file_list() == ["abcd"]
|
||||||
assert await td.get_financial_records("tdxfin/gpcw.txt") == b"abcd"
|
with mock.patch.object(td, "get_file",
|
||||||
|
new=mock.AsyncMock(
|
||||||
|
return_value=_make_financial_dat())):
|
||||||
|
assert await td.get_financial_records(
|
||||||
|
"gpcw20260331.zip") == _make_financial_dat()
|
||||||
assert isinstance(await td.get_company_info_category(1, "600000"), list)
|
assert isinstance(await td.get_company_info_category(1, "600000"), list)
|
||||||
assert isinstance(await td.get_company_info_content(
|
assert isinstance(await td.get_company_info_content(
|
||||||
1, "600000", "f.txt"), str)
|
1, "600000", "f.txt"), str)
|
||||||
@@ -578,7 +655,7 @@ async def test_aliases_goods(td):
|
|||||||
assert await td.get_goods_count(31) == 1 # 只有 1 条 market=31
|
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([(31, "00700")]), list)
|
||||||
assert isinstance(await td.get_goods_quotes_list(31), 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 await td.get_goods_chart_sampling(31, "00700") == [99.0, 98.0]
|
||||||
assert isinstance(await td.get_goods_tick_chart(31, "00700"), list)
|
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(31, "00700"), list)
|
||||||
assert isinstance(await td.get_goods_transaction_all(31, "00700"), list)
|
assert isinstance(await td.get_goods_transaction_all(31, "00700"), list)
|
||||||
|
|||||||
+140
-2
@@ -6,14 +6,19 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import io
|
import io
|
||||||
import struct
|
import struct
|
||||||
import unittest.mock as mock
|
|
||||||
import zipfile
|
import zipfile
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from pytdxdata.api import TdxData
|
from pytdxdata.api import TdxData
|
||||||
from pytdxdata.codec.block import infer_block_category, parse_block_dat
|
from pytdxdata.codec.block import infer_block_category, parse_block_dat
|
||||||
from pytdxdata.codec.financial import parse_financial_dat, parse_financial_file_list
|
from pytdxdata.codec.financial import (
|
||||||
|
extract_gpcw_dat,
|
||||||
|
looks_like_gpcw_dat,
|
||||||
|
parse_financial_dat,
|
||||||
|
parse_financial_file_list,
|
||||||
|
)
|
||||||
from pytdxdata.codec.industry import parse_tdxhy_cfg
|
from pytdxdata.codec.industry import parse_tdxhy_cfg
|
||||||
from pytdxdata.models import FinancialFileInfo, FinancialRecord, IndustryInfo, TdxBlock
|
from pytdxdata.models import FinancialFileInfo, FinancialRecord, IndustryInfo, TdxBlock
|
||||||
|
|
||||||
@@ -317,3 +322,136 @@ async def test_api_get_financial_records_parsed_no_date_in_name():
|
|||||||
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
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# looks_like_gpcw_dat / extract_gpcw_dat(BUG-2 修复的判据层)
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def test_looks_like_gpcw_dat_accepts_real_dat():
|
||||||
|
assert looks_like_gpcw_dat(_valid_two_record_dat()) is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_looks_like_gpcw_dat_rejects_short_shell():
|
||||||
|
"""服务器对不存在的文件名回的空壳(0~1 字节)必须判否。"""
|
||||||
|
assert looks_like_gpcw_dat(b"") is False
|
||||||
|
assert looks_like_gpcw_dat(b"\x00") is False
|
||||||
|
assert looks_like_gpcw_dat(b"abcd") is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_looks_like_gpcw_dat_rejects_zero_header():
|
||||||
|
"""长度够但 header 全零(max_count=0 / report_size=0)也要判否。"""
|
||||||
|
assert looks_like_gpcw_dat(b"\x00" * 64) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_looks_like_gpcw_dat_rejects_report_size_not_multiple_of_4():
|
||||||
|
data = _make_dat_raw([(b"600000", 1, 31)], struct.pack("<2f", 1.0, 2.0),
|
||||||
|
report_size=6)
|
||||||
|
assert looks_like_gpcw_dat(data) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_looks_like_gpcw_dat_rejects_truncated_index():
|
||||||
|
"""header 声称的条目数超出实际长度 -> 判否。"""
|
||||||
|
data = _make_dat_raw([(b"600000", 1, 31)], struct.pack("<2f", 1.0, 2.0),
|
||||||
|
max_count=100)
|
||||||
|
assert looks_like_gpcw_dat(data) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_gpcw_dat_from_uncompressed():
|
||||||
|
dat = _valid_two_record_dat()
|
||||||
|
assert extract_gpcw_dat(dat) == dat
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_gpcw_dat_from_zip():
|
||||||
|
dat = _valid_two_record_dat()
|
||||||
|
assert extract_gpcw_dat(_make_financial_zip(dat)) == dat
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_gpcw_dat_empty_and_garbage():
|
||||||
|
assert extract_gpcw_dat(b"") == b""
|
||||||
|
assert extract_gpcw_dat(b"\x00") == b""
|
||||||
|
assert extract_gpcw_dat(b"not a financial file") == b""
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_gpcw_dat_zip_without_dat_member():
|
||||||
|
assert extract_gpcw_dat(_make_financial_zip(b"x", inner_name="readme.txt")) == b""
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_gpcw_dat_zip_with_invalid_inner_dat():
|
||||||
|
"""zip 里虽有 .dat,但内容不是有效财报数据 -> 空。"""
|
||||||
|
assert extract_gpcw_dat(_make_financial_zip(b"\x00" * 4)) == b""
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_gpcw_dat_broken_zip():
|
||||||
|
"""以 PK 开头但不是合法 zip -> 空,不抛异常。"""
|
||||||
|
assert extract_gpcw_dat(b"PK\x03\x04broken-not-a-zip") == b""
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# TdxData._fetch_financial_dat 候选回退(BUG-2 回归)
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_fetch_financial_dat_falls_back_to_uncompressed_dat():
|
||||||
|
"""索引名 ``gpcw*.zip`` 取不到时,必须回退到服务器实际的 ``tdxfin/*.dat``。"""
|
||||||
|
td = _new_tdxdata()
|
||||||
|
dat = _valid_two_record_dat()
|
||||||
|
seen: list[str] = []
|
||||||
|
|
||||||
|
async def fake(name: str) -> bytes:
|
||||||
|
seen.append(name)
|
||||||
|
if name == "tdxfin/gpcw20260331.dat":
|
||||||
|
return dat
|
||||||
|
if name == "gpcw20260331.zip":
|
||||||
|
return b"\x00" # 裸名 -> MAC 路由 -> 1 字节空壳
|
||||||
|
return b"" # 带前缀的 .zip 不存在
|
||||||
|
|
||||||
|
with mock.patch.object(td, "get_file", new=fake):
|
||||||
|
got = await td._fetch_financial_dat("gpcw20260331.zip")
|
||||||
|
|
||||||
|
assert got == dat
|
||||||
|
assert seen == ["tdxfin/gpcw20260331.zip", "tdxfin/gpcw20260331.dat"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_fetch_financial_dat_prefers_declared_zip_when_present():
|
||||||
|
"""服务器若恢复提供 .zip,应优先用索引声明的那个名字。"""
|
||||||
|
td = _new_tdxdata()
|
||||||
|
dat = _valid_two_record_dat()
|
||||||
|
seen: list[str] = []
|
||||||
|
|
||||||
|
async def fake(name: str) -> bytes:
|
||||||
|
seen.append(name)
|
||||||
|
return _make_financial_zip(dat)
|
||||||
|
|
||||||
|
with mock.patch.object(td, "get_file", new=fake):
|
||||||
|
got = await td._fetch_financial_dat("tdxfin/gpcw20260331.zip")
|
||||||
|
|
||||||
|
assert got == dat
|
||||||
|
assert seen == ["tdxfin/gpcw20260331.zip"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_fetch_financial_dat_skips_raising_candidate():
|
||||||
|
"""某个候选取回时抛异常,不应中断,继续试后面的候选。"""
|
||||||
|
td = _new_tdxdata()
|
||||||
|
dat = _valid_two_record_dat()
|
||||||
|
|
||||||
|
async def fake(name: str) -> bytes:
|
||||||
|
if name.endswith(".zip"):
|
||||||
|
raise ConnectionError("模拟网络错误")
|
||||||
|
return dat
|
||||||
|
|
||||||
|
with mock.patch.object(td, "get_file", new=fake):
|
||||||
|
assert await td._fetch_financial_dat("gpcw20260331.zip") == dat
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_fetch_financial_dat_all_candidates_fail_returns_empty():
|
||||||
|
td = _new_tdxdata()
|
||||||
|
|
||||||
|
async def fake(name: str) -> bytes:
|
||||||
|
return b""
|
||||||
|
|
||||||
|
with mock.patch.object(td, "get_file", new=fake):
|
||||||
|
assert await td._fetch_financial_dat("gpcw20260331.zip") == b""
|
||||||
Reference in new issue
Block a user