Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8a9376adb | ||
|
|
1c2f2ac057 | ||
|
|
5d3465987d | ||
|
|
dd89a09643 | ||
|
|
a043bc9eb1 | ||
|
|
acde4de40d | ||
|
|
3d2c1252f1 | ||
|
|
605f97e5df | ||
|
|
16ba83ec01 | ||
|
|
1c740a9d48 | ||
|
|
75c2e33b68 | ||
|
|
32f565ecb9 | ||
|
|
16841e9ae3 | ||
|
|
bed6450992 | ||
|
|
c9892050c3 | ||
|
|
a836cda1b2 | ||
|
|
25ff6bbe06 | ||
|
|
5085cacf0d | ||
|
|
0d13066386 | ||
|
|
f5dc0f8076 | ||
|
|
031eefab4d | ||
|
|
3498dd7a4b | ||
|
|
c2ebc0ab91 | ||
|
|
71a6d68ed7 |
@@ -5,6 +5,13 @@ APP_ENCRYPTION_KEY=
|
||||
# the system settings; all accounts use the same backend market snapshot.
|
||||
TUSHARE_TOKEN=your_tushare_token_here
|
||||
|
||||
# Official xiaobai-datahub client. Read flags default on in config/datahub.config.json.
|
||||
# compose.yaml pins every DATAHUB_READ_* to 1 so leftover .env zeros cannot keep
|
||||
# official pages on the old APIs. Old website APIs are emergency fallback only.
|
||||
# DATAHUB_SHADOW_* can still override a single dataset.
|
||||
DATAHUB_BASE_URL=http://127.0.0.1:8766
|
||||
DATAHUB_TOKEN=
|
||||
|
||||
# Optional iFinD HTTP credential. The backend exchanges it for a short-lived
|
||||
# access token and never exposes either token to browsers.
|
||||
IFIND_REFRESH_TOKEN=your_ifind_refresh_token_here
|
||||
|
||||
@@ -8,6 +8,9 @@ data/*.db
|
||||
data/*.db-shm
|
||||
data/*.db-wal
|
||||
data/backups/
|
||||
datahub-data/
|
||||
xiaobai-datahub/data/
|
||||
xiaobai-datahub/.venv/
|
||||
data/*.bak
|
||||
data/*.backup
|
||||
*.log
|
||||
|
||||
+3
-1
@@ -54,7 +54,9 @@ background scheduler
|
||||
feature repository mixins; do not add feature queries to it.
|
||||
- `backend/jobs/` owns job definitions, locks, retries, idempotency, and persisted run state.
|
||||
`backend/jobs/service.py` is the application-facing owner of scheduler start/stop, manual
|
||||
refresh submission, and periodic refresh coordination.
|
||||
refresh submission, and periodic refresh coordination. `backend/jobs/refresh.py` owns
|
||||
whether a dashboard payload is a usable refresh result versus a failed job, and whether
|
||||
after-hours official catch-up is due.
|
||||
- `backend/llm/` owns model selection, membership/quota checks, fallback, provider transport,
|
||||
streaming rules, and call audit. Feature agents only prepare messages and interpret
|
||||
feature-specific results.
|
||||
|
||||
@@ -1,264 +1,46 @@
|
||||
# 小白复盘
|
||||
|
||||
> 一个给 A 股股民自己用的**盘后复盘工作台**。
|
||||
> 收盘以后打开它,把「今天市场到底发生了什么」按情绪、梯队、轮动、竞价、龙虎榜一条条看明白,再决定明天激进还是保守。
|
||||
面向 A 股盘后复盘的本地 Web 工作台。收盘后把涨停、炸板、连板梯队、板块轮动、集合竞价、龙虎榜等数据整理成可浏览的复盘界面;不接券商、不代为下单,也不提供个股推荐。
|
||||
|
||||
**一句话定位**:小白复盘是一套可以自己部署、自己掌控数据的 A 股盘后复盘工具。它把散落在各个行情软件里的涨停、炸板、连板梯队、板块轮动、集合竞价、龙虎榜数据,整理成一套**看得懂、能追问、可记录**的复盘界面。
|
||||
本目录是唯一正式源码。模块边界见 [ARCHITECTURE.md](ARCHITECTURE.md),产品与维护文档见 [docs/README.md](docs/README.md)。
|
||||
|
||||
它**不是**行情交易软件,**不接券商、不代为下单**,也不提供任何形式的个股推荐。
|
||||
## 主要功能
|
||||
|
||||
---
|
||||
登录后左侧共 16 个页面,另有一个内嵌页「策略持续跟踪」。交易日快照保存在本地 SQLite 数据库 `data/review.db`。
|
||||
|
||||
## 一、为什么值得试(项目亮点)
|
||||
- **情绪周期**:0–100 情绪温度与阶段判定(默认首页)
|
||||
- **涨停池 / 炸板池 / 跌停板 / 昨日涨停 / 涨停表现**:封板结构、炸板、跌停与昨日反馈
|
||||
- **市场天梯**:按连板高度排列的市场梯队
|
||||
- **板块轮动**:近若干交易日板块热力与成分下钻
|
||||
- **集合竞价**:盘前生命周期;9:30 后停止更新并冻结为复盘归档。当前数据源提供 9:25 最终竞价快照,不是动态虚拟撮合行情
|
||||
- **题材库 / 人气热榜 / 龙虎榜**:题材成分、双榜人气、席位与游资档案
|
||||
- **智能选股**(会员):六阶段策略、精选策略库、自然语言编译为受控公式后的确定性筛选与滚动回测;候选需手动加入后才进入五交易日跟踪
|
||||
- **问师**(会员):按选定的游资思维 Skill 单师对话;新增公开角色时在 `游资skills` 下增加含 `SKILL.md` 的目录,并在 `游资skills/mentor_catalog.json` 登记。管理员私有角色放在 `data/private-mentor-skills`(不进 Git / 镜像)
|
||||
- **问天**(会员):观势 / 观气 / 观心。卦象、干支、节气与气机由本地程序确定性计算,大模型只负责文字解释。此前仅冻结过界面视觉方案,现已解冻;问天可纳入后续数据与功能迁移,本阶段不主动重做视觉。
|
||||
- **我的复盘**:手工交易日志、每日复盘、提醒中心与复盘助手;不接券商、不自动下单
|
||||
|
||||
1. **先看情绪,再看个股**
|
||||
用一个 0–100 的「情绪温度」,把当天市场的冷热程度和它处在哪个阶段(冰点 → 修复 → 发酵 → 高潮 → 分化 → 退潮)直接摆在第一屏。先判断环境,再谈个股。
|
||||
全局能力:日间 / 夜间主题、股票代码悬停预览日 K 与分时、`Ctrl + K` 全局搜索。图表数据不写入主行情,也不参与情绪、选股或问天计算。
|
||||
|
||||
2. **说的就是短线玩家的话**
|
||||
晋级、断板、连板高度、梯队完整度、封单额、炸板……这些词不用解释,界面上原样呈现,不用再自己在行情软件里一层层翻。
|
||||
## 技术栈
|
||||
|
||||
3. **不会写公式,也能按自己的想法筛股票**
|
||||
可以直接写一句人话(比如「连续两天放量上涨且不是 ST」),系统会把它编译成受控公式再执行筛选。技术活儿交给程序,判断权始终在你手上。
|
||||
| 层面 | 说明 |
|
||||
| --- | --- |
|
||||
| 运行时 | Python 3.12;标准库 `ThreadingHTTPServer`,无独立 Web 框架 |
|
||||
| 依赖 | `requirements.txt` 仅含 `cryptography`;问天历法使用仓库内 `vendor/lunar_python` |
|
||||
| 数据库 | SQLite(WAL),默认文件 `data/review.db` |
|
||||
| 前端 | 原生 HTML / CSS / JavaScript,无打包、无构建步骤 |
|
||||
| 部署 | Docker / Docker Compose,或本机直接运行 `server.py` |
|
||||
| 安全 | 账号密码 scrypt 哈希;行情 Token 与模型密钥用 `APP_ENCRYPTION_KEY` 加密后存库 |
|
||||
|
||||
4. **有问题可以「问」**
|
||||
- **问师**:挑一位游资思维模型,系统自动把当天情绪、梯队、龙虎榜等数据喂给它,单师对话,边看数据边追问。
|
||||
- **问天**:一个偏传统文化视角的模块,分「观势 / 观气 / 观心」三部分,看盘之外也给自己留一段安静时间。
|
||||
## 环境要求
|
||||
|
||||
5. **复盘能留下来,而不是第二天就忘**
|
||||
交易日志可以记录当时的买卖逻辑和情绪标签(平静 / 笃定 / 犹豫 / 焦虑 / 冲动),配合每日复盘三问和提醒中心,帮自己看清是不是在情绪化操作。
|
||||
- Python 3.12(与 `Dockerfile` 一致)
|
||||
- 本机启动:能执行 `python` / `pip`
|
||||
- Docker 部署:Docker Engine 24+,Compose v2(`docker compose`)
|
||||
- 行情:部署者自行申请并配置 Tushare Pro Token;部分分时优先使用同花顺 iFinD(可选)
|
||||
- 问师、问天解释、复盘助手、自然语言编译公式:需配置 OpenAI 兼容接口;未配置时市场数据页仍可用
|
||||
|
||||
6. **数据在自己手里**
|
||||
所有数据存在部署机器本地的 SQLite 数据库里,账号密码用 scrypt 哈希保存,行情 Token 和模型密钥加密存放。没有云端账号,不上传个人交易记录。
|
||||
|
||||
7. **一套界面,白天晚上都能看**
|
||||
内置日间 / 夜间两套配色,股票代码上悬停就弹出日 K 与分时小图,`Ctrl + K` 可以全局搜索股票、板块和题材。
|
||||
|
||||
---
|
||||
|
||||
## 二、主要功能
|
||||
|
||||
界面左侧一共有 **16 个页面**,另有一个内嵌页面(策略持续跟踪)。下面按分组说明。
|
||||
|
||||
### 2.1 市场数据(登录即可用)
|
||||
|
||||
| 页面 | 解决什么问题 | 打开后能看到什么 |
|
||||
| --- | --- | --- |
|
||||
| **情绪周期** | 收盘后说不清市场整体冷热、处在什么阶段 | 0–100 情绪温度、升温 / 降温方向、六阶段判定、由五个维度(市场宽度 20、涨停生态 25、赚钱效应 30、连板结构 15、成交活跃度 10)加权算出 |
|
||||
| **涨停池** | 当天封板的票散在各处,看不出封板结构 | 按首板 / 2 板 / 3 板+ 筛选,含首封时间、开板次数、封单额、涨停原因 |
|
||||
| **炸板池** | 触板没封住容易被误当成涨停 | 距涨停还差多少、开了几次板、炸板原因 |
|
||||
| **跌停板** | 亏钱效应集中在哪不直观 | 连续跌停天数、风险线索、风险行业聚集提示 |
|
||||
| **昨日涨停** | 昨天追板的人今天怎么样 | 晋级 / 炸板 / 跌停 / 断板四类结果,加一条「兑现率」(收红口径)摘要 |
|
||||
| **涨停表现** | 梯队到底健不健康 | 按连板高度看晋级率、收红率、平均涨幅,并给出当日结论 |
|
||||
| **市场天梯** | 连板梯队靠手翻拼不出来 | 从首板逐层排到当天最高板(至少展示 5 层),配市场高度与梯队完整度指标 |
|
||||
| **板块轮动** | 热点是延续还是一日游 | 最近 9 个交易日、Top 12 板块的热力矩阵,点板块可跨日高亮看连续性,并可下钻到申万二级成分股 |
|
||||
| **集合竞价** | 9:25 的竞价信息太散 | 四个页签:重点异动 / 我的自选 / 全部候选 / 竞价一字;关注分满分 100,可按「超预期 / 符合预期 / 低于预期」筛选;9:30 后停止更新,冻结归档供复盘 |
|
||||
| **题材库** | 题材排行和成分股要开好几个网站 | 左边题材排行、右边成分股,题材上悬停直接出日 K / 分时预览 |
|
||||
| **人气热榜** | 各家榜单各看各的 | 同花顺 + 东方财富双榜汇总,可切单榜或看「双榜共识」 |
|
||||
| **龙虎榜** | 上榜明细和游资动向查起来费劲 | 每日明细、净买入 / 净卖出筛选、活跃游资,点游资可看当日操作,游资档案带席位归类 |
|
||||
|
||||
### 2.2 智能功能(会员可用)
|
||||
|
||||
| 页面 | 解决什么问题 | 打开后能看到什么 |
|
||||
| --- | --- | --- |
|
||||
| **智能选股** | 自己写条件门槛高,盘中手翻太累 | 三种模式:① 六阶段策略,当日行情更新后(15:10 之后)自动计算;② **29 套精选策略库**,每套都标注适用环境、失效风险与准入条件;③ 自定义选股,自然语言写条件 → 编译成受控公式 → 确定性筛选执行 → 滚动回测 |
|
||||
| **策略持续跟踪** | 选出来的票加完自选就忘了为什么选 | 只有手动加入的候选才进入跟踪,展示 T+1 开盘 / 收盘、T+3、T+5、最大涨幅与最大回撤,到期自动提醒 |
|
||||
| **问师** | 复盘时没人讨论、视角单一 | 选一位游资思维模型单师对话,系统按模型流派自动喂情绪、梯队、龙虎榜等对应数据,回答为流式输出并带动态追问 |
|
||||
| **问天** | 想换个视角看市场,也想让自己静下来 | **观势**:用市场数据生成三才六爻,用来观察「势」;**观气**:依干支、精确节气、五运六气观察「运」;**观心**:不看盘、不输问题,先准备 1 秒,接着做 5 轮「吸气 3 秒、停顿 2 秒、呼气 4 秒」,再以六次三枚铜钱起卦完成一次问心仪式 |
|
||||
| **我的复盘** | 交易散养、不复盘、情绪化操作 | 结构化交易日志(方向、价格、仓位、盈亏、逻辑、执行、情绪、标签)、每日复盘三问、提醒中心、复盘助手(读取你的日志与市场数据,给出分析和条件化计划) |
|
||||
|
||||
> 说明:卦象、干支、节气与气机关系全部由本地程序确定性计算,大模型只负责文字解释,不参与起卦,也不会改动结果。
|
||||
|
||||
### 2.3 全局能力
|
||||
|
||||
- 股票 / 板块 / 题材上悬停,弹出日 K 与分时快速预览
|
||||
- `Ctrl + K` 全局搜索
|
||||
- 日间 / 夜间双主题一键切换
|
||||
- 提醒中心集中查看策略跟踪与手工提醒
|
||||
- 登录页有一组会动的小 K 线小人(红涨绿跌)
|
||||
|
||||
---
|
||||
|
||||
## 三、特色页面展示
|
||||
|
||||
> 下面每个占位都写清了「这张图要展示什么」。补图时,把图片文件放进仓库的 `docs/images/` 目录、按占位里写好的文件名命名,然后将该占位块(引文整段)替换为「补图后替换本块」后面那行图片语法(去掉反引号)即可;图未补上之前,方框内的文字就是给补图人的说明,不影响阅读。
|
||||
|
||||
### 3.1 情绪周期
|
||||
|
||||
> **【图 1|情绪周期主界面(截图)】**
|
||||
> 展示:日间主题下情绪周期页整屏,需清楚露出 0–100 情绪温度大数字、当前阶段卡(如「发酵」)、以及温度变化曲线。
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 2|阶段与五维构成(截图)】**
|
||||
> 展示:阶段卡与五个维度的评分构成(市场宽度、涨停生态、赚钱效应、连板结构、成交活跃度),体现「温度不是拍脑袋来的」。
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 3|日距切换(动图,约 4 秒)】**
|
||||
> 展示:在 10 / 20 / 60 日之间切换查看温度走势,动作要慢一点,让人看清曲线在动。
|
||||
> 补图后替换本块:``
|
||||
|
||||
### 3.2 市场天梯
|
||||
|
||||
> **【图 4|连板梯队全景(截图)】**
|
||||
> 展示:从首板一路排到当天最高板的分层结构,右侧「市场高度」与「梯队完整度」两个指标要同时入镜。
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 5|展开 / 收起交互(动图,约 4 秒)】**
|
||||
> 展示:点击展开某高度的成分股再收起,说明每一层都能点开看细节。
|
||||
> 补图后替换本块:``
|
||||
|
||||
### 3.3 涨停相关股池
|
||||
|
||||
> **【图 6|涨停池与炸板池(截图,两张并排)】**
|
||||
> 展示:左为涨停池(含首封时间、开板次数、封单额、涨停原因),右为炸板池(含距涨停、开板次数、炸板原因)。
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 7|昨日涨停与涨停表现(截图,两张并排)】**
|
||||
> 展示:左为昨日涨停的四类结果与兑现率摘要,右为涨停表现按连板高度列出的晋级率、收红率、平均涨幅与当日结论。
|
||||
> 补图后替换本块:``
|
||||
|
||||
### 3.4 板块轮动
|
||||
|
||||
> **【图 8|9 日热力矩阵(截图)】**
|
||||
> 展示:最近 9 个交易日、Top 12 板块的强度色阶矩阵,含强度图例。
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 9|点板块跨日高亮(动图,约 6 秒)】**
|
||||
> 展示:点选某个板块后,该板块在 9 天里的位置被高亮,直观看出「延续」还是「一日游」;再点开看下钻的申万二级成分股。
|
||||
> 补图后替换本块:``
|
||||
|
||||
### 3.5 集合竞价
|
||||
|
||||
> **【图 10|竞价中心与关注分(截图)】**
|
||||
> 展示:重点异动页签下的候选列表,关注分列(满分 100)与「超预期 / 符合预期 / 低于预期」筛选条要看得见,右侧的题材承接卡片一并入镜。
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 11|竞价生命周期(截图或示意静态图)】**
|
||||
> 展示:9:15 前预告 → 9:15–9:25 等待最终竞价 → 9:25–9:30 读取最终竞价 → 9:30 后冻结归档这四个节点。**建议用静态图表达,不做盘中动态录屏,避免被误解为实时撮合行情。**
|
||||
> 补图后替换本块:``
|
||||
|
||||
### 3.6 龙虎榜
|
||||
|
||||
> **【图 12|龙虎榜明细与净买卖(截图)】**
|
||||
> 展示:每日上榜明细表,净买入 / 净卖出筛选条,以及活跃游资区域。
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 13|游资档案(截图)】**
|
||||
> 展示:游资档案详情,含席位归类与当日操作列表。
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 14|点游资看当日操作(动图,约 5 秒)】**
|
||||
> 展示:在明细里点某个游资,弹出它当天的全部操作,说明「席位 ↔ 个股」是打通的。
|
||||
> 补图后替换本块:``
|
||||
|
||||
### 3.7 智能选股
|
||||
|
||||
> **【图 15|29 套精选策略库(截图)】**
|
||||
> 展示:策略库列表,画面里要能数出策略卡片,并露出其中一张的「适用环境 / 失效风险 / 准入条件」。
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 16|自然语言写公式全流程(动图,约 15 秒,可加速)】**
|
||||
> 展示:输入一句人话 → 编译成受控公式 → 执行筛选 → 返回候选表 → 加入持续跟踪,完整走一遍。**本图是全篇技术含量最高的一张,务必配「不构成投资建议」角标。**
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 17|策略持续跟踪(截图)】**
|
||||
> 展示:某个候选的 T+1 开盘 / 收盘、T+3、T+5、最大涨幅与最大回撤。
|
||||
> 补图后替换本块:``
|
||||
|
||||
### 3.8 问师
|
||||
|
||||
> **【图 18|问师对话(截图)】**
|
||||
> 展示:模型选择区与一段已完成的对话,回答中引用了情绪、梯队、龙虎榜等真实市场数据。
|
||||
> 补图后替换本块:``
|
||||
|
||||
### 3.9 问天
|
||||
|
||||
> **【图 19|观势(截图)】**
|
||||
> 展示:由市场数据生成的三才六爻卦象图,以及六爻与市场数据的对应关系。
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 20|观气(截图)】**
|
||||
> 展示:干支、精确节气、五运六气与客主加临关系的呈现。
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 21|观心(截图)】**
|
||||
> 展示:观心呼吸引导界面(准备 1 秒 + 「吸 3 秒、顿 2 秒、呼 4 秒」共 5 轮),以及六次三枚铜钱起卦的界面。
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 22|起卦动效(动图,约 10 秒)】**
|
||||
> 展示:铜钱起卦与六爻推演的现有效果。**只录现有动画,不做任何页面改动;全片挂「传统文化娱乐化观察,非预测」角标。**
|
||||
> 补图后替换本块:``
|
||||
|
||||
### 3.10 我的复盘
|
||||
|
||||
> **【图 23|交易日志与情绪标签(截图)】**
|
||||
> 展示:一条交易记录的完整字段,并把情绪五标签(平静 / 笃定 / 犹豫 / 焦虑 / 冲动)放大到看得清。
|
||||
> 补图后替换本块:``
|
||||
|
||||
> **【图 24|复盘助手(动图,约 8 秒)】**
|
||||
> 展示:复盘助手读取个人日志与市场数据后,流式输出一段分析与条件化计划。
|
||||
> 补图后替换本块:``
|
||||
|
||||
### 3.11 全局细节
|
||||
|
||||
> **【图 25|四个小细节(截图,四宫格拼图)】**
|
||||
> 展示:① 代码悬停弹出的日 K / 分时预览;② `Ctrl + K` 全局搜索;③ 日间 / 夜间双主题对比;④ 登录页会动的小 K 线小人。
|
||||
> 补图后替换本块:``
|
||||
|
||||
---
|
||||
|
||||
## 四、适合谁用
|
||||
|
||||
- **每天收盘后不知道从哪看起的散户**:先给一个情绪温度和阶段,再往下拆。
|
||||
- **做短线、看连板梯队的人**:晋级、断板、高度、完整度都在一个页面里。
|
||||
- **想按自己的条件筛股票、但不会写公式的人**:说人话就行。
|
||||
- **知道自己「管不住手」的人**:交易日志 + 情绪标签 + 每日复盘三问,把情绪化操作摆到自己面前。
|
||||
- **在意数据隐私、想把工具放在自己机器上的人**:私有部署,数据不出本机。
|
||||
- **对传统文化视角感兴趣的玩家**:问天的观势 / 观气 / 观心提供了另一种看市场的方式。
|
||||
|
||||
**不太适合**:想要一键自动下单的人(本项目不接券商);想要「跟着买就能赚」的人(本项目不提供任何形式的投资建议)。
|
||||
|
||||
---
|
||||
|
||||
## 五、一天怎么用(典型流程)
|
||||
|
||||
1. **收盘后 10 分钟:定环境**
|
||||
打开「情绪周期」,看温度多少、在哪个阶段、是升温还是降温。先定下明天的基调是激进还是保守。
|
||||
|
||||
2. **看结构:谁在涨、涨到几板**
|
||||
进「市场天梯」看连板梯队和市场高度,再到「涨停池 / 炸板池 / 跌停板」看当天的封板结构与亏钱效应。
|
||||
|
||||
3. **看延续:热点有没有搬家**
|
||||
进「板块轮动」,点几个强势板块,看它们在最近 9 天是连续走强还是只有一天行情。
|
||||
|
||||
4. **看结果:昨天追板的人今天怎么样**
|
||||
进「昨日涨停」和「涨停表现」,对照梯队健康度,检验自己的判断。
|
||||
|
||||
5. **查人气与席位**
|
||||
「人气热榜」看双榜共识,「龙虎榜」看活跃游资当天做了什么。
|
||||
|
||||
6. **按自己的条件选一批候选**
|
||||
进「智能选股」,要么用六阶段策略或 29 套精选策略,要么直接写一句人话让它编译成公式。选出来的候选**手动**加入「策略持续跟踪」,后面 T+1 / T+3 / T+5 会自动提醒你回看。
|
||||
|
||||
7. **有疑问就问**
|
||||
「问师」按游资思维模型边看数据边追问;想静一静就去「问天」做一次观心。
|
||||
|
||||
8. **记下来**
|
||||
在「我的复盘」里写当天交易日志(含情绪标签)和复盘三问。第二天开盘前,先回看昨天的记录。
|
||||
|
||||
---
|
||||
|
||||
## 六、部署与访问
|
||||
|
||||
> 本项目为**私有部署的个人工具**,没有官方在线版,也不提供公共账号。
|
||||
|
||||
- **部署方式**:仓库内提供 `Dockerfile` 与 `compose.yaml`,在已有 Docker 环境的机器上即可启动;也可直接用 Python 运行 `server.py` 在本机启动。
|
||||
- **访问方式**:部署完成后通过浏览器访问该机器上的服务端口(默认 8765),**具体地址由部署者自己决定**。出于安全考虑,本文档不写任何内网 IP、账号、密码或密钥。
|
||||
- **数据存放**:所有行情快照、复盘记录与账号数据都存在部署机器本地的 SQLite 数据库文件中(`data/review.db`),随 `data/` 目录一起备份即可。
|
||||
- **账号**:首次使用先注册,第一个注册的账号自动成为管理员,之后注册的默认为普通用户。
|
||||
- **数据来源**:行情数据来自 Tushare Pro 等第三方数据接口(部分分时数据优先使用同花顺 iFinD),**需要部署者自己申请并配置 Token**;部分接口的可用性取决于数据源方的授权与积分权限,个别数据缺失时页面会明确提示,不会用估算值顶替。
|
||||
- **大模型功能**:问师、问天解释、复盘助手、自然语言编译公式等需要配置一个 OpenAI 兼容的接口,由部署者自行配置与管理额度;未配置时这些对话与解释功能不可用,市场数据部分不受影响。
|
||||
|
||||
### 本机启动
|
||||
## 安装与启动
|
||||
|
||||
仓库根目录即为运行目录(`server.py`、`requirements.txt` 都在根目录)。
|
||||
|
||||
@@ -267,94 +49,90 @@ python -m pip install -r requirements.txt
|
||||
python server.py
|
||||
```
|
||||
|
||||
默认监听本机回环地址、端口 `8765`(仅本机浏览器可访问)。首次使用先注册账号。主行情不再回退演示数据:盘前、非交易日或临时取数失败时沿用最近真实收盘快照;没有任何真实快照时,页面会提示等待管理员完成首次同步。
|
||||
默认监听 `127.0.0.1:8765`(仅本机可访问)。浏览器打开该地址,首次使用先注册账号;第一个账号自动成为管理员,之后注册的默认为普通用户。
|
||||
|
||||
Windows 下若需要后台启动,并把日志、进程号和 Python 缓存统一写入 `runtime/`(不在源码根目录产生运行文件),可使用:
|
||||
主行情不再回退演示数据:盘前、非交易日或临时取数失败时沿用最近真实收盘快照;没有任何真实快照时,页面会提示等待管理员完成首次同步。
|
||||
|
||||
可选参数:
|
||||
|
||||
```bash
|
||||
python server.py --host 127.0.0.1 --port 8765
|
||||
```
|
||||
|
||||
Windows 下若需要后台启动,并把日志、进程号和 Python 缓存写入 `runtime/`(不在源码根目录产生运行文件):
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File tools/start_local.ps1
|
||||
```
|
||||
|
||||
### Docker 部署
|
||||
该脚本默认端口为 `8797`。统一验收:
|
||||
|
||||
局域网或服务器部署使用仓库根目录的 `Dockerfile` 与 `compose.yaml`。完整的迁移、持久化、防火墙、备份和恢复步骤见 [DOCKER_DEPLOY.md](DOCKER_DEPLOY.md)。
|
||||
```bash
|
||||
python tools/verify_baseline.py
|
||||
```
|
||||
|
||||
### 系统与账号配置
|
||||
涉及运行时或前端时再加 `--e2e`(Playwright)。
|
||||
|
||||
管理员通过页面右上角「系统管理」保存公共 Tushare Token、平台主/辅助模型、会员每日额度和后台刷新开关。所有用户读取同一份 SQLite 行情快照,不再分别配置行情 Token。
|
||||
## Docker 使用
|
||||
|
||||
`.env` 中的 Tushare 和平台 LLM 配置只用于初始化系统配置,密钥不会返回到浏览器。请将 `.env` 与数据库一起备份,丢失 `APP_ENCRYPTION_KEY` 后无法恢复加密资料。
|
||||
局域网或服务器部署使用仓库根目录的 `Dockerfile` 与 `compose.yaml`。容器监听 `8765`,默认以非 root 用户运行,并把宿主机 `./data` 挂到容器内 `/app/data`。
|
||||
|
||||
普通用户在「账号设置」中维护个人资料、查看会员状态和修改密码,不配置个人 LLM。有效会员自动使用平台模型;管理员可在「系统管理」中手动开通、续期、停用会员。平台模型受管理员设置的每日调用次数限制,管理员账号始终可用。
|
||||
1. 复制 `.env.example` 为 `.env`,填入 `APP_ENCRYPTION_KEY` 以及行情 / 模型等初始化配置。密钥不会返回到浏览器。
|
||||
2. `compose.yaml` 构建时要求带上当前 Git 提交号,避免打出无版本标签的镜像:
|
||||
|
||||
新增公开问师角色时,在 `游资skills` 下增加一个包含 `SKILL.md` 的独立目录,并在 `游资skills/mentor_catalog.json` 中登记。管理员私有角色放在 `data/private-mentor-skills`,该目录不进入 Git 或 Docker 镜像,且只会出现在管理员的问师列表中。
|
||||
```bash
|
||||
export XIAOBAI_GIT_REV="$(git rev-parse HEAD)"
|
||||
export XIAOBAI_GIT_SHORT="$(git rev-parse --short=7 HEAD)"
|
||||
docker compose build
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
### 相关文档
|
||||
3. 检查健康接口:
|
||||
|
||||
- [ARCHITECTURE.md](ARCHITECTURE.md) — 模块边界与源码职责
|
||||
```bash
|
||||
docker compose ps
|
||||
curl http://127.0.0.1:8765/api/health
|
||||
```
|
||||
|
||||
健康响应类似 `{"ok": true, "storage": "sqlite", "account_required": true}`。
|
||||
|
||||
完整的迁移、持久化、防火墙、备份、恢复与正式线构建入口见 [DOCKER_DEPLOY.md](DOCKER_DEPLOY.md)。`.env` 必须与数据库成对备份;丢失 `APP_ENCRYPTION_KEY` 后无法恢复加密资料。
|
||||
|
||||
## 目录与配置
|
||||
|
||||
```text
|
||||
server.py 进程入口
|
||||
backend/ 服务、路由、数据、任务、LLM
|
||||
frontend/ 无构建前端(shared + pages)
|
||||
config/ 页面 / API / 任务等注册表
|
||||
data/ SQLite 与私有数据(数据库文件不进 Git)
|
||||
runtime/ 本地日志、PID、缓存(不进 Git)
|
||||
tools/ 启动、验收与构建辅助脚本
|
||||
游资skills/ 公开问师角色
|
||||
vendor/ 本地第三方库(含 lunar-python)
|
||||
Dockerfile
|
||||
compose.yaml
|
||||
.env.example 环境变量模板(复制为 .env 后填写)
|
||||
```
|
||||
|
||||
管理员通过页面右上角「系统管理」保存公共 Tushare Token、平台主/辅助模型、会员每日额度和后台刷新开关。所有用户读取同一份 SQLite 行情快照。`.env` 中的 Tushare 和平台 LLM 配置只用于初始化系统配置。
|
||||
|
||||
普通用户在「账号设置」中维护个人资料、查看会员状态和修改密码,不配置个人 LLM。有效会员使用平台模型;管理员可开通、续期、停用会员。平台模型受每日调用次数限制,管理员账号始终可用。
|
||||
|
||||
相关文档:
|
||||
|
||||
- [ARCHITECTURE.md](ARCHITECTURE.md) — 模块边界
|
||||
- [docs/README.md](docs/README.md) — 交接手册入口
|
||||
- [DOCKER_DEPLOY.md](DOCKER_DEPLOY.md) — Docker 部署、备份与恢复
|
||||
- [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) — 第三方授权(含问天历法库)
|
||||
- [AGENTS.md](AGENTS.md) — 维护约束
|
||||
|
||||
**技术组成(简要)**
|
||||
## 注意事项与免责声明
|
||||
|
||||
| 层面 | 说明 |
|
||||
| --- | --- |
|
||||
| 后端 | Python 3.12,仅用标准库自带的 HTTP 服务与自研路由,第三方依赖极少 |
|
||||
| 数据库 | SQLite(WAL 模式),单文件,易备份 |
|
||||
| 前端 | 原生 JavaScript + HTML,无构建工具、无打包步骤,改完刷新即可 |
|
||||
| 部署 | Docker / Docker Compose,或本机直接运行 |
|
||||
| 安全 | 账号密码 scrypt 哈希存储;行情 Token 与模型密钥使用 `APP_ENCRYPTION_KEY` 加密后存库,密钥与数据库需一起备份 |
|
||||
|
||||
---
|
||||
|
||||
## 七、免责声明
|
||||
|
||||
- 本项目是一个**个人研究与复盘工具**,所提供的全部数据、指标、候选与文字分析,**均不构成投资建议、证券推荐或买卖要约**。
|
||||
- 本项目**不接券商、不代为下单**,交易日志只做手工记录与统计,不代表任何实际成交。
|
||||
- 情绪温度、阶段判定、连板梯队、策略筛选等均为**基于公开数据的统计与规则计算结果**,不预测未来走势,不保证任何收益。历史统计与回测结果不代表未来表现。
|
||||
- 「问天」模块属于**传统文化视角的娱乐化观察**,卦象、干支、节气与气机关系由本地程序确定性生成,用于换个角度看市场和自我觉察,**不具备预测功能,不得作为投资依据**。
|
||||
- 行情数据来自第三方接口,可能存在延迟、缺失或口径调整;页面会在数据不可用时明确提示,请以交易所与券商正式披露的数据为准。
|
||||
- 本项目是个人研究与复盘工具,全部数据、指标、候选与文字分析均不构成投资建议、证券推荐或买卖要约。
|
||||
- 不接券商、不代为下单。交易日志只做手工记录与统计,不代表实际成交。
|
||||
- 情绪温度、阶段判定、连板梯队、策略筛选等均为基于公开数据的统计与规则计算,不预测走势,不保证收益。
|
||||
- 「问天」属于传统文化视角的观察工具,不具备预测功能,不得作为投资依据。问天不是永久冻结区:此前只冻结过界面视觉方案,现已解冻,后续数据与功能迁移可以纳入。
|
||||
- 行情来自第三方接口,可能延迟、缺失或口径调整;不可用时页面会明确提示,请以交易所与券商正式披露为准。
|
||||
- 不要把服务端口直接暴露到公网。不要把 Token、密码、密钥、数据库或 `.env` 提交进 Git。
|
||||
- 股市有风险,入市需谨慎。投资决策及其后果由使用者本人承担。
|
||||
|
||||
---
|
||||
|
||||
## 附:精简版项目推荐语
|
||||
|
||||
> 下面三段可以单独整段复制转发,不需要带图也能看懂。
|
||||
|
||||
### 一句话版(约 60 字,适合评论区、群聊快速安利)
|
||||
|
||||
> 小白复盘:一个自己部署的 A 股盘后复盘工作台——情绪、梯队、轮动、龙虎榜一页页看明白;说人话就能选股,不荐股、不下单,数据只存自己机器。
|
||||
|
||||
### 短版(约 320 字,适合社交平台、群聊、朋友圈)
|
||||
|
||||
> 发现一个挺特别的 A 股盘后复盘工具,叫「小白复盘」。
|
||||
>
|
||||
> 它不荐股、也不下单,就专心做一件事:把收盘后散落在各个软件里的信息整理成人看得懂的样子。打开先给你一个 0–100 的情绪温度和「冰点→修复→发酵→高潮→分化→退潮」六个阶段,让你先知道今天是什么环境;然后连板梯队、涨停炸板、板块轮动的 9 天热力图、集合竞价、龙虎榜游资动向,一页一页往下看。
|
||||
>
|
||||
> 最惊喜的是不会写公式也能选股——直接写一句人话,它帮你编译成条件去筛。还有「问师」可以按游资思维跟你对话,「问天」用卦象换个角度看市场、也让你静一静。
|
||||
>
|
||||
> 数据存在自己机器上的本地数据库里,私有部署,不上传。
|
||||
>
|
||||
> 提醒一句:它只是个把信息摆清楚的工具,不荐股也不下单,不构成投资建议。
|
||||
|
||||
### 稍长版(约 580 字,适合发论坛、公众号、仓库简介)
|
||||
|
||||
> **小白复盘 —— 给 A 股股民自己的盘后复盘工作台**
|
||||
>
|
||||
> 收盘以后,你是怎么复盘的?在好几个软件之间来回切,还是干脆不复盘?
|
||||
>
|
||||
> 小白复盘是一套可以自己部署的 A 股盘后复盘工具。它把涨停、炸板、跌停、连板梯队、板块轮动、集合竞价、龙虎榜这些散落各处的数据,整理成 16 个看得懂的页面:
|
||||
>
|
||||
> - **情绪周期**:0–100 情绪温度 + 六阶段判定,由市场宽度、涨停生态、赚钱效应、连板结构、成交活跃度五个维度加权算出,先看环境再看个股。
|
||||
> - **市场天梯**:从首板一路排到当天最高板,配市场高度与梯队完整度。
|
||||
> - **板块轮动**:近 9 个交易日 Top 12 板块热力矩阵,点一下就能看出热点是延续还是一日游。
|
||||
> - **集合竞价**:关注分满分 100,9:30 后自动冻结归档,专门留给复盘看。
|
||||
> - **龙虎榜**:席位明细、活跃游资、游资档案打通,点游资就能看它当天做了什么。
|
||||
> - **智能选股**:29 套精选策略(每套都写了适用环境和失效风险),也可以直接写一句人话,让它编译成公式去筛选。
|
||||
> - **问师 / 问天 / 我的复盘**:一个陪你按游资思维聊数据,一个用传统卦象换个角度看市场,一个帮你记下每笔交易的逻辑和情绪。
|
||||
>
|
||||
> 它不接券商、不代为下单,也不给出任何个股推荐——只负责把信息摆清楚,判断始终在你自己手里。所有数据存在你自己机器的本地 SQLite 里,私有部署,不上传。
|
||||
>
|
||||
> 项目私有部署、无公共在线版;文中所有功能描述均对应现有实现,不构成投资建议,市场有风险。
|
||||
|
||||
@@ -1,11 +1,23 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from http.server import ThreadingHTTPServer
|
||||
from typing import Any
|
||||
|
||||
|
||||
def configure_logging() -> None:
|
||||
"""让 INFO 级结构化日志(含 datahub 影子对比报告)落到容器日志。"""
|
||||
if logging.getLogger().handlers:
|
||||
return
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
)
|
||||
|
||||
|
||||
def main(handler_class: type[Any] | None = None, service: Any | None = None) -> None:
|
||||
configure_logging()
|
||||
if handler_class is None or service is None:
|
||||
from backend.application import RequestHandler, SERVICE
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ from backend.features.accounts.security import SecretVault
|
||||
def environment_credentials(environment: Mapping[str, str]) -> dict[str, str]:
|
||||
return {
|
||||
"tushare_token": str(environment.get("TUSHARE_TOKEN") or "").strip(),
|
||||
"datahub_token": str(environment.get("DATAHUB_TOKEN") or "").strip(),
|
||||
"datahub_base_url": str(environment.get("DATAHUB_BASE_URL") or "").strip(),
|
||||
"ifind_refresh_token": str(environment.get("IFIND_REFRESH_TOKEN") or "").strip(),
|
||||
"ifind_access_token": str(environment.get("IFIND_ACCESS_TOKEN") or "").strip(),
|
||||
"platform_llm_primary_api_key": str(
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
from backend.data.datahub.bridge import DatahubAwareTushareClient, DatahubBridge
|
||||
from backend.data.datahub.client import DatahubClient, DatahubResponse
|
||||
from backend.data.datahub.errors import DatahubError
|
||||
from backend.data.datahub.settings import DATASETS, DatahubSettings, DatasetFlags
|
||||
|
||||
__all__ = [
|
||||
"DATASETS",
|
||||
"DatahubAwareTushareClient",
|
||||
"DatahubBridge",
|
||||
"DatahubClient",
|
||||
"DatahubError",
|
||||
"DatahubResponse",
|
||||
"DatahubSettings",
|
||||
"DatasetFlags",
|
||||
]
|
||||
@@ -0,0 +1,542 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from typing import Any, Callable
|
||||
|
||||
from backend.data.datahub.client import DatahubClient, DatahubResponse
|
||||
from backend.data.datahub.compare import compare_rows
|
||||
from backend.data.datahub.errors import DatahubError
|
||||
from backend.data.datahub.native import (
|
||||
API_TO_DATASET,
|
||||
filter_calendar_rows,
|
||||
filter_stock_rows,
|
||||
project_fields,
|
||||
to_native_rows,
|
||||
yyyymmdd,
|
||||
)
|
||||
from backend.data.datahub.redact import redact_text, redact_value
|
||||
from backend.data.datahub.route_state import LEDGER
|
||||
from backend.data.datahub.settings import DatahubSettings
|
||||
from backend.data.providers.tushare_client import TushareClient
|
||||
|
||||
LOGGER = logging.getLogger("xiaobai.datahub")
|
||||
ShadowSink = Callable[[dict[str, Any]], None]
|
||||
|
||||
|
||||
def _usable_intraday_points(rows: list[Any]) -> list[dict[str, Any]]:
|
||||
points: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
try:
|
||||
close = float(row.get("close") or 0)
|
||||
except (TypeError, ValueError):
|
||||
close = 0.0
|
||||
if close <= 0:
|
||||
continue
|
||||
point = dict(row)
|
||||
if "average" not in point and point.get("avg_price") is not None:
|
||||
point["average"] = point.get("avg_price")
|
||||
points.append(point)
|
||||
return points
|
||||
|
||||
|
||||
EMPTY_FAIL_DATASETS = {
|
||||
"stocks", "daily", "index_daily", "valuation", "moneyflow", "auction",
|
||||
"limit_events", "sector_daily",
|
||||
}
|
||||
|
||||
|
||||
def looks_like_heaven(module_name: str, filename: str = "") -> bool:
|
||||
"""问天调用栈识别(诊断用)。问天按数据集依赖接入,不再整栈强制旧链路。"""
|
||||
path = filename.replace("\\", "/")
|
||||
return module_name.startswith("backend.features.heaven") or "/features/heaven/" in path
|
||||
|
||||
|
||||
def caller_is_heaven(depth: int = 24) -> bool:
|
||||
frame = sys._getframe(1)
|
||||
for _ in range(depth):
|
||||
frame = frame.f_back if frame is not None else None
|
||||
if frame is None:
|
||||
return False
|
||||
name = str(frame.f_globals.get("__name__") or "")
|
||||
filename = str(frame.f_code.co_filename or "")
|
||||
if looks_like_heaven(name, filename):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class DatahubBridge:
|
||||
def __init__(
|
||||
self,
|
||||
settings: DatahubSettings,
|
||||
client: DatahubClient,
|
||||
shadow_sink: ShadowSink | None = None,
|
||||
heaven_guard: Callable[[], bool] | None = None,
|
||||
) -> None:
|
||||
self.settings = settings
|
||||
self.client = client
|
||||
self.shadow_sink = shadow_sink
|
||||
self.heaven_guard = heaven_guard or caller_is_heaven
|
||||
|
||||
def dataset_status(self, trade_date: str) -> list[dict[str, Any]] | None:
|
||||
flags = self.settings.flags("status")
|
||||
if not flags.read and not flags.shadow:
|
||||
return None
|
||||
try:
|
||||
response = self._require_fresh(self.client.dataset_status(yyyymmdd(trade_date)), "status")
|
||||
rows = list(response.data or [])
|
||||
if flags.shadow:
|
||||
self._emit_shadow(compare_rows("status", [], rows, response.meta))
|
||||
if flags.read:
|
||||
return rows
|
||||
return None
|
||||
except Exception as exc:
|
||||
self._log_failure("status", exc)
|
||||
if flags.shadow:
|
||||
self._emit_shadow(compare_rows("status", [], [], {}, self._error_text(exc)))
|
||||
return None
|
||||
|
||||
def batches(self, trade_date: str, dataset: str = "") -> list[dict[str, Any]] | None:
|
||||
flags = self.settings.flags("status")
|
||||
if not flags.read:
|
||||
return None
|
||||
try:
|
||||
response = self._require_fresh(
|
||||
self.client.batches(yyyymmdd(trade_date), dataset),
|
||||
"status",
|
||||
)
|
||||
return list(response.data or [])
|
||||
except Exception as exc:
|
||||
self._log_failure("status", exc)
|
||||
return None
|
||||
|
||||
def try_intraday(self, code: str) -> dict[str, Any] | None:
|
||||
flags = self.settings.flags("intraday")
|
||||
if not flags.read:
|
||||
return None
|
||||
try:
|
||||
response = self.client.intraday_points(code=code)
|
||||
data = response.data
|
||||
if not isinstance(data, dict):
|
||||
raise DatahubError("EMPTY", "datahub intraday payload invalid")
|
||||
points = _usable_intraday_points(data.get("points") or [])
|
||||
if not points:
|
||||
raise DatahubError("EMPTY", "datahub intraday empty")
|
||||
if (response.meta or {}).get("stale"):
|
||||
raise DatahubError("STALE", "datahub intraday stale")
|
||||
self._record_route("intraday", "datahub", str((response.meta or {}).get("source") or "datahub"))
|
||||
return {
|
||||
"entity_type": str(data.get("entity_type") or "stock"),
|
||||
"identifier": str(data.get("identifier") or code),
|
||||
"name": str(data.get("name") or ""),
|
||||
"code": str(data.get("code") or code),
|
||||
"trade_date": str(data.get("trade_date") or points[-1].get("date") or ""),
|
||||
"previous_close": float(data.get("previous_close") or 0),
|
||||
"points": points,
|
||||
"source": "datahub",
|
||||
}
|
||||
except Exception as exc:
|
||||
self._log_failure("intraday", exc)
|
||||
return None
|
||||
|
||||
def try_market_quotes(self, trade_date: str = "") -> list[dict[str, Any]] | None:
|
||||
return self._try_quote_rows("quotes", {}, expected_date=trade_date, minimum=200)
|
||||
|
||||
def try_quotes(self, codes: list[str]) -> list[dict[str, Any]] | None:
|
||||
cleaned = [str(item or "").strip() for item in codes if str(item or "").strip()]
|
||||
if not cleaned:
|
||||
return None
|
||||
return self._try_quote_rows("quotes", {"codes": ",".join(cleaned[:60])}, minimum=1)
|
||||
|
||||
def try_index_quotes(self) -> list[dict[str, Any]] | None:
|
||||
flags = self.settings.flags("index_quotes")
|
||||
if not flags.read:
|
||||
return None
|
||||
try:
|
||||
response = self.client.index_quotes()
|
||||
rows = [dict(item) for item in (response.data or []) if isinstance(item, dict)]
|
||||
if len(rows) < 3:
|
||||
raise DatahubError("EMPTY", "datahub index quotes incomplete")
|
||||
if (response.meta or {}).get("stale"):
|
||||
raise DatahubError("STALE", "datahub index quotes stale")
|
||||
self._record_route(
|
||||
"index_quotes",
|
||||
"datahub",
|
||||
str((response.meta or {}).get("source") or "datahub"),
|
||||
)
|
||||
return rows
|
||||
except Exception as exc:
|
||||
self._log_failure("index_quotes", exc)
|
||||
return None
|
||||
|
||||
def try_daily_chart(
|
||||
self,
|
||||
code: str,
|
||||
end_date: str,
|
||||
limit: int = 90,
|
||||
dataset: str = "daily",
|
||||
) -> list[dict[str, Any]] | None:
|
||||
flags = self.settings.flags(dataset)
|
||||
if not flags.read:
|
||||
return None
|
||||
compact_end = yyyymmdd(end_date)
|
||||
if not compact_end:
|
||||
return None
|
||||
try:
|
||||
start = _shift_yyyymmdd(compact_end, -max(190, int(limit) * 3))
|
||||
if dataset == "index_daily":
|
||||
response = self._paginate(
|
||||
self.client.index_bars,
|
||||
{"code": code, "from": start, "to": compact_end},
|
||||
)
|
||||
else:
|
||||
response = self._paginate(
|
||||
self.client.daily_bars,
|
||||
{"code": code, "from": start, "to": compact_end, "adjust": "none"},
|
||||
)
|
||||
# Charts can use a partial history window; do not discard usable bars
|
||||
# just because the requested lookback is not fully covered.
|
||||
self._validate_usable(
|
||||
dataset,
|
||||
list(response.data or []),
|
||||
response,
|
||||
require_complete=False,
|
||||
)
|
||||
rows = _chart_bars(list(response.data or []))
|
||||
if not rows:
|
||||
raise DatahubError("EMPTY", f"{dataset} chart empty")
|
||||
self._record_route(dataset, "datahub", str((response.meta or {}).get("source") or "datahub"))
|
||||
return rows[-max(20, min(180, int(limit))):]
|
||||
except Exception as exc:
|
||||
self._log_failure(dataset, exc)
|
||||
return None
|
||||
|
||||
def record_legacy(self, dataset: str, source: str = "", error: str = "") -> None:
|
||||
self._record_route(dataset, "legacy", source, error)
|
||||
|
||||
def route_snapshot(self) -> list[dict[str, Any]]:
|
||||
return LEDGER.snapshot()
|
||||
|
||||
def _try_quote_rows(
|
||||
self,
|
||||
dataset: str,
|
||||
params: dict[str, Any],
|
||||
expected_date: str = "",
|
||||
minimum: int = 1,
|
||||
) -> list[dict[str, Any]] | None:
|
||||
flags = self.settings.flags(dataset)
|
||||
if not flags.read:
|
||||
return None
|
||||
try:
|
||||
response = self.client.quotes_latest(**params)
|
||||
rows = [_native_quote(item) for item in (response.data or []) if isinstance(item, dict)]
|
||||
rows = [item for item in rows if item]
|
||||
want = yyyymmdd(expected_date)
|
||||
if want:
|
||||
dated = [item for item in rows if not item.get("quote_date") or item.get("quote_date") == want]
|
||||
if dated:
|
||||
rows = dated
|
||||
if len(rows) < minimum:
|
||||
raise DatahubError("EMPTY", f"datahub {dataset} empty")
|
||||
if (response.meta or {}).get("stale"):
|
||||
raise DatahubError("STALE", f"datahub {dataset} stale")
|
||||
self._record_route(dataset, "datahub", str((response.meta or {}).get("source") or "datahub"))
|
||||
return rows
|
||||
except Exception as exc:
|
||||
self._log_failure(dataset, exc)
|
||||
return None
|
||||
|
||||
def query(
|
||||
self,
|
||||
api_name: str,
|
||||
params: dict[str, Any] | None,
|
||||
fields: str,
|
||||
legacy_query: Callable[..., list[dict[str, Any]]],
|
||||
) -> list[dict[str, Any]]:
|
||||
dataset = API_TO_DATASET.get(api_name)
|
||||
# 问天按实际数据依赖接入:已映射到 hub 的 API 跟随开关;未映射的继续旧链路。
|
||||
if not dataset:
|
||||
return legacy_query(api_name, params, fields)
|
||||
flags = self.settings.flags(dataset)
|
||||
if not flags.read and not flags.shadow:
|
||||
return legacy_query(api_name, params, fields)
|
||||
|
||||
hub_rows: list[dict[str, Any]] | None = None
|
||||
hub_meta: dict[str, Any] = {}
|
||||
hub_error: str | None = None
|
||||
hub_canonical: list[dict[str, Any]] = []
|
||||
try:
|
||||
response = self._fetch_dataset(dataset, params or {}, api_name=api_name)
|
||||
hub_canonical = self._extract_rows(dataset, response, params or {})
|
||||
hub_rows = to_native_rows(dataset, hub_canonical)
|
||||
hub_meta = dict(response.meta)
|
||||
self._validate_usable(dataset, hub_rows, response)
|
||||
except Exception as exc:
|
||||
hub_error = self._error_text(exc)
|
||||
self._log_failure(dataset, exc)
|
||||
|
||||
if flags.shadow:
|
||||
try:
|
||||
legacy_rows = legacy_query(api_name, params, fields)
|
||||
except Exception as exc:
|
||||
if flags.read and hub_rows is not None and hub_error is None:
|
||||
self._emit_shadow(
|
||||
compare_rows(dataset, [], hub_canonical, hub_meta, self._error_text(exc), fields)
|
||||
)
|
||||
return project_fields(hub_rows, fields)
|
||||
raise
|
||||
self._emit_shadow(compare_rows(dataset, legacy_rows, hub_canonical, hub_meta, hub_error, fields))
|
||||
if flags.read and hub_rows is not None and hub_error is None:
|
||||
self._record_route(dataset, "datahub", str(hub_meta.get("source") or "datahub"))
|
||||
return project_fields(hub_rows, fields)
|
||||
if flags.read:
|
||||
self._record_route(dataset, "legacy", "tushare", hub_error or "")
|
||||
return legacy_rows
|
||||
|
||||
if flags.read and hub_rows is not None and hub_error is None:
|
||||
self._record_route(dataset, "datahub", str(hub_meta.get("source") or "datahub"))
|
||||
return project_fields(hub_rows, fields)
|
||||
result = legacy_query(api_name, params, fields)
|
||||
if flags.read:
|
||||
self._record_route(dataset, "legacy", "tushare", hub_error or "")
|
||||
return result
|
||||
|
||||
def _fetch_dataset(self, dataset: str, params: dict[str, Any], api_name: str = "") -> DatahubResponse:
|
||||
date = yyyymmdd(params.get("trade_date") or params.get("date"))
|
||||
start = yyyymmdd(params.get("start_date") or params.get("from") or date)
|
||||
end = yyyymmdd(params.get("end_date") or params.get("to") or date)
|
||||
code = str(params.get("ts_code") or params.get("code") or "").strip()
|
||||
if dataset == "calendar":
|
||||
if not start or not end:
|
||||
raise DatahubError("INVALID_ARGUMENT", "calendar requires start_date and end_date")
|
||||
return self.client.calendar(start, end)
|
||||
if dataset == "stocks":
|
||||
return self._paginate(self.client.stocks, {})
|
||||
fetchers = {
|
||||
"daily": self.client.daily_bars,
|
||||
"index_daily": self.client.index_bars,
|
||||
"valuation": self.client.valuation,
|
||||
"moneyflow": self.client.moneyflow,
|
||||
"auction": self.client.auction,
|
||||
"limit_events": self.client.limit_events,
|
||||
"popularity": self.client.popularity,
|
||||
"dragon_tiger": self.client.dragon_tiger,
|
||||
"sector_daily": self.client.sectors,
|
||||
}
|
||||
fetcher = fetchers[dataset]
|
||||
query: dict[str, Any] = {}
|
||||
if code:
|
||||
query["code"] = code
|
||||
if date and not (params.get("start_date") or params.get("end_date")):
|
||||
query["date"] = date
|
||||
else:
|
||||
if start:
|
||||
query["from"] = start
|
||||
if end:
|
||||
query["to"] = end
|
||||
if dataset == "daily":
|
||||
query["adjust"] = "none"
|
||||
if dataset == "limit_events":
|
||||
limit_type = str(params.get("limit_type") or "").strip().upper()
|
||||
if limit_type:
|
||||
query["limit_type"] = limit_type
|
||||
if dataset == "popularity":
|
||||
if api_name == "ths_hot":
|
||||
query["source"] = "ths"
|
||||
elif api_name == "dc_hot":
|
||||
query["source"] = "dc"
|
||||
if dataset == "sector_daily":
|
||||
family = {
|
||||
"ths_daily": "ths",
|
||||
"dc_index": "dc",
|
||||
"sw_daily": "sw",
|
||||
}.get(api_name, "")
|
||||
if family:
|
||||
query["family"] = family
|
||||
return self._paginate(fetcher, query)
|
||||
|
||||
def _paginate(self, fetcher: Callable[..., DatahubResponse], params: dict[str, Any]) -> DatahubResponse:
|
||||
limit = self.settings.page_limit
|
||||
offset = 0
|
||||
rows: list[Any] = []
|
||||
meta: dict[str, Any] = {}
|
||||
schema_version = 1
|
||||
while True:
|
||||
page = fetcher(**{**params, "limit": limit, "offset": offset})
|
||||
meta = dict(page.meta)
|
||||
schema_version = page.schema_version
|
||||
data = page.data or []
|
||||
if not isinstance(data, list):
|
||||
raise DatahubError("INTERNAL", "datahub returned a non-list payload")
|
||||
rows.extend(data)
|
||||
if len(data) < limit:
|
||||
break
|
||||
offset += limit
|
||||
if offset > 200_000:
|
||||
break
|
||||
return DatahubResponse(data=rows, meta=meta, schema_version=schema_version)
|
||||
|
||||
def _extract_rows(
|
||||
self,
|
||||
dataset: str,
|
||||
response: DatahubResponse,
|
||||
params: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
rows = [dict(item) for item in (response.data or [])]
|
||||
if dataset == "calendar":
|
||||
return filter_calendar_rows(rows, params)
|
||||
if dataset == "stocks":
|
||||
return filter_stock_rows(rows, params)
|
||||
return rows
|
||||
|
||||
def _validate_usable(
|
||||
self,
|
||||
dataset: str,
|
||||
rows: list[dict[str, Any]],
|
||||
response: DatahubResponse,
|
||||
require_complete: bool = True,
|
||||
) -> None:
|
||||
meta = response.meta or {}
|
||||
stale_seconds = int(meta.get("staleness_seconds") or 0)
|
||||
if meta.get("stale") or stale_seconds > self.settings.stale_seconds_max:
|
||||
raise DatahubError("STALE", f"{dataset} data is stale")
|
||||
if dataset in EMPTY_FAIL_DATASETS and not rows:
|
||||
raise DatahubError("EMPTY", f"{dataset} returned no rows")
|
||||
coverage = meta.get("coverage") if isinstance(meta.get("coverage"), dict) else {}
|
||||
if require_complete and (meta.get("incomplete") is True or coverage.get("complete") is False):
|
||||
missing = coverage.get("missing_count")
|
||||
raise DatahubError("INCOMPLETE", f"{dataset} range is incomplete missing={missing}")
|
||||
|
||||
def _require_fresh(self, response: DatahubResponse, dataset: str) -> DatahubResponse:
|
||||
self._validate_usable(dataset, list(response.data or []) if isinstance(response.data, list) else [], response)
|
||||
return response
|
||||
|
||||
def _emit_shadow(self, report: dict[str, Any]) -> None:
|
||||
safe = redact_value(report, secrets=self.settings.secrets())
|
||||
LOGGER.info("datahub shadow %s", safe)
|
||||
if self.shadow_sink is not None:
|
||||
self.shadow_sink(report)
|
||||
|
||||
def _log_failure(self, dataset: str, exc: Exception) -> None:
|
||||
error = redact_text(self._error_text(exc), self.settings.secrets())
|
||||
LOGGER.warning("datahub fallback dataset=%s error=%s", dataset, error)
|
||||
self._record_route(dataset, "legacy", "pending-legacy", error)
|
||||
|
||||
def _record_route(self, dataset: str, route: str, source: str = "", error: str = "") -> None:
|
||||
LEDGER.record(dataset, route, source, redact_text(error, self.settings.secrets()))
|
||||
|
||||
def _error_text(self, exc: Exception) -> str:
|
||||
if isinstance(exc, DatahubError):
|
||||
text = f"{exc.code}: {exc.message}"
|
||||
else:
|
||||
text = str(exc)
|
||||
return redact_text(text, self.settings.secrets())
|
||||
|
||||
|
||||
def _native_quote(row: dict[str, Any]) -> dict[str, Any] | None:
|
||||
ts_code = str(row.get("ts_code") or "").strip()
|
||||
close = _finite(row.get("close") if row.get("close") not in (None, "") else row.get("price"))
|
||||
previous = _finite(
|
||||
row.get("pre_close") if row.get("pre_close") not in (None, "") else row.get("previous_close")
|
||||
)
|
||||
if not ts_code or close <= 0 or previous <= 0:
|
||||
return None
|
||||
volume = _finite(row.get("vol") if row.get("vol") not in (None, "") else row.get("volume"))
|
||||
return {
|
||||
"ts_code": ts_code,
|
||||
"name": str(row.get("name") or ts_code).strip(),
|
||||
"pre_close": previous,
|
||||
"open": _finite(row.get("open")),
|
||||
"high": _finite(row.get("high")),
|
||||
"low": _finite(row.get("low")),
|
||||
"close": close,
|
||||
"vol": volume,
|
||||
"amount": _finite(row.get("amount")),
|
||||
"num": 0,
|
||||
"quote_date": yyyymmdd(row.get("quote_date") or row.get("trade_date")),
|
||||
"source": str(row.get("source") or "datahub"),
|
||||
}
|
||||
|
||||
|
||||
def _chart_bars(rows: list[Any]) -> list[dict[str, Any]]:
|
||||
normalized: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
compact = yyyymmdd(row.get("trade_date"))
|
||||
close = _finite(row.get("close"))
|
||||
if len(compact) != 8 or close <= 0:
|
||||
continue
|
||||
volume = _finite(row.get("volume") if row.get("volume") not in (None, "") else row.get("vol"))
|
||||
amount = _finite(row.get("amount"))
|
||||
if volume and volume < close * 10 and amount > 1000:
|
||||
volume = volume * 100
|
||||
trade_date = f"{compact[:4]}-{compact[4:6]}-{compact[6:8]}"
|
||||
previous = normalized[-1]["close"] if normalized else 0.0
|
||||
normalized.append(
|
||||
{
|
||||
"trade_date": trade_date,
|
||||
"open": _finite(row.get("open")),
|
||||
"high": _finite(row.get("high")),
|
||||
"low": _finite(row.get("low")),
|
||||
"close": close,
|
||||
"change": round((close / previous - 1) * 100, 4) if previous else _finite(row.get("pct_chg")),
|
||||
"volume": volume,
|
||||
"amount_billion": amount / 100_000_000,
|
||||
}
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def _shift_yyyymmdd(value: str, days: int) -> str:
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
stamp = datetime.strptime(value, "%Y%m%d")
|
||||
return (stamp + timedelta(days=days)).strftime("%Y%m%d")
|
||||
|
||||
|
||||
def _finite(value: Any) -> float:
|
||||
try:
|
||||
return float(value or 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
class DatahubAwareTushareClient:
|
||||
def __init__(self, legacy: TushareClient, bridge: DatahubBridge) -> None:
|
||||
self._legacy = legacy
|
||||
self._bridge = bridge
|
||||
# Mixins run as methods on the inner instance (dashboard / indices /
|
||||
# getattr). Bind hub hooks and query onto that instance so real
|
||||
# assembly cannot skip 8766.
|
||||
self._legacy_query = legacy.query
|
||||
legacy.query = self.query
|
||||
legacy.try_market_quotes = self.try_market_quotes
|
||||
legacy.try_quotes = self.try_quotes
|
||||
legacy.try_index_quotes = self.try_index_quotes
|
||||
legacy.record_datahub_legacy = self.record_datahub_legacy
|
||||
|
||||
def query(
|
||||
self,
|
||||
api_name: str,
|
||||
params: dict[str, Any] | None = None,
|
||||
fields: str = "",
|
||||
) -> list[dict[str, Any]]:
|
||||
return self._bridge.query(api_name, params, fields, self._legacy_query)
|
||||
|
||||
def try_market_quotes(self, trade_date: str = "") -> list[dict[str, Any]] | None:
|
||||
return self._bridge.try_market_quotes(trade_date)
|
||||
|
||||
def try_quotes(self, codes: list[str]) -> list[dict[str, Any]] | None:
|
||||
return self._bridge.try_quotes(codes)
|
||||
|
||||
def try_index_quotes(self) -> list[dict[str, Any]] | None:
|
||||
return self._bridge.try_index_quotes()
|
||||
|
||||
def record_datahub_legacy(self, dataset: str, source: str = "", error: str = "") -> None:
|
||||
self._bridge.record_legacy(dataset, source, error)
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._legacy, name)
|
||||
@@ -0,0 +1,205 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable
|
||||
|
||||
from backend.data.datahub.errors import DatahubError
|
||||
from backend.data.datahub.redact import redact_text
|
||||
from backend.data.datahub.settings import DatahubSettings
|
||||
|
||||
LOGGER = logging.getLogger("xiaobai.datahub")
|
||||
UrlOpen = Callable[..., Any]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DatahubResponse:
|
||||
data: Any
|
||||
meta: dict[str, Any] = field(default_factory=dict)
|
||||
schema_version: int = 1
|
||||
status: int = 200
|
||||
|
||||
|
||||
class DatahubClient:
|
||||
def __init__(
|
||||
self,
|
||||
settings: DatahubSettings,
|
||||
urlopen: UrlOpen = urllib.request.urlopen,
|
||||
) -> None:
|
||||
self.settings = settings
|
||||
self._urlopen = urlopen
|
||||
|
||||
def health(self) -> DatahubResponse:
|
||||
return self.get("/v1/health")
|
||||
|
||||
def calendar(self, start: str, end: str) -> DatahubResponse:
|
||||
return self.get("/v1/calendar", {"from": start, "to": end})
|
||||
|
||||
def stocks(self, updated_since: str = "", limit: int | None = None, offset: int = 0) -> DatahubResponse:
|
||||
params: dict[str, Any] = {"offset": offset, "limit": limit or self.settings.page_limit}
|
||||
if updated_since:
|
||||
params["updated_since"] = updated_since
|
||||
return self.get("/v1/stocks", params)
|
||||
|
||||
def daily_bars(self, **params: Any) -> DatahubResponse:
|
||||
return self.get("/v1/bars/daily", params)
|
||||
|
||||
def index_bars(self, **params: Any) -> DatahubResponse:
|
||||
return self.get("/v1/indexes/bars", params)
|
||||
|
||||
def valuation(self, **params: Any) -> DatahubResponse:
|
||||
return self.get("/v1/valuation", params)
|
||||
|
||||
def moneyflow(self, **params: Any) -> DatahubResponse:
|
||||
return self.get("/v1/moneyflow", params)
|
||||
|
||||
def auction(self, **params: Any) -> DatahubResponse:
|
||||
return self.get("/v1/auction", params)
|
||||
|
||||
def limit_events(self, **params: Any) -> DatahubResponse:
|
||||
return self.get("/v1/limit-events", params)
|
||||
|
||||
def popularity(self, **params: Any) -> DatahubResponse:
|
||||
return self.get("/v1/popularity", params)
|
||||
|
||||
def dragon_tiger(self, **params: Any) -> DatahubResponse:
|
||||
return self.get("/v1/dragon-tiger", params)
|
||||
|
||||
def sectors(self, **params: Any) -> DatahubResponse:
|
||||
return self.get("/v1/sectors", params)
|
||||
|
||||
def quotes_latest(self, **params: Any) -> DatahubResponse:
|
||||
return self.get("/v1/quotes/latest", params)
|
||||
|
||||
def index_quotes(self, **params: Any) -> DatahubResponse:
|
||||
return self.get("/v1/indexes/quotes", params)
|
||||
|
||||
def intraday_points(self, **params: Any) -> DatahubResponse:
|
||||
return self.get("/v1/intraday/points", params)
|
||||
|
||||
def dataset_status(self, date: str) -> DatahubResponse:
|
||||
return self.get("/v1/datasets/status", {"date": date})
|
||||
|
||||
def batches(self, date: str, dataset: str = "") -> DatahubResponse:
|
||||
params: dict[str, Any] = {"date": date}
|
||||
if dataset:
|
||||
params["dataset"] = dataset
|
||||
return self.get("/v1/batches", params)
|
||||
|
||||
def get(self, path: str, params: dict[str, Any] | None = None) -> DatahubResponse:
|
||||
if not self.settings.token:
|
||||
raise DatahubError("NOT_CONFIGURED", "DATAHUB_TOKEN is not configured")
|
||||
query = {
|
||||
key: value
|
||||
for key, value in (params or {}).items()
|
||||
if value is not None and value != ""
|
||||
}
|
||||
url = self.settings.base_url + path
|
||||
if query:
|
||||
url = f"{url}?{urllib.parse.urlencode(query)}"
|
||||
attempts = 1 + max(0, self.settings.retries)
|
||||
last_error: DatahubError | None = None
|
||||
for attempt in range(attempts):
|
||||
try:
|
||||
return self._request(url)
|
||||
except DatahubError as exc:
|
||||
last_error = exc
|
||||
if exc.code not in {"TIMEOUT", "UNAVAILABLE"} or attempt + 1 >= attempts:
|
||||
raise
|
||||
LOGGER.warning(
|
||||
"datahub retry %s/%s %s",
|
||||
attempt + 1,
|
||||
attempts,
|
||||
redact_text(str(exc), self.settings.secrets()),
|
||||
)
|
||||
raise last_error or DatahubError("INTERNAL", "datahub request failed")
|
||||
|
||||
def _request(self, url: str) -> DatahubResponse:
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"Accept": "application/json",
|
||||
"X-Datahub-Token": self.settings.token,
|
||||
"User-Agent": "XiaobaiReviewDatahub/1.0",
|
||||
},
|
||||
method="GET",
|
||||
)
|
||||
try:
|
||||
with self._urlopen(request, timeout=self.settings.timeout_seconds) as response:
|
||||
status = int(getattr(response, "status", 200) or 200)
|
||||
raw = response.read().decode("utf-8")
|
||||
except TimeoutError as exc:
|
||||
raise DatahubError("TIMEOUT", "datahub request timed out") from exc
|
||||
except urllib.error.HTTPError as exc:
|
||||
body = _read_error_body(exc)
|
||||
raise _http_error(exc.code, body, self.settings.secrets()) from exc
|
||||
except urllib.error.URLError as exc:
|
||||
reason = redact_text(str(getattr(exc, "reason", exc)), self.settings.secrets())
|
||||
if "timed out" in reason.lower():
|
||||
raise DatahubError("TIMEOUT", "datahub request timed out") from exc
|
||||
raise DatahubError("UNAVAILABLE", f"datahub unavailable: {reason}") from exc
|
||||
payload = _parse_json(raw, self.settings.secrets())
|
||||
return _as_response(payload, status, self.settings.secrets())
|
||||
|
||||
|
||||
def _parse_json(raw: str, secrets: tuple[str, ...]) -> dict[str, Any]:
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise DatahubError("INTERNAL", "datahub returned invalid json") from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise DatahubError("INTERNAL", "datahub returned a non-object payload")
|
||||
return payload
|
||||
|
||||
|
||||
def _as_response(payload: dict[str, Any], status: int, secrets: tuple[str, ...]) -> DatahubResponse:
|
||||
error = payload.get("error")
|
||||
if isinstance(error, dict):
|
||||
raise _mapped_error(str(error.get("code") or "INTERNAL"), str(error.get("message") or "datahub error"), status)
|
||||
if status >= 400:
|
||||
raise DatahubError("UNAVAILABLE", f"datahub http {status}", status)
|
||||
return DatahubResponse(
|
||||
data=payload.get("data"),
|
||||
meta=dict(payload.get("meta") or {}),
|
||||
schema_version=int(payload.get("schema_version") or 1),
|
||||
status=status,
|
||||
)
|
||||
|
||||
|
||||
def _http_error(status: int, payload: dict[str, Any], secrets: tuple[str, ...]) -> DatahubError:
|
||||
error = payload.get("error") if isinstance(payload.get("error"), dict) else {}
|
||||
code = str((error or {}).get("code") or "")
|
||||
message = str((error or {}).get("message") or payload.get("message") or f"datahub http {status}")
|
||||
message = redact_text(message, secrets)
|
||||
if status == 401 or code == "UNAUTHORIZED":
|
||||
return DatahubError("UNAUTHORIZED", message, status)
|
||||
if status == 404 or code == "DATASET_NOT_PUBLISHED":
|
||||
return DatahubError("DATASET_NOT_PUBLISHED", message, status)
|
||||
if status == 400 or code == "INVALID_ARGUMENT":
|
||||
return DatahubError("INVALID_ARGUMENT", message, status)
|
||||
if status in {429, 503} or code in {"RATE_LIMITED", "SOURCE_UNAVAILABLE"}:
|
||||
return DatahubError("UNAVAILABLE", message, status)
|
||||
return DatahubError(code or "INTERNAL", message, status)
|
||||
|
||||
|
||||
def _mapped_error(code: str, message: str, status: int) -> DatahubError:
|
||||
if code == "STALE_DATA":
|
||||
return DatahubError("STALE", message, status)
|
||||
if code in {"UNAUTHORIZED", "DATASET_NOT_PUBLISHED", "INVALID_ARGUMENT"}:
|
||||
return DatahubError(code, message, status)
|
||||
if code in {"RATE_LIMITED", "SOURCE_UNAVAILABLE"}:
|
||||
return DatahubError("UNAVAILABLE", message, status)
|
||||
return DatahubError(code or "INTERNAL", message, status)
|
||||
|
||||
|
||||
def _read_error_body(exc: urllib.error.HTTPError) -> dict[str, Any]:
|
||||
try:
|
||||
raw = exc.read().decode("utf-8")
|
||||
payload = json.loads(raw)
|
||||
return payload if isinstance(payload, dict) else {"message": raw}
|
||||
except Exception:
|
||||
return {"message": str(exc)}
|
||||
@@ -0,0 +1,161 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from backend.data.datahub.native import SCALE_FIELDS, row_key, to_canonical_row, yyyymmdd
|
||||
|
||||
NUMERIC_TOLERANCE = 1e-4
|
||||
CANONICAL_ALIASES = {"volume": "vol"}
|
||||
|
||||
|
||||
def compare_rows(
|
||||
dataset: str,
|
||||
legacy_rows: list[dict[str, Any]],
|
||||
hub_rows: list[dict[str, Any]] | None,
|
||||
hub_meta: dict[str, Any] | None = None,
|
||||
hub_error: str | None = None,
|
||||
fields: str = "",
|
||||
) -> dict[str, Any]:
|
||||
hub = hub_rows or []
|
||||
requested = _requested_fields(fields)
|
||||
legacy_map = {row_key(dataset, row): row for row in legacy_rows}
|
||||
hub_map = {row_key(dataset, _align_hub_row(row)): row for row in hub}
|
||||
missing_hub = sorted(key for key in legacy_map if key not in hub_map)
|
||||
missing_legacy = sorted(key for key in hub_map if key not in legacy_map)
|
||||
value_diffs: list[dict[str, Any]] = []
|
||||
unit_conversion: list[dict[str, Any]] = []
|
||||
matched = 0
|
||||
for key, legacy in legacy_map.items():
|
||||
hub_row = hub_map.get(key)
|
||||
if hub_row is None:
|
||||
continue
|
||||
field_report = _compare_fields(dataset, legacy, hub_row, requested)
|
||||
if field_report["unit_conversion"]:
|
||||
unit_conversion.append({"key": list(key), "fields": field_report["unit_conversion"]})
|
||||
if field_report["value_diff"]:
|
||||
value_diffs.append({"key": list(key), "fields": field_report["value_diff"]})
|
||||
if not field_report["unit_conversion"] and not field_report["value_diff"]:
|
||||
matched += 1
|
||||
stale_seconds = int((hub_meta or {}).get("staleness_seconds") or 0)
|
||||
time_skew = bool((hub_meta or {}).get("stale")) or stale_seconds > 0
|
||||
return {
|
||||
"dataset": dataset,
|
||||
"legacy_rows": len(legacy_rows),
|
||||
"hub_rows": len(hub),
|
||||
"matched": matched,
|
||||
"missing_hub": [list(item) for item in missing_hub[:20]],
|
||||
"missing_legacy": [list(item) for item in missing_legacy[:20]],
|
||||
"missing_hub_count": len(missing_hub),
|
||||
"missing_legacy_count": len(missing_legacy),
|
||||
"value_diff_count": len(value_diffs),
|
||||
"unit_conversion_count": len(unit_conversion),
|
||||
"value_diffs": value_diffs[:20],
|
||||
"unit_conversion": unit_conversion[:20],
|
||||
"time_skew": time_skew,
|
||||
"staleness_seconds": stale_seconds,
|
||||
"published_at": (hub_meta or {}).get("published_at"),
|
||||
"trade_date": yyyymmdd((hub_meta or {}).get("trade_date")),
|
||||
"hub_error": hub_error,
|
||||
"fields_compared": sorted(requested) if requested is not None else None,
|
||||
"equal": (
|
||||
not hub_error
|
||||
and not missing_hub
|
||||
and not missing_legacy
|
||||
and not value_diffs
|
||||
and not unit_conversion
|
||||
and not time_skew
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _align_hub_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
aligned = dict(row)
|
||||
if "volume" in aligned and "vol" not in aligned:
|
||||
aligned["vol"] = aligned.get("volume")
|
||||
return aligned
|
||||
|
||||
|
||||
def _requested_fields(fields: str) -> list[str] | None:
|
||||
"""Fields the website actually asked for; None means "no projection"."""
|
||||
keys = [item.strip() for item in str(fields or "").split(",") if item.strip()]
|
||||
if not keys:
|
||||
return None
|
||||
seen: list[str] = []
|
||||
for key in keys:
|
||||
canonical = CANONICAL_ALIASES.get(key, key)
|
||||
if canonical not in seen:
|
||||
seen.append(canonical)
|
||||
return seen
|
||||
|
||||
|
||||
def _compare_fields(
|
||||
dataset: str,
|
||||
legacy: dict[str, Any],
|
||||
hub: dict[str, Any],
|
||||
requested: list[str] | None = None,
|
||||
) -> dict[str, list[dict[str, Any]]]:
|
||||
canonical_legacy = to_canonical_row(dataset, legacy)
|
||||
hub_canonical = _hub_canonical(dataset, hub)
|
||||
native_hub = _align_hub_row(hub)
|
||||
value_diff: list[dict[str, Any]] = []
|
||||
unit_conversion: list[dict[str, Any]] = []
|
||||
keys = (set(canonical_legacy) | set(hub_canonical)) - {"batch_id", "updated_at", "volume"}
|
||||
if requested is not None:
|
||||
# Compare only what the website asked for. Extra hub columns are
|
||||
# transport detail, not business differences; a requested field still
|
||||
# alarms when it is missing or holds a different value.
|
||||
keys = set(requested) - {"batch_id", "updated_at", "volume"}
|
||||
scales = SCALE_FIELDS.get(dataset) or {}
|
||||
for field in sorted(keys):
|
||||
left = canonical_legacy.get(field)
|
||||
right = hub_canonical.get(field)
|
||||
if _same(left, right):
|
||||
continue
|
||||
native_left = legacy.get(field)
|
||||
hub_raw = native_hub.get(field)
|
||||
if field in scales and _near(_optional(native_left), _optional(hub_raw)):
|
||||
unit_conversion.append(
|
||||
{"field": field, "legacy": native_left, "hub": hub_raw, "reason": "unit_conversion"}
|
||||
)
|
||||
continue
|
||||
value_diff.append({"field": field, "legacy": left, "hub": right, "reason": "value_diff"})
|
||||
return {"value_diff": value_diff, "unit_conversion": unit_conversion}
|
||||
|
||||
|
||||
def _hub_canonical(dataset: str, row: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Hub API rows are already canonical; only align field names."""
|
||||
aligned = dict(row)
|
||||
if "volume" in aligned and "vol" not in aligned:
|
||||
aligned["vol"] = aligned.get("volume")
|
||||
if dataset == "calendar":
|
||||
is_open = aligned.get("is_open")
|
||||
aligned["is_open"] = 1 if is_open in (True, 1, "1", "Y", "y") else 0
|
||||
aligned["cal_date"] = yyyymmdd(aligned.get("cal_date"))
|
||||
aligned["pretrade_date"] = yyyymmdd(aligned.get("pretrade_date")) or None
|
||||
aligned["exchange"] = str(aligned.get("exchange") or "SSE")
|
||||
return aligned
|
||||
|
||||
|
||||
def _same(left: Any, right: Any) -> bool:
|
||||
if left in (None, "") and right in (None, ""):
|
||||
return True
|
||||
if isinstance(left, (int, float)) or isinstance(right, (int, float)):
|
||||
return _near(_optional(left), _optional(right))
|
||||
return str(left or "") == str(right or "")
|
||||
|
||||
|
||||
def _near(left: float | None, right: float | None) -> bool:
|
||||
if left is None and right is None:
|
||||
return True
|
||||
if left is None or right is None:
|
||||
return False
|
||||
return abs(left - right) <= max(NUMERIC_TOLERANCE, abs(left) * 1e-9, abs(right) * 1e-9)
|
||||
|
||||
|
||||
def _optional(value: Any) -> float | None:
|
||||
if value in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
@@ -0,0 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class DatahubError(RuntimeError):
|
||||
def __init__(self, code: str, message: str, status: int | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.status = status
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.code}: {self.message}"
|
||||
@@ -0,0 +1,204 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from backend.data.numbers import finite_number
|
||||
|
||||
|
||||
AMOUNT_THOUSAND_YUAN = 1000.0
|
||||
AMOUNT_WAN_YUAN = 10000.0
|
||||
VOLUME_LOT = 100.0
|
||||
|
||||
API_TO_DATASET = {
|
||||
"trade_cal": "calendar",
|
||||
"stock_basic": "stocks",
|
||||
"daily": "daily",
|
||||
"daily_basic": "valuation",
|
||||
"index_daily": "index_daily",
|
||||
"moneyflow": "moneyflow",
|
||||
"stk_auction": "auction",
|
||||
"limit_list_d": "limit_events",
|
||||
"ths_hot": "popularity",
|
||||
"dc_hot": "popularity",
|
||||
"hm_detail": "dragon_tiger",
|
||||
"ths_daily": "sector_daily",
|
||||
"dc_index": "sector_daily",
|
||||
"sw_daily": "sector_daily",
|
||||
}
|
||||
|
||||
SCALE_FIELDS = {
|
||||
"daily": {"vol": VOLUME_LOT, "amount": AMOUNT_THOUSAND_YUAN},
|
||||
"index_daily": {"vol": VOLUME_LOT, "amount": AMOUNT_THOUSAND_YUAN},
|
||||
"valuation": {"total_mv": AMOUNT_WAN_YUAN, "circ_mv": AMOUNT_WAN_YUAN},
|
||||
"moneyflow": {
|
||||
"buy_sm_amount": AMOUNT_WAN_YUAN,
|
||||
"sell_sm_amount": AMOUNT_WAN_YUAN,
|
||||
"buy_md_amount": AMOUNT_WAN_YUAN,
|
||||
"sell_md_amount": AMOUNT_WAN_YUAN,
|
||||
"buy_lg_amount": AMOUNT_WAN_YUAN,
|
||||
"sell_lg_amount": AMOUNT_WAN_YUAN,
|
||||
"buy_elg_amount": AMOUNT_WAN_YUAN,
|
||||
"sell_elg_amount": AMOUNT_WAN_YUAN,
|
||||
"net_mf_amount": AMOUNT_WAN_YUAN,
|
||||
},
|
||||
"auction": {"vol": VOLUME_LOT, "float_share": AMOUNT_WAN_YUAN},
|
||||
"limit_events": {
|
||||
"limit_amount": AMOUNT_WAN_YUAN,
|
||||
"float_mv": AMOUNT_WAN_YUAN,
|
||||
"total_mv": AMOUNT_WAN_YUAN,
|
||||
},
|
||||
"dragon_tiger": {
|
||||
"buy_amount": AMOUNT_WAN_YUAN,
|
||||
"sell_amount": AMOUNT_WAN_YUAN,
|
||||
"net_amount": AMOUNT_WAN_YUAN,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def yyyymmdd(value: Any) -> str:
|
||||
return str(value or "").replace("-", "")[:8]
|
||||
|
||||
|
||||
def to_native_rows(dataset: str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return [to_native_row(dataset, row) for row in rows]
|
||||
|
||||
|
||||
def to_native_row(dataset: str, row: dict[str, Any]) -> dict[str, Any]:
|
||||
if dataset == "calendar":
|
||||
is_open = row.get("is_open")
|
||||
return {
|
||||
"exchange": str(row.get("exchange") or "SSE"),
|
||||
"cal_date": yyyymmdd(row.get("cal_date")),
|
||||
"is_open": 1 if is_open in (True, 1, "1", "Y", "y") else 0,
|
||||
"pretrade_date": yyyymmdd(row.get("pretrade_date")) or None,
|
||||
}
|
||||
converted = dict(row)
|
||||
converted.pop("batch_id", None)
|
||||
if "volume" in converted and "vol" not in converted:
|
||||
converted["vol"] = converted.pop("volume")
|
||||
elif "volume" in converted:
|
||||
converted.pop("volume", None)
|
||||
scales = SCALE_FIELDS.get(dataset) or {}
|
||||
for field, factor in scales.items():
|
||||
if field in converted:
|
||||
converted[field] = _unscale(converted.get(field), factor)
|
||||
if dataset == "stocks":
|
||||
converted.pop("updated_at", None)
|
||||
if dataset == "popularity":
|
||||
# keep hub source; callers filter ths/dc themselves when needed
|
||||
if converted.get("ts_name") and not converted.get("name"):
|
||||
converted["name"] = converted.get("ts_name")
|
||||
if dataset == "dragon_tiger":
|
||||
if converted.get("ts_name") and not converted.get("name"):
|
||||
converted["name"] = converted.get("ts_name")
|
||||
if dataset == "sector_daily":
|
||||
if converted.get("pct_change") is not None and converted.get("pct_chg") is None:
|
||||
converted["pct_chg"] = converted.get("pct_change")
|
||||
return converted
|
||||
|
||||
|
||||
def to_canonical_row(dataset: str, row: dict[str, Any]) -> dict[str, Any]:
|
||||
if dataset == "calendar":
|
||||
is_open = row.get("is_open")
|
||||
return {
|
||||
"exchange": str(row.get("exchange") or "SSE"),
|
||||
"cal_date": yyyymmdd(row.get("cal_date")),
|
||||
"is_open": 1 if is_open in (True, 1, "1", "Y", "y") else 0,
|
||||
"pretrade_date": yyyymmdd(row.get("pretrade_date")) or None,
|
||||
}
|
||||
converted = dict(row)
|
||||
if "volume" in converted and "vol" not in converted:
|
||||
converted["vol"] = converted.pop("volume")
|
||||
scales = SCALE_FIELDS.get(dataset) or {}
|
||||
for field, factor in scales.items():
|
||||
if field in converted:
|
||||
converted[field] = _scale(converted.get(field), factor)
|
||||
return converted
|
||||
|
||||
|
||||
def row_key(dataset: str, row: dict[str, Any]) -> tuple[str, ...]:
|
||||
if dataset == "calendar":
|
||||
return (yyyymmdd(row.get("cal_date")),)
|
||||
if dataset == "stocks":
|
||||
return (str(row.get("ts_code") or "").upper(),)
|
||||
if dataset == "status":
|
||||
return (str(row.get("dataset") or ""), yyyymmdd(row.get("trade_date")))
|
||||
if dataset == "limit_events":
|
||||
return (
|
||||
str(row.get("ts_code") or "").upper(),
|
||||
yyyymmdd(row.get("trade_date")),
|
||||
str(row.get("limit_type") or ""),
|
||||
)
|
||||
if dataset == "popularity":
|
||||
return (
|
||||
str(row.get("ts_code") or "").upper(),
|
||||
yyyymmdd(row.get("trade_date")),
|
||||
str(row.get("source") or ""),
|
||||
)
|
||||
if dataset == "dragon_tiger":
|
||||
return (
|
||||
str(row.get("ts_code") or "").upper(),
|
||||
yyyymmdd(row.get("trade_date")),
|
||||
str(row.get("hm_name") or ""),
|
||||
)
|
||||
if dataset == "sector_daily":
|
||||
return (
|
||||
str(row.get("ts_code") or "").upper(),
|
||||
yyyymmdd(row.get("trade_date")),
|
||||
str(row.get("family") or ""),
|
||||
)
|
||||
return (str(row.get("ts_code") or "").upper(), yyyymmdd(row.get("trade_date")))
|
||||
|
||||
|
||||
def project_fields(rows: list[dict[str, Any]], fields: str) -> list[dict[str, Any]]:
|
||||
keys = [item.strip() for item in str(fields or "").split(",") if item.strip()]
|
||||
if not keys:
|
||||
return rows
|
||||
return [{key: row.get(key) for key in keys} for row in rows]
|
||||
|
||||
|
||||
def filter_stock_rows(rows: list[dict[str, Any]], params: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
payload = params or {}
|
||||
ts_code = str(payload.get("ts_code") or "").strip().upper()
|
||||
status = str(payload.get("list_status") or "").strip()
|
||||
name = str(payload.get("name") or "").strip()
|
||||
filtered = rows
|
||||
if ts_code:
|
||||
filtered = [row for row in filtered if str(row.get("ts_code") or "").upper() == ts_code]
|
||||
if status:
|
||||
filtered = [row for row in filtered if str(row.get("list_status") or status) == status]
|
||||
if name:
|
||||
filtered = [row for row in filtered if name.casefold() in str(row.get("name") or "").casefold()]
|
||||
return filtered
|
||||
|
||||
|
||||
def filter_calendar_rows(rows: list[dict[str, Any]], params: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
payload = params or {}
|
||||
if payload.get("is_open") in (1, "1", True):
|
||||
return [row for row in rows if int(row.get("is_open") or 0) == 1]
|
||||
if payload.get("is_open") in (0, "0", False):
|
||||
return [row for row in rows if int(row.get("is_open") or 0) == 0]
|
||||
return rows
|
||||
|
||||
|
||||
def _scale(value: Any, factor: float) -> float | None:
|
||||
number = _optional_number(value)
|
||||
if number is None:
|
||||
return None
|
||||
return number * factor
|
||||
|
||||
|
||||
def _unscale(value: Any, factor: float) -> float | None:
|
||||
number = _optional_number(value)
|
||||
if number is None or factor == 0:
|
||||
return None
|
||||
return number / factor
|
||||
|
||||
|
||||
def _optional_number(value: Any) -> float | None:
|
||||
if value in (None, ""):
|
||||
return None
|
||||
number = finite_number(value, default=float("nan"))
|
||||
if number != number:
|
||||
return None
|
||||
return number
|
||||
@@ -0,0 +1,39 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
SECRET_HINTS = (
|
||||
"token",
|
||||
"password",
|
||||
"secret",
|
||||
"key",
|
||||
"authorization",
|
||||
"credential",
|
||||
"cookie",
|
||||
)
|
||||
|
||||
|
||||
def redact_value(value: Any, key: str = "", secrets: tuple[str, ...] = ()) -> Any:
|
||||
lowered = key.lower()
|
||||
if any(part in lowered for part in SECRET_HINTS):
|
||||
return "***"
|
||||
if isinstance(value, dict):
|
||||
return {
|
||||
str(item_key): redact_value(item_value, str(item_key), secrets)
|
||||
for item_key, item_value in value.items()
|
||||
}
|
||||
if isinstance(value, list):
|
||||
return [redact_value(item, key, secrets) for item in value]
|
||||
text = str(value) if value is not None and not isinstance(value, (int, float, bool)) else value
|
||||
if isinstance(text, str):
|
||||
return redact_text(text, secrets)
|
||||
return value
|
||||
|
||||
|
||||
def redact_text(text: str, secrets: tuple[str, ...] = ()) -> str:
|
||||
redacted = text
|
||||
for secret in secrets:
|
||||
if secret:
|
||||
redacted = redacted.replace(secret, "***")
|
||||
return redacted
|
||||
@@ -0,0 +1,57 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from threading import Lock
|
||||
from typing import Any
|
||||
|
||||
from backend.data.datahub.settings import DATASETS
|
||||
|
||||
DATASET_LABELS = {
|
||||
"calendar": "交易日历",
|
||||
"stocks": "股票主档",
|
||||
"daily": "个股日K",
|
||||
"index_daily": "指数日K",
|
||||
"valuation": "估值",
|
||||
"moneyflow": "资金流",
|
||||
"auction": "竞价",
|
||||
"limit_events": "涨停池",
|
||||
"popularity": "人气榜",
|
||||
"dragon_tiger": "龙虎榜",
|
||||
"sector_daily": "题材板块",
|
||||
"quotes": "全市场实时行情",
|
||||
"index_quotes": "指数实时行情",
|
||||
"intraday": "分时",
|
||||
"status": "数据集状态",
|
||||
}
|
||||
|
||||
|
||||
class DatahubRouteLedger:
|
||||
def __init__(self) -> None:
|
||||
self._lock = Lock()
|
||||
self._rows: dict[str, dict[str, Any]] = {}
|
||||
|
||||
def record(self, dataset: str, route: str, source: str = "", error: str = "") -> None:
|
||||
name = str(dataset or "").strip() or "unknown"
|
||||
with self._lock:
|
||||
self._rows[name] = {
|
||||
"dataset": name,
|
||||
"label": DATASET_LABELS.get(name, name),
|
||||
"route": "legacy" if route == "legacy" else "datahub",
|
||||
"source": str(source or "").strip(),
|
||||
"error": str(error or "").strip(),
|
||||
"at": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||
}
|
||||
|
||||
def snapshot(self) -> list[dict[str, Any]]:
|
||||
with self._lock:
|
||||
rows = [dict(item) for item in self._rows.values()]
|
||||
order = {name: index for index, name in enumerate(DATASETS)}
|
||||
rows.sort(key=lambda item: (order.get(str(item.get("dataset")), 99), str(item.get("dataset"))))
|
||||
return rows
|
||||
|
||||
def clear(self) -> None:
|
||||
with self._lock:
|
||||
self._rows.clear()
|
||||
|
||||
|
||||
LEDGER = DatahubRouteLedger()
|
||||
@@ -0,0 +1,134 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
|
||||
from backend.bootstrap.config import APP_DIR
|
||||
|
||||
|
||||
DATASETS = (
|
||||
"calendar",
|
||||
"stocks",
|
||||
"daily",
|
||||
"index_daily",
|
||||
"valuation",
|
||||
"moneyflow",
|
||||
"auction",
|
||||
"limit_events",
|
||||
"popularity",
|
||||
"dragon_tiger",
|
||||
"sector_daily",
|
||||
"quotes",
|
||||
"index_quotes",
|
||||
"intraday",
|
||||
"status",
|
||||
)
|
||||
|
||||
ENV_DATASET = {
|
||||
"calendar": "CALENDAR",
|
||||
"stocks": "STOCKS",
|
||||
"daily": "DAILY",
|
||||
"index_daily": "INDEX_DAILY",
|
||||
"valuation": "VALUATION",
|
||||
"moneyflow": "MONEYFLOW",
|
||||
"auction": "AUCTION",
|
||||
"limit_events": "LIMIT_EVENTS",
|
||||
"popularity": "POPULARITY",
|
||||
"dragon_tiger": "DRAGON_TIGER",
|
||||
"sector_daily": "SECTOR_DAILY",
|
||||
"quotes": "QUOTES",
|
||||
"index_quotes": "INDEX_QUOTES",
|
||||
"intraday": "INTRADAY",
|
||||
"status": "STATUS",
|
||||
}
|
||||
|
||||
DEFAULT_CONFIG_PATH = APP_DIR / "config" / "datahub.config.json"
|
||||
|
||||
|
||||
def _truthy(value: Any) -> bool:
|
||||
return str(value or "").strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _int(value: Any, default: int) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DatasetFlags:
|
||||
name: str
|
||||
read: bool = False
|
||||
shadow: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DatahubSettings:
|
||||
base_url: str
|
||||
token: str
|
||||
timeout_seconds: int = 8
|
||||
retries: int = 1
|
||||
page_limit: int = 5000
|
||||
stale_seconds_max: int = 86400
|
||||
datasets: dict[str, DatasetFlags] | None = None
|
||||
|
||||
def flags(self, dataset: str) -> DatasetFlags:
|
||||
mapped = self.datasets or {}
|
||||
return mapped.get(dataset) or DatasetFlags(dataset)
|
||||
|
||||
def any_enabled(self) -> bool:
|
||||
return any(item.read or item.shadow for item in (self.datasets or {}).values())
|
||||
|
||||
def secrets(self) -> tuple[str, ...]:
|
||||
return tuple(item for item in (self.token,) if item)
|
||||
|
||||
@classmethod
|
||||
def load(
|
||||
cls,
|
||||
path: Path | None = None,
|
||||
environ: Mapping[str, str] | None = None,
|
||||
credentials: Mapping[str, object] | None = None,
|
||||
) -> "DatahubSettings":
|
||||
config_path = path or DEFAULT_CONFIG_PATH
|
||||
payload: dict[str, Any] = {}
|
||||
if config_path.is_file():
|
||||
payload = json.loads(config_path.read_text(encoding="utf-8"))
|
||||
env = dict(os.environ if environ is None else environ)
|
||||
creds = dict(credentials or {})
|
||||
dataset_flags: dict[str, DatasetFlags] = {}
|
||||
raw_datasets = payload.get("datasets") or {}
|
||||
for name in DATASETS:
|
||||
item = raw_datasets.get(name) or {}
|
||||
env_key = ENV_DATASET[name]
|
||||
read = _truthy(env.get(f"DATAHUB_READ_{env_key}")) if f"DATAHUB_READ_{env_key}" in env else bool(item.get("read"))
|
||||
shadow = (
|
||||
_truthy(env.get(f"DATAHUB_SHADOW_{env_key}"))
|
||||
if f"DATAHUB_SHADOW_{env_key}" in env
|
||||
else bool(item.get("shadow"))
|
||||
)
|
||||
dataset_flags[name] = DatasetFlags(name, read=read, shadow=shadow)
|
||||
token = str(
|
||||
env.get("DATAHUB_TOKEN")
|
||||
or creds.get("datahub_token")
|
||||
or payload.get("token")
|
||||
or ""
|
||||
).strip()
|
||||
base_url = str(
|
||||
env.get("DATAHUB_BASE_URL")
|
||||
or creds.get("datahub_base_url")
|
||||
or payload.get("base_url")
|
||||
or "http://127.0.0.1:8766"
|
||||
).strip().rstrip("/")
|
||||
return cls(
|
||||
base_url=base_url,
|
||||
token=token,
|
||||
timeout_seconds=_int(env.get("DATAHUB_TIMEOUT") or payload.get("timeout_seconds"), 8),
|
||||
retries=max(0, _int(env.get("DATAHUB_RETRIES") or payload.get("retries"), 1)),
|
||||
page_limit=max(1, _int(payload.get("page_limit"), 5000)),
|
||||
stale_seconds_max=max(0, _int(payload.get("stale_seconds_max"), 86400)),
|
||||
datasets=dataset_flags,
|
||||
)
|
||||
+43
-2
@@ -3,8 +3,10 @@ from __future__ import annotations
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from backend.data.contracts import DataUsage
|
||||
from backend.data.datahub import DatahubAwareTushareClient, DatahubBridge, DatahubClient, DatahubSettings
|
||||
from backend.data.policy import DataSourcePolicy
|
||||
from backend.data.providers import IfindProvider, TushareProvider
|
||||
from backend.data.quality import DataQualityGate, QualityEvidence, QualityReport
|
||||
@@ -22,6 +24,7 @@ class DataGateway:
|
||||
ifind_provider: IfindProvider
|
||||
chart_data: MarketChartClient
|
||||
realtime_observer: WebRealtimeAggregator
|
||||
datahub: DatahubBridge
|
||||
|
||||
@property
|
||||
def ifind(self) -> IfindHttpClient:
|
||||
@@ -34,7 +37,40 @@ class DataGateway:
|
||||
) -> TushareClient:
|
||||
if dataset_id:
|
||||
self.policy.assert_allowed(dataset_id, "tushare", usage)
|
||||
return self.tushare_provider.client()
|
||||
legacy = self.tushare_provider.client()
|
||||
legacy.realtime_aggregator = self.realtime_observer
|
||||
return DatahubAwareTushareClient(legacy, self.datahub)
|
||||
|
||||
def dataset_status(self, trade_date: str) -> list[dict[str, Any]] | None:
|
||||
return self.datahub.dataset_status(trade_date)
|
||||
|
||||
def batches(self, trade_date: str, dataset: str = "") -> list[dict[str, Any]] | None:
|
||||
return self.datahub.batches(trade_date, dataset)
|
||||
|
||||
def datahub_status(self) -> dict[str, Any]:
|
||||
from backend.data.datahub.route_state import DATASET_LABELS, LEDGER
|
||||
from backend.data.datahub.settings import DATASETS
|
||||
|
||||
settings = self.datahub.settings
|
||||
flags = []
|
||||
enabled = 0
|
||||
for name in DATASETS:
|
||||
read = bool(settings.flags(name).read)
|
||||
if read:
|
||||
enabled += 1
|
||||
flags.append({"dataset": name, "label": DATASET_LABELS.get(name, name), "read": read})
|
||||
routes = LEDGER.snapshot()
|
||||
fallbacks = [item for item in routes if item.get("route") == "legacy"]
|
||||
return {
|
||||
"configured": bool(settings.token and settings.base_url),
|
||||
"base_url": settings.base_url,
|
||||
"enabled_reads": enabled,
|
||||
"total_reads": len(DATASETS),
|
||||
"flags": flags,
|
||||
"routes": routes,
|
||||
"fallback_count": len(fallbacks),
|
||||
"fallback_labels": [str(item.get("label") or item.get("dataset")) for item in fallbacks],
|
||||
}
|
||||
|
||||
def assert_source(self, dataset_id: str, provider_id: str, usage: DataUsage) -> None:
|
||||
self.policy.assert_allowed(dataset_id, provider_id, usage)
|
||||
@@ -64,6 +100,7 @@ class DataGateway:
|
||||
def build_data_gateway(
|
||||
credentials: dict[str, object],
|
||||
tushare_token_supplier: Callable[[], str] | None = None,
|
||||
datahub_settings: DatahubSettings | None = None,
|
||||
) -> DataGateway:
|
||||
ifind = IfindHttpClient(
|
||||
str(credentials.get("ifind_refresh_token") or ""),
|
||||
@@ -73,11 +110,15 @@ def build_data_gateway(
|
||||
lambda: str(credentials.get("tushare_token") or "")
|
||||
)
|
||||
policy = DataSourcePolicy.load()
|
||||
settings = datahub_settings or DatahubSettings.load(credentials=credentials)
|
||||
datahub_client = DatahubClient(settings)
|
||||
datahub = DatahubBridge(settings, datahub_client)
|
||||
return DataGateway(
|
||||
policy=policy,
|
||||
quality=DataQualityGate.load(policy),
|
||||
tushare_provider=TushareProvider(token_supplier),
|
||||
ifind_provider=IfindProvider(ifind),
|
||||
chart_data=MarketChartClient(ifind, EastmoneyChartClient()),
|
||||
chart_data=MarketChartClient(ifind, EastmoneyChartClient(), datahub),
|
||||
realtime_observer=WebRealtimeAggregator(),
|
||||
datahub=datahub,
|
||||
)
|
||||
|
||||
@@ -3,7 +3,11 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from backend.data.numbers import finite_number as _number
|
||||
from backend.data.providers.tushare_helpers import _display_time, _prices_equal
|
||||
from backend.data.providers.tushare_helpers import (
|
||||
_display_time,
|
||||
_prices_equal,
|
||||
calendar_is_open,
|
||||
)
|
||||
|
||||
|
||||
class DailyMarketMixin:
|
||||
@@ -17,7 +21,11 @@ class DailyMarketMixin:
|
||||
trade_date = requested
|
||||
else:
|
||||
row = requested_rows[0]
|
||||
trade_date = row["cal_date"] if row.get("is_open") == 1 else row.get("pretrade_date", requested)
|
||||
trade_date = (
|
||||
row["cal_date"]
|
||||
if calendar_is_open(row.get("is_open"))
|
||||
else row.get("pretrade_date", requested)
|
||||
)
|
||||
|
||||
resolved_rows = self.query(
|
||||
"trade_cal",
|
||||
|
||||
@@ -16,6 +16,12 @@ from backend.data.providers.tushare_transport import TushareError
|
||||
|
||||
|
||||
class DashboardMixin:
|
||||
def _now(self) -> datetime:
|
||||
clock = getattr(self, "clock", None)
|
||||
if callable(clock):
|
||||
return clock()
|
||||
return datetime.now().astimezone()
|
||||
|
||||
def dashboard(self, requested_date: str) -> dict[str, Any]:
|
||||
trade_date, previous_trade_date = self.resolve_trade_context(requested_date)
|
||||
if self.should_use_realtime(requested_date, trade_date):
|
||||
@@ -26,11 +32,12 @@ class DashboardMixin:
|
||||
)
|
||||
|
||||
daily = self._load_daily(trade_date)
|
||||
now = self._now()
|
||||
if (
|
||||
not daily
|
||||
and requested_date == datetime.now().astimezone().strftime("%Y%m%d")
|
||||
and requested_date == now.strftime("%Y%m%d")
|
||||
and trade_date == requested_date
|
||||
and datetime.now().astimezone().time().replace(tzinfo=None) >= dt_time(9, 15)
|
||||
and now.time().replace(tzinfo=None) >= dt_time(9, 15)
|
||||
):
|
||||
return self._realtime_dashboard(
|
||||
requested_date,
|
||||
@@ -98,15 +105,14 @@ class DashboardMixin:
|
||||
}
|
||||
return apply_sentiment_to_dashboard(dashboard)
|
||||
|
||||
@staticmethod
|
||||
def should_use_realtime(requested_date: str, trade_date: str) -> bool:
|
||||
"""Use rt_k for today's open market until end-of-day datasets settle."""
|
||||
now = datetime.now().astimezone()
|
||||
def should_use_realtime(self, requested_date: str, trade_date: str) -> bool:
|
||||
"""Use live quotes for today's open session until official daily settles."""
|
||||
now = self._now()
|
||||
today = now.strftime("%Y%m%d")
|
||||
return (
|
||||
requested_date == today
|
||||
and trade_date == today
|
||||
and dt_time(9, 15) <= now.time().replace(tzinfo=None) < dt_time(16, 30)
|
||||
and dt_time(9, 15) <= now.time().replace(tzinfo=None) < dt_time(15, 5)
|
||||
)
|
||||
|
||||
def _realtime_dashboard(
|
||||
@@ -122,7 +128,7 @@ class DashboardMixin:
|
||||
)
|
||||
if not codes:
|
||||
raise TushareError("No active stock codes available for rt_k")
|
||||
quotes = self.query("rt_k", {"ts_code": codes})
|
||||
quotes, quote_source = self._load_realtime_quotes(codes, trade_date)
|
||||
if not quotes:
|
||||
raise TushareError(f"No realtime data returned for {trade_date}")
|
||||
|
||||
@@ -178,14 +184,35 @@ class DashboardMixin:
|
||||
)
|
||||
sectors = _build_sectors(limits)
|
||||
previous_sectors = _build_sectors(previous_limits)
|
||||
now = datetime.now().astimezone()
|
||||
now = self._now()
|
||||
market_status = _realtime_market_status(now.time().replace(tzinfo=None))
|
||||
if quote_source == "datahub":
|
||||
notice = (
|
||||
"盘中行情由数据中枢统一提供;涨停原因、封板时间和开板次数以盘后榜单校正为准。"
|
||||
)
|
||||
source_name = "datahub"
|
||||
elif quote_source == "eastmoney_clist":
|
||||
notice = (
|
||||
"盘中行情由东财免费实时快照计算;涨停原因、封板时间和开板次数以盘后榜单校正为准。"
|
||||
)
|
||||
source_name = "eastmoney"
|
||||
elif quote_source == "tencent_qt":
|
||||
notice = (
|
||||
"盘中行情由腾讯免费实时行情计算;涨停原因、封板时间和开板次数以盘后榜单校正为准。"
|
||||
)
|
||||
source_name = "tencent"
|
||||
else:
|
||||
notice = (
|
||||
"盘中行情由 Tushare rt_k 实时计算;涨停原因、封板时间和开板次数以盘后榜单校正为准。"
|
||||
)
|
||||
source_name = "tushare"
|
||||
dashboard = {
|
||||
"meta": {
|
||||
"requested_date": _display_date(requested_date),
|
||||
"trade_date": _display_date(trade_date),
|
||||
"previous_trade_date": _display_date(previous_trade_date),
|
||||
"source": "tushare",
|
||||
"source": source_name,
|
||||
"quote_source": quote_source,
|
||||
"mode": "realtime",
|
||||
"realtime": True,
|
||||
"market_status": market_status,
|
||||
@@ -193,7 +220,8 @@ class DashboardMixin:
|
||||
"auto_refresh": False,
|
||||
"quote_count": len(daily),
|
||||
"updated_at": now.isoformat(timespec="seconds"),
|
||||
"notice": "盘中行情由 Tushare rt_k 实时计算;涨停原因、封板时间和开板次数以盘后榜单校正为准。",
|
||||
"notice": notice,
|
||||
"indices": self._free_realtime_indices() if quote_source != "tushare_rt_k" else [],
|
||||
},
|
||||
"overview": _build_overview(daily, up_rows, down_rows, broken_rows),
|
||||
"limits": limits,
|
||||
@@ -207,6 +235,89 @@ class DashboardMixin:
|
||||
}
|
||||
return apply_sentiment_to_dashboard(dashboard)
|
||||
|
||||
def _realtime_aggregator(self):
|
||||
aggregator = getattr(self, "realtime_aggregator", None)
|
||||
if aggregator is None:
|
||||
raise TushareError("免费实时源未配置")
|
||||
return aggregator
|
||||
|
||||
def _load_realtime_quotes(
|
||||
self,
|
||||
codes: str,
|
||||
trade_date: str,
|
||||
) -> tuple[list[dict[str, Any]], str]:
|
||||
hub = getattr(self, "try_market_quotes", None)
|
||||
if callable(hub):
|
||||
quotes = hub(trade_date)
|
||||
if quotes:
|
||||
return list(quotes), "datahub"
|
||||
rt_error = ""
|
||||
try:
|
||||
quotes = self.query("rt_k", {"ts_code": codes})
|
||||
if quotes:
|
||||
self._mark_quote_legacy("tushare_rt_k", rt_error)
|
||||
return list(quotes), "tushare_rt_k"
|
||||
rt_error = f"No realtime data returned for {trade_date}"
|
||||
except TushareError as exc:
|
||||
rt_error = str(exc)
|
||||
try:
|
||||
quotes, quote_source = self._free_realtime_quotes(trade_date, codes)
|
||||
except Exception as exc:
|
||||
raise TushareError(
|
||||
f"当天盘中实时行情不可用:rt_k={rt_error};免费源={exc}"
|
||||
) from exc
|
||||
if not quotes:
|
||||
raise TushareError(
|
||||
f"当天盘中实时行情不可用:rt_k={rt_error};免费源=empty"
|
||||
)
|
||||
self._mark_quote_legacy(quote_source, rt_error)
|
||||
return quotes, quote_source
|
||||
|
||||
def _mark_quote_legacy(self, source: str, error: str = "") -> None:
|
||||
marker = getattr(self, "record_datahub_legacy", None)
|
||||
if callable(marker):
|
||||
marker("quotes", source, error)
|
||||
|
||||
def _free_realtime_quotes(
|
||||
self,
|
||||
trade_date: str,
|
||||
codes: str = "",
|
||||
) -> tuple[list[dict[str, Any]], str]:
|
||||
aggregator = self._realtime_aggregator()
|
||||
last_error = ""
|
||||
try:
|
||||
quotes = aggregator.eastmoney_market_quotes(expected_date=trade_date)
|
||||
if quotes:
|
||||
return quotes, "eastmoney_clist"
|
||||
except Exception as exc:
|
||||
last_error = str(exc)
|
||||
code_list = [item for item in str(codes or "").split(",") if item]
|
||||
try:
|
||||
quotes = aggregator.tencent_market_quotes(code_list, expected_date=trade_date)
|
||||
except Exception as exc:
|
||||
raise TushareError(
|
||||
f"eastmoney={last_error or 'empty'};tencent={exc}"
|
||||
) from exc
|
||||
if not quotes:
|
||||
raise TushareError(f"eastmoney={last_error or 'empty'};tencent=empty")
|
||||
return quotes, "tencent_qt"
|
||||
|
||||
def _free_realtime_indices(self) -> list[dict[str, Any]]:
|
||||
hub = getattr(self, "try_index_quotes", None)
|
||||
if callable(hub):
|
||||
rows = hub()
|
||||
converted = [item for item in (_hub_index_quote(row) for row in rows or []) if item]
|
||||
if converted:
|
||||
return converted
|
||||
try:
|
||||
rows = self._realtime_aggregator().eastmoney_indices()
|
||||
marker = getattr(self, "record_datahub_legacy", None)
|
||||
if callable(marker):
|
||||
marker("index_quotes", "eastmoney_push2")
|
||||
return rows
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def _load_realtime_reference(
|
||||
self,
|
||||
trade_date: str,
|
||||
@@ -234,7 +345,7 @@ class DashboardMixin:
|
||||
{"trade_date": previous_trade_date},
|
||||
"ts_code,trade_date,total_share,float_share,free_share,total_mv,circ_mv",
|
||||
)
|
||||
if not basic_rows or not price_limits:
|
||||
if not basic_rows:
|
||||
raise TushareError(f"Realtime reference data is incomplete for {trade_date}")
|
||||
result = {
|
||||
"basic_rows": basic_rows,
|
||||
@@ -608,6 +719,31 @@ def _build_yesterday_performance(
|
||||
return result
|
||||
|
||||
|
||||
def _hub_index_quote(row: dict[str, Any]) -> dict[str, Any] | None:
|
||||
ts_code = str(row.get("ts_code") or "")
|
||||
code = str(row.get("code") or ts_code.split(".")[0])
|
||||
close = _number(row.get("price") if row.get("price") not in (None, "") else row.get("close"))
|
||||
previous = _number(
|
||||
row.get("previous_close") if row.get("previous_close") not in (None, "") else row.get("pre_close")
|
||||
)
|
||||
if close <= 0 or previous <= 0:
|
||||
return None
|
||||
amount = _number(row.get("amount"))
|
||||
amount_billion = _number(row.get("amount_billion"))
|
||||
if not amount_billion and amount:
|
||||
amount_billion = round(amount / 100_000_000, 2)
|
||||
return {
|
||||
"code": code,
|
||||
"name": str(row.get("name") or code),
|
||||
"price": close,
|
||||
"change": _number(row.get("pct_chg") if row.get("pct_chg") not in (None, "") else row.get("change")),
|
||||
"previous_close": previous,
|
||||
"amount_billion": amount_billion,
|
||||
"quote_time": str(row.get("quote_time") or ""),
|
||||
"source": "datahub",
|
||||
}
|
||||
|
||||
|
||||
def _build_limit_performance(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
result = []
|
||||
for level in sorted({int(row.get("prior_streak") or 1) for row in rows}, reverse=True):
|
||||
|
||||
@@ -6,6 +6,17 @@ from typing import Any
|
||||
from backend.data.numbers import finite_number as _number
|
||||
|
||||
|
||||
def calendar_is_open(value: Any) -> bool:
|
||||
if value in (True, 1, "1", "Y", "y"):
|
||||
return True
|
||||
if value in (False, 0, "0", "N", "n", None, ""):
|
||||
return False
|
||||
try:
|
||||
return int(value) == 1
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def _text(value: Any) -> str:
|
||||
if isinstance(value, (list, tuple, set)):
|
||||
return "、".join(str(item).strip() for item in value if str(item).strip())
|
||||
|
||||
@@ -59,6 +59,87 @@ class IndexMixin:
|
||||
}
|
||||
|
||||
def realtime_market_indices(self, requested_date: str) -> dict[str, Any]:
|
||||
hub = getattr(self, "try_index_quotes", None)
|
||||
if callable(hub):
|
||||
rows = hub()
|
||||
if rows:
|
||||
try:
|
||||
return self._hub_realtime_market_indices(requested_date, rows)
|
||||
except TushareError:
|
||||
pass
|
||||
try:
|
||||
payload = self._tushare_realtime_market_indices(requested_date)
|
||||
marker = getattr(self, "record_datahub_legacy", None)
|
||||
if callable(marker):
|
||||
marker("index_quotes", "tushare_rt_idx_k")
|
||||
return payload
|
||||
except TushareError:
|
||||
payload = self._free_realtime_market_indices(requested_date)
|
||||
marker = getattr(self, "record_datahub_legacy", None)
|
||||
if callable(marker):
|
||||
marker("index_quotes", str(payload.get("source") or "eastmoney_push2"))
|
||||
return payload
|
||||
|
||||
def _hub_realtime_market_indices(
|
||||
self,
|
||||
requested_date: str,
|
||||
rows: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
trade_date, _ = self.resolve_trade_context(requested_date)
|
||||
index_names = {
|
||||
"000001.SH": "上证指数",
|
||||
"399001.SZ": "深证成指",
|
||||
"399006.SZ": "创业板指",
|
||||
}
|
||||
by_code = {str(row.get("ts_code") or ""): row for row in rows}
|
||||
by_symbol = {str(row.get("code") or ""): row for row in rows}
|
||||
indices = []
|
||||
for ts_code, name in index_names.items():
|
||||
row = by_code.get(ts_code) or by_symbol.get(ts_code.split(".")[0])
|
||||
if not row:
|
||||
continue
|
||||
close = _number(row.get("price") if row.get("price") not in (None, "") else row.get("close"))
|
||||
previous_close = _number(
|
||||
row.get("previous_close") if row.get("previous_close") not in (None, "") else row.get("pre_close")
|
||||
)
|
||||
if close <= 0 or previous_close <= 0:
|
||||
continue
|
||||
amount = _number(row.get("amount"))
|
||||
amount_billion = _number(row.get("amount_billion"))
|
||||
if not amount_billion and amount:
|
||||
amount_billion = round(amount / 100_000_000, 2)
|
||||
indices.append(
|
||||
{
|
||||
"ts_code": ts_code,
|
||||
"name": str(row.get("name") or name).strip(),
|
||||
"trade_date": trade_date,
|
||||
"close": close,
|
||||
"pct_chg": round(
|
||||
_number(row.get("pct_chg")) or (close / previous_close - 1) * 100,
|
||||
3,
|
||||
),
|
||||
"return_5d": 0,
|
||||
"amount_billion": amount_billion,
|
||||
"quote_time": str(row.get("quote_time") or ""),
|
||||
"source": "datahub",
|
||||
}
|
||||
)
|
||||
if len(indices) != 3:
|
||||
raise TushareError("Realtime index quotes are incomplete")
|
||||
return {
|
||||
"trade_date": trade_date,
|
||||
"source": "datahub",
|
||||
"realtime": True,
|
||||
"precise": True,
|
||||
"indices": indices,
|
||||
"aggregate": {
|
||||
"average_pct_chg": round(sum(item["pct_chg"] for item in indices) / len(indices), 3),
|
||||
"average_return_5d": 0,
|
||||
"average_return_20d": 0,
|
||||
},
|
||||
}
|
||||
|
||||
def _tushare_realtime_market_indices(self, requested_date: str) -> dict[str, Any]:
|
||||
trade_date, _ = self.resolve_trade_context(requested_date)
|
||||
index_names = {
|
||||
"000001.SH": "上证指数",
|
||||
@@ -116,3 +197,52 @@ class IndexMixin:
|
||||
"average_return_20d": 0,
|
||||
},
|
||||
}
|
||||
|
||||
def _free_realtime_market_indices(self, requested_date: str) -> dict[str, Any]:
|
||||
trade_date, _ = self.resolve_trade_context(requested_date)
|
||||
aggregator = getattr(self, "realtime_aggregator", None)
|
||||
if aggregator is None:
|
||||
raise TushareError("免费实时源未配置")
|
||||
quotes = aggregator.eastmoney_indices()
|
||||
index_names = {
|
||||
"000001": ("000001.SH", "上证指数"),
|
||||
"399001": ("399001.SZ", "深证成指"),
|
||||
"399006": ("399006.SZ", "创业板指"),
|
||||
}
|
||||
indices = []
|
||||
for quote in quotes:
|
||||
mapped = index_names.get(str(quote.get("code") or ""))
|
||||
if not mapped:
|
||||
continue
|
||||
ts_code, name = mapped
|
||||
close = _number(quote.get("price"))
|
||||
previous_close = _number(quote.get("previous_close"))
|
||||
if close <= 0 or previous_close <= 0:
|
||||
continue
|
||||
indices.append(
|
||||
{
|
||||
"ts_code": ts_code,
|
||||
"name": str(quote.get("name") or name).strip(),
|
||||
"trade_date": trade_date,
|
||||
"close": close,
|
||||
"pct_chg": round(_number(quote.get("change")) or (close / previous_close - 1) * 100, 3),
|
||||
"return_5d": 0,
|
||||
"amount_billion": round(_number(quote.get("amount_billion")), 2),
|
||||
"quote_time": quote.get("quote_time") or "",
|
||||
"source": quote.get("source") or "eastmoney_push2",
|
||||
}
|
||||
)
|
||||
if len(indices) != 3:
|
||||
raise TushareError("Realtime index quotes are incomplete")
|
||||
return {
|
||||
"trade_date": trade_date,
|
||||
"source": "eastmoney_push2",
|
||||
"realtime": True,
|
||||
"precise": True,
|
||||
"indices": indices,
|
||||
"aggregate": {
|
||||
"average_pct_chg": round(sum(item["pct_chg"] for item in indices) / len(indices), 3),
|
||||
"average_return_5d": 0,
|
||||
"average_return_20d": 0,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -19,8 +19,20 @@ class RealtimeAggregateError(RuntimeError):
|
||||
|
||||
|
||||
EASTMONEY_INDEX_URL = "https://push2.eastmoney.com/api/qt/ulist.np/get"
|
||||
EASTMONEY_STOCK_URL = "https://push2.eastmoney.com/api/qt/stock/get"
|
||||
EASTMONEY_STOCK_FIELDS = "f43,f44,f45,f46,f47,f48,f57,f58,f60,f86,f168"
|
||||
EASTMONEY_SECTOR_URL = "https://push2.eastmoney.com/api/qt/clist/get"
|
||||
EASTMONEY_A_SHARE_BOARDS = (
|
||||
"m:0+t:6",
|
||||
"m:0+t:80",
|
||||
"m:1+t:2",
|
||||
"m:1+t:23",
|
||||
"m:0+t:81",
|
||||
)
|
||||
EASTMONEY_QUOTE_FIELDS = "f12,f13,f14,f2,f3,f4,f5,f6,f15,f16,f17,f18,f8,f124"
|
||||
EASTMONEY_MARKET_PAGE_SIZE = 100
|
||||
TENCENT_INDEX_URL = "https://qt.gtimg.cn/q=sh000001,sz399001,sz399006"
|
||||
TENCENT_QUOTE_URL = "https://qt.gtimg.cn/q="
|
||||
THS_LIMIT_URL = "https://data.10jqka.com.cn/dataapi/limit_up/limit_up_pool"
|
||||
XGB_POOL_URL = "https://flash-api.xuangubao.cn/api/pool/detail"
|
||||
BROWSER_USER_AGENT = (
|
||||
@@ -134,6 +146,181 @@ class WebRealtimeAggregator:
|
||||
raise RealtimeAggregateError(f"Eastmoney returned {len(result)}/3 indices")
|
||||
return result
|
||||
|
||||
def eastmoney_market_quotes(self, expected_date: str = "") -> list[dict[str, Any]]:
|
||||
"""Full A-share snapshot via Eastmoney clist, used when Tushare rt_k is unavailable."""
|
||||
now = time.time()
|
||||
cache_key = "assembled:eastmoney_market"
|
||||
with self._response_cache_lock:
|
||||
cached = self._response_cache.get(cache_key)
|
||||
cache_age = now - float((cached or {}).get("created_at") or 0)
|
||||
if cached and cache_age <= min(20, self.response_cache_ttl_seconds):
|
||||
quotes = list(cached.get("payload") or [])
|
||||
return self._filter_quotes_by_date(quotes, expected_date)
|
||||
|
||||
rows: list[dict[str, Any]] = []
|
||||
board_errors: list[str] = []
|
||||
for board in EASTMONEY_A_SHARE_BOARDS:
|
||||
try:
|
||||
rows.extend(self._eastmoney_board_quotes(board))
|
||||
except Exception as exc:
|
||||
board_errors.append(f"{board}:{exc}")
|
||||
quotes = []
|
||||
seen: set[str] = set()
|
||||
for row in rows:
|
||||
quote = _normalize_eastmoney_quote(row)
|
||||
ts_code = str((quote or {}).get("ts_code") or "")
|
||||
if not quote or ts_code in seen:
|
||||
continue
|
||||
seen.add(ts_code)
|
||||
quotes.append(quote)
|
||||
if len(quotes) < 200:
|
||||
detail = f";{'; '.join(board_errors)}" if board_errors else ""
|
||||
raise RealtimeAggregateError(
|
||||
f"Eastmoney market snapshot too small: {len(quotes)}{detail}"
|
||||
)
|
||||
quotes = self._filter_quotes_by_date(quotes, expected_date)
|
||||
with self._response_cache_lock:
|
||||
self._response_cache[cache_key] = {"created_at": now, "payload": quotes}
|
||||
return quotes
|
||||
|
||||
def _eastmoney_board_quotes(self, board: str) -> list[dict[str, Any]]:
|
||||
first = self._eastmoney_market_page(board, 1)
|
||||
data = first.get("data") or {}
|
||||
rows = _diff_rows(data)
|
||||
total = int(_number(data.get("total")))
|
||||
page_count = 1
|
||||
if total > 0:
|
||||
page_count = max(1, (total + EASTMONEY_MARKET_PAGE_SIZE - 1) // EASTMONEY_MARKET_PAGE_SIZE)
|
||||
for page in range(2, min(page_count, 40) + 1):
|
||||
payload = self._eastmoney_market_page(board, page)
|
||||
rows.extend(_diff_rows(payload.get("data") or {}))
|
||||
return rows
|
||||
|
||||
def _eastmoney_market_page(self, board: str, page: int) -> dict[str, Any]:
|
||||
return self._get_json(
|
||||
EASTMONEY_SECTOR_URL,
|
||||
{
|
||||
"pn": str(page),
|
||||
"pz": str(EASTMONEY_MARKET_PAGE_SIZE),
|
||||
"po": "1",
|
||||
"np": "1",
|
||||
"fltt": "2",
|
||||
"invt": "2",
|
||||
"fid": "f12",
|
||||
"fs": board,
|
||||
"fields": EASTMONEY_QUOTE_FIELDS,
|
||||
},
|
||||
referer="https://quote.eastmoney.com/center/gridlist.html",
|
||||
)
|
||||
|
||||
def _filter_quotes_by_date(
|
||||
self,
|
||||
quotes: list[dict[str, Any]],
|
||||
expected_date: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
want = str(expected_date or "").replace("-", "")
|
||||
if not want or not quotes:
|
||||
return quotes
|
||||
dated = [item for item in quotes if str(item.get("quote_date") or "") == want]
|
||||
if dated and len(dated) >= max(100, int(len(quotes) * 0.2)):
|
||||
return dated
|
||||
if dated:
|
||||
return dated
|
||||
if all(not item.get("quote_date") for item in quotes):
|
||||
return quotes
|
||||
raise RealtimeAggregateError(f"Eastmoney quotes are not for {want}")
|
||||
|
||||
def tencent_market_quotes(
|
||||
self,
|
||||
codes: list[str],
|
||||
expected_date: str = "",
|
||||
) -> list[dict[str, Any]]:
|
||||
symbols: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for raw in codes:
|
||||
ts = str(raw or "").strip().upper()
|
||||
if not ts:
|
||||
continue
|
||||
symbol = ts.split(".")[0]
|
||||
if not symbol.isdigit() or len(symbol) != 6 or symbol in seen:
|
||||
continue
|
||||
seen.add(symbol)
|
||||
if ts.endswith(".SH") or symbol.startswith(("5", "6", "9")):
|
||||
symbols.append(f"sh{symbol}")
|
||||
elif ts.endswith(".BJ") or symbol.startswith(("4", "8")):
|
||||
symbols.append(f"bj{symbol}")
|
||||
else:
|
||||
symbols.append(f"sz{symbol}")
|
||||
if not symbols:
|
||||
raise RealtimeAggregateError("No stock codes available for Tencent quotes")
|
||||
|
||||
quotes: list[dict[str, Any]] = []
|
||||
batch_size = 80
|
||||
|
||||
def load_batch(batch: list[str]) -> list[dict[str, Any]]:
|
||||
raw, _cache_age = self._get_text(
|
||||
f"{TENCENT_QUOTE_URL}{','.join(batch)}",
|
||||
referer="https://gu.qq.com/",
|
||||
encoding="gb18030",
|
||||
)
|
||||
return [
|
||||
quote
|
||||
for line in raw.splitlines()
|
||||
if (quote := _parse_tencent_stock_quote(line))
|
||||
]
|
||||
|
||||
batches = [symbols[index:index + batch_size] for index in range(0, len(symbols), batch_size)]
|
||||
errors: list[str] = []
|
||||
with ThreadPoolExecutor(max_workers=4) as executor:
|
||||
for result in executor.map(self._capture, [lambda batch=batch: load_batch(batch) for batch in batches]):
|
||||
rows, status = result
|
||||
if status.get("ok") and rows:
|
||||
quotes.extend(rows)
|
||||
elif not status.get("ok"):
|
||||
errors.append(str(status.get("error") or "batch failed"))
|
||||
if len(quotes) < 200:
|
||||
detail = f";{'; '.join(errors[:3])}" if errors else ""
|
||||
raise RealtimeAggregateError(
|
||||
f"Tencent market snapshot too small: {len(quotes)}{detail}"
|
||||
)
|
||||
return self._filter_quotes_by_date(quotes, expected_date)
|
||||
|
||||
def tencent_stock_quote(self, code: str, expected_date: str = "") -> dict[str, Any]:
|
||||
symbol, _secid, ts_code = _a_share_identity(code)
|
||||
raw, _cache_age = self._get_text(
|
||||
f"{TENCENT_QUOTE_URL}{symbol}",
|
||||
referer="https://gu.qq.com/",
|
||||
encoding="gb18030",
|
||||
)
|
||||
quote = next(
|
||||
(
|
||||
item
|
||||
for line in raw.splitlines()
|
||||
if (item := _parse_tencent_stock_quote(line))
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not quote:
|
||||
raise RealtimeAggregateError(f"Tencent stock quote unavailable for {ts_code}")
|
||||
return _require_quote_date(quote, expected_date)
|
||||
|
||||
def eastmoney_stock_quote(self, code: str, expected_date: str = "") -> dict[str, Any]:
|
||||
_symbol, secid, ts_code = _a_share_identity(code)
|
||||
payload = self._get_json(
|
||||
EASTMONEY_STOCK_URL,
|
||||
{
|
||||
"secid": secid,
|
||||
"invt": "2",
|
||||
"fltt": "2",
|
||||
"fields": EASTMONEY_STOCK_FIELDS,
|
||||
},
|
||||
referer="https://quote.eastmoney.com/",
|
||||
)
|
||||
quote = _normalize_eastmoney_stock_quote(payload.get("data") or {}, ts_code)
|
||||
if not quote:
|
||||
raise RealtimeAggregateError(f"Eastmoney stock quote unavailable for {ts_code}")
|
||||
return _require_quote_date(quote, expected_date)
|
||||
|
||||
def tencent_indices(self) -> list[dict[str, Any]]:
|
||||
raw, cache_age = self._get_text(
|
||||
TENCENT_INDEX_URL,
|
||||
@@ -397,6 +584,143 @@ class WebRealtimeAggregator:
|
||||
) from last_error
|
||||
|
||||
|
||||
def _diff_rows(data: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
diff = data.get("diff") or []
|
||||
if isinstance(diff, dict):
|
||||
return [row for row in diff.values() if isinstance(row, dict)]
|
||||
return [row for row in diff if isinstance(row, dict)]
|
||||
|
||||
|
||||
def _a_share_identity(code: str) -> tuple[str, str, str]:
|
||||
raw = str(code or "").strip().upper()
|
||||
symbol = raw.split(".")[0]
|
||||
if not symbol.isdigit() or len(symbol) != 6:
|
||||
raise RealtimeAggregateError("Invalid stock code")
|
||||
if raw.endswith(".SH") or symbol.startswith(("5", "6", "9")):
|
||||
return f"sh{symbol}", f"1.{symbol}", f"{symbol}.SH"
|
||||
if raw.endswith(".BJ") or symbol.startswith(("4", "8")):
|
||||
return f"bj{symbol}", f"0.{symbol}", f"{symbol}.BJ"
|
||||
return f"sz{symbol}", f"0.{symbol}", f"{symbol}.SZ"
|
||||
|
||||
|
||||
def _require_quote_date(quote: dict[str, Any], expected_date: str) -> dict[str, Any]:
|
||||
want = str(expected_date or "").replace("-", "")
|
||||
got = str(quote.get("quote_date") or "")
|
||||
if want and got != want:
|
||||
raise RealtimeAggregateError(f"quote date {got or 'empty'} is not {want}")
|
||||
return quote
|
||||
|
||||
|
||||
def _normalize_eastmoney_stock_quote(
|
||||
row: dict[str, Any], ts_code: str
|
||||
) -> dict[str, Any] | None:
|
||||
close = _number(row.get("f43"))
|
||||
previous_close = _number(row.get("f60"))
|
||||
if close <= 0 or previous_close <= 0:
|
||||
return None
|
||||
epoch = int(_number(row.get("f86")))
|
||||
quote_date = ""
|
||||
if epoch > 0:
|
||||
quote_date = datetime.fromtimestamp(epoch).astimezone().strftime("%Y%m%d")
|
||||
return {
|
||||
"ts_code": ts_code,
|
||||
"name": row.get("f58") or ts_code.split(".")[0],
|
||||
"pre_close": previous_close,
|
||||
"open": _number(row.get("f46")),
|
||||
"high": _number(row.get("f44")),
|
||||
"low": _number(row.get("f45")),
|
||||
"close": close,
|
||||
"vol": _number(row.get("f47")) * 100,
|
||||
"amount": _number(row.get("f48")),
|
||||
"num": 0,
|
||||
"quote_date": quote_date,
|
||||
"quote_time_epoch": epoch,
|
||||
"turnover_rate": _number(row.get("f168")),
|
||||
"source": "eastmoney_stock",
|
||||
}
|
||||
|
||||
|
||||
def _parse_tencent_stock_quote(line: str) -> dict[str, Any] | None:
|
||||
if '="' not in line:
|
||||
return None
|
||||
prefix, payload = line.split('="', 1)
|
||||
fields = payload.rsplit('";', 1)[0].split("~")
|
||||
if len(fields) < 38:
|
||||
return None
|
||||
symbol = fields[2]
|
||||
if not symbol.isdigit() or len(symbol) != 6:
|
||||
return None
|
||||
close = _number(fields[3])
|
||||
previous_close = _number(fields[4])
|
||||
if close <= 0 or previous_close <= 0:
|
||||
return None
|
||||
marker = prefix.lower()
|
||||
if "sh" in marker:
|
||||
ts_code = f"{symbol}.SH"
|
||||
elif "bj" in marker:
|
||||
ts_code = f"{symbol}.BJ"
|
||||
else:
|
||||
ts_code = f"{symbol}.SZ"
|
||||
try:
|
||||
quote_time = datetime.strptime(fields[30], "%Y%m%d%H%M%S")
|
||||
quote_date = quote_time.strftime("%Y%m%d")
|
||||
epoch = int(quote_time.timestamp())
|
||||
except ValueError:
|
||||
quote_date = ""
|
||||
epoch = 0
|
||||
return {
|
||||
"ts_code": ts_code,
|
||||
"name": fields[1] or symbol,
|
||||
"pre_close": previous_close,
|
||||
"open": _number(fields[5]),
|
||||
"high": _number(fields[33]),
|
||||
"low": _number(fields[34]),
|
||||
"close": close,
|
||||
"vol": _number(fields[6]) * 100,
|
||||
"amount": _number(fields[37]) * 10000,
|
||||
"num": 0,
|
||||
"quote_date": quote_date,
|
||||
"quote_time_epoch": epoch,
|
||||
"source": "tencent_qt",
|
||||
}
|
||||
|
||||
|
||||
def _normalize_eastmoney_quote(row: dict[str, Any]) -> dict[str, Any] | None:
|
||||
symbol = str(row.get("f12") or "").strip()
|
||||
if not symbol.isdigit() or len(symbol) != 6:
|
||||
return None
|
||||
close = _number(row.get("f2"))
|
||||
previous_close = _number(row.get("f18"))
|
||||
if close <= 0 or previous_close <= 0:
|
||||
return None
|
||||
market = int(_number(row.get("f13")))
|
||||
if market == 1 or symbol.startswith(("5", "6", "9")):
|
||||
ts_code = f"{symbol}.SH"
|
||||
elif symbol.startswith(("4", "8")):
|
||||
ts_code = f"{symbol}.BJ"
|
||||
else:
|
||||
ts_code = f"{symbol}.SZ"
|
||||
epoch = int(_number(row.get("f124")))
|
||||
quote_date = ""
|
||||
if epoch > 0:
|
||||
quote_date = datetime.fromtimestamp(epoch).astimezone().strftime("%Y%m%d")
|
||||
return {
|
||||
"ts_code": ts_code,
|
||||
"name": row.get("f14") or symbol,
|
||||
"pre_close": previous_close,
|
||||
"open": _number(row.get("f17")),
|
||||
"high": _number(row.get("f15")),
|
||||
"low": _number(row.get("f16")),
|
||||
"close": close,
|
||||
"vol": _number(row.get("f5")) * 100,
|
||||
"amount": _number(row.get("f6")),
|
||||
"num": 0,
|
||||
"quote_date": quote_date,
|
||||
"quote_time_epoch": epoch,
|
||||
"source": "eastmoney_clist",
|
||||
}
|
||||
|
||||
|
||||
def _normalize_sector(value: Any) -> str:
|
||||
text = str(value or "").strip().replace(" ", "")
|
||||
for suffix in ("板块", "概念", "行业", "Ⅱ", "Ⅲ", "(A股)", "(A股)"):
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
import urllib.error
|
||||
@@ -15,12 +16,15 @@ from typing import Any, ClassVar
|
||||
from backend.bootstrap.config import tushare_code as _stock_market_code
|
||||
from backend.data.providers.ifind_client import IfindError, IfindHttpClient
|
||||
|
||||
LOGGER = logging.getLogger("xiaobai.charts")
|
||||
|
||||
|
||||
class ChartDataError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
TRENDS_URL = "https://push2delay.eastmoney.com/api/qt/stock/trends2/get"
|
||||
HIS_TRENDS_URL = "https://push2his.eastmoney.com/api/qt/stock/trends2/get"
|
||||
BOARD_LIST_URL = "https://push2delay.eastmoney.com/api/qt/clist/get"
|
||||
BROWSER_USER_AGENT = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
@@ -37,14 +41,23 @@ INDEX_SECIDS = {
|
||||
class MarketChartClient:
|
||||
"""Prefer iFinD for display charts and retain Eastmoney as a last resort."""
|
||||
|
||||
def __init__(self, ifind: IfindHttpClient, fallback: "EastmoneyChartClient") -> None:
|
||||
def __init__(
|
||||
self,
|
||||
ifind: IfindHttpClient,
|
||||
fallback: "EastmoneyChartClient",
|
||||
datahub: Any = None,
|
||||
) -> None:
|
||||
self.ifind = ifind
|
||||
self.fallback = fallback
|
||||
self.datahub = datahub
|
||||
|
||||
def stock_intraday(self, code: str) -> dict[str, Any]:
|
||||
normalized = str(code or "").strip()
|
||||
if not re.fullmatch(r"\d{6}", normalized):
|
||||
raise ChartDataError("Invalid stock code")
|
||||
hub_chart = self._datahub_intraday(normalized)
|
||||
if hub_chart is not None:
|
||||
return hub_chart
|
||||
ifind_code = _stock_market_code(normalized)
|
||||
try:
|
||||
return self._ifind_intraday(ifind_code, "stock", normalized)
|
||||
@@ -55,12 +68,18 @@ class MarketChartClient:
|
||||
normalized = str(code or "").strip()
|
||||
if not re.fullmatch(r"\d{6}", normalized):
|
||||
raise ChartDataError("Invalid stock code")
|
||||
hub_rows = self._datahub_daily(normalized, end_date, limit, "daily")
|
||||
if hub_rows:
|
||||
return hub_rows
|
||||
return self._ifind_daily(_stock_market_code(normalized), end_date, limit)
|
||||
|
||||
def index_daily(self, identifier: str, end_date: str, limit: int = 90) -> list[dict[str, Any]]:
|
||||
normalized = str(identifier or "").strip().upper()
|
||||
if normalized not in INDEX_SECIDS:
|
||||
raise ChartDataError("Unsupported index")
|
||||
hub_rows = self._datahub_daily(normalized, end_date, limit, "index_daily")
|
||||
if hub_rows:
|
||||
return hub_rows
|
||||
return self._ifind_daily(normalized, end_date, limit)
|
||||
|
||||
def board_daily(self, identifier: str, end_date: str, limit: int = 90) -> list[dict[str, Any]]:
|
||||
@@ -73,11 +92,135 @@ class MarketChartClient:
|
||||
normalized = str(identifier or "").strip().upper()
|
||||
if normalized not in INDEX_SECIDS:
|
||||
raise ChartDataError("Unsupported index")
|
||||
hub_chart = self._datahub_intraday(normalized)
|
||||
if hub_chart is not None:
|
||||
return hub_chart
|
||||
try:
|
||||
return self._ifind_intraday(normalized, "index", normalized)
|
||||
except (IfindError, ChartDataError):
|
||||
return self.fallback.index_intraday(normalized)
|
||||
|
||||
def _datahub_intraday(self, code: str) -> dict[str, Any] | None:
|
||||
if self.datahub is None:
|
||||
return None
|
||||
try:
|
||||
chart = self.datahub.try_intraday(code)
|
||||
except Exception as exc:
|
||||
LOGGER.warning("datahub intraday unexpected error: %s", exc)
|
||||
return None
|
||||
if not chart:
|
||||
return None
|
||||
points = list(chart.get("points") or [])
|
||||
if not points:
|
||||
return None
|
||||
return chart
|
||||
|
||||
def _datahub_daily(
|
||||
self,
|
||||
code: str,
|
||||
end_date: str,
|
||||
limit: int,
|
||||
dataset: str,
|
||||
) -> list[dict[str, Any]] | None:
|
||||
if self.datahub is None or not hasattr(self.datahub, "try_daily_chart"):
|
||||
return None
|
||||
try:
|
||||
rows = self.datahub.try_daily_chart(code, end_date, limit, dataset)
|
||||
except Exception as exc:
|
||||
LOGGER.warning("datahub daily unexpected error: %s", exc)
|
||||
rows = None
|
||||
if not rows:
|
||||
if hasattr(self.datahub, "record_legacy"):
|
||||
self.datahub.record_legacy(dataset, "ifind")
|
||||
return None
|
||||
compact_end = str(end_date or "").replace("-", "")
|
||||
market_now = datetime.now().astimezone()
|
||||
today = market_now.strftime("%Y%m%d")
|
||||
market_open = (
|
||||
market_now.weekday() < 5
|
||||
and market_now.time().replace(tzinfo=None) >= dt_time(9, 30)
|
||||
)
|
||||
if compact_end == today and market_open:
|
||||
overlay = self._datahub_today_bar(code, dataset, rows)
|
||||
if overlay:
|
||||
if rows and rows[-1]["trade_date"] == overlay["trade_date"]:
|
||||
rows[-1] = overlay
|
||||
else:
|
||||
rows.append(overlay)
|
||||
return rows
|
||||
|
||||
def _datahub_today_bar(
|
||||
self,
|
||||
code: str,
|
||||
dataset: str,
|
||||
history: list[dict[str, Any]],
|
||||
) -> dict[str, Any] | None:
|
||||
today_display = datetime.now().astimezone().date().isoformat()
|
||||
previous = history[-1]["close"] if history and history[-1]["trade_date"] != today_display else (
|
||||
history[-2]["close"] if len(history) >= 2 else 0.0
|
||||
)
|
||||
quote = None
|
||||
if dataset == "index_daily" and hasattr(self.datahub, "try_index_quotes"):
|
||||
quotes = self.datahub.try_index_quotes() or []
|
||||
quote = next(
|
||||
(
|
||||
item for item in quotes
|
||||
if str(item.get("ts_code") or "") == code or str(item.get("code") or "") == code.split(".")[0]
|
||||
),
|
||||
None,
|
||||
)
|
||||
elif hasattr(self.datahub, "try_quotes"):
|
||||
quotes = self.datahub.try_quotes([code]) or []
|
||||
quote = quotes[0] if quotes else None
|
||||
if quote:
|
||||
close = _number(quote.get("close") if quote.get("close") not in (None, "") else quote.get("price"))
|
||||
open_price = _number(quote.get("open"))
|
||||
high = _number(quote.get("high"))
|
||||
low = _number(quote.get("low"))
|
||||
previous_close = _number(
|
||||
quote.get("pre_close") if quote.get("pre_close") not in (None, "") else quote.get("previous_close")
|
||||
) or previous
|
||||
volume = _number(quote.get("vol") if quote.get("vol") not in (None, "") else quote.get("volume"))
|
||||
amount = _number(quote.get("amount"))
|
||||
if close > 0 and open_price > 0:
|
||||
return {
|
||||
"trade_date": today_display,
|
||||
"open": open_price,
|
||||
"high": high or close,
|
||||
"low": low or close,
|
||||
"close": close,
|
||||
"change": round((close / previous_close - 1) * 100, 4) if previous_close else 0.0,
|
||||
"volume": volume,
|
||||
"amount_billion": amount / 100_000_000,
|
||||
"realtime": True,
|
||||
}
|
||||
chart = self._datahub_intraday(code)
|
||||
points = list((chart or {}).get("points") or [])
|
||||
if not points:
|
||||
return None
|
||||
closes = [_number(point.get("close")) for point in points if _number(point.get("close")) > 0]
|
||||
if not closes:
|
||||
return None
|
||||
opens = [_number(point.get("open")) for point in points if _number(point.get("open")) > 0]
|
||||
highs = [_number(point.get("high")) for point in points if _number(point.get("high")) > 0]
|
||||
lows = [_number(point.get("low")) for point in points if _number(point.get("low")) > 0]
|
||||
volume = sum(_number(point.get("volume")) for point in points)
|
||||
amount = sum(_number(point.get("amount")) for point in points)
|
||||
previous_close = _number((chart or {}).get("previous_close")) or previous
|
||||
close = closes[-1]
|
||||
open_price = opens[0] if opens else closes[0]
|
||||
return {
|
||||
"trade_date": today_display,
|
||||
"open": open_price,
|
||||
"high": max(highs or closes),
|
||||
"low": min(lows or closes),
|
||||
"close": close,
|
||||
"change": round((close / previous_close - 1) * 100, 4) if previous_close else 0.0,
|
||||
"volume": volume,
|
||||
"amount_billion": amount / 100_000_000,
|
||||
"realtime": True,
|
||||
}
|
||||
|
||||
def board_intraday(self, identifier: str, name: str = "") -> dict[str, Any]:
|
||||
normalized = str(identifier or "").strip().upper()
|
||||
try:
|
||||
@@ -305,21 +448,29 @@ class EastmoneyChartClient:
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
payload = self._request_json(
|
||||
TRENDS_URL,
|
||||
{
|
||||
"secid": secid,
|
||||
"fields1": "f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13",
|
||||
"fields2": "f51,f52,f53,f54,f55,f56,f57,f58",
|
||||
"iscr": "0",
|
||||
"ndays": "1",
|
||||
},
|
||||
"https://quote.eastmoney.com/",
|
||||
)
|
||||
data = payload.get("data") or {}
|
||||
points = [point for raw in data.get("trends") or [] if (point := _parse_trend(raw))]
|
||||
params = {
|
||||
"secid": secid,
|
||||
"fields1": "f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13",
|
||||
"fields2": "f51,f52,f53,f54,f55,f56,f57,f58",
|
||||
"iscr": "0",
|
||||
}
|
||||
last_error: Exception | None = None
|
||||
data: dict[str, Any] = {}
|
||||
points: list[dict[str, Any]] = []
|
||||
for url, ndays in ((TRENDS_URL, "1"), (TRENDS_URL, "5"), (HIS_TRENDS_URL, "5")):
|
||||
request_params = {**params, "ndays": ndays}
|
||||
try:
|
||||
payload = self._request_json(url, request_params, "https://quote.eastmoney.com/")
|
||||
except ChartDataError as exc:
|
||||
last_error = exc
|
||||
continue
|
||||
data = payload.get("data") or {}
|
||||
parsed = [point for raw in data.get("trends") or [] if (point := _parse_trend(raw))]
|
||||
points = _latest_session(parsed)
|
||||
if points:
|
||||
break
|
||||
if not points:
|
||||
raise ChartDataError("No intraday chart data returned")
|
||||
raise ChartDataError("No intraday chart data returned") from last_error
|
||||
|
||||
result = {
|
||||
"entity_type": entity_type,
|
||||
@@ -433,6 +584,15 @@ class EastmoneyChartClient:
|
||||
raise ChartDataError("Intraday chart request failed") from last_error
|
||||
|
||||
|
||||
def _latest_session(points: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
if not points:
|
||||
return []
|
||||
latest = max(str(point.get("date") or "") for point in points)
|
||||
if not latest:
|
||||
return points
|
||||
return [point for point in points if str(point.get("date") or "") == latest]
|
||||
|
||||
|
||||
def _parse_trend(raw: Any) -> dict[str, Any] | None:
|
||||
fields = str(raw or "").split(",")
|
||||
if len(fields) < 8 or " " not in fields[0]:
|
||||
|
||||
@@ -15,6 +15,7 @@ from backend.bootstrap.config import (
|
||||
)
|
||||
from backend.data.providers.ifind_client import IfindError
|
||||
from backend.data.providers.tushare_client import TushareClient, TushareError
|
||||
from backend.data.realtime import RealtimeAggregateError
|
||||
from backend.features.market.backfill_history import (
|
||||
DEFAULT_RECENT_TRADING_DAYS,
|
||||
MAX_RANGE_TRADING_DAYS,
|
||||
@@ -42,6 +43,7 @@ SEARCH_TYPE_LABELS = {
|
||||
"theme": "题材",
|
||||
"index": "指数",
|
||||
}
|
||||
TODAY_DAILY_UNAVAILABLE_NOTICE = "今日日K暂不可用,仍显示最近收盘K线。"
|
||||
THS_SEARCH_TYPES = {
|
||||
"I": ("sector", "行业板块"),
|
||||
"R": ("sector", "地域板块"),
|
||||
@@ -63,11 +65,37 @@ class MarketServiceMixin:
|
||||
if gateway is not None:
|
||||
return gateway.tushare()
|
||||
# Compatibility for isolated legacy unit-test service stubs.
|
||||
return TushareClient(self.token)
|
||||
client = TushareClient(self.token)
|
||||
aggregator = getattr(self, "realtime_aggregator", None)
|
||||
if aggregator is not None:
|
||||
client.realtime_aggregator = aggregator
|
||||
return client
|
||||
|
||||
def _now(self) -> datetime:
|
||||
clock = getattr(self, "clock", None)
|
||||
if callable(clock):
|
||||
return clock()
|
||||
return datetime.now().astimezone()
|
||||
|
||||
def _is_requested_open_session(self, requested_date: str) -> bool:
|
||||
now = self._now()
|
||||
if requested_date != now.strftime("%Y%m%d"):
|
||||
return False
|
||||
if now.time().replace(tzinfo=None) < dt_time(9, 15):
|
||||
return False
|
||||
client = self._tushare_client() if self.configured else None
|
||||
resolve = getattr(client, "resolve_trade_context", None) if client else None
|
||||
if resolve is None:
|
||||
return now.weekday() < 5
|
||||
try:
|
||||
trade_date, _ = resolve(requested_date)
|
||||
except Exception:
|
||||
return now.weekday() < 5
|
||||
return str(trade_date or "") == requested_date
|
||||
|
||||
def get_dashboard(self, trade_date: str, force: bool = False) -> dict[str, Any]:
|
||||
normalized_date = normalize_date(trade_date)
|
||||
now = datetime.now().astimezone()
|
||||
now = self._now()
|
||||
if (
|
||||
normalized_date == now.strftime("%Y%m%d")
|
||||
and now.time().replace(tzinfo=None) < datetime.strptime("09:15", "%H:%M").time()
|
||||
@@ -79,6 +107,8 @@ class MarketServiceMixin:
|
||||
if not force:
|
||||
snapshot = self.database.get_snapshot(normalized_date)
|
||||
if snapshot and str((snapshot.get("meta") or {}).get("source") or "") != "demo":
|
||||
if self._should_retry_incomplete_snapshot(snapshot, normalized_date):
|
||||
return self.sync_dashboard(normalized_date)
|
||||
snapshot = copy.deepcopy(snapshot)
|
||||
if normalized_date != now.strftime("%Y%m%d"):
|
||||
snapshot.setdefault("meta", {}).update(
|
||||
@@ -97,6 +127,8 @@ class MarketServiceMixin:
|
||||
"dashboard_request_v1", normalized_date
|
||||
)
|
||||
if resolved and str((resolved.get("meta") or {}).get("source") or "") != "demo":
|
||||
if self._should_retry_incomplete_snapshot(resolved, normalized_date):
|
||||
return self.sync_dashboard(normalized_date)
|
||||
resolved = copy.deepcopy(resolved)
|
||||
resolved.setdefault("meta", {})["requested_date"] = self._display_compact_date(
|
||||
normalized_date
|
||||
@@ -138,6 +170,71 @@ class MarketServiceMixin:
|
||||
def _display_compact_date(compact: str) -> str:
|
||||
return f"{compact[:4]}-{compact[4:6]}-{compact[6:8]}"
|
||||
|
||||
@staticmethod
|
||||
def _chinese_month_day(value: str) -> str:
|
||||
compact = str(value or "").replace("-", "").replace("/", "")
|
||||
if len(compact) < 8 or not compact[:8].isdigit():
|
||||
return "最近可用交易日"
|
||||
return f"{int(compact[4:6])} 月 {int(compact[6:8])} 日"
|
||||
|
||||
@classmethod
|
||||
def _preparing_display_notice(cls, actual_date: str, requested_date: str) -> str:
|
||||
shown = cls._chinese_month_day(actual_date)
|
||||
requested = str(requested_date or "").replace("-", "")
|
||||
if requested == date.today().strftime("%Y%m%d"):
|
||||
return f"今日数据正在准备,当前展示 {shown}"
|
||||
return f"所选日期数据尚未到齐,当前展示 {shown}"
|
||||
|
||||
@staticmethod
|
||||
def _snapshot_age_seconds(meta: dict[str, Any]) -> float:
|
||||
raw = str(meta.get("updated_at") or "")
|
||||
if not raw:
|
||||
return 10**9
|
||||
try:
|
||||
updated_at = datetime.fromisoformat(raw)
|
||||
except ValueError:
|
||||
return 10**9
|
||||
now = datetime.now().astimezone()
|
||||
if updated_at.tzinfo is None:
|
||||
updated_at = updated_at.replace(tzinfo=now.tzinfo)
|
||||
return (now - updated_at.astimezone(now.tzinfo)).total_seconds()
|
||||
|
||||
def _should_retry_incomplete_snapshot(
|
||||
self, snapshot: dict[str, Any], requested_date: str
|
||||
) -> bool:
|
||||
if requested_date != self._now().strftime("%Y%m%d"):
|
||||
return False
|
||||
meta = snapshot.get("meta") or {}
|
||||
actual = str(meta.get("trade_date") or "").replace("-", "")
|
||||
stale_carry = bool(meta.get("carried_forward") or actual != requested_date)
|
||||
if stale_carry and self._is_requested_open_session(requested_date):
|
||||
return True
|
||||
incomplete = meta.get("limit_data_source") == "derived" or stale_carry
|
||||
return incomplete and self._snapshot_age_seconds(meta) >= 60
|
||||
|
||||
def _annotate_data_status(self, dashboard: dict[str, Any]) -> dict[str, Any]:
|
||||
meta = dashboard.setdefault("meta", {})
|
||||
notice = str(meta.get("notice") or "")
|
||||
requested = str(meta.get("requested_date") or "").replace("-", "")
|
||||
actual = str(meta.get("trade_date") or "").replace("-", "")
|
||||
if meta.get("limit_data_source") == "derived" and not meta.get("carried_forward"):
|
||||
meta["data_status"] = "partial"
|
||||
meta["display_notice"] = notice or "部分正式数据尚未到齐,当前展示日线推算结果"
|
||||
elif meta.get("carried_forward"):
|
||||
if "非交易日" in notice or "盘前" in notice:
|
||||
meta["data_status"] = "carried"
|
||||
meta["display_notice"] = notice
|
||||
else:
|
||||
meta["data_status"] = "preparing"
|
||||
meta["display_notice"] = self._preparing_display_notice(actual, requested)
|
||||
elif meta.get("realtime"):
|
||||
meta["data_status"] = "intraday"
|
||||
meta.setdefault("display_notice", "")
|
||||
else:
|
||||
meta["data_status"] = "official"
|
||||
meta.setdefault("display_notice", "")
|
||||
return dashboard
|
||||
|
||||
def _carry_dashboard(
|
||||
self, snapshot: dict[str, Any], requested_date: str, reason: str
|
||||
) -> dict[str, Any]:
|
||||
@@ -152,16 +249,16 @@ class MarketServiceMixin:
|
||||
"notice": reason,
|
||||
}
|
||||
)
|
||||
return carried
|
||||
return self._annotate_data_status(carried)
|
||||
|
||||
def _realtime_snapshot_due(
|
||||
self,
|
||||
normalized_date: str,
|
||||
snapshot: dict[str, Any],
|
||||
) -> bool:
|
||||
if not self.configured or normalized_date != date.today().strftime("%Y%m%d"):
|
||||
if not self.configured or normalized_date != self._now().strftime("%Y%m%d"):
|
||||
return False
|
||||
now = datetime.now().astimezone()
|
||||
now = self._now()
|
||||
local_time = now.time().replace(tzinfo=None)
|
||||
realtime_start = datetime.strptime("09:15", "%H:%M").time()
|
||||
morning_end = datetime.strptime("11:35", "%H:%M").time()
|
||||
@@ -197,19 +294,28 @@ class MarketServiceMixin:
|
||||
if not self.configured:
|
||||
raise TushareError("公共行情尚未配置")
|
||||
dashboard = self._tushare_client().dashboard(normalized_date)
|
||||
|
||||
if (dashboard.get("meta") or {}).get("limit_data_source") == "derived":
|
||||
raise TushareError(
|
||||
str((dashboard.get("meta") or {}).get("notice") or "官方涨跌停数据尚未返回")
|
||||
meta = dashboard.setdefault("meta", {})
|
||||
quote_source = str(meta.get("quote_source") or "")
|
||||
meta["source"] = source
|
||||
if quote_source:
|
||||
meta["quote_source"] = quote_source
|
||||
meta["requested_date"] = self._display_compact_date(normalized_date)
|
||||
if meta.get("limit_data_source") == "derived":
|
||||
meta.setdefault(
|
||||
"notice",
|
||||
"涨跌停高级接口当日数据尚未更新,已使用日线数据推算。",
|
||||
)
|
||||
|
||||
dashboard["meta"]["source"] = source
|
||||
dashboard["meta"]["requested_date"] = self._display_compact_date(normalized_date)
|
||||
dashboard = self._enrich_dashboard_sentiment(dashboard, normalized_date)
|
||||
record_count = self._record_count(dashboard)
|
||||
actual_date = normalize_date(
|
||||
str(dashboard.get("meta", {}).get("trade_date") or normalized_date)
|
||||
)
|
||||
if actual_date != normalized_date and self._is_requested_open_session(
|
||||
normalized_date
|
||||
):
|
||||
raise TushareError(
|
||||
f"Intraday dashboard resolved {actual_date} instead of {normalized_date}"
|
||||
)
|
||||
self.database.save_snapshot(actual_date, source, dashboard)
|
||||
if actual_date != normalized_date:
|
||||
dashboard.setdefault("meta", {}).update(
|
||||
@@ -231,10 +337,37 @@ class MarketServiceMixin:
|
||||
)
|
||||
return self._apply_reason_overrides(self._with_storage(dashboard, cached=False))
|
||||
except TushareError as exc:
|
||||
if self._is_requested_open_session(normalized_date):
|
||||
existing = self.database.get_snapshot(normalized_date)
|
||||
existing_date = str(
|
||||
((existing or {}).get("meta") or {}).get("trade_date") or ""
|
||||
).replace("-", "")
|
||||
if existing and existing_date == normalized_date:
|
||||
kept = copy.deepcopy(existing)
|
||||
kept.setdefault("meta", {}).update(
|
||||
{
|
||||
"requested_date": self._display_compact_date(normalized_date),
|
||||
}
|
||||
)
|
||||
self.database.finish_sync(
|
||||
sync_id,
|
||||
"fallback",
|
||||
self._record_count(kept),
|
||||
str(exc),
|
||||
"tushare",
|
||||
)
|
||||
return self._apply_reason_overrides(
|
||||
self._with_storage(kept, cached=True)
|
||||
)
|
||||
self.database.finish_sync(sync_id, "failed", message=str(exc))
|
||||
raise ValueError("当天盘中行情暂时不可用,请稍后重试。") from exc
|
||||
fallback = self.database.get_latest_real_snapshot(normalized_date)
|
||||
if fallback:
|
||||
actual = str((fallback.get("meta") or {}).get("trade_date") or "")
|
||||
carried = self._carry_dashboard(
|
||||
fallback, normalized_date, f"最新行情暂不可用,沿用最近收盘快照:{exc}"
|
||||
fallback,
|
||||
normalized_date,
|
||||
self._preparing_display_notice(actual, normalized_date),
|
||||
)
|
||||
self.database.finish_sync(
|
||||
sync_id, "fallback", self._record_count(carried), str(exc), "tushare"
|
||||
@@ -683,26 +816,27 @@ class MarketServiceMixin:
|
||||
"trade_date": f"{actual_date[:4]}-{actual_date[4:6]}-{actual_date[6:]}",
|
||||
}
|
||||
today = now.strftime("%Y%m%d")
|
||||
latest_bar = (result.get("prices") or [{}])[-1] if result.get("prices") else {}
|
||||
official_today = (
|
||||
actual_date == today and not bool(latest_bar.get("realtime"))
|
||||
)
|
||||
after_close = now.time().replace(tzinfo=None) >= dt_time(15, 0)
|
||||
should_merge = (
|
||||
requested_date == today
|
||||
and actual_date <= today
|
||||
and now.weekday() < 5
|
||||
and now.time().replace(tzinfo=None) >= dt_time(9, 30)
|
||||
and not (official_today and after_close)
|
||||
)
|
||||
if should_merge:
|
||||
quote = self._ifind_realtime_stock_quote(code)
|
||||
quote = self._resolve_today_daily_quote(code, today, result)
|
||||
if quote and self._valid_realtime_stock_quote(quote, today):
|
||||
self._merge_realtime_stock_detail(result, quote, requested_date)
|
||||
elif self.configured and actual_date < today:
|
||||
client = self._tushare_client()
|
||||
try:
|
||||
resolved_date, _ = client.resolve_trade_context(requested_date)
|
||||
if resolved_date == today:
|
||||
quote = client.realtime_stock_quote(tushare_code(code), requested_date)
|
||||
if self._valid_realtime_stock_quote(quote, today):
|
||||
self._merge_realtime_stock_detail(result, quote, requested_date)
|
||||
except TushareError:
|
||||
pass
|
||||
elif actual_date < today:
|
||||
result["meta"] = {
|
||||
**(result.get("meta") or {}),
|
||||
"notice": TODAY_DAILY_UNAVAILABLE_NOTICE,
|
||||
}
|
||||
return self._enrich_stock_detail(result)
|
||||
|
||||
@staticmethod
|
||||
@@ -817,6 +951,134 @@ class MarketServiceMixin:
|
||||
"quote_time": str(row.get("time") or ""),
|
||||
}
|
||||
|
||||
def _resolve_today_daily_quote(
|
||||
self, code: str, today: str, payload: dict[str, Any]
|
||||
) -> dict[str, Any] | None:
|
||||
quote = self._ifind_realtime_stock_quote(code)
|
||||
if quote and self._valid_realtime_stock_quote(quote, today):
|
||||
return quote
|
||||
if self.configured:
|
||||
try:
|
||||
client = self._tushare_client()
|
||||
resolve = getattr(client, "resolve_trade_context", None)
|
||||
resolved = today
|
||||
if callable(resolve):
|
||||
resolved, _ = resolve(today)
|
||||
if str(resolved or "") == today:
|
||||
quote = client.realtime_stock_quote(tushare_code(code), today)
|
||||
if self._valid_realtime_stock_quote(quote, today):
|
||||
return quote
|
||||
except TushareError:
|
||||
pass
|
||||
quote = self._free_realtime_stock_quote(code, today)
|
||||
if quote and self._valid_realtime_stock_quote(quote, today):
|
||||
return quote
|
||||
return self._intraday_realtime_stock_quote(code, today, payload)
|
||||
|
||||
def _free_realtime_stock_quote(self, code: str, today: str) -> dict[str, Any] | None:
|
||||
aggregator = getattr(self, "realtime_aggregator", None)
|
||||
if aggregator is None:
|
||||
return None
|
||||
ts_code = tushare_code(code)
|
||||
for loader in (
|
||||
getattr(aggregator, "tencent_stock_quote", None),
|
||||
getattr(aggregator, "eastmoney_stock_quote", None),
|
||||
):
|
||||
if not callable(loader):
|
||||
continue
|
||||
try:
|
||||
row = loader(ts_code, expected_date=today)
|
||||
except (RealtimeAggregateError, Exception):
|
||||
continue
|
||||
quote = self._quote_from_free_row(code, today, row)
|
||||
if quote:
|
||||
return quote
|
||||
return None
|
||||
|
||||
def _quote_from_free_row(
|
||||
self, code: str, today: str, row: dict[str, Any]
|
||||
) -> dict[str, Any] | None:
|
||||
price = float(row.get("close") or 0)
|
||||
previous_close = float(row.get("pre_close") or 0)
|
||||
if price <= 0 or previous_close <= 0:
|
||||
return None
|
||||
try:
|
||||
name, sector = self._stock_identity(code, today)
|
||||
except Exception:
|
||||
name, sector = "--", "其他"
|
||||
epoch = int(row.get("quote_time_epoch") or 0)
|
||||
if epoch > 0:
|
||||
quote_time = datetime.fromtimestamp(epoch).astimezone().isoformat(timespec="seconds")
|
||||
else:
|
||||
quote_date = str(row.get("quote_date") or today)
|
||||
quote_time = f"{quote_date[:4]}-{quote_date[4:6]}-{quote_date[6:]}"
|
||||
return {
|
||||
"name": str(row.get("name") or name or "--"),
|
||||
"sector": sector,
|
||||
"price": price,
|
||||
"open": float(row.get("open") or 0),
|
||||
"high": float(row.get("high") or 0),
|
||||
"low": float(row.get("low") or 0),
|
||||
"change": round((price / previous_close - 1) * 100, 4),
|
||||
"volume": float(row.get("vol") or 0),
|
||||
"amount_billion": float(row.get("amount") or 0) / 100_000_000,
|
||||
"turnover_rate": float(row.get("turnover_rate") or 0),
|
||||
"quote_time": quote_time,
|
||||
}
|
||||
|
||||
def _intraday_realtime_stock_quote(
|
||||
self, code: str, today: str, payload: dict[str, Any]
|
||||
) -> dict[str, Any] | None:
|
||||
chart_data = getattr(self, "chart_data", None)
|
||||
if chart_data is None:
|
||||
return None
|
||||
try:
|
||||
chart = chart_data.stock_intraday(code)
|
||||
except (AttributeError, ChartDataError, Exception):
|
||||
return None
|
||||
points = [
|
||||
point
|
||||
for point in list(chart.get("points") or [])
|
||||
if str(point.get("date") or "").replace("-", "") == today
|
||||
]
|
||||
if not points:
|
||||
return None
|
||||
opens = [float(point.get("open") or 0) for point in points if float(point.get("open") or 0) > 0]
|
||||
highs = [float(point.get("high") or 0) for point in points if float(point.get("high") or 0) > 0]
|
||||
lows = [float(point.get("low") or 0) for point in points if float(point.get("low") or 0) > 0]
|
||||
closes = [float(point.get("close") or 0) for point in points if float(point.get("close") or 0) > 0]
|
||||
if not opens or not highs or not lows or not closes:
|
||||
return None
|
||||
price = closes[-1]
|
||||
previous_close = float(chart.get("previous_close") or 0)
|
||||
if previous_close <= 0:
|
||||
history = list(payload.get("prices") or [])
|
||||
previous_close = float((history[-1] if history else {}).get("close") or 0)
|
||||
if previous_close <= 0:
|
||||
return None
|
||||
volume = sum(float(point.get("volume") or 0) for point in points)
|
||||
amount = sum(float(point.get("amount") or 0) for point in points)
|
||||
if volume <= 0 and amount <= 0:
|
||||
return None
|
||||
try:
|
||||
name, sector = self._stock_identity(code, today)
|
||||
except Exception:
|
||||
name, sector = "--", "其他"
|
||||
return {
|
||||
"name": name,
|
||||
"sector": sector,
|
||||
"price": price,
|
||||
"open": opens[0],
|
||||
"high": max(highs),
|
||||
"low": min(lows),
|
||||
"change": round((price / previous_close - 1) * 100, 4),
|
||||
"volume": volume,
|
||||
"volume_unit": "lots",
|
||||
"amount_billion": amount / 100_000_000,
|
||||
"turnover_rate": 0.0,
|
||||
"quote_time": str(points[-1].get("date") or today),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _merge_realtime_stock_detail(
|
||||
payload: dict[str, Any], quote: dict[str, Any], trade_date: str
|
||||
@@ -855,6 +1117,7 @@ class MarketServiceMixin:
|
||||
**(payload.get("meta") or {}),
|
||||
"trade_date": display_date,
|
||||
"realtime": True,
|
||||
"notice": "",
|
||||
"updated_at": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||
}
|
||||
|
||||
@@ -1160,7 +1423,7 @@ class MarketServiceMixin:
|
||||
"storage": "sqlite",
|
||||
"cached": cached,
|
||||
}
|
||||
return result
|
||||
return self._annotate_data_status(result)
|
||||
|
||||
@staticmethod
|
||||
def _record_count(dashboard: dict[str, Any]) -> int:
|
||||
|
||||
@@ -130,6 +130,7 @@ class SystemServiceMixin:
|
||||
),
|
||||
**self.database.status(),
|
||||
"jobs": self.jobs.repository.recent(12),
|
||||
"datahub": self._datahub_status(),
|
||||
},
|
||||
"llm": {
|
||||
"primary_configured": self._profile_configured(platform["primary"]),
|
||||
@@ -145,6 +146,22 @@ class SystemServiceMixin:
|
||||
},
|
||||
}
|
||||
|
||||
def _datahub_status(self) -> dict[str, Any]:
|
||||
gateway = getattr(self, "data_gateway", None)
|
||||
reporter = getattr(gateway, "datahub_status", None)
|
||||
if callable(reporter):
|
||||
return reporter()
|
||||
return {
|
||||
"configured": False,
|
||||
"base_url": "",
|
||||
"enabled_reads": 0,
|
||||
"total_reads": 0,
|
||||
"flags": [],
|
||||
"routes": [],
|
||||
"fallback_count": 0,
|
||||
"fallback_labels": [],
|
||||
}
|
||||
|
||||
def save_system_settings(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
current = dict(self._system_credentials)
|
||||
token = str(payload.get("tushare_token") or current.get("tushare_token") or "").strip()
|
||||
|
||||
@@ -109,7 +109,14 @@ class HttpTransportMixin:
|
||||
return {}
|
||||
if length <= 0 or length > 65536:
|
||||
raise ValueError("请求内容为空或过大。")
|
||||
return json.loads(self.rfile.read(length).decode("utf-8"))
|
||||
raw = self.rfile.read(length)
|
||||
try:
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
raise ValueError("请求不是合法 JSON。") from None
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("请求不是合法 JSON。")
|
||||
return payload
|
||||
|
||||
def serve_static(self, request_path: str) -> None:
|
||||
relative = unquote(request_path).lstrip("/") or "index.html"
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, time as dt_time
|
||||
|
||||
|
||||
def dashboard_has_usable_data(dashboard: dict[str, object]) -> bool:
|
||||
if not isinstance(dashboard, dict) or dashboard.get("status") == "failed":
|
||||
return False
|
||||
meta = dashboard.get("meta") or {}
|
||||
overview = dashboard.get("overview") or {}
|
||||
if isinstance(meta, dict) and (meta.get("trade_date") or meta.get("carried_forward")):
|
||||
return True
|
||||
return bool(isinstance(overview, dict) and overview)
|
||||
|
||||
|
||||
def verified_dashboard_result(dashboard: dict[str, object]) -> dict[str, object]:
|
||||
"""Manual refresh and automatic catch-up share this rule.
|
||||
|
||||
Derived limit lists or a previous usable snapshot are not whole-job failures.
|
||||
Only a payload with no displayable market data is recorded as failed.
|
||||
"""
|
||||
if dashboard_has_usable_data(dashboard):
|
||||
return dashboard
|
||||
meta = dashboard.get("meta") if isinstance(dashboard, dict) else None
|
||||
notice = ""
|
||||
if isinstance(meta, dict):
|
||||
notice = str(meta.get("notice") or meta.get("display_notice") or "")
|
||||
return {
|
||||
"status": "failed",
|
||||
"error": notice or "未获取到可用行情",
|
||||
}
|
||||
|
||||
|
||||
def official_catchup_due(today: str, snapshot: dict[str, object]) -> bool:
|
||||
now = datetime.now().astimezone().time().replace(tzinfo=None)
|
||||
if not (dt_time(15, 5) <= now < dt_time(22, 0)):
|
||||
return False
|
||||
meta = snapshot.get("meta") if isinstance(snapshot.get("meta"), dict) else {}
|
||||
actual = str(meta.get("trade_date") or "").replace("-", "")
|
||||
if (
|
||||
actual == today
|
||||
and meta.get("limit_data_source") != "derived"
|
||||
and not meta.get("carried_forward")
|
||||
and not meta.get("realtime")
|
||||
and meta.get("mode") != "realtime"
|
||||
):
|
||||
return False
|
||||
return True
|
||||
+11
-12
@@ -5,16 +5,7 @@ import time
|
||||
from datetime import date
|
||||
|
||||
from backend.bootstrap.config import normalize_date
|
||||
|
||||
|
||||
def _verified_dashboard_result(dashboard: dict[str, object]) -> dict[str, object]:
|
||||
meta = dashboard.get("meta") or {}
|
||||
if isinstance(meta, dict) and meta.get("carried_forward"):
|
||||
return {
|
||||
"status": "failed",
|
||||
"error": str(meta.get("notice") or "未获取到所选日期的最新行情"),
|
||||
}
|
||||
return dashboard
|
||||
from backend.jobs.refresh import official_catchup_due, verified_dashboard_result
|
||||
|
||||
|
||||
class JobServiceMixin:
|
||||
@@ -36,7 +27,7 @@ class JobServiceMixin:
|
||||
started = self.jobs.submit(
|
||||
"market.refresh",
|
||||
key,
|
||||
lambda: _verified_dashboard_result(self.sync_dashboard(normalized)),
|
||||
lambda: verified_dashboard_result(self.sync_dashboard(normalized)),
|
||||
{"trade_date": normalized, "trigger": "administrator"},
|
||||
)
|
||||
return {"started": started, "job_key": key if started else ""}
|
||||
@@ -54,7 +45,15 @@ class JobServiceMixin:
|
||||
self.jobs.submit(
|
||||
"market.refresh",
|
||||
f"realtime:{today}:{bucket}",
|
||||
lambda: self.sync_dashboard(today),
|
||||
lambda: verified_dashboard_result(self.sync_dashboard(today)),
|
||||
{"trade_date": today, "trigger": "realtime-poll"},
|
||||
)
|
||||
elif official_catchup_due(today, snapshot):
|
||||
bucket = int(time.time() // 300)
|
||||
self.jobs.submit(
|
||||
"market.refresh",
|
||||
f"catchup:{today}:{bucket}",
|
||||
lambda: verified_dashboard_result(self.sync_dashboard(today)),
|
||||
{"trade_date": today, "trigger": "official-catchup"},
|
||||
)
|
||||
self._schedule_automatic_screeners(today, snapshot)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# Optional overlay. Does not replace the existing xiaobai-review service.
|
||||
# Start later (总工部署时) with:
|
||||
# docker compose -f compose.yaml -f compose.datahub.yaml up -d
|
||||
#
|
||||
# Required .env keys: DATAHUB_ENCRYPTION_KEY, DATAHUB_TOKEN, DATAHUB_ADMIN_PASSWORD, TUSHARE_TOKEN
|
||||
|
||||
services:
|
||||
xiaobai-datahub:
|
||||
build:
|
||||
context: ./xiaobai-datahub
|
||||
dockerfile: Dockerfile
|
||||
image: xiaobai-datahub:local
|
||||
container_name: xiaobai-datahub
|
||||
ports:
|
||||
- "0.0.0.0:8766:8766/tcp"
|
||||
env_file:
|
||||
- ./xiaobai-datahub/.env
|
||||
environment:
|
||||
DATAHUB_ENCRYPTION_KEY: "${DATAHUB_ENCRYPTION_KEY:?DATAHUB_ENCRYPTION_KEY must be set}"
|
||||
DATAHUB_TOKEN: "${DATAHUB_TOKEN:?DATAHUB_TOKEN must be set}"
|
||||
DATAHUB_ADMIN_PASSWORD: "${DATAHUB_ADMIN_PASSWORD:?DATAHUB_ADMIN_PASSWORD must be set}"
|
||||
TUSHARE_TOKEN: "${TUSHARE_TOKEN:-}"
|
||||
DATAHUB_DB_PATH: /app/data/datahub.db
|
||||
DATAHUB_BACKUP_DIR: /app/data/backups
|
||||
TZ: Asia/Shanghai
|
||||
PYTHONUTF8: "1"
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ./datahub-data
|
||||
target: /app/data
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=64m,mode=1777
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
stop_grace_period: 30s
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
@@ -13,6 +13,22 @@ services:
|
||||
- ./.env
|
||||
environment:
|
||||
APP_ENCRYPTION_KEY: "${APP_ENCRYPTION_KEY:?APP_ENCRYPTION_KEY must be set in .env}"
|
||||
DATAHUB_BASE_URL: "${DATAHUB_BASE_URL:-http://192.168.200.11:8766}"
|
||||
DATAHUB_READ_CALENDAR: "1"
|
||||
DATAHUB_READ_STOCKS: "1"
|
||||
DATAHUB_READ_DAILY: "1"
|
||||
DATAHUB_READ_INDEX_DAILY: "1"
|
||||
DATAHUB_READ_VALUATION: "1"
|
||||
DATAHUB_READ_MONEYFLOW: "1"
|
||||
DATAHUB_READ_AUCTION: "1"
|
||||
DATAHUB_READ_LIMIT_EVENTS: "1"
|
||||
DATAHUB_READ_POPULARITY: "1"
|
||||
DATAHUB_READ_DRAGON_TIGER: "1"
|
||||
DATAHUB_READ_SECTOR_DAILY: "1"
|
||||
DATAHUB_READ_QUOTES: "1"
|
||||
DATAHUB_READ_INDEX_QUOTES: "1"
|
||||
DATAHUB_READ_INTRADAY: "1"
|
||||
DATAHUB_READ_STATUS: "1"
|
||||
TZ: Asia/Shanghai
|
||||
PYTHONUTF8: "1"
|
||||
volumes:
|
||||
|
||||
@@ -12,6 +12,12 @@ These registries describe the approved product surface of the standalone applica
|
||||
providers, model entry points, CSS layers, and remaining code hotspots.
|
||||
- `data-fields.config.json`: canonical data products, provider eligibility, intended use, and
|
||||
known blocked datasets.
|
||||
- `datahub.config.json`: official read-only client for `xiaobai-datahub`. Each dataset has its
|
||||
own `read` / `shadow` flag; official reads default on. `compose.yaml` pins every
|
||||
`DATAHUB_READ_*` to `"1"` so a leftover `.env` `=0` cannot silently keep official
|
||||
pages on the old APIs. Environment variables can still override a single
|
||||
`DATAHUB_SHADOW_*` without a master switch. The old website APIs stay as
|
||||
emergency fallback only.
|
||||
- `data-quality.config.json`: freshness, coverage, units, adjustment, point-in-time, and
|
||||
fail-closed rules for every canonical data product.
|
||||
- `jobs.config.json`: background schedules, dependencies, lock keys, retry policy, timeouts,
|
||||
|
||||
@@ -204,6 +204,11 @@
|
||||
"path": "backend/data/providers/tushare_client.py",
|
||||
"runtime_role": "stable client facade for primary deterministic market data"
|
||||
},
|
||||
{
|
||||
"provider": "datahub",
|
||||
"path": "backend/data/datahub/client.py",
|
||||
"runtime_role": "optional official EOD read path behind per-dataset flags"
|
||||
},
|
||||
{
|
||||
"provider": "ifind",
|
||||
"path": "backend/data/providers/ifind_client.py",
|
||||
@@ -217,12 +222,12 @@
|
||||
{
|
||||
"provider": "eastmoney",
|
||||
"path": "backend/data/realtime.py",
|
||||
"runtime_role": "isolated realtime observation"
|
||||
"runtime_role": "isolated realtime observation and intraday dashboard fallback"
|
||||
},
|
||||
{
|
||||
"provider": "tencent",
|
||||
"path": "backend/data/realtime.py",
|
||||
"runtime_role": "index observation fallback"
|
||||
"runtime_role": "index observation and intraday quote fallback"
|
||||
}
|
||||
],
|
||||
"provider_domains": [
|
||||
@@ -278,6 +283,18 @@
|
||||
"owner": "backend/data/providers/tushare.py",
|
||||
"compatibility_fallback": "backend/features/market/service.py"
|
||||
},
|
||||
{
|
||||
"client": "DatahubClient",
|
||||
"owner": "backend/data/gateway.py"
|
||||
},
|
||||
{
|
||||
"client": "DatahubBridge",
|
||||
"owner": "backend/data/gateway.py"
|
||||
},
|
||||
{
|
||||
"client": "DatahubAwareTushareClient",
|
||||
"owner": "backend/data/gateway.py"
|
||||
},
|
||||
{
|
||||
"client": "IfindHttpClient",
|
||||
"owner": "backend/data/gateway.py"
|
||||
@@ -313,6 +330,7 @@
|
||||
"system_service": "backend/features/system/service.py",
|
||||
"account_bridge": "backend/features/accounts/application.py",
|
||||
"job_lifecycle": "backend/jobs/service.py",
|
||||
"job_refresh_status": "backend/jobs/refresh.py",
|
||||
"feature_routes": "backend/features/*/routes.py"
|
||||
},
|
||||
"numeric_normalization": [
|
||||
@@ -455,8 +473,8 @@
|
||||
},
|
||||
{
|
||||
"path": "frontend/shared/shell.css",
|
||||
"bytes": 63659,
|
||||
"lines": 3763
|
||||
"bytes": 63733,
|
||||
"lines": 3767
|
||||
},
|
||||
{
|
||||
"path": "backend/features/heaven/engine.py",
|
||||
@@ -465,8 +483,8 @@
|
||||
},
|
||||
{
|
||||
"path": "frontend/index.html",
|
||||
"bytes": 48254,
|
||||
"lines": 664
|
||||
"bytes": 48447,
|
||||
"lines": 665
|
||||
},
|
||||
{
|
||||
"path": "backend/features/screener/catalog.py",
|
||||
@@ -478,6 +496,11 @@
|
||||
"bytes": 35247,
|
||||
"lines": 2416
|
||||
},
|
||||
{
|
||||
"path": "backend/data/providers/tushare_dashboard.py",
|
||||
"bytes": 33603,
|
||||
"lines": 784
|
||||
},
|
||||
{
|
||||
"path": "database.py",
|
||||
"bytes": 32073,
|
||||
@@ -488,11 +511,6 @@
|
||||
"bytes": 31756,
|
||||
"lines": 562
|
||||
},
|
||||
{
|
||||
"path": "backend/data/providers/tushare_dashboard.py",
|
||||
"bytes": 28234,
|
||||
"lines": 648
|
||||
},
|
||||
{
|
||||
"path": "backend/data/providers/tushare_industries.py",
|
||||
"bytes": 26540,
|
||||
@@ -515,8 +533,8 @@
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages/market/preview.js",
|
||||
"bytes": 18178,
|
||||
"lines": 446
|
||||
"bytes": 18339,
|
||||
"lines": 450
|
||||
},
|
||||
{
|
||||
"path": "backend/features/heaven/trend.py",
|
||||
@@ -533,6 +551,16 @@
|
||||
"bytes": 15311,
|
||||
"lines": 387
|
||||
},
|
||||
{
|
||||
"path": "frontend/shared/admin.js",
|
||||
"bytes": 15235,
|
||||
"lines": 289
|
||||
},
|
||||
{
|
||||
"path": "frontend/shared/dashboard.js",
|
||||
"bytes": 15063,
|
||||
"lines": 321
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages/pools/page.html",
|
||||
"bytes": 14942,
|
||||
@@ -543,11 +571,6 @@
|
||||
"bytes": 14743,
|
||||
"lines": 342
|
||||
},
|
||||
{
|
||||
"path": "frontend/shared/admin.js",
|
||||
"bytes": 14410,
|
||||
"lines": 268
|
||||
},
|
||||
{
|
||||
"path": "backend/features/heaven/market_context.py",
|
||||
"bytes": 13681,
|
||||
@@ -559,9 +582,9 @@
|
||||
"lines": 289
|
||||
},
|
||||
{
|
||||
"path": "frontend/shared/dashboard.js",
|
||||
"bytes": 12894,
|
||||
"lines": 274
|
||||
"path": "backend/features/system/service.py",
|
||||
"bytes": 12937,
|
||||
"lines": 271
|
||||
},
|
||||
{
|
||||
"path": "backend/features/market/insights_auction_data.py",
|
||||
@@ -569,9 +592,9 @@
|
||||
"lines": 318
|
||||
},
|
||||
{
|
||||
"path": "backend/features/system/service.py",
|
||||
"bytes": 12392,
|
||||
"lines": 254
|
||||
"path": "backend/data/providers/tushare_indices.py",
|
||||
"bytes": 10956,
|
||||
"lines": 248
|
||||
},
|
||||
{
|
||||
"path": "backend/features/market/insights_auction.py",
|
||||
@@ -620,8 +643,8 @@
|
||||
},
|
||||
{
|
||||
"path": "backend/data/providers/tushare_daily.py",
|
||||
"bytes": 6837,
|
||||
"lines": 160
|
||||
"bytes": 6949,
|
||||
"lines": 168
|
||||
},
|
||||
{
|
||||
"path": "backend/application.py",
|
||||
@@ -658,21 +681,16 @@
|
||||
"bytes": 6092,
|
||||
"lines": 138
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages/market/stock-detail.js",
|
||||
"bytes": 6041,
|
||||
"lines": 134
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages/dragon-tiger/page.html",
|
||||
"bytes": 5754,
|
||||
"lines": 85
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages/market/stock-detail.js",
|
||||
"bytes": 5690,
|
||||
"lines": 124
|
||||
},
|
||||
{
|
||||
"path": "backend/data/providers/tushare_indices.py",
|
||||
"bytes": 5451,
|
||||
"lines": 118
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages.config.js",
|
||||
"bytes": 5385,
|
||||
@@ -769,14 +787,19 @@
|
||||
"lines": 63
|
||||
},
|
||||
{
|
||||
"path": "backend/features/mentor/routes.py",
|
||||
"bytes": 2299,
|
||||
"lines": 57
|
||||
"path": "backend/data/providers/tushare_helpers.py",
|
||||
"bytes": 2360,
|
||||
"lines": 75
|
||||
},
|
||||
{
|
||||
"path": "backend/jobs/service.py",
|
||||
"bytes": 2219,
|
||||
"lines": 60
|
||||
"bytes": 2337,
|
||||
"lines": 59
|
||||
},
|
||||
{
|
||||
"path": "backend/features/mentor/routes.py",
|
||||
"bytes": 2299,
|
||||
"lines": 57
|
||||
},
|
||||
{
|
||||
"path": "backend/features/screener/regime.py",
|
||||
@@ -793,11 +816,6 @@
|
||||
"bytes": 2165,
|
||||
"lines": 35
|
||||
},
|
||||
{
|
||||
"path": "backend/data/providers/tushare_helpers.py",
|
||||
"bytes": 2083,
|
||||
"lines": 64
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages/market/breadth.js",
|
||||
"bytes": 2071,
|
||||
@@ -808,6 +826,11 @@
|
||||
"bytes": 1919,
|
||||
"lines": 45
|
||||
},
|
||||
{
|
||||
"path": "backend/jobs/refresh.py",
|
||||
"bytes": 1808,
|
||||
"lines": 48
|
||||
},
|
||||
{
|
||||
"path": "backend/features/system/routes.py",
|
||||
"bytes": 1791,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"providers": {
|
||||
"tushare": {"class": "licensed", "calculation_allowed": true},
|
||||
"datahub": {"class": "licensed", "calculation_allowed": true},
|
||||
"ifind": {"class": "licensed", "calculation_allowed": true},
|
||||
"eastmoney": {"class": "public_web", "calculation_allowed": false},
|
||||
"tencent": {"class": "public_web", "calculation_allowed": false},
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"base_url": "http://127.0.0.1:8766",
|
||||
"timeout_seconds": 8,
|
||||
"retries": 1,
|
||||
"page_limit": 5000,
|
||||
"stale_seconds_max": 86400,
|
||||
"datasets": {
|
||||
"calendar": { "read": true, "shadow": false },
|
||||
"stocks": { "read": true, "shadow": false },
|
||||
"daily": { "read": true, "shadow": false },
|
||||
"index_daily": { "read": true, "shadow": false },
|
||||
"valuation": { "read": true, "shadow": false },
|
||||
"moneyflow": { "read": true, "shadow": false },
|
||||
"auction": { "read": true, "shadow": false },
|
||||
"limit_events": { "read": true, "shadow": false },
|
||||
"popularity": { "read": true, "shadow": false },
|
||||
"dragon_tiger": { "read": true, "shadow": false },
|
||||
"sector_daily": { "read": true, "shadow": false },
|
||||
"quotes": { "read": true, "shadow": false },
|
||||
"index_quotes": { "read": true, "shadow": false },
|
||||
"intraday": { "read": true, "shadow": false },
|
||||
"status": { "read": true, "shadow": false }
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -32,4 +32,4 @@
|
||||
|
||||
- 旧文档不能删:被替代的旧文档开头要加一行「⚠️ 本文档已过时,仅留档备查,请勿删除」,再写新版。
|
||||
- 用中文大白话写,专业词要带通俗解释,让不懂代码的人也能看懂。
|
||||
- 「问天」板块是冻结区,任何改动都不许碰;写文档时别误导后来人去改它。
|
||||
- 「问天」不是永久冻结区:此前只冻结过界面视觉方案,现已解冻。问天可纳入后续数据与功能迁移,不要再写成“永远不碰”。
|
||||
|
||||
@@ -213,12 +213,12 @@
|
||||
{
|
||||
"provider": "eastmoney",
|
||||
"path": "realtime_aggregator.py",
|
||||
"runtime_role": "isolated realtime observation"
|
||||
"runtime_role": "isolated realtime observation and intraday dashboard fallback"
|
||||
},
|
||||
{
|
||||
"provider": "tencent",
|
||||
"path": "realtime_aggregator.py",
|
||||
"runtime_role": "index observation fallback"
|
||||
"runtime_role": "index observation and intraday quote fallback"
|
||||
}
|
||||
],
|
||||
"llm_entrypoints": [
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
| 任务 | 说明 | 状态 |
|
||||
|---|---|---|
|
||||
| 全站视觉统一改造收尾 | 主线。17 个阶段已完成,正在最终验收、代码合并 | 收尾中 |
|
||||
| 行情刷新误报与旧数据提示 | HEL-412:高级接口未到齐不再记整次失败;今日正式数据晚到时提示当前展示日期 | 施工中 |
|
||||
| 手机端独立重新设计 | 先出视觉/交互规范和技术架构方案,等老板确认后再施工 | 方案送审中 |
|
||||
|
||||
## 已做完
|
||||
|
||||
+2
-2
@@ -29,11 +29,11 @@
|
||||
- **智能工具类(3 个)**:智能选股、问师、问天。
|
||||
- **个人类(1 个)**:我的复盘。
|
||||
|
||||
其中「问天」是冻结区(见下面的硬规矩)。
|
||||
其中「问天」此前只在全站视觉改造阶段冻结过界面方案,现已解冻;问天可以纳入后续数据与功能迁移,但不等于本阶段要重做视觉。
|
||||
|
||||
## 几条硬规矩(不能破坏的边界)
|
||||
|
||||
- 「问天」板块是**冻结区**,任何改动都不许碰它。
|
||||
- 「问天」板块**不是永久冻结区**:此前冻结的是界面视觉方案,现已解冻。问天现有功能与界面不要破坏;后续数据与功能迁移可以纳入,不主动重做视觉。
|
||||
- **不用假数据冒充真行情**;数据缺失就明说“没有/不可用”,不能编。
|
||||
- **每个用户自己的数据互相隔离**(自选、复盘、对话、问天历史等),看不到别人的。
|
||||
- **计算由程序确定性完成**(情绪周期、智能选股、问天排盘等),AI 大模型(LLM,就是会聊天的那个 AI)只负责解释或编译自然语言条件,不能改计算结果。
|
||||
|
||||
@@ -611,6 +611,7 @@
|
||||
<label class="form-field"><span>iFinD Refresh Token</span><input id="systemIfindTokenInput" type="password" autocomplete="off" maxlength="2048" placeholder="留空保留现有 Token"></label>
|
||||
<label class="switch-control"><input id="systemBackgroundRefresh" type="checkbox"><span>启用交易时段后台刷新</span></label>
|
||||
<p class="form-hint">所有用户读取同一份后台快照,页面不会随后台任务自动重绘。</p>
|
||||
<div id="datahubRouteStatus" class="admin-refresh-status" data-tone="idle" role="status" aria-live="polite"><i data-lucide="database"></i><span>数据中枢线路待检查</span></div>
|
||||
<div id="adminRefreshStatus" class="admin-refresh-status" data-tone="idle" role="status" aria-live="polite"><i data-lucide="circle-dot"></i><span>尚未手动刷新</span></div>
|
||||
<div class="dialog-actions admin-inline-actions"><button id="adminRefreshButton" class="button" type="button"><i data-lucide="refresh-cw"></i>立即后台刷新</button><button class="button primary" type="submit">保存行情配置</button></div>
|
||||
</form>
|
||||
|
||||
@@ -770,11 +770,33 @@
|
||||
scroll.classList.add("m-motion-fade-in");
|
||||
}
|
||||
|
||||
function dashboardFreshnessNotice() {
|
||||
const meta = (state.dashboard && state.dashboard.meta) || {};
|
||||
if (meta.display_notice) return String(meta.display_notice);
|
||||
const requested = String(meta.requested_date || "").replace(/-/g, "");
|
||||
const actual = String(meta.trade_date || "").replace(/-/g, "");
|
||||
const compact = actual;
|
||||
const shown = /^\d{8}$/.test(compact)
|
||||
? (Number(compact.slice(4, 6)) + " 月 " + Number(compact.slice(6, 8)) + " 日")
|
||||
: "";
|
||||
if (meta.data_status === "preparing" || (meta.carried_forward && actual && requested && actual !== requested)) {
|
||||
return shown ? ("今日数据正在准备,当前展示 " + shown) : "今日数据正在准备,当前展示最近可用数据";
|
||||
}
|
||||
if (meta.data_status === "partial" || meta.limit_data_source === "derived") {
|
||||
return meta.notice || "部分正式数据尚未到齐,当前展示日线推算结果";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function renderTopArea(key) {
|
||||
const page = document.querySelector(".m-page");
|
||||
if (!page) return;
|
||||
let top = page.querySelector(".m-top");
|
||||
let html = buildStrip();
|
||||
const freshness = dashboardFreshnessNotice();
|
||||
if (freshness) {
|
||||
html = '<div class="m-phase-notice"><strong>' + escapeHtml(freshness) + "</strong></div>" + html;
|
||||
}
|
||||
if (key === "market/performance") html += performanceConclusion();
|
||||
if (!top) {
|
||||
top = document.createElement("div");
|
||||
@@ -5197,6 +5219,15 @@
|
||||
return '<span class="m-sys-dot' + (ok ? " m-sys-dot--ok" : "") + '"></span>';
|
||||
}
|
||||
|
||||
function datahubStatusText(hub) {
|
||||
const enabled = number(hub.enabled_reads);
|
||||
const total = number(hub.total_reads) || enabled;
|
||||
const fallbacks = hub.fallback_labels || [];
|
||||
if (fallbacks.length) return " 备用 " + fallbacks.join("、");
|
||||
if (hub.configured) return " 主线路 " + enabled + "/" + total;
|
||||
return " 未配置";
|
||||
}
|
||||
|
||||
function renderSystemAdmin(key) {
|
||||
if (key === "system/members") {
|
||||
renderSystemMembers();
|
||||
@@ -5215,6 +5246,7 @@
|
||||
'<div class="m-sys-status-item"><span>iFinD</span><span>' + statusDot(ifind.configured) + (ifind.configured ? " 已配置" : " 未配置") + "</span></div>" +
|
||||
'<div class="m-sys-status-item"><span>行情快照</span><strong>' + number(data.snapshot_dates) + " 个交易日</strong></div>" +
|
||||
'<div class="m-sys-status-item"><span>后台刷新</span><span>' + statusDot(data.background_refresh_enabled) + (data.background_refresh_enabled ? " 已启用" : " 已暂停") + "</span></div>" +
|
||||
'<div class="m-sys-status-item"><span>数据中枢</span><span>' + statusDot(Boolean((data.datahub || {}).configured) && !((data.datahub || {}).fallback_count)) + datahubStatusText(data.datahub || {}) + "</span></div>" +
|
||||
"</div></div>" +
|
||||
'<div class="m-card m-sys-section"><strong>数据源密钥</strong>' +
|
||||
formFieldHtml("Tushare Token", '<input id="m-sys-token" type="password" autocomplete="off" minlength="20" placeholder="留空则保留现有 Token">', false) +
|
||||
|
||||
@@ -367,7 +367,11 @@ function selectStockPreviewChart(chart) {
|
||||
}
|
||||
} else if ((payload.prices || []).length) {
|
||||
setText("stockPreviewDate", payload.meta?.trade_date || "最新行情");
|
||||
setText("stockPreviewSource", `日 K 行情 · ${payload.prices.length} 个交易日`);
|
||||
const notice = String(payload.meta?.notice || "").trim();
|
||||
setText(
|
||||
"stockPreviewSource",
|
||||
notice ? `日 K 行情 · ${payload.prices.length} 个交易日 · ${notice}` : `日 K 行情 · ${payload.prices.length} 个交易日`,
|
||||
);
|
||||
drawDailyPreviewChart(payload.prices);
|
||||
} else {
|
||||
setText("stockPreviewDate", payload.meta?.trade_date || "最新行情");
|
||||
|
||||
@@ -52,7 +52,11 @@ async function openStock(code, fallback = null) {
|
||||
renderStockNotes(payload.notes || []);
|
||||
updateWatchButton();
|
||||
if (state.stockDetailChartMode === "daily") {
|
||||
setText("chartSource", `日 K 行情 · ${payload.prices.length} 个交易日`);
|
||||
const notice = String(payload.meta?.notice || "").trim();
|
||||
setText(
|
||||
"chartSource",
|
||||
notice ? `日 K 行情 · ${payload.prices.length} 个交易日 · ${notice}` : `日 K 行情 · ${payload.prices.length} 个交易日`,
|
||||
);
|
||||
requestAnimationFrame(() => drawPriceChart(payload.prices || []));
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -69,7 +73,13 @@ async function selectStockDetailChart(mode) {
|
||||
syncDetailChartButtons("stock", selected);
|
||||
if (selected === "daily") {
|
||||
const prices = state.stockDetail?.prices || [];
|
||||
setText("chartSource", prices.length ? `日 K 行情 · ${prices.length} 个交易日` : "正在加载行情");
|
||||
const notice = String(state.stockDetail?.meta?.notice || "").trim();
|
||||
setText(
|
||||
"chartSource",
|
||||
prices.length
|
||||
? (notice ? `日 K 行情 · ${prices.length} 个交易日 · ${notice}` : `日 K 行情 · ${prices.length} 个交易日`)
|
||||
: "正在加载行情",
|
||||
);
|
||||
if (prices.length) requestAnimationFrame(() => drawPriceChart(prices));
|
||||
else clearPriceChart("正在加载日 K 数据");
|
||||
return;
|
||||
|
||||
@@ -44,6 +44,7 @@ async function openAdminSettings(refreshOnly = false) {
|
||||
status.textContent = `Tushare ${data.configured ? "已配置" : "未配置"} · iFinD ${ifind.configured ? "已配置" : "未配置"} · ${number(data.snapshot_dates)} 个交易日`;
|
||||
status.classList.toggle("connected", Boolean(data.configured));
|
||||
setText("systemDataStatus", data.background_refresh_enabled ? "后台刷新已启用" : "后台刷新已暂停");
|
||||
renderDatahubRouteStatus(data.datahub || {});
|
||||
document.querySelector("#systemTokenInput").value = "";
|
||||
document.querySelector("#systemIfindTokenInput").value = "";
|
||||
document.querySelector("#systemBackgroundRefresh").checked = Boolean(data.background_refresh_enabled);
|
||||
@@ -55,6 +56,26 @@ async function openAdminSettings(refreshOnly = false) {
|
||||
}
|
||||
}
|
||||
|
||||
function renderDatahubRouteStatus(hub) {
|
||||
const box = document.querySelector("#datahubRouteStatus");
|
||||
if (!box) return;
|
||||
const label = box.querySelector("span");
|
||||
const enabled = number(hub.enabled_reads);
|
||||
const total = number(hub.total_reads) || enabled;
|
||||
const fallbacks = hub.fallback_labels || [];
|
||||
if (fallbacks.length) {
|
||||
box.dataset.tone = "warning";
|
||||
if (label) label.textContent = `数据中枢主线路 ${enabled}/${total} · 备用 ${fallbacks.length} 类:${fallbacks.join("、")}`;
|
||||
return;
|
||||
}
|
||||
box.dataset.tone = hub.configured ? "success" : "idle";
|
||||
if (label) {
|
||||
label.textContent = hub.configured
|
||||
? `数据中枢主线路 ${enabled}/${total},当前无备用`
|
||||
: "数据中枢尚未配置,网站仍走原接口";
|
||||
}
|
||||
}
|
||||
|
||||
function selectAdminPanel(panel) {
|
||||
const selected = ["market", "models", "members"].includes(panel) ? panel : "market";
|
||||
document.querySelector("#adminSectionSelect").value = selected;
|
||||
|
||||
@@ -66,11 +66,18 @@ async function startAdminRefresh() {
|
||||
const requestedCompact = requestedDate.replaceAll("-", "");
|
||||
const actualCompact = actualDate.replaceAll("-", "");
|
||||
const updated = formatTimestamp(meta.updated_at);
|
||||
if (actualCompact !== requestedCompact || meta.carried_forward) {
|
||||
const reason = meta.notice ? `;${meta.notice}` : "";
|
||||
setAdminRefreshStatus("warning", `刷新已完成,但没有获取到 ${requestedDate} 的最新行情;当前仍是 ${actualDate || "未知日期"}${reason}`, "triangle-alert");
|
||||
showToast("刷新完成,但未获取到所选日期的最新行情");
|
||||
} else if (meta.notice) {
|
||||
const freshness = dashboardFreshnessMessage(meta);
|
||||
if (meta.realtime && actualCompact === requestedCompact && !meta.carried_forward) {
|
||||
setAdminRefreshStatus("success", `刷新成功:已获取 ${actualDate} 的盘中行情,更新时间 ${updated}`, "circle-check");
|
||||
showToast(`刷新成功:已获取 ${actualDate} 的盘中行情`);
|
||||
return;
|
||||
}
|
||||
if (freshness || actualCompact !== requestedCompact || meta.carried_forward || meta.limit_data_source === "derived") {
|
||||
setAdminRefreshStatus("warning", freshness || `部分正式数据尚未到齐,当前展示 ${actualDate || "最近可用数据"}`, "triangle-alert");
|
||||
setStatus(freshness || "部分正式数据尚未到齐,当前展示最近可用数据");
|
||||
return;
|
||||
}
|
||||
if (meta.notice) {
|
||||
setAdminRefreshStatus("warning", `已刷新到 ${actualDate}(${updated}),但数据源提示:${meta.notice}`, "triangle-alert");
|
||||
showToast(`已刷新到 ${actualDate},请留意数据源提示`);
|
||||
} else {
|
||||
@@ -105,6 +112,37 @@ async function waitForAdminRefresh(jobKey) {
|
||||
throw new Error("刷新等待超时,请稍后重试");
|
||||
}
|
||||
|
||||
let dashboardCatchupTimer = 0;
|
||||
|
||||
function chineseMonthDay(value) {
|
||||
const compact = String(value || "").replaceAll("-", "").replaceAll("/", "");
|
||||
if (!/^\d{8}/.test(compact)) return "";
|
||||
return `${Number(compact.slice(4, 6))} 月 ${Number(compact.slice(6, 8))} 日`;
|
||||
}
|
||||
|
||||
function dashboardFreshnessMessage(meta = {}) {
|
||||
if (meta.display_notice) return String(meta.display_notice);
|
||||
const requested = String(meta.requested_date || "").replaceAll("-", "");
|
||||
const actual = String(meta.trade_date || "").replaceAll("-", "");
|
||||
const shown = chineseMonthDay(actual);
|
||||
if (meta.data_status === "preparing" || (meta.carried_forward && actual && requested && actual !== requested)) {
|
||||
return shown ? `今日数据正在准备,当前展示 ${shown}` : "今日数据正在准备,当前展示最近可用数据";
|
||||
}
|
||||
if (meta.data_status === "partial" || meta.limit_data_source === "derived") {
|
||||
return meta.notice || "部分正式数据尚未到齐,当前展示日线推算结果";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function scheduleDashboardCatchup(meta = {}) {
|
||||
window.clearTimeout(dashboardCatchupTimer);
|
||||
const status = String(meta.data_status || "");
|
||||
if (status !== "preparing" && status !== "partial") return;
|
||||
dashboardCatchupTimer = window.setTimeout(() => {
|
||||
loadDashboard(false, true, false);
|
||||
}, 60000);
|
||||
}
|
||||
|
||||
function applyDashboard(payload, background = false) {
|
||||
state.dashboard = payload;
|
||||
const selectedDate = payload.meta.requested_date || payload.meta.trade_date;
|
||||
@@ -112,7 +150,11 @@ function applyDashboard(payload, background = false) {
|
||||
document.querySelector("#qiObservationDate").value = selectedDate;
|
||||
document.querySelector("#journalDate").value = selectedDate;
|
||||
renderDashboard();
|
||||
setStatus(`${dashboardSourceLabel(payload.meta)} · 数据已更新`);
|
||||
const freshness = dashboardFreshnessMessage(payload.meta || {});
|
||||
setStatus(freshness || `${dashboardSourceLabel(payload.meta)} · 数据已更新`);
|
||||
const updatedAt = document.querySelector("#updatedAt");
|
||||
if (updatedAt) updatedAt.dataset.tone = freshness ? "warning" : "ok";
|
||||
scheduleDashboardCatchup(payload.meta || {});
|
||||
if (!background) {
|
||||
if (state.activeView === "dragonView") loadDragonTiger();
|
||||
if (state.activeView === "screenerView") loadScreenerSetup();
|
||||
@@ -180,7 +222,12 @@ function renderDashboard() {
|
||||
}
|
||||
}
|
||||
updateSentimentGauge(overview.sentiment_score);
|
||||
setText("updatedAt", `${dashboardSourceLabel(meta)} · 更新 ${formatTimestamp(meta.updated_at)}`);
|
||||
const freshness = dashboardFreshnessMessage(meta);
|
||||
setText("updatedAt", freshness
|
||||
? freshness
|
||||
: `${dashboardSourceLabel(meta)} · 更新 ${formatTimestamp(meta.updated_at)}`);
|
||||
const updatedAt = document.querySelector("#updatedAt");
|
||||
if (updatedAt) updatedAt.dataset.tone = freshness ? "warning" : "ok";
|
||||
|
||||
renderLimitTable();
|
||||
renderLadderMini(ladders || []);
|
||||
|
||||
@@ -921,6 +921,10 @@ body.sidebar-collapsed .app-main {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.status-bar #updatedAt[data-tone="warning"] {
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
.status-bar .risk-note {
|
||||
display: block;
|
||||
|
||||
|
||||
@@ -1,23 +1,452 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import threading
|
||||
import unittest
|
||||
from datetime import date, datetime, timedelta, timezone, time as dt_time
|
||||
from unittest.mock import patch
|
||||
from pathlib import Path
|
||||
|
||||
from backend.jobs.service import _verified_dashboard_result
|
||||
from backend.features.market.service import MarketServiceMixin
|
||||
from backend.jobs.refresh import (
|
||||
dashboard_has_usable_data,
|
||||
official_catchup_due,
|
||||
verified_dashboard_result,
|
||||
)
|
||||
from backend.data.providers.tushare_transport import TushareError
|
||||
|
||||
|
||||
class AdminRefreshStatusTests(unittest.TestCase):
|
||||
def test_carried_snapshot_is_reported_as_failed_job(self):
|
||||
result = _verified_dashboard_result(
|
||||
{"meta": {"carried_forward": True, "notice": "官方涨跌停数据尚未返回"}}
|
||||
def test_carried_snapshot_is_usable_not_failed_job(self):
|
||||
result = verified_dashboard_result(
|
||||
{
|
||||
"meta": {
|
||||
"trade_date": "2026-09-01",
|
||||
"requested_date": "2026-09-02",
|
||||
"carried_forward": True,
|
||||
"notice": "今日数据正在准备,当前展示 9 月 1 日",
|
||||
"data_status": "preparing",
|
||||
},
|
||||
"overview": {"limit_up_count": 12},
|
||||
}
|
||||
)
|
||||
|
||||
self.assertEqual(result["status"], "failed")
|
||||
self.assertEqual(result["error"], "官方涨跌停数据尚未返回")
|
||||
self.assertNotEqual(result.get("status"), "failed")
|
||||
self.assertEqual(result["meta"]["data_status"], "preparing")
|
||||
self.assertTrue(dashboard_has_usable_data(result))
|
||||
|
||||
def test_derived_limit_snapshot_is_usable_not_failed_job(self):
|
||||
dashboard = {
|
||||
"meta": {
|
||||
"trade_date": "2026-09-02",
|
||||
"limit_data_source": "derived",
|
||||
"notice": "涨跌停高级接口当日数据尚未更新,已使用日线数据推算。",
|
||||
"data_status": "partial",
|
||||
},
|
||||
"overview": {"limit_up_count": 8},
|
||||
}
|
||||
|
||||
self.assertIs(verified_dashboard_result(dashboard), dashboard)
|
||||
|
||||
def test_current_snapshot_is_reported_as_successful_job(self):
|
||||
dashboard = {"meta": {"trade_date": "2026-08-28", "carried_forward": False}}
|
||||
|
||||
self.assertIs(_verified_dashboard_result(dashboard), dashboard)
|
||||
self.assertIs(verified_dashboard_result(dashboard), dashboard)
|
||||
|
||||
def test_empty_payload_is_still_failed(self):
|
||||
result = verified_dashboard_result({"meta": {}, "overview": {}})
|
||||
self.assertEqual(result["status"], "failed")
|
||||
|
||||
|
||||
class FakeSyncDatabase:
|
||||
def __init__(self, latest=None):
|
||||
self.latest = latest
|
||||
self.saved = []
|
||||
self.finished = []
|
||||
|
||||
def start_sync(self, *_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
def save_snapshot(self, trade_date, source, payload):
|
||||
self.saved.append((trade_date, source, copy.deepcopy(payload)))
|
||||
|
||||
def save_data_snapshot(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
def finish_sync(self, *args, **kwargs):
|
||||
self.finished.append((args, kwargs))
|
||||
|
||||
def get_latest_real_snapshot(self, *_args, **_kwargs):
|
||||
return copy.deepcopy(self.latest)
|
||||
|
||||
def get_snapshot(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
def get_data_snapshot(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
def reason_overrides(self, *_args, **_kwargs):
|
||||
return {}
|
||||
|
||||
|
||||
class FakeDerivedClient:
|
||||
def dashboard(self, trade_date: str):
|
||||
return {
|
||||
"meta": {
|
||||
"trade_date": f"{trade_date[:4]}-{trade_date[4:6]}-{trade_date[6:8]}",
|
||||
"limit_data_source": "derived",
|
||||
"notice": "涨跌停高级接口当日数据尚未更新,已使用日线数据推算。",
|
||||
"updated_at": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||
},
|
||||
"overview": {"limit_up_count": 3},
|
||||
"limits": [{"code": "000001"}],
|
||||
"broken": [],
|
||||
"down_limits": [],
|
||||
"yesterday_limits": [],
|
||||
}
|
||||
|
||||
|
||||
SHANGHAI = timezone(timedelta(hours=8))
|
||||
TRADE_DAY = date(2026, 9, 8)
|
||||
|
||||
|
||||
def at_clock(hour: int, minute: int, day: date = TRADE_DAY) -> datetime:
|
||||
return datetime(day.year, day.month, day.day, hour, minute, tzinfo=SHANGHAI)
|
||||
|
||||
|
||||
class FakeMissingDailyClient:
|
||||
def __init__(self, open_today: bool = True):
|
||||
self.open_today = open_today
|
||||
|
||||
def dashboard(self, trade_date: str):
|
||||
raise TushareError(f"No daily data returned for {trade_date}")
|
||||
|
||||
def resolve_trade_context(self, requested: str):
|
||||
if self.open_today:
|
||||
return requested, "20260907"
|
||||
return "20260907", "20260904"
|
||||
|
||||
|
||||
class FakeRealtimeTodayClient:
|
||||
def dashboard(self, trade_date: str):
|
||||
return {
|
||||
"meta": {
|
||||
"trade_date": f"{trade_date[:4]}-{trade_date[4:6]}-{trade_date[6:8]}",
|
||||
"requested_date": f"{trade_date[:4]}-{trade_date[4:6]}-{trade_date[6:8]}",
|
||||
"realtime": True,
|
||||
"mode": "realtime",
|
||||
"market_status": "trading",
|
||||
"notice": "盘中行情由 Tushare rt_k 实时计算;涨停原因、封板时间和开板次数以盘后榜单校正为准。",
|
||||
"updated_at": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||
},
|
||||
"overview": {"limit_up_count": 15},
|
||||
"limits": [{"code": "000001"}],
|
||||
"broken": [],
|
||||
"down_limits": [],
|
||||
"yesterday_limits": [],
|
||||
}
|
||||
|
||||
def resolve_trade_context(self, requested: str):
|
||||
return requested, "20260907"
|
||||
|
||||
|
||||
class FakeFreeRealtimeTodayClient:
|
||||
def dashboard(self, trade_date: str):
|
||||
return {
|
||||
"meta": {
|
||||
"trade_date": f"{trade_date[:4]}-{trade_date[4:6]}-{trade_date[6:8]}",
|
||||
"requested_date": f"{trade_date[:4]}-{trade_date[4:6]}-{trade_date[6:8]}",
|
||||
"realtime": True,
|
||||
"mode": "realtime",
|
||||
"quote_source": "eastmoney_clist",
|
||||
"source": "eastmoney",
|
||||
"market_status": "trading",
|
||||
"notice": "盘中行情由东财免费实时快照计算;涨停原因、封板时间和开板次数以盘后榜单校正为准。",
|
||||
"updated_at": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||
"indices": [{"code": "000001", "price": 3800.1, "change": 0.5}],
|
||||
},
|
||||
"overview": {"limit_up_count": 18, "up_count": 2100, "amount_billion": 12345.6},
|
||||
"limits": [{"code": "000001"}],
|
||||
"broken": [],
|
||||
"down_limits": [],
|
||||
"yesterday_limits": [],
|
||||
}
|
||||
|
||||
def resolve_trade_context(self, requested: str):
|
||||
return requested, "20260907"
|
||||
|
||||
|
||||
class SyncHarness(MarketServiceMixin):
|
||||
def __init__(self, client, latest=None, clock=None):
|
||||
self.configured = True
|
||||
self.sync_lock = threading.Lock()
|
||||
self.database = FakeSyncDatabase(latest)
|
||||
self._client = client
|
||||
self.current_user_id = 1
|
||||
self.clock = clock
|
||||
|
||||
def _tushare_client(self):
|
||||
return self._client
|
||||
|
||||
def _enrich_dashboard_sentiment(self, dashboard, _trade_date):
|
||||
return dashboard
|
||||
|
||||
def _apply_reason_overrides(self, dashboard):
|
||||
return dashboard
|
||||
|
||||
|
||||
class DashboardFreshnessTests(unittest.TestCase):
|
||||
def test_derived_limits_are_kept_as_partial_success(self):
|
||||
today = date.today().strftime("%Y%m%d")
|
||||
harness = SyncHarness(FakeDerivedClient())
|
||||
payload = harness.sync_dashboard(today)
|
||||
meta = payload["meta"]
|
||||
|
||||
self.assertEqual(meta["limit_data_source"], "derived")
|
||||
self.assertEqual(meta["data_status"], "partial")
|
||||
self.assertFalse(meta.get("carried_forward"))
|
||||
self.assertIn("日线数据推算", meta["display_notice"])
|
||||
self.assertEqual(harness.database.finished[0][0][1], "success")
|
||||
self.assertEqual(verified_dashboard_result(payload), payload)
|
||||
|
||||
def test_intraday_refresh_keeps_today_and_does_not_fall_back_to_yesterday(self):
|
||||
today = TRADE_DAY.strftime("%Y%m%d")
|
||||
latest = {
|
||||
"meta": {"trade_date": "2026-09-07", "source": "tushare"},
|
||||
"overview": {"limit_up_count": 20},
|
||||
}
|
||||
harness = SyncHarness(
|
||||
FakeRealtimeTodayClient(),
|
||||
latest,
|
||||
clock=lambda: at_clock(10, 5),
|
||||
)
|
||||
payload = harness.sync_dashboard(today)
|
||||
meta = payload["meta"]
|
||||
|
||||
self.assertFalse(meta.get("carried_forward"))
|
||||
self.assertTrue(meta["realtime"])
|
||||
self.assertEqual(meta["data_status"], "intraday")
|
||||
self.assertEqual(str(meta["trade_date"]).replace("-", ""), today)
|
||||
self.assertNotIn("今日数据正在准备", meta.get("display_notice") or "")
|
||||
self.assertEqual(harness.database.saved[0][0], today)
|
||||
|
||||
def test_intraday_free_source_keeps_today_and_indices(self):
|
||||
today = TRADE_DAY.strftime("%Y%m%d")
|
||||
latest = {
|
||||
"meta": {"trade_date": "2026-09-07", "source": "tushare"},
|
||||
"overview": {"limit_up_count": 20},
|
||||
}
|
||||
harness = SyncHarness(
|
||||
FakeFreeRealtimeTodayClient(),
|
||||
latest,
|
||||
clock=lambda: at_clock(10, 5),
|
||||
)
|
||||
payload = harness.sync_dashboard(today)
|
||||
meta = payload["meta"]
|
||||
self.assertFalse(meta.get("carried_forward"))
|
||||
self.assertTrue(meta["realtime"])
|
||||
self.assertEqual(meta["data_status"], "intraday")
|
||||
self.assertEqual(str(meta["trade_date"]).replace("-", ""), today)
|
||||
self.assertEqual(meta["quote_source"], "eastmoney_clist")
|
||||
self.assertEqual(payload["overview"]["amount_billion"], 12345.6)
|
||||
self.assertEqual(meta["indices"][0]["price"], 3800.1)
|
||||
self.assertEqual(harness.database.saved[0][0], today)
|
||||
|
||||
def test_intraday_missing_quotes_do_not_carry_yesterday(self):
|
||||
today = TRADE_DAY.strftime("%Y%m%d")
|
||||
latest = {
|
||||
"meta": {"trade_date": "2026-09-07", "source": "tushare"},
|
||||
"overview": {"limit_up_count": 20},
|
||||
}
|
||||
harness = SyncHarness(
|
||||
FakeMissingDailyClient(),
|
||||
latest,
|
||||
clock=lambda: at_clock(10, 5),
|
||||
)
|
||||
with self.assertRaises(ValueError) as ctx:
|
||||
harness.sync_dashboard(today)
|
||||
self.assertIn("当天盘中行情", str(ctx.exception))
|
||||
self.assertFalse(harness.database.saved)
|
||||
|
||||
def test_intraday_keeps_existing_today_snapshot_when_refresh_fails(self):
|
||||
today = TRADE_DAY.strftime("%Y%m%d")
|
||||
existing = {
|
||||
"meta": {
|
||||
"trade_date": "2026-09-08",
|
||||
"realtime": True,
|
||||
"mode": "realtime",
|
||||
"source": "tushare",
|
||||
},
|
||||
"overview": {"limit_up_count": 11},
|
||||
"limits": [{"code": "600000"}],
|
||||
"broken": [],
|
||||
"down_limits": [],
|
||||
"yesterday_limits": [],
|
||||
}
|
||||
harness = SyncHarness(
|
||||
FakeMissingDailyClient(),
|
||||
clock=lambda: at_clock(10, 5),
|
||||
)
|
||||
harness.database.get_snapshot = lambda *_args, **_kwargs: copy.deepcopy(existing)
|
||||
payload = harness.sync_dashboard(today)
|
||||
meta = payload["meta"]
|
||||
self.assertEqual(str(meta["trade_date"]).replace("-", ""), today)
|
||||
self.assertTrue(meta["realtime"])
|
||||
self.assertEqual(meta["data_status"], "intraday")
|
||||
self.assertFalse(meta.get("carried_forward"))
|
||||
|
||||
def test_lunch_and_after_hours_keep_today_until_official_arrives(self):
|
||||
today = TRADE_DAY.strftime("%Y%m%d")
|
||||
for clock in (lambda: at_clock(12, 0), lambda: at_clock(16, 10)):
|
||||
harness = SyncHarness(
|
||||
FakeRealtimeTodayClient(),
|
||||
clock=clock,
|
||||
)
|
||||
payload = harness.sync_dashboard(today)
|
||||
self.assertEqual(str(payload["meta"]["trade_date"]).replace("-", ""), today)
|
||||
self.assertFalse(payload["meta"].get("carried_forward"))
|
||||
|
||||
def test_preopen_and_weekend_still_carry_last_session(self):
|
||||
latest = {
|
||||
"meta": {"trade_date": "2026-09-07", "source": "tushare"},
|
||||
"overview": {"limit_up_count": 20},
|
||||
}
|
||||
preopen = SyncHarness(
|
||||
FakeMissingDailyClient(),
|
||||
latest,
|
||||
clock=lambda: at_clock(8, 30),
|
||||
)
|
||||
preopen_payload = preopen.sync_dashboard(TRADE_DAY.strftime("%Y%m%d"))
|
||||
self.assertTrue(preopen_payload["meta"]["carried_forward"])
|
||||
self.assertEqual(preopen_payload["meta"]["data_status"], "preparing")
|
||||
self.assertIn("今日数据正在准备,当前展示", preopen_payload["meta"]["display_notice"])
|
||||
|
||||
weekend = SyncHarness(
|
||||
FakeMissingDailyClient(open_today=False),
|
||||
latest,
|
||||
clock=lambda: at_clock(10, 5, date(2026, 9, 5)),
|
||||
)
|
||||
weekend_payload = weekend.sync_dashboard("20260905")
|
||||
self.assertTrue(weekend_payload["meta"]["carried_forward"])
|
||||
|
||||
def test_history_date_still_uses_official_or_preparing_notice(self):
|
||||
latest = {
|
||||
"meta": {"trade_date": "2026-09-01", "source": "tushare"},
|
||||
"overview": {"limit_up_count": 8},
|
||||
}
|
||||
harness = SyncHarness(
|
||||
FakeMissingDailyClient(),
|
||||
latest,
|
||||
clock=lambda: at_clock(10, 5),
|
||||
)
|
||||
payload = harness.sync_dashboard("20260902")
|
||||
self.assertTrue(payload["meta"]["carried_forward"])
|
||||
self.assertIn("所选日期数据尚未到齐", payload["meta"]["display_notice"])
|
||||
|
||||
def test_carried_today_snapshot_is_retried_immediately_in_session(self):
|
||||
today = TRADE_DAY.strftime("%Y%m%d")
|
||||
snapshot = {
|
||||
"meta": {
|
||||
"source": "tushare",
|
||||
"trade_date": "2026-09-07",
|
||||
"carried_forward": True,
|
||||
"requested_date": "2026-09-08",
|
||||
"updated_at": at_clock(10, 0).isoformat(),
|
||||
},
|
||||
"overview": {"limit_up_count": 1},
|
||||
}
|
||||
harness = SyncHarness(
|
||||
FakeRealtimeTodayClient(),
|
||||
clock=lambda: at_clock(10, 5),
|
||||
)
|
||||
harness.database.get_snapshot = lambda *_args, **_kwargs: copy.deepcopy(snapshot)
|
||||
payload = harness.get_dashboard(today)
|
||||
self.assertEqual(str(payload["meta"]["trade_date"]).replace("-", ""), today)
|
||||
self.assertEqual(payload["meta"]["data_status"], "intraday")
|
||||
self.assertTrue(harness.database.saved)
|
||||
|
||||
def test_weekend_carry_is_not_labeled_as_preparing(self):
|
||||
snapshot = {
|
||||
"meta": {"trade_date": "2026-07-24", "source": "tushare", "updated_at": "2026-07-24T15:00:00+08:00"},
|
||||
"overview": {"limit_up_count": 1},
|
||||
}
|
||||
harness = SyncHarness(FakeMissingDailyClient())
|
||||
carried = harness._carry_dashboard(snapshot, "20260725", "非交易日沿用最近交易日收盘行情")
|
||||
self.assertEqual(carried["meta"]["data_status"], "carried")
|
||||
self.assertIn("非交易日", carried["meta"]["display_notice"])
|
||||
|
||||
def test_stale_derived_snapshot_is_retried(self):
|
||||
today = date.today().strftime("%Y%m%d")
|
||||
old = datetime.now(timezone.utc) - timedelta(minutes=5)
|
||||
snapshot = {
|
||||
"meta": {
|
||||
"source": "tushare",
|
||||
"trade_date": f"{today[:4]}-{today[4:6]}-{today[6:8]}",
|
||||
"limit_data_source": "derived",
|
||||
"updated_at": old.isoformat(),
|
||||
},
|
||||
"overview": {"limit_up_count": 1},
|
||||
}
|
||||
harness = SyncHarness(FakeDerivedClient())
|
||||
harness.database.get_snapshot = lambda *_args, **_kwargs: copy.deepcopy(snapshot)
|
||||
payload = harness.get_dashboard(today)
|
||||
self.assertEqual(payload["meta"]["data_status"], "partial")
|
||||
self.assertTrue(harness.database.saved)
|
||||
|
||||
def test_official_catchup_skips_complete_today_snapshot(self):
|
||||
today = date.today().strftime("%Y%m%d")
|
||||
iso = f"{today[:4]}-{today[4:6]}-{today[6:8]}"
|
||||
due = official_catchup_due(
|
||||
today,
|
||||
{"meta": {"trade_date": iso, "limit_data_source": "official"}},
|
||||
)
|
||||
derived_due = official_catchup_due(
|
||||
today,
|
||||
{"meta": {"trade_date": iso, "limit_data_source": "derived"}},
|
||||
)
|
||||
now = datetime.now().astimezone().time().replace(tzinfo=None)
|
||||
if dt_time(15, 5) <= now < dt_time(22, 0):
|
||||
self.assertFalse(due)
|
||||
self.assertTrue(derived_due)
|
||||
else:
|
||||
self.assertFalse(due)
|
||||
self.assertFalse(derived_due)
|
||||
|
||||
def test_official_catchup_is_due_for_intraday_snapshot_after_close(self):
|
||||
today = TRADE_DAY.strftime("%Y%m%d")
|
||||
snapshot = {
|
||||
"meta": {
|
||||
"trade_date": "2026-09-08",
|
||||
"realtime": True,
|
||||
"mode": "realtime",
|
||||
}
|
||||
}
|
||||
with patch("backend.jobs.refresh.datetime") as mocked:
|
||||
mocked.now.return_value = at_clock(16, 10)
|
||||
mocked.strptime = datetime.strptime
|
||||
self.assertTrue(official_catchup_due(today, snapshot))
|
||||
official = {
|
||||
"meta": {
|
||||
"trade_date": "2026-09-08",
|
||||
"limit_data_source": "official",
|
||||
"realtime": False,
|
||||
}
|
||||
}
|
||||
self.assertFalse(official_catchup_due(today, official))
|
||||
|
||||
|
||||
class FrontendRefreshCopyTests(unittest.TestCase):
|
||||
def test_dashboard_script_distinguishes_partial_from_failure(self):
|
||||
script = (Path(__file__).resolve().parents[1] / "frontend" / "shared" / "dashboard.js").read_text(encoding="utf-8")
|
||||
self.assertIn("今日数据正在准备,当前展示", script)
|
||||
self.assertIn("部分正式数据尚未到齐", script)
|
||||
self.assertIn("盘中行情", script)
|
||||
self.assertIn("meta.realtime && actualCompact === requestedCompact", script)
|
||||
self.assertIn('job.status === "failed"', script)
|
||||
failed_block = script.split("if (job.status === \"failed\")", 1)[1].split("const query", 1)[0]
|
||||
self.assertIn("后台刷新失败", failed_block)
|
||||
success_block = script.split("const freshness = dashboardFreshnessMessage(meta);", 1)[1]
|
||||
self.assertNotIn("后台刷新失败", success_block.split("} else {", 1)[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import logging
|
||||
import unittest
|
||||
|
||||
from backend.bootstrap.runtime import configure_logging
|
||||
|
||||
|
||||
class ConfigureLoggingTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self._saved_handlers = logging.getLogger().handlers[:]
|
||||
self._saved_level = logging.getLogger().level
|
||||
logging.getLogger().handlers.clear()
|
||||
|
||||
def tearDown(self) -> None:
|
||||
logging.getLogger().handlers[:] = self._saved_handlers
|
||||
logging.getLogger().setLevel(self._saved_level)
|
||||
|
||||
def test_configures_root_logger_at_info(self) -> None:
|
||||
configure_logging()
|
||||
root = logging.getLogger()
|
||||
self.assertTrue(root.handlers)
|
||||
self.assertEqual(root.level, logging.INFO)
|
||||
with self.assertLogs("xiaobai.datahub", level="INFO") as captured:
|
||||
logging.getLogger("xiaobai.datahub").info("datahub shadow %s", {"dataset": "daily"})
|
||||
self.assertIn("datahub shadow", captured.output[0])
|
||||
|
||||
def test_keeps_existing_configuration(self) -> None:
|
||||
handler = logging.NullHandler()
|
||||
logging.getLogger().addHandler(handler)
|
||||
configure_logging()
|
||||
self.assertEqual(logging.getLogger().handlers, [handler])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -2,7 +2,8 @@ from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from backend.features.market.charts import ChartDataError, EastmoneyChartClient
|
||||
from backend.data.providers.ifind_client import IfindHttpClient
|
||||
from backend.features.market.charts import ChartDataError, EastmoneyChartClient, HIS_TRENDS_URL, MarketChartClient, TRENDS_URL
|
||||
from server import DashboardService
|
||||
|
||||
|
||||
@@ -72,6 +73,171 @@ class ChartDataProviderTests(unittest.TestCase):
|
||||
self.client.stock_intraday("abc")
|
||||
|
||||
|
||||
class LookbackChartClient(EastmoneyChartClient):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(cache_ttl_seconds=20)
|
||||
self.requests: list[tuple[str, dict[str, str]]] = []
|
||||
|
||||
def _request_json(self, url, params, referer):
|
||||
self.requests.append((url, params))
|
||||
if url == TRENDS_URL and params.get("ndays") == "1":
|
||||
return {"data": {"code": "601318", "name": "中国平安", "preClose": 56.0, "trends": []}}
|
||||
if url == TRENDS_URL and params.get("ndays") == "5":
|
||||
return {"data": {"code": "601318", "name": "中国平安", "preClose": 56.0, "trends": []}}
|
||||
if url == HIS_TRENDS_URL:
|
||||
return {
|
||||
"data": {
|
||||
"code": "601318",
|
||||
"name": "中国平安",
|
||||
"preClose": 55.8,
|
||||
"trends": [
|
||||
"2026-09-07 09:30,55.80,55.90,56.00,55.70,100,5580.00,55.900",
|
||||
"2026-09-07 15:00,56.10,56.20,56.30,56.00,200,11240.00,56.150",
|
||||
"2026-09-08 09:30,0,0,0,0,0,0.00,0",
|
||||
],
|
||||
}
|
||||
}
|
||||
raise ChartDataError("unexpected url")
|
||||
|
||||
|
||||
class ChartLookbackTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
EastmoneyChartClient._cache.clear()
|
||||
self.client = LookbackChartClient()
|
||||
|
||||
def test_empty_today_falls_back_to_latest_available_session(self):
|
||||
payload = self.client.stock_intraday("601318")
|
||||
urls = [url for url, _ in self.client.requests]
|
||||
self.assertEqual(urls[0], TRENDS_URL)
|
||||
self.assertEqual(self.client.requests[0][1]["ndays"], "1")
|
||||
self.assertEqual(urls[1], TRENDS_URL)
|
||||
self.assertEqual(self.client.requests[1][1]["ndays"], "5")
|
||||
self.assertEqual(urls[2], HIS_TRENDS_URL)
|
||||
self.assertEqual(payload["trade_date"], "2026-09-07")
|
||||
self.assertEqual([point["time"] for point in payload["points"]], ["09:30", "15:00"])
|
||||
self.assertEqual(payload["points"][0]["close"], 55.9)
|
||||
|
||||
def test_delay_multiday_can_recover_without_his(self):
|
||||
class DelayFive(EastmoneyChartClient):
|
||||
def __init__(self):
|
||||
super().__init__(cache_ttl_seconds=20)
|
||||
self.requests = []
|
||||
|
||||
def _request_json(self, url, params, referer):
|
||||
self.requests.append((url, params))
|
||||
if params.get("ndays") == "1":
|
||||
return {"data": {"code": "000001", "name": "平安银行", "preClose": 11.7, "trends": []}}
|
||||
return {
|
||||
"data": {
|
||||
"code": "000001",
|
||||
"name": "平安银行",
|
||||
"preClose": 11.5,
|
||||
"trends": [
|
||||
"2026-09-07 09:30,11.50,11.60,11.70,11.40,100,1160.00,11.600",
|
||||
"2026-09-07 15:00,11.70,11.80,11.90,11.60,200,2360.00,11.750",
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
EastmoneyChartClient._cache.clear()
|
||||
client = DelayFive()
|
||||
payload = client.stock_intraday("000001")
|
||||
self.assertEqual(payload["trade_date"], "2026-09-07")
|
||||
self.assertEqual(len(payload["points"]), 2)
|
||||
self.assertEqual([url for url, _ in client.requests], [TRENDS_URL, TRENDS_URL])
|
||||
|
||||
def test_sh_sz_cyb_codes_use_correct_secid(self):
|
||||
for code, secid in (("601318", "1.601318"), ("000001", "0.000001"), ("300750", "0.300750")):
|
||||
EastmoneyChartClient._cache.clear()
|
||||
client = LookbackChartClient()
|
||||
client.stock_intraday(code)
|
||||
self.assertEqual(client.requests[0][1]["secid"], secid)
|
||||
|
||||
|
||||
class FakeHub:
|
||||
def __init__(self, chart=None, error=None, daily=None):
|
||||
self.chart = chart
|
||||
self.error = error
|
||||
self.daily = daily
|
||||
self.calls: list[str] = []
|
||||
self.legacy: list[str] = []
|
||||
|
||||
def try_intraday(self, code):
|
||||
self.calls.append(code)
|
||||
if self.error:
|
||||
raise self.error
|
||||
return self.chart
|
||||
|
||||
def try_daily_chart(self, code, end_date, limit=90, dataset="daily"):
|
||||
self.calls.append(f"{dataset}:{code}")
|
||||
if self.error:
|
||||
raise self.error
|
||||
return self.daily
|
||||
|
||||
def record_legacy(self, dataset, source="", error=""):
|
||||
self.legacy.append(dataset)
|
||||
|
||||
|
||||
class DatahubChartFallbackTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
EastmoneyChartClient._cache.clear()
|
||||
|
||||
def test_datahub_success_skips_old_channel(self):
|
||||
hub = FakeHub(
|
||||
{
|
||||
"entity_type": "stock",
|
||||
"identifier": "601318",
|
||||
"name": "中国平安",
|
||||
"code": "601318",
|
||||
"trade_date": "2026-09-08",
|
||||
"previous_close": 56.36,
|
||||
"points": [{"date": "2026-09-08", "time": "09:30", "close": 56.5, "average": 56.4}],
|
||||
"source": "datahub",
|
||||
}
|
||||
)
|
||||
fallback = LookbackChartClient()
|
||||
client = MarketChartClient(IfindHttpClient(), fallback, hub)
|
||||
payload = client.stock_intraday("601318")
|
||||
self.assertEqual(payload["source"], "datahub")
|
||||
self.assertEqual(hub.calls, ["601318"])
|
||||
self.assertEqual(fallback.requests, [])
|
||||
|
||||
def test_datahub_timeout_or_empty_falls_back_to_eastmoney(self):
|
||||
fallback = LookbackChartClient()
|
||||
for hub in (
|
||||
FakeHub(chart=None),
|
||||
FakeHub(error=RuntimeError("timeout")),
|
||||
FakeHub(error=RuntimeError("datahub exploded")),
|
||||
FakeHub(chart={"points": []}),
|
||||
):
|
||||
EastmoneyChartClient._cache.clear()
|
||||
fallback.requests.clear()
|
||||
client = MarketChartClient(IfindHttpClient(), fallback, hub)
|
||||
payload = client.stock_intraday("000001")
|
||||
self.assertEqual(payload["trade_date"], "2026-09-07")
|
||||
self.assertGreaterEqual(len(payload["points"]), 1)
|
||||
self.assertTrue(fallback.requests)
|
||||
|
||||
def test_datahub_daily_skips_ifind(self):
|
||||
hub = FakeHub(
|
||||
daily=[
|
||||
{
|
||||
"trade_date": "2026-09-07",
|
||||
"open": 10.0,
|
||||
"high": 10.4,
|
||||
"low": 9.9,
|
||||
"close": 10.2,
|
||||
"volume": 1000,
|
||||
"amount_billion": 0.02,
|
||||
}
|
||||
]
|
||||
)
|
||||
client = MarketChartClient(IfindHttpClient(), LookbackChartClient(), hub)
|
||||
rows = client.stock_daily("600000", "20260907")
|
||||
self.assertEqual(rows[-1]["trade_date"], "2026-09-07")
|
||||
self.assertIn("daily:600000", hub.calls)
|
||||
|
||||
|
||||
class ChartServiceStub:
|
||||
@staticmethod
|
||||
def _payload(code: str, name: str):
|
||||
|
||||
@@ -67,6 +67,9 @@ class DataGatewayTests(unittest.TestCase):
|
||||
"TushareClient": {"backend/features/market/service.py"},
|
||||
"TushareProvider": {"backend/data/gateway.py"},
|
||||
"WebRealtimeAggregator": {"backend/data/gateway.py"},
|
||||
"DatahubClient": {"backend/data/gateway.py"},
|
||||
"DatahubAwareTushareClient": {"backend/data/gateway.py"},
|
||||
"DatahubBridge": {"backend/data/gateway.py"},
|
||||
}
|
||||
found = {name: set() for name in owners}
|
||||
for path in (root / "backend").rglob("*.py"):
|
||||
|
||||
@@ -0,0 +1,620 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import json
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from backend.data import build_data_gateway
|
||||
from backend.data.datahub.bridge import DatahubAwareTushareClient, DatahubBridge, looks_like_heaven
|
||||
from backend.data.datahub.client import DatahubClient, DatahubResponse
|
||||
from backend.data.datahub.compare import compare_rows
|
||||
from backend.data.datahub.errors import DatahubError
|
||||
from backend.data.datahub.native import to_canonical_row, to_native_row
|
||||
from backend.data.datahub.route_state import LEDGER
|
||||
from backend.data.datahub.settings import DATASETS, DatahubSettings, DatasetFlags
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TOKEN = "super-secret-datahub-token"
|
||||
|
||||
LEGACY_DAILY = {
|
||||
"ts_code": "600000.SH",
|
||||
"trade_date": "20240902",
|
||||
"open": 10.11,
|
||||
"high": 10.25,
|
||||
"low": 10.01,
|
||||
"close": 10.20,
|
||||
"pct_chg": 1.2345,
|
||||
"vol": 1000.0,
|
||||
"amount": 2000.0,
|
||||
}
|
||||
HUB_DAILY = {
|
||||
"ts_code": "600000.SH",
|
||||
"trade_date": "20240902",
|
||||
"open": 10.11,
|
||||
"high": 10.25,
|
||||
"low": 10.01,
|
||||
"close": 10.20,
|
||||
"pct_chg": 1.2345,
|
||||
"volume": 100000.0,
|
||||
"amount": 2000000.0,
|
||||
}
|
||||
|
||||
|
||||
class FakeLegacy:
|
||||
def __init__(self, rows: list[dict[str, Any]] | Exception | None = None) -> None:
|
||||
self.token = "legacy-token"
|
||||
self.timeout = 30
|
||||
self.rows = [] if rows is None else rows
|
||||
self.calls: list[tuple[str, dict[str, Any] | None, str]] = []
|
||||
|
||||
def query(self, api_name: str, params: dict[str, Any] | None = None, fields: str = "") -> list[dict[str, Any]]:
|
||||
self.calls.append((api_name, params, fields))
|
||||
if isinstance(self.rows, Exception):
|
||||
raise self.rows
|
||||
return [dict(row) for row in self.rows]
|
||||
|
||||
|
||||
class FakeClient(DatahubClient):
|
||||
def __init__(self, error: DatahubError | None = None, response: DatahubResponse | None = None) -> None:
|
||||
super().__init__(DatahubSettings(base_url="http://127.0.0.1:9", token=TOKEN))
|
||||
self.error = error
|
||||
self.response = response or DatahubResponse(
|
||||
data=[dict(HUB_DAILY)],
|
||||
meta={"tier": "official", "trade_date": "20240902", "stale": False, "staleness_seconds": 0},
|
||||
)
|
||||
self.paths: list[str] = []
|
||||
self.calls: list[tuple[str, dict[str, Any]]] = []
|
||||
|
||||
def get(self, path: str, params: dict[str, Any] | None = None) -> DatahubResponse:
|
||||
self.paths.append(path)
|
||||
self.calls.append((path, {key: value for key, value in (params or {}).items()}))
|
||||
if TOKEN in json.dumps(params or {}) or TOKEN in path:
|
||||
raise AssertionError("token leaked into url")
|
||||
if self.error:
|
||||
raise self.error
|
||||
return self.response
|
||||
|
||||
|
||||
def flags(**enabled: tuple[bool, bool]) -> DatahubSettings:
|
||||
datasets = {name: DatasetFlags(name) for name in DATASETS}
|
||||
for name, pair in enabled.items():
|
||||
datasets[name] = DatasetFlags(name, read=pair[0], shadow=pair[1])
|
||||
return DatahubSettings(base_url="http://127.0.0.1:9", token=TOKEN, datasets=datasets)
|
||||
|
||||
|
||||
class DatahubBridgeTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
LEDGER.clear()
|
||||
|
||||
def test_default_config_enables_official_reads(self) -> None:
|
||||
settings = DatahubSettings.load(environ={}, credentials={})
|
||||
self.assertTrue(settings.any_enabled())
|
||||
self.assertTrue(all(settings.flags(name).read and not settings.flags(name).shadow for name in DATASETS))
|
||||
client = FakeClient()
|
||||
legacy = FakeLegacy([LEGACY_DAILY])
|
||||
wrapped = DatahubAwareTushareClient(legacy, DatahubBridge(settings, client))
|
||||
rows = wrapped.query("daily", {"trade_date": "20240902"}, "ts_code,close,vol,amount")
|
||||
self.assertEqual(rows[0]["amount"], 2000.0)
|
||||
self.assertEqual(client.paths, ["/v1/bars/daily"])
|
||||
self.assertEqual(legacy.calls, [])
|
||||
self.assertEqual(LEDGER.snapshot()[0]["route"], "datahub")
|
||||
|
||||
def test_each_dataset_has_independent_read_flag(self) -> None:
|
||||
settings = flags(daily=(True, False), auction=(False, False))
|
||||
self.assertTrue(settings.flags("daily").read)
|
||||
self.assertFalse(settings.flags("auction").read)
|
||||
self.assertFalse(any(settings.flags(name).read for name in DATASETS if name != "daily"))
|
||||
source = (ROOT / "config" / "datahub.config.json").read_text(encoding="utf-8")
|
||||
self.assertNotIn("master", source)
|
||||
self.assertNotIn("DATAHUB_READ_ALL", source)
|
||||
compose = (ROOT / "compose.yaml").read_text(encoding="utf-8")
|
||||
for env_key in (
|
||||
"CALENDAR", "STOCKS", "DAILY", "INDEX_DAILY", "VALUATION", "MONEYFLOW",
|
||||
"AUCTION", "LIMIT_EVENTS", "POPULARITY", "DRAGON_TIGER", "SECTOR_DAILY",
|
||||
"QUOTES", "INDEX_QUOTES", "INTRADAY", "STATUS",
|
||||
):
|
||||
self.assertIn(f'DATAHUB_READ_{env_key}: "1"', compose)
|
||||
|
||||
def test_read_flag_replaces_only_that_dataset_and_converts_units(self) -> None:
|
||||
shadows: list[dict[str, Any]] = []
|
||||
client = FakeClient()
|
||||
legacy = FakeLegacy([LEGACY_DAILY])
|
||||
wrapped = DatahubAwareTushareClient(
|
||||
legacy,
|
||||
DatahubBridge(flags(daily=(True, False)), client, shadow_sink=shadows.append),
|
||||
)
|
||||
rows = wrapped.query("daily", {"trade_date": "20240902"}, "ts_code,vol,amount")
|
||||
self.assertEqual(rows[0]["vol"], 1000.0)
|
||||
self.assertEqual(rows[0]["amount"], 2000.0)
|
||||
self.assertEqual(legacy.calls, [])
|
||||
self.assertEqual(client.paths, ["/v1/bars/daily"])
|
||||
calendar_legacy = FakeLegacy([{"cal_date": "20240902", "is_open": 1}])
|
||||
calendar_client = FakeClient(error=DatahubError("INTERNAL", "nope"))
|
||||
calendar_wrapped = DatahubAwareTushareClient(
|
||||
calendar_legacy,
|
||||
DatahubBridge(flags(daily=(True, False)), calendar_client),
|
||||
)
|
||||
calendar = calendar_wrapped.query("trade_cal", {"start_date": "20240902", "end_date": "20240902"}, "")
|
||||
self.assertEqual(calendar[0]["is_open"], 1)
|
||||
self.assertEqual(calendar_client.paths, [])
|
||||
|
||||
def test_fallback_on_down_401_timeout_empty_unpublished_stale_and_incomplete(self) -> None:
|
||||
cases = [
|
||||
DatahubError("UNAVAILABLE", "down"),
|
||||
DatahubError("UNAUTHORIZED", "401"),
|
||||
DatahubError("TIMEOUT", "late"),
|
||||
DatahubError("EMPTY", "no rows"),
|
||||
DatahubError("DATASET_NOT_PUBLISHED", "not ready"),
|
||||
DatahubError("STALE", "old"),
|
||||
DatahubError("INCOMPLETE", "truncated"),
|
||||
]
|
||||
for error in cases:
|
||||
with self.subTest(error=error.code):
|
||||
if error.code == "EMPTY":
|
||||
client = FakeClient(response=DatahubResponse(data=[], meta={"stale": False, "staleness_seconds": 0}))
|
||||
elif error.code == "STALE":
|
||||
client = FakeClient(response=DatahubResponse(
|
||||
data=[dict(HUB_DAILY)],
|
||||
meta={"stale": True, "staleness_seconds": 999999},
|
||||
))
|
||||
elif error.code == "INCOMPLETE":
|
||||
client = FakeClient(response=DatahubResponse(
|
||||
data=[dict(HUB_DAILY)],
|
||||
meta={
|
||||
"stale": False,
|
||||
"staleness_seconds": 0,
|
||||
"incomplete": True,
|
||||
"coverage": {"complete": False, "missing_count": 80},
|
||||
},
|
||||
))
|
||||
else:
|
||||
client = FakeClient(error=error)
|
||||
legacy = FakeLegacy([LEGACY_DAILY])
|
||||
wrapped = DatahubAwareTushareClient(legacy, DatahubBridge(flags(daily=(True, False)), client))
|
||||
rows = wrapped.query("daily", {"trade_date": "20240902"}, "ts_code,amount")
|
||||
self.assertEqual(rows[0]["amount"], 2000.0)
|
||||
self.assertEqual(len(legacy.calls), 1)
|
||||
|
||||
def test_shadow_compares_without_replacing_and_survives_hub_failure(self) -> None:
|
||||
reports: list[dict[str, Any]] = []
|
||||
client = FakeClient()
|
||||
legacy = FakeLegacy([LEGACY_DAILY])
|
||||
wrapped = DatahubAwareTushareClient(
|
||||
legacy,
|
||||
DatahubBridge(flags(daily=(False, True)), client, shadow_sink=reports.append),
|
||||
)
|
||||
rows = wrapped.query("daily", {"trade_date": "20240902"}, "ts_code,amount,vol")
|
||||
self.assertEqual(rows[0]["amount"], 2000.0)
|
||||
self.assertEqual(len(legacy.calls), 1)
|
||||
self.assertEqual(reports[0]["equal"], True)
|
||||
self.assertEqual(reports[0]["matched"], 1)
|
||||
|
||||
failed = FakeClient(error=DatahubError("UNAVAILABLE", TOKEN))
|
||||
fail_reports: list[dict[str, Any]] = []
|
||||
fail_legacy = FakeLegacy([LEGACY_DAILY])
|
||||
fail_wrapped = DatahubAwareTushareClient(
|
||||
fail_legacy,
|
||||
DatahubBridge(flags(daily=(False, True)), failed, shadow_sink=fail_reports.append),
|
||||
)
|
||||
again = fail_wrapped.query("daily", {"trade_date": "20240902"}, "amount")
|
||||
self.assertEqual(again[0]["amount"], 2000.0)
|
||||
self.assertTrue(fail_reports[0]["hub_error"])
|
||||
self.assertNotIn(TOKEN, json.dumps(fail_reports[0]))
|
||||
|
||||
def test_compare_classifies_unit_conversion_missing_row_and_value_diff(self) -> None:
|
||||
equal = compare_rows("daily", [LEGACY_DAILY], [HUB_DAILY], {"stale": False, "staleness_seconds": 0})
|
||||
self.assertTrue(equal["equal"])
|
||||
unit = compare_rows("daily", [LEGACY_DAILY], [{**HUB_DAILY, "amount": 2000.0, "volume": 1000.0}])
|
||||
self.assertGreater(unit["unit_conversion_count"], 0)
|
||||
missing = compare_rows("daily", [LEGACY_DAILY], [])
|
||||
self.assertEqual(missing["missing_hub_count"], 1)
|
||||
value = compare_rows("daily", [LEGACY_DAILY], [{**HUB_DAILY, "close": 99.0}])
|
||||
self.assertEqual(value["value_diff_count"], 1)
|
||||
skew = compare_rows("daily", [LEGACY_DAILY], [HUB_DAILY], {"stale": False, "staleness_seconds": 12})
|
||||
self.assertTrue(skew["time_skew"])
|
||||
|
||||
def test_shadow_extra_hub_columns_are_not_false_diffs_when_projected(self) -> None:
|
||||
hub_full = {**HUB_DAILY, "adj_factor": 1.1}
|
||||
legacy_close_only = {k: LEGACY_DAILY[k] for k in ("ts_code", "trade_date", "close")}
|
||||
report = compare_rows(
|
||||
"daily", [legacy_close_only], [hub_full],
|
||||
{"stale": False, "staleness_seconds": 0},
|
||||
fields="ts_code,trade_date,close",
|
||||
)
|
||||
self.assertTrue(report["equal"])
|
||||
self.assertEqual(report["value_diff_count"], 0)
|
||||
self.assertEqual(report["fields_compared"], ["close", "trade_date", "ts_code"])
|
||||
# without projection the same pair shows the historic false diff
|
||||
unprojected = compare_rows("daily", [legacy_close_only], [hub_full])
|
||||
self.assertFalse(unprojected["equal"])
|
||||
|
||||
legacy_stocks = {"ts_code": "600000.SH", "name": "浦发银行"}
|
||||
hub_stocks = {
|
||||
"ts_code": "600000.SH", "symbol": "600000", "name": "浦发银行", "area": "上海",
|
||||
"industry": "银行", "market": "主板", "list_status": "L", "list_date": "19991110",
|
||||
}
|
||||
stocks = compare_rows("stocks", [legacy_stocks], [hub_stocks], {}, fields="ts_code,name")
|
||||
self.assertTrue(stocks["equal"])
|
||||
|
||||
legacy_cal = {"cal_date": "20240902", "is_open": 1}
|
||||
hub_cal = {
|
||||
"cal_date": "20240902", "is_open": True,
|
||||
"pretrade_date": "20240830", "prev_open": "20240830",
|
||||
}
|
||||
calendar = compare_rows(
|
||||
"calendar", [legacy_cal], [hub_cal], {}, fields="cal_date,is_open"
|
||||
)
|
||||
self.assertTrue(calendar["equal"])
|
||||
|
||||
def test_shadow_projection_still_alarms_on_requested_field_problems(self) -> None:
|
||||
hub_missing_field = {k: v for k, v in HUB_DAILY.items() if k != "close"}
|
||||
legacy_close_only = {k: LEGACY_DAILY[k] for k in ("ts_code", "trade_date", "close")}
|
||||
lost = compare_rows(
|
||||
"daily", [legacy_close_only], [hub_missing_field], fields="ts_code,trade_date,close"
|
||||
)
|
||||
self.assertFalse(lost["equal"])
|
||||
self.assertEqual(lost["value_diff_count"], 1)
|
||||
|
||||
changed = compare_rows(
|
||||
"daily", [legacy_close_only], [{**HUB_DAILY, "close": 99.0}],
|
||||
fields="ts_code,trade_date,close",
|
||||
)
|
||||
self.assertFalse(changed["equal"])
|
||||
self.assertEqual(changed["value_diff_count"], 1)
|
||||
self.assertEqual(changed["value_diffs"][0]["fields"][0]["field"], "close")
|
||||
|
||||
gone = compare_rows("daily", [LEGACY_DAILY], [], fields="ts_code,trade_date,close")
|
||||
self.assertEqual(gone["missing_hub_count"], 1)
|
||||
self.assertFalse(gone["equal"])
|
||||
|
||||
unit = compare_rows(
|
||||
"daily", [LEGACY_DAILY], [{**HUB_DAILY, "amount": 2000.0, "volume": 1000.0}],
|
||||
fields="ts_code,trade_date,vol,amount",
|
||||
)
|
||||
self.assertGreater(unit["unit_conversion_count"], 0)
|
||||
self.assertFalse(unit["equal"])
|
||||
|
||||
def test_bridge_shadow_report_uses_website_request_fields(self) -> None:
|
||||
hub_full = {**HUB_DAILY, "adj_factor": 1.1}
|
||||
legacy_close_only = {k: LEGACY_DAILY[k] for k in ("ts_code", "trade_date", "close", "vol", "amount")}
|
||||
reports: list[dict[str, Any]] = []
|
||||
client = FakeClient(
|
||||
response=DatahubResponse(
|
||||
data=[hub_full],
|
||||
meta={"tier": "official", "trade_date": "20240902", "stale": False, "staleness_seconds": 0},
|
||||
)
|
||||
)
|
||||
wrapped = DatahubAwareTushareClient(
|
||||
FakeLegacy([legacy_close_only]),
|
||||
DatahubBridge(flags(daily=(False, True)), client, shadow_sink=reports.append),
|
||||
)
|
||||
rows = wrapped.query("daily", {"trade_date": "20240902"}, "ts_code,trade_date,close,vol,amount")
|
||||
self.assertEqual(rows[0]["close"], 10.20)
|
||||
self.assertEqual(rows[0]["vol"], 1000.0)
|
||||
self.assertTrue(reports[0]["equal"])
|
||||
self.assertEqual(reports[0]["matched"], 1)
|
||||
|
||||
def test_native_roundtrip_matches_known_scales(self) -> None:
|
||||
native = to_native_row("daily", HUB_DAILY)
|
||||
self.assertEqual(native["vol"], 1000.0)
|
||||
self.assertEqual(native["amount"], 2000.0)
|
||||
canonical = to_canonical_row("daily", native)
|
||||
self.assertEqual(canonical["vol"], 100000.0)
|
||||
self.assertEqual(canonical["amount"], 2000000.0)
|
||||
|
||||
def test_heaven_can_use_hub_when_dataset_flag_is_on(self) -> None:
|
||||
"""问天按数据依赖接入:已映射 API 跟随开关,不再整栈强制旧链路。"""
|
||||
self.assertTrue(looks_like_heaven("backend.features.heaven.market_context", "backend/features/heaven/market_context.py"))
|
||||
self.assertFalse(looks_like_heaven("backend.features.market.service", "backend/features/market/service.py"))
|
||||
client = FakeClient()
|
||||
legacy = FakeLegacy([LEGACY_DAILY])
|
||||
wrapped = DatahubAwareTushareClient(
|
||||
legacy,
|
||||
DatahubBridge(flags(daily=(True, False)), client, heaven_guard=lambda: True),
|
||||
)
|
||||
rows = wrapped.query("daily", {"trade_date": "20240902"}, "amount")
|
||||
self.assertEqual(rows[0]["amount"], 2000.0)
|
||||
self.assertEqual(client.paths, ["/v1/bars/daily"])
|
||||
self.assertEqual(legacy.calls, [])
|
||||
|
||||
def test_status_flag_does_not_run_when_off_and_falls_back_when_on(self) -> None:
|
||||
off = DatahubBridge(flags(), FakeClient(error=DatahubError("UNAVAILABLE", "down")))
|
||||
self.assertIsNone(off.dataset_status("20240902"))
|
||||
reports: list[dict[str, Any]] = []
|
||||
failed = DatahubBridge(
|
||||
flags(status=(True, True)),
|
||||
FakeClient(error=DatahubError("UNAUTHORIZED", "nope")),
|
||||
shadow_sink=reports.append,
|
||||
)
|
||||
self.assertIsNone(failed.dataset_status("20240902"))
|
||||
self.assertTrue(reports[0]["hub_error"])
|
||||
ok = DatahubBridge(
|
||||
flags(status=(True, False)),
|
||||
FakeClient(response=DatahubResponse(data=[{"dataset": "daily", "state": "published"}], meta={"stale": False, "staleness_seconds": 0})),
|
||||
)
|
||||
self.assertEqual(ok.dataset_status("20240902")[0]["state"], "published")
|
||||
|
||||
def test_default_gateway_wraps_tushare_without_calling_datahub(self) -> None:
|
||||
gateway = build_data_gateway({}, datahub_settings=flags())
|
||||
client = gateway.tushare()
|
||||
self.assertIsInstance(client, DatahubAwareTushareClient)
|
||||
self.assertFalse(gateway.datahub.settings.any_enabled())
|
||||
|
||||
def test_stock_detail_range_query_is_not_silently_accepted_when_incomplete(self) -> None:
|
||||
source = (ROOT / "backend" / "data" / "providers" / "tushare_stocks.py").read_text(encoding="utf-8")
|
||||
self.assertIn('"daily"', source)
|
||||
self.assertIn("start_date", source)
|
||||
self.assertIn("end_date", source)
|
||||
client = FakeClient(
|
||||
response=DatahubResponse(
|
||||
data=[dict(HUB_DAILY)],
|
||||
meta={"stale": False, "staleness_seconds": 0, "incomplete": True, "coverage": {"complete": False, "missing_count": 89}},
|
||||
)
|
||||
)
|
||||
legacy = FakeLegacy([LEGACY_DAILY])
|
||||
wrapped = DatahubAwareTushareClient(legacy, DatahubBridge(flags(daily=(True, False)), client))
|
||||
rows = wrapped.query(
|
||||
"daily",
|
||||
{"ts_code": "600000.SH", "start_date": "20240301", "end_date": "20240902"},
|
||||
"ts_code,amount",
|
||||
)
|
||||
self.assertEqual(rows[0]["amount"], 2000.0)
|
||||
self.assertEqual(len(legacy.calls), 1)
|
||||
|
||||
def test_try_intraday_respects_switch_and_falls_back_on_bad_payload(self) -> None:
|
||||
closed = DatahubBridge(flags(), FakeClient(error=DatahubError("INTERNAL", "should not run")))
|
||||
self.assertIsNone(closed.try_intraday("601318"))
|
||||
|
||||
empty = DatahubBridge(
|
||||
flags(intraday=(True, False)),
|
||||
FakeClient(response=DatahubResponse(data={"points": []}, meta={"stale": False})),
|
||||
)
|
||||
self.assertIsNone(empty.try_intraday("601318"))
|
||||
|
||||
stale = DatahubBridge(
|
||||
flags(intraday=(True, False)),
|
||||
FakeClient(response=DatahubResponse(
|
||||
data={
|
||||
"entity_type": "stock",
|
||||
"code": "601318",
|
||||
"trade_date": "2026-09-07",
|
||||
"previous_close": 55.8,
|
||||
"points": [{"date": "2026-09-07", "time": "09:30", "close": 55.9, "avg_price": 55.85}],
|
||||
},
|
||||
meta={"stale": True},
|
||||
)),
|
||||
)
|
||||
self.assertIsNone(stale.try_intraday("601318"))
|
||||
|
||||
ok = DatahubBridge(
|
||||
flags(intraday=(True, False)),
|
||||
FakeClient(response=DatahubResponse(
|
||||
data={
|
||||
"entity_type": "stock",
|
||||
"identifier": "601318",
|
||||
"name": "中国平安",
|
||||
"code": "601318",
|
||||
"trade_date": "2026-09-08",
|
||||
"previous_close": 56.36,
|
||||
"points": [
|
||||
{"date": "2026-09-08", "time": "09:30", "close": 0},
|
||||
{"date": "2026-09-08", "time": "09:31", "close": 56.5, "avg_price": 56.4},
|
||||
],
|
||||
},
|
||||
meta={"stale": False},
|
||||
)),
|
||||
)
|
||||
chart = ok.try_intraday("601318")
|
||||
self.assertEqual(chart["source"], "datahub")
|
||||
self.assertEqual(len(chart["points"]), 1)
|
||||
self.assertEqual(chart["points"][0]["average"], 56.4)
|
||||
self.assertEqual(ok.client.paths, ["/v1/intraday/points"])
|
||||
self.assertEqual(ok.client.calls, [("/v1/intraday/points", {"code": "601318"})])
|
||||
self.assertNotIn("date", ok.client.calls[0][1])
|
||||
|
||||
timeout = DatahubBridge(
|
||||
flags(intraday=(True, False)),
|
||||
FakeClient(error=DatahubError("TIMEOUT", "datahub request timed out")),
|
||||
)
|
||||
self.assertIsNone(timeout.try_intraday("601318"))
|
||||
broken = DatahubBridge(
|
||||
flags(intraday=(True, False)),
|
||||
FakeClient(error=DatahubError("INTERNAL", "datahub exploded")),
|
||||
)
|
||||
self.assertIsNone(broken.try_intraday("601318"))
|
||||
self.assertTrue(DatahubSettings.load(environ={}, credentials={}).flags("intraday").read)
|
||||
|
||||
def test_try_market_quotes_and_visible_fallback(self) -> None:
|
||||
quotes = [
|
||||
{
|
||||
"ts_code": f"{600000 + index:06d}.SH",
|
||||
"name": f"股票{index}",
|
||||
"close": 10.2,
|
||||
"pre_close": 10.0,
|
||||
"open": 10.1,
|
||||
"high": 10.3,
|
||||
"low": 9.9,
|
||||
"vol": 1000,
|
||||
"amount": 2000000,
|
||||
"quote_date": "20240902",
|
||||
}
|
||||
for index in range(220)
|
||||
]
|
||||
ok = DatahubBridge(
|
||||
flags(quotes=(True, False)),
|
||||
FakeClient(
|
||||
response=DatahubResponse(
|
||||
data=quotes,
|
||||
meta={"stale": False, "staleness_seconds": 0, "source": "eastmoney:clist"},
|
||||
)
|
||||
),
|
||||
)
|
||||
rows = ok.try_market_quotes("20240902")
|
||||
self.assertEqual(len(rows), 220)
|
||||
self.assertEqual(rows[0]["pre_close"], 10.0)
|
||||
self.assertEqual(ok.client.paths, ["/v1/quotes/latest"])
|
||||
self.assertEqual(LEDGER.snapshot()[0]["route"], "datahub")
|
||||
|
||||
failed = DatahubBridge(
|
||||
flags(quotes=(True, False)),
|
||||
FakeClient(error=DatahubError("UNAVAILABLE", "down")),
|
||||
)
|
||||
self.assertIsNone(failed.try_market_quotes("20240902"))
|
||||
failed.record_legacy("quotes", "tencent_qt", "down")
|
||||
snap = next(item for item in LEDGER.snapshot() if item["dataset"] == "quotes")
|
||||
self.assertEqual(snap["route"], "legacy")
|
||||
self.assertEqual(snap["source"], "tencent_qt")
|
||||
self.assertIn("备用", "备用")
|
||||
|
||||
gateway = build_data_gateway({}, datahub_settings=flags(quotes=(True, False)))
|
||||
status = gateway.datahub_status()
|
||||
self.assertEqual(status["enabled_reads"], 1)
|
||||
self.assertEqual(status["total_reads"], len(DATASETS))
|
||||
self.assertGreaterEqual(status["fallback_count"], 1)
|
||||
|
||||
def test_try_daily_chart_converts_hub_bars(self) -> None:
|
||||
rows = [
|
||||
{
|
||||
"ts_code": "600000.SH",
|
||||
"trade_date": "20240901",
|
||||
"open": 10.0,
|
||||
"high": 10.4,
|
||||
"low": 9.9,
|
||||
"close": 10.2,
|
||||
"volume": 100000,
|
||||
"amount": 2000000,
|
||||
},
|
||||
{
|
||||
"ts_code": "600000.SH",
|
||||
"trade_date": "20240902",
|
||||
"open": 10.2,
|
||||
"high": 10.5,
|
||||
"low": 10.1,
|
||||
"close": 10.4,
|
||||
"volume": 120000,
|
||||
"amount": 2400000,
|
||||
},
|
||||
]
|
||||
hub = DatahubBridge(
|
||||
flags(daily=(True, False)),
|
||||
FakeClient(
|
||||
response=DatahubResponse(
|
||||
data=rows,
|
||||
meta={"stale": False, "staleness_seconds": 0, "source": "tushare:daily"},
|
||||
)
|
||||
),
|
||||
)
|
||||
chart = hub.try_daily_chart("600000.SH", "20240902", 90, "daily")
|
||||
self.assertEqual(chart[-1]["trade_date"], "2024-09-02")
|
||||
self.assertEqual(chart[-1]["close"], 10.4)
|
||||
self.assertAlmostEqual(chart[-1]["amount_billion"], 0.024)
|
||||
|
||||
def test_try_daily_chart_keeps_usable_bars_when_coverage_incomplete(self) -> None:
|
||||
rows = [
|
||||
{
|
||||
"ts_code": "000001.SZ",
|
||||
"trade_date": "20240901",
|
||||
"open": 10.0,
|
||||
"high": 10.4,
|
||||
"low": 9.9,
|
||||
"close": 10.2,
|
||||
"volume": 100000,
|
||||
"amount": 2000000,
|
||||
},
|
||||
{
|
||||
"ts_code": "000001.SZ",
|
||||
"trade_date": "20240902",
|
||||
"open": 10.2,
|
||||
"high": 10.5,
|
||||
"low": 10.1,
|
||||
"close": 10.4,
|
||||
"volume": 120000,
|
||||
"amount": 2400000,
|
||||
},
|
||||
]
|
||||
hub = DatahubBridge(
|
||||
flags(daily=(True, False)),
|
||||
FakeClient(
|
||||
response=DatahubResponse(
|
||||
data=rows,
|
||||
meta={
|
||||
"stale": False,
|
||||
"staleness_seconds": 0,
|
||||
"incomplete": True,
|
||||
"coverage": {"complete": False, "missing_count": 127},
|
||||
"source": "tushare:daily",
|
||||
},
|
||||
)
|
||||
),
|
||||
)
|
||||
chart = hub.try_daily_chart("000001.SZ", "20240902", 90, "daily")
|
||||
self.assertIsNotNone(chart)
|
||||
self.assertEqual(chart[-1]["trade_date"], "2024-09-02")
|
||||
self.assertEqual(chart[-1]["close"], 10.4)
|
||||
|
||||
def test_gateway_tushare_assembly_binds_hooks_on_inner_client(self) -> None:
|
||||
quotes = [
|
||||
{
|
||||
"ts_code": f"{index:06d}.SZ",
|
||||
"name": f"S{index}",
|
||||
"pre_close": 10.0,
|
||||
"open": 10.0,
|
||||
"high": 10.5,
|
||||
"low": 9.8,
|
||||
"close": 10.2,
|
||||
"vol": 100.0,
|
||||
"amount": 1000.0,
|
||||
"quote_date": "20240902",
|
||||
}
|
||||
for index in range(1, 221)
|
||||
]
|
||||
hub_client = FakeClient(
|
||||
response=DatahubResponse(
|
||||
data=quotes,
|
||||
meta={"stale": False, "staleness_seconds": 0, "source": "eastmoney_clist"},
|
||||
)
|
||||
)
|
||||
gateway = build_data_gateway(
|
||||
{"tushare_token": "tok"},
|
||||
datahub_settings=flags(quotes=(True, False), daily=(True, False)),
|
||||
)
|
||||
gateway.datahub.client = hub_client
|
||||
wrapped = gateway.tushare()
|
||||
inner = wrapped._legacy
|
||||
self.assertTrue(callable(getattr(inner, "try_market_quotes", None)))
|
||||
self.assertTrue(callable(getattr(inner, "try_index_quotes", None)))
|
||||
self.assertTrue(callable(getattr(inner, "record_datahub_legacy", None)))
|
||||
self.assertIs(inner.query.__self__, wrapped)
|
||||
self.assertEqual(inner.query.__func__, wrapped.query.__func__)
|
||||
self.assertFalse(hasattr(type(inner), "try_market_quotes"))
|
||||
rows = inner.try_market_quotes("20240902")
|
||||
self.assertGreaterEqual(len(rows or []), 200)
|
||||
self.assertIn("/v1/quotes/latest", hub_client.paths)
|
||||
hub_client.response = DatahubResponse(
|
||||
data=[dict(HUB_DAILY)],
|
||||
meta={"stale": False, "staleness_seconds": 0, "source": "tushare:daily"},
|
||||
)
|
||||
daily = inner.query("daily", {"trade_date": "20240902"}, "ts_code,amount")
|
||||
self.assertEqual(daily[0]["amount"], 2000.0)
|
||||
self.assertIn("/v1/bars/daily", hub_client.paths)
|
||||
|
||||
def test_features_do_not_import_datahub_client(self) -> None:
|
||||
violations = []
|
||||
for path in (ROOT / "backend" / "features").rglob("*.py"):
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||||
for node in ast.walk(tree):
|
||||
names = []
|
||||
if isinstance(node, ast.Import):
|
||||
names = [alias.name for alias in node.names]
|
||||
elif isinstance(node, ast.ImportFrom) and node.module:
|
||||
names = [node.module]
|
||||
for name in names:
|
||||
if "datahub" in name.split("."):
|
||||
violations.append(f"{path.relative_to(ROOT)} -> {name}")
|
||||
self.assertEqual(violations, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,185 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from backend.data.datahub.client import DatahubClient
|
||||
from backend.data.datahub.errors import DatahubError
|
||||
from backend.data.datahub.redact import redact_text
|
||||
from backend.data.datahub.settings import DatahubSettings
|
||||
|
||||
|
||||
TOKEN = "super-secret-datahub-token"
|
||||
|
||||
|
||||
class FakeHubState:
|
||||
def __init__(self) -> None:
|
||||
self.mode = "ok"
|
||||
self.hits = 0
|
||||
self.paths: list[str] = []
|
||||
|
||||
|
||||
STATE = FakeHubState()
|
||||
|
||||
|
||||
class FakeHubHandler(BaseHTTPRequestHandler):
|
||||
def log_message(self, format: str, *args: object) -> None:
|
||||
return
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
STATE.hits += 1
|
||||
parsed = urlparse(self.path)
|
||||
STATE.paths.append(parsed.path)
|
||||
token = self.headers.get("X-Datahub-Token", "")
|
||||
if STATE.mode == "timeout":
|
||||
raise TimeoutError("simulated timeout")
|
||||
if token != TOKEN:
|
||||
self._json(401, {"error": {"code": "UNAUTHORIZED", "message": "missing or invalid X-Datahub-Token"}})
|
||||
return
|
||||
if STATE.mode == "unpublished":
|
||||
self._json(404, {"error": {"code": "DATASET_NOT_PUBLISHED", "message": "daily 19990101 尚未发布", "expected_at": "15:05+08:00"}})
|
||||
return
|
||||
if STATE.mode == "empty":
|
||||
self._json(200, {"schema_version": 1, "data": [], "meta": {"tier": "official", "stale": False, "staleness_seconds": 0}})
|
||||
return
|
||||
if STATE.mode == "stale":
|
||||
self._json(200, {"schema_version": 1, "data": [{"ts_code": "600000.SH", "trade_date": "20240902", "close": 10.2, "volume": 100000, "amount": 2000000}], "meta": {"tier": "official", "stale": True, "staleness_seconds": 999999}})
|
||||
return
|
||||
if STATE.mode == "invalid":
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.end_headers()
|
||||
self.wfile.write(b"not-json")
|
||||
return
|
||||
if parsed.path == "/v1/health":
|
||||
self._json(200, {"schema_version": 1, "data": {"status": "ok"}, "meta": {"tier": "official", "source": "datahub", "stale": False, "staleness_seconds": 0}})
|
||||
return
|
||||
if parsed.path == "/v1/calendar":
|
||||
self._json(200, {"schema_version": 1, "data": [{"cal_date": "20240902", "is_open": True, "pretrade_date": "20240830"}], "meta": {"tier": "official", "trade_date": "20240902", "stale": False, "staleness_seconds": 0}})
|
||||
return
|
||||
if parsed.path == "/v1/bars/daily":
|
||||
query = {key: values[-1] for key, values in parse_qs(parsed.query).items()}
|
||||
self._json(200, {
|
||||
"schema_version": 1,
|
||||
"data": [{
|
||||
"ts_code": "600000.SH",
|
||||
"trade_date": query.get("date") or "20240902",
|
||||
"open": 10.11, "high": 10.25, "low": 10.01, "close": 10.20,
|
||||
"pct_chg": 1.2345, "volume": 100000.0, "amount": 2000000.0, "adj_factor": 1.1,
|
||||
}],
|
||||
"meta": {"tier": "official", "trade_date": "20240902", "stale": False, "staleness_seconds": 0, "source": "tushare:daily"},
|
||||
})
|
||||
return
|
||||
if parsed.path == "/v1/datasets/status":
|
||||
self._json(200, {"schema_version": 1, "data": [{"dataset": "daily", "state": "published", "trade_date": "20240902"}], "meta": {"tier": "official", "stale": False, "staleness_seconds": 0}})
|
||||
return
|
||||
self._json(400, {"error": {"code": "INVALID_ARGUMENT", "message": f"unknown endpoint: {parsed.path}"}})
|
||||
|
||||
def _json(self, status: int, payload: dict) -> None:
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
class DatahubClientTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.server = ThreadingHTTPServer(("127.0.0.1", 0), FakeHubHandler)
|
||||
cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.base = f"http://127.0.0.1:{cls.server.server_address[1]}"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.server.shutdown()
|
||||
cls.server.server_close()
|
||||
|
||||
def setUp(self) -> None:
|
||||
STATE.mode = "ok"
|
||||
STATE.hits = 0
|
||||
STATE.paths = []
|
||||
self.client = DatahubClient(DatahubSettings(base_url=self.base, token=TOKEN, retries=1, timeout_seconds=2))
|
||||
|
||||
def test_health_envelope(self) -> None:
|
||||
response = self.client.health()
|
||||
self.assertEqual(response.schema_version, 1)
|
||||
self.assertEqual(response.data["status"], "ok")
|
||||
self.assertIn("stale", response.meta)
|
||||
|
||||
def test_missing_and_bad_token_401(self) -> None:
|
||||
missing = DatahubClient(DatahubSettings(base_url=self.base, token=""))
|
||||
with self.assertRaises(DatahubError) as raised:
|
||||
missing.health()
|
||||
self.assertEqual(raised.exception.code, "NOT_CONFIGURED")
|
||||
bad = DatahubClient(DatahubSettings(base_url=self.base, token="wrong"))
|
||||
with self.assertRaises(DatahubError) as raised:
|
||||
bad.health()
|
||||
self.assertEqual(raised.exception.code, "UNAUTHORIZED")
|
||||
self.assertNotIn(TOKEN, str(raised.exception))
|
||||
|
||||
def test_unpublished_and_empty_and_stale_codes(self) -> None:
|
||||
STATE.mode = "unpublished"
|
||||
with self.assertRaises(DatahubError) as raised:
|
||||
self.client.daily_bars(date="19990101")
|
||||
self.assertEqual(raised.exception.code, "DATASET_NOT_PUBLISHED")
|
||||
STATE.mode = "empty"
|
||||
response = self.client.daily_bars(date="20240902")
|
||||
self.assertEqual(response.data, [])
|
||||
STATE.mode = "stale"
|
||||
stale = self.client.daily_bars(date="20240902")
|
||||
self.assertTrue(stale.meta["stale"])
|
||||
|
||||
def test_invalid_json_maps_to_internal(self) -> None:
|
||||
STATE.mode = "invalid"
|
||||
with self.assertRaises(DatahubError) as raised:
|
||||
self.client.health()
|
||||
self.assertEqual(raised.exception.code, "INTERNAL")
|
||||
|
||||
def test_timeout_maps_and_retries(self) -> None:
|
||||
hits = {"n": 0}
|
||||
|
||||
def boom(_request, timeout=None):
|
||||
hits["n"] += 1
|
||||
raise TimeoutError("late")
|
||||
|
||||
client = DatahubClient(
|
||||
DatahubSettings(base_url=self.base, token=TOKEN, retries=1, timeout_seconds=1),
|
||||
urlopen=boom,
|
||||
)
|
||||
with self.assertRaises(DatahubError) as raised:
|
||||
client.health()
|
||||
self.assertEqual(raised.exception.code, "TIMEOUT")
|
||||
self.assertEqual(hits["n"], 2)
|
||||
|
||||
def test_token_never_appears_in_error_text_or_logs(self) -> None:
|
||||
stream = io.StringIO()
|
||||
logger = logging.getLogger("xiaobai.datahub")
|
||||
handler = logging.StreamHandler(stream)
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
try:
|
||||
with self.assertRaises(DatahubError):
|
||||
DatahubClient(DatahubSettings(base_url=self.base, token="wrong")).health()
|
||||
blob = stream.getvalue() + redact_text("header " + TOKEN, (TOKEN,))
|
||||
self.assertNotIn(TOKEN, blob)
|
||||
self.assertIn("***", redact_text(TOKEN, (TOKEN,)))
|
||||
finally:
|
||||
logger.removeHandler(handler)
|
||||
|
||||
def test_calendar_and_status_contract(self) -> None:
|
||||
calendar = self.client.calendar("20240901", "20240902")
|
||||
self.assertEqual(calendar.data[0]["cal_date"], "20240902")
|
||||
status = self.client.dataset_status("20240902")
|
||||
self.assertEqual(status.data[0]["dataset"], "daily")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -3,9 +3,10 @@ from __future__ import annotations
|
||||
import http.client
|
||||
import json
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from backend.data.realtime import WebRealtimeAggregator
|
||||
from backend.data.realtime import RealtimeAggregateError, WebRealtimeAggregator
|
||||
from backend.features.heaven.engine import _market_line_scores, build_manual_market_hexagram
|
||||
from server import DashboardService
|
||||
from backend.data.providers.tushare_client import (
|
||||
@@ -377,6 +378,87 @@ class RealtimeAggregatorTests(unittest.TestCase):
|
||||
self.assertEqual(rows[0]["quote_time"][:10], "2026-07-20")
|
||||
self.assertAlmostEqual(rows[0]["amount_billion"], 12946.52)
|
||||
|
||||
@patch.object(WebRealtimeAggregator, "_get_json")
|
||||
def test_eastmoney_market_quotes_normalize_and_keep_expected_date(self, get_json: MagicMock):
|
||||
epoch = datetime(2026, 7, 20, 10, 5).timestamp()
|
||||
rows = []
|
||||
for index in range(200):
|
||||
sz = index < 100
|
||||
rows.append(
|
||||
{
|
||||
"f12": f"{index:06d}" if sz else f"{600000 + index - 100:06d}",
|
||||
"f13": 0 if sz else 1,
|
||||
"f14": f"股票{index}",
|
||||
"f2": 11.2,
|
||||
"f3": 2.0,
|
||||
"f5": 10,
|
||||
"f6": 50000000,
|
||||
"f15": 11.3,
|
||||
"f16": 11.0,
|
||||
"f17": 11.1,
|
||||
"f18": 11.0,
|
||||
"f124": epoch,
|
||||
}
|
||||
)
|
||||
def fake_get_json(_url, params, referer=""):
|
||||
page = int(params.get("pn") or 1)
|
||||
start = (page - 1) * 100
|
||||
return {"rc": 0, "data": {"total": 200, "diff": rows[start:start + 100]}}
|
||||
|
||||
get_json.side_effect = fake_get_json
|
||||
aggregator = WebRealtimeAggregator()
|
||||
aggregator._response_cache.clear()
|
||||
quotes = aggregator.eastmoney_market_quotes("20260720")
|
||||
self.assertEqual(len(quotes), 200)
|
||||
self.assertEqual(quotes[0]["ts_code"], "000000.SZ")
|
||||
self.assertTrue(quotes[100]["ts_code"].endswith(".SH"))
|
||||
self.assertEqual(quotes[0]["vol"], 1000)
|
||||
self.assertEqual(quotes[0]["quote_date"], "20260720")
|
||||
|
||||
@patch.object(WebRealtimeAggregator, "_get_text")
|
||||
def test_tencent_stock_quote_keeps_expected_date(self, get_text: MagicMock):
|
||||
fields = [""] * 38
|
||||
fields[1] = "浦发银行"
|
||||
fields[2] = "600000"
|
||||
fields[3] = "11.20"
|
||||
fields[4] = "11.00"
|
||||
fields[5] = "11.10"
|
||||
fields[6] = "1234"
|
||||
fields[30] = "20260720103000"
|
||||
fields[33] = "11.30"
|
||||
fields[34] = "11.00"
|
||||
fields[37] = "1380"
|
||||
get_text.return_value = (f'v_sh600000="{"~".join(fields)}";', 0)
|
||||
|
||||
quote = WebRealtimeAggregator().tencent_stock_quote("600000", "20260720")
|
||||
|
||||
self.assertEqual(quote["ts_code"], "600000.SH")
|
||||
self.assertEqual(quote["quote_date"], "20260720")
|
||||
self.assertEqual(quote["vol"], 123400)
|
||||
self.assertAlmostEqual(quote["amount"], 13_800_000)
|
||||
|
||||
@patch.object(WebRealtimeAggregator, "_get_json")
|
||||
def test_eastmoney_stock_quote_rejects_stale_date(self, get_json: MagicMock):
|
||||
epoch = datetime(2026, 7, 19, 15, 0).timestamp()
|
||||
get_json.return_value = {
|
||||
"rc": 0,
|
||||
"data": {
|
||||
"f43": 11.2,
|
||||
"f44": 11.3,
|
||||
"f45": 11.0,
|
||||
"f46": 11.1,
|
||||
"f47": 10,
|
||||
"f48": 50000000,
|
||||
"f57": "300750",
|
||||
"f58": "宁德时代",
|
||||
"f60": 11.0,
|
||||
"f86": epoch,
|
||||
},
|
||||
}
|
||||
|
||||
with self.assertRaises(RealtimeAggregateError):
|
||||
WebRealtimeAggregator().eastmoney_stock_quote("300750.SZ", "20260720")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -138,7 +138,7 @@ class HttpDispatchContractTests(unittest.TestCase):
|
||||
self.assertTrue(claimed.isdisjoint(methods))
|
||||
claimed.update(methods)
|
||||
self.assertLessEqual(len(path.read_text(encoding="utf-8").splitlines()), line_limit)
|
||||
self.assertEqual(len(claimed), 27)
|
||||
self.assertEqual(len(claimed), 28)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from backend.data.providers.tushare_client import TushareClient
|
||||
from backend.data.providers.tushare_helpers import calendar_is_open
|
||||
from backend.data.providers.tushare_transport import TushareError
|
||||
from backend.data.realtime import (
|
||||
RealtimeAggregateError,
|
||||
_normalize_eastmoney_quote,
|
||||
_parse_tencent_stock_quote,
|
||||
)
|
||||
|
||||
|
||||
class FakeRealtimeClient(TushareClient):
|
||||
@@ -81,6 +89,65 @@ class FakeRealtimeClient(TushareClient):
|
||||
raise AssertionError(f"Unexpected API call: {api_name} {params}")
|
||||
|
||||
|
||||
FREE_QUOTES = [
|
||||
{
|
||||
"ts_code": "000001.SZ", "name": "甲", "pre_close": 10.0,
|
||||
"open": 10.1, "high": 11.0, "low": 10.0, "close": 11.0,
|
||||
"vol": 1000, "amount": 100000000, "num": 10,
|
||||
"quote_date": "20260720",
|
||||
},
|
||||
{
|
||||
"ts_code": "000002.SZ", "name": "乙", "pre_close": 20.0,
|
||||
"open": 19.5, "high": 20.0, "low": 18.0, "close": 18.0,
|
||||
"vol": 2000, "amount": 200000000, "num": 20,
|
||||
"quote_date": "20260720",
|
||||
},
|
||||
{
|
||||
"ts_code": "000003.SZ", "name": "丙", "pre_close": 30.0,
|
||||
"open": 31.0, "high": 33.0, "low": 30.0, "close": 32.0,
|
||||
"vol": 3000, "amount": 300000000, "num": 30,
|
||||
"quote_date": "20260720",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
class FakeFreeAggregator:
|
||||
def __init__(self, quotes=None, fail=False):
|
||||
self.quotes = list(quotes if quotes is not None else FREE_QUOTES)
|
||||
self.fail = fail
|
||||
self.calls = 0
|
||||
|
||||
def eastmoney_market_quotes(self, expected_date=""):
|
||||
self.calls += 1
|
||||
if self.fail:
|
||||
raise RealtimeAggregateError("eastmoney down")
|
||||
if expected_date and self.quotes:
|
||||
dated = [
|
||||
row for row in self.quotes
|
||||
if str(row.get("quote_date") or "") == str(expected_date).replace("-", "")
|
||||
]
|
||||
if dated:
|
||||
return dated
|
||||
return list(self.quotes)
|
||||
|
||||
def tencent_market_quotes(self, codes, expected_date=""):
|
||||
return self.eastmoney_market_quotes(expected_date)
|
||||
|
||||
def eastmoney_indices(self):
|
||||
return [
|
||||
{
|
||||
"code": "000001",
|
||||
"name": "上证指数",
|
||||
"price": 3800.12,
|
||||
"change": 0.85,
|
||||
"previous_close": 3768.0,
|
||||
"amount_billion": 4200.5,
|
||||
"quote_time": "2026-07-20T10:05:00+08:00",
|
||||
"source": "eastmoney_push2",
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
class RealtimeDashboardTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
TushareClient._realtime_reference_cache.clear()
|
||||
@@ -130,6 +197,272 @@ class RealtimeDashboardTests(unittest.TestCase):
|
||||
self.assertEqual(dashboard["meta"]["limit_data_source"], "derived")
|
||||
self.assertIn("日线数据推算", dashboard["meta"]["notice"])
|
||||
|
||||
def test_calendar_open_flag_accepts_string_and_bool(self):
|
||||
self.assertTrue(calendar_is_open(1))
|
||||
self.assertTrue(calendar_is_open("1"))
|
||||
self.assertTrue(calendar_is_open(True))
|
||||
self.assertFalse(calendar_is_open(0))
|
||||
self.assertFalse(calendar_is_open("0"))
|
||||
self.assertFalse(calendar_is_open(False))
|
||||
|
||||
original_query = self.client.query
|
||||
|
||||
def query(api_name, params=None, fields=""):
|
||||
if api_name == "trade_cal":
|
||||
return [
|
||||
{
|
||||
"cal_date": params.get("start_date"),
|
||||
"is_open": "1",
|
||||
"pretrade_date": "20260907",
|
||||
}
|
||||
]
|
||||
return original_query(api_name, params, fields)
|
||||
|
||||
self.client.query = query
|
||||
trade_date, previous = self.client.resolve_trade_context("20260908")
|
||||
self.assertEqual(trade_date, "20260908")
|
||||
self.assertEqual(previous, "20260907")
|
||||
|
||||
def test_session_clock_uses_realtime_until_official_window(self):
|
||||
today = "20260908"
|
||||
self.client.clock = lambda: datetime(
|
||||
2026, 9, 8, 10, 5, tzinfo=timezone(timedelta(hours=8))
|
||||
)
|
||||
self.assertTrue(self.client.should_use_realtime(today, today))
|
||||
self.client.clock = lambda: datetime(
|
||||
2026, 9, 8, 16, 10, tzinfo=timezone(timedelta(hours=8))
|
||||
)
|
||||
self.assertFalse(self.client.should_use_realtime(today, today))
|
||||
|
||||
def test_realtime_dashboard_survives_missing_limit_table(self):
|
||||
original_query = self.client.query
|
||||
|
||||
def query(api_name, params=None, fields=""):
|
||||
if api_name == "stk_limit":
|
||||
return []
|
||||
return original_query(api_name, params, fields)
|
||||
|
||||
self.client.query = query
|
||||
TushareClient._realtime_reference_cache.clear()
|
||||
dashboard = self.client._realtime_dashboard("20260720", "20260720", "20260717")
|
||||
self.assertTrue(dashboard["meta"]["realtime"])
|
||||
self.assertEqual(dashboard["meta"]["quote_count"], 3)
|
||||
self.assertEqual(dashboard["overview"]["limit_up_count"], 0)
|
||||
|
||||
def test_rt_k_permission_error_falls_back_to_free_quotes(self):
|
||||
original_query = self.client.query
|
||||
|
||||
def query(api_name, params=None, fields=""):
|
||||
if api_name == "rt_k":
|
||||
raise TushareError("没有接口访问权限")
|
||||
return original_query(api_name, params, fields)
|
||||
|
||||
self.client.query = query
|
||||
self.client.realtime_aggregator = FakeFreeAggregator()
|
||||
TushareClient._realtime_reference_cache.clear()
|
||||
dashboard = self.client._realtime_dashboard("20260720", "20260720", "20260717")
|
||||
|
||||
self.assertTrue(dashboard["meta"]["realtime"])
|
||||
self.assertEqual(dashboard["meta"]["quote_source"], "eastmoney_clist")
|
||||
self.assertEqual(dashboard["meta"]["trade_date"], "2026-07-20")
|
||||
self.assertEqual(dashboard["meta"]["quote_count"], 3)
|
||||
self.assertEqual(dashboard["overview"]["limit_up_count"], 1)
|
||||
self.assertEqual(dashboard["overview"]["limit_down_count"], 1)
|
||||
self.assertEqual(dashboard["overview"]["amount_billion"], 6.0)
|
||||
self.assertIn("东财免费实时", dashboard["meta"]["notice"])
|
||||
self.assertEqual(dashboard["meta"]["indices"][0]["price"], 3800.12)
|
||||
|
||||
def test_rt_k_empty_result_falls_back_to_free_quotes(self):
|
||||
original_query = self.client.query
|
||||
|
||||
def query(api_name, params=None, fields=""):
|
||||
if api_name == "rt_k":
|
||||
return []
|
||||
return original_query(api_name, params, fields)
|
||||
|
||||
self.client.query = query
|
||||
self.client.realtime_aggregator = FakeFreeAggregator()
|
||||
TushareClient._realtime_reference_cache.clear()
|
||||
dashboard = self.client._realtime_dashboard("20260720", "20260720", "20260717")
|
||||
self.assertEqual(dashboard["meta"]["quote_source"], "eastmoney_clist")
|
||||
self.assertEqual(str(dashboard["meta"]["trade_date"]).replace("-", ""), "20260720")
|
||||
|
||||
def test_rt_k_and_free_source_failure_keeps_today_error(self):
|
||||
original_query = self.client.query
|
||||
|
||||
def query(api_name, params=None, fields=""):
|
||||
if api_name == "rt_k":
|
||||
raise TushareError("没有接口访问权限")
|
||||
return original_query(api_name, params, fields)
|
||||
|
||||
self.client.query = query
|
||||
self.client.realtime_aggregator = FakeFreeAggregator(fail=True)
|
||||
TushareClient._realtime_reference_cache.clear()
|
||||
with self.assertRaises(TushareError) as ctx:
|
||||
self.client._realtime_dashboard("20260720", "20260720", "20260717")
|
||||
self.assertIn("当天盘中实时行情不可用", str(ctx.exception))
|
||||
self.assertIn("没有接口访问权限", str(ctx.exception))
|
||||
|
||||
def test_rt_k_and_eastmoney_failure_falls_back_to_tencent(self):
|
||||
original_query = self.client.query
|
||||
|
||||
def query(api_name, params=None, fields=""):
|
||||
if api_name == "rt_k":
|
||||
raise TushareError("没有接口访问权限")
|
||||
return original_query(api_name, params, fields)
|
||||
|
||||
class TencentOnlyAggregator(FakeFreeAggregator):
|
||||
def eastmoney_market_quotes(self, expected_date=""):
|
||||
raise RealtimeAggregateError("eastmoney blocked")
|
||||
|
||||
def tencent_market_quotes(self, codes, expected_date=""):
|
||||
return list(FREE_QUOTES)
|
||||
|
||||
self.client.query = query
|
||||
self.client.realtime_aggregator = TencentOnlyAggregator()
|
||||
TushareClient._realtime_reference_cache.clear()
|
||||
dashboard = self.client._realtime_dashboard("20260720", "20260720", "20260717")
|
||||
self.assertEqual(dashboard["meta"]["quote_source"], "tencent_qt")
|
||||
self.assertEqual(str(dashboard["meta"]["trade_date"]).replace("-", ""), "20260720")
|
||||
self.assertIn("腾讯免费实时", dashboard["meta"]["notice"])
|
||||
self.assertEqual(dashboard["overview"]["amount_billion"], 6.0)
|
||||
|
||||
def test_normalize_eastmoney_quote_maps_units_and_exchange(self):
|
||||
quote = _normalize_eastmoney_quote(
|
||||
{
|
||||
"f12": "600000",
|
||||
"f13": 1,
|
||||
"f14": "浦发银行",
|
||||
"f2": 10.5,
|
||||
"f5": 12.0,
|
||||
"f6": 200000000,
|
||||
"f15": 10.8,
|
||||
"f16": 10.2,
|
||||
"f17": 10.3,
|
||||
"f18": 10.0,
|
||||
"f124": 1752986700,
|
||||
}
|
||||
)
|
||||
self.assertEqual(quote["ts_code"], "600000.SH")
|
||||
self.assertEqual(quote["vol"], 1200)
|
||||
self.assertEqual(quote["close"], 10.5)
|
||||
self.assertEqual(quote["pre_close"], 10.0)
|
||||
self.assertEqual(quote["source"], "eastmoney_clist")
|
||||
|
||||
def test_parse_tencent_stock_quote_keeps_today_and_units(self):
|
||||
line = (
|
||||
'v_sz000001="51~平安银行~000001~11.73~11.70~11.66~346232~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~'
|
||||
'~20260720100500~0.03~0.26~11.79~11.65~11.73/346232/406045563~346232~40605~0.18~5.24~~11.79~11.65~1.20~'
|
||||
'2276.29~2276.31~0.49~12.87~10.53~0.95~-3076~11.73~4.43~5.34~~~0.18~40604.5563~0.0000~0~";'
|
||||
)
|
||||
quote = _parse_tencent_stock_quote(line)
|
||||
self.assertEqual(quote["ts_code"], "000001.SZ")
|
||||
self.assertEqual(quote["quote_date"], "20260720")
|
||||
self.assertEqual(quote["close"], 11.73)
|
||||
self.assertEqual(quote["pre_close"], 11.70)
|
||||
self.assertEqual(quote["vol"], 34623200)
|
||||
self.assertEqual(quote["amount"], 406050000)
|
||||
self.assertEqual(quote["source"], "tencent_qt")
|
||||
|
||||
def test_datahub_market_quotes_used_before_legacy(self):
|
||||
calls = []
|
||||
|
||||
def try_market_quotes(trade_date):
|
||||
calls.append(trade_date)
|
||||
return list(FREE_QUOTES)
|
||||
|
||||
self.client.try_market_quotes = try_market_quotes
|
||||
self.client.realtime_aggregator = FakeFreeAggregator(fail=True)
|
||||
TushareClient._realtime_reference_cache.clear()
|
||||
dashboard = self.client._realtime_dashboard("20260720", "20260720", "20260717")
|
||||
self.assertEqual(calls, ["20260720"])
|
||||
self.assertEqual(dashboard["meta"]["quote_source"], "datahub")
|
||||
self.assertEqual(dashboard["meta"]["source"], "datahub")
|
||||
self.assertEqual(dashboard["meta"]["quote_count"], 3)
|
||||
self.assertIn("数据中枢", dashboard["meta"]["notice"])
|
||||
|
||||
def test_gateway_dashboard_uses_bound_market_quotes(self) -> None:
|
||||
from backend.data import build_data_gateway
|
||||
from backend.data.datahub.client import DatahubResponse
|
||||
from backend.data.datahub.settings import DATASETS, DatahubSettings, DatasetFlags
|
||||
from backend.data.gateway import DataGateway
|
||||
from backend.data.providers.tushare import TushareProvider
|
||||
|
||||
quotes = [
|
||||
{
|
||||
"ts_code": item["ts_code"],
|
||||
"name": item["name"],
|
||||
"pre_close": item["pre_close"],
|
||||
"open": item["open"],
|
||||
"high": item["high"],
|
||||
"low": item["low"],
|
||||
"close": item["close"],
|
||||
"vol": item["vol"],
|
||||
"amount": item["amount"],
|
||||
"quote_date": "20260720",
|
||||
}
|
||||
for item in FREE_QUOTES
|
||||
]
|
||||
extras = [
|
||||
{
|
||||
"ts_code": f"{index:06d}.SZ",
|
||||
"name": f"X{index}",
|
||||
"pre_close": 10.0,
|
||||
"open": 10.0,
|
||||
"high": 10.2,
|
||||
"low": 9.8,
|
||||
"close": 10.1,
|
||||
"vol": 100.0,
|
||||
"amount": 1000.0,
|
||||
"quote_date": "20260720",
|
||||
}
|
||||
for index in range(10, 230)
|
||||
]
|
||||
|
||||
class QuoteHub:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def quotes_latest(self, **params):
|
||||
return self.get("/v1/quotes/latest", params)
|
||||
|
||||
def get(self, path, params=None):
|
||||
self.calls.append(path)
|
||||
if path == "/v1/quotes/latest":
|
||||
return DatahubResponse(
|
||||
data=quotes + extras,
|
||||
meta={"stale": False, "staleness_seconds": 0, "source": "eastmoney_clist"},
|
||||
)
|
||||
raise AssertionError(path)
|
||||
|
||||
datasets = {name: DatasetFlags(name) for name in DATASETS}
|
||||
datasets["quotes"] = DatasetFlags("quotes", read=True, shadow=False)
|
||||
settings = DatahubSettings(base_url="http://127.0.0.1:9", token="tok", datasets=datasets)
|
||||
base = build_data_gateway({"tushare_token": "tok"}, datahub_settings=settings)
|
||||
gateway = DataGateway(
|
||||
policy=base.policy,
|
||||
quality=base.quality,
|
||||
tushare_provider=TushareProvider(
|
||||
lambda: "tok",
|
||||
client_factory=lambda token: FakeRealtimeClient(token),
|
||||
),
|
||||
ifind_provider=base.ifind_provider,
|
||||
chart_data=base.chart_data,
|
||||
realtime_observer=base.realtime_observer,
|
||||
datahub=base.datahub,
|
||||
)
|
||||
gateway.datahub.client = QuoteHub()
|
||||
wrapped = gateway.tushare()
|
||||
inner = wrapped._legacy
|
||||
inner.clock = lambda: datetime(2026, 7, 20, 10, 30, tzinfo=timezone(timedelta(hours=8)))
|
||||
inner.realtime_aggregator = FakeFreeAggregator(fail=True)
|
||||
TushareClient._realtime_reference_cache.clear()
|
||||
dashboard = wrapped.dashboard("20260720")
|
||||
self.assertEqual(dashboard["meta"]["quote_source"], "datahub")
|
||||
self.assertIn("/v1/quotes/latest", gateway.datahub.client.calls)
|
||||
self.assertTrue(callable(getattr(inner, "try_market_quotes", None)))
|
||||
self.assertFalse(hasattr(type(inner), "try_market_quotes"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -5,6 +5,10 @@ import unittest
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.data.providers.tushare_client import TushareError
|
||||
from backend.data.realtime import RealtimeAggregateError
|
||||
from backend.features.market.charts import ChartDataError
|
||||
from backend.features.market.service import TODAY_DAILY_UNAVAILABLE_NOTICE
|
||||
from server import DashboardService
|
||||
|
||||
|
||||
@@ -17,6 +21,10 @@ class DetailDatabaseStub:
|
||||
def list_notes(user_id, code=""):
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def get_snapshot(trade_date):
|
||||
return {}
|
||||
|
||||
|
||||
class RealtimeClientStub:
|
||||
quote_calls = 0
|
||||
@@ -61,6 +69,122 @@ class FixedPreopenDatetime(datetime):
|
||||
return cls.fixed_now
|
||||
|
||||
|
||||
class FixedLunchDatetime(datetime):
|
||||
fixed_now = datetime(2026, 7, 31, 11, 45).astimezone()
|
||||
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return cls.fixed_now
|
||||
|
||||
|
||||
class FixedAfterCloseDatetime(datetime):
|
||||
fixed_now = datetime(2026, 7, 31, 15, 30).astimezone()
|
||||
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return cls.fixed_now
|
||||
|
||||
|
||||
class DeniedRealtimeClientStub:
|
||||
quote_calls = 0
|
||||
|
||||
def __init__(self, token):
|
||||
self.token = token
|
||||
|
||||
@staticmethod
|
||||
def resolve_trade_context(requested_date):
|
||||
return requested_date, requested_date
|
||||
|
||||
@classmethod
|
||||
def realtime_stock_quote(cls, ts_code, reference_date=""):
|
||||
cls.quote_calls += 1
|
||||
raise TushareError("没有接口访问权限")
|
||||
|
||||
|
||||
class FreeQuoteAggregator:
|
||||
def __init__(self, quote=None, fail=False):
|
||||
self.quote = quote
|
||||
self.fail = fail
|
||||
self.tencent_calls = 0
|
||||
self.eastmoney_calls = 0
|
||||
|
||||
def tencent_stock_quote(self, code, expected_date=""):
|
||||
self.tencent_calls += 1
|
||||
if self.fail:
|
||||
raise RealtimeAggregateError("tencent down")
|
||||
if self.quote and self.quote.get("source") == "eastmoney_stock":
|
||||
raise RealtimeAggregateError("tencent empty")
|
||||
if self.quote:
|
||||
return self.quote
|
||||
raise RealtimeAggregateError("tencent empty")
|
||||
|
||||
def eastmoney_stock_quote(self, code, expected_date=""):
|
||||
self.eastmoney_calls += 1
|
||||
if self.fail:
|
||||
raise RealtimeAggregateError("eastmoney down")
|
||||
if self.quote and self.quote.get("source") == "eastmoney_stock":
|
||||
return self.quote
|
||||
raise RealtimeAggregateError("eastmoney empty")
|
||||
|
||||
|
||||
class IntradayChartStub:
|
||||
def __init__(self, points, previous_close=10.0, trade_date="2026-07-31"):
|
||||
self.points = points
|
||||
self.previous_close = previous_close
|
||||
self.trade_date = trade_date
|
||||
|
||||
def stock_daily(self, code, end_date, limit=90):
|
||||
raise ChartDataError("iFinD daily unavailable")
|
||||
|
||||
def stock_intraday(self, code):
|
||||
return {
|
||||
"trade_date": self.trade_date,
|
||||
"previous_close": self.previous_close,
|
||||
"points": self.points,
|
||||
}
|
||||
|
||||
|
||||
def _history_payload(code="002141"):
|
||||
yesterday = (FixedMarketDatetime.fixed_now - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
return {
|
||||
"meta": {"trade_date": yesterday, "source": "tushare"},
|
||||
"stock": {"code": code, "name": "旧名称", "price": 10, "change": 7.1},
|
||||
"prices": [
|
||||
{
|
||||
"trade_date": yesterday,
|
||||
"open": 9.5,
|
||||
"high": 10.1,
|
||||
"low": 9.4,
|
||||
"close": 10,
|
||||
"change": 7.1,
|
||||
"volume": 100,
|
||||
"amount_billion": 1.1,
|
||||
}
|
||||
],
|
||||
"moneyflow": {},
|
||||
}
|
||||
|
||||
|
||||
def _free_quote(source="tencent_qt", **overrides):
|
||||
quote = {
|
||||
"ts_code": "002141.SZ",
|
||||
"name": "贤程科技",
|
||||
"pre_close": 10.0,
|
||||
"open": 10.2,
|
||||
"high": 10.8,
|
||||
"low": 10.1,
|
||||
"close": 10.6,
|
||||
"vol": 250000,
|
||||
"amount": 26_500_000,
|
||||
"quote_date": "20260731",
|
||||
"quote_time_epoch": int(datetime(2026, 7, 31, 10, 31).timestamp()),
|
||||
"source": source,
|
||||
"turnover_rate": 2.5,
|
||||
}
|
||||
quote.update(overrides)
|
||||
return quote
|
||||
|
||||
|
||||
class StockDetailRealtimeTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.service = DashboardService.__new__(DashboardService)
|
||||
@@ -68,7 +192,11 @@ class StockDetailRealtimeTests(unittest.TestCase):
|
||||
self.service.database = DetailDatabaseStub()
|
||||
self.service._request_context = threading.local()
|
||||
self.service._request_context.user_id = 1
|
||||
self.service.ifind = None
|
||||
self.service.realtime_aggregator = None
|
||||
self.service.chart_data = None
|
||||
RealtimeClientStub.quote_calls = 0
|
||||
DeniedRealtimeClientStub.quote_calls = 0
|
||||
|
||||
def test_today_detail_merges_rt_quote_without_mutating_daily_cache(self):
|
||||
today = FixedMarketDatetime.fixed_now.strftime("%Y%m%d")
|
||||
@@ -162,6 +290,183 @@ class StockDetailRealtimeTests(unittest.TestCase):
|
||||
self.assertEqual(result["stock"]["change"], 1.2)
|
||||
self.assertEqual(RealtimeClientStub.quote_calls, 0)
|
||||
|
||||
def test_today_detail_falls_back_to_tencent_quote_when_rt_k_denied(self):
|
||||
today = FixedMarketDatetime.fixed_now.strftime("%Y%m%d")
|
||||
aggregator = FreeQuoteAggregator(_free_quote())
|
||||
self.service.realtime_aggregator = aggregator
|
||||
DeniedRealtimeClientStub.quote_calls = 0
|
||||
|
||||
with patch("backend.features.market.service.datetime", FixedMarketDatetime), patch(
|
||||
"backend.features.market.service.TushareClient", DeniedRealtimeClientStub
|
||||
):
|
||||
result = self.service._prepare_stock_detail(_history_payload(), "002141", today)
|
||||
|
||||
bar = result["prices"][-1]
|
||||
self.assertEqual(bar["trade_date"], "2026-07-31")
|
||||
self.assertTrue(bar["realtime"])
|
||||
self.assertEqual(bar["open"], 10.2)
|
||||
self.assertEqual(bar["high"], 10.8)
|
||||
self.assertEqual(bar["low"], 10.1)
|
||||
self.assertEqual(bar["close"], 10.6)
|
||||
self.assertAlmostEqual(bar["change"], 6.0, places=4)
|
||||
self.assertEqual(bar["volume"], 2500)
|
||||
self.assertAlmostEqual(bar["amount_billion"], 0.265)
|
||||
self.assertEqual(len(result["prices"]), 2)
|
||||
self.assertEqual(result["meta"]["notice"], "")
|
||||
self.assertEqual(aggregator.tencent_calls, 1)
|
||||
self.assertEqual(DeniedRealtimeClientStub.quote_calls, 1)
|
||||
|
||||
def test_today_detail_falls_back_to_eastmoney_then_intraday(self):
|
||||
today = FixedMarketDatetime.fixed_now.strftime("%Y%m%d")
|
||||
aggregator = FreeQuoteAggregator(
|
||||
_free_quote("eastmoney_stock", ts_code="600000.SH", name="浦发银行"),
|
||||
)
|
||||
self.service.realtime_aggregator = aggregator
|
||||
DeniedRealtimeClientStub.quote_calls = 0
|
||||
|
||||
with patch("backend.features.market.service.datetime", FixedMarketDatetime), patch(
|
||||
"backend.features.market.service.TushareClient", DeniedRealtimeClientStub
|
||||
):
|
||||
result = self.service._prepare_stock_detail(_history_payload("600000"), "600000", today)
|
||||
|
||||
self.assertEqual(result["prices"][-1]["trade_date"], "2026-07-31")
|
||||
self.assertEqual(result["prices"][-1]["close"], 10.6)
|
||||
self.assertEqual(aggregator.tencent_calls, 1)
|
||||
self.assertEqual(aggregator.eastmoney_calls, 1)
|
||||
|
||||
aggregator = FreeQuoteAggregator(fail=True)
|
||||
self.service.realtime_aggregator = aggregator
|
||||
self.service.chart_data = IntradayChartStub(
|
||||
[
|
||||
{
|
||||
"date": "2026-07-31",
|
||||
"time": "09:30",
|
||||
"open": 10.1,
|
||||
"high": 10.2,
|
||||
"low": 10.0,
|
||||
"close": 10.15,
|
||||
"volume": 120,
|
||||
"amount": 121800,
|
||||
},
|
||||
{
|
||||
"date": "2026-07-31",
|
||||
"time": "10:05",
|
||||
"open": 10.15,
|
||||
"high": 10.5,
|
||||
"low": 9.9,
|
||||
"close": 10.4,
|
||||
"volume": 80,
|
||||
"amount": 83200,
|
||||
},
|
||||
]
|
||||
)
|
||||
with patch("backend.features.market.service.datetime", FixedMarketDatetime), patch(
|
||||
"backend.features.market.service.TushareClient", DeniedRealtimeClientStub
|
||||
):
|
||||
result = self.service._prepare_stock_detail(_history_payload("300750"), "300750", today)
|
||||
|
||||
bar = result["prices"][-1]
|
||||
self.assertEqual(bar["trade_date"], "2026-07-31")
|
||||
self.assertEqual(bar["open"], 10.1)
|
||||
self.assertEqual(bar["high"], 10.5)
|
||||
self.assertEqual(bar["low"], 9.9)
|
||||
self.assertEqual(bar["close"], 10.4)
|
||||
self.assertAlmostEqual(bar["change"], 4.0, places=4)
|
||||
self.assertEqual(bar["volume"], 200)
|
||||
self.assertTrue(bar["realtime"])
|
||||
|
||||
def test_today_detail_keeps_history_when_free_sources_fail(self):
|
||||
today = FixedMarketDatetime.fixed_now.strftime("%Y%m%d")
|
||||
self.service.realtime_aggregator = FreeQuoteAggregator(fail=True)
|
||||
self.service.chart_data = IntradayChartStub([], trade_date="2026-07-30")
|
||||
DeniedRealtimeClientStub.quote_calls = 0
|
||||
|
||||
with patch("backend.features.market.service.datetime", FixedMarketDatetime), patch(
|
||||
"backend.features.market.service.TushareClient", DeniedRealtimeClientStub
|
||||
):
|
||||
result = self.service._prepare_stock_detail(_history_payload(), "002141", today)
|
||||
|
||||
self.assertEqual(result["prices"][-1]["trade_date"], "2026-07-30")
|
||||
self.assertFalse(result["meta"].get("realtime", False))
|
||||
self.assertEqual(result["meta"]["notice"], TODAY_DAILY_UNAVAILABLE_NOTICE)
|
||||
self.assertEqual(len(result["prices"]), 1)
|
||||
|
||||
def test_lunch_keeps_morning_realtime_bar(self):
|
||||
today = FixedLunchDatetime.fixed_now.strftime("%Y%m%d")
|
||||
self.service.realtime_aggregator = FreeQuoteAggregator(
|
||||
_free_quote(quote_time_epoch=int(datetime(2026, 7, 31, 11, 30).timestamp()))
|
||||
)
|
||||
DeniedRealtimeClientStub.quote_calls = 0
|
||||
with patch("backend.features.market.service.datetime", FixedLunchDatetime), patch(
|
||||
"backend.features.market.service.TushareClient", DeniedRealtimeClientStub
|
||||
):
|
||||
result = self.service._prepare_stock_detail(_history_payload(), "002141", today)
|
||||
|
||||
self.assertEqual(result["prices"][-1]["trade_date"], "2026-07-31")
|
||||
self.assertTrue(result["meta"]["realtime"])
|
||||
|
||||
def test_after_close_keeps_forming_bar_until_official_ready(self):
|
||||
today = FixedAfterCloseDatetime.fixed_now.strftime("%Y%m%d")
|
||||
self.service.realtime_aggregator = FreeQuoteAggregator(_free_quote())
|
||||
DeniedRealtimeClientStub.quote_calls = 0
|
||||
with patch("backend.features.market.service.datetime", FixedAfterCloseDatetime), patch(
|
||||
"backend.features.market.service.TushareClient", DeniedRealtimeClientStub
|
||||
):
|
||||
forming = self.service._prepare_stock_detail(_history_payload(), "002141", today)
|
||||
self.assertEqual(forming["prices"][-1]["trade_date"], "2026-07-31")
|
||||
self.assertTrue(forming["prices"][-1]["realtime"])
|
||||
|
||||
official = _history_payload()
|
||||
official["prices"].append(
|
||||
{
|
||||
"trade_date": "2026-07-31",
|
||||
"open": 10.15,
|
||||
"high": 10.9,
|
||||
"low": 10.05,
|
||||
"close": 10.7,
|
||||
"change": 7.0,
|
||||
"volume": 1800,
|
||||
"amount_billion": 0.3,
|
||||
}
|
||||
)
|
||||
RealtimeClientStub.quote_calls = 0
|
||||
with patch("backend.features.market.service.datetime", FixedAfterCloseDatetime), patch(
|
||||
"backend.features.market.service.TushareClient", RealtimeClientStub
|
||||
):
|
||||
replaced = self.service._prepare_stock_detail(official, "002141", today)
|
||||
|
||||
self.assertEqual(replaced["prices"][-1]["close"], 10.7)
|
||||
self.assertFalse(replaced["prices"][-1].get("realtime", False))
|
||||
self.assertEqual(len(replaced["prices"]), 2)
|
||||
self.assertEqual(RealtimeClientStub.quote_calls, 0)
|
||||
|
||||
def test_same_date_bar_is_replaced_not_duplicated(self):
|
||||
today = FixedMarketDatetime.fixed_now.strftime("%Y%m%d")
|
||||
payload = _history_payload()
|
||||
payload["prices"].append(
|
||||
{
|
||||
"trade_date": "2026-07-31",
|
||||
"open": 10.0,
|
||||
"high": 10.1,
|
||||
"low": 9.9,
|
||||
"close": 10.05,
|
||||
"change": 0.5,
|
||||
"volume": 10,
|
||||
"amount_billion": 0.01,
|
||||
"realtime": True,
|
||||
}
|
||||
)
|
||||
self.service.realtime_aggregator = FreeQuoteAggregator(_free_quote())
|
||||
DeniedRealtimeClientStub.quote_calls = 0
|
||||
with patch("backend.features.market.service.datetime", FixedMarketDatetime), patch(
|
||||
"backend.features.market.service.TushareClient", DeniedRealtimeClientStub
|
||||
):
|
||||
result = self.service._prepare_stock_detail(payload, "002141", today)
|
||||
|
||||
self.assertEqual(len(result["prices"]), 2)
|
||||
self.assertEqual(result["prices"][-1]["close"], 10.6)
|
||||
self.assertEqual(result["prices"][-1]["trade_date"], "2026-07-31")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -97,6 +97,7 @@ def code_hotspots() -> list[dict[str, Any]]:
|
||||
"backend/features/system/service.py",
|
||||
"backend/features/accounts/application.py",
|
||||
"backend/jobs/service.py",
|
||||
"backend/jobs/refresh.py",
|
||||
"database.py",
|
||||
"backend/features/screener/engine.py",
|
||||
"backend/features/screener/catalog.py",
|
||||
@@ -217,10 +218,11 @@ def build() -> dict[str, Any]:
|
||||
),
|
||||
"external_data_adapters": [
|
||||
{"provider": "tushare", "path": "backend/data/providers/tushare_client.py", "runtime_role": "stable client facade for primary deterministic market data"},
|
||||
{"provider": "datahub", "path": "backend/data/datahub/client.py", "runtime_role": "optional official EOD read path behind per-dataset flags"},
|
||||
{"provider": "ifind", "path": "backend/data/providers/ifind_client.py", "runtime_role": "realtime, charts, snapshots, enrichment"},
|
||||
{"provider": "eastmoney", "path": "backend/features/market/charts.py", "runtime_role": "display chart fallback"},
|
||||
{"provider": "eastmoney", "path": "backend/data/realtime.py", "runtime_role": "isolated realtime observation"},
|
||||
{"provider": "tencent", "path": "backend/data/realtime.py", "runtime_role": "index observation fallback"},
|
||||
{"provider": "eastmoney", "path": "backend/data/realtime.py", "runtime_role": "isolated realtime observation and intraday dashboard fallback"},
|
||||
{"provider": "tencent", "path": "backend/data/realtime.py", "runtime_role": "index observation and intraday quote fallback"},
|
||||
],
|
||||
"provider_domains": [
|
||||
{"provider": "tushare", "path": "backend/data/providers/tushare_transport.py", "responsibility": "HTTP transport and provider errors"},
|
||||
@@ -235,6 +237,9 @@ def build() -> dict[str, Any]:
|
||||
],
|
||||
"provider_construction": [
|
||||
{"client": "TushareClient", "owner": "backend/data/providers/tushare.py", "compatibility_fallback": "backend/features/market/service.py"},
|
||||
{"client": "DatahubClient", "owner": "backend/data/gateway.py"},
|
||||
{"client": "DatahubBridge", "owner": "backend/data/gateway.py"},
|
||||
{"client": "DatahubAwareTushareClient", "owner": "backend/data/gateway.py"},
|
||||
{"client": "IfindHttpClient", "owner": "backend/data/gateway.py"},
|
||||
{"client": "MarketChartClient", "owner": "backend/data/gateway.py"},
|
||||
{"client": "WebRealtimeAggregator", "owner": "backend/data/gateway.py"},
|
||||
@@ -261,6 +266,7 @@ def build() -> dict[str, Any]:
|
||||
"system_service": "backend/features/system/service.py",
|
||||
"account_bridge": "backend/features/accounts/application.py",
|
||||
"job_lifecycle": "backend/jobs/service.py",
|
||||
"job_refresh_status": "backend/jobs/refresh.py",
|
||||
"feature_routes": "backend/features/*/routes.py",
|
||||
},
|
||||
"numeric_normalization": [
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
.git
|
||||
.gitignore
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.log
|
||||
data/
|
||||
tests/
|
||||
@@ -0,0 +1,13 @@
|
||||
# Fernet key. Generate with: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
|
||||
DATAHUB_ENCRYPTION_KEY=
|
||||
|
||||
# Consumer API token for /v1 (32+ random bytes, shown once). Never log this value.
|
||||
DATAHUB_TOKEN=
|
||||
|
||||
# Initial admin password for /admin. Forced change on first login.
|
||||
DATAHUB_ADMIN_PASSWORD=
|
||||
|
||||
# Tushare Pro token. Stored encrypted after first launch; never returned by API or admin pages.
|
||||
TUSHARE_TOKEN=
|
||||
|
||||
TZ=Asia/Shanghai
|
||||
@@ -0,0 +1,36 @@
|
||||
FROM python:3.12-slim-bookworm
|
||||
|
||||
ARG APP_UID=10002
|
||||
ARG APP_GID=10002
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PYTHONUTF8=1 \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
||||
TZ=Asia/Shanghai
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
ca-certificates \
|
||||
tzdata \
|
||||
&& groupadd --gid "${APP_GID}" datahub \
|
||||
&& useradd --uid "${APP_UID}" --gid "${APP_GID}" --create-home --shell /usr/sbin/nologin datahub \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt ./
|
||||
RUN python -m pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY --chown=datahub:datahub . .
|
||||
RUN mkdir -p /app/data /app/data/backups && chown -R datahub:datahub /app/data
|
||||
|
||||
USER datahub
|
||||
|
||||
EXPOSE 8766
|
||||
STOPSIGNAL SIGINT
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8766/livez', timeout=4).read()"]
|
||||
|
||||
CMD ["python", "-u", "server.py", "--host", "0.0.0.0", "--port", "8766"]
|
||||
@@ -0,0 +1,152 @@
|
||||
# xiaobai-datahub
|
||||
|
||||
独立行情数据中枢(HEL-382 / P0)。与 `xiaobai-review` 同仓库、不同容器、不共享数据库文件。
|
||||
本阶段不部署现网;只提供可本地运行、可自测的底座和盘后正式数据链路。
|
||||
|
||||
## 做什么
|
||||
|
||||
- SQLite WAL `datahub.db`,容器名 `xiaobai-datahub`,端口 `8766`
|
||||
- Tushare 盘后正式数据:交易日历、股票主档、daily、daily_basic、adj_factor、index_daily、moneyflow、stk_auction、limit_list_d、ths_hot/dc_hot、hm_detail、ths_daily/dc_index/sw_daily
|
||||
- 盘中观察(provisional):东财/腾讯指数报价、个股最新价、全市场快照、分时点(`/v1/quotes/latest` 不传 codes 即全市场,`/v1/indexes/quotes` `/v1/intraday/points`);永不写入 eod_* 正式表
|
||||
- 暂存 → 校验 → 整批原子发布 → 可回滚
|
||||
- `/v1` 稳定接口(`X-Datahub-Token`)
|
||||
- `/admin/` 最小管理后台(总览 / 数据源 / 调度 / 发布 / 数据集 / 审计)
|
||||
- 同花顺/选股宝/AKShare/iFinD 适配器位仍预留;东财/腾讯已接入盘中观察
|
||||
|
||||
## 单位口径(相对现站)
|
||||
|
||||
现站 `xiaobai-review` 按 Tushare 原始单位入库、展示时再换算。中枢在归一化层一次换算:
|
||||
|
||||
| 字段 | Tushare / 现站 | 中枢 canonical |
|
||||
|---|---|---|
|
||||
| `daily.amount` / `index_daily.amount` | 千元 | 元(×1000) |
|
||||
| `daily.vol` / `index_daily.vol` | 手 | 股(×100) |
|
||||
| `moneyflow.*_amount` | 万元 | 元(×1e4) |
|
||||
| `daily_basic.total_mv` / `circ_mv` | 万元 | 元(×1e4) |
|
||||
| `stk_auction.amount` | 元 | 元 |
|
||||
|
||||
差异为口径升级,golden 测试按上表对照,不为 0 的字段都有说明。
|
||||
|
||||
## 本地启动(不走 Docker)
|
||||
|
||||
```bash
|
||||
cd xiaobai-datahub
|
||||
python -m venv .venv && .venv/bin/pip install -r requirements.txt
|
||||
cp .env.example .env
|
||||
# 填入 DATAHUB_ENCRYPTION_KEY / DATAHUB_TOKEN / DATAHUB_ADMIN_PASSWORD / TUSHARE_TOKEN
|
||||
# 生成 Fernet 密钥:
|
||||
# python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
|
||||
.venv/bin/python server.py --host 127.0.0.1 --port 8766
|
||||
```
|
||||
|
||||
- 管理后台:http://127.0.0.1:8766/admin/
|
||||
- 存活检查:http://127.0.0.1:8766/livez (无需 token)
|
||||
- `/v1/*` 必须带请求头 `X-Datahub-Token`
|
||||
|
||||
## Docker(独立 compose,不改现网 review 服务)
|
||||
|
||||
```bash
|
||||
cd xiaobai-datahub
|
||||
cp .env.example .env # 填密钥
|
||||
mkdir -p data
|
||||
docker compose build
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
仓库根目录另有 `compose.datahub.yaml`,供总工以后与现有 `compose.yaml` 叠加部署,本卡不执行现网 `up`。
|
||||
|
||||
## 自测
|
||||
|
||||
```bash
|
||||
cd xiaobai-datahub
|
||||
python -m unittest discover -s tests -v
|
||||
```
|
||||
|
||||
不调用真实 Tushare;用内存/临时库和假适配器。
|
||||
|
||||
## 历史回补
|
||||
|
||||
交易日历默认从 `20160101` 拉到今天后 30 天;盘前 `precheck` 与手动回补都走同一 UPSERT,可重复执行。
|
||||
|
||||
网站实际使用的指数(上证、深成、创业板、沪深300)按交易日增量发布,默认覆盖 260 个交易日(大于现有 90 天窗口,并覆盖智能选股基准回看)。已发布日期默认跳过。
|
||||
|
||||
```bash
|
||||
cd xiaobai-datahub
|
||||
python -m datahub history-backfill
|
||||
# 可选:--calendar-start 20160101 --index-days 260 --force
|
||||
```
|
||||
|
||||
管理后台也可手动跑 `history_backfill` 任务,或 `POST /admin/api/backfill` 且 `dataset=history`、确认词 `history:full`。
|
||||
|
||||
区间接口在 `meta.coverage` / `meta.incomplete` 标明覆盖是否完整;网站只读接入把不完整区间视为不可用并回旧链路。个股日 K 的 90 天区间查询依赖已核实,本阶段不回补全市场历史。
|
||||
|
||||
## 估值字段级质量门
|
||||
|
||||
`hub-quality.config.json` 的 `field_gates` 按数据集配置关键字段:非空率下限(支持按字段覆盖,如 `dv_ttm` 合法高空值)、非有限值比例上限、以及相对上一已发布批次的非空率塌陷保护。字段大面积为空的批次会被拒绝发布、保留上一份正常正式数据,失败原因逐字段写入 `batches.error` / `quality_json`。被拒后数据集仍视为缺失,盘后自动重试(HEL-435 机制)会继续尝试直到成功或截止。配置对任意数据集生效,不写死单日或单字段。
|
||||
|
||||
## 整批原子发布(release group)
|
||||
|
||||
盘后发布/重发(eod_a、eod_retry、`eod-refresh`、跨数据集重发)不再逐数据集各自切换,而是走整批原子可见机制:
|
||||
|
||||
- 一致性边界:日 K、估值、资金流、竞价同属 A 组整批;指数日 K 为 B 组;当日股票主档快照随 A 组一同切换(主档 `stock_master` 的 UPSERT 与快照发布同一事务,不会出现主档先行/滞后)。
|
||||
- 流程:组内全部成员先在暂存表完成拉取、字段质量门、覆盖检查和跨数据集交叉校验(`cross_gates` 配置 ts_code 覆盖重叠率下限),全部达标后才在**一个 SQLite 事务**里复制正式表并翻转全部 `publications` 指针。
|
||||
- 任一成员失败(拉取失败、质量门拒绝、交叉校验不过、切换事务中断)→ 整批不切换,对外继续提供上一份完整正式版本,失败原因写入 `batches.error` 与 `audit_log`(`action=release-group`),等待晚间自动重试。
|
||||
- 读取侧任何时刻只会看到"旧完整版本"或"新完整版本":发布指针在单事务内统一翻转,容器重启/事务中断自动回滚,不暴露字段残缺或跨数据集混合版本。
|
||||
- 幂等:仅当一致性边界内全部成员都已发布时才整组跳过;边界内任有缺失则整组重暂存后统一切换,避免旧批次与新批次混在同一次重发中。重复执行、并发重试不会在完整边界已就绪时生成重复批次(调度器另有 EOD 互斥锁)。
|
||||
|
||||
## 股票主档每日刷新与发布
|
||||
|
||||
交易日 20:00 与 23:10(`stocks_refresh_times` 可配)自动刷新股票主档并发布版本化快照(`eod_stocks` + `publications.dataset='stocks'`),覆盖当日新上市、证券简称变化和上市首日 N/C 前缀摘除;无变化则跳过,重复执行幂等。`/v1/stocks` 从最新已发布快照提供数据并带 `batch_id` / `published_at`;`/v1/datasets/status` 同步展示 stocks 状态。
|
||||
|
||||
```bash
|
||||
cd xiaobai-datahub
|
||||
python -m datahub stocks-refresh # 手动触发;--force 无变化也重发
|
||||
```
|
||||
|
||||
## 资金流历史回补
|
||||
|
||||
网站会沿真实调用链查最近若干交易日的 moneyflow(个股详情任意日期点查 + 智能选股最近 5 个交易日),默认回补最近 60 个交易日(`moneyflow_history_trading_days` 可配,已发布日期自动跳过)。点查未覆盖的历史日期返回 `DATASET_NOT_PUBLISHED` 并附 `available_from` / `available_to`(低于下界时 `reason=history_not_backfilled`),网站据此明确回退旧链路,不会静默拿到半截数据。
|
||||
|
||||
```bash
|
||||
cd xiaobai-datahub
|
||||
python -m datahub moneyflow-backfill # --trading-days 60 --end-date --force 可选
|
||||
```
|
||||
|
||||
## 盘后补跑与强制重发
|
||||
|
||||
```bash
|
||||
cd xiaobai-datahub
|
||||
python -m datahub eod-refresh --trade-date 20260904 # 补不完整的 A/B 边界
|
||||
python -m datahub eod-refresh --trade-date 20260904 --force --dataset valuation
|
||||
# --force 按一致性边界整组重发:valuation/daily/moneyflow/auction/stocks → A 组;
|
||||
# index_daily → B 组。不可再单独切换某一个正式数据集。
|
||||
```
|
||||
|
||||
管理后台「补数」对盘后正式数据集同样走 `force_republish_boundary`,不会绕过 A/B 整批边界。
|
||||
|
||||
## 估值发布后复核与自动追补
|
||||
|
||||
Tushare `daily_basic` 会在盘后继续改当日字段。HEL-423 在 2026-09-07 观察到:中枢 17:10 发布 `003021.SZ turnover_rate=1.3565`,21:05 上游/旧链路已是 `1.3572`;其余 7 类观察对象当日一致。日 K、资金流、竞价、指数没有同类晚间修订证据,股票主档已有 20:00/23:10 刷新,因此默认只复核估值,不盲目全量重拉。
|
||||
|
||||
窗口(可配):交易日 **20:00–23:20**,每 30 分钟一次轻量比对(对齐网站 21:00 / 23:30 观察)。只拉取 `daily_basic`,按网站真实请求字段精确比较,无误差豁免。
|
||||
|
||||
- 无变化:不产生新批次,状态「已追平」。
|
||||
- 发现修订:重新走字段质量门、覆盖检查和 A 组整批原子发布;读者全程只能看到上一完整版本或新完整版本。
|
||||
- 上游空 / 接口失败 / 不完整 / 质量门拒绝:保留上一完整版本,状态「复核失败」。
|
||||
- 23:20 截止后停止当晚复核;下一自然日盘前对上一交易日再做一次安全追赶。
|
||||
- 与 `eod_a` / `eod_retry` 共用互斥锁;容器重启会在窗口内立即补一次。
|
||||
|
||||
## 备份
|
||||
|
||||
每日 00:40 任务把 `datahub.db` 备份到 `data/backups/`(保留 14 份)。也可手动:
|
||||
|
||||
```bash
|
||||
python -c "from pathlib import Path; from datahub.db import HubDB; HubDB(Path('data/datahub.db')).backup_to(Path('data/backups/manual.db'))"
|
||||
```
|
||||
|
||||
## 安全
|
||||
|
||||
- 密钥只以 `configured / 末4位 / 更新时间` 出现在后台,不进日志、不进 `/v1`
|
||||
- HTTP 解析失败只记录“请求不是合法 JSON”,不把请求正文、密码或 Token 写入容器日志
|
||||
- 回滚、补数需重新输入密码 + 确认词
|
||||
- 容器非 root(uid 10002)、read_only、cap_drop ALL
|
||||
@@ -0,0 +1,299 @@
|
||||
const state = { csrf: "", page: "overview" };
|
||||
|
||||
function $(id) { return document.getElementById(id); }
|
||||
|
||||
async function api(path, options = {}) {
|
||||
const headers = Object.assign({ "Content-Type": "application/json" }, options.headers || {});
|
||||
if (state.csrf && (options.method || "GET") !== "GET") headers["X-CSRF-Token"] = state.csrf;
|
||||
const res = await fetch(path, Object.assign({}, options, { headers, credentials: "same-origin" }));
|
||||
const body = await res.json();
|
||||
if (!res.ok) {
|
||||
const msg = (body.error && body.error.message) || body.error || res.statusText;
|
||||
throw new Error(msg);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
function show(id) {
|
||||
["login-view", "change-view", "shell"].forEach((key) => { $(key).hidden = key !== id; });
|
||||
}
|
||||
|
||||
function esc(value) {
|
||||
return String(value ?? "").replace(/[&<>"]/g, (ch) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[ch]));
|
||||
}
|
||||
|
||||
function table(headers, rows) {
|
||||
const thead = headers.map((h) => `<th>${esc(h)}</th>`).join("");
|
||||
const body = rows.length
|
||||
? rows.map((cols) => `<tr>${cols.map((c) => `<td>${c}</td>`).join("")}</tr>`).join("")
|
||||
: `<tr><td colspan="${headers.length}">暂无数据</td></tr>`;
|
||||
return `<table><thead><tr>${thead}</tr></thead><tbody>${body}</tbody></table>`;
|
||||
}
|
||||
|
||||
async function boot() {
|
||||
try {
|
||||
const session = await api("/admin/api/session");
|
||||
state.csrf = session.csrf;
|
||||
$("who").textContent = session.username;
|
||||
if (session.must_change) { show("change-view"); return; }
|
||||
show("shell");
|
||||
await render();
|
||||
} catch {
|
||||
show("login-view");
|
||||
}
|
||||
}
|
||||
|
||||
$("login-form").addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.target);
|
||||
$("login-error").hidden = true;
|
||||
try {
|
||||
const result = await api("/admin/api/login", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ username: form.get("username"), password: form.get("password") }),
|
||||
});
|
||||
state.csrf = result.csrf;
|
||||
if (result.must_change) show("change-view");
|
||||
else { show("shell"); await render(); }
|
||||
} catch (err) {
|
||||
$("login-error").hidden = false;
|
||||
$("login-error").textContent = err.message;
|
||||
}
|
||||
});
|
||||
|
||||
$("change-form").addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.target);
|
||||
try {
|
||||
await api("/admin/api/change-password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ current: form.get("current"), new_password: form.get("new_password") }),
|
||||
});
|
||||
show("shell");
|
||||
await render();
|
||||
} catch (err) {
|
||||
$("change-error").hidden = false;
|
||||
$("change-error").textContent = err.message;
|
||||
}
|
||||
});
|
||||
|
||||
$("logout-btn").addEventListener("click", async () => {
|
||||
await api("/admin/api/logout", { method: "POST", body: "{}" });
|
||||
show("login-view");
|
||||
});
|
||||
|
||||
$("theme-btn").addEventListener("click", () => {
|
||||
const root = document.documentElement;
|
||||
const next = root.getAttribute("data-theme") === "night" ? "" : "night";
|
||||
if (next) root.setAttribute("data-theme", next);
|
||||
else root.removeAttribute("data-theme");
|
||||
$("theme-btn").textContent = next ? "日间" : "夜间";
|
||||
});
|
||||
|
||||
document.querySelectorAll("nav button").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
document.querySelectorAll("nav button").forEach((item) => item.classList.remove("active"));
|
||||
btn.classList.add("active");
|
||||
state.page = btn.dataset.page;
|
||||
render();
|
||||
});
|
||||
});
|
||||
|
||||
async function render() {
|
||||
const page = $("page");
|
||||
if (state.page === "overview") {
|
||||
const data = await api("/admin/api/overview");
|
||||
$("phase").textContent = data.session_phase;
|
||||
const eod = data.eod_status || {};
|
||||
const rev = data.revision_status || {};
|
||||
const eodLabels = {
|
||||
pending_first_attempt: "等待首次尝试",
|
||||
waiting_upstream: "等待上游",
|
||||
done: "已成功",
|
||||
cutoff_failed: "已截止失败",
|
||||
closed_day: "休市",
|
||||
};
|
||||
const revLabels = {
|
||||
waiting_review: "等待复核",
|
||||
review_failed: "复核失败",
|
||||
aligned: "已追平",
|
||||
cutoff: "已截止",
|
||||
pending_publish: "待发布",
|
||||
closed_day: "休市",
|
||||
};
|
||||
const eodExtra = [];
|
||||
if (eod.state === "waiting_upstream") {
|
||||
eodExtra.push(`已试 ${eod.attempts} 次`);
|
||||
if (eod.next_retry_at) eodExtra.push(`下次重试 ${esc(String(eod.next_retry_at).replace("T", " ").slice(11, 16))}`);
|
||||
if (eod.missing_datasets && eod.missing_datasets.length) eodExtra.push(`缺 ${esc(eod.missing_datasets.join(","))}`);
|
||||
}
|
||||
if (eod.state === "cutoff_failed" && eod.missing_datasets) {
|
||||
eodExtra.push(`缺 ${esc(eod.missing_datasets.join(","))}`);
|
||||
}
|
||||
const revExtra = [];
|
||||
if (rev.detail) revExtra.push(esc(String(rev.detail)));
|
||||
if (rev.window) revExtra.push(esc(String(rev.window)));
|
||||
page.innerHTML = `
|
||||
<div class="cards">
|
||||
<div class="card"><div class="muted">交易日</div><strong>${esc(data.trade_date)}</strong></div>
|
||||
<div class="card"><div class="muted">阶段</div><strong>${esc(data.session_phase)}</strong></div>
|
||||
<div class="card"><div class="muted">今日发布</div><strong>${data.publications.length}</strong></div>
|
||||
<div class="card"><div class="muted">盘后补跑</div><strong>${esc(eodLabels[eod.state] || eod.state || "-")}</strong><div class="muted">${eodExtra.join(" · ")}</div></div>
|
||||
<div class="card"><div class="muted">估值复核</div><strong>${esc(revLabels[rev.state] || rev.state || "-")}</strong><div class="muted">${revExtra.join(" · ")}</div></div>
|
||||
<div class="card"><div class="muted">异常批次</div><strong class="${data.anomalies.length ? "fail" : "ok"}">${data.anomalies.length}</strong></div>
|
||||
</div>
|
||||
<h2>最近调用</h2>
|
||||
${table(["时间", "源", "端点", "结果", "耗时"], data.recent_calls.map((row) => [
|
||||
esc(row.created_at), esc(row.provider), esc(row.endpoint),
|
||||
row.ok ? '<span class="ok">成功</span>' : `<span class="fail">${esc(row.error)}</span>`,
|
||||
`${row.latency_ms ?? "-"} ms`,
|
||||
]))}
|
||||
`;
|
||||
return;
|
||||
}
|
||||
if (state.page === "sources") {
|
||||
const data = await api("/admin/api/sources");
|
||||
page.innerHTML = `<h2>数据源</h2>` + table(
|
||||
["源", "角色", "状态", "凭据", "操作"],
|
||||
data.items.map((item) => {
|
||||
const cred = item.credential || {};
|
||||
const credText = cred.configured ? `已配置 · ${esc(cred.last4 || "****")}` : "未配置";
|
||||
return [
|
||||
esc(item.provider),
|
||||
esc(item.role),
|
||||
esc((item.health && (item.health.state || item.health.status)) || "-"),
|
||||
credText,
|
||||
`<button data-probe="${esc(item.provider)}">探测一次</button>`,
|
||||
];
|
||||
}),
|
||||
);
|
||||
page.querySelectorAll("[data-probe]").forEach((btn) => {
|
||||
btn.addEventListener("click", async () => {
|
||||
const result = await api(`/admin/api/sources/${btn.dataset.probe}/probe`, { method: "POST", body: "{}" });
|
||||
alert(JSON.stringify(result));
|
||||
render();
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (state.page === "jobs") {
|
||||
const data = await api("/admin/api/jobs");
|
||||
page.innerHTML = `
|
||||
<h2>调度任务</h2>
|
||||
${table(["任务", "时刻", "操作"], data.jobs.map((job) => [
|
||||
`${esc(job.id)} · ${esc(job.title)}`, esc(job.at),
|
||||
`<button data-run="${esc(job.id)}">手动触发</button>`,
|
||||
]))}
|
||||
<h3>最近运行</h3>
|
||||
${table(["ID", "任务", "状态", "开始", "结束", "错误"], data.runs.map((row) => [
|
||||
row.id, esc(row.job_id), esc(row.state), esc(row.started_at), esc(row.finished_at), esc(row.error),
|
||||
]))}
|
||||
`;
|
||||
page.querySelectorAll("[data-run]").forEach((btn) => {
|
||||
btn.addEventListener("click", async () => {
|
||||
const date = prompt("交易日 YYYYMMDD(可留空=今天)", "") || "";
|
||||
await api(`/admin/api/jobs/${btn.dataset.run}/run`, { method: "POST", body: JSON.stringify({ trade_date: date }) });
|
||||
render();
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (state.page === "release") {
|
||||
const date = new Date().toISOString().slice(0, 10).replace(/-/g, "");
|
||||
const data = await api(`/admin/api/batches?date=${date}`);
|
||||
page.innerHTML = `
|
||||
<h2>盘后发布 ${esc(data.trade_date)}</h2>
|
||||
<div class="toolbar">
|
||||
<label>日期 <input id="rel-date" value="${esc(data.trade_date)}" /></label>
|
||||
<button type="button" id="rel-load">查看</button>
|
||||
<button type="button" id="rel-backfill">补数</button>
|
||||
</div>
|
||||
<h3>当前映射</h3>
|
||||
${table(["数据集", "活跃批次", "上一批次", "状态", "发布时间", "操作"], data.publications.map((row) => [
|
||||
esc(row.dataset), esc(row.active_batch), esc(row.prev_batch), esc(row.state), esc(row.published_at),
|
||||
row.prev_batch ? `<button class="danger" data-rollback="${esc(row.dataset)}">回滚</button>` : "-",
|
||||
]))}
|
||||
<h3>批次</h3>
|
||||
${table(["batch_id", "数据集", "状态", "行数", "错误"], data.batches.map((row) => [
|
||||
esc(row.batch_id), esc(row.dataset), esc(row.state), row.rows_out ?? "", esc(row.error),
|
||||
]))}
|
||||
`;
|
||||
$bindRelease(page);
|
||||
return;
|
||||
}
|
||||
if (state.page === "datasets") {
|
||||
const data = await api("/admin/api/datasets?date=");
|
||||
page.innerHTML = `
|
||||
<h2>数据集 / 质量 ${esc(data.trade_date)}</h2>
|
||||
${table(["数据集", "批次", "状态", "发布时间"], data.publications.map((row) => [
|
||||
esc(row.dataset), esc(row.active_batch), esc(row.state), esc(row.published_at),
|
||||
]))}
|
||||
<h3>源间差异</h3>
|
||||
${table(["指标", "左", "右", "偏差", "样本"], data.diff_reports.map((row) => [
|
||||
esc(row.metric), esc(row.left_value), esc(row.right_value), esc(row.deviation), row.sample_count ?? "",
|
||||
]))}
|
||||
`;
|
||||
return;
|
||||
}
|
||||
if (state.page === "audit") {
|
||||
const data = await api("/admin/api/audit");
|
||||
page.innerHTML = `<h2>审计</h2>` + table(
|
||||
["时间", "操作者", "动作", "对象", "详情"],
|
||||
data.items.map((row) => [esc(row.created_at), esc(row.actor), esc(row.action), esc(row.target), esc(row.detail)]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function $bindRelease(page) {
|
||||
page.querySelector("#rel-load").addEventListener("click", async () => {
|
||||
const date = page.querySelector("#rel-date").value;
|
||||
const data = await api(`/admin/api/batches?date=${encodeURIComponent(date)}`);
|
||||
state.page = "release";
|
||||
// re-render with fetched date by writing location hash
|
||||
history.replaceState(null, "", `#release-${date}`);
|
||||
$("page").innerHTML = renderRelease(data);
|
||||
$bindRelease($("page"));
|
||||
});
|
||||
page.querySelector("#rel-backfill").addEventListener("click", () => dangerous("backfill"));
|
||||
page.querySelectorAll("[data-rollback]").forEach((btn) => {
|
||||
btn.addEventListener("click", () => dangerous("rollback", btn.dataset.rollback));
|
||||
});
|
||||
}
|
||||
|
||||
function renderRelease(data) {
|
||||
return `
|
||||
<h2>盘后发布 ${esc(data.trade_date)}</h2>
|
||||
<div class="toolbar">
|
||||
<label>日期 <input id="rel-date" value="${esc(data.trade_date)}" /></label>
|
||||
<button type="button" id="rel-load">查看</button>
|
||||
<button type="button" id="rel-backfill">补数</button>
|
||||
</div>
|
||||
<h3>当前映射</h3>
|
||||
${table(["数据集", "活跃批次", "上一批次", "状态", "发布时间", "操作"], data.publications.map((row) => [
|
||||
esc(row.dataset), esc(row.active_batch), esc(row.prev_batch), esc(row.state), esc(row.published_at),
|
||||
row.prev_batch ? `<button class="danger" data-rollback="${esc(row.dataset)}">回滚</button>` : "-",
|
||||
]))}
|
||||
<h3>批次</h3>
|
||||
${table(["batch_id", "数据集", "状态", "行数", "错误"], data.batches.map((row) => [
|
||||
esc(row.batch_id), esc(row.dataset), esc(row.state), row.rows_out ?? "", esc(row.error),
|
||||
]))}
|
||||
`;
|
||||
}
|
||||
|
||||
async function dangerous(kind, dataset) {
|
||||
const date = ($("rel-date") && $("rel-date").value) || "";
|
||||
const ds = dataset || prompt("数据集(daily/valuation/moneyflow/auction/stocks→A组整批;index_daily→B组;或 reference)", "daily");
|
||||
if (!ds) return;
|
||||
const password = prompt("二次确认:输入管理密码");
|
||||
if (!password) return;
|
||||
const confirmWord = `${ds}:${date}`;
|
||||
const typed = prompt(`请输入确认词:${confirmWord}`);
|
||||
const path = kind === "rollback" ? "/admin/api/rollback" : "/admin/api/backfill";
|
||||
await api(path, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ dataset: ds, trade_date: date, password, confirm: typed }),
|
||||
});
|
||||
render();
|
||||
}
|
||||
|
||||
boot();
|
||||
@@ -0,0 +1,53 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>xiaobai-datahub 管理后台</title>
|
||||
<link rel="stylesheet" href="/admin/styles.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<section id="login-view" class="panel auth-panel">
|
||||
<h1>数据中枢</h1>
|
||||
<p class="muted">内网管理后台,用于查看源状态、调度和盘后发布批次。</p>
|
||||
<form id="login-form">
|
||||
<label>账号 <input name="username" value="hub_admin" autocomplete="username" /></label>
|
||||
<label>密码 <input name="password" type="password" autocomplete="current-password" /></label>
|
||||
<button type="submit">登录</button>
|
||||
<p id="login-error" class="error" hidden></p>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section id="change-view" class="panel auth-panel" hidden>
|
||||
<h1>修改初始密码</h1>
|
||||
<form id="change-form">
|
||||
<label>当前密码 <input name="current" type="password" /></label>
|
||||
<label>新密码(至少 8 位) <input name="new_password" type="password" /></label>
|
||||
<button type="submit">保存并继续</button>
|
||||
<p id="change-error" class="error" hidden></p>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section id="shell" hidden>
|
||||
<header class="top">
|
||||
<strong>xiaobai-datahub</strong>
|
||||
<span id="phase" class="pill"></span>
|
||||
<span id="who" class="muted"></span>
|
||||
<button type="button" id="theme-btn" class="ghost">夜间</button>
|
||||
<button type="button" id="logout-btn" class="ghost">退出</button>
|
||||
</header>
|
||||
<nav>
|
||||
<button data-page="overview" class="active">总览</button>
|
||||
<button data-page="sources">数据源</button>
|
||||
<button data-page="jobs">调度任务</button>
|
||||
<button data-page="release">盘后发布</button>
|
||||
<button data-page="datasets">数据集</button>
|
||||
<button data-page="audit">审计</button>
|
||||
</nav>
|
||||
<main id="page"></main>
|
||||
</section>
|
||||
</div>
|
||||
<script src="/admin/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,51 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--bg: #f4f5f7;
|
||||
--surface: #ffffff;
|
||||
--text: #1f2329;
|
||||
--muted: #646a73;
|
||||
--line: #dee0e3;
|
||||
--action: #3370ff;
|
||||
--danger: #e04536;
|
||||
--ok: #16a34a;
|
||||
--warn: #b45309;
|
||||
--radius: 8px;
|
||||
--pad: 16px;
|
||||
font-family: "Segoe UI", "PingFang SC", "Noto Sans SC", sans-serif;
|
||||
}
|
||||
:root[data-theme="night"] {
|
||||
color-scheme: dark;
|
||||
--bg: #111318;
|
||||
--surface: #1b1e24;
|
||||
--text: #e8eaed;
|
||||
--muted: #9aa0a6;
|
||||
--line: #2a2f38;
|
||||
--action: #5b8cff;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; background: var(--bg); color: var(--text); }
|
||||
.panel, header.top, nav, main { background: var(--surface); }
|
||||
.auth-panel { max-width: 420px; margin: 12vh auto; padding: 28px; border-radius: var(--radius); border: 1px solid var(--line); }
|
||||
label { display: block; margin: 12px 0; }
|
||||
input, select { width: 100%; padding: 8px 10px; border: 1px solid var(--line); border-radius: 4px; background: var(--bg); color: var(--text); }
|
||||
button { background: var(--action); color: #fff; border: 0; border-radius: 4px; padding: 8px 14px; cursor: pointer; }
|
||||
button.ghost { background: transparent; color: var(--text); border: 1px solid var(--line); }
|
||||
button.danger { background: var(--danger); }
|
||||
.muted { color: var(--muted); }
|
||||
.error { color: var(--danger); }
|
||||
.top { display: flex; gap: 12px; align-items: center; padding: 10px var(--pad); border-bottom: 1px solid var(--line); }
|
||||
nav { display: flex; gap: 4px; padding: 8px var(--pad); border-bottom: 1px solid var(--line); }
|
||||
nav button { background: transparent; color: var(--muted); }
|
||||
nav button.active { color: var(--action); background: transparent; font-weight: 600; }
|
||||
main { padding: var(--pad); min-height: calc(100vh - 96px); }
|
||||
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin-bottom: 16px; }
|
||||
.card { border: 1px solid var(--line); border-radius: var(--radius); padding: 12px; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||||
th, td { text-align: left; padding: 8px; border-bottom: 1px solid var(--line); vertical-align: top; }
|
||||
.pill { font-size: 12px; padding: 2px 8px; border-radius: 999px; border: 1px solid var(--line); }
|
||||
.ok { color: var(--ok); }
|
||||
.warn { color: var(--warn); }
|
||||
.fail { color: var(--danger); }
|
||||
.toolbar { display: flex; gap: 8px; flex-wrap: wrap; margin: 12px 0; align-items: end; }
|
||||
.toolbar label { margin: 0; }
|
||||
dialog { border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface); color: var(--text); padding: 20px; }
|
||||
@@ -0,0 +1,39 @@
|
||||
services:
|
||||
xiaobai-datahub:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: xiaobai-datahub:local
|
||||
container_name: xiaobai-datahub
|
||||
ports:
|
||||
- "0.0.0.0:8766:8766/tcp"
|
||||
env_file:
|
||||
- ./.env
|
||||
environment:
|
||||
DATAHUB_ENCRYPTION_KEY: "${DATAHUB_ENCRYPTION_KEY:?DATAHUB_ENCRYPTION_KEY must be set}"
|
||||
DATAHUB_TOKEN: "${DATAHUB_TOKEN:?DATAHUB_TOKEN must be set}"
|
||||
DATAHUB_ADMIN_PASSWORD: "${DATAHUB_ADMIN_PASSWORD:?DATAHUB_ADMIN_PASSWORD must be set}"
|
||||
TUSHARE_TOKEN: "${TUSHARE_TOKEN:-}"
|
||||
DATAHUB_DB_PATH: /app/data/datahub.db
|
||||
DATAHUB_BACKUP_DIR: /app/data/backups
|
||||
TZ: Asia/Shanghai
|
||||
PYTHONUTF8: "1"
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ./data
|
||||
target: /app/data
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=64m,mode=1777
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
stop_grace_period: 30s
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"daily_row_ratio": 0.98,
|
||||
"null_rate_max": 0.01,
|
||||
"cross_check_price_deviation": 0.03,
|
||||
"cross_check_outlier_ratio": 0.05,
|
||||
"index_price_deviation": 0.005,
|
||||
"max_publish_attempts": 5,
|
||||
"staging_retain_days": 14,
|
||||
"job_run_retain_days": 90,
|
||||
"backup_retain": 14,
|
||||
"publication_generations": 3,
|
||||
"tushare_rate_per_minute": 300,
|
||||
"list_limit_default": 5000,
|
||||
"list_limit_max": 5000,
|
||||
"calendar_start": "20160101",
|
||||
"index_history_trading_days": 260,
|
||||
"eod_retry_start": "15:15",
|
||||
"eod_retry_interval_minutes": 30,
|
||||
"eod_retry_cutoff": "23:30",
|
||||
"revision_review_datasets": ["valuation"],
|
||||
"revision_review_start": "20:00",
|
||||
"revision_review_interval_minutes": 30,
|
||||
"revision_review_cutoff": "23:20",
|
||||
"moneyflow_history_trading_days": 60,
|
||||
"stocks_refresh_times": [
|
||||
"20:00",
|
||||
"23:10"
|
||||
],
|
||||
"cross_gates": [
|
||||
{
|
||||
"left": "daily",
|
||||
"right": "valuation",
|
||||
"min_key_overlap": 0.98
|
||||
},
|
||||
{
|
||||
"left": "daily",
|
||||
"right": "moneyflow",
|
||||
"min_key_overlap": 0.98
|
||||
}
|
||||
],
|
||||
"field_gates": {
|
||||
"valuation": {
|
||||
"fields": [
|
||||
"turnover_rate",
|
||||
"volume_ratio",
|
||||
"total_mv",
|
||||
"circ_mv",
|
||||
"pe_ttm",
|
||||
"pb",
|
||||
"ps_ttm",
|
||||
"dv_ttm"
|
||||
],
|
||||
"min_nonnull_rate": 0.9,
|
||||
"min_nonnull_rate_by_field": {
|
||||
"pe_ttm": 0.5,
|
||||
"dv_ttm": 0.3
|
||||
},
|
||||
"max_nonnull_drop_vs_prev": 0.15,
|
||||
"max_nonfinite_rate": 0.01
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
"""xiaobai-datahub: independent market-data service for xiaobai-review."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
SCHEMA_VERSION = 1
|
||||
@@ -0,0 +1,4 @@
|
||||
from datahub.cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,15 @@
|
||||
from datahub.adapters.akshare import ADAPTER as akshare
|
||||
from datahub.adapters.eastmoney import EastmoneyAdapter
|
||||
from datahub.adapters.ifind import ADAPTER as ifind
|
||||
from datahub.adapters.tencent import TencentAdapter
|
||||
from datahub.adapters.ths import ADAPTER as ths
|
||||
from datahub.adapters.xgb import ADAPTER as xgb
|
||||
|
||||
RESERVED = {
|
||||
"eastmoney": EastmoneyAdapter(),
|
||||
"tencent": TencentAdapter(),
|
||||
"ths": ths,
|
||||
"xgb": xgb,
|
||||
"akshare": akshare,
|
||||
"ifind": ifind,
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
from datahub.adapters.base import ReservedAdapter
|
||||
|
||||
ADAPTER = ReservedAdapter("akshare")
|
||||
@@ -0,0 +1,47 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
|
||||
|
||||
class AdapterError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class MarketAdapter(ABC):
|
||||
"""Uniform adapter: probe / fetch / normalize. Realtime adapters may be stubs in P0."""
|
||||
|
||||
name: str = "base"
|
||||
|
||||
@abstractmethod
|
||||
def probe(self) -> dict[str, Any]:
|
||||
"""Liveness check. Must not leak credentials."""
|
||||
|
||||
@abstractmethod
|
||||
def fetch(self, dataset: str, params: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""Return provider-native rows (pre-canonical)."""
|
||||
|
||||
@abstractmethod
|
||||
def normalize(self, dataset: str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Map provider-native rows onto hub canonical fields."""
|
||||
|
||||
|
||||
class ReservedAdapter(MarketAdapter):
|
||||
"""Placeholder for a later free/licensed source. Does not pull data in P0."""
|
||||
|
||||
def __init__(self, name: str) -> None:
|
||||
self.name = name
|
||||
|
||||
def probe(self) -> dict[str, Any]:
|
||||
return {
|
||||
"provider": self.name,
|
||||
"configured": False,
|
||||
"state": "reserved",
|
||||
"message": "适配器位已预留,本阶段不接入",
|
||||
}
|
||||
|
||||
def fetch(self, dataset: str, params: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
raise AdapterError(f"{self.name} 适配器本阶段未接入")
|
||||
|
||||
def normalize(self, dataset: str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return []
|
||||
@@ -0,0 +1,382 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from datahub.adapters.base import AdapterError, MarketAdapter
|
||||
from datahub.numbers import finite_number, round4
|
||||
|
||||
EASTMONEY_INDEX_URL = "https://push2.eastmoney.com/api/qt/ulist.np/get"
|
||||
EASTMONEY_CLIST_URL = "https://push2.eastmoney.com/api/qt/clist/get"
|
||||
EASTMONEY_A_SHARE_BOARDS = (
|
||||
"m:0+t:6",
|
||||
"m:0+t:80",
|
||||
"m:1+t:2",
|
||||
"m:1+t:23",
|
||||
"m:0+t:81",
|
||||
)
|
||||
EASTMONEY_QUOTE_FIELDS = "f12,f13,f14,f2,f3,f4,f5,f6,f15,f16,f17,f18,f8,f124"
|
||||
EASTMONEY_MARKET_PAGE_SIZE = 100
|
||||
TRENDS_URL = "https://push2delay.eastmoney.com/api/qt/stock/trends2/get"
|
||||
HIS_TRENDS_URL = "https://push2his.eastmoney.com/api/qt/stock/trends2/get"
|
||||
BROWSER_UA = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
|
||||
)
|
||||
INDEX_SECIDS = {
|
||||
"000001.SH": "1.000001",
|
||||
"399001.SZ": "0.399001",
|
||||
"399006.SZ": "0.399006",
|
||||
}
|
||||
|
||||
|
||||
class EastmoneyAdapter(MarketAdapter):
|
||||
name = "eastmoney"
|
||||
|
||||
def __init__(self, timeout: int = 8) -> None:
|
||||
self.timeout = timeout
|
||||
|
||||
def probe(self) -> dict[str, Any]:
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
rows = self.fetch_indices()
|
||||
state = "ok" if len(rows) == 3 else "empty"
|
||||
except AdapterError as exc:
|
||||
return {
|
||||
"provider": self.name,
|
||||
"configured": True,
|
||||
"state": "error",
|
||||
"message": str(exc),
|
||||
"latency_ms": round((time.perf_counter() - started) * 1000),
|
||||
}
|
||||
return {
|
||||
"provider": self.name,
|
||||
"configured": True,
|
||||
"state": state,
|
||||
"latency_ms": round((time.perf_counter() - started) * 1000),
|
||||
}
|
||||
|
||||
def fetch(self, dataset: str, params: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
if dataset in {"indexes_quotes", "index_quotes"}:
|
||||
return self.fetch_indices()
|
||||
if dataset in {"quotes", "quotes_latest"}:
|
||||
codes = params.get("codes") or []
|
||||
if isinstance(codes, str):
|
||||
codes = [item.strip() for item in codes.split(",") if item.strip()]
|
||||
if codes:
|
||||
return self.fetch_quotes(list(codes))
|
||||
return self.fetch_market_quotes()
|
||||
if dataset in {"quotes_market", "market_quotes"}:
|
||||
return self.fetch_market_quotes()
|
||||
raise AdapterError(f"{self.name} unsupported dataset: {dataset}")
|
||||
|
||||
def normalize(self, dataset: str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return list(rows)
|
||||
|
||||
def fetch_indices(self) -> list[dict[str, Any]]:
|
||||
payload = self._get_json(
|
||||
EASTMONEY_INDEX_URL,
|
||||
{
|
||||
"secids": "1.000001,0.399001,0.399006",
|
||||
"fltt": "2",
|
||||
"invt": "2",
|
||||
"fields": "f12,f14,f2,f3,f4,f15,f16,f17,f18,f6,f124",
|
||||
},
|
||||
referer="https://quote.eastmoney.com/",
|
||||
)
|
||||
rows = list((payload.get("data") or {}).get("diff") or [])
|
||||
result = []
|
||||
for row in rows:
|
||||
code = str(row.get("f12") or "")
|
||||
if code not in {"000001", "399001", "399006"}:
|
||||
continue
|
||||
epoch = int(finite_number(row.get("f124")) or 0)
|
||||
ts_code = f"{code}.SH" if code.startswith("0") and code == "000001" else f"{code}.SZ"
|
||||
if code == "000001":
|
||||
ts_code = "000001.SH"
|
||||
result.append(
|
||||
{
|
||||
"ts_code": ts_code,
|
||||
"code": code,
|
||||
"name": row.get("f14") or code,
|
||||
"price": round4(finite_number(row.get("f2"))),
|
||||
"pct_chg": round4(finite_number(row.get("f3"))),
|
||||
"change_amount": round4(finite_number(row.get("f4"))),
|
||||
"open": round4(finite_number(row.get("f17"))),
|
||||
"high": round4(finite_number(row.get("f15"))),
|
||||
"low": round4(finite_number(row.get("f16"))),
|
||||
"previous_close": round4(finite_number(row.get("f18"))),
|
||||
"amount": round4(finite_number(row.get("f6"))),
|
||||
"quote_time_epoch": epoch,
|
||||
"quote_time": (
|
||||
datetime.fromtimestamp(epoch).astimezone().isoformat(timespec="seconds")
|
||||
if epoch
|
||||
else ""
|
||||
),
|
||||
"source": "eastmoney_push2",
|
||||
}
|
||||
)
|
||||
if len(result) != 3:
|
||||
raise AdapterError(f"Eastmoney returned {len(result)}/3 indices")
|
||||
return result
|
||||
|
||||
def fetch_quotes(self, codes: list[str]) -> list[dict[str, Any]]:
|
||||
# Eastmoney clist does not accept arbitrary code lists well; use ulist.np for batches.
|
||||
secids = []
|
||||
for code in codes:
|
||||
ts = str(code or "").upper()
|
||||
symbol = ts.split(".")[0]
|
||||
if ts.endswith(".SH") or symbol.startswith(("5", "6", "9")):
|
||||
secids.append(f"1.{symbol}")
|
||||
else:
|
||||
secids.append(f"0.{symbol}")
|
||||
if not secids:
|
||||
return []
|
||||
payload = self._get_json(
|
||||
EASTMONEY_INDEX_URL,
|
||||
{
|
||||
"secids": ",".join(secids[:60]),
|
||||
"fltt": "2",
|
||||
"invt": "2",
|
||||
"fields": "f12,f14,f2,f3,f4,f15,f16,f17,f18,f5,f6,f8,f124",
|
||||
},
|
||||
referer="https://quote.eastmoney.com/",
|
||||
)
|
||||
rows = list((payload.get("data") or {}).get("diff") or [])
|
||||
result = []
|
||||
for row in rows:
|
||||
symbol = str(row.get("f12") or "")
|
||||
if not symbol:
|
||||
continue
|
||||
ts_code = f"{symbol}.SH" if symbol.startswith(("5", "6", "9")) else f"{symbol}.SZ"
|
||||
epoch = int(finite_number(row.get("f124")) or 0)
|
||||
result.append(
|
||||
{
|
||||
"ts_code": ts_code,
|
||||
"name": row.get("f14") or symbol,
|
||||
"price": round4(finite_number(row.get("f2"))),
|
||||
"pct_chg": round4(finite_number(row.get("f3"))),
|
||||
"change_amount": round4(finite_number(row.get("f4"))),
|
||||
"open": round4(finite_number(row.get("f17"))),
|
||||
"high": round4(finite_number(row.get("f15"))),
|
||||
"low": round4(finite_number(row.get("f16"))),
|
||||
"previous_close": round4(finite_number(row.get("f18"))),
|
||||
"volume": round4(finite_number(row.get("f5"))),
|
||||
"amount": round4(finite_number(row.get("f6"))),
|
||||
"turnover_rate": round4(finite_number(row.get("f8"))),
|
||||
"quote_time_epoch": epoch,
|
||||
"quote_time": (
|
||||
datetime.fromtimestamp(epoch).astimezone().isoformat(timespec="seconds")
|
||||
if epoch
|
||||
else ""
|
||||
),
|
||||
"source": "eastmoney_push2",
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
def fetch_market_quotes(self) -> list[dict[str, Any]]:
|
||||
rows: list[dict[str, Any]] = []
|
||||
board_errors: list[str] = []
|
||||
for board in EASTMONEY_A_SHARE_BOARDS:
|
||||
try:
|
||||
rows.extend(self._board_quotes(board))
|
||||
except Exception as exc:
|
||||
board_errors.append(f"{board}:{exc}")
|
||||
quotes: list[dict[str, Any]] = []
|
||||
seen: set[str] = set()
|
||||
for row in rows:
|
||||
quote = _normalize_market_quote(row)
|
||||
ts_code = str((quote or {}).get("ts_code") or "")
|
||||
if not quote or ts_code in seen:
|
||||
continue
|
||||
seen.add(ts_code)
|
||||
quotes.append(quote)
|
||||
if len(quotes) < 200:
|
||||
detail = f";{'; '.join(board_errors)}" if board_errors else ""
|
||||
raise AdapterError(f"Eastmoney market snapshot too small: {len(quotes)}{detail}")
|
||||
return quotes
|
||||
|
||||
def _board_quotes(self, board: str) -> list[dict[str, Any]]:
|
||||
first = self._market_page(board, 1)
|
||||
data = first.get("data") or {}
|
||||
rows = list(data.get("diff") or [])
|
||||
total = int(finite_number(data.get("total")) or 0)
|
||||
page_count = 1
|
||||
if total > 0:
|
||||
page_count = max(1, (total + EASTMONEY_MARKET_PAGE_SIZE - 1) // EASTMONEY_MARKET_PAGE_SIZE)
|
||||
for page in range(2, min(page_count, 40) + 1):
|
||||
payload = self._market_page(board, page)
|
||||
rows.extend(list((payload.get("data") or {}).get("diff") or []))
|
||||
return rows
|
||||
|
||||
def _market_page(self, board: str, page: int) -> dict[str, Any]:
|
||||
return self._get_json(
|
||||
EASTMONEY_CLIST_URL,
|
||||
{
|
||||
"pn": str(page),
|
||||
"pz": str(EASTMONEY_MARKET_PAGE_SIZE),
|
||||
"po": "1",
|
||||
"np": "1",
|
||||
"fltt": "2",
|
||||
"invt": "2",
|
||||
"fid": "f12",
|
||||
"fs": board,
|
||||
"fields": EASTMONEY_QUOTE_FIELDS,
|
||||
},
|
||||
referer="https://quote.eastmoney.com/center/gridlist.html",
|
||||
)
|
||||
|
||||
def fetch_intraday(self, ts_code: str, date: str = "") -> dict[str, Any]:
|
||||
code = str(ts_code or "").upper()
|
||||
if code in INDEX_SECIDS:
|
||||
secid = INDEX_SECIDS[code]
|
||||
entity = "index"
|
||||
identifier = code
|
||||
else:
|
||||
symbol = code.split(".")[0]
|
||||
market = "1" if symbol.startswith(("5", "6", "9")) else "0"
|
||||
secid = f"{market}.{symbol}"
|
||||
entity = "stock"
|
||||
identifier = symbol
|
||||
params = {
|
||||
"secid": secid,
|
||||
"fields1": "f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13",
|
||||
"fields2": "f51,f52,f53,f54,f55,f56,f57,f58",
|
||||
"iscr": "0",
|
||||
}
|
||||
data: dict[str, Any] = {}
|
||||
points: list[dict[str, Any]] = []
|
||||
last_error: Exception | None = None
|
||||
for url, ndays in ((TRENDS_URL, "1"), (TRENDS_URL, "5"), (HIS_TRENDS_URL, "5")):
|
||||
try:
|
||||
payload = self._get_json(
|
||||
url,
|
||||
{**params, "ndays": ndays},
|
||||
referer="https://quote.eastmoney.com/",
|
||||
)
|
||||
except AdapterError as exc:
|
||||
last_error = exc
|
||||
continue
|
||||
data = payload.get("data") or {}
|
||||
parsed = [point for raw in data.get("trends") or [] if (point := _parse_trend(raw))]
|
||||
points = _preferred_session(parsed, date)
|
||||
if points:
|
||||
break
|
||||
if not points:
|
||||
raise AdapterError("No intraday chart data returned") from last_error
|
||||
return {
|
||||
"entity_type": entity,
|
||||
"identifier": identifier,
|
||||
"ts_code": code if "." in code else f"{identifier}.{'SH' if identifier.startswith(('5','6','9')) else 'SZ'}",
|
||||
"name": str(data.get("name") or ""),
|
||||
"code": str(data.get("code") or identifier),
|
||||
"trade_date": points[-1]["date"],
|
||||
"previous_close": round4(finite_number(data.get("preClose"))),
|
||||
"points": points,
|
||||
"source": "eastmoney_trends2",
|
||||
}
|
||||
|
||||
def _get_json(self, url: str, params: dict[str, str], referer: str) -> dict[str, Any]:
|
||||
request_url = f"{url}?{urllib.parse.urlencode(params)}"
|
||||
request = urllib.request.Request(
|
||||
request_url,
|
||||
headers={
|
||||
"Accept": "application/json,text/plain,*/*",
|
||||
"User-Agent": BROWSER_UA,
|
||||
"Referer": referer,
|
||||
},
|
||||
method="GET",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
||||
return json.loads(response.read().decode("utf-8"))
|
||||
except Exception as exc:
|
||||
raise AdapterError(f"eastmoney request failed: {exc}") from exc
|
||||
|
||||
|
||||
def _preferred_session(points: list[dict[str, Any]], preferred_date: str = "") -> list[dict[str, Any]]:
|
||||
if not points:
|
||||
return []
|
||||
want = ""
|
||||
digits = str(preferred_date or "").replace("-", "")[:8]
|
||||
if len(digits) == 8 and digits.isdigit():
|
||||
want = f"{digits[:4]}-{digits[4:6]}-{digits[6:8]}"
|
||||
if want:
|
||||
matched = [point for point in points if str(point.get("date") or "") == want]
|
||||
if matched:
|
||||
return matched
|
||||
latest = max(str(point.get("date") or "") for point in points)
|
||||
if not latest:
|
||||
return points
|
||||
return [point for point in points if str(point.get("date") or "") == latest]
|
||||
|
||||
|
||||
def _normalize_market_quote(row: dict[str, Any]) -> dict[str, Any] | None:
|
||||
symbol = str(row.get("f12") or "").strip()
|
||||
if not symbol.isdigit() or len(symbol) != 6:
|
||||
return None
|
||||
close = round4(finite_number(row.get("f2")))
|
||||
previous_close = round4(finite_number(row.get("f18")))
|
||||
if close <= 0 or previous_close <= 0:
|
||||
return None
|
||||
market = int(finite_number(row.get("f13")) or 0)
|
||||
if market == 1 or symbol.startswith(("5", "6", "9")):
|
||||
ts_code = f"{symbol}.SH"
|
||||
elif symbol.startswith(("4", "8")):
|
||||
ts_code = f"{symbol}.BJ"
|
||||
else:
|
||||
ts_code = f"{symbol}.SZ"
|
||||
epoch = int(finite_number(row.get("f124")) or 0)
|
||||
quote_date = ""
|
||||
if epoch > 0:
|
||||
quote_date = datetime.fromtimestamp(epoch).astimezone().strftime("%Y%m%d")
|
||||
return {
|
||||
"ts_code": ts_code,
|
||||
"name": row.get("f14") or symbol,
|
||||
"pre_close": previous_close,
|
||||
"previous_close": previous_close,
|
||||
"open": round4(finite_number(row.get("f17"))),
|
||||
"high": round4(finite_number(row.get("f15"))),
|
||||
"low": round4(finite_number(row.get("f16"))),
|
||||
"close": close,
|
||||
"price": close,
|
||||
"pct_chg": round4(finite_number(row.get("f3"))),
|
||||
"vol": round4(finite_number(row.get("f5")) * 100),
|
||||
"volume": round4(finite_number(row.get("f5")) * 100),
|
||||
"amount": round4(finite_number(row.get("f6"))),
|
||||
"quote_date": quote_date,
|
||||
"quote_time_epoch": epoch,
|
||||
"source": "eastmoney_clist",
|
||||
}
|
||||
|
||||
|
||||
def _parse_trend(raw: Any) -> dict[str, Any] | None:
|
||||
text = str(raw or "")
|
||||
parts = text.split(",")
|
||||
if len(parts) < 8:
|
||||
return None
|
||||
stamp = parts[0]
|
||||
try:
|
||||
when = datetime.strptime(stamp, "%Y-%m-%d %H:%M")
|
||||
except ValueError:
|
||||
return None
|
||||
close = round4(finite_number(parts[2]))
|
||||
if close <= 0:
|
||||
return None
|
||||
return {
|
||||
"time": when.strftime("%H:%M"),
|
||||
"date": when.strftime("%Y-%m-%d"),
|
||||
"open": round4(finite_number(parts[1])),
|
||||
"close": close,
|
||||
"high": round4(finite_number(parts[3])),
|
||||
"low": round4(finite_number(parts[4])),
|
||||
"avg_price": round4(finite_number(parts[7] if len(parts) > 7 else parts[2])),
|
||||
"volume": round4(finite_number(parts[5])),
|
||||
"amount": round4(finite_number(parts[6])),
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
from datahub.adapters.base import ReservedAdapter
|
||||
|
||||
ADAPTER = ReservedAdapter("ifind")
|
||||
@@ -0,0 +1,99 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from datahub.adapters.base import AdapterError, MarketAdapter
|
||||
from datahub.numbers import finite_number, round4
|
||||
|
||||
TENCENT_INDEX_URL = "https://qt.gtimg.cn/q=sh000001,sz399001,sz399006"
|
||||
BROWSER_UA = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
|
||||
)
|
||||
|
||||
|
||||
class TencentAdapter(MarketAdapter):
|
||||
name = "tencent"
|
||||
|
||||
def __init__(self, timeout: int = 8) -> None:
|
||||
self.timeout = timeout
|
||||
|
||||
def probe(self) -> dict[str, Any]:
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
rows = self.fetch_indices()
|
||||
state = "ok" if len(rows) == 3 else "empty"
|
||||
except AdapterError as exc:
|
||||
return {
|
||||
"provider": self.name,
|
||||
"configured": True,
|
||||
"state": "error",
|
||||
"message": str(exc),
|
||||
"latency_ms": round((time.perf_counter() - started) * 1000),
|
||||
}
|
||||
return {
|
||||
"provider": self.name,
|
||||
"configured": True,
|
||||
"state": state,
|
||||
"latency_ms": round((time.perf_counter() - started) * 1000),
|
||||
}
|
||||
|
||||
def fetch(self, dataset: str, params: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
if dataset in {"indexes_quotes", "index_quotes"}:
|
||||
return self.fetch_indices()
|
||||
raise AdapterError(f"{self.name} unsupported dataset: {dataset}")
|
||||
|
||||
def normalize(self, dataset: str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return list(rows)
|
||||
|
||||
def fetch_indices(self) -> list[dict[str, Any]]:
|
||||
request = urllib.request.Request(
|
||||
TENCENT_INDEX_URL,
|
||||
headers={"User-Agent": BROWSER_UA, "Referer": "https://gu.qq.com/"},
|
||||
method="GET",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
||||
raw = response.read().decode("gb18030", errors="ignore")
|
||||
except Exception as exc:
|
||||
raise AdapterError(f"tencent request failed: {exc}") from exc
|
||||
result = []
|
||||
for line in raw.splitlines():
|
||||
if '="' not in line:
|
||||
continue
|
||||
fields = line.split('="', 1)[1].rsplit('";', 1)[0].split("~")
|
||||
if len(fields) < 38:
|
||||
continue
|
||||
code = fields[2]
|
||||
if code not in {"000001", "399001", "399006"}:
|
||||
continue
|
||||
try:
|
||||
quote_time = datetime.strptime(fields[30], "%Y%m%d%H%M%S").astimezone()
|
||||
except ValueError as exc:
|
||||
raise AdapterError(f"Tencent invalid quote time for {code}") from exc
|
||||
ts_code = "000001.SH" if code == "000001" else f"{code}.SZ"
|
||||
result.append(
|
||||
{
|
||||
"ts_code": ts_code,
|
||||
"code": code,
|
||||
"name": fields[1] or code,
|
||||
"price": round4(finite_number(fields[3])),
|
||||
"pct_chg": round4(finite_number(fields[32])),
|
||||
"change_amount": round4(finite_number(fields[31])),
|
||||
"open": round4(finite_number(fields[5])),
|
||||
"high": round4(finite_number(fields[33])),
|
||||
"low": round4(finite_number(fields[34])),
|
||||
"previous_close": round4(finite_number(fields[4])),
|
||||
"amount": round4(finite_number(fields[37]) * 10000),
|
||||
"quote_time_epoch": int(quote_time.timestamp()),
|
||||
"quote_time": quote_time.isoformat(timespec="seconds"),
|
||||
"source": "tencent_qt",
|
||||
}
|
||||
)
|
||||
if len(result) != 3:
|
||||
raise AdapterError(f"Tencent returned {len(result)}/3 indices")
|
||||
return result
|
||||
@@ -0,0 +1,3 @@
|
||||
from datahub.adapters.base import ReservedAdapter
|
||||
|
||||
ADAPTER = ReservedAdapter("ths")
|
||||
@@ -0,0 +1,256 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import Any, Callable
|
||||
|
||||
from datahub.adapters.base import AdapterError, MarketAdapter
|
||||
from datahub.normalize import (
|
||||
normalize_auction,
|
||||
normalize_calendar,
|
||||
normalize_daily,
|
||||
normalize_dragon_tiger,
|
||||
normalize_index_daily,
|
||||
normalize_limit_event,
|
||||
normalize_moneyflow,
|
||||
normalize_popularity,
|
||||
normalize_sector_daily,
|
||||
normalize_stock,
|
||||
normalize_valuation,
|
||||
)
|
||||
|
||||
TUSHARE_URL = "http://api.tushare.pro"
|
||||
|
||||
TUSHARE_FIELDS = {
|
||||
"trade_cal": "exchange,cal_date,is_open,pretrade_date",
|
||||
"stock_basic": "ts_code,symbol,name,area,industry,market,list_status,list_date",
|
||||
"daily": "ts_code,trade_date,open,high,low,close,pct_chg,vol,amount",
|
||||
"daily_basic": "ts_code,trade_date,turnover_rate,volume_ratio,total_mv,circ_mv,pe_ttm,pb,ps_ttm,dv_ttm",
|
||||
"adj_factor": "ts_code,trade_date,adj_factor",
|
||||
"index_daily": "ts_code,trade_date,open,high,low,close,pct_chg,vol,amount",
|
||||
"moneyflow": (
|
||||
"ts_code,trade_date,buy_sm_amount,sell_sm_amount,buy_md_amount,sell_md_amount,"
|
||||
"buy_lg_amount,sell_lg_amount,buy_elg_amount,sell_elg_amount,net_mf_amount"
|
||||
),
|
||||
"stk_auction": "ts_code,trade_date,vol,price,amount,pre_close,turnover_rate,volume_ratio,float_share",
|
||||
"limit_list_d": (
|
||||
"trade_date,ts_code,industry,name,close,pct_chg,amount,limit_amount,"
|
||||
"float_mv,total_mv,turnover_ratio,fd_amount,first_time,last_time,"
|
||||
"open_times,up_stat,limit_times,limit_type"
|
||||
),
|
||||
"ths_hot": "ts_code,ts_name,hot,rank,pct_change,current_price,concept,data_type,trade_date",
|
||||
"dc_hot": "ts_code,ts_name,rank,pct_change,current_price,hot,concept,data_type,trade_date",
|
||||
"hm_detail": "trade_date,ts_code,ts_name,buy_amount,sell_amount,net_amount,hm_name,hm_orgs,tag",
|
||||
"hm_list": "name,desc,orgs",
|
||||
"top_list": "trade_date,ts_code,name,pct_change,reason",
|
||||
"top_inst": "trade_date,ts_code,exalter,buy,buy_rate,sell,sell_rate,net_buy,side,reason",
|
||||
"ths_index": "ts_code,name,count,exchange,list_date,type",
|
||||
"ths_daily": "ts_code,trade_date,open,high,low,close,pre_close,pct_change,vol,turnover_rate",
|
||||
"dc_index": "ts_code,trade_date,name,open,high,low,close,pre_close,pct_change,vol,amount,turnover_rate",
|
||||
"sw_daily": "ts_code,trade_date,name,open,high,low,close,pct_change,vol,amount",
|
||||
}
|
||||
|
||||
DATASET_API = {
|
||||
"calendar": "trade_cal",
|
||||
"stocks": "stock_basic",
|
||||
"daily": "daily",
|
||||
"valuation": "daily_basic",
|
||||
"adj_factor": "adj_factor",
|
||||
"index_daily": "index_daily",
|
||||
"moneyflow": "moneyflow",
|
||||
"auction": "stk_auction",
|
||||
"limit_events": "limit_list_d",
|
||||
"popularity": "ths_hot",
|
||||
"dragon_tiger": "hm_detail",
|
||||
"sector_daily": "ths_daily",
|
||||
}
|
||||
|
||||
WEBSITE_INDEX_CODES = ("000001.SH", "399001.SZ", "399006.SZ", "000300.SH")
|
||||
DEFAULT_INDEX_CODES = WEBSITE_INDEX_CODES
|
||||
LIMIT_TYPES = ("U", "D", "Z")
|
||||
|
||||
|
||||
class TushareAdapter(MarketAdapter):
|
||||
name = "tushare"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
token: str,
|
||||
timeout: int = 30,
|
||||
transport: Callable[[str, dict[str, Any], str], list[dict[str, Any]]] | None = None,
|
||||
) -> None:
|
||||
self.token = token
|
||||
self.timeout = timeout
|
||||
self._transport = transport
|
||||
|
||||
def probe(self) -> dict[str, Any]:
|
||||
if not self.token:
|
||||
return {"provider": self.name, "configured": False, "state": "unconfigured"}
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
rows = self.fetch("calendar", {"exchange": "SSE", "start_date": "20200102", "end_date": "20200102"})
|
||||
except AdapterError as exc:
|
||||
return {
|
||||
"provider": self.name,
|
||||
"configured": True,
|
||||
"state": "error",
|
||||
"message": str(exc),
|
||||
"latency_ms": round((time.perf_counter() - started) * 1000),
|
||||
}
|
||||
return {
|
||||
"provider": self.name,
|
||||
"configured": True,
|
||||
"state": "ok" if rows else "empty",
|
||||
"latency_ms": round((time.perf_counter() - started) * 1000),
|
||||
}
|
||||
|
||||
def fetch(self, dataset: str, params: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
if dataset == "limit_events":
|
||||
return self.fetch_limit_events(str(params.get("trade_date") or ""))
|
||||
if dataset == "popularity":
|
||||
return self.fetch_popularity(str(params.get("trade_date") or ""))
|
||||
if dataset == "dragon_tiger":
|
||||
return self.fetch_dragon_tiger(str(params.get("trade_date") or ""))
|
||||
if dataset == "sector_daily":
|
||||
return self.fetch_sector_daily(str(params.get("trade_date") or ""))
|
||||
api_name = DATASET_API.get(dataset, dataset)
|
||||
fields = TUSHARE_FIELDS.get(api_name, "")
|
||||
query_params = dict(params)
|
||||
if api_name == "stock_basic" and "list_status" not in query_params:
|
||||
query_params["list_status"] = "L"
|
||||
if api_name == "trade_cal" and "exchange" not in query_params:
|
||||
query_params["exchange"] = "SSE"
|
||||
if api_name == "index_daily" and "ts_code" not in query_params:
|
||||
query_params.setdefault("ts_code", DEFAULT_INDEX_CODES[0])
|
||||
return self._query(api_name, query_params, fields)
|
||||
|
||||
def fetch_limit_events(self, trade_date: str) -> list[dict[str, Any]]:
|
||||
rows: list[dict[str, Any]] = []
|
||||
for limit_type in LIMIT_TYPES:
|
||||
part = self._query(
|
||||
"limit_list_d",
|
||||
{"trade_date": trade_date, "limit_type": limit_type},
|
||||
TUSHARE_FIELDS["limit_list_d"],
|
||||
)
|
||||
for row in part:
|
||||
row = dict(row)
|
||||
row.setdefault("limit_type", limit_type)
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
def fetch_popularity(self, trade_date: str) -> list[dict[str, Any]]:
|
||||
rows: list[dict[str, Any]] = []
|
||||
for api_name, source in (("ths_hot", "ths"), ("dc_hot", "dc")):
|
||||
for row in self._query(api_name, {"trade_date": trade_date}, TUSHARE_FIELDS[api_name]):
|
||||
item = dict(row)
|
||||
item["source"] = source
|
||||
item.setdefault("trade_date", trade_date)
|
||||
rows.append(item)
|
||||
return rows
|
||||
|
||||
def fetch_dragon_tiger(self, trade_date: str) -> list[dict[str, Any]]:
|
||||
details = self._query("hm_detail", {"trade_date": trade_date}, TUSHARE_FIELDS["hm_detail"])
|
||||
top_rows = self._query("top_list", {"trade_date": trade_date}, TUSHARE_FIELDS["top_list"])
|
||||
context = {
|
||||
str(row.get("ts_code") or ""): row
|
||||
for row in top_rows
|
||||
if str(row.get("ts_code") or "")
|
||||
}
|
||||
rows: list[dict[str, Any]] = []
|
||||
for row in details:
|
||||
item = dict(row)
|
||||
stock = context.get(str(item.get("ts_code") or ""), {})
|
||||
if item.get("pct_change") is None and stock.get("pct_change") is not None:
|
||||
item["pct_change"] = stock.get("pct_change")
|
||||
if not item.get("reason") and stock.get("reason"):
|
||||
item["reason"] = stock.get("reason")
|
||||
if not item.get("ts_name") and stock.get("name"):
|
||||
item["ts_name"] = stock.get("name")
|
||||
rows.append(item)
|
||||
return rows
|
||||
|
||||
def fetch_sector_daily(self, trade_date: str) -> list[dict[str, Any]]:
|
||||
rows: list[dict[str, Any]] = []
|
||||
for api_name, family in (("ths_daily", "ths"), ("dc_index", "dc"), ("sw_daily", "sw")):
|
||||
try:
|
||||
part = self._query(api_name, {"trade_date": trade_date}, TUSHARE_FIELDS[api_name])
|
||||
except AdapterError:
|
||||
part = []
|
||||
for row in part:
|
||||
item = dict(row)
|
||||
item["family"] = family
|
||||
rows.append(item)
|
||||
return rows
|
||||
|
||||
def fetch_index_daily(self, trade_date: str, codes: tuple[str, ...] = DEFAULT_INDEX_CODES) -> list[dict[str, Any]]:
|
||||
rows: list[dict[str, Any]] = []
|
||||
for ts_code in codes:
|
||||
rows.extend(self.fetch("index_daily", {"ts_code": ts_code, "trade_date": trade_date}))
|
||||
return rows
|
||||
|
||||
def normalize(self, dataset: str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
if dataset in {"limit_events", "limit_list_d"}:
|
||||
return [normalize_limit_event(row) for row in rows]
|
||||
if dataset == "popularity":
|
||||
return [normalize_popularity(row, source=str(row.get("source") or "")) for row in rows]
|
||||
if dataset == "dragon_tiger":
|
||||
return [normalize_dragon_tiger(row) for row in rows]
|
||||
if dataset == "sector_daily":
|
||||
return [
|
||||
normalize_sector_daily(row, family=str(row.get("family") or "ths"))
|
||||
for row in rows
|
||||
]
|
||||
mapping = {
|
||||
"calendar": normalize_calendar,
|
||||
"trade_cal": normalize_calendar,
|
||||
"stocks": normalize_stock,
|
||||
"stock_basic": normalize_stock,
|
||||
"daily": normalize_daily,
|
||||
"valuation": normalize_valuation,
|
||||
"daily_basic": normalize_valuation,
|
||||
"moneyflow": normalize_moneyflow,
|
||||
"auction": normalize_auction,
|
||||
"stk_auction": normalize_auction,
|
||||
"index_daily": normalize_index_daily,
|
||||
}
|
||||
fn = mapping.get(dataset)
|
||||
if fn is None:
|
||||
if dataset == "adj_factor":
|
||||
return [
|
||||
{
|
||||
"ts_code": str(row.get("ts_code") or "").upper(),
|
||||
"trade_date": str(row.get("trade_date") or ""),
|
||||
"adj_factor": row.get("adj_factor"),
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
raise AdapterError(f"unsupported dataset: {dataset}")
|
||||
return [fn(row) for row in rows]
|
||||
|
||||
def _query(self, api_name: str, params: dict[str, Any], fields: str) -> list[dict[str, Any]]:
|
||||
if self._transport is not None:
|
||||
return self._transport(api_name, params, fields)
|
||||
if not self.token:
|
||||
raise AdapterError("Tushare token 未配置")
|
||||
payload = json.dumps(
|
||||
{"api_name": api_name, "token": self.token, "params": params, "fields": fields}
|
||||
).encode("utf-8")
|
||||
request = urllib.request.Request(
|
||||
TUSHARE_URL,
|
||||
data=payload,
|
||||
headers={"Content-Type": "application/json", "User-Agent": "XiaobaiDatahub/0.1"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
||||
result = json.loads(response.read().decode("utf-8"))
|
||||
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
|
||||
raise AdapterError(f"Tushare 请求失败: {exc}") from exc
|
||||
if result.get("code") not in (0, "0", None):
|
||||
raise AdapterError(str(result.get("msg") or f"Tushare error {result.get('code')}"))
|
||||
data = result.get("data") or {}
|
||||
items = data.get("items") or []
|
||||
fields_list = data.get("fields") or (fields.split(",") if fields else [])
|
||||
return [dict(zip(fields_list, item)) for item in items]
|
||||
@@ -0,0 +1,3 @@
|
||||
from datahub.adapters.base import ReservedAdapter
|
||||
|
||||
ADAPTER = ReservedAdapter("xgb")
|
||||
@@ -0,0 +1,188 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from datahub.adapters import RESERVED
|
||||
from datahub.auth import AuthService
|
||||
from datahub.db import HubDB
|
||||
from datahub.pipeline import OFFICIAL_DATASETS, STOCKS_DATASET, Pipeline
|
||||
from datahub.scheduler import Scheduler
|
||||
from datahub.serving import ApiError
|
||||
from datahub.timeutil import isoformat, now_shanghai, session_phase, yyyymmdd
|
||||
|
||||
|
||||
class AdminAPI:
|
||||
def __init__(self, db: HubDB, pipeline: Pipeline, scheduler: Scheduler, auth: AuthService) -> None:
|
||||
self.db = db
|
||||
self.pipeline = pipeline
|
||||
self.scheduler = scheduler
|
||||
self.auth = auth
|
||||
|
||||
def overview(self) -> dict[str, Any]:
|
||||
today = yyyymmdd(now_shanghai())
|
||||
cal = self.db.fetchone(
|
||||
"SELECT is_open FROM trade_calendar WHERE exchange = 'SSE' AND cal_date = ?",
|
||||
(today,),
|
||||
)
|
||||
is_open = bool(cal and int(cal["is_open"]) == 1)
|
||||
pubs = self.db.fetchall("SELECT * FROM publications WHERE trade_date = ?", (today,))
|
||||
failed = self.db.fetchall(
|
||||
"SELECT * FROM batches WHERE trade_date = ? AND state IN ('failed','staged')",
|
||||
(today,),
|
||||
)
|
||||
calls = self.db.fetchall(
|
||||
"SELECT * FROM src_calls ORDER BY id DESC LIMIT 20",
|
||||
)
|
||||
return {
|
||||
"trade_date": today,
|
||||
"session_phase": session_phase(now_shanghai(), is_open),
|
||||
"is_open_day": is_open,
|
||||
"eod_status": self.scheduler.eod_status(today),
|
||||
"revision_status": self.scheduler.revision_status(today),
|
||||
"publications": pubs,
|
||||
"anomalies": failed,
|
||||
"recent_calls": _public_calls(calls),
|
||||
"source_count": len(self.db.fetchall("SELECT provider FROM src_health")),
|
||||
}
|
||||
|
||||
def sources(self) -> dict[str, Any]:
|
||||
health = {f"{row['provider']}:{row['endpoint_class']}": row for row in self.db.fetchall("SELECT * FROM src_health")}
|
||||
items = [
|
||||
{
|
||||
"provider": "tushare",
|
||||
"role": "official",
|
||||
"health": health.get("tushare:pro") or {"state": "unknown"},
|
||||
"credential": self.auth.credential_status("tushare_token") or {"configured": bool(self.pipeline.adapter.token)},
|
||||
}
|
||||
]
|
||||
for name, adapter in RESERVED.items():
|
||||
items.append(
|
||||
{
|
||||
"provider": name,
|
||||
"role": "reserved",
|
||||
"health": adapter.probe(),
|
||||
"credential": {"configured": False, "last4": "", "updated_at": ""},
|
||||
}
|
||||
)
|
||||
# Prefer encrypted last4 if stored
|
||||
cred = self.auth.credential_status("tushare_token")
|
||||
if cred.get("configured"):
|
||||
items[0]["credential"] = cred
|
||||
elif self.pipeline.adapter.token:
|
||||
from datahub.crypto import mask_secret
|
||||
|
||||
items[0]["credential"] = {"configured": True, "last4": mask_secret(self.pipeline.adapter.token), "updated_at": ""}
|
||||
return {"items": items}
|
||||
|
||||
def probe(self, provider: str) -> dict[str, Any]:
|
||||
if provider == "tushare":
|
||||
return self.pipeline.adapter.probe()
|
||||
adapter = RESERVED.get(provider)
|
||||
if adapter is None:
|
||||
raise ApiError("INVALID_ARGUMENT", f"unknown provider: {provider}")
|
||||
return adapter.probe()
|
||||
|
||||
def jobs(self) -> dict[str, Any]:
|
||||
runs = self.db.fetchall("SELECT * FROM job_runs ORDER BY id DESC LIMIT 100")
|
||||
stocks_times = "/".join(self.pipeline.settings.stocks_refresh_times) or "20:00"
|
||||
return {
|
||||
"jobs": [
|
||||
{"id": "precheck", "at": "08:45", "title": "盘前预检"},
|
||||
{"id": "eod_a", "at": "15:05", "title": "盘后批 A daily/valuation/moneyflow/auction"},
|
||||
{"id": "eod_b", "at": "15:10", "title": "盘后批 B index_daily"},
|
||||
{"id": "eod_retry", "at": "15:15-23:30", "title": "盘后未出数自动重试(每 30 分钟,成功即停)"},
|
||||
{"id": "eod_revise", "at": "20:00-23:20", "title": "估值发布后复核(轻量比对,有修订才整组原子追补)"},
|
||||
{"id": "stocks_refresh", "at": stocks_times, "title": "股票主档刷新与正式发布(新上市/更名,无变化跳过)"},
|
||||
{"id": "history_backfill", "at": "manual", "title": "回补历史日历与指数日 K"},
|
||||
{"id": "cleanup", "at": "00:30", "title": "清理 staging / 日志"},
|
||||
{"id": "backup", "at": "00:40", "title": "SQLite 备份"},
|
||||
],
|
||||
"runs": runs,
|
||||
}
|
||||
|
||||
def run_job(self, job_id: str, trade_date: str) -> dict[str, Any]:
|
||||
return self.scheduler.run_job(job_id, yyyymmdd(trade_date or now_shanghai()))
|
||||
|
||||
def batches(self, date: str, dataset: str = "") -> dict[str, Any]:
|
||||
trade_date = yyyymmdd(date or now_shanghai())
|
||||
if dataset:
|
||||
rows = self.db.fetchall(
|
||||
"SELECT * FROM batches WHERE trade_date = ? AND dataset = ? ORDER BY started_at",
|
||||
(trade_date, dataset),
|
||||
)
|
||||
else:
|
||||
rows = self.db.fetchall(
|
||||
"SELECT * FROM batches WHERE trade_date = ? ORDER BY started_at",
|
||||
(trade_date,),
|
||||
)
|
||||
pubs = self.db.fetchall("SELECT * FROM publications WHERE trade_date = ?", (trade_date,))
|
||||
return {"trade_date": trade_date, "batches": rows, "publications": pubs}
|
||||
|
||||
def datasets(self, date: str) -> dict[str, Any]:
|
||||
trade_date = yyyymmdd(date or now_shanghai())
|
||||
pubs = self.db.fetchall("SELECT * FROM publications WHERE trade_date = ?", (trade_date,))
|
||||
diffs = self.db.fetchall(
|
||||
"SELECT * FROM diff_reports WHERE trade_date = ? ORDER BY id",
|
||||
(trade_date,),
|
||||
)
|
||||
return {"trade_date": trade_date, "publications": pubs, "diff_reports": diffs}
|
||||
|
||||
def audit(self) -> dict[str, Any]:
|
||||
return {"items": self.db.fetchall("SELECT * FROM audit_log ORDER BY id DESC LIMIT 200")}
|
||||
|
||||
def rollback(self, dataset: str, trade_date: str, password: str, confirm: str, actor: str) -> dict[str, Any]:
|
||||
self._dangerous(password, confirm, f"{dataset}:{trade_date}")
|
||||
result = self.pipeline.rollback(dataset, trade_date, actor=actor)
|
||||
return result
|
||||
|
||||
def backfill(self, dataset: str, trade_date: str, password: str, confirm: str, actor: str) -> dict[str, Any]:
|
||||
day = yyyymmdd(trade_date or now_shanghai())
|
||||
if dataset == "history":
|
||||
self._dangerous(password, confirm, "history:full")
|
||||
result = self.pipeline.backfill_history(day)
|
||||
else:
|
||||
self._dangerous(password, confirm, f"{dataset}:{day}")
|
||||
if dataset == "reference":
|
||||
result = self.pipeline.ingest_reference(day)
|
||||
elif dataset in OFFICIAL_DATASETS or dataset == STOCKS_DATASET:
|
||||
# Manual same-day republish must rebuild the full A/B boundary.
|
||||
# Gate failures and mid-switch exceptions both surface as
|
||||
# FAILED_PRECONDITION so the admin API never leaks raw
|
||||
# transaction errors to the client.
|
||||
try:
|
||||
result = self.pipeline.force_republish_boundary(dataset, day)
|
||||
failures = self.pipeline.eod_failures(result)
|
||||
if failures:
|
||||
raise ApiError("FAILED_PRECONDITION", "; ".join(failures))
|
||||
except ApiError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ApiError("FAILED_PRECONDITION", str(exc)) from exc
|
||||
else:
|
||||
raise ApiError("INVALID_ARGUMENT", f"unsupported backfill dataset: {dataset}")
|
||||
self.pipeline.audit(actor, "backfill", f"{dataset}:{day}", json.dumps({"ok": True}))
|
||||
return result
|
||||
|
||||
def _dangerous(self, password: str, confirm: str, expected: str) -> None:
|
||||
if not self.auth.confirm_password(password):
|
||||
raise ApiError("UNAUTHORIZED", "二次确认密码错误")
|
||||
if confirm.strip() != expected:
|
||||
raise ApiError("INVALID_ARGUMENT", f"确认词必须为 {expected}")
|
||||
|
||||
|
||||
def _public_calls(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
out = []
|
||||
for row in rows:
|
||||
out.append(
|
||||
{
|
||||
"id": row["id"],
|
||||
"provider": row["provider"],
|
||||
"endpoint": row["endpoint"],
|
||||
"ok": bool(row["ok"]),
|
||||
"latency_ms": row["latency_ms"],
|
||||
"error": row["error"],
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
)
|
||||
return out
|
||||
@@ -0,0 +1,190 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import secrets
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
|
||||
from datahub.crypto import SecretVault, mask_secret
|
||||
from datahub.db import HubDB
|
||||
from datahub.timeutil import isoformat, now_shanghai
|
||||
|
||||
PBKDF2_ROUNDS = 200_000
|
||||
SESSION_HOURS = 12
|
||||
LOGIN_FAIL_LIMIT = 5
|
||||
LOCK_MINUTES = 10
|
||||
|
||||
|
||||
def hash_password(password: str, salt: bytes | None = None) -> tuple[str, str]:
|
||||
raw_salt = salt or os.urandom(16)
|
||||
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), raw_salt, PBKDF2_ROUNDS, dklen=32)
|
||||
return (
|
||||
base64.urlsafe_b64encode(raw_salt).decode("ascii"),
|
||||
base64.urlsafe_b64encode(digest).decode("ascii"),
|
||||
)
|
||||
|
||||
|
||||
def verify_password(password: str, salt_text: str, expected_hash: str) -> bool:
|
||||
try:
|
||||
salt = base64.urlsafe_b64decode(salt_text.encode("ascii"))
|
||||
_, actual = hash_password(password, salt)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
return hmac.compare_digest(actual, expected_hash)
|
||||
|
||||
|
||||
def token_hash(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
class AuthService:
|
||||
def __init__(self, db: HubDB, vault: SecretVault, api_token: str, admin_password: str) -> None:
|
||||
self.db = db
|
||||
self.vault = vault
|
||||
self._bootstrap(api_token, admin_password)
|
||||
|
||||
def _bootstrap(self, api_token: str, admin_password: str) -> None:
|
||||
if api_token:
|
||||
existing = self.db.fetchone("SELECT token_hash FROM api_tokens WHERE name = ?", ("review",))
|
||||
hashed = token_hash(api_token)
|
||||
last4 = mask_secret(api_token)
|
||||
if existing is None:
|
||||
self.db.execute(
|
||||
"INSERT INTO api_tokens(token_hash, name, last4, created_at) VALUES (?,?,?,?)",
|
||||
(hashed, "review", last4, isoformat()),
|
||||
)
|
||||
elif existing["token_hash"] != hashed:
|
||||
self.db.execute(
|
||||
"UPDATE api_tokens SET token_hash = ?, last4 = ? WHERE name = ?",
|
||||
(hashed, last4, "review"),
|
||||
)
|
||||
admin = self.db.fetchone("SELECT id FROM hub_admin WHERE username = ?", ("hub_admin",))
|
||||
if admin is None and admin_password:
|
||||
salt, hashed = hash_password(admin_password)
|
||||
now = isoformat()
|
||||
self.db.execute(
|
||||
"""
|
||||
INSERT INTO hub_admin(username, password_salt, password_hash, password_must_change, created_at, updated_at)
|
||||
VALUES (?, ?, ?, 1, ?, ?)
|
||||
""",
|
||||
("hub_admin", salt, hashed, now, now),
|
||||
)
|
||||
|
||||
def check_api_token(self, supplied: str) -> bool:
|
||||
if not supplied:
|
||||
return False
|
||||
row = self.db.fetchone(
|
||||
"SELECT token_hash FROM api_tokens WHERE token_hash = ? AND revoked_at IS NULL",
|
||||
(token_hash(supplied),),
|
||||
)
|
||||
return row is not None
|
||||
|
||||
def login(self, username: str, password: str) -> dict[str, Any]:
|
||||
user = self.db.fetchone("SELECT * FROM hub_admin WHERE username = ?", (username,))
|
||||
if not user:
|
||||
raise PermissionError("账号或密码错误")
|
||||
now = now_shanghai()
|
||||
locked_until = user.get("locked_until")
|
||||
if locked_until:
|
||||
try:
|
||||
from datetime import datetime
|
||||
|
||||
if datetime.fromisoformat(str(locked_until)) > now:
|
||||
raise PermissionError("账号已锁定,请稍后再试")
|
||||
except ValueError:
|
||||
pass
|
||||
if not verify_password(password, str(user["password_salt"]), str(user["password_hash"])):
|
||||
fails = int(user["failed_attempts"] or 0) + 1
|
||||
lock = isoformat(now + timedelta(minutes=LOCK_MINUTES)) if fails >= LOGIN_FAIL_LIMIT else None
|
||||
self.db.execute(
|
||||
"UPDATE hub_admin SET failed_attempts = ?, locked_until = ? WHERE id = ?",
|
||||
(fails, lock, user["id"]),
|
||||
)
|
||||
raise PermissionError("账号或密码错误")
|
||||
self.db.execute(
|
||||
"UPDATE hub_admin SET failed_attempts = 0, locked_until = NULL WHERE id = ?",
|
||||
(user["id"],),
|
||||
)
|
||||
session = secrets.token_urlsafe(32)
|
||||
csrf = secrets.token_urlsafe(24)
|
||||
expires = isoformat(now + timedelta(hours=SESSION_HOURS))
|
||||
self.db.execute(
|
||||
"INSERT INTO hub_sessions(token_hash, csrf_token, expires_at, created_at) VALUES (?,?,?,?)",
|
||||
(token_hash(session), csrf, expires, isoformat(now)),
|
||||
)
|
||||
return {
|
||||
"session": session,
|
||||
"csrf": csrf,
|
||||
"must_change": bool(user["password_must_change"]),
|
||||
"expires_at": expires,
|
||||
}
|
||||
|
||||
def session_user(self, raw_token: str) -> dict[str, Any] | None:
|
||||
if not raw_token:
|
||||
return None
|
||||
row = self.db.fetchone(
|
||||
"SELECT * FROM hub_sessions WHERE token_hash = ?",
|
||||
(token_hash(raw_token),),
|
||||
)
|
||||
if not row:
|
||||
return None
|
||||
if str(row["expires_at"]) < isoformat():
|
||||
self.db.execute("DELETE FROM hub_sessions WHERE token_hash = ?", (row["token_hash"],))
|
||||
return None
|
||||
admin = self.db.fetchone("SELECT username, password_must_change FROM hub_admin WHERE username = ?", ("hub_admin",))
|
||||
return {
|
||||
"username": (admin or {}).get("username") or "hub_admin",
|
||||
"csrf_token": row["csrf_token"],
|
||||
"must_change": bool((admin or {}).get("password_must_change")),
|
||||
"token_hash": row["token_hash"],
|
||||
}
|
||||
|
||||
def logout(self, raw_token: str) -> None:
|
||||
if raw_token:
|
||||
self.db.execute("DELETE FROM hub_sessions WHERE token_hash = ?", (token_hash(raw_token),))
|
||||
|
||||
def change_password(self, current: str, new_password: str) -> None:
|
||||
if len(new_password) < 8:
|
||||
raise ValueError("新密码至少 8 位")
|
||||
user = self.db.fetchone("SELECT * FROM hub_admin WHERE username = ?", ("hub_admin",))
|
||||
if not user or not verify_password(current, str(user["password_salt"]), str(user["password_hash"])):
|
||||
raise PermissionError("当前密码错误")
|
||||
salt, hashed = hash_password(new_password)
|
||||
self.db.execute(
|
||||
"UPDATE hub_admin SET password_salt=?, password_hash=?, password_must_change=0, updated_at=? WHERE id=?",
|
||||
(salt, hashed, isoformat(), user["id"]),
|
||||
)
|
||||
|
||||
def confirm_password(self, password: str) -> bool:
|
||||
user = self.db.fetchone("SELECT * FROM hub_admin WHERE username = ?", ("hub_admin",))
|
||||
if not user:
|
||||
return False
|
||||
return verify_password(password, str(user["password_salt"]), str(user["password_hash"]))
|
||||
|
||||
def credential_status(self, name: str) -> dict[str, Any]:
|
||||
row = self.db.fetchone("SELECT last4, updated_at FROM credentials WHERE name = ?", (name,))
|
||||
if not row:
|
||||
return {"configured": False, "last4": "", "updated_at": ""}
|
||||
return {"configured": True, "last4": row["last4"], "updated_at": row["updated_at"]}
|
||||
|
||||
def store_credential(self, name: str, secret: str) -> None:
|
||||
payload = self.vault.encrypt_json({name: secret})
|
||||
self.db.execute(
|
||||
"""
|
||||
INSERT INTO credentials(name, encrypted_payload, last4, updated_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(name) DO UPDATE SET
|
||||
encrypted_payload=excluded.encrypted_payload, last4=excluded.last4, updated_at=excluded.updated_at
|
||||
""",
|
||||
(name, payload, mask_secret(secret), isoformat()),
|
||||
)
|
||||
|
||||
def load_credential(self, name: str) -> str:
|
||||
row = self.db.fetchone("SELECT encrypted_payload FROM credentials WHERE name = ?", (name,))
|
||||
if not row:
|
||||
return ""
|
||||
data = self.vault.decrypt_json(str(row["encrypted_payload"]))
|
||||
return str(data.get(name) or "")
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Command-line entry for one-shot datahub operations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
|
||||
from datahub.hub import build_hub
|
||||
from datahub.pipeline import EOD_A_DATASETS, OFFICIAL_DATASETS, STOCKS_DATASET
|
||||
from datahub.settings import load_settings
|
||||
from datahub.timeutil import yyyymmdd
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="xiaobai-datahub CLI")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
history = sub.add_parser("history-backfill", help="回补 2016 年起交易日历和网站所用指数日 K")
|
||||
history.add_argument("--calendar-start", default=None, help="日历起点,默认配置 calendar_start")
|
||||
history.add_argument("--index-days", type=int, default=None, help="指数回补交易日数量,默认 260")
|
||||
history.add_argument("--force", action="store_true", help="覆盖已发布的指数日期")
|
||||
refresh = sub.add_parser("eod-refresh", help="对指定交易日补跑盘后正式数据(跳过已完整发布的一致性边界,仍走质量门禁)")
|
||||
refresh.add_argument("--trade-date", default=None, help="交易日 YYYYMMDD,默认今天")
|
||||
refresh.add_argument(
|
||||
"--force", action="store_true",
|
||||
help="强制重发 --dataset 所属的完整一致性边界(A 组或 B 组),生成新批次并保留上一批次可回滚",
|
||||
)
|
||||
refresh.add_argument(
|
||||
"--dataset", default=None,
|
||||
help="配合 --force:指定边界内任一成员(如 valuation→整组 A;index_daily→整组 B)",
|
||||
)
|
||||
stocks_refresh = sub.add_parser("stocks-refresh", help="刷新股票主档并发布正式快照(幂等:无变化则跳过)")
|
||||
stocks_refresh.add_argument("--trade-date", default=None, help="交易日 YYYYMMDD,默认今天")
|
||||
stocks_refresh.add_argument("--force", action="store_true", help="即使快照无变化也重新发布")
|
||||
moneyflow_backfill = sub.add_parser(
|
||||
"moneyflow-backfill", help="回补资金流历史(默认覆盖网站所需的最近 N 个交易日,跳过已发布日期)",
|
||||
)
|
||||
moneyflow_backfill.add_argument("--end-date", default=None, help="截止交易日 YYYYMMDD,默认今天")
|
||||
moneyflow_backfill.add_argument("--trading-days", type=int, default=None, help="回补交易日数量,默认配置 moneyflow_history_trading_days")
|
||||
moneyflow_backfill.add_argument("--force", action="store_true", help="覆盖已发布的资金流日期")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
settings = load_settings()
|
||||
hub = build_hub(settings)
|
||||
if args.command == "history-backfill":
|
||||
result = hub.pipeline.backfill_history(
|
||||
calendar_start=args.calendar_start,
|
||||
index_days=args.index_days,
|
||||
force=args.force,
|
||||
)
|
||||
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
||||
sys.stdout.write("\n")
|
||||
return 0 if result.get("ok") else 1
|
||||
if args.command == "eod-refresh":
|
||||
day = yyyymmdd(args.trade_date) if args.trade_date else yyyymmdd()
|
||||
if args.force:
|
||||
allowed = set(OFFICIAL_DATASETS) | {STOCKS_DATASET}
|
||||
if not args.dataset:
|
||||
parser.error("--force requires --dataset (e.g. --dataset valuation)")
|
||||
if args.dataset not in allowed:
|
||||
parser.error(f"unknown dataset: {args.dataset}")
|
||||
result = hub.pipeline.force_republish_boundary(args.dataset, day)
|
||||
boundary = "A" if args.dataset in EOD_A_DATASETS or args.dataset == STOCKS_DATASET else "B"
|
||||
else:
|
||||
result = hub.pipeline.run_eod_missing(day)
|
||||
boundary = None
|
||||
hub.pipeline.audit("cli", "eod-refresh", f"eod:{day}", json.dumps(
|
||||
{"force": bool(args.force), "dataset": args.dataset, "boundary": boundary,
|
||||
**{name: item.get("state") for name, item in result.items() if isinstance(item, dict)}},
|
||||
ensure_ascii=False,
|
||||
))
|
||||
if args.force:
|
||||
failures = hub.pipeline.eod_failures(result)
|
||||
payload = {"trade_date": day, "boundary": boundary, "datasets": result}
|
||||
json.dump(payload, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
||||
sys.stdout.write("\n")
|
||||
return 0 if not failures else 1
|
||||
missing = hub.pipeline.missing_official_datasets(day)
|
||||
payload = {"trade_date": day, "datasets": result, "missing_after": missing}
|
||||
json.dump(payload, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
||||
sys.stdout.write("\n")
|
||||
return 0 if not missing else 1
|
||||
if args.command == "stocks-refresh":
|
||||
day = yyyymmdd(args.trade_date) if args.trade_date else yyyymmdd()
|
||||
result = hub.pipeline.refresh_stocks(day, force=args.force)
|
||||
hub.pipeline.audit("cli", "stocks-refresh", f"stocks:{day}", json.dumps(
|
||||
{"force": bool(args.force), "state": result.get("state"), "batch_id": result.get("batch_id")},
|
||||
ensure_ascii=False,
|
||||
))
|
||||
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
||||
sys.stdout.write("\n")
|
||||
return 0 if result.get("state") != "failed" else 1
|
||||
if args.command == "moneyflow-backfill":
|
||||
result = hub.pipeline.backfill_moneyflow_history(
|
||||
end_date=args.end_date,
|
||||
trading_days=args.trading_days,
|
||||
force=args.force,
|
||||
)
|
||||
hub.pipeline.audit("cli", "moneyflow-backfill", f"moneyflow:{result.get('end')}", json.dumps(
|
||||
{"published": len(result.get("published") or []), "skipped": len(result.get("skipped") or []),
|
||||
"failed": len(result.get("failed") or [])},
|
||||
ensure_ascii=False,
|
||||
))
|
||||
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
||||
sys.stdout.write("\n")
|
||||
return 0 if result.get("ok") else 1
|
||||
parser.error(f"unknown command: {args.command}")
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,26 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datahub.db import HubDB
|
||||
|
||||
|
||||
def resolve_code(db: HubDB, raw: str) -> str | None:
|
||||
text = str(raw or "").strip().upper()
|
||||
if not text:
|
||||
return None
|
||||
if "." in text:
|
||||
row = db.fetchone("SELECT ts_code FROM stock_master WHERE ts_code = ?", (text,))
|
||||
if row:
|
||||
return row["ts_code"]
|
||||
# indices are not always in stock_master
|
||||
return text
|
||||
matches = db.fetchall(
|
||||
"SELECT ts_code FROM stock_master WHERE symbol = ? OR ts_code LIKE ?",
|
||||
(text, f"{text}.%"),
|
||||
)
|
||||
if len(matches) == 1:
|
||||
return matches[0]["ts_code"]
|
||||
if len(matches) > 1:
|
||||
return None
|
||||
# unique exchange guess for 6-digit codes
|
||||
suffix = "SH" if text.startswith("6") or text.startswith("9") else "SZ" if text.startswith(("0", "3")) else "BJ"
|
||||
return f"{text}.{suffix}"
|
||||
@@ -0,0 +1,130 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Iterable
|
||||
|
||||
from datahub.db import HubDB
|
||||
from datahub.timeutil import iter_yyyymmdd, yyyymmdd
|
||||
|
||||
MISSING_SAMPLE_LIMIT = 10
|
||||
|
||||
|
||||
def coverage_payload(
|
||||
*,
|
||||
kind: str,
|
||||
start: str,
|
||||
end: str,
|
||||
expected: Iterable[str],
|
||||
available: Iterable[str],
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
start = yyyymmdd(start)
|
||||
end = yyyymmdd(end)
|
||||
expected_list = sorted({yyyymmdd(item) for item in expected if item})
|
||||
available_set = {yyyymmdd(item) for item in available if item}
|
||||
missing = [item for item in expected_list if item not in available_set]
|
||||
payload: dict[str, Any] = {
|
||||
"kind": kind,
|
||||
"complete": not missing,
|
||||
"requested_from": start,
|
||||
"requested_to": end,
|
||||
"available_from": min(available_set) if available_set else None,
|
||||
"available_to": max(available_set) if available_set else None,
|
||||
"expected_count": len(expected_list),
|
||||
"available_count": len(available_set),
|
||||
"missing_count": len(missing),
|
||||
"missing_sample": missing[:MISSING_SAMPLE_LIMIT],
|
||||
}
|
||||
if extra:
|
||||
payload.update(extra)
|
||||
return payload
|
||||
|
||||
|
||||
def calendar_coverage(db: HubDB, start: str, end: str, exchange: str = "SSE") -> dict[str, Any]:
|
||||
start = yyyymmdd(start)
|
||||
end = yyyymmdd(end)
|
||||
expected = list(iter_yyyymmdd(start, end))
|
||||
rows = db.fetchall(
|
||||
"SELECT cal_date FROM trade_calendar WHERE exchange = ? AND cal_date >= ? AND cal_date <= ?",
|
||||
(exchange, start, end),
|
||||
)
|
||||
return coverage_payload(
|
||||
kind="calendar",
|
||||
start=start,
|
||||
end=end,
|
||||
expected=expected,
|
||||
available=(row["cal_date"] for row in rows),
|
||||
extra={"exchange": exchange},
|
||||
)
|
||||
|
||||
|
||||
def published_range_coverage(
|
||||
db: HubDB,
|
||||
dataset: str,
|
||||
start: str,
|
||||
end: str,
|
||||
ts_code: str = "",
|
||||
table: str = "",
|
||||
) -> dict[str, Any]:
|
||||
start = yyyymmdd(start)
|
||||
end = yyyymmdd(end)
|
||||
calendar = calendar_coverage(db, start, end)
|
||||
open_rows = db.fetchall(
|
||||
"""
|
||||
SELECT cal_date FROM trade_calendar
|
||||
WHERE exchange = 'SSE' AND is_open = 1 AND cal_date >= ? AND cal_date <= ?
|
||||
ORDER BY cal_date
|
||||
""",
|
||||
(start, end),
|
||||
)
|
||||
expected_open = [row["cal_date"] for row in open_rows]
|
||||
pubs = db.fetchall(
|
||||
"""
|
||||
SELECT trade_date, active_batch FROM publications
|
||||
WHERE dataset = ? AND trade_date >= ? AND trade_date <= ?
|
||||
ORDER BY trade_date
|
||||
""",
|
||||
(dataset, start, end),
|
||||
)
|
||||
published_dates = [row["trade_date"] for row in pubs]
|
||||
available = list(published_dates)
|
||||
extra: dict[str, Any] = {
|
||||
"dataset": dataset,
|
||||
"calendar_complete": calendar["complete"],
|
||||
"calendar_missing_count": calendar["missing_count"],
|
||||
}
|
||||
if ts_code and table and pubs:
|
||||
present_code: list[str] = []
|
||||
for pub in pubs:
|
||||
hit = db.fetchone(
|
||||
f"SELECT 1 AS ok FROM {table} WHERE trade_date = ? AND batch_id = ? AND ts_code = ? LIMIT 1",
|
||||
(pub["trade_date"], pub["active_batch"], ts_code),
|
||||
)
|
||||
if hit:
|
||||
present_code.append(pub["trade_date"])
|
||||
available = present_code
|
||||
extra["code"] = ts_code
|
||||
payload = coverage_payload(
|
||||
kind="published_range",
|
||||
start=start,
|
||||
end=end,
|
||||
expected=expected_open,
|
||||
available=available,
|
||||
extra=extra,
|
||||
)
|
||||
if not calendar["complete"]:
|
||||
payload["complete"] = False
|
||||
payload["calendar_missing_sample"] = calendar["missing_sample"]
|
||||
return payload
|
||||
|
||||
|
||||
def point_coverage(trade_date: str, dataset: str = "") -> dict[str, Any]:
|
||||
day = yyyymmdd(trade_date)
|
||||
payload = coverage_payload(
|
||||
kind="point",
|
||||
start=day,
|
||||
end=day,
|
||||
expected=[day],
|
||||
available=[day],
|
||||
extra={"dataset": dataset} if dataset else None,
|
||||
)
|
||||
return payload
|
||||
@@ -0,0 +1,42 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
|
||||
|
||||
class SecretVault:
|
||||
def __init__(self, key: str) -> None:
|
||||
try:
|
||||
self._fernet = Fernet(key.encode("ascii"))
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise ValueError("DATAHUB_ENCRYPTION_KEY 格式无效。") from exc
|
||||
|
||||
@staticmethod
|
||||
def generate_key() -> str:
|
||||
return Fernet.generate_key().decode("ascii")
|
||||
|
||||
def encrypt_json(self, payload: dict[str, Any]) -> str:
|
||||
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||
return self._fernet.encrypt(raw).decode("ascii")
|
||||
|
||||
def decrypt_json(self, token: str) -> dict[str, Any]:
|
||||
if not token:
|
||||
return {}
|
||||
try:
|
||||
payload = json.loads(self._fernet.decrypt(token.encode("ascii")).decode("utf-8"))
|
||||
except (InvalidToken, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise ValueError("凭据无法解密,请检查 DATAHUB_ENCRYPTION_KEY。") from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("凭据格式无效。")
|
||||
return payload
|
||||
|
||||
|
||||
def mask_secret(value: str, last_n: int = 4) -> str:
|
||||
text = str(value or "")
|
||||
if not text:
|
||||
return ""
|
||||
if len(text) <= last_n:
|
||||
return "*" * len(text)
|
||||
return ("*" * max(4, len(text) - last_n)) + text[-last_n:]
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Extended EOD datasets beyond the first-batch A/B release groups.
|
||||
|
||||
These publish independently (soft): a failure here must not block daily/valuation
|
||||
release. Scheduler runs them after the core EOD window.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
# Independent soft datasets (not part of A/B atomic groups).
|
||||
EXTENDED_SOFT_DATASETS = {
|
||||
"limit_events",
|
||||
"popularity",
|
||||
"dragon_tiger",
|
||||
"sector_daily",
|
||||
}
|
||||
|
||||
EXTENDED_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS eod_limit_events (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, limit_type TEXT NOT NULL,
|
||||
name TEXT, industry TEXT, close REAL, pct_chg REAL, amount REAL,
|
||||
limit_amount REAL, float_mv REAL, total_mv REAL, turnover_ratio REAL,
|
||||
fd_amount REAL, first_time TEXT, last_time TEXT,
|
||||
open_times INTEGER, up_stat TEXT, limit_times INTEGER,
|
||||
batch_id TEXT NOT NULL,
|
||||
PRIMARY KEY (ts_code, trade_date, limit_type, batch_id)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS staging_limit_events (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, limit_type TEXT NOT NULL, batch_id TEXT NOT NULL,
|
||||
name TEXT, industry TEXT, close REAL, pct_chg REAL, amount REAL,
|
||||
limit_amount REAL, float_mv REAL, total_mv REAL, turnover_ratio REAL,
|
||||
fd_amount REAL, first_time TEXT, last_time TEXT,
|
||||
open_times INTEGER, up_stat TEXT, limit_times INTEGER,
|
||||
PRIMARY KEY (batch_id, ts_code, trade_date, limit_type)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS eod_popularity (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, source TEXT NOT NULL,
|
||||
ts_name TEXT, rank INTEGER, pct_change REAL, current_price REAL,
|
||||
hot REAL, concept TEXT, data_type TEXT,
|
||||
batch_id TEXT NOT NULL,
|
||||
PRIMARY KEY (ts_code, trade_date, source, batch_id)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS staging_popularity (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, source TEXT NOT NULL, batch_id TEXT NOT NULL,
|
||||
ts_name TEXT, rank INTEGER, pct_change REAL, current_price REAL,
|
||||
hot REAL, concept TEXT, data_type TEXT,
|
||||
PRIMARY KEY (batch_id, ts_code, trade_date, source)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS eod_dragon_tiger (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, hm_name TEXT NOT NULL,
|
||||
ts_name TEXT, buy_amount REAL, sell_amount REAL, net_amount REAL,
|
||||
hm_orgs TEXT, tag TEXT, pct_change REAL, reason TEXT,
|
||||
batch_id TEXT NOT NULL,
|
||||
PRIMARY KEY (ts_code, trade_date, hm_name, batch_id)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS staging_dragon_tiger (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, hm_name TEXT NOT NULL, batch_id TEXT NOT NULL,
|
||||
ts_name TEXT, buy_amount REAL, sell_amount REAL, net_amount REAL,
|
||||
hm_orgs TEXT, tag TEXT, pct_change REAL, reason TEXT,
|
||||
PRIMARY KEY (batch_id, ts_code, trade_date, hm_name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS eod_sector_daily (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, family TEXT NOT NULL,
|
||||
name TEXT, open REAL, high REAL, low REAL, close REAL, pre_close REAL,
|
||||
pct_change REAL, vol REAL, turnover_rate REAL, amount REAL,
|
||||
batch_id TEXT NOT NULL,
|
||||
PRIMARY KEY (ts_code, trade_date, family, batch_id)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS staging_sector_daily (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, family TEXT NOT NULL, batch_id TEXT NOT NULL,
|
||||
name TEXT, open REAL, high REAL, low REAL, close REAL, pre_close REAL,
|
||||
pct_change REAL, vol REAL, turnover_rate REAL, amount REAL,
|
||||
PRIMARY KEY (batch_id, ts_code, trade_date, family)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sector_master (
|
||||
ts_code TEXT PRIMARY KEY,
|
||||
name TEXT,
|
||||
family TEXT NOT NULL,
|
||||
exchange TEXT,
|
||||
list_date TEXT,
|
||||
member_count INTEGER,
|
||||
type TEXT,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_eod_limit_date ON eod_limit_events(trade_date, batch_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_eod_pop_date ON eod_popularity(trade_date, batch_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_eod_lhb_date ON eod_dragon_tiger(trade_date, batch_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_eod_sector_date ON eod_sector_daily(trade_date, family, batch_id);
|
||||
"""
|
||||
|
||||
EXTENDED_DATASET_TABLES = {
|
||||
"limit_events": ("eod_limit_events", "staging_limit_events"),
|
||||
"popularity": ("eod_popularity", "staging_popularity"),
|
||||
"dragon_tiger": ("eod_dragon_tiger", "staging_dragon_tiger"),
|
||||
"sector_daily": ("eod_sector_daily", "staging_sector_daily"),
|
||||
}
|
||||
|
||||
EXTENDED_STAGING_INSERT: dict[str, tuple[str, Any]] = {
|
||||
"limit_events": (
|
||||
"INSERT INTO staging_limit_events("
|
||||
"ts_code,trade_date,limit_type,batch_id,name,industry,close,pct_chg,amount,"
|
||||
"limit_amount,float_mv,total_mv,turnover_ratio,fd_amount,first_time,last_time,"
|
||||
"open_times,up_stat,limit_times) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
lambda r, b: (
|
||||
r["ts_code"], r["trade_date"], r["limit_type"], b,
|
||||
r.get("name"), r.get("industry"), r.get("close"), r.get("pct_chg"), r.get("amount"),
|
||||
r.get("limit_amount"), r.get("float_mv"), r.get("total_mv"), r.get("turnover_ratio"),
|
||||
r.get("fd_amount"), r.get("first_time"), r.get("last_time"),
|
||||
r.get("open_times"), r.get("up_stat"), r.get("limit_times"),
|
||||
),
|
||||
),
|
||||
"popularity": (
|
||||
"INSERT INTO staging_popularity("
|
||||
"ts_code,trade_date,source,batch_id,ts_name,rank,pct_change,current_price,hot,concept,data_type) "
|
||||
"VALUES (?,?,?,?,?,?,?,?,?,?,?)",
|
||||
lambda r, b: (
|
||||
r["ts_code"], r["trade_date"], r["source"], b,
|
||||
r.get("ts_name"), r.get("rank"), r.get("pct_change"), r.get("current_price"),
|
||||
r.get("hot"), r.get("concept"), r.get("data_type"),
|
||||
),
|
||||
),
|
||||
"dragon_tiger": (
|
||||
"INSERT INTO staging_dragon_tiger("
|
||||
"ts_code,trade_date,hm_name,batch_id,ts_name,buy_amount,sell_amount,net_amount,"
|
||||
"hm_orgs,tag,pct_change,reason) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
lambda r, b: (
|
||||
r["ts_code"], r["trade_date"], r["hm_name"], b,
|
||||
r.get("ts_name"), r.get("buy_amount"), r.get("sell_amount"), r.get("net_amount"),
|
||||
r.get("hm_orgs"), r.get("tag"), r.get("pct_change"), r.get("reason"),
|
||||
),
|
||||
),
|
||||
"sector_daily": (
|
||||
"INSERT INTO staging_sector_daily("
|
||||
"ts_code,trade_date,family,batch_id,name,open,high,low,close,pre_close,"
|
||||
"pct_change,vol,turnover_rate,amount) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
lambda r, b: (
|
||||
r["ts_code"], r["trade_date"], r["family"], b,
|
||||
r.get("name"), r.get("open"), r.get("high"), r.get("low"), r.get("close"),
|
||||
r.get("pre_close"), r.get("pct_change"), r.get("vol"), r.get("turnover_rate"),
|
||||
r.get("amount"),
|
||||
),
|
||||
),
|
||||
}
|
||||
|
||||
EXTENDED_EOD_COPY = {
|
||||
"limit_events": (
|
||||
"INSERT OR REPLACE INTO eod_limit_events "
|
||||
"SELECT ts_code,trade_date,limit_type,name,industry,close,pct_chg,amount,"
|
||||
"limit_amount,float_mv,total_mv,turnover_ratio,fd_amount,first_time,last_time,"
|
||||
"open_times,up_stat,limit_times,batch_id "
|
||||
"FROM staging_limit_events WHERE batch_id = ?"
|
||||
),
|
||||
"popularity": (
|
||||
"INSERT OR REPLACE INTO eod_popularity "
|
||||
"SELECT ts_code,trade_date,source,ts_name,rank,pct_change,current_price,hot,concept,data_type,batch_id "
|
||||
"FROM staging_popularity WHERE batch_id = ?"
|
||||
),
|
||||
"dragon_tiger": (
|
||||
"INSERT OR REPLACE INTO eod_dragon_tiger "
|
||||
"SELECT ts_code,trade_date,hm_name,ts_name,buy_amount,sell_amount,net_amount,"
|
||||
"hm_orgs,tag,pct_change,reason,batch_id "
|
||||
"FROM staging_dragon_tiger WHERE batch_id = ?"
|
||||
),
|
||||
"sector_daily": (
|
||||
"INSERT OR REPLACE INTO eod_sector_daily "
|
||||
"SELECT ts_code,trade_date,family,name,open,high,low,close,pre_close,"
|
||||
"pct_change,vol,turnover_rate,amount,batch_id "
|
||||
"FROM staging_sector_daily WHERE batch_id = ?"
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
import threading
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from datahub.datasets_ext import EXTENDED_DATASET_TABLES, EXTENDED_SCHEMA
|
||||
from datahub.timeutil import isoformat
|
||||
|
||||
_BASE_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version INTEGER PRIMARY KEY,
|
||||
applied_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS credentials (
|
||||
name TEXT PRIMARY KEY,
|
||||
encrypted_payload TEXT NOT NULL,
|
||||
last4 TEXT,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS hub_admin (
|
||||
id INTEGER PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password_salt TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
password_must_change INTEGER NOT NULL DEFAULT 1,
|
||||
failed_attempts INTEGER NOT NULL DEFAULT 0,
|
||||
locked_until TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS hub_sessions (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
csrf_token TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS api_tokens (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
last4 TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
revoked_at TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS trade_calendar (
|
||||
exchange TEXT NOT NULL,
|
||||
cal_date TEXT NOT NULL,
|
||||
is_open INTEGER NOT NULL,
|
||||
pretrade_date TEXT,
|
||||
fetched_at TEXT NOT NULL,
|
||||
PRIMARY KEY (exchange, cal_date)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS stock_master (
|
||||
ts_code TEXT PRIMARY KEY,
|
||||
symbol TEXT,
|
||||
name TEXT,
|
||||
area TEXT,
|
||||
industry TEXT,
|
||||
market TEXT,
|
||||
list_status TEXT,
|
||||
list_date TEXT,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS eod_bars (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL,
|
||||
open REAL, high REAL, low REAL, close REAL, pct_chg REAL,
|
||||
volume REAL, amount REAL, adj_factor REAL,
|
||||
batch_id TEXT NOT NULL,
|
||||
PRIMARY KEY (ts_code, trade_date, batch_id)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS eod_valuation (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL,
|
||||
turnover_rate REAL, volume_ratio REAL,
|
||||
total_mv REAL, circ_mv REAL,
|
||||
pe_ttm REAL, pb REAL, ps_ttm REAL, dv_ttm REAL,
|
||||
batch_id TEXT NOT NULL,
|
||||
PRIMARY KEY (ts_code, trade_date, batch_id)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS eod_moneyflow (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL,
|
||||
buy_sm_amount REAL, sell_sm_amount REAL,
|
||||
buy_md_amount REAL, sell_md_amount REAL,
|
||||
buy_lg_amount REAL, sell_lg_amount REAL,
|
||||
buy_elg_amount REAL, sell_elg_amount REAL,
|
||||
net_mf_amount REAL,
|
||||
batch_id TEXT NOT NULL,
|
||||
PRIMARY KEY (ts_code, trade_date, batch_id)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS eod_auction (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL,
|
||||
volume REAL, price REAL, amount REAL, pre_close REAL,
|
||||
turnover_rate REAL, volume_ratio REAL, float_share REAL,
|
||||
batch_id TEXT NOT NULL,
|
||||
PRIMARY KEY (ts_code, trade_date, batch_id)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS eod_index_bars (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL,
|
||||
open REAL, high REAL, low REAL, close REAL, pct_chg REAL,
|
||||
volume REAL, amount REAL,
|
||||
batch_id TEXT NOT NULL,
|
||||
PRIMARY KEY (ts_code, trade_date, batch_id)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS eod_stocks (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL,
|
||||
symbol TEXT, name TEXT, area TEXT, industry TEXT, market TEXT,
|
||||
list_status TEXT, list_date TEXT,
|
||||
batch_id TEXT NOT NULL,
|
||||
PRIMARY KEY (ts_code, trade_date, batch_id)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS staging_stocks (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, batch_id TEXT NOT NULL,
|
||||
symbol TEXT, name TEXT, area TEXT, industry TEXT, market TEXT,
|
||||
list_status TEXT, list_date TEXT,
|
||||
PRIMARY KEY (batch_id, ts_code, trade_date)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS staging_bars (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, batch_id TEXT NOT NULL,
|
||||
open REAL, high REAL, low REAL, close REAL, pct_chg REAL,
|
||||
volume REAL, amount REAL, adj_factor REAL,
|
||||
PRIMARY KEY (batch_id, ts_code, trade_date)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS staging_valuation (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, batch_id TEXT NOT NULL,
|
||||
turnover_rate REAL, volume_ratio REAL,
|
||||
total_mv REAL, circ_mv REAL, pe_ttm REAL, pb REAL, ps_ttm REAL, dv_ttm REAL,
|
||||
PRIMARY KEY (batch_id, ts_code, trade_date)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS staging_moneyflow (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, batch_id TEXT NOT NULL,
|
||||
buy_sm_amount REAL, sell_sm_amount REAL, buy_md_amount REAL, sell_md_amount REAL,
|
||||
buy_lg_amount REAL, sell_lg_amount REAL, buy_elg_amount REAL, sell_elg_amount REAL,
|
||||
net_mf_amount REAL,
|
||||
PRIMARY KEY (batch_id, ts_code, trade_date)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS staging_auction (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, batch_id TEXT NOT NULL,
|
||||
volume REAL, price REAL, amount REAL, pre_close REAL,
|
||||
turnover_rate REAL, volume_ratio REAL, float_share REAL,
|
||||
PRIMARY KEY (batch_id, ts_code, trade_date)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS staging_index_bars (
|
||||
ts_code TEXT NOT NULL, trade_date TEXT NOT NULL, batch_id TEXT NOT NULL,
|
||||
open REAL, high REAL, low REAL, close REAL, pct_chg REAL,
|
||||
volume REAL, amount REAL,
|
||||
PRIMARY KEY (batch_id, ts_code, trade_date)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS publications (
|
||||
dataset TEXT NOT NULL, trade_date TEXT NOT NULL,
|
||||
active_batch TEXT NOT NULL, prev_batch TEXT,
|
||||
state TEXT NOT NULL,
|
||||
published_at TEXT NOT NULL,
|
||||
PRIMARY KEY (dataset, trade_date)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS publication_history (
|
||||
dataset TEXT NOT NULL, trade_date TEXT NOT NULL,
|
||||
batch_id TEXT NOT NULL, published_at TEXT NOT NULL,
|
||||
generation INTEGER NOT NULL,
|
||||
PRIMARY KEY (dataset, trade_date, batch_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS batches (
|
||||
batch_id TEXT PRIMARY KEY,
|
||||
dataset TEXT NOT NULL,
|
||||
trade_date TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
attempt INTEGER DEFAULT 0,
|
||||
rows_in INTEGER,
|
||||
rows_out INTEGER,
|
||||
quality_json TEXT,
|
||||
started_at TEXT,
|
||||
finished_at TEXT,
|
||||
error TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS src_health (
|
||||
provider TEXT NOT NULL, endpoint_class TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
last_ok_at TEXT, last_error TEXT,
|
||||
consec_failures INTEGER DEFAULT 0,
|
||||
opened_at TEXT,
|
||||
cooldown_until TEXT,
|
||||
PRIMARY KEY (provider, endpoint_class)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS src_calls (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
provider TEXT NOT NULL,
|
||||
endpoint TEXT NOT NULL,
|
||||
ok INTEGER NOT NULL,
|
||||
latency_ms INTEGER,
|
||||
error TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS job_runs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
job_id TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
started_at TEXT,
|
||||
finished_at TEXT,
|
||||
rows_in INTEGER,
|
||||
rows_out INTEGER,
|
||||
error TEXT,
|
||||
attempt INTEGER DEFAULT 1,
|
||||
detail TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS eod_progress (
|
||||
trade_date TEXT PRIMARY KEY,
|
||||
state TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
last_attempt_at TEXT,
|
||||
next_retry_at TEXT,
|
||||
finished_at TEXT,
|
||||
detail TEXT,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS revision_progress (
|
||||
trade_date TEXT PRIMARY KEY,
|
||||
state TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
last_attempt_at TEXT,
|
||||
next_retry_at TEXT,
|
||||
finished_at TEXT,
|
||||
catchup_done INTEGER NOT NULL DEFAULT 0,
|
||||
last_diff TEXT,
|
||||
detail TEXT,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
actor TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
target TEXT,
|
||||
detail TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS rt_cache (
|
||||
cache_key TEXT PRIMARY KEY,
|
||||
payload TEXT NOT NULL,
|
||||
source TEXT NOT NULL,
|
||||
stored_at TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS last_known_good (
|
||||
cache_key TEXT PRIMARY KEY,
|
||||
payload TEXT NOT NULL,
|
||||
source TEXT NOT NULL,
|
||||
stored_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS diff_reports (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
trade_date TEXT NOT NULL,
|
||||
metric TEXT NOT NULL,
|
||||
left_source TEXT,
|
||||
right_source TEXT,
|
||||
left_value REAL,
|
||||
right_value REAL,
|
||||
deviation REAL,
|
||||
sample_count INTEGER,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_batches_date ON batches(trade_date, dataset);
|
||||
CREATE INDEX IF NOT EXISTS idx_job_runs_job ON job_runs(job_id, started_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_src_calls_created ON src_calls(created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_eod_bars_date ON eod_bars(trade_date, batch_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_calendar_open ON trade_calendar(is_open, cal_date);
|
||||
"""
|
||||
|
||||
SCHEMA = _BASE_SCHEMA + EXTENDED_SCHEMA
|
||||
|
||||
DATASET_TABLES = {
|
||||
"daily": ("eod_bars", "staging_bars"),
|
||||
"valuation": ("eod_valuation", "staging_valuation"),
|
||||
"moneyflow": ("eod_moneyflow", "staging_moneyflow"),
|
||||
"auction": ("eod_auction", "staging_auction"),
|
||||
"index_daily": ("eod_index_bars", "staging_index_bars"),
|
||||
"stocks": ("eod_stocks", "staging_stocks"),
|
||||
**EXTENDED_DATASET_TABLES,
|
||||
}
|
||||
|
||||
|
||||
class ManagedConnection(sqlite3.Connection):
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
try:
|
||||
return super().__exit__(exc_type, exc_value, traceback)
|
||||
finally:
|
||||
self.close()
|
||||
|
||||
|
||||
class HubDB:
|
||||
def __init__(self, path: Path, timeout_seconds: float = 20) -> None:
|
||||
self.path = Path(path)
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.timeout_seconds = timeout_seconds
|
||||
self._write_lock = threading.RLock()
|
||||
self.initialize()
|
||||
|
||||
def connect(self) -> sqlite3.Connection:
|
||||
connection = sqlite3.connect(
|
||||
self.path,
|
||||
timeout=self.timeout_seconds,
|
||||
factory=ManagedConnection,
|
||||
)
|
||||
connection.row_factory = sqlite3.Row
|
||||
connection.execute("PRAGMA journal_mode=WAL")
|
||||
connection.execute("PRAGMA foreign_keys=ON")
|
||||
connection.execute("PRAGMA busy_timeout=20000")
|
||||
connection.execute("PRAGMA synchronous=NORMAL")
|
||||
return connection
|
||||
|
||||
def initialize(self) -> None:
|
||||
with self.connect() as connection:
|
||||
connection.executescript(SCHEMA)
|
||||
row = connection.execute(
|
||||
"SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1"
|
||||
).fetchone()
|
||||
if row is None:
|
||||
connection.execute(
|
||||
"INSERT INTO schema_migrations(version, applied_at) VALUES (1, ?)",
|
||||
(isoformat(),),
|
||||
)
|
||||
|
||||
@contextmanager
|
||||
def write(self) -> Iterator[sqlite3.Connection]:
|
||||
with self._write_lock:
|
||||
with self.connect() as connection:
|
||||
yield connection
|
||||
|
||||
def fetchall(self, sql: str, params: tuple[Any, ...] = ()) -> list[dict[str, Any]]:
|
||||
with self.connect() as connection:
|
||||
rows = connection.execute(sql, params).fetchall()
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
def fetchone(self, sql: str, params: tuple[Any, ...] = ()) -> dict[str, Any] | None:
|
||||
with self.connect() as connection:
|
||||
row = connection.execute(sql, params).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def execute(self, sql: str, params: tuple[Any, ...] = ()) -> None:
|
||||
with self.write() as connection:
|
||||
connection.execute(sql, params)
|
||||
|
||||
def executemany(self, sql: str, rows: list[tuple[Any, ...]]) -> None:
|
||||
with self.write() as connection:
|
||||
connection.executemany(sql, rows)
|
||||
|
||||
def backup_to(self, dest: Path) -> None:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
with self.connect() as source, sqlite3.connect(dest) as target:
|
||||
source.backup(target)
|
||||
|
||||
def vacuum(self) -> None:
|
||||
with self.connect() as connection:
|
||||
connection.execute("VACUUM")
|
||||
@@ -0,0 +1,13 @@
|
||||
from datahub.governance.circuit import CircuitBreaker, CircuitState
|
||||
from datahub.governance.lkg import LastKnownGood
|
||||
from datahub.governance.ratelimit import TokenBucket
|
||||
from datahub.governance.retry import RetryError, retry_call
|
||||
|
||||
__all__ = [
|
||||
"CircuitBreaker",
|
||||
"CircuitState",
|
||||
"LastKnownGood",
|
||||
"RetryError",
|
||||
"TokenBucket",
|
||||
"retry_call",
|
||||
]
|
||||
@@ -0,0 +1,107 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
class CircuitState:
|
||||
state: str = "closed" # closed | open | half_open
|
||||
consec_failures: int = 0
|
||||
opened_at: float | None = None
|
||||
cooldown_until: float = 0.0
|
||||
last_error: str = ""
|
||||
last_ok_at: float | None = None
|
||||
|
||||
|
||||
class CircuitBreaker:
|
||||
"""Sliding-window breaker: 5 consecutive failures or >50% of 60s window → open."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
failure_threshold: int = 5,
|
||||
window_seconds: float = 60.0,
|
||||
open_seconds: float = 120.0,
|
||||
max_open_seconds: float = 600.0,
|
||||
clock=time.monotonic,
|
||||
) -> None:
|
||||
self.failure_threshold = failure_threshold
|
||||
self.window_seconds = window_seconds
|
||||
self.open_seconds = open_seconds
|
||||
self.max_open_seconds = max_open_seconds
|
||||
self._clock = clock
|
||||
self._lock = threading.Lock()
|
||||
self._events: deque[tuple[float, bool]] = deque()
|
||||
self.status = CircuitState()
|
||||
self._open_stretch = open_seconds
|
||||
|
||||
def allow(self) -> bool:
|
||||
with self._lock:
|
||||
self._refresh_locked()
|
||||
if self.status.state == "open":
|
||||
return False
|
||||
if self.status.state == "half_open":
|
||||
# single probe in flight: caller must record success/failure
|
||||
return True
|
||||
return True
|
||||
|
||||
def record_success(self) -> CircuitState:
|
||||
with self._lock:
|
||||
now = self._clock()
|
||||
self._events.append((now, True))
|
||||
self.status.last_ok_at = now
|
||||
self.status.consec_failures = 0
|
||||
self.status.last_error = ""
|
||||
self._open_stretch = self.open_seconds
|
||||
self.status.state = "closed"
|
||||
self.status.opened_at = None
|
||||
self.status.cooldown_until = 0.0
|
||||
return self._copy()
|
||||
|
||||
def record_failure(self, error: str = "") -> CircuitState:
|
||||
with self._lock:
|
||||
now = self._clock()
|
||||
self._events.append((now, False))
|
||||
self.status.consec_failures += 1
|
||||
self.status.last_error = error
|
||||
self._prune_locked(now)
|
||||
failures = sum(1 for _, ok in self._events if not ok)
|
||||
total = len(self._events)
|
||||
rate = (failures / total) if total else 0.0
|
||||
trip = self.status.consec_failures >= self.failure_threshold or (
|
||||
total >= self.failure_threshold and rate > 0.5
|
||||
)
|
||||
if trip:
|
||||
self.status.state = "open"
|
||||
self.status.opened_at = now
|
||||
self.status.cooldown_until = now + self._open_stretch
|
||||
self._open_stretch = min(self.max_open_seconds, self._open_stretch * 2)
|
||||
return self._copy()
|
||||
|
||||
def snapshot(self) -> CircuitState:
|
||||
with self._lock:
|
||||
self._refresh_locked()
|
||||
return self._copy()
|
||||
|
||||
def _refresh_locked(self) -> None:
|
||||
now = self._clock()
|
||||
self._prune_locked(now)
|
||||
if self.status.state == "open" and now >= self.status.cooldown_until:
|
||||
self.status.state = "half_open"
|
||||
|
||||
def _prune_locked(self, now: float) -> None:
|
||||
cutoff = now - self.window_seconds
|
||||
while self._events and self._events[0][0] < cutoff:
|
||||
self._events.popleft()
|
||||
|
||||
def _copy(self) -> CircuitState:
|
||||
return CircuitState(
|
||||
state=self.status.state,
|
||||
consec_failures=self.status.consec_failures,
|
||||
opened_at=self.status.opened_at,
|
||||
cooldown_until=self.status.cooldown_until,
|
||||
last_error=self.status.last_error,
|
||||
last_ok_at=self.status.last_ok_at,
|
||||
)
|
||||
@@ -0,0 +1,84 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from datahub.db import HubDB
|
||||
from datahub.timeutil import isoformat, now_shanghai
|
||||
|
||||
|
||||
class LastKnownGood:
|
||||
def __init__(self, db: HubDB) -> None:
|
||||
self.db = db
|
||||
|
||||
def store(self, cache_key: str, payload: Any, source: str) -> None:
|
||||
self.db.execute(
|
||||
"""
|
||||
INSERT INTO last_known_good(cache_key, payload, source, stored_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(cache_key) DO UPDATE SET
|
||||
payload=excluded.payload, source=excluded.source, stored_at=excluded.stored_at
|
||||
""",
|
||||
(cache_key, json.dumps(payload, ensure_ascii=False), source, isoformat()),
|
||||
)
|
||||
|
||||
def load(self, cache_key: str) -> dict[str, Any] | None:
|
||||
row = self.db.fetchone("SELECT * FROM last_known_good WHERE cache_key = ?", (cache_key,))
|
||||
if not row:
|
||||
return None
|
||||
return {
|
||||
"payload": json.loads(row["payload"]),
|
||||
"source": row["source"],
|
||||
"stored_at": row["stored_at"],
|
||||
}
|
||||
|
||||
def put_rt(self, cache_key: str, payload: Any, source: str, ttl_seconds: int) -> None:
|
||||
now = now_shanghai()
|
||||
expires = isoformat(now.replace(microsecond=0))
|
||||
# expires_at stored as iso; compute by adding ttl via timestamp
|
||||
from datetime import timedelta
|
||||
|
||||
self.db.execute(
|
||||
"""
|
||||
INSERT INTO rt_cache(cache_key, payload, source, stored_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(cache_key) DO UPDATE SET
|
||||
payload=excluded.payload, source=excluded.source,
|
||||
stored_at=excluded.stored_at, expires_at=excluded.expires_at
|
||||
""",
|
||||
(
|
||||
cache_key,
|
||||
json.dumps(payload, ensure_ascii=False),
|
||||
source,
|
||||
isoformat(now),
|
||||
isoformat(now + timedelta(seconds=ttl_seconds)),
|
||||
),
|
||||
)
|
||||
self.store(cache_key, payload, source)
|
||||
|
||||
def get_rt(self, cache_key: str, max_stale_seconds: int | None = None) -> dict[str, Any] | None:
|
||||
row = self.db.fetchone("SELECT * FROM rt_cache WHERE cache_key = ?", (cache_key,))
|
||||
if not row:
|
||||
lkg = self.load(cache_key)
|
||||
if not lkg:
|
||||
return None
|
||||
return {**lkg, "stale": True}
|
||||
stored_at = row["stored_at"]
|
||||
expired = row["expires_at"] < isoformat()
|
||||
result = {
|
||||
"payload": json.loads(row["payload"]),
|
||||
"source": row["source"],
|
||||
"stored_at": stored_at,
|
||||
"stale": expired,
|
||||
}
|
||||
if expired and max_stale_seconds is not None:
|
||||
from datetime import datetime
|
||||
|
||||
try:
|
||||
stored = datetime.fromisoformat(stored_at)
|
||||
age = (now_shanghai() - stored).total_seconds()
|
||||
except ValueError:
|
||||
age = max_stale_seconds + 1
|
||||
if age > max_stale_seconds:
|
||||
return None
|
||||
return result
|
||||
@@ -0,0 +1,36 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
class TokenBucket:
|
||||
def __init__(self, rate_per_minute: float, capacity: float | None = None, clock=time.monotonic) -> None:
|
||||
self.rate_per_second = max(0.001, rate_per_minute / 60.0)
|
||||
self.capacity = float(capacity if capacity is not None else rate_per_minute)
|
||||
self._tokens = self.capacity
|
||||
self._updated = clock()
|
||||
self._clock = clock
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def acquire(self, tokens: float = 1.0, block: bool = True) -> bool:
|
||||
while True:
|
||||
with self._lock:
|
||||
now = self._clock()
|
||||
elapsed = max(0.0, now - self._updated)
|
||||
self._tokens = min(self.capacity, self._tokens + elapsed * self.rate_per_second)
|
||||
self._updated = now
|
||||
if self._tokens >= tokens:
|
||||
self._tokens -= tokens
|
||||
return True
|
||||
wait = (tokens - self._tokens) / self.rate_per_second
|
||||
if not block:
|
||||
return False
|
||||
time.sleep(min(wait, 0.05))
|
||||
|
||||
@property
|
||||
def remaining(self) -> float:
|
||||
with self._lock:
|
||||
now = self._clock()
|
||||
elapsed = max(0.0, now - self._updated)
|
||||
return min(self.capacity, self._tokens + elapsed * self.rate_per_second)
|
||||
@@ -0,0 +1,35 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from typing import TypeVar
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class RetryError(RuntimeError):
|
||||
def __init__(self, message: str, attempts: int, last_error: BaseException | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.attempts = attempts
|
||||
self.last_error = last_error
|
||||
|
||||
|
||||
def retry_call(
|
||||
fn: Callable[[], T],
|
||||
attempts: int = 5,
|
||||
base_delay: float = 0.2,
|
||||
max_delay: float = 8.0,
|
||||
sleeper: Callable[[float], None] = time.sleep,
|
||||
retry_on: tuple[type[BaseException], ...] = (Exception,),
|
||||
) -> T:
|
||||
last: BaseException | None = None
|
||||
for attempt in range(1, max(1, attempts) + 1):
|
||||
try:
|
||||
return fn()
|
||||
except retry_on as exc:
|
||||
last = exc
|
||||
if attempt >= attempts:
|
||||
break
|
||||
delay = min(max_delay, base_delay * (2 ** (attempt - 1)))
|
||||
sleeper(delay)
|
||||
raise RetryError(f"retry exhausted after {attempts} attempts: {last}", attempts, last)
|
||||
@@ -0,0 +1,250 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import mimetypes
|
||||
import secrets
|
||||
from http import HTTPStatus
|
||||
from http.cookies import SimpleCookie
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Any
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
from datahub.hub import Hub
|
||||
from datahub.logutil import configure_logging, get_logger
|
||||
from datahub.serving import ApiError, parse_query
|
||||
|
||||
LOGGER = get_logger()
|
||||
SESSION_COOKIE = "datahub_session"
|
||||
|
||||
|
||||
class HubRequestHandler(BaseHTTPRequestHandler):
|
||||
hub: Hub
|
||||
|
||||
def log_message(self, format: str, *args: Any) -> None:
|
||||
LOGGER.info(format % args)
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
self._dispatch("GET")
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
self._dispatch("POST")
|
||||
|
||||
def do_OPTIONS(self) -> None: # noqa: N802
|
||||
self.send_response(HTTPStatus.NO_CONTENT)
|
||||
self.send_header("Allow", "GET, POST, OPTIONS")
|
||||
self.end_headers()
|
||||
|
||||
def _dispatch(self, method: str) -> None:
|
||||
parsed = urlparse(self.path)
|
||||
path = unquote(parsed.path)
|
||||
try:
|
||||
if path in {"/livez", "/healthz"}:
|
||||
self._json({"status": "ok"}, HTTPStatus.OK)
|
||||
return
|
||||
if path.startswith("/v1/"):
|
||||
self._v1(path, parsed.query)
|
||||
return
|
||||
if path.startswith("/admin/api/"):
|
||||
self._admin_api(method, path)
|
||||
return
|
||||
if path.startswith("/admin"):
|
||||
self._admin_static(path)
|
||||
return
|
||||
if path == "/":
|
||||
self.send_response(HTTPStatus.FOUND)
|
||||
self.send_header("Location", "/admin/")
|
||||
self.end_headers()
|
||||
return
|
||||
self._json({"error": {"code": "INVALID_ARGUMENT", "message": "Not found"}}, HTTPStatus.NOT_FOUND)
|
||||
except ApiError as exc:
|
||||
self._json(exc.payload(), exc.status)
|
||||
except PermissionError as exc:
|
||||
self._json({"error": {"code": "UNAUTHORIZED", "message": str(exc)}}, HTTPStatus.UNAUTHORIZED)
|
||||
except ValueError as exc:
|
||||
self._json({"error": {"code": "INVALID_ARGUMENT", "message": str(exc)}}, HTTPStatus.BAD_REQUEST)
|
||||
except Exception:
|
||||
LOGGER.exception("internal error")
|
||||
self._json({"error": {"code": "INTERNAL", "message": "internal error"}}, HTTPStatus.INTERNAL_SERVER_ERROR)
|
||||
|
||||
def _v1(self, path: str, query: str) -> None:
|
||||
token = self.headers.get("X-Datahub-Token", "")
|
||||
if not self.hub.auth.check_api_token(token):
|
||||
self.hub.pipeline.audit("anonymous", "unauthorized", path, "")
|
||||
raise ApiError("UNAUTHORIZED", "missing or invalid X-Datahub-Token")
|
||||
payload = self.hub.api.handle(path, parse_query(query))
|
||||
self._json(payload, HTTPStatus.OK)
|
||||
|
||||
def _admin_api(self, method: str, path: str) -> None:
|
||||
if path == "/admin/api/login" and method == "POST":
|
||||
body = self._read_json()
|
||||
result = self.hub.auth.login(str(body.get("username") or "hub_admin"), str(body.get("password") or ""))
|
||||
self._json(
|
||||
{"ok": True, "must_change": result["must_change"], "csrf": result["csrf"]},
|
||||
HTTPStatus.OK,
|
||||
extra_headers=[self._cookie(result["session"])],
|
||||
)
|
||||
return
|
||||
user = self.hub.auth.session_user(self._cookie_value(SESSION_COOKIE))
|
||||
if not user:
|
||||
raise ApiError("UNAUTHORIZED", "请先登录")
|
||||
if method == "POST" and path != "/admin/api/login":
|
||||
csrf = self.headers.get("X-CSRF-Token", "")
|
||||
if not csrf or not secrets.compare_digest(csrf, str(user["csrf_token"])):
|
||||
raise ApiError("UNAUTHORIZED", "CSRF 校验失败")
|
||||
if path == "/admin/api/logout" and method == "POST":
|
||||
self.hub.auth.logout(self._cookie_value(SESSION_COOKIE))
|
||||
self._json({"ok": True}, HTTPStatus.OK, extra_headers=[self._cookie("", clear=True)])
|
||||
return
|
||||
if path == "/admin/api/session" and method == "GET":
|
||||
self._json({"username": user["username"], "must_change": user["must_change"], "csrf": user["csrf_token"]}, HTTPStatus.OK)
|
||||
return
|
||||
if path == "/admin/api/change-password" and method == "POST":
|
||||
body = self._read_json()
|
||||
self.hub.auth.change_password(str(body.get("current") or ""), str(body.get("new_password") or ""))
|
||||
self.hub.pipeline.audit(user["username"], "change_password", "hub_admin", "")
|
||||
self._json({"ok": True}, HTTPStatus.OK)
|
||||
return
|
||||
if user["must_change"] and path not in {"/admin/api/change-password", "/admin/api/session"}:
|
||||
raise ApiError("UNAUTHORIZED", "请先修改初始密码")
|
||||
if path == "/admin/api/overview" and method == "GET":
|
||||
self._json(self.hub.admin.overview(), HTTPStatus.OK)
|
||||
return
|
||||
if path == "/admin/api/sources" and method == "GET":
|
||||
self._json(self.hub.admin.sources(), HTTPStatus.OK)
|
||||
return
|
||||
if path.startswith("/admin/api/sources/") and path.endswith("/probe") and method == "POST":
|
||||
provider = path.split("/")[4]
|
||||
self._json(self.hub.admin.probe(provider), HTTPStatus.OK)
|
||||
return
|
||||
if path == "/admin/api/jobs" and method == "GET":
|
||||
self._json(self.hub.admin.jobs(), HTTPStatus.OK)
|
||||
return
|
||||
if path.startswith("/admin/api/jobs/") and path.endswith("/run") and method == "POST":
|
||||
job_id = path.split("/")[4]
|
||||
body = self._read_json(allow_empty=True)
|
||||
self._json(self.hub.admin.run_job(job_id, str(body.get("trade_date") or "")), HTTPStatus.OK)
|
||||
return
|
||||
if path == "/admin/api/batches" and method == "GET":
|
||||
query = parse_query(urlparse(self.path).query)
|
||||
date = (query.get("date") or [""])[0]
|
||||
dataset = (query.get("dataset") or [""])[0]
|
||||
self._json(self.hub.admin.batches(date, dataset), HTTPStatus.OK)
|
||||
return
|
||||
if path == "/admin/api/datasets" and method == "GET":
|
||||
query = parse_query(urlparse(self.path).query)
|
||||
self._json(self.hub.admin.datasets((query.get("date") or [""])[0]), HTTPStatus.OK)
|
||||
return
|
||||
if path == "/admin/api/audit" and method == "GET":
|
||||
self._json(self.hub.admin.audit(), HTTPStatus.OK)
|
||||
return
|
||||
if path == "/admin/api/rollback" and method == "POST":
|
||||
body = self._read_json()
|
||||
result = self.hub.admin.rollback(
|
||||
str(body.get("dataset") or ""),
|
||||
str(body.get("trade_date") or ""),
|
||||
str(body.get("password") or ""),
|
||||
str(body.get("confirm") or ""),
|
||||
user["username"],
|
||||
)
|
||||
self._json(result, HTTPStatus.OK)
|
||||
return
|
||||
if path == "/admin/api/backfill" and method == "POST":
|
||||
body = self._read_json()
|
||||
result = self.hub.admin.backfill(
|
||||
str(body.get("dataset") or ""),
|
||||
str(body.get("trade_date") or ""),
|
||||
str(body.get("password") or ""),
|
||||
str(body.get("confirm") or ""),
|
||||
user["username"],
|
||||
)
|
||||
self._json(result, HTTPStatus.OK)
|
||||
return
|
||||
raise ApiError("INVALID_ARGUMENT", f"unknown admin endpoint: {path}")
|
||||
|
||||
def _admin_static(self, path: str) -> None:
|
||||
relative = path[len("/admin"):].lstrip("/") or "index.html"
|
||||
candidate = (self.hub.static_dir / relative).resolve()
|
||||
try:
|
||||
candidate.relative_to(self.hub.static_dir.resolve())
|
||||
except ValueError:
|
||||
self.send_error(HTTPStatus.FORBIDDEN)
|
||||
return
|
||||
if candidate.is_dir():
|
||||
candidate = candidate / "index.html"
|
||||
if not candidate.is_file():
|
||||
candidate = self.hub.static_dir / "index.html"
|
||||
content = candidate.read_bytes()
|
||||
content_type = mimetypes.guess_type(candidate.name)[0] or "application/octet-stream"
|
||||
if content_type.startswith("text/") or content_type in {"application/javascript", "application/json"}:
|
||||
content_type += "; charset=utf-8"
|
||||
self.send_response(HTTPStatus.OK)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(content)))
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
self.end_headers()
|
||||
self.wfile.write(content)
|
||||
|
||||
def _read_json(self, allow_empty: bool = False) -> dict[str, Any]:
|
||||
length = int(self.headers.get("Content-Length", "0") or 0)
|
||||
if length == 0 and allow_empty:
|
||||
return {}
|
||||
if length <= 0 or length > 65536:
|
||||
raise ValueError("请求内容为空或过大")
|
||||
raw = self.rfile.read(length)
|
||||
try:
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
LOGGER.warning("invalid json request body")
|
||||
raise ValueError("请求不是合法 JSON") from None
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("请求不是合法 JSON")
|
||||
return payload
|
||||
|
||||
def _cookie_value(self, name: str) -> str:
|
||||
cookie = SimpleCookie()
|
||||
try:
|
||||
cookie.load(self.headers.get("Cookie", ""))
|
||||
except Exception:
|
||||
return ""
|
||||
morsel = cookie.get(name)
|
||||
return morsel.value if morsel else ""
|
||||
|
||||
def _cookie(self, value: str, clear: bool = False) -> str:
|
||||
max_age = 0 if clear else 12 * 3600
|
||||
return f"{SESSION_COOKIE}={value}; Path=/; HttpOnly; SameSite=Strict; Max-Age={max_age}"
|
||||
|
||||
def _json(self, payload: dict[str, Any], status: HTTPStatus, extra_headers: list[str] | None = None) -> None:
|
||||
raw = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
for header in extra_headers or []:
|
||||
self.send_header("Set-Cookie", header)
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
|
||||
def make_handler(hub: Hub) -> type[HubRequestHandler]:
|
||||
class BoundHandler(HubRequestHandler):
|
||||
pass
|
||||
|
||||
BoundHandler.hub = hub
|
||||
BoundHandler.protocol_version = "HTTP/1.1"
|
||||
return BoundHandler
|
||||
|
||||
|
||||
def serve(hub: Hub, host: str, port: int) -> None:
|
||||
configure_logging(hub.settings.log_level)
|
||||
handler = make_handler(hub)
|
||||
server = ThreadingHTTPServer((host, port), handler)
|
||||
hub.start()
|
||||
LOGGER.info("xiaobai-datahub listening", extra={"hub": {"host": host, "port": port}})
|
||||
print(f"xiaobai-datahub is running at http://{host}:{port}/admin/")
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
hub.stop()
|
||||
server.server_close()
|
||||
@@ -0,0 +1,54 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from datahub.adapters.tushare import TushareAdapter
|
||||
from datahub.admin_api import AdminAPI
|
||||
from datahub.auth import AuthService
|
||||
from datahub.crypto import SecretVault
|
||||
from datahub.db import HubDB
|
||||
from datahub.governance.circuit import CircuitBreaker
|
||||
from datahub.governance.lkg import LastKnownGood
|
||||
from datahub.governance.ratelimit import TokenBucket
|
||||
from datahub.pipeline import Pipeline
|
||||
from datahub.scheduler import Scheduler
|
||||
from datahub.serving import V1API
|
||||
from datahub.settings import Settings, load_settings
|
||||
|
||||
|
||||
class Hub:
|
||||
def __init__(self, settings: Settings, adapter: TushareAdapter | None = None) -> None:
|
||||
if not settings.encryption_key:
|
||||
raise SystemExit("DATAHUB_ENCRYPTION_KEY 未配置")
|
||||
self.settings = settings
|
||||
self.db = HubDB(settings.db_path)
|
||||
self.vault = SecretVault(settings.encryption_key)
|
||||
self.auth = AuthService(self.db, self.vault, settings.api_token, settings.admin_password)
|
||||
token = settings.tushare_token or self.auth.load_credential("tushare_token")
|
||||
if settings.tushare_token:
|
||||
self.auth.store_credential("tushare_token", settings.tushare_token)
|
||||
token = settings.tushare_token
|
||||
self.adapter = adapter or TushareAdapter(token)
|
||||
self.pipeline = Pipeline(
|
||||
self.db,
|
||||
self.adapter,
|
||||
settings,
|
||||
bucket=TokenBucket(settings.tushare_rate_per_minute),
|
||||
breaker=CircuitBreaker(),
|
||||
)
|
||||
self.lkg = LastKnownGood(self.db)
|
||||
self.scheduler = Scheduler(self.db, self.pipeline)
|
||||
self.api = V1API(self.db, self.pipeline, settings)
|
||||
self.admin = AdminAPI(self.db, self.pipeline, self.scheduler, self.auth)
|
||||
self.static_dir = Path(__file__).resolve().parents[1] / "admin"
|
||||
|
||||
def start(self) -> None:
|
||||
if self.settings.scheduler_enabled:
|
||||
self.scheduler.start()
|
||||
|
||||
def stop(self) -> None:
|
||||
self.scheduler.stop()
|
||||
|
||||
|
||||
def build_hub(settings: Settings | None = None) -> Hub:
|
||||
return Hub(settings or load_settings())
|
||||
@@ -0,0 +1,82 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import sys
|
||||
import traceback
|
||||
from typing import Any
|
||||
|
||||
from datahub.timeutil import isoformat
|
||||
|
||||
_SECRET_KEYS = (
|
||||
"token", "password", "secret", "key", "authorization", "credential",
|
||||
"tushare_token", "datahub_token", "encryption_key", "cookie",
|
||||
)
|
||||
_SECRET_JSON = re.compile(
|
||||
r'(?i)("(?:' + "|".join(re.escape(key) for key in _SECRET_KEYS) + r')"\s*:\s*")([^"\\]*(?:\\.[^"\\]*)*)(")'
|
||||
)
|
||||
|
||||
|
||||
def redact_log_text(text: str) -> str:
|
||||
return _SECRET_JSON.sub(r"\1***\3", str(text))
|
||||
|
||||
|
||||
def _redact(value: Any, key: str = "") -> Any:
|
||||
lowered = key.lower()
|
||||
if any(part in lowered for part in _SECRET_KEYS):
|
||||
return "***"
|
||||
if isinstance(value, dict):
|
||||
return {str(item_key): _redact(item_value, str(item_key)) for item_key, item_value in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_redact(item) for item in value]
|
||||
if isinstance(value, str):
|
||||
return redact_log_text(value)
|
||||
return value
|
||||
|
||||
|
||||
def _safe_exc_text(exc_info: tuple[Any, Any, Any]) -> str:
|
||||
exc = exc_info[1]
|
||||
if isinstance(exc, json.JSONDecodeError):
|
||||
return f"JSONDecodeError: invalid json at position {exc.pos}"
|
||||
cause = getattr(exc, "__cause__", None)
|
||||
if isinstance(cause, json.JSONDecodeError):
|
||||
return f"{type(exc).__name__}: invalid json in request"
|
||||
text = "".join(traceback.format_exception(*exc_info))
|
||||
if isinstance(cause, json.JSONDecodeError) and cause.doc:
|
||||
text = text.replace(cause.doc, "")
|
||||
if isinstance(exc, json.JSONDecodeError) and exc.doc:
|
||||
text = text.replace(exc.doc, "")
|
||||
return redact_log_text(text)
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
payload: dict[str, Any] = {
|
||||
"ts": isoformat(),
|
||||
"level": record.levelname,
|
||||
"logger": record.name,
|
||||
"message": redact_log_text(record.getMessage()),
|
||||
}
|
||||
extra = getattr(record, "hub", None)
|
||||
if isinstance(extra, dict):
|
||||
payload.update(_redact(extra))
|
||||
if record.exc_info:
|
||||
payload["exc"] = _safe_exc_text(record.exc_info)
|
||||
return json.dumps(payload, ensure_ascii=False, default=str)
|
||||
|
||||
|
||||
def configure_logging(level: str = "INFO") -> logging.Logger:
|
||||
logger = logging.getLogger("datahub")
|
||||
if logger.handlers:
|
||||
return logger
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(JsonFormatter())
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(getattr(logging, level.upper(), logging.INFO))
|
||||
logger.propagate = False
|
||||
return logger
|
||||
|
||||
|
||||
def get_logger() -> logging.Logger:
|
||||
return logging.getLogger("datahub")
|
||||
@@ -0,0 +1,295 @@
|
||||
"""Canonical field normalization for Tushare-native rows.
|
||||
|
||||
Units (architecture §7.1):
|
||||
- price: 4 decimal REAL
|
||||
- pct_chg: percent, 4 decimal REAL
|
||||
- volume: shares (Tushare daily/index vol is 手 → ×100)
|
||||
- amount: yuan (Tushare daily/index amount is 千元 → ×1000)
|
||||
- moneyflow amounts: yuan (Tushare is 万元 → ×1e4)
|
||||
- daily_basic total_mv / circ_mv: yuan (Tushare is 万元 → ×1e4)
|
||||
- stk_auction.amount is already yuan in Tushare; volume 手 → ×100
|
||||
|
||||
Existing xiaobai-review stores Tushare native units and converts at display time.
|
||||
Hub converts once at ingest. Golden tests compare hub output against applying
|
||||
these same factors to review-native rows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from datahub.numbers import finite_number, round4
|
||||
|
||||
AMOUNT_THOUSAND_YUAN = 1000.0
|
||||
AMOUNT_WAN_YUAN = 10000.0
|
||||
VOLUME_LOT = 100.0
|
||||
|
||||
DAILY_FIELDS = ("ts_code", "trade_date", "open", "high", "low", "close", "pct_chg", "vol", "amount")
|
||||
VALUATION_FIELDS = (
|
||||
"ts_code", "trade_date", "turnover_rate", "volume_ratio",
|
||||
"total_mv", "circ_mv", "pe_ttm", "pb", "ps_ttm", "dv_ttm",
|
||||
)
|
||||
MONEYFLOW_FIELDS = (
|
||||
"ts_code", "trade_date",
|
||||
"buy_sm_amount", "sell_sm_amount", "buy_md_amount", "sell_md_amount",
|
||||
"buy_lg_amount", "sell_lg_amount", "buy_elg_amount", "sell_elg_amount",
|
||||
"net_mf_amount",
|
||||
)
|
||||
AUCTION_FIELDS = (
|
||||
"ts_code", "trade_date", "vol", "price", "amount", "pre_close",
|
||||
"turnover_rate", "volume_ratio", "float_share",
|
||||
)
|
||||
INDEX_FIELDS = ("ts_code", "trade_date", "open", "high", "low", "close", "pct_chg", "vol", "amount")
|
||||
CALENDAR_FIELDS = ("exchange", "cal_date", "is_open", "pretrade_date")
|
||||
STOCK_FIELDS = ("ts_code", "symbol", "name", "area", "industry", "market", "list_status", "list_date")
|
||||
|
||||
|
||||
def _code(value: Any) -> str:
|
||||
return str(value or "").strip().upper()
|
||||
|
||||
|
||||
def _date(value: Any) -> str:
|
||||
return str(value or "").replace("-", "")[:8]
|
||||
|
||||
|
||||
def review_daily_to_canonical(row: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Convert a review-stored daily row (Tushare native units) to hub canonical."""
|
||||
return normalize_daily(row)
|
||||
|
||||
|
||||
def normalize_daily(row: dict[str, Any], adj_factor: float | None = None) -> dict[str, Any]:
|
||||
return {
|
||||
"ts_code": _code(row.get("ts_code")),
|
||||
"trade_date": _date(row.get("trade_date")),
|
||||
"open": round4(finite_number(row.get("open"))),
|
||||
"high": round4(finite_number(row.get("high"))),
|
||||
"low": round4(finite_number(row.get("low"))),
|
||||
"close": round4(finite_number(row.get("close"))),
|
||||
"pct_chg": round4(finite_number(row.get("pct_chg"))),
|
||||
"volume": round4(_scale(row.get("vol"), VOLUME_LOT)),
|
||||
"amount": round4(_scale(row.get("amount"), AMOUNT_THOUSAND_YUAN)),
|
||||
"adj_factor": round4(finite_number(adj_factor if adj_factor is not None else row.get("adj_factor"))),
|
||||
}
|
||||
|
||||
|
||||
def normalize_valuation(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"ts_code": _code(row.get("ts_code")),
|
||||
"trade_date": _date(row.get("trade_date")),
|
||||
"turnover_rate": round4(finite_number(row.get("turnover_rate"))),
|
||||
"volume_ratio": round4(finite_number(row.get("volume_ratio"))),
|
||||
"total_mv": round4(_scale(row.get("total_mv"), AMOUNT_WAN_YUAN)),
|
||||
"circ_mv": round4(_scale(row.get("circ_mv"), AMOUNT_WAN_YUAN)),
|
||||
"pe_ttm": round4(finite_number(row.get("pe_ttm"))),
|
||||
"pb": round4(finite_number(row.get("pb"))),
|
||||
"ps_ttm": round4(finite_number(row.get("ps_ttm"))),
|
||||
"dv_ttm": round4(finite_number(row.get("dv_ttm"))),
|
||||
}
|
||||
|
||||
|
||||
def normalize_moneyflow(row: dict[str, Any]) -> dict[str, Any]:
|
||||
converted = {
|
||||
"ts_code": _code(row.get("ts_code")),
|
||||
"trade_date": _date(row.get("trade_date")),
|
||||
}
|
||||
for field in MONEYFLOW_FIELDS[2:]:
|
||||
converted[field] = round4(_scale(row.get(field), AMOUNT_WAN_YUAN))
|
||||
return converted
|
||||
|
||||
|
||||
def normalize_auction(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"ts_code": _code(row.get("ts_code")),
|
||||
"trade_date": _date(row.get("trade_date")),
|
||||
"volume": round4(_scale(row.get("vol") if row.get("vol") is not None else row.get("volume"), VOLUME_LOT)),
|
||||
"price": round4(finite_number(row.get("price"))),
|
||||
"amount": round4(finite_number(row.get("amount"))),
|
||||
"pre_close": round4(finite_number(row.get("pre_close"))),
|
||||
"turnover_rate": round4(finite_number(row.get("turnover_rate"))),
|
||||
"volume_ratio": round4(finite_number(row.get("volume_ratio"))),
|
||||
"float_share": round4(_scale(row.get("float_share"), AMOUNT_WAN_YUAN) if row.get("float_share") is not None else None),
|
||||
}
|
||||
|
||||
|
||||
def normalize_index_daily(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"ts_code": _code(row.get("ts_code")),
|
||||
"trade_date": _date(row.get("trade_date")),
|
||||
"open": round4(finite_number(row.get("open"))),
|
||||
"high": round4(finite_number(row.get("high"))),
|
||||
"low": round4(finite_number(row.get("low"))),
|
||||
"close": round4(finite_number(row.get("close"))),
|
||||
"pct_chg": round4(finite_number(row.get("pct_chg"))),
|
||||
"volume": round4(_scale(row.get("vol"), VOLUME_LOT)),
|
||||
"amount": round4(_scale(row.get("amount"), AMOUNT_THOUSAND_YUAN)),
|
||||
}
|
||||
|
||||
|
||||
def normalize_calendar(row: dict[str, Any]) -> dict[str, Any]:
|
||||
is_open = row.get("is_open")
|
||||
if is_open in (True, "1", 1, "Y", "y"):
|
||||
open_flag = 1
|
||||
elif is_open in (False, "0", 0, "N", "n", None, ""):
|
||||
open_flag = 0
|
||||
else:
|
||||
open_flag = int(is_open)
|
||||
return {
|
||||
"exchange": str(row.get("exchange") or "SSE"),
|
||||
"cal_date": _date(row.get("cal_date") or row.get("calDate")),
|
||||
"is_open": open_flag,
|
||||
"pretrade_date": _date(row.get("pretrade_date")) or None,
|
||||
}
|
||||
|
||||
|
||||
def normalize_stock(row: dict[str, Any]) -> dict[str, Any]:
|
||||
ts_code = _code(row.get("ts_code"))
|
||||
symbol = str(row.get("symbol") or "").strip() or (ts_code.split(".")[0] if ts_code else "")
|
||||
return {
|
||||
"ts_code": ts_code,
|
||||
"symbol": symbol,
|
||||
"name": str(row.get("name") or "").strip(),
|
||||
"area": str(row.get("area") or "").strip() or None,
|
||||
"industry": str(row.get("industry") or "").strip() or None,
|
||||
"market": str(row.get("market") or "").strip() or None,
|
||||
"list_status": str(row.get("list_status") or "L").strip() or "L",
|
||||
"list_date": _date(row.get("list_date")) or None,
|
||||
}
|
||||
|
||||
|
||||
def normalize_limit_event(row: dict[str, Any]) -> dict[str, Any]:
|
||||
"""limit_list_d. float_mv/total_mv/limit_amount are 万元 → yuan; amount/fd_amount already yuan."""
|
||||
return {
|
||||
"ts_code": _code(row.get("ts_code")),
|
||||
"trade_date": _date(row.get("trade_date")),
|
||||
"limit_type": str(row.get("limit_type") or "").strip().upper() or "U",
|
||||
"name": str(row.get("name") or "").strip() or None,
|
||||
"industry": str(row.get("industry") or "").strip() or None,
|
||||
"close": round4(finite_number(row.get("close"))),
|
||||
"pct_chg": round4(finite_number(row.get("pct_chg"))),
|
||||
"amount": round4(finite_number(row.get("amount"))),
|
||||
"limit_amount": round4(_scale(row.get("limit_amount"), AMOUNT_WAN_YUAN)),
|
||||
"float_mv": round4(_scale(row.get("float_mv"), AMOUNT_WAN_YUAN)),
|
||||
"total_mv": round4(_scale(row.get("total_mv"), AMOUNT_WAN_YUAN)),
|
||||
"turnover_ratio": round4(finite_number(row.get("turnover_ratio"))),
|
||||
"fd_amount": round4(finite_number(row.get("fd_amount"))),
|
||||
"first_time": str(row.get("first_time") or "").strip() or None,
|
||||
"last_time": str(row.get("last_time") or "").strip() or None,
|
||||
"open_times": _optional_int(row.get("open_times")),
|
||||
"up_stat": str(row.get("up_stat") or "").strip() or None,
|
||||
"limit_times": _optional_int(row.get("limit_times")),
|
||||
}
|
||||
|
||||
|
||||
def normalize_popularity(row: dict[str, Any], source: str = "") -> dict[str, Any]:
|
||||
src = str(source or row.get("source") or "").strip().lower() or "ths"
|
||||
return {
|
||||
"ts_code": _code(row.get("ts_code")),
|
||||
"trade_date": _date(row.get("trade_date")),
|
||||
"source": src,
|
||||
"ts_name": str(row.get("ts_name") or row.get("name") or "").strip() or None,
|
||||
"rank": _optional_int(row.get("rank")),
|
||||
"pct_change": round4(
|
||||
finite_number(row.get("pct_change") if row.get("pct_change") is not None else row.get("pct_chg"))
|
||||
),
|
||||
"current_price": round4(finite_number(row.get("current_price") or row.get("price"))),
|
||||
"hot": round4(finite_number(row.get("hot"))),
|
||||
"concept": str(row.get("concept") or "").strip() or None,
|
||||
"data_type": str(row.get("data_type") or "").strip() or None,
|
||||
}
|
||||
|
||||
|
||||
def normalize_dragon_tiger(row: dict[str, Any]) -> dict[str, Any]:
|
||||
"""hm_detail amounts are 万元 → yuan."""
|
||||
return {
|
||||
"ts_code": _code(row.get("ts_code")),
|
||||
"trade_date": _date(row.get("trade_date")),
|
||||
"hm_name": str(row.get("hm_name") or "未命名游资").strip() or "未命名游资",
|
||||
"ts_name": str(row.get("ts_name") or row.get("name") or "").strip() or None,
|
||||
"buy_amount": round4(_scale(row.get("buy_amount"), AMOUNT_WAN_YUAN)),
|
||||
"sell_amount": round4(_scale(row.get("sell_amount"), AMOUNT_WAN_YUAN)),
|
||||
"net_amount": round4(_scale(row.get("net_amount"), AMOUNT_WAN_YUAN)),
|
||||
"hm_orgs": str(row.get("hm_orgs") or "").strip() or None,
|
||||
"tag": str(row.get("tag") or "").strip() or None,
|
||||
"pct_change": round4(finite_number(row.get("pct_change"))),
|
||||
"reason": str(row.get("reason") or "").strip() or None,
|
||||
}
|
||||
|
||||
|
||||
def normalize_sector_daily(row: dict[str, Any], family: str = "ths") -> dict[str, Any]:
|
||||
fam = str(family or row.get("family") or "ths").strip().lower()
|
||||
return {
|
||||
"ts_code": _code(row.get("ts_code")),
|
||||
"trade_date": _date(row.get("trade_date")),
|
||||
"family": fam,
|
||||
"name": str(row.get("name") or "").strip() or None,
|
||||
"open": round4(finite_number(row.get("open"))),
|
||||
"high": round4(finite_number(row.get("high"))),
|
||||
"low": round4(finite_number(row.get("low"))),
|
||||
"close": round4(finite_number(row.get("close"))),
|
||||
"pre_close": round4(finite_number(row.get("pre_close"))),
|
||||
"pct_change": round4(
|
||||
finite_number(row.get("pct_change") if row.get("pct_change") is not None else row.get("pct_chg"))
|
||||
),
|
||||
"vol": round4(finite_number(row.get("vol"))),
|
||||
"turnover_rate": round4(finite_number(row.get("turnover_rate"))),
|
||||
"amount": round4(finite_number(row.get("amount"))),
|
||||
}
|
||||
|
||||
|
||||
def _optional_int(value: Any) -> int | None:
|
||||
if value in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return int(float(value))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def apply_qfq(price: float | None, factor: float | None, latest_factor: float | None) -> float | None:
|
||||
if price is None:
|
||||
return None
|
||||
current = factor if factor not in (None, 0) else 1.0
|
||||
latest = latest_factor if latest_factor not in (None, 0) else current
|
||||
return round4(price * current / latest)
|
||||
|
||||
|
||||
def qfq_bar(row: dict[str, Any], latest_factor: float | None) -> dict[str, Any]:
|
||||
factor = finite_number(row.get("adj_factor"), 1.0) or 1.0
|
||||
out = dict(row)
|
||||
for field in ("open", "high", "low", "close"):
|
||||
out[field] = apply_qfq(finite_number(row.get(field)), factor, latest_factor)
|
||||
return out
|
||||
|
||||
|
||||
NORMALIZERS = {
|
||||
"daily": normalize_daily,
|
||||
"valuation": normalize_valuation,
|
||||
"daily_basic": normalize_valuation,
|
||||
"moneyflow": normalize_moneyflow,
|
||||
"auction": normalize_auction,
|
||||
"stk_auction": normalize_auction,
|
||||
"index_daily": normalize_index_daily,
|
||||
"trade_cal": normalize_calendar,
|
||||
"calendar": normalize_calendar,
|
||||
"stock_basic": normalize_stock,
|
||||
"stocks": normalize_stock,
|
||||
"limit_events": normalize_limit_event,
|
||||
"limit_list_d": normalize_limit_event,
|
||||
"popularity": normalize_popularity,
|
||||
"dragon_tiger": normalize_dragon_tiger,
|
||||
"sector_daily": normalize_sector_daily,
|
||||
}
|
||||
|
||||
|
||||
def normalize_rows(dataset: str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
fn = NORMALIZERS.get(dataset)
|
||||
if fn is None:
|
||||
raise ValueError(f"unknown dataset: {dataset}")
|
||||
return [fn(row) for row in rows]
|
||||
|
||||
|
||||
def _scale(value: Any, factor: float) -> float | None:
|
||||
number = finite_number(value)
|
||||
if number is None:
|
||||
return None
|
||||
return number * factor
|
||||
@@ -0,0 +1,23 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import Any
|
||||
|
||||
|
||||
def finite_number(value: Any, default: float | None = None) -> float | None:
|
||||
"""Return a finite float, or default (None means JSON null)."""
|
||||
if value is None or value == "":
|
||||
return default
|
||||
try:
|
||||
number = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
if not math.isfinite(number):
|
||||
return default
|
||||
return number
|
||||
|
||||
|
||||
def round4(value: float | None) -> float | None:
|
||||
if value is None:
|
||||
return None
|
||||
return round(float(value), 4)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,260 @@
|
||||
"""Provisional (盘中观察) serving: quotes, index quotes, intraday points.
|
||||
|
||||
Free sources only. Never writes official eod_* tables. Uses rt_cache + LKG.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from datahub.adapters.eastmoney import EastmoneyAdapter
|
||||
from datahub.adapters.tencent import TencentAdapter
|
||||
from datahub.codes import resolve_code
|
||||
from datahub.db import HubDB
|
||||
from datahub.governance.lkg import LastKnownGood
|
||||
from datahub.timeutil import isoformat, now_shanghai, yyyymmdd
|
||||
|
||||
QUOTE_TTL = 60
|
||||
INDEX_TTL = 60
|
||||
INTRADAY_TTL = 20
|
||||
|
||||
|
||||
class RealtimeApiError(RuntimeError):
|
||||
def __init__(self, code: str, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
def _envelope(data: Any, meta: dict[str, Any]) -> dict[str, Any]:
|
||||
from datahub import SCHEMA_VERSION
|
||||
|
||||
return {"schema_version": SCHEMA_VERSION, "data": data, "meta": meta}
|
||||
|
||||
|
||||
def fetch_index_quotes(db: HubDB) -> dict[str, Any]:
|
||||
cache_key = "indexes:quotes"
|
||||
cached = _read_cache(db, cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
eastmoney = EastmoneyAdapter()
|
||||
try:
|
||||
rows = eastmoney.fetch_indices()
|
||||
source = "eastmoney:ulist"
|
||||
except Exception:
|
||||
rows = TencentAdapter().fetch_indices()
|
||||
source = "tencent:qt"
|
||||
if len(rows) < 3:
|
||||
raise RealtimeApiError("SOURCE_UNAVAILABLE", "index quotes incomplete")
|
||||
payload = _envelope(
|
||||
rows,
|
||||
{
|
||||
"tier": "provisional",
|
||||
"trade_date": yyyymmdd(now_shanghai()),
|
||||
"source": source,
|
||||
"stale": False,
|
||||
"staleness_seconds": 0,
|
||||
"published_at": isoformat(now_shanghai()),
|
||||
},
|
||||
)
|
||||
_write_cache(db, cache_key, payload, INDEX_TTL, source)
|
||||
return payload
|
||||
|
||||
|
||||
def fetch_market_quotes(db: HubDB) -> dict[str, Any]:
|
||||
cache_key = "quotes:market"
|
||||
cached = _read_cache(db, cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
adapter = EastmoneyAdapter()
|
||||
try:
|
||||
rows = adapter.fetch_market_quotes()
|
||||
source = "eastmoney:clist"
|
||||
except Exception as exc:
|
||||
raise RealtimeApiError("SOURCE_UNAVAILABLE", f"market quotes unavailable: {exc}") from exc
|
||||
payload = _envelope(
|
||||
rows,
|
||||
{
|
||||
"tier": "provisional",
|
||||
"trade_date": yyyymmdd(now_shanghai()),
|
||||
"source": source,
|
||||
"stale": False,
|
||||
"staleness_seconds": 0,
|
||||
"published_at": isoformat(now_shanghai()),
|
||||
"scope": "market",
|
||||
},
|
||||
)
|
||||
_write_cache(db, cache_key, payload, QUOTE_TTL, source)
|
||||
return payload
|
||||
|
||||
|
||||
def fetch_quotes(db: HubDB, codes: list[str]) -> dict[str, Any]:
|
||||
if not codes:
|
||||
return fetch_market_quotes(db)
|
||||
resolved: list[str] = []
|
||||
for code in codes[:60]:
|
||||
item = resolve_code(db, code) or _guess_ts_code(code)
|
||||
if item:
|
||||
resolved.append(item)
|
||||
if not resolved:
|
||||
raise RealtimeApiError("INVALID_ARGUMENT", "no resolvable codes")
|
||||
cache_key = "quotes:" + ",".join(sorted(resolved))
|
||||
cached = _read_cache(db, cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
adapter = EastmoneyAdapter()
|
||||
try:
|
||||
rows = adapter.fetch_quotes(resolved)
|
||||
source = "eastmoney:clist"
|
||||
except Exception as exc:
|
||||
raise RealtimeApiError("SOURCE_UNAVAILABLE", f"quotes unavailable: {exc}") from exc
|
||||
payload = _envelope(
|
||||
rows,
|
||||
{
|
||||
"tier": "provisional",
|
||||
"trade_date": yyyymmdd(now_shanghai()),
|
||||
"source": source,
|
||||
"stale": False,
|
||||
"staleness_seconds": 0,
|
||||
"published_at": isoformat(now_shanghai()),
|
||||
},
|
||||
)
|
||||
_write_cache(db, cache_key, payload, QUOTE_TTL, source)
|
||||
return payload
|
||||
|
||||
|
||||
def fetch_intraday(db: HubDB, code: str, date: str = "") -> dict[str, Any]:
|
||||
ts_code = resolve_code(db, code) or _guess_ts_code(code)
|
||||
if not ts_code:
|
||||
raise RealtimeApiError("INVALID_ARGUMENT", f"ambiguous code: {code}")
|
||||
cache_key = f"intraday:{ts_code}:{date or 'today'}"
|
||||
cached = _read_cache(db, cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
adapter = EastmoneyAdapter()
|
||||
try:
|
||||
payload_data = adapter.fetch_intraday(ts_code, date)
|
||||
source = "eastmoney:trends2"
|
||||
except Exception as exc:
|
||||
recovered = _load_intraday_lkg(db, ts_code, date)
|
||||
if recovered is None:
|
||||
raise RealtimeApiError("SOURCE_UNAVAILABLE", f"intraday unavailable: {exc}") from exc
|
||||
return recovered
|
||||
payload = _envelope(
|
||||
payload_data,
|
||||
{
|
||||
"tier": "provisional",
|
||||
"trade_date": yyyymmdd(payload_data.get("trade_date") or date or now_shanghai()),
|
||||
"source": source,
|
||||
"stale": False,
|
||||
"staleness_seconds": 0,
|
||||
"published_at": isoformat(now_shanghai()),
|
||||
},
|
||||
)
|
||||
_write_cache(db, cache_key, payload, INTRADAY_TTL, source)
|
||||
return payload
|
||||
|
||||
|
||||
def _load_intraday_lkg(db: HubDB, ts_code: str, date: str = "") -> dict[str, Any] | None:
|
||||
store = LastKnownGood(db)
|
||||
keys = [f"intraday:{ts_code}:{date or 'today'}"]
|
||||
if date:
|
||||
keys.append(f"intraday:{ts_code}:today")
|
||||
for key in keys:
|
||||
item = store.load(key)
|
||||
payload = _lkg_payload(item)
|
||||
if payload is not None:
|
||||
return payload
|
||||
row = db.fetchone(
|
||||
"SELECT * FROM last_known_good WHERE cache_key LIKE ? ORDER BY stored_at DESC LIMIT 1",
|
||||
(f"intraday:{ts_code}:%",),
|
||||
)
|
||||
if not row:
|
||||
return None
|
||||
try:
|
||||
raw = json.loads(row["payload"])
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return _mark_stale(raw) if isinstance(raw, dict) else None
|
||||
|
||||
|
||||
def _lkg_payload(item: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
if not item:
|
||||
return None
|
||||
payload = item.get("payload")
|
||||
return _mark_stale(payload) if isinstance(payload, dict) else None
|
||||
|
||||
|
||||
def _mark_stale(payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
data = payload.get("data")
|
||||
if not isinstance(data, dict) or not data.get("points"):
|
||||
return None
|
||||
stamped = dict(payload)
|
||||
meta = dict(stamped.get("meta") or {})
|
||||
meta["stale"] = True
|
||||
stamped["meta"] = meta
|
||||
return stamped
|
||||
|
||||
|
||||
def _guess_ts_code(code: str) -> str | None:
|
||||
raw = str(code or "").strip().upper()
|
||||
if "." in raw:
|
||||
return raw
|
||||
if len(raw) == 6 and raw.isdigit():
|
||||
if raw.startswith(("5", "6", "9")):
|
||||
return f"{raw}.SH"
|
||||
return f"{raw}.SZ"
|
||||
return None
|
||||
|
||||
|
||||
def _read_cache(db: HubDB, cache_key: str) -> dict[str, Any] | None:
|
||||
row = db.fetchone("SELECT * FROM rt_cache WHERE cache_key = ?", (cache_key,))
|
||||
if not row:
|
||||
return None
|
||||
expires = str(row.get("expires_at") or "")
|
||||
now = isoformat(now_shanghai())
|
||||
if expires and expires < now:
|
||||
return None
|
||||
try:
|
||||
payload = json.loads(row["payload"])
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
if isinstance(payload, dict) and isinstance(payload.get("meta"), dict):
|
||||
stored = str(row.get("stored_at") or "")
|
||||
try:
|
||||
age = max(0, int(time.time() - datetime.fromisoformat(stored).timestamp()))
|
||||
except Exception:
|
||||
age = 0
|
||||
payload["meta"]["staleness_seconds"] = age
|
||||
payload["meta"]["stale"] = age > QUOTE_TTL
|
||||
return payload
|
||||
|
||||
|
||||
def _write_cache(db: HubDB, cache_key: str, payload: dict[str, Any], ttl: int, source: str) -> None:
|
||||
from datetime import timedelta
|
||||
|
||||
now = now_shanghai()
|
||||
stored = isoformat(now)
|
||||
expires = isoformat(now + timedelta(seconds=ttl))
|
||||
db.execute(
|
||||
"""
|
||||
INSERT INTO rt_cache(cache_key, payload, source, stored_at, expires_at)
|
||||
VALUES (?,?,?,?,?)
|
||||
ON CONFLICT(cache_key) DO UPDATE SET
|
||||
payload=excluded.payload, source=excluded.source,
|
||||
stored_at=excluded.stored_at, expires_at=excluded.expires_at
|
||||
""",
|
||||
(cache_key, json.dumps(payload, ensure_ascii=False), source, stored, expires),
|
||||
)
|
||||
db.execute(
|
||||
"""
|
||||
INSERT INTO last_known_good(cache_key, payload, source, stored_at)
|
||||
VALUES (?,?,?,?)
|
||||
ON CONFLICT(cache_key) DO UPDATE SET
|
||||
payload=excluded.payload, source=excluded.source, stored_at=excluded.stored_at
|
||||
""",
|
||||
(cache_key, json.dumps(payload, ensure_ascii=False), source, stored),
|
||||
)
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Post-publish revision review for datasets whose upstream may rewrite T-day fields.
|
||||
|
||||
HEL-423 field evidence, not a whitelist of tolerated diffs:
|
||||
|
||||
- 2026-09-07 valuation/daily_basic: hub published 003021.SZ turnover_rate=1.3565
|
||||
at 17:10; website legacy and a direct Tushare read at 21:05 both showed 1.3572.
|
||||
The other seven observed objects (daily, moneyflow, auction, stocks, status,
|
||||
index_daily, calendar) matched. Hub had already stopped the day after the
|
||||
first successful publish, so the revision never self-healed.
|
||||
- 2026-09-02: same dataset, opposite direction (hub already held the later
|
||||
value). Confirms daily_basic is rewritten after the first complete dump.
|
||||
|
||||
Daily bars, moneyflow, auction and index_daily have no same-evening field
|
||||
revision evidence. Stocks already refreshes at 20:00/23:10. Review therefore
|
||||
fetches only configured revision-risk datasets (default: valuation) and
|
||||
compares the website-requested field set. No numeric tolerance.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from datahub.db import DATASET_TABLES
|
||||
from datahub.normalize import VALUATION_FIELDS
|
||||
from datahub.numbers import finite_number, round4
|
||||
|
||||
# Datasets with proven same-evening upstream rewrites. Config may replace this
|
||||
# list; it must not silently expand to a full EOD re-pull.
|
||||
DEFAULT_REVISION_DATASETS = ("valuation",)
|
||||
|
||||
# Website daily_basic request (HEL-423): ts_code/trade_date plus the eight
|
||||
# value fields used by the old link and field_gates.
|
||||
WEBSITE_COMPARE_FIELDS: dict[str, tuple[str, ...]] = {
|
||||
"valuation": VALUATION_FIELDS,
|
||||
}
|
||||
|
||||
REVISION_STATES = ("waiting_review", "review_failed", "aligned", "cutoff")
|
||||
|
||||
|
||||
def revision_datasets(quality: dict[str, Any] | None) -> tuple[str, ...]:
|
||||
raw = (quality or {}).get("revision_review_datasets")
|
||||
if isinstance(raw, (list, tuple)) and raw:
|
||||
names = tuple(str(item) for item in raw if str(item))
|
||||
if names:
|
||||
return names
|
||||
return DEFAULT_REVISION_DATASETS
|
||||
|
||||
|
||||
def compare_fields(dataset: str) -> tuple[str, ...]:
|
||||
fields = WEBSITE_COMPARE_FIELDS.get(dataset)
|
||||
if fields:
|
||||
return fields
|
||||
gate = {}
|
||||
return tuple(str(item) for item in (gate.get("fields") or []) if str(item))
|
||||
|
||||
|
||||
def _norm_value(field: str, value: Any) -> Any:
|
||||
if field in {"ts_code", "trade_date"}:
|
||||
return str(value or "")
|
||||
number = round4(finite_number(value))
|
||||
return number
|
||||
|
||||
|
||||
def row_signature(row: dict[str, Any], fields: tuple[str, ...]) -> tuple[Any, ...]:
|
||||
return tuple(_norm_value(field, row.get(field)) for field in fields)
|
||||
|
||||
|
||||
def diff_published_vs_upstream(
|
||||
dataset: str,
|
||||
published: list[dict[str, Any]],
|
||||
upstream: list[dict[str, Any]],
|
||||
*,
|
||||
max_diffs: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
"""Exact compare on website-requested fields. No tolerance / exemption."""
|
||||
fields = compare_fields(dataset)
|
||||
if not fields:
|
||||
fields = tuple(sorted({key for row in published + upstream for key in row if key != "batch_id"}))
|
||||
pub_map = {str(row.get("ts_code") or "").upper(): row for row in published}
|
||||
up_map = {str(row.get("ts_code") or "").upper(): row for row in upstream}
|
||||
missing = sorted(code for code in pub_map if code not in up_map)
|
||||
extra = sorted(code for code in up_map if code not in pub_map)
|
||||
diffs: list[dict[str, Any]] = []
|
||||
for code in sorted(set(pub_map) & set(up_map)):
|
||||
left = row_signature(pub_map[code], fields)
|
||||
right = row_signature(up_map[code], fields)
|
||||
if left == right:
|
||||
continue
|
||||
for field, old, new in zip(fields, left, right):
|
||||
if old == new:
|
||||
continue
|
||||
diffs.append({"ts_code": code, "field": field, "published": old, "upstream": new})
|
||||
if len(diffs) >= max_diffs:
|
||||
break
|
||||
if len(diffs) >= max_diffs:
|
||||
break
|
||||
changed = bool(diffs or missing or extra)
|
||||
return {
|
||||
"changed": changed,
|
||||
"dataset": dataset,
|
||||
"fields": list(fields),
|
||||
"published_rows": len(published),
|
||||
"upstream_rows": len(upstream),
|
||||
"missing_codes": missing[:max_diffs],
|
||||
"extra_codes": extra[:max_diffs],
|
||||
"diffs": diffs,
|
||||
}
|
||||
|
||||
|
||||
def official_table(dataset: str) -> str:
|
||||
return DATASET_TABLES[dataset][0]
|
||||
@@ -0,0 +1,583 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime, time, timedelta
|
||||
from typing import Any
|
||||
|
||||
from datahub.db import HubDB
|
||||
from datahub.logutil import get_logger
|
||||
from datahub.pipeline import Pipeline
|
||||
from datahub.revision import revision_datasets
|
||||
from datahub.timeutil import isoformat, now_shanghai, yyyymmdd
|
||||
|
||||
LOGGER = get_logger()
|
||||
|
||||
JobFn = Callable[[str], Any]
|
||||
|
||||
EOD_JOB_IDS = {"eod_a", "eod_b", "eod_retry", "eod_revise"}
|
||||
|
||||
|
||||
def is_open_day(db: HubDB, day: str) -> bool:
|
||||
row = db.fetchone(
|
||||
"SELECT is_open FROM trade_calendar WHERE exchange = 'SSE' AND cal_date = ?",
|
||||
(day,),
|
||||
)
|
||||
if row is None:
|
||||
return True # unknown calendar: do not skip reference refresh
|
||||
return int(row["is_open"]) == 1
|
||||
|
||||
|
||||
def previous_open_day(db: HubDB, day: str) -> str | None:
|
||||
row = db.fetchone(
|
||||
"""
|
||||
SELECT cal_date FROM trade_calendar
|
||||
WHERE exchange = 'SSE' AND is_open = 1 AND cal_date < ?
|
||||
ORDER BY cal_date DESC LIMIT 1
|
||||
""",
|
||||
(day,),
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
return str(row["cal_date"])
|
||||
|
||||
|
||||
def _hhmm(value: str) -> time:
|
||||
return datetime.strptime(value, "%H:%M").time()
|
||||
|
||||
|
||||
class Scheduler:
|
||||
"""Calendar-driven in-process scheduler. Non-trading days skip EOD fetches.
|
||||
|
||||
EOD datasets that failed to publish (e.g. upstream not ready at 15:05)
|
||||
are retried automatically every ``eod_retry_interval_minutes`` between
|
||||
``eod_retry_start`` and ``eod_retry_cutoff``. Progress is persisted in
|
||||
``eod_progress`` so a container restart catches up instead of waiting
|
||||
for the next day, and completed days are never re-fetched.
|
||||
"""
|
||||
|
||||
def __init__(self, db: HubDB, pipeline: Pipeline, jobs: dict[str, JobFn] | None = None) -> None:
|
||||
self.db = db
|
||||
self.pipeline = pipeline
|
||||
self.jobs = jobs or {
|
||||
"precheck": self._precheck,
|
||||
"eod_a": self._eod_a,
|
||||
"eod_b": self._eod_b,
|
||||
"eod_c": self._eod_c,
|
||||
"eod_d": self._eod_d,
|
||||
"eod_e": self._eod_e,
|
||||
"eod_f": self._eod_f,
|
||||
"eod_retry": self._eod_retry,
|
||||
"eod_revise": self._eod_revise,
|
||||
"stocks_refresh": self._stocks_refresh,
|
||||
"cleanup": self._cleanup,
|
||||
"backup": self._backup,
|
||||
"history_backfill": self._history_backfill,
|
||||
}
|
||||
self._stop = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
self._fired: set[tuple[str, str, str]] = set()
|
||||
self._eod_lock = threading.Lock()
|
||||
|
||||
def start(self, interval_seconds: float = 30.0) -> None:
|
||||
if self._thread and self._thread.is_alive():
|
||||
return
|
||||
|
||||
def loop() -> None:
|
||||
while not self._stop.wait(interval_seconds):
|
||||
try:
|
||||
self.tick()
|
||||
except Exception:
|
||||
LOGGER.exception("scheduler tick failed")
|
||||
|
||||
self._thread = threading.Thread(target=loop, name="datahub-scheduler", daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self, timeout: float = 5.0) -> None:
|
||||
self._stop.set()
|
||||
if self._thread and self._thread is not threading.current_thread():
|
||||
self._thread.join(timeout)
|
||||
|
||||
def tick(self, clock: datetime | None = None) -> list[str]:
|
||||
now = now_shanghai(clock)
|
||||
day = yyyymmdd(now)
|
||||
current = now.time()
|
||||
ran: list[str] = []
|
||||
plan = [
|
||||
("precheck", time(8, 45)),
|
||||
("eod_a", time(15, 5)),
|
||||
("eod_b", time(15, 10)),
|
||||
("eod_c", time(16, 40)),
|
||||
("eod_d", time(16, 45)),
|
||||
("eod_e", time(18, 5)),
|
||||
("eod_f", time(22, 40)),
|
||||
("cleanup", time(0, 30)),
|
||||
("backup", time(0, 40)),
|
||||
]
|
||||
for refresh_at in self.pipeline.settings.stocks_refresh_times:
|
||||
plan.append(("stocks_refresh", _hhmm(refresh_at)))
|
||||
open_day = is_open_day(self.db, day)
|
||||
for job_id, at in plan:
|
||||
if current < at:
|
||||
continue
|
||||
key = (job_id, day, at.strftime("%H%M"))
|
||||
if key in self._fired:
|
||||
continue
|
||||
if job_id in {"eod_a", "eod_b", "eod_c", "eod_d", "eod_e", "eod_f", "stocks_refresh"} and not open_day:
|
||||
self._fired.add(key)
|
||||
continue
|
||||
self._fired.add(key)
|
||||
if job_id in {"eod_a", "eod_b"}:
|
||||
# Record the attempt before running: even a crash must not
|
||||
# hide that today's first EOD try already happened.
|
||||
self._record_eod_attempt(day, now)
|
||||
try:
|
||||
self.run_job(job_id, day)
|
||||
except Exception:
|
||||
if job_id not in {"eod_a", "eod_b", "eod_c", "eod_d", "eod_e", "eod_f", "stocks_refresh"}:
|
||||
raise
|
||||
# Keep the tick alive; evening retries take over.
|
||||
LOGGER.exception("scheduled job %s failed for %s", job_id, day)
|
||||
ran.append(job_id)
|
||||
if job_id in {"eod_a", "eod_b"}:
|
||||
self._settle_eod(day)
|
||||
ran.extend(self._eod_retry_tick(now, day, open_day))
|
||||
ran.extend(self._revision_review_tick(now, day, open_day))
|
||||
ran.extend(self._revision_catchup_tick(now, day))
|
||||
return ran
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# EOD retry window
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _eod_retry_tick(self, now: datetime, day: str, open_day: bool) -> list[str]:
|
||||
if not open_day:
|
||||
return []
|
||||
settings = self.pipeline.settings
|
||||
current = now.time()
|
||||
start = _hhmm(settings.eod_retry_start)
|
||||
cutoff = _hhmm(settings.eod_retry_cutoff)
|
||||
interval = timedelta(minutes=settings.eod_retry_interval_minutes)
|
||||
missing = self.pipeline.missing_official_datasets(day)
|
||||
row = self.eod_progress(day)
|
||||
|
||||
if not missing:
|
||||
if row is None or row["state"] != "done":
|
||||
self._save_eod_progress(day, state="done", finished_at=isoformat(now))
|
||||
return []
|
||||
if current < start:
|
||||
return []
|
||||
if row and row["state"] == "cutoff_failed":
|
||||
return []
|
||||
if current >= cutoff:
|
||||
detail = "截止时间已到,缺失数据集: " + ",".join(missing)
|
||||
self._save_eod_progress(day, state="cutoff_failed", finished_at=isoformat(now), detail=detail)
|
||||
with self.db.write() as connection:
|
||||
connection.execute(
|
||||
"INSERT INTO job_runs(job_id, state, started_at, finished_at, error, attempt, detail)"
|
||||
" VALUES ('eod_retry','failed',?,?,?,?,?)",
|
||||
(isoformat(now), isoformat(now), detail, int((row or {}).get("attempts") or 0), "eod cutoff reached"),
|
||||
)
|
||||
LOGGER.warning(
|
||||
"eod retry window closed without data",
|
||||
extra={"hub": {"trade_date": day, "missing": missing, "reason": "eod_cutoff"}},
|
||||
)
|
||||
return []
|
||||
last = None
|
||||
if row and row["last_attempt_at"]:
|
||||
try:
|
||||
last = datetime.fromisoformat(str(row["last_attempt_at"]))
|
||||
except ValueError:
|
||||
last = None
|
||||
if last is not None and now_shanghai(last).replace(tzinfo=None) + interval > now.replace(tzinfo=None):
|
||||
return []
|
||||
if "eod_retry" not in self.jobs:
|
||||
return []
|
||||
self._record_eod_attempt(day, now)
|
||||
ran = []
|
||||
try:
|
||||
self.run_job("eod_retry", day)
|
||||
except Exception:
|
||||
# job_runs already carries the failure; the window keeps retrying.
|
||||
LOGGER.warning("eod retry failed for %s", day, exc_info=True)
|
||||
ran.append("eod_retry")
|
||||
self._settle_eod(day)
|
||||
return ran
|
||||
|
||||
def _settle_eod(self, day: str) -> None:
|
||||
"""Flip the day to done as soon as every official dataset is published."""
|
||||
if not self.pipeline.missing_official_datasets(day):
|
||||
row = self.eod_progress(day)
|
||||
if row is None or row["state"] != "done":
|
||||
self._save_eod_progress(day, state="done", finished_at=isoformat())
|
||||
|
||||
def eod_progress(self, day: str) -> dict[str, Any] | None:
|
||||
return self.db.fetchone("SELECT * FROM eod_progress WHERE trade_date = ?", (day,))
|
||||
|
||||
def eod_status(self, trade_date: str | None = None, clock: datetime | None = None) -> dict[str, Any]:
|
||||
"""Human/admin facing view: 等待上游 / 下次重试 / 已成功 / 已截止失败."""
|
||||
day = yyyymmdd(trade_date or now_shanghai(clock))
|
||||
now = now_shanghai(clock)
|
||||
row = self.eod_progress(day)
|
||||
open_day = is_open_day(self.db, day)
|
||||
missing = self.pipeline.missing_official_datasets(day)
|
||||
if row and row["state"] == "done":
|
||||
state = "done"
|
||||
elif not open_day:
|
||||
state = "closed_day"
|
||||
elif not missing:
|
||||
state = "done"
|
||||
elif row and row["state"] == "cutoff_failed":
|
||||
state = "cutoff_failed"
|
||||
elif now.time() < _hhmm("15:05"):
|
||||
state = "pending_first_attempt"
|
||||
else:
|
||||
state = "waiting_upstream"
|
||||
return {
|
||||
"trade_date": day,
|
||||
"is_open_day": open_day,
|
||||
"state": state,
|
||||
"missing_datasets": missing,
|
||||
"attempts": int((row or {}).get("attempts") or 0),
|
||||
"last_attempt_at": (row or {}).get("last_attempt_at"),
|
||||
"next_retry_at": (row or {}).get("next_retry_at") if state == "waiting_upstream" else None,
|
||||
"finished_at": (row or {}).get("finished_at"),
|
||||
"detail": (row or {}).get("detail"),
|
||||
}
|
||||
|
||||
def revision_progress(self, day: str) -> dict[str, Any] | None:
|
||||
return self.db.fetchone("SELECT * FROM revision_progress WHERE trade_date = ?", (day,))
|
||||
|
||||
def revision_status(self, trade_date: str | None = None, clock: datetime | None = None) -> dict[str, Any]:
|
||||
"""等待复核 / 复核失败 / 已追平 / 已截止."""
|
||||
day = yyyymmdd(trade_date or now_shanghai(clock))
|
||||
row = self.revision_progress(day)
|
||||
open_day = is_open_day(self.db, day)
|
||||
published = self._revision_ready(day)
|
||||
if row and row["state"] in {"aligned", "review_failed", "cutoff", "waiting_review"}:
|
||||
state = str(row["state"])
|
||||
elif not open_day:
|
||||
state = "closed_day"
|
||||
elif not published:
|
||||
state = "pending_publish"
|
||||
else:
|
||||
state = "waiting_review"
|
||||
return {
|
||||
"trade_date": day,
|
||||
"is_open_day": open_day,
|
||||
"state": state,
|
||||
"datasets": list(revision_datasets(self.pipeline.settings.quality)),
|
||||
"attempts": int((row or {}).get("attempts") or 0),
|
||||
"last_attempt_at": (row or {}).get("last_attempt_at"),
|
||||
"next_retry_at": (row or {}).get("next_retry_at") if state in {"waiting_review", "review_failed"} else None,
|
||||
"finished_at": (row or {}).get("finished_at"),
|
||||
"catchup_done": bool(int((row or {}).get("catchup_done") or 0)),
|
||||
"detail": (row or {}).get("detail"),
|
||||
"window": f"{self.pipeline.settings.revision_review_start}-{self.pipeline.settings.revision_review_cutoff}",
|
||||
}
|
||||
|
||||
def _revision_ready(self, day: str) -> bool:
|
||||
return all(
|
||||
self.pipeline.active_batch(dataset, day)
|
||||
for dataset in revision_datasets(self.pipeline.settings.quality)
|
||||
)
|
||||
|
||||
def _revision_due(self, now: datetime, row: dict[str, Any] | None) -> bool:
|
||||
if row is None or not row.get("last_attempt_at"):
|
||||
return True
|
||||
try:
|
||||
last = datetime.fromisoformat(str(row["last_attempt_at"]))
|
||||
except ValueError:
|
||||
return True
|
||||
interval = timedelta(minutes=self.pipeline.settings.revision_review_interval_minutes)
|
||||
return now_shanghai(last).replace(tzinfo=None) + interval <= now.replace(tzinfo=None)
|
||||
|
||||
def _revision_review_tick(self, now: datetime, day: str, open_day: bool) -> list[str]:
|
||||
if not open_day or not self._revision_ready(day):
|
||||
return []
|
||||
settings = self.pipeline.settings
|
||||
current = now.time()
|
||||
start = _hhmm(settings.revision_review_start)
|
||||
cutoff = _hhmm(settings.revision_review_cutoff)
|
||||
row = self.revision_progress(day)
|
||||
if current < start:
|
||||
if row is None:
|
||||
self._save_revision_progress(day, state="waiting_review")
|
||||
return []
|
||||
if current >= cutoff:
|
||||
if row is None or row["state"] not in {"aligned", "cutoff"}:
|
||||
detail = "复核窗口已截止"
|
||||
self._save_revision_progress(
|
||||
day, state="cutoff", finished_at=isoformat(now), detail=detail,
|
||||
)
|
||||
with self.db.write() as connection:
|
||||
connection.execute(
|
||||
"INSERT INTO job_runs(job_id, state, started_at, finished_at, error, attempt, detail)"
|
||||
" VALUES ('eod_revise','failed',?,?,?,?,?)",
|
||||
(
|
||||
isoformat(now), isoformat(now), detail,
|
||||
int((row or {}).get("attempts") or 0), "revision cutoff reached",
|
||||
),
|
||||
)
|
||||
elif row["state"] == "aligned" and not row.get("finished_at"):
|
||||
self._save_revision_progress(day, finished_at=isoformat(now))
|
||||
return []
|
||||
if not self._revision_due(now, row):
|
||||
return []
|
||||
if "eod_revise" not in self.jobs:
|
||||
return []
|
||||
return self._run_revision_job(day, now, catchup=False)
|
||||
|
||||
def _revision_catchup_tick(self, now: datetime, day: str) -> list[str]:
|
||||
prev = previous_open_day(self.db, day)
|
||||
if prev is None or prev >= day:
|
||||
return []
|
||||
if not self._revision_ready(prev):
|
||||
return []
|
||||
row = self.revision_progress(prev)
|
||||
if row and int(row.get("catchup_done") or 0):
|
||||
return []
|
||||
if not self._revision_due(now, row):
|
||||
return []
|
||||
if "eod_revise" not in self.jobs:
|
||||
return []
|
||||
return self._run_revision_job(prev, now, catchup=True)
|
||||
|
||||
def _run_revision_job(self, day: str, now: datetime, catchup: bool) -> list[str]:
|
||||
attempts = int((self.revision_progress(day) or {}).get("attempts") or 0) + 1
|
||||
interval = self.pipeline.settings.revision_review_interval_minutes
|
||||
self._save_revision_progress(
|
||||
day,
|
||||
state="waiting_review",
|
||||
attempts=attempts,
|
||||
last_attempt_at=isoformat(now),
|
||||
next_retry_at=isoformat(now + timedelta(minutes=interval)),
|
||||
)
|
||||
ran: list[str] = []
|
||||
try:
|
||||
out = self.run_job("eod_revise", day)
|
||||
except Exception as exc:
|
||||
LOGGER.warning("revision review failed for %s: %s", day, exc)
|
||||
self._save_revision_progress(
|
||||
day,
|
||||
state="review_failed",
|
||||
detail="复核失败,保留上一完整版本",
|
||||
)
|
||||
ran.append("eod_revise")
|
||||
return ran
|
||||
ran.append("eod_revise")
|
||||
if out.get("state") == "skipped":
|
||||
return ran
|
||||
result = out.get("result") if isinstance(out.get("result"), dict) else {}
|
||||
failed = [
|
||||
name for name, item in result.items()
|
||||
if isinstance(item, dict) and item.get("state") == "failed"
|
||||
]
|
||||
review = result.get("review") if isinstance(result.get("review"), dict) else None
|
||||
watched = [
|
||||
result[name]
|
||||
for name in revision_datasets(self.pipeline.settings.quality)
|
||||
if isinstance(result.get(name), dict)
|
||||
]
|
||||
diff_blob = None
|
||||
if review and review.get("diffs"):
|
||||
diff_blob = json.dumps(review.get("diffs"), ensure_ascii=False)
|
||||
else:
|
||||
for item in watched:
|
||||
if item.get("diffs"):
|
||||
diff_blob = json.dumps(item.get("diffs"), ensure_ascii=False)
|
||||
break
|
||||
revised = bool(review and review.get("reason") == "revised")
|
||||
matched = any(item.get("reason") == "unchanged" or item.get("state") == "aligned" for item in watched)
|
||||
if failed:
|
||||
self._save_revision_progress(
|
||||
day,
|
||||
state="review_failed",
|
||||
detail="复核失败,保留上一完整版本",
|
||||
last_diff=diff_blob,
|
||||
)
|
||||
elif revised or matched:
|
||||
fields: dict[str, Any] = {
|
||||
"state": "aligned",
|
||||
"finished_at": isoformat(now),
|
||||
"detail": "已追平" if revised else "已追平(无变化)",
|
||||
"last_diff": diff_blob,
|
||||
}
|
||||
if catchup:
|
||||
fields["catchup_done"] = 1
|
||||
self._save_revision_progress(day, **fields)
|
||||
return ran
|
||||
|
||||
def _save_revision_progress(self, day: str, **fields: Any) -> None:
|
||||
columns = [
|
||||
"trade_date", "state", "attempts", "last_attempt_at",
|
||||
"next_retry_at", "finished_at", "catchup_done", "last_diff", "detail", "updated_at",
|
||||
]
|
||||
with self.db.write() as connection:
|
||||
existing = connection.execute(
|
||||
"SELECT trade_date FROM revision_progress WHERE trade_date = ?",
|
||||
(day,),
|
||||
).fetchone()
|
||||
if existing is None:
|
||||
payload = {name: None for name in columns}
|
||||
payload.update({
|
||||
"trade_date": day,
|
||||
"state": "waiting_review",
|
||||
"attempts": 0,
|
||||
"catchup_done": 0,
|
||||
})
|
||||
payload.update(fields)
|
||||
payload["updated_at"] = isoformat()
|
||||
placeholders = ",".join("?" for _ in columns)
|
||||
connection.execute(
|
||||
f"INSERT INTO revision_progress({','.join(columns)}) VALUES ({placeholders})",
|
||||
tuple(payload[name] for name in columns),
|
||||
)
|
||||
else:
|
||||
assignments = ", ".join(f"{name} = ?" for name in fields)
|
||||
connection.execute(
|
||||
f"UPDATE revision_progress SET {assignments}, updated_at = ? WHERE trade_date = ?",
|
||||
(*fields.values(), isoformat(), day),
|
||||
)
|
||||
|
||||
def _record_eod_attempt(self, day: str, now: datetime) -> None:
|
||||
row = self.eod_progress(day)
|
||||
attempts = int((row or {}).get("attempts") or 0) + 1
|
||||
interval = self.pipeline.settings.eod_retry_interval_minutes
|
||||
self._save_eod_progress(
|
||||
day,
|
||||
state="waiting_upstream",
|
||||
attempts=attempts,
|
||||
last_attempt_at=isoformat(now),
|
||||
next_retry_at=isoformat(now + timedelta(minutes=interval)),
|
||||
)
|
||||
|
||||
def _save_eod_progress(self, day: str, **fields: Any) -> None:
|
||||
columns = [
|
||||
"trade_date", "state", "attempts", "last_attempt_at",
|
||||
"next_retry_at", "finished_at", "detail", "updated_at",
|
||||
]
|
||||
with self.db.write() as connection:
|
||||
existing = connection.execute(
|
||||
"SELECT trade_date FROM eod_progress WHERE trade_date = ?",
|
||||
(day,),
|
||||
).fetchone()
|
||||
if existing is None:
|
||||
payload = {name: None for name in columns}
|
||||
payload.update({"trade_date": day, "state": "waiting_upstream", "attempts": 0})
|
||||
payload.update(fields)
|
||||
payload["updated_at"] = isoformat()
|
||||
placeholders = ",".join("?" for _ in columns)
|
||||
connection.execute(
|
||||
f"INSERT INTO eod_progress({','.join(columns)}) VALUES ({placeholders})",
|
||||
tuple(payload[name] for name in columns),
|
||||
)
|
||||
else:
|
||||
assignments = ", ".join(f"{name} = ?" for name in fields)
|
||||
connection.execute(
|
||||
f"UPDATE eod_progress SET {assignments}, updated_at = ? WHERE trade_date = ?",
|
||||
(*fields.values(), isoformat(), day),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Job execution
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def run_job(self, job_id: str, trade_date: str) -> dict[str, Any]:
|
||||
fn = self.jobs.get(job_id)
|
||||
if fn is None:
|
||||
raise KeyError(job_id)
|
||||
if job_id in EOD_JOB_IDS:
|
||||
if not self._eod_lock.acquire(blocking=False):
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"state": "skipped",
|
||||
"detail": "another EOD job is already running",
|
||||
}
|
||||
try:
|
||||
return self._run_job(fn, job_id, trade_date)
|
||||
finally:
|
||||
self._eod_lock.release()
|
||||
return self._run_job(fn, job_id, trade_date)
|
||||
|
||||
def _run_job(self, fn: JobFn, job_id: str, trade_date: str) -> dict[str, Any]:
|
||||
started = isoformat()
|
||||
run_id = None
|
||||
with self.db.write() as connection:
|
||||
cur = connection.execute(
|
||||
"INSERT INTO job_runs(job_id, state, started_at, attempt) VALUES (?,?,?,1)",
|
||||
(job_id, "running", started),
|
||||
)
|
||||
run_id = cur.lastrowid
|
||||
try:
|
||||
result = fn(trade_date) or {}
|
||||
if isinstance(result, dict):
|
||||
failures = self.pipeline.eod_failures(result) if job_id in EOD_JOB_IDS else []
|
||||
if failures:
|
||||
raise RuntimeError("; ".join(failures))
|
||||
with self.db.write() as connection:
|
||||
connection.execute(
|
||||
"UPDATE job_runs SET state=?, finished_at=?, rows_out=?, detail=? WHERE id=?",
|
||||
("ok", isoformat(), result.get("rows") if isinstance(result, dict) else None, str(result)[:2000], run_id),
|
||||
)
|
||||
return {"job_id": job_id, "result": result, "state": "ok"}
|
||||
except Exception as exc:
|
||||
with self.db.write() as connection:
|
||||
connection.execute(
|
||||
"UPDATE job_runs SET state=?, finished_at=?, error=? WHERE id=?",
|
||||
("failed", isoformat(), str(exc), run_id),
|
||||
)
|
||||
raise
|
||||
|
||||
def _precheck(self, trade_date: str) -> dict[str, Any]:
|
||||
return self.pipeline.ingest_reference(trade_date)
|
||||
|
||||
def _eod_a(self, trade_date: str) -> dict[str, Any]:
|
||||
return self.pipeline.run_eod_batch_a(trade_date)
|
||||
|
||||
def _eod_b(self, trade_date: str) -> dict[str, Any]:
|
||||
return self.pipeline.run_eod_batch_b(trade_date)
|
||||
|
||||
def _eod_c(self, trade_date: str) -> dict[str, Any]:
|
||||
return self.pipeline.run_eod_batch_c(trade_date)
|
||||
|
||||
def _eod_d(self, trade_date: str) -> dict[str, Any]:
|
||||
return self.pipeline.run_eod_batch_d(trade_date)
|
||||
|
||||
def _eod_e(self, trade_date: str) -> dict[str, Any]:
|
||||
return self.pipeline.run_eod_batch_e(trade_date)
|
||||
|
||||
def _eod_f(self, trade_date: str) -> dict[str, Any]:
|
||||
return self.pipeline.run_eod_batch_f(trade_date)
|
||||
|
||||
def _eod_retry(self, trade_date: str) -> dict[str, Any]:
|
||||
return self.pipeline.run_eod_missing(trade_date)
|
||||
|
||||
def _eod_revise(self, trade_date: str) -> dict[str, Any]:
|
||||
return self.pipeline.review_published_revisions(trade_date)
|
||||
|
||||
def _stocks_refresh(self, trade_date: str) -> dict[str, Any]:
|
||||
return self.pipeline.refresh_stocks(trade_date)
|
||||
|
||||
def _history_backfill(self, trade_date: str) -> dict[str, Any]:
|
||||
return self.pipeline.backfill_history(trade_date)
|
||||
|
||||
def _cleanup(self, trade_date: str) -> dict[str, Any]:
|
||||
result = self.pipeline.cleanup()
|
||||
if now_shanghai().weekday() == 6:
|
||||
self.pipeline.db.vacuum()
|
||||
result["vacuum"] = True
|
||||
return result
|
||||
|
||||
def _backup(self, trade_date: str) -> dict[str, Any]:
|
||||
from pathlib import Path
|
||||
|
||||
dest_dir = Path(self.pipeline.settings.backup_dir)
|
||||
dest = dest_dir / f"datahub-{trade_date}.db"
|
||||
self.pipeline.db.backup_to(dest)
|
||||
keep = int(self.pipeline.settings.quality.get("backup_retain") or 14)
|
||||
backups = sorted(dest_dir.glob("datahub-*.db"))
|
||||
for old in backups[:-keep]:
|
||||
old.unlink(missing_ok=True)
|
||||
return {"path": str(dest.name), "kept": min(len(backups), keep)}
|
||||
@@ -0,0 +1,532 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
from datahub import SCHEMA_VERSION
|
||||
from datahub.codes import resolve_code
|
||||
from datahub.coverage import calendar_coverage, point_coverage, published_range_coverage
|
||||
from datahub.db import HubDB
|
||||
from datahub.normalize import qfq_bar
|
||||
from datahub.numbers import finite_number
|
||||
from datahub.pipeline import Pipeline
|
||||
from datahub.settings import Settings
|
||||
from datahub.timeutil import isoformat, now_shanghai, session_phase, yyyymmdd
|
||||
|
||||
ERROR_STATUS = {
|
||||
"UNAUTHORIZED": HTTPStatus.UNAUTHORIZED,
|
||||
"INVALID_ARGUMENT": HTTPStatus.BAD_REQUEST,
|
||||
"RATE_LIMITED": HTTPStatus.TOO_MANY_REQUESTS,
|
||||
"SOURCE_UNAVAILABLE": HTTPStatus.SERVICE_UNAVAILABLE,
|
||||
"DATASET_NOT_PUBLISHED": HTTPStatus.NOT_FOUND,
|
||||
"STALE_DATA": HTTPStatus.OK,
|
||||
"INTERNAL": HTTPStatus.INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, code: str, message: str, retry_after: int | None = None, extra: dict[str, Any] | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.retry_after = retry_after
|
||||
self.extra = extra or {}
|
||||
|
||||
def payload(self) -> dict[str, Any]:
|
||||
body: dict[str, Any] = {"code": self.code, "message": self.message}
|
||||
if self.retry_after is not None:
|
||||
body["retry_after"] = self.retry_after
|
||||
body.update(self.extra)
|
||||
return {"error": body}
|
||||
|
||||
@property
|
||||
def status(self) -> HTTPStatus:
|
||||
return ERROR_STATUS.get(self.code, HTTPStatus.INTERNAL_SERVER_ERROR)
|
||||
|
||||
|
||||
def envelope(data: Any, meta: dict[str, Any]) -> dict[str, Any]:
|
||||
return {"schema_version": SCHEMA_VERSION, "data": data, "meta": meta}
|
||||
|
||||
|
||||
class V1API:
|
||||
def __init__(self, db: HubDB, pipeline: Pipeline, settings: Settings) -> None:
|
||||
self.db = db
|
||||
self.pipeline = pipeline
|
||||
self.settings = settings
|
||||
|
||||
def handle(self, path: str, query: dict[str, list[str]]) -> dict[str, Any]:
|
||||
q = {key: values[-1] if values else "" for key, values in query.items()}
|
||||
if path == "/v1/health":
|
||||
return self.health()
|
||||
if path == "/v1/calendar":
|
||||
return self.calendar(q.get("from") or "", q.get("to") or "")
|
||||
if path == "/v1/stocks":
|
||||
return self.stocks(q.get("updated_since") or "", q)
|
||||
if path == "/v1/bars/daily":
|
||||
return self.daily_bars(q)
|
||||
if path == "/v1/indexes/bars":
|
||||
return self.index_bars(q)
|
||||
if path == "/v1/valuation":
|
||||
return self.valuation(q)
|
||||
if path == "/v1/moneyflow":
|
||||
return self.moneyflow(q)
|
||||
if path == "/v1/auction":
|
||||
return self.auction(q)
|
||||
if path == "/v1/limit-events":
|
||||
return self.limit_events(q)
|
||||
if path == "/v1/popularity":
|
||||
return self.popularity(q)
|
||||
if path == "/v1/dragon-tiger":
|
||||
return self.dragon_tiger(q)
|
||||
if path == "/v1/sectors":
|
||||
return self.sectors(q)
|
||||
if path == "/v1/quotes/latest":
|
||||
return self.quotes_latest(q)
|
||||
if path == "/v1/indexes/quotes":
|
||||
return self.index_quotes(q)
|
||||
if path == "/v1/intraday/points":
|
||||
return self.intraday_points(q)
|
||||
if path == "/v1/datasets/status":
|
||||
return self.dataset_status(q.get("date") or "")
|
||||
if path == "/v1/batches":
|
||||
return self.batches(q.get("date") or "", q.get("dataset") or "")
|
||||
raise ApiError("INVALID_ARGUMENT", f"unknown endpoint: {path}")
|
||||
|
||||
def health(self) -> dict[str, Any]:
|
||||
today = yyyymmdd(now_shanghai())
|
||||
cal = self.db.fetchone(
|
||||
"SELECT is_open FROM trade_calendar WHERE exchange = 'SSE' AND cal_date = ?",
|
||||
(today,),
|
||||
)
|
||||
is_open = bool(cal and cal["is_open"] == 1)
|
||||
sources = self.db.fetchall("SELECT * FROM src_health")
|
||||
return envelope(
|
||||
{
|
||||
"status": "ok",
|
||||
"session_phase": session_phase(now_shanghai(), is_open),
|
||||
"trade_date": today,
|
||||
"is_open_day": is_open,
|
||||
"sources": [
|
||||
{
|
||||
"provider": row["provider"],
|
||||
"endpoint_class": row["endpoint_class"],
|
||||
"state": row["state"],
|
||||
"last_ok_at": row["last_ok_at"],
|
||||
"consec_failures": row["consec_failures"],
|
||||
}
|
||||
for row in sources
|
||||
],
|
||||
},
|
||||
{"tier": "official", "trade_date": today, "source": "datahub", "stale": False, "staleness_seconds": 0},
|
||||
)
|
||||
|
||||
def calendar(self, start: str, end: str) -> dict[str, Any]:
|
||||
start = yyyymmdd(start or add_default(-30))
|
||||
end = yyyymmdd(end or add_default(5))
|
||||
rows = self.db.fetchall(
|
||||
"""
|
||||
SELECT cal_date, is_open, pretrade_date,
|
||||
(SELECT MAX(cal_date) FROM trade_calendar t2
|
||||
WHERE t2.exchange = 'SSE' AND t2.is_open = 1 AND t2.cal_date < t1.cal_date) AS prev_open
|
||||
FROM trade_calendar t1
|
||||
WHERE exchange = 'SSE' AND cal_date >= ? AND cal_date <= ?
|
||||
ORDER BY cal_date
|
||||
""",
|
||||
(start, end),
|
||||
)
|
||||
items = [
|
||||
{
|
||||
"cal_date": row["cal_date"],
|
||||
"is_open": bool(row["is_open"]),
|
||||
"pretrade_date": row["pretrade_date"],
|
||||
"prev_open": row["prev_open"],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
meta = self._official_meta("calendar", end if items else start, source="tushare:trade_cal")
|
||||
return envelope(items, attach_coverage(meta, calendar_coverage(self.db, start, end)))
|
||||
|
||||
def stocks(self, updated_since: str, q: dict[str, str]) -> dict[str, Any]:
|
||||
limit, offset = self._page(q)
|
||||
today = yyyymmdd(now_shanghai())
|
||||
batch_id, snapshot = self.pipeline.published_stock_snapshot(today)
|
||||
if batch_id:
|
||||
# Formal view: the latest published stock snapshot, with batch
|
||||
# metadata. Filters are applied in-memory on the snapshot.
|
||||
pub = self.pipeline.latest_stocks_publication(today) or {}
|
||||
rows = snapshot
|
||||
if updated_since:
|
||||
rows = []
|
||||
rows = rows[offset: offset + limit]
|
||||
return envelope(
|
||||
rows,
|
||||
{
|
||||
"tier": "official",
|
||||
"trade_date": pub.get("trade_date"),
|
||||
"published_at": pub.get("published_at"),
|
||||
"source": "tushare:stock_basic",
|
||||
"batch_id": batch_id,
|
||||
"stale": False,
|
||||
"staleness_seconds": 0,
|
||||
"state": pub.get("state"),
|
||||
},
|
||||
)
|
||||
if updated_since:
|
||||
rows = self.db.fetchall(
|
||||
"SELECT * FROM stock_master WHERE updated_at >= ? ORDER BY ts_code LIMIT ? OFFSET ?",
|
||||
(updated_since, limit, offset),
|
||||
)
|
||||
else:
|
||||
rows = self.db.fetchall(
|
||||
"SELECT * FROM stock_master ORDER BY ts_code LIMIT ? OFFSET ?",
|
||||
(limit, offset),
|
||||
)
|
||||
return envelope(rows, self._official_meta("stocks", yyyymmdd(), source="tushare:stock_basic"))
|
||||
|
||||
def daily_bars(self, q: dict[str, str]) -> dict[str, Any]:
|
||||
return self._published_rows(
|
||||
dataset="daily",
|
||||
table="eod_bars",
|
||||
q=q,
|
||||
source="tushare:daily",
|
||||
adjust=q.get("adjust") or "none",
|
||||
)
|
||||
|
||||
def index_bars(self, q: dict[str, str]) -> dict[str, Any]:
|
||||
return self._published_rows(
|
||||
dataset="index_daily",
|
||||
table="eod_index_bars",
|
||||
q=q,
|
||||
source="tushare:index_daily",
|
||||
default_code="000001.SH",
|
||||
)
|
||||
|
||||
def valuation(self, q: dict[str, str]) -> dict[str, Any]:
|
||||
return self._published_rows(dataset="valuation", table="eod_valuation", q=q, source="tushare:daily_basic")
|
||||
|
||||
def moneyflow(self, q: dict[str, str]) -> dict[str, Any]:
|
||||
return self._published_rows(dataset="moneyflow", table="eod_moneyflow", q=q, source="tushare:moneyflow")
|
||||
|
||||
def auction(self, q: dict[str, str]) -> dict[str, Any]:
|
||||
return self._published_rows(dataset="auction", table="eod_auction", q=q, source="tushare:stk_auction")
|
||||
|
||||
def limit_events(self, q: dict[str, str]) -> dict[str, Any]:
|
||||
return self._published_rows(
|
||||
dataset="limit_events",
|
||||
table="eod_limit_events",
|
||||
q=q,
|
||||
source="tushare:limit_list_d",
|
||||
extra_filters={"limit_type": q.get("limit_type") or ""},
|
||||
)
|
||||
|
||||
def popularity(self, q: dict[str, str]) -> dict[str, Any]:
|
||||
return self._published_rows(
|
||||
dataset="popularity",
|
||||
table="eod_popularity",
|
||||
q=q,
|
||||
source="tushare:ths_hot+dc_hot",
|
||||
extra_filters={"source": q.get("source") or ""},
|
||||
)
|
||||
|
||||
def dragon_tiger(self, q: dict[str, str]) -> dict[str, Any]:
|
||||
return self._published_rows(
|
||||
dataset="dragon_tiger",
|
||||
table="eod_dragon_tiger",
|
||||
q=q,
|
||||
source="tushare:hm_detail",
|
||||
)
|
||||
|
||||
def sectors(self, q: dict[str, str]) -> dict[str, Any]:
|
||||
return self._published_rows(
|
||||
dataset="sector_daily",
|
||||
table="eod_sector_daily",
|
||||
q=q,
|
||||
source="tushare:ths_daily+dc_index+sw_daily",
|
||||
extra_filters={"family": q.get("family") or ""},
|
||||
)
|
||||
|
||||
def quotes_latest(self, q: dict[str, str]) -> dict[str, Any]:
|
||||
from datahub.realtime_serve import RealtimeApiError, fetch_market_quotes, fetch_quotes
|
||||
|
||||
codes = [item.strip() for item in str(q.get("codes") or "").split(",") if item.strip()]
|
||||
try:
|
||||
if codes:
|
||||
return fetch_quotes(self.db, codes)
|
||||
return fetch_market_quotes(self.db)
|
||||
except RealtimeApiError as exc:
|
||||
raise ApiError(exc.code, exc.message) from exc
|
||||
|
||||
def index_quotes(self, q: dict[str, str]) -> dict[str, Any]:
|
||||
from datahub.realtime_serve import RealtimeApiError, fetch_index_quotes
|
||||
|
||||
try:
|
||||
return fetch_index_quotes(self.db)
|
||||
except RealtimeApiError as exc:
|
||||
raise ApiError(exc.code, exc.message) from exc
|
||||
|
||||
def intraday_points(self, q: dict[str, str]) -> dict[str, Any]:
|
||||
from datahub.realtime_serve import RealtimeApiError, fetch_intraday
|
||||
|
||||
code = str(q.get("code") or "").strip()
|
||||
if not code:
|
||||
raise ApiError("INVALID_ARGUMENT", "code is required")
|
||||
raw_date = str(q.get("date") or "").strip()
|
||||
try:
|
||||
trade_date = yyyymmdd(raw_date or now_shanghai())
|
||||
except ValueError as exc:
|
||||
raise ApiError("INVALID_ARGUMENT", str(exc)) from exc
|
||||
try:
|
||||
return fetch_intraday(self.db, code, trade_date)
|
||||
except RealtimeApiError as exc:
|
||||
raise ApiError(exc.code, exc.message) from exc
|
||||
|
||||
def dataset_status(self, date: str) -> dict[str, Any]:
|
||||
trade_date = yyyymmdd(date or now_shanghai())
|
||||
datasets = (
|
||||
"daily", "valuation", "moneyflow", "auction", "index_daily", "stocks",
|
||||
"limit_events", "popularity", "dragon_tiger", "sector_daily",
|
||||
)
|
||||
items = []
|
||||
for dataset in datasets:
|
||||
pub = self.db.fetchone(
|
||||
"SELECT * FROM publications WHERE dataset = ? AND trade_date = ?",
|
||||
(dataset, trade_date),
|
||||
)
|
||||
batch = None
|
||||
if pub:
|
||||
batch = self.db.fetchone("SELECT * FROM batches WHERE batch_id = ?", (pub["active_batch"],))
|
||||
items.append(
|
||||
{
|
||||
"dataset": dataset,
|
||||
"trade_date": trade_date,
|
||||
"state": (pub or {}).get("state") or "unpublished",
|
||||
"batch_id": (pub or {}).get("active_batch"),
|
||||
"published_at": (pub or {}).get("published_at"),
|
||||
"rows_out": (batch or {}).get("rows_out"),
|
||||
"quality": _parse_json((batch or {}).get("quality_json")),
|
||||
}
|
||||
)
|
||||
return envelope(items, self._official_meta("status", trade_date, source="datahub"))
|
||||
|
||||
def batches(self, date: str, dataset: str) -> dict[str, Any]:
|
||||
trade_date = yyyymmdd(date or now_shanghai())
|
||||
if dataset:
|
||||
rows = self.db.fetchall(
|
||||
"SELECT * FROM batches WHERE trade_date = ? AND dataset = ? ORDER BY started_at",
|
||||
(trade_date, dataset),
|
||||
)
|
||||
else:
|
||||
rows = self.db.fetchall(
|
||||
"SELECT * FROM batches WHERE trade_date = ? ORDER BY started_at",
|
||||
(trade_date,),
|
||||
)
|
||||
return envelope(rows, self._official_meta("batches", trade_date, source="datahub"))
|
||||
|
||||
def _published_rows(
|
||||
self,
|
||||
dataset: str,
|
||||
table: str,
|
||||
q: dict[str, str],
|
||||
source: str,
|
||||
adjust: str = "none",
|
||||
default_code: str = "",
|
||||
extra_filters: dict[str, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
trade_date = q.get("date") or q.get("trade_date") or ""
|
||||
code = q.get("code") or default_code
|
||||
start = q.get("from") or ""
|
||||
end = q.get("to") or ""
|
||||
if trade_date:
|
||||
trade_date = yyyymmdd(trade_date)
|
||||
start = end = trade_date
|
||||
if not start or not end:
|
||||
if not trade_date:
|
||||
raise ApiError("INVALID_ARGUMENT", "date or from/to is required")
|
||||
else:
|
||||
start = yyyymmdd(start)
|
||||
end = yyyymmdd(end)
|
||||
ts_code = ""
|
||||
if code:
|
||||
resolved = resolve_code(self.db, code)
|
||||
if resolved is None:
|
||||
raise ApiError("INVALID_ARGUMENT", f"ambiguous code: {code}")
|
||||
ts_code = resolved
|
||||
filters = {key: value for key, value in (extra_filters or {}).items() if value}
|
||||
# For a range, use per-date published batch. Single-date is the common path.
|
||||
if start == end:
|
||||
pub = self.db.fetchone(
|
||||
"SELECT * FROM publications WHERE dataset = ? AND trade_date = ?",
|
||||
(dataset, start),
|
||||
)
|
||||
if not pub:
|
||||
raise ApiError(
|
||||
"DATASET_NOT_PUBLISHED",
|
||||
f"{dataset} {start} 尚未发布",
|
||||
extra=self._unpublished_extra(dataset, start),
|
||||
)
|
||||
limit, offset = self._page(q)
|
||||
sql = f"SELECT * FROM {table} WHERE trade_date = ? AND batch_id = ?"
|
||||
params: list[Any] = [start, pub["active_batch"]]
|
||||
if ts_code:
|
||||
sql += " AND ts_code = ?"
|
||||
params.append(ts_code)
|
||||
for key, value in filters.items():
|
||||
sql += f" AND {key} = ?"
|
||||
params.append(value)
|
||||
sql += " ORDER BY ts_code LIMIT ? OFFSET ?"
|
||||
params.extend([limit, offset])
|
||||
rows = [dict(row) for row in self.db.fetchall(sql, tuple(params))]
|
||||
if adjust == "qfq" and dataset == "daily":
|
||||
rows = self._apply_qfq(rows)
|
||||
meta = {
|
||||
"tier": "official",
|
||||
"trade_date": start,
|
||||
"published_at": pub["published_at"],
|
||||
"source": source,
|
||||
"batch_id": pub["active_batch"],
|
||||
"stale": False,
|
||||
"staleness_seconds": 0,
|
||||
"state": pub["state"],
|
||||
}
|
||||
return envelope(rows, attach_coverage(meta, point_coverage(start, dataset)))
|
||||
# multi-day: walk published dates
|
||||
pubs = self.db.fetchall(
|
||||
"SELECT * FROM publications WHERE dataset = ? AND trade_date >= ? AND trade_date <= ? ORDER BY trade_date",
|
||||
(dataset, start, end),
|
||||
)
|
||||
if not pubs:
|
||||
raise ApiError(
|
||||
"DATASET_NOT_PUBLISHED",
|
||||
f"{dataset} {start}-{end} 尚未发布",
|
||||
extra=self._unpublished_extra(dataset, end),
|
||||
)
|
||||
rows: list[dict[str, Any]] = []
|
||||
limit, offset = self._page(q)
|
||||
for pub in pubs:
|
||||
sql = f"SELECT * FROM {table} WHERE trade_date = ? AND batch_id = ?"
|
||||
params = [pub["trade_date"], pub["active_batch"]]
|
||||
if ts_code:
|
||||
sql += " AND ts_code = ?"
|
||||
params.append(ts_code)
|
||||
for key, value in filters.items():
|
||||
sql += f" AND {key} = ?"
|
||||
params.append(value)
|
||||
sql += " ORDER BY ts_code"
|
||||
rows.extend(self.db.fetchall(sql, tuple(params)))
|
||||
sliced = rows[offset: offset + limit]
|
||||
if adjust == "qfq" and dataset == "daily":
|
||||
sliced = self._apply_qfq(sliced)
|
||||
last = pubs[-1]
|
||||
coverage = published_range_coverage(
|
||||
self.db,
|
||||
dataset,
|
||||
start,
|
||||
end,
|
||||
ts_code=ts_code,
|
||||
table=table,
|
||||
)
|
||||
return envelope(
|
||||
sliced,
|
||||
attach_coverage(
|
||||
{
|
||||
"tier": "official",
|
||||
"trade_date": last["trade_date"],
|
||||
"published_at": last["published_at"],
|
||||
"source": source,
|
||||
"batch_id": last["active_batch"],
|
||||
"stale": False,
|
||||
"staleness_seconds": 0,
|
||||
},
|
||||
coverage,
|
||||
),
|
||||
)
|
||||
|
||||
def _apply_qfq(self, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
by_code: dict[str, list[dict[str, Any]]] = {}
|
||||
for row in rows:
|
||||
by_code.setdefault(str(row["ts_code"]), []).append(row)
|
||||
out: list[dict[str, Any]] = []
|
||||
for code, group in by_code.items():
|
||||
latest = None
|
||||
factors = [finite_number(item.get("adj_factor")) for item in group]
|
||||
factors = [item for item in factors if item]
|
||||
if factors:
|
||||
latest = max(factors)
|
||||
else:
|
||||
extra = self.db.fetchone(
|
||||
"SELECT MAX(adj_factor) AS f FROM eod_bars WHERE ts_code = ?",
|
||||
(code,),
|
||||
)
|
||||
latest = finite_number((extra or {}).get("f"), 1.0)
|
||||
out.extend(qfq_bar(item, latest) for item in group)
|
||||
return out
|
||||
|
||||
def _page(self, q: dict[str, str]) -> tuple[int, int]:
|
||||
try:
|
||||
limit = int(q.get("limit") or self.settings.list_limit_default)
|
||||
offset = int(q.get("offset") or 0)
|
||||
except ValueError as exc:
|
||||
raise ApiError("INVALID_ARGUMENT", "limit/offset must be integers") from exc
|
||||
limit = max(1, min(limit, self.settings.list_limit_max))
|
||||
offset = max(0, offset)
|
||||
return limit, offset
|
||||
|
||||
def _unpublished_extra(self, dataset: str, trade_date: str) -> dict[str, Any]:
|
||||
"""Identifiable coverage info: is this a history gap or today-not-yet?"""
|
||||
extra: dict[str, Any] = {"expected_at": "15:05+08:00"}
|
||||
row = self.db.fetchone(
|
||||
"SELECT MIN(trade_date) AS a, MAX(trade_date) AS b FROM publications WHERE dataset = ?",
|
||||
(dataset,),
|
||||
)
|
||||
if row and row.get("a"):
|
||||
extra["available_from"] = row["a"]
|
||||
extra["available_to"] = row["b"]
|
||||
if str(trade_date) < str(row["a"]):
|
||||
extra["reason"] = "history_not_backfilled"
|
||||
return extra
|
||||
|
||||
def _official_meta(self, dataset: str, trade_date: str, source: str) -> dict[str, Any]:
|
||||
pub = self.db.fetchone(
|
||||
"SELECT * FROM publications WHERE dataset = ? AND trade_date = ?",
|
||||
(dataset, trade_date),
|
||||
)
|
||||
return {
|
||||
"tier": "official",
|
||||
"trade_date": trade_date,
|
||||
"published_at": (pub or {}).get("published_at"),
|
||||
"source": source,
|
||||
"batch_id": (pub or {}).get("active_batch"),
|
||||
"stale": False,
|
||||
"staleness_seconds": 0,
|
||||
}
|
||||
|
||||
|
||||
def add_default(days: int) -> str:
|
||||
from datetime import timedelta
|
||||
|
||||
return (now_shanghai() + timedelta(days=days)).strftime("%Y%m%d")
|
||||
|
||||
|
||||
def attach_coverage(meta: dict[str, Any], coverage: dict[str, Any]) -> dict[str, Any]:
|
||||
merged = dict(meta)
|
||||
merged["coverage"] = coverage
|
||||
merged["incomplete"] = not bool(coverage.get("complete"))
|
||||
return merged
|
||||
|
||||
|
||||
def parse_query(raw: str) -> dict[str, list[str]]:
|
||||
return parse_qs(raw, keep_blank_values=True)
|
||||
|
||||
|
||||
def _parse_json(raw: Any) -> Any:
|
||||
if not raw:
|
||||
return None
|
||||
if isinstance(raw, dict):
|
||||
return raw
|
||||
import json
|
||||
|
||||
try:
|
||||
return json.loads(str(raw))
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
@@ -0,0 +1,117 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_DB_PATH = Path(os.environ.get("DATAHUB_DB_PATH") or (ROOT / "data" / "datahub.db"))
|
||||
DEFAULT_BACKUP_DIR = Path(os.environ.get("DATAHUB_BACKUP_DIR") or (ROOT / "data" / "backups"))
|
||||
DEFAULT_CONFIG_PATH = ROOT / "config" / "hub-quality.config.json"
|
||||
|
||||
|
||||
def _load_quality(path: Path) -> dict[str, Any]:
|
||||
if not path.is_file():
|
||||
return {}
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@dataclass
|
||||
class Settings:
|
||||
host: str = "127.0.0.1"
|
||||
port: int = 8766
|
||||
encryption_key: str = ""
|
||||
api_token: str = ""
|
||||
admin_password: str = ""
|
||||
tushare_token: str = ""
|
||||
db_path: Path = DEFAULT_DB_PATH
|
||||
backup_dir: Path = DEFAULT_BACKUP_DIR
|
||||
quality: dict[str, Any] = field(default_factory=dict)
|
||||
log_level: str = "INFO"
|
||||
scheduler_enabled: bool = True
|
||||
|
||||
@property
|
||||
def tushare_rate_per_minute(self) -> int:
|
||||
return int(self.quality.get("tushare_rate_per_minute") or 300)
|
||||
|
||||
@property
|
||||
def max_publish_attempts(self) -> int:
|
||||
return int(self.quality.get("max_publish_attempts") or 5)
|
||||
|
||||
@property
|
||||
def list_limit_default(self) -> int:
|
||||
return int(self.quality.get("list_limit_default") or 5000)
|
||||
|
||||
@property
|
||||
def list_limit_max(self) -> int:
|
||||
return int(self.quality.get("list_limit_max") or 5000)
|
||||
|
||||
@property
|
||||
def calendar_start(self) -> str:
|
||||
return str(self.quality.get("calendar_start") or "20160101")
|
||||
|
||||
@property
|
||||
def index_history_trading_days(self) -> int:
|
||||
return int(self.quality.get("index_history_trading_days") or 260)
|
||||
|
||||
@property
|
||||
def moneyflow_history_trading_days(self) -> int:
|
||||
return int(self.quality.get("moneyflow_history_trading_days") or 60)
|
||||
|
||||
@property
|
||||
def stocks_refresh_times(self) -> tuple[str, ...]:
|
||||
raw = self.quality.get("stocks_refresh_times") or ["20:00", "23:10"]
|
||||
if isinstance(raw, str):
|
||||
raw = [raw]
|
||||
return tuple(str(item) for item in raw)
|
||||
|
||||
@property
|
||||
def eod_retry_start(self) -> str:
|
||||
return str(self.quality.get("eod_retry_start") or "15:15")
|
||||
|
||||
@property
|
||||
def eod_retry_interval_minutes(self) -> int:
|
||||
return int(self.quality.get("eod_retry_interval_minutes") or 30)
|
||||
|
||||
@property
|
||||
def eod_retry_cutoff(self) -> str:
|
||||
return str(self.quality.get("eod_retry_cutoff") or "23:30")
|
||||
|
||||
@property
|
||||
def revision_review_start(self) -> str:
|
||||
# Before the 21:00 website shadow observation.
|
||||
return str(self.quality.get("revision_review_start") or "20:00")
|
||||
|
||||
@property
|
||||
def revision_review_interval_minutes(self) -> int:
|
||||
return int(self.quality.get("revision_review_interval_minutes") or 30)
|
||||
|
||||
@property
|
||||
def revision_review_cutoff(self) -> str:
|
||||
# Last light review ~23:00; cutoff before the 23:30 observation.
|
||||
return str(self.quality.get("revision_review_cutoff") or "23:20")
|
||||
|
||||
|
||||
def load_settings(
|
||||
env: dict[str, str] | None = None,
|
||||
config_path: Path | None = None,
|
||||
) -> Settings:
|
||||
environ = env if env is not None else dict(os.environ)
|
||||
quality_path = config_path or DEFAULT_CONFIG_PATH
|
||||
db_path = Path(environ.get("DATAHUB_DB_PATH") or DEFAULT_DB_PATH)
|
||||
backup_dir = Path(environ.get("DATAHUB_BACKUP_DIR") or DEFAULT_BACKUP_DIR)
|
||||
return Settings(
|
||||
host=environ.get("DATAHUB_HOST") or "127.0.0.1",
|
||||
port=int(environ.get("DATAHUB_PORT") or 8766),
|
||||
encryption_key=str(environ.get("DATAHUB_ENCRYPTION_KEY") or "").strip(),
|
||||
api_token=str(environ.get("DATAHUB_TOKEN") or "").strip(),
|
||||
admin_password=str(environ.get("DATAHUB_ADMIN_PASSWORD") or "").strip(),
|
||||
tushare_token=str(environ.get("TUSHARE_TOKEN") or "").strip(),
|
||||
db_path=db_path,
|
||||
backup_dir=backup_dir,
|
||||
quality=_load_quality(quality_path),
|
||||
log_level=environ.get("DATAHUB_LOG_LEVEL") or "INFO",
|
||||
scheduler_enabled=str(environ.get("DATAHUB_SCHEDULER") or "1") not in {"0", "false", "False"},
|
||||
)
|
||||
@@ -0,0 +1,74 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
SHANGHAI = ZoneInfo("Asia/Shanghai")
|
||||
|
||||
|
||||
def now_shanghai(clock: datetime | None = None) -> datetime:
|
||||
if clock is not None:
|
||||
if clock.tzinfo is None:
|
||||
return clock.replace(tzinfo=SHANGHAI)
|
||||
return clock.astimezone(SHANGHAI)
|
||||
return datetime.now(SHANGHAI)
|
||||
|
||||
|
||||
def isoformat(value: datetime | None = None) -> str:
|
||||
current = now_shanghai(value)
|
||||
return current.isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def yyyymmdd(value: date | datetime | str | None = None) -> str:
|
||||
if value is None:
|
||||
return now_shanghai().strftime("%Y%m%d")
|
||||
if isinstance(value, str):
|
||||
digits = value.replace("-", "")[:8]
|
||||
if len(digits) != 8 or not digits.isdigit():
|
||||
raise ValueError(f"invalid trade_date: {value}")
|
||||
return digits
|
||||
if isinstance(value, datetime):
|
||||
return value.astimezone(SHANGHAI).strftime("%Y%m%d")
|
||||
return value.strftime("%Y%m%d")
|
||||
|
||||
|
||||
def parse_trade_date(value: str) -> date:
|
||||
text = yyyymmdd(value)
|
||||
return date(int(text[:4]), int(text[4:6]), int(text[6:8]))
|
||||
|
||||
|
||||
def session_phase(clock: datetime | None, is_open_day: bool) -> str:
|
||||
"""pre | intradaily | lunch | eod | closed"""
|
||||
if not is_open_day:
|
||||
return "closed"
|
||||
current = now_shanghai(clock).time()
|
||||
if current < time(9, 15):
|
||||
return "pre"
|
||||
if current < time(11, 30) or (time(13, 0) <= current <= time(15, 5)):
|
||||
return "intraday"
|
||||
if current < time(13, 0):
|
||||
return "lunch"
|
||||
if current <= time(23, 40):
|
||||
return "eod"
|
||||
return "closed"
|
||||
|
||||
|
||||
def add_days(trade_date: str, days: int) -> str:
|
||||
return (parse_trade_date(trade_date) + timedelta(days=days)).strftime("%Y%m%d")
|
||||
|
||||
|
||||
def iter_yyyymmdd(start: str, end: str):
|
||||
cursor = parse_trade_date(start)
|
||||
last = parse_trade_date(end)
|
||||
if cursor > last:
|
||||
return
|
||||
while cursor <= last:
|
||||
yield cursor.strftime("%Y%m%d")
|
||||
cursor += timedelta(days=1)
|
||||
|
||||
|
||||
def utc_timestamp(value: Any) -> str:
|
||||
if isinstance(value, datetime):
|
||||
return isoformat(value)
|
||||
return isoformat()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user