复制 local 代码到 serve
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
# Dependencies
|
||||
frontend/node_modules
|
||||
backend/.venv
|
||||
**/__pycache__
|
||||
|
||||
# Build outputs
|
||||
frontend/dist
|
||||
dist
|
||||
build
|
||||
|
||||
# Git
|
||||
.git
|
||||
.gitignore
|
||||
|
||||
# IDE
|
||||
.vscode
|
||||
.idea
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
# Local env files
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
@@ -0,0 +1,30 @@
|
||||
# 注意:当前项目已改为硬编码配置(backend/app/config.py),Docker 启动不再需要 .env。
|
||||
# 此文件仅保留作为本地开发/调试时的备用参考。
|
||||
|
||||
# ===== 数据源 API Key =====
|
||||
# 留空或不填则启用 Free 试用模式,仅能拿历史日 K 单股数据
|
||||
TICKFLOW_API_KEY=
|
||||
|
||||
# ===== AI(可选,留空跳过 AI 功能) =====
|
||||
AI_PROVIDER=openai_compat # openai_compat | ollama
|
||||
AI_BASE_URL=https://api.deepseek.com/v1
|
||||
AI_API_KEY=
|
||||
AI_MODEL=deepseek-chat
|
||||
AI_DAILY_TOKEN_BUDGET=500000
|
||||
|
||||
# ===== Server =====
|
||||
HOST=0.0.0.0
|
||||
PORT=3018
|
||||
LOG_LEVEL=INFO
|
||||
|
||||
# ===== Data =====
|
||||
DATA_DIR=./data
|
||||
|
||||
# ===== Docker 基础镜像源(可选) =====
|
||||
# 国内网络拉取 Docker Hub 超时时,可取消注释并替换为可用镜像站。
|
||||
# 常见镜像站:阿里云 registry.cn-hangzhou.aliyuncs.com
|
||||
# DaoCloud m.daocloud.io/docker.io
|
||||
# 中科大 docker.mirrors.ustc.edu.cn
|
||||
# 网易 hub-mirror.c.163.com
|
||||
# PYTHON_IMAGE=registry.cn-hangzhou.aliyuncs.com/library/python:3.11-slim
|
||||
# NODE_IMAGE=registry.cn-hangzhou.aliyuncs.com/library/node:20-alpine
|
||||
@@ -0,0 +1,76 @@
|
||||
# 两阶段构建:前端 dist 拷进后端镜像,单容器运行
|
||||
# 可选:构建网络无法直连官方源时,传入 --build-arg USE_CN_MIRROR=1 启用国内镜像
|
||||
ARG USE_CN_MIRROR=1
|
||||
ARG NPM_REGISTRY=https://registry.npmmirror.com
|
||||
ARG PYPI_INDEX=https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
# 备用 PyPI 源:主源同步延迟/故障时自动兜底(阿里云与清华互为补充)
|
||||
ARG PYPI_FALLBACK=https://mirrors.aliyun.com/pypi/simple
|
||||
ARG BACKEND_EXTRAS=
|
||||
|
||||
# === Stage 1: 前端构建 ===
|
||||
FROM node:20-alpine AS frontend-builder
|
||||
ARG USE_CN_MIRROR=1
|
||||
ARG NPM_REGISTRY=https://registry.npmmirror.com
|
||||
WORKDIR /build
|
||||
# 关键:corepack 不读 npm 的 registry 配置,且跨 RUN 不保留环境变量,
|
||||
# 因此国内网络下最稳的做法是直接用 npm 安装 pnpm(npm 会读取 .npmrc 镜像源),
|
||||
# 彻底绕开 corepack 再次联网下载 pnpm 的问题。
|
||||
RUN if [ "$USE_CN_MIRROR" = "1" ]; then npm config set registry "$NPM_REGISTRY"; fi && \
|
||||
npm install -g pnpm@9
|
||||
# 让 pnpm 走镜像源安装依赖
|
||||
RUN if [ "$USE_CN_MIRROR" = "1" ]; then pnpm config set registry "$NPM_REGISTRY"; fi
|
||||
COPY frontend/package.json frontend/pnpm-lock.yaml* ./
|
||||
RUN pnpm install --frozen-lockfile || pnpm install
|
||||
COPY frontend/ ./
|
||||
RUN pnpm build
|
||||
|
||||
# === Stage 2: Python 运行时 ===
|
||||
FROM python:3.11-slim AS runtime
|
||||
ARG USE_CN_MIRROR=1
|
||||
ARG PYPI_INDEX=https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
ARG PYPI_FALLBACK=https://mirrors.aliyun.com/pypi/simple
|
||||
ARG BACKEND_EXTRAS=
|
||||
WORKDIR /app
|
||||
|
||||
# 安装 uv(快) —— 国内镜像下三重兜底:主源 → 备用源 → 官方源,
|
||||
# 任一成功即可,避免单一镜像同步延迟/故障导致构建失败。
|
||||
# uv 发版极频繁,国内镜像同步存在时间窗口,不锁版本且无 fallback 时
|
||||
# 容易遇到 "from versions: none"(索引解析不到最新版)。
|
||||
RUN if [ "$USE_CN_MIRROR" = "1" ]; then \
|
||||
pip install --no-cache-dir uv -i "$PYPI_INDEX" || \
|
||||
pip install --no-cache-dir uv -i "$PYPI_FALLBACK" || \
|
||||
pip install --no-cache-dir uv; \
|
||||
else \
|
||||
pip install --no-cache-dir uv; \
|
||||
fi
|
||||
|
||||
# Backend deps
|
||||
COPY README.md /README.md
|
||||
COPY backend/pyproject.toml backend/uv.lock* ./
|
||||
# uv 原生支持同时挂多个 index(主源 + 备用源),会自动在两源中查找,
|
||||
# 比逐个重试更稳健 —— 任一源缺包时另一源补位。
|
||||
RUN if [ "$USE_CN_MIRROR" = "1" ]; then \
|
||||
export UV_DEFAULT_INDEX="$PYPI_INDEX" UV_EXTRA_INDEX_URL="$PYPI_FALLBACK"; \
|
||||
fi; \
|
||||
set -- --no-dev; \
|
||||
for extra in $BACKEND_EXTRAS; do \
|
||||
set -- "$@" --extra "$extra"; \
|
||||
done; \
|
||||
uv sync --frozen "$@" || uv sync "$@"
|
||||
|
||||
# Backend code
|
||||
# 注意:Docker 里 WORKDIR=/app, 而 config.py 的 _PROJECT_ROOT 是按开发布局
|
||||
# (<root>/backend/app/) 推导的, 容器内会错算到 /。这里用环境变量显式指定
|
||||
# 三个关键路径, 确保 static / tiers / data 都指向容器内正确位置。
|
||||
COPY backend/app ./app
|
||||
COPY tiers.yaml /app/tiers.yaml
|
||||
ENV STATIC_DIR=/app/static \
|
||||
TIERS_YAML=/app/tiers.yaml \
|
||||
DATA_DIR=/app/data
|
||||
|
||||
# Frontend 静态产物
|
||||
COPY --from=frontend-builder /build/dist ./static
|
||||
|
||||
ENV PYTHONPATH=/app
|
||||
EXPOSE 3018
|
||||
CMD ["uv", "run", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "3018"]
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 tickflow-stock-panel contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+328
@@ -0,0 +1,328 @@
|
||||
<div align="center">
|
||||
|
||||
# 📈 A股智能量化工作台
|
||||
|
||||
**自托管、零运维的 A 股「选股 + 监控 + 回测」量化工作台**
|
||||
|
||||
**面向个人散户与量化爱好者而生**
|
||||
|
||||
[](./LICENSE)
|
||||
[](https://www.python.org/)
|
||||
[](https://react.dev/)
|
||||
[](https://tickflow.org/auth/register?ref=V3KDKGXPEA)
|
||||
[](./Dockerfile)
|
||||
[](https://github.com/shy3130/tickflow-stock-panel/stargazers)
|
||||
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
|
||||
**[快速开始](#-快速开始)** · **[核心功能](#-核心功能)** · **[配置](#️-配置)** · **[路线图](#-路线图)**
|
||||
|
||||
</div>
|
||||
|
||||
- 🆓 **开箱即用** — 留空 Key 即进 None 模式,历史日 K 免费体验,**无需付费**
|
||||
- 🏠 **自托管零运维** — Docker 单容器部署,数据完全掌握在自己手里
|
||||
- 🔍 **三位一体** — 选股(20 内置策略)+ 实时监控 + 向量化回测,Polars 毫秒级扫描全 A 股
|
||||
- 🤖 **AI 加持** — 一句话生成策略代码,任意 OpenAI 兼容接口均可接入(留空即关闭)
|
||||
- 🔌 **自由扩展** — 自有量化项目数据,与内置数据同台分析
|
||||
- 🇨🇳 **A 股专用** — 盘后自动AI复盘并推送至飞书等;连板梯队、涨停动量、内置ths 概念 / 行业
|
||||
|
||||
|
||||
|
||||
基于 [TickFlow](https://tickflow.org/auth/register?ref=V3KDKGXPEA) 数据源。**明确不做**:不对标同花顺 / 通达信,不内置「AI 荐股 / 涨停预测」。
|
||||
|
||||
> ⚠️ 考虑到tickflow数据源没有人气/资金流向等个性化数据,我将开放自有的第三方数据以供大佬们研究使用,包括但不限于当前内置的ths概念/ths行业(后续更新在这里)
|
||||
|
||||
|
||||
> 有更多稳定免费数据源推荐,或者提交建议/意见的大佬可以邮件到 415333856@qq.com,q群 109338242
|
||||
|
||||
|
||||
觉得有用可以点个 Star,蟹蟹 🌹
|
||||
|
||||
---
|
||||
|
||||
## 🎯 项目定位
|
||||
|
||||
**面向个人散户与量化爱好者的 A 股分析工作台**,聚焦「**选股 + 监控 + 回测**」三大场景,LLM能力驱动进行市场分析,掌控市场节奏;让普通投资者也能拥有一套可自定义策略的量化工具。
|
||||
|
||||
---
|
||||
|
||||
## 📸 界面预览
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" align="center"><b>看板 Dashboard</b></td>
|
||||
<td width="50%" align="center"><b>策略 Screener</b></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="./screenshots/dashboard.png" alt="看板页面"></td>
|
||||
<td width="50%"><img src="./screenshots/screener.png" alt="策略页"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" align="center"><b>回测 Backtest</b></td>
|
||||
<td width="50%" align="center"><b>监控中心 Monitor</b></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="./screenshots/backtest.png" alt="回测页"></td>
|
||||
<td width="50%"><img src="./screenshots/monitor.png" alt="监控中心"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" align="center"><b>连板梯队 Limit Ladder</b></td>
|
||||
<td width="50%" align="center"><b>概念分析 Concept</b></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="./screenshots/limit-ladder.png" alt="连板梯队页"></td>
|
||||
<td width="50%"><img src="./screenshots/concept-analysis.png" alt="概念分析"></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<div align="center">
|
||||
|
||||
### 📸 [查看更多界面截图 »](./screenshots/README.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 前置依赖
|
||||
|
||||
| 工具 | 版本 | 安装 |
|
||||
| :--------------------------------- | :----- | :------------------------------------------------- |
|
||||
| Python | ≥ 3.11 | [python.org](https://www.python.org/) |
|
||||
| Node | ≥ 20 | [nodejs.org](https://nodejs.org/) |
|
||||
| [`uv`](https://docs.astral.sh/uv/) | latest | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
|
||||
| `pnpm` | 9 | `npm i -g pnpm` |
|
||||
|
||||
### 方式 A:Dev 模式(二次开发推荐)
|
||||
|
||||
```bash
|
||||
cp .env.example .env # 按需填 TICKFLOW_API_KEY(留空 = None 模式)
|
||||
./dev.sh # Windows: .\dev.ps1
|
||||
```
|
||||
|
||||
自动检查 / 下载依赖、释放端口、同时起前后端,Ctrl-C 一并关闭。默认:
|
||||
|
||||
- 后端 → <http://localhost:3018> · 前端 → <http://localhost:3011>
|
||||
- 自定义端口:`BACKEND_PORT=8000 FRONTEND_PORT=5173 ./dev.sh`
|
||||
|
||||
### 方式 B:Docker(部署最省心)
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
docker compose up --build
|
||||
# 打开 http://localhost:3018
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><b>环境适配与高级选项(老 CPU · 手动启动 · 回测依赖)</b></summary>
|
||||
|
||||
**老 CPU 兼容(avx2/fma 缺失报错或 exit 132)**:桌面客户端安装包已内置兼容内核(新老 CPU 通吃)。Docker / 源码用户在 `.env` 打开 `BACKEND_EXTRAS=legacy-cpu` 后重建,会给 Polars 切到 `rtcompat` 运行时;需回测则 `BACKEND_EXTRAS=legacy-cpu backtest`。
|
||||
|
||||
**手动分别启动:**
|
||||
|
||||
```bash
|
||||
# 后端
|
||||
cd backend && uv sync --extra backtest # 含回测依赖
|
||||
uv run uvicorn app.main:app --reload --port 3018
|
||||
|
||||
# 前端
|
||||
cd frontend && pnpm install && pnpm dev # http://localhost:3011
|
||||
```
|
||||
|
||||
**回测依赖**:vectorbt → numba 体积较大,作为可选 extras(`uv sync --extra backtest`)。macOS / Intel 无预构建 wheel 时需 `brew install cmake` 现场编译。
|
||||
|
||||
</details>
|
||||
|
||||
### 🔄 更新代码(已部署用户必读)
|
||||
|
||||
拉取新版本只需一条命令:
|
||||
|
||||
```bash
|
||||
git pull
|
||||
```
|
||||
|
||||
**整个 `data/` 目录都不纳入 git**——行情 K线、财务、自选、回测、监控记录,乃至概念/行业扩展数据,全部是程序运行时生成/拉取的用户数据,`git pull` 物理上无法影响它们。新用户首次启动时,概念/行业两份扩展数据会自动从远程接口拉取,无需任何手动操作。
|
||||
|
||||
> ⚠️ **切勿使用以下命令"解决冲突"或"清理",它们会一次性删光 `data/` 下所有未被 git 跟踪的数据:**
|
||||
> - `git clean -fdx`(最危险,会删掉所有 `.gitignore` 忽略的文件)
|
||||
> - `git reset --hard`
|
||||
> - 直接删除整个项目文件夹重新 `git clone`
|
||||
>
|
||||
> 若 `git pull` 报冲突,通常是本地误改了被跟踪的文件,请先 `git stash` 暂存再 pull,或单独联系作者,不要直接执行上面的命令。
|
||||
|
||||
### 🧭 跑起来后的第一次使用
|
||||
|
||||
1. **设置 → 凭据与能力** → 点 **重新检测**,确认档位标签
|
||||
2. **设置** → **立即跑盘后管道**:拉日 K + 计算 enriched 表(None / Free 走 free-api,当日数据盘后 1-2 小时可用)
|
||||
3. **自选**页加标的 → **选股**页点策略卡片扫描 / 配自定义信号
|
||||
4. **回测**页选策略 + 区间 → 看净值 / 夏普 / 交易明细(SSE 实时进度)
|
||||
5. **监控中心**配规则(策略 / 个股信号 / 价格 / 异动),盘中实时弹窗 + 持久化记录
|
||||
|
||||
---
|
||||
|
||||
## ✨ 核心功能
|
||||
|
||||
### 🔍 选股引擎(Screener)
|
||||
|
||||
**20 个内置策略**,每个策略一个独立 Python 文件,基于 Polars 表达式向量化实现(`backend/app/strategy/builtin/`):
|
||||
|
||||
| 类型 | 代表策略 |
|
||||
| :---------- | :------------------------------------------------------- |
|
||||
| 趋势 / 形态 | 趋势突破 · 均线多头 · MA 金叉 · MACD 金叉放量 · 布林突破 |
|
||||
| 量价 / 涨停 | 量价齐升 · 高换手强势 · 连板股 · 断板反包 · 涨停动量 |
|
||||
| 反转 / 波动 | 超跌反弹 · 超卖反转 · 新低反转 · 低波动龙头 · 回踩 MA20 |
|
||||
|
||||
**扩展策略的三种方式:**
|
||||
|
||||
| 方式 | 说明 |
|
||||
| :---------------- | :---------------------------------------------------------------------------------------------------- |
|
||||
| **🎛️ 自定义信号** | 不写代码,UI 上 `字段 + 操作符 + 阈值` 组合编译成 Polars 表达式热加载 |
|
||||
| **🤖 AI 生成** | 一句话描述思路,LLM 读 `strategy-guide.md` 生成完整策略文件(经 `ast` 校验)→ 落入 `data/strategies/ai/` |
|
||||
| **📝 代码迁移** | 参照开发指南把已有策略改写为 Polars 文件放入 `data/strategies/custom/`,引擎自动发现 |
|
||||
|
||||
### 📊 指标流水线(Indicators)
|
||||
|
||||
原生 Polars 向量化,全 A 股一次扫表落盘 enriched Parquet:
|
||||
|
||||
- **均线 / 趋势**:MA(5-60)· EMA · MACD · 动量 · 布林带
|
||||
- **震荡 / 波动**:RSI · KDJ · ATR · 年化波动率 · 振幅
|
||||
- **量能 / 涨跌停**:量比 · 量均线 · 涨停信号 · 连板数
|
||||
- **原子信号**:MA / MACD 金叉死叉 · N 日新高新低 · 布林突破
|
||||
- **复权**:基于除权因子自动前复权,回测与指标口径一致
|
||||
|
||||
### 🧪 回测引擎(Backtest)
|
||||
|
||||
基于 vectorbt:**三种模式**(个股 / 策略组合 / 自由信号组合),真实约束(T+1 · 手续费 · 滑点 · 止损 · 最大持仓天数),组合管理(最大持仓 · 敞口 · 等权 / 自定义仓位)。SSE 流式进度支持切页重连,输出净值曲线 · 夏普 · 最大回撤 · 胜率 · 交易明细。
|
||||
|
||||
### 📡 监控中心(Monitor)
|
||||
|
||||
统一规则引擎,一个页面管理**四类监控**(策略 · 个股信号 · 价格涨跌 · 全市场异动):
|
||||
|
||||
- 多条件 AND/OR + 冷却期去重 + 严重级别(info/warn/critical)
|
||||
- 多入口配置:监控中心新建 / 个股详情页「加监控」/ 策略卡片一键开启
|
||||
- 命中后右下角弹窗(可配声效)+ 持久化到 `alerts.jsonl`,菜单未读徽标
|
||||
- **触发记录详情**:每条记录展示命中的具体条件(如 `RSI>80`)与当前价位,一眼看清为何触发
|
||||
- **飞书 Webhook 推送**:全局一处配置飞书群机器人地址,启用推送的规则命中即推送到飞书群(支持签名校验);可在设置页设「默认推送渠道」,新建规则自动预填
|
||||
|
||||
### 📈 个股分析(Beta)
|
||||
|
||||
以「行情 + 关键价位」为主体的单标的决策页:
|
||||
|
||||
- **专用日 K 图表**:主图 + 成交量 + 滑块,默认近 6 个月
|
||||
- **9 类关键价位**(纯函数实时计算,毫秒级):压力支撑 · 成交密集区 · 枢轴点 · 前高前低 · Keltner 通道 · ATR 止损 · 缺口位 · 斐波那契 · 整数关口
|
||||
- **AI 四维分析**:技术 / 基本面 / 财务 / 消息面流式生成,实战派交易员视角
|
||||
|
||||
### 🧰 数据与扩展
|
||||
|
||||
- **TickFlow 多源数据**:日 K / 分钟 K / 指数 / 财务 / 实时行情
|
||||
- **🔌 第三方接入(重点)**:Tushare 等 HTTP 定时拉取 · CSV / Excel 上传 · JSON 写入,自动 schema 发现 + 符号归一,页面可视化配置,**可与自有量化项目数据并入 DuckDB 同台分析**
|
||||
- **盘后定时管道**:APScheduler 15:30 CST 自动拉日 K + 重算 enriched + 跑监控
|
||||
- **令牌桶限流**:适配各档位 rpm / batch,批量合并 + 增量拉取
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ 配置
|
||||
|
||||
所有配置从根目录 `.env` 读取(复制 `.env.example` 开始),也可在面板 **设置** 页修改。
|
||||
|
||||
### 数据源:TickFlow
|
||||
|
||||
```ini
|
||||
TICKFLOW_API_KEY= # 留空 = None 模式(历史日K免费);填 Key = 按订阅档位解锁
|
||||
```
|
||||
|
||||
留空即 None 模式,通过 free-api 使用历史日 K(当日数据盘后 1-2 小时可用);免费注册 Key 后进 Free 模式,开启自选股实时监控。**实时行情按档位**:
|
||||
|
||||
| 档位 | 实时能力 |
|
||||
| :------- | :--------------------------------------- |
|
||||
| Free | 自选页前 5 个标的实时监控(最低 6 秒刷新) |
|
||||
| Starter+ | 全市场实时行情 |
|
||||
| Pro | 分钟 K + 盘口 |
|
||||
| Expert | WebSocket + 财务数据 |
|
||||
|
||||
> 完整能力矩阵见 [tickflow.org/pricing](https://tickflow.org/pricing/),高等档位含较低档全部权益。
|
||||
|
||||
### AI(可选)
|
||||
|
||||
用于自然语言生成策略。**所有配置留空即跳过**,不影响核心功能。支持任意 OpenAI 兼容接口:
|
||||
|
||||
```ini
|
||||
AI_PROVIDER=openai_compat # openai_compat | ollama
|
||||
AI_BASE_URL=https://api.deepseek.com/v1
|
||||
AI_API_KEY= # 留空 = 关闭 AI
|
||||
AI_MODEL=deepseek-chat
|
||||
AI_DAILY_TOKEN_BUDGET=500000 # 每日 token 预算上限
|
||||
```
|
||||
|
||||
### 服务与数据
|
||||
|
||||
```ini
|
||||
HOST=0.0.0.0 # 监听地址
|
||||
PORT=3018 # 服务端口
|
||||
LOG_LEVEL=INFO # DEBUG | INFO | WARNING | ERROR
|
||||
DATA_DIR=./data # Parquet / DuckDB 数据存储目录
|
||||
```
|
||||
|
||||
### 访问密码
|
||||
|
||||
面板首次设置访问密码时,出于安全考虑**仅允许本机或内网访问**(防公网陌生人抢先设置锁死面板)。公网服务器部署有两种方式设首个密码:
|
||||
|
||||
1. **环境变量预置(推荐)** — 在 `.env` 填入 `AUTH_PASSWORD`,首次启动自动初始化(哈希后写入 `auth.json`,之后不再读取):
|
||||
```ini
|
||||
AUTH_PASSWORD=你的密码 # 至少 6 位;仅首次生效,已设过则不覆盖
|
||||
```
|
||||
2. **SSH 端口转发** — 本机执行 `ssh -L 3018:127.0.0.1:3018 用户@服务器IP`,浏览器开 `http://127.0.0.1:3018` 设密码
|
||||
|
||||
> 详细步骤与重置密码见 [docs/deploy-password.md](./docs/deploy-password.md)。设完密码后改密码走页面 UI(`设置 → 修改密码`)。
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 技术栈
|
||||
|
||||
| 层 | 选型 |
|
||||
| :----------- | :------------------------------------------------------------------------------------------------ |
|
||||
| **后端** | FastAPI · Pydantic v2 · APScheduler · sse-starlette |
|
||||
| **数据** | Polars(计算)· DuckDB(查询)· Parquet(存储) |
|
||||
| **回测** | vectorbt(全项目唯一 pandas 边界) |
|
||||
| **数据源** | [TickFlow](https://tickflow.org/auth/register?ref=V3KDKGXPEA) 官方 SDK 、其他数据源后续迭代实装 |
|
||||
| **AI**(可选) | OpenAI 兼容接口(DeepSeek / 通义 / Ollama 等) |
|
||||
| **前端** | React 18 · Vite · TypeScript · Tailwind · Tanstack Query · Lightweight Charts · ECharts · dnd-kit |
|
||||
| **部署** | Docker 两阶段构建,前端 dist 拷进后端镜像,**单容器** |
|
||||
|
||||
---
|
||||
|
||||
## 🗺️ 路线图
|
||||
|
||||
| Phase | 内容 | 状态 |
|
||||
| :----- | :----------------------------------------------------------------- | :--- |
|
||||
| 0-1 | 仓库骨架 · FastAPI 壳 · 能力探测 · K 线同步与分析页 | ✅ |
|
||||
| 2-3 | Polars enriched 流水线 · Screener · vectorbt 回测(T+1/手续费/止损) | ✅ |
|
||||
| 4-5 | 监控引擎 · 四类监控规则 · 实时 SSE 推送 · 持久化记录 | ✅ |
|
||||
| 6 | 个股分析(专用日 K + 9 类关键价位 + AI 四维分析) | ✅ |
|
||||
| **v2** | Webhook 推送(QMT/掘金下单)· 板块异动 · 早晚报 · 更多扩展 | 🚧 |
|
||||
|
||||
---
|
||||
|
||||
## 📚 文档与贡献
|
||||
|
||||
- [docs/strategy-guide.md](./docs/strategy-guide.md) —— 策略开发指南(AI 生成与手写规范)
|
||||
- [docs/](./docs) —— 策略构建步骤、示例
|
||||
|
||||
欢迎 Issue 和 PR。新增内置策略:在 `backend/app/strategy/builtin/` 参照现有文件实现 `StrategyDef`,引擎自动发现。
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 免责声明
|
||||
|
||||
本项目仅供**学习与量化研究**,**不构成任何投资建议**。回测结果不代表未来收益。A 股有风险,入市需谨慎。数据准确性以数据源 TickFlow 官方为准。
|
||||
|
||||
## 📄 License
|
||||
|
||||
[MIT](./LICENSE) © tickflow-stock-panel contributors · 本项目依赖 [TickFlow](https://tickflow.org/auth/register?ref=V3KDKGXPEA) 提供数据服务,使用前请遵守其服务条款。
|
||||
|
||||
## 社区
|
||||
|
||||
本开源项目已链接并认可 [LINUX DO 社区](https://linux.do)。
|
||||
@@ -0,0 +1 @@
|
||||
v0.1.64
|
||||
@@ -0,0 +1,15 @@
|
||||
"""TickFlow Stock Panel backend."""
|
||||
|
||||
import sys
|
||||
|
||||
__version__ = "0.1.70"
|
||||
|
||||
# Windows 默认 stdout/stderr 编码为 GBK(cp936),TickFlow SDK 内部输出含 emoji 的
|
||||
# 指数/标的名称(如 \U0001f193)时会抛 UnicodeEncodeError,导致请求失败。
|
||||
# 进程加载最早阶段强制 UTF-8,根治此类编码崩溃。
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
if hasattr(_stream, "reconfigure"):
|
||||
try:
|
||||
_stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
@@ -0,0 +1 @@
|
||||
"""FastAPI 路由汇总。"""
|
||||
@@ -0,0 +1,144 @@
|
||||
"""告警触发记录 API — 查询/清空/生成演示数据 alerts.jsonl。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
|
||||
from app.services import alert_store
|
||||
|
||||
router = APIRouter(prefix="/api/alerts", tags=["alerts"])
|
||||
|
||||
|
||||
def _data_dir(request: Request) -> Path:
|
||||
return request.app.state.repo.store.data_dir
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_alerts(
|
||||
request: Request,
|
||||
days: int = 7,
|
||||
limit: int = 5000,
|
||||
source: str | None = None,
|
||||
type: str | None = None,
|
||||
):
|
||||
"""查询触发记录 (时间倒序)。"""
|
||||
events = alert_store.list_recent(
|
||||
_data_dir(request), days=days, limit=limit, source=source, type=type,
|
||||
)
|
||||
total = alert_store.count(_data_dir(request))
|
||||
return {"alerts": events, "total": total}
|
||||
|
||||
|
||||
@router.delete("")
|
||||
def clear_alerts(request: Request):
|
||||
"""清空全部触发记录。"""
|
||||
n = alert_store.clear(_data_dir(request))
|
||||
return {"ok": True, "cleared": n}
|
||||
|
||||
|
||||
@router.delete("/{ts}")
|
||||
def delete_alert(ts: int, request: Request):
|
||||
"""删除单条触发记录 (按 ts 毫秒时间戳)。"""
|
||||
deleted = alert_store.delete_one(_data_dir(request), ts)
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=404, detail="记录不存在")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ── 演示数据生成 (仅 Dev 页用) ─────────────────────────
|
||||
|
||||
_DEMO_STOCKS = [
|
||||
("600519.SH", "贵州茅台"), ("000001.SZ", "平安银行"), ("300750.SZ", "宁德时代"),
|
||||
("002594.SZ", "比亚迪"), ("000858.SZ", "五粮液"), ("601318.SH", "中国平安"),
|
||||
("002475.SZ", "立讯精密"), ("600036.SH", "招商银行"), ("000725.SZ", "京东方A"),
|
||||
("300059.SZ", "东方财富"),
|
||||
]
|
||||
_DEMO_TEMPLATES = [
|
||||
("signal", "MA金叉触发", ["signal_ma_golden_5_20"], "info"),
|
||||
("signal", "放量突破新高", ["signal_volume_surge", "signal_n_day_high"], "warn"),
|
||||
("signal", "MACD金叉", ["signal_macd_golden"], "info"),
|
||||
("signal", "跌破MA20", ["signal_ma20_breakdown"], "info"),
|
||||
("price", "涨幅超 5%", [], "warn"),
|
||||
("price", "RSI 极度超卖", [], "warn"),
|
||||
("price", "跌幅超 3%", [], "info"),
|
||||
("market", "涨停封板", ["signal_limit_up"], "critical"),
|
||||
("market", "连板异动", ["signal_limit_up"], "warn"),
|
||||
("market", "炸板", ["signal_broken_limit_up"], "warn"),
|
||||
# 新策略变更格式
|
||||
("strategy", "策略「趋势突破」进入 贵州茅台 +2.3%", ["signal_n_day_high", "signal_volume_surge"], "info"),
|
||||
("strategy", "策略「趋势突破」移出 五粮液 -1.5%", ["signal_ma20_breakdown"], "info"),
|
||||
("strategy", "策略「新低反转」进入 平安银行 +1.1%", ["signal_n_day_low"], "warn"),
|
||||
("strategy", "策略「MACD金叉」移出 比亚迪 -0.8%", ["signal_macd_golden"], "info"),
|
||||
# 批量变更
|
||||
("strategy", "策略「趋势突破」进入 6 只:平安银行、宁德时代、比亚迪、东方财富、招商银行、立讯精密", [], "info"),
|
||||
("strategy", "策略「MACD金叉」移出 7 只:京东方A、平安银行、五粮液、立讯精密、招商银行、东方财富、比亚迪", [], "warn"),
|
||||
]
|
||||
|
||||
|
||||
@router.post("/seed")
|
||||
def seed_demo_alerts(request: Request, count: int = 12, recent: bool = True):
|
||||
"""生成演示触发记录 (Dev 页用)。
|
||||
|
||||
Args:
|
||||
count: 生成条数 (1-50)
|
||||
recent: True=时间戳设为"刚刚"(用于测试闪烁效果); False=分散在近3天
|
||||
"""
|
||||
count = max(1, min(50, count))
|
||||
now_ms = int(time.time() * 1000)
|
||||
events = []
|
||||
for i in range(count):
|
||||
source, message, signals, severity = _DEMO_TEMPLATES[i % len(_DEMO_TEMPLATES)]
|
||||
sym, name = _DEMO_STOCKS[i % len(_DEMO_STOCKS)]
|
||||
# 策略类型按消息推导 type: new_entry / dropped, 否则沿用 source
|
||||
if source == "strategy":
|
||||
if "进入" in message:
|
||||
ev_type = "new_entry"
|
||||
elif "移出" in message:
|
||||
ev_type = "dropped"
|
||||
else:
|
||||
ev_type = "strategy"
|
||||
else:
|
||||
ev_type = source
|
||||
# recent 模式: 时间戳从现在往前每条错开 30 秒 (最新在前)
|
||||
ts = now_ms - (i * 30000) if recent else now_ms - random.randint(60, 4320) * 60 * 1000
|
||||
events.append({
|
||||
"ts": ts,
|
||||
"rule_id": f"demo_rule_{i}",
|
||||
"rule_name": message,
|
||||
"source": source,
|
||||
"type": ev_type,
|
||||
"symbol": "" if source == "strategy" and ("只:" in message) else sym,
|
||||
"name": name,
|
||||
"message": message,
|
||||
"price": round(random.uniform(8, 1800), 2) if not (source == "strategy" and "只:" in message) else None,
|
||||
"change_pct": round(random.uniform(-0.06, 0.098), 4) if not (source == "strategy" and "只:" in message) else None,
|
||||
"signals": signals,
|
||||
"severity": severity,
|
||||
})
|
||||
alert_store.append_many(_data_dir(request), events)
|
||||
|
||||
# 同步推入 SSE 队列, 让所有连着 SSE 的客户端实时收到 (不依赖轮询)
|
||||
qs = getattr(request.app.state, "quote_service", None)
|
||||
if qs:
|
||||
# 转成 SSE 推送格式 (和 _evaluate_monitors 一致)
|
||||
sse_alerts = [{
|
||||
"source": ev["source"],
|
||||
"type": ev["type"],
|
||||
"rule_id": ev.get("rule_id"),
|
||||
"symbol": ev["symbol"],
|
||||
"name": ev["name"],
|
||||
"message": ev["message"],
|
||||
"price": ev["price"],
|
||||
"change_pct": ev["change_pct"],
|
||||
"signals": ev["signals"],
|
||||
"severity": ev.get("severity", "info"),
|
||||
} for ev in events]
|
||||
with qs._lock:
|
||||
qs._pending_alerts.extend(sse_alerts)
|
||||
qs._alert_event.set()
|
||||
|
||||
return {"ok": True, "generated": len(events)}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
"""自定义分析菜单 API。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
router = APIRouter(prefix="/api/analysis-menus", tags=["analysis-menus"])
|
||||
|
||||
|
||||
class AnalysisColumn(BaseModel):
|
||||
field: str
|
||||
label: str = ""
|
||||
type: Literal["string", "number", "percent", "amount", "date"] = "string"
|
||||
width: int | None = None
|
||||
sortable: bool = False
|
||||
precision: int | None = None
|
||||
format: str | None = None
|
||||
aggregate: Literal["count", "avg", "sum", "min", "max"] | None = None
|
||||
visible: bool = True
|
||||
|
||||
|
||||
class DefaultSort(BaseModel):
|
||||
field: str
|
||||
order: Literal["asc", "desc"] = "desc"
|
||||
|
||||
|
||||
class AnalysisMenu(BaseModel):
|
||||
id: str = Field(..., min_length=1, max_length=64, pattern=r"^[a-zA-Z0-9_]+$")
|
||||
label: str = Field(..., min_length=1, max_length=64)
|
||||
icon: str = "chart"
|
||||
data_source: str = Field(..., min_length=1)
|
||||
template: Literal["dimension_rank", "ranking", "table"] = "dimension_rank"
|
||||
dimension_field: str | None = None
|
||||
rank_field: str | None = None
|
||||
group_columns: list[AnalysisColumn] = Field(default_factory=list)
|
||||
detail_columns: list[AnalysisColumn] = Field(default_factory=list)
|
||||
default_sort: DefaultSort | None = None
|
||||
visible: bool = True
|
||||
order: int = 0
|
||||
created_at: str | None = None
|
||||
updated_at: str | None = None
|
||||
builtin: bool = False
|
||||
|
||||
|
||||
class UpsertAnalysisMenu(BaseModel):
|
||||
label: str = Field(..., min_length=1, max_length=64)
|
||||
icon: str = "chart"
|
||||
data_source: str = Field(..., min_length=1)
|
||||
template: Literal["dimension_rank", "ranking", "table"] = "dimension_rank"
|
||||
dimension_field: str | None = None
|
||||
rank_field: str | None = None
|
||||
group_columns: list[AnalysisColumn] = Field(default_factory=list)
|
||||
detail_columns: list[AnalysisColumn] = Field(default_factory=list)
|
||||
default_sort: DefaultSort | None = None
|
||||
visible: bool = True
|
||||
order: int = 0
|
||||
|
||||
|
||||
class ReorderMenusReq(BaseModel):
|
||||
ids: list[str] = Field(..., min_length=1)
|
||||
|
||||
|
||||
def _data_dir(request: Request) -> Path:
|
||||
return request.app.state.repo.store.data_dir
|
||||
|
||||
|
||||
def _base_dir(request: Request) -> Path:
|
||||
return _data_dir(request) / "analysis_menus"
|
||||
|
||||
|
||||
def _path(request: Request, menu_id: str) -> Path:
|
||||
return _base_dir(request) / f"{menu_id}.json"
|
||||
|
||||
|
||||
def _load_saved(request: Request) -> list[AnalysisMenu]:
|
||||
base = _base_dir(request)
|
||||
if not base.exists():
|
||||
return []
|
||||
items: list[AnalysisMenu] = []
|
||||
for p in sorted(base.glob("*.json")):
|
||||
try:
|
||||
raw = json.loads(p.read_text(encoding="utf-8"))
|
||||
items.append(AnalysisMenu(**raw))
|
||||
except Exception:
|
||||
continue
|
||||
return items
|
||||
|
||||
|
||||
def _ordered(items: list[AnalysisMenu]) -> list[AnalysisMenu]:
|
||||
return sorted(items, key=lambda m: (m.order, m.label, m.id))
|
||||
|
||||
|
||||
def _save(request: Request, menu: AnalysisMenu) -> AnalysisMenu:
|
||||
now = datetime.now().isoformat()
|
||||
if not menu.created_at:
|
||||
menu.created_at = now
|
||||
menu.updated_at = now
|
||||
menu.builtin = False
|
||||
base = _base_dir(request)
|
||||
base.mkdir(parents=True, exist_ok=True)
|
||||
_path(request, menu.id).write_text(
|
||||
json.dumps(menu.model_dump(), ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return menu
|
||||
|
||||
|
||||
def _default_menus(request: Request) -> list[AnalysisMenu]:
|
||||
"""自动生成的默认分析菜单。
|
||||
|
||||
历史上会扫描扩展数据配置,对含「概念」字段的表自动生成一个「概念分析」菜单。
|
||||
现已关闭自动生成 —— 内置的概念分析页(/concept-analysis)已覆盖该场景,
|
||||
自动菜单会造成导航重复。需要时用户可在「设置 → 扩展页面」手动创建。
|
||||
"""
|
||||
return []
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_menus(request: Request):
|
||||
saved = _load_saved(request)
|
||||
saved_ids = {m.id for m in saved}
|
||||
defaults = [m for m in _default_menus(request) if m.id not in saved_ids]
|
||||
return {"items": _ordered(saved + defaults)}
|
||||
|
||||
|
||||
@router.get("/{menu_id}")
|
||||
def get_menu(request: Request, menu_id: str):
|
||||
for menu in _ordered(_load_saved(request) + _default_menus(request)):
|
||||
if menu.id == menu_id:
|
||||
return menu
|
||||
raise HTTPException(404, f"分析菜单 '{menu_id}' 不存在")
|
||||
|
||||
|
||||
@router.post("/reorder")
|
||||
def reorder_menus(request: Request, body: ReorderMenusReq):
|
||||
saved = {m.id: m for m in _load_saved(request)}
|
||||
defaults = {m.id: m for m in _default_menus(request)}
|
||||
for idx, menu_id in enumerate(body.ids):
|
||||
menu = saved.get(menu_id) or defaults.get(menu_id)
|
||||
if not menu:
|
||||
continue
|
||||
menu.order = idx
|
||||
_save(request, menu)
|
||||
return {"items": _ordered(_load_saved(request))}
|
||||
|
||||
|
||||
@router.post("/{menu_id}")
|
||||
def upsert_menu(request: Request, menu_id: str, body: UpsertAnalysisMenu):
|
||||
if not menu_id.replace("_", "").isalnum():
|
||||
raise HTTPException(400, "菜单标识只能包含字母、数字和下划线")
|
||||
existing = next((m for m in _load_saved(request) if m.id == menu_id), None)
|
||||
menu = AnalysisMenu(
|
||||
id=menu_id,
|
||||
created_at=existing.created_at if existing else None,
|
||||
**body.model_dump(),
|
||||
)
|
||||
return _save(request, menu)
|
||||
|
||||
|
||||
@router.delete("/{menu_id}")
|
||||
def delete_menu(request: Request, menu_id: str):
|
||||
p = _path(request, menu_id)
|
||||
if not p.exists():
|
||||
raise HTTPException(404, f"分析菜单 '{menu_id}' 不存在或为默认菜单")
|
||||
p.unlink()
|
||||
return {"status": "deleted"}
|
||||
@@ -0,0 +1,213 @@
|
||||
"""访问认证 API。
|
||||
|
||||
端点:
|
||||
GET /api/auth/status — 是否已设密码、当前会话是否有效
|
||||
POST /api/auth/setup — 首次设置密码(仅限本机/内网, 防公网抢占)
|
||||
POST /api/auth/login — 登录(密码 → 会话 token, 含限流)
|
||||
POST /api/auth/logout — 注销当前会话
|
||||
POST /api/auth/change-password — 改密码(需已登录)
|
||||
|
||||
安全:
|
||||
- setup 端点只接受本机/内网请求(request.client.host), 公网请求 403。
|
||||
否则黑客可比用户更早扫到域名, 抢先设密码, 反客为主。
|
||||
- login 限流: 同一来源 IP 连续失败 5 次, 锁 5 分钟(内存计数)。
|
||||
- 会话 token 通过 HttpOnly cookie 下发, 前端无需手动管理。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from threading import Lock
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.services import auth
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
|
||||
COOKIE_NAME = "tf_session"
|
||||
_COOKIE_MAX_AGE = 30 * 24 * 3600 # 与 SESSION_TTL 一致
|
||||
|
||||
# 限流: { ip: (fail_count, lock_until_ts) }
|
||||
_fail_counter: dict[str, tuple[int, float]] = defaultdict(lambda: (0, 0.0))
|
||||
_fail_lock = Lock()
|
||||
_MAX_FAILS = 5
|
||||
_LOCK_SECONDS = 300
|
||||
|
||||
|
||||
def _is_local_network(host: str | None) -> bool:
|
||||
"""是否本机或内网请求。
|
||||
|
||||
反向代理(Nginx)场景下 request.client.host 是代理本身(127.0.0.1),
|
||||
需信任 X-Forwarded-For 的最左(原始客户端)。本项目部署若经反代,
|
||||
请在反代配置正确的 X-Forwarded-For(标准做法)。
|
||||
"""
|
||||
if not host:
|
||||
return False
|
||||
if host in ("127.0.0.1", "::1", "localhost"):
|
||||
return True
|
||||
# 内网网段: 10.x / 172.16-31.x / 192.168.x
|
||||
if host.startswith("10.") or host.startswith("192.168."):
|
||||
return True
|
||||
if host.startswith("172."):
|
||||
try:
|
||||
second = int(host.split(".")[1])
|
||||
if 16 <= second <= 31:
|
||||
return True
|
||||
except (IndexError, ValueError):
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _client_ip(request: Request) -> str:
|
||||
"""取真实客户端 IP(信任反代 X-Forwarded-For)。"""
|
||||
xff = request.headers.get("x-forwarded-for")
|
||||
if xff:
|
||||
return xff.split(",")[0].strip()
|
||||
return request.client.host if request.client else "unknown"
|
||||
|
||||
|
||||
def _check_login_rate_limit(ip: str) -> None:
|
||||
"""登录失败限流检查, 触发则抛 429。"""
|
||||
with _fail_lock:
|
||||
count, until = _fail_counter.get(ip, (0, 0.0))
|
||||
now = time.time()
|
||||
if until > now:
|
||||
wait = int(until - now)
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=f"登录失败次数过多, 请 {wait} 秒后重试",
|
||||
)
|
||||
|
||||
|
||||
def _record_login_fail(ip: str) -> None:
|
||||
"""记录一次登录失败, 达阈值则锁定。"""
|
||||
with _fail_lock:
|
||||
count, until = _fail_counter.get(ip, (0, 0.0))
|
||||
count += 1
|
||||
if count >= _MAX_FAILS:
|
||||
until = time.time() + _LOCK_SECONDS
|
||||
logger.warning("auth login locked for %s after %d fails", ip, count)
|
||||
_fail_counter[ip] = (count, until)
|
||||
|
||||
|
||||
def _clear_login_fails(ip: str) -> None:
|
||||
"""登录成功后清除该 IP 的失败计数。"""
|
||||
with _fail_lock:
|
||||
_fail_counter.pop(ip, None)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 端点
|
||||
# ================================================================
|
||||
|
||||
class PasswordIn(BaseModel):
|
||||
password: str = Field(min_length=6, max_length=128)
|
||||
|
||||
|
||||
class LoginIn(BaseModel):
|
||||
password: str = Field(min_length=1, max_length=128)
|
||||
|
||||
|
||||
class ChangePasswordIn(BaseModel):
|
||||
old_password: str = Field(min_length=1, max_length=128)
|
||||
new_password: str = Field(min_length=6, max_length=128)
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
def auth_status(request: Request) -> dict:
|
||||
"""认证状态: 是否已设密码 + 当前请求是否已登录。"""
|
||||
token = request.cookies.get(COOKIE_NAME)
|
||||
return {
|
||||
"configured": auth.is_configured(),
|
||||
"authenticated": bool(token and auth.is_valid_session(token)),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/setup")
|
||||
def setup_password(req: PasswordIn, request: Request) -> dict:
|
||||
"""首次设置访问密码。仅限本机/内网请求(防公网抢占)。
|
||||
|
||||
若已设置过密码, 返回 409(改密码走 /change-password)。
|
||||
"""
|
||||
# 关键: 限制只有服务器主人(本机/内网)能设密码
|
||||
client_ip = _client_ip(request)
|
||||
if not _is_local_network(client_ip):
|
||||
logger.warning("setup rejected from non-local ip: %s", client_ip)
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="首次设置密码仅允许本机或内网访问,请通过 SSH/本地浏览器操作",
|
||||
)
|
||||
|
||||
if auth.is_configured():
|
||||
raise HTTPException(status_code=409, detail="密码已设置,如需修改请登录后使用改密码功能")
|
||||
|
||||
auth.set_password(req.password)
|
||||
logger.info("access password set up from %s", client_ip)
|
||||
return {"ok": True, "configured": True}
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
def login(req: LoginIn, request: Request, response: Response) -> dict:
|
||||
"""登录: 密码 → 会话 token(写 HttpOnly cookie)。含失败限流。"""
|
||||
ip = _client_ip(request)
|
||||
_check_login_rate_limit(ip)
|
||||
|
||||
if not auth.is_configured():
|
||||
raise HTTPException(status_code=409, detail="尚未设置访问密码")
|
||||
|
||||
token = auth.verify_and_create_session(req.password)
|
||||
if not token:
|
||||
_record_login_fail(ip)
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
|
||||
_clear_login_fails(ip)
|
||||
# HttpOnly: 防 XSS 窃取; SameSite=Lax: 防 CSRF; Path=/: 全站生效
|
||||
response.set_cookie(
|
||||
key=COOKIE_NAME,
|
||||
value=token,
|
||||
max_age=_COOKIE_MAX_AGE,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
path="/",
|
||||
secure=False, # 自托管可能无 HTTPS, 不强制 secure(建议反代加 HTTPS)
|
||||
)
|
||||
return {"ok": True, "authenticated": True}
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
def logout(request: Request, response: Response) -> dict:
|
||||
"""注销当前会话。"""
|
||||
token = request.cookies.get(COOKIE_NAME)
|
||||
if token:
|
||||
auth.revoke_session(token)
|
||||
response.delete_cookie(key=COOKIE_NAME, path="/")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/change-password")
|
||||
def change_password(req: ChangePasswordIn, request: Request) -> dict:
|
||||
"""修改密码: 需验证旧密码, 成功后所有会话失效(含当前, 需重新登录)。"""
|
||||
token = request.cookies.get(COOKIE_NAME)
|
||||
if not (token and auth.is_valid_session(token)):
|
||||
raise HTTPException(status_code=401, detail="请先登录")
|
||||
|
||||
if not auth.is_configured():
|
||||
raise HTTPException(status_code=409, detail="尚未设置访问密码")
|
||||
|
||||
# 验证旧密码
|
||||
new_token = auth.verify_and_create_session(req.old_password)
|
||||
if not new_token:
|
||||
ip = _client_ip(request)
|
||||
_record_login_fail(ip)
|
||||
raise HTTPException(status_code=401, detail="旧密码错误")
|
||||
# 临时 token 用完即弃
|
||||
auth.revoke_session(new_token)
|
||||
|
||||
# 改密码(set_password 会清空所有会话)
|
||||
auth.set_password(req.new_password)
|
||||
return {"ok": True, "message": "密码已修改, 请重新登录"}
|
||||
@@ -0,0 +1,474 @@
|
||||
"""回测 API — 信号回测 + 因子回测 + 策略回测。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import queue
|
||||
import threading
|
||||
from dataclasses import asdict
|
||||
from datetime import date, timedelta
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.config import settings
|
||||
from app.services.backtest import (
|
||||
BacktestConfig,
|
||||
BacktestService,
|
||||
VectorbtUnavailable,
|
||||
is_available,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/backtest", tags=["backtest"])
|
||||
|
||||
FACTOR_DEFAULT_DAYS = 180
|
||||
STRATEGY_DEFAULT_DAYS = 365 * 3
|
||||
BACKTEST_MAX_SERVER_DAYS = 186
|
||||
FACTOR_MAX_SYMBOLS = 1000
|
||||
BACKTEST_SERVER_GUARD_MESSAGE = (
|
||||
"当前服务器内存约 1.8GB,回测区间最多支持 6 个月;"
|
||||
"更长周期容易触发 OOM,建议在 8GB 以上内存环境或本机运行。"
|
||||
)
|
||||
|
||||
|
||||
def _get_engine(request: Request):
|
||||
"""获取或创建 BacktestEngine (单例,PanelCache 跨请求生效)。"""
|
||||
from app.backtest.engine import BacktestEngine
|
||||
engine = getattr(request.app.state, "backtest_engine", None)
|
||||
if engine is None:
|
||||
engine = BacktestEngine(request.app.state.repo)
|
||||
request.app.state.backtest_engine = engine
|
||||
return engine
|
||||
|
||||
|
||||
def _resolve_start(req: BaseModel, end: date, default_days: int) -> date:
|
||||
"""未传 start 使用默认区间;显式传 null/空值表示全部历史。"""
|
||||
start = getattr(req, "start")
|
||||
if start is not None:
|
||||
return start
|
||||
if "start" in req.model_fields_set:
|
||||
return date(1900, 1, 1)
|
||||
return end - timedelta(days=default_days)
|
||||
|
||||
|
||||
def _guard_server_backtest_range(start: date, end: date):
|
||||
if not settings.backtest_range_guard:
|
||||
return
|
||||
days = (end - start).days + 1
|
||||
if days > BACKTEST_MAX_SERVER_DAYS:
|
||||
raise HTTPException(status_code=400, detail=BACKTEST_SERVER_GUARD_MESSAGE)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 状态
|
||||
# ================================================================
|
||||
|
||||
@router.get("/status")
|
||||
def status():
|
||||
"""前端可用此接口判断回测页是否要灰显。"""
|
||||
return {"available": True}
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 信号回测 (现有接口,保持不变)
|
||||
# ================================================================
|
||||
|
||||
class BacktestRequest(BaseModel):
|
||||
symbols: list[str] = Field(..., min_length=1)
|
||||
start: date | None = None
|
||||
end: date | None = None
|
||||
entries: list[str] = []
|
||||
exits: list[str] = []
|
||||
stop_loss_pct: float | None = None
|
||||
max_hold_days: int | None = None
|
||||
fees_pct: float = 0.0002
|
||||
slippage_bps: float = 5
|
||||
matching: Literal["close_t", "open_t+1"] = "close_t"
|
||||
|
||||
|
||||
@router.post("/run")
|
||||
def run(req: BacktestRequest, request: Request):
|
||||
"""信号回测 — 现有接口,向后兼容。"""
|
||||
repo = request.app.state.repo
|
||||
svc = BacktestService(repo)
|
||||
end = req.end or date.today()
|
||||
start = req.start or (end - timedelta(days=365 * 3))
|
||||
|
||||
cfg = BacktestConfig(
|
||||
symbols=req.symbols,
|
||||
start=start,
|
||||
end=end,
|
||||
entries=req.entries,
|
||||
exits=req.exits,
|
||||
stop_loss_pct=req.stop_loss_pct,
|
||||
max_hold_days=req.max_hold_days,
|
||||
fees_pct=req.fees_pct,
|
||||
slippage_bps=req.slippage_bps,
|
||||
matching=req.matching,
|
||||
)
|
||||
try:
|
||||
result = svc.run(cfg)
|
||||
except VectorbtUnavailable as e:
|
||||
raise HTTPException(status_code=503, detail=str(e)) from e
|
||||
return asdict(result)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 因子回测
|
||||
# ================================================================
|
||||
|
||||
class FactorColumnsResponse(BaseModel):
|
||||
columns: list[dict]
|
||||
|
||||
|
||||
@router.get("/factor/columns")
|
||||
def factor_columns():
|
||||
"""返回可用的因子列列表。"""
|
||||
from app.backtest.factor import FACTOR_COLUMNS
|
||||
return {"columns": FACTOR_COLUMNS}
|
||||
|
||||
|
||||
class FactorBacktestRequest(BaseModel):
|
||||
factor_name: str
|
||||
symbols: list[str] | None = None
|
||||
start: date | None = None
|
||||
end: date | None = None
|
||||
n_groups: int = 5
|
||||
rebalance: Literal["daily", "weekly", "monthly"] = "monthly"
|
||||
weight: Literal["equal", "factor_weight"] = "equal"
|
||||
fees_pct: float = 0.0002
|
||||
slippage_bps: float = 5.0
|
||||
|
||||
|
||||
@router.post("/factor/run")
|
||||
def factor_run(req: FactorBacktestRequest, request: Request):
|
||||
"""因子回测 — IC/IR 分析 + 分层回测。"""
|
||||
from app.backtest.factor import FactorBacktestService, FactorConfig
|
||||
|
||||
engine = _get_engine(request)
|
||||
svc = FactorBacktestService(engine)
|
||||
|
||||
end = req.end or date.today()
|
||||
start = _resolve_start(req, end, STRATEGY_DEFAULT_DAYS)
|
||||
_guard_server_backtest_range(start, end)
|
||||
symbols = req.symbols if req.symbols else None
|
||||
if symbols is not None and len(symbols) > FACTOR_MAX_SYMBOLS:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"指定标的最多支持 {FACTOR_MAX_SYMBOLS} 只,请缩小标的范围。",
|
||||
)
|
||||
|
||||
cfg = FactorConfig(
|
||||
factor_name=req.factor_name,
|
||||
symbols=symbols,
|
||||
start=start,
|
||||
end=end,
|
||||
n_groups=req.n_groups,
|
||||
rebalance=req.rebalance,
|
||||
weight=req.weight,
|
||||
fees_pct=req.fees_pct,
|
||||
slippage_bps=req.slippage_bps,
|
||||
)
|
||||
result = svc.run(cfg)
|
||||
return asdict(result)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 策略回测
|
||||
# ================================================================
|
||||
|
||||
class StrategyBacktestRequest(BaseModel):
|
||||
strategy_id: str
|
||||
symbols: list[str] | None = None
|
||||
start: date | None = None
|
||||
end: date | None = None
|
||||
params: dict | None = None
|
||||
overrides: dict | None = None
|
||||
# matching 向后兼容; 显式传 entry_fill/exit_fill 时以二者为准。
|
||||
matching: Literal["close_t", "open_t+1"] = "open_t+1"
|
||||
entry_fill: Literal["close_t", "open_t+1"] | None = None
|
||||
exit_fill: Literal["close_t", "open_t+1"] | None = None
|
||||
fees_pct: float = 0.0002
|
||||
slippage_bps: float = 5.0
|
||||
max_positions: int = 10
|
||||
max_exposure_pct: float = 1.0
|
||||
initial_capital: float = 1_000_000.0
|
||||
position_sizing: Literal["equal", "score_weight"] = "equal"
|
||||
mode: Literal["position", "full"] = "position"
|
||||
holding_days: int = 5
|
||||
|
||||
|
||||
@router.post("/strategy/run")
|
||||
def strategy_run(req: StrategyBacktestRequest, request: Request):
|
||||
"""策略回测 — 复用 StrategyDef 体系做全周期回测。"""
|
||||
from app.backtest.strategy import StrategyBacktestService, StrategyBacktestConfig
|
||||
|
||||
engine = _get_engine(request)
|
||||
strategy_engine = request.app.state.strategy_engine
|
||||
svc = StrategyBacktestService(engine, strategy_engine)
|
||||
|
||||
end = req.end or date.today()
|
||||
start = _resolve_start(req, end, FACTOR_DEFAULT_DAYS)
|
||||
_guard_server_backtest_range(start, end)
|
||||
|
||||
cfg = StrategyBacktestConfig(
|
||||
strategy_id=req.strategy_id,
|
||||
symbols=req.symbols if req.symbols else None,
|
||||
start=start,
|
||||
end=end,
|
||||
params=req.params,
|
||||
overrides=req.overrides,
|
||||
matching=req.matching,
|
||||
entry_fill=req.entry_fill,
|
||||
exit_fill=req.exit_fill,
|
||||
fees_pct=req.fees_pct,
|
||||
slippage_bps=req.slippage_bps,
|
||||
max_positions=req.max_positions,
|
||||
max_exposure_pct=req.max_exposure_pct,
|
||||
initial_capital=req.initial_capital,
|
||||
position_sizing=req.position_sizing,
|
||||
mode=req.mode,
|
||||
holding_days=req.holding_days,
|
||||
)
|
||||
result = svc.run(cfg)
|
||||
return asdict(result)
|
||||
|
||||
|
||||
# ── SSE 流式回测 (实时进度 + 可取消 + 支持重连) ───────────────────
|
||||
|
||||
import time
|
||||
import hashlib
|
||||
|
||||
|
||||
class _BacktestJob:
|
||||
"""单个回测任务的状态, 存模块级供重连使用。"""
|
||||
__slots__ = ("key", "cancel_event", "progress", "result", "error", "done", "finish_ts")
|
||||
|
||||
def __init__(self, key: str):
|
||||
self.key = key
|
||||
self.cancel_event = threading.Event()
|
||||
self.progress: list[dict] = [] # 进度历史 (新连接可回放)
|
||||
self.result = None # 完成后的结果
|
||||
self.error: str | None = None
|
||||
self.done = False
|
||||
self.finish_ts: float = 0.0
|
||||
|
||||
|
||||
# 模块级任务表: key -> _BacktestJob
|
||||
_running_jobs: dict[str, _BacktestJob] = {}
|
||||
_jobs_lock = threading.Lock()
|
||||
_JOB_TTL = 300 # 完成后保留 5 分钟
|
||||
|
||||
|
||||
def _cleanup_stale_jobs():
|
||||
"""清理过期任务 (完成超过 TTL 的)。"""
|
||||
now = time.time()
|
||||
stale = [k for k, j in _running_jobs.items() if j.done and now - j.finish_ts > _JOB_TTL]
|
||||
for k in stale:
|
||||
_running_jobs.pop(k, None)
|
||||
|
||||
|
||||
def _make_job_key(
|
||||
strategy_id: str, symbols: str | None, start: str | None, end: str | None,
|
||||
matching: str, entry_fill: str | None, exit_fill: str | None,
|
||||
fees_pct: float, slippage_bps: float,
|
||||
max_positions: int, max_exposure_pct: float, initial_capital: float, position_sizing: str,
|
||||
params: str | None, overrides: str | None,
|
||||
mode: str = "position", holding_days: int = 5,
|
||||
) -> str:
|
||||
raw = f"{strategy_id}|{symbols}|{start}|{end}|{matching}|{entry_fill}|{exit_fill}|{fees_pct}|{slippage_bps}|{max_positions}|{max_exposure_pct}|{initial_capital}|{position_sizing}|{params}|{overrides}|{mode}|{holding_days}"
|
||||
return hashlib.md5(raw.encode()).hexdigest()[:12]
|
||||
|
||||
|
||||
@router.get("/strategy/stream")
|
||||
async def strategy_stream(
|
||||
request: Request,
|
||||
strategy_id: str,
|
||||
symbols: str | None = None,
|
||||
start: str | None = None,
|
||||
end: str | None = None,
|
||||
matching: str = "open_t+1",
|
||||
entry_fill: str | None = None,
|
||||
exit_fill: str | None = None,
|
||||
fees_pct: float = 0.0002,
|
||||
slippage_bps: float = 5.0,
|
||||
max_positions: int = 10,
|
||||
max_exposure_pct: float = 1.0,
|
||||
initial_capital: float = 1_000_000.0,
|
||||
position_sizing: str = "equal",
|
||||
params: str | None = None,
|
||||
overrides: str | None = None,
|
||||
mode: str = "position",
|
||||
holding_days: int = 5,
|
||||
):
|
||||
"""SSE 流式策略回测: 实时推送进度, 完成后推送结果, 支持重连 (刷新/切页后恢复)。
|
||||
|
||||
- 相同参数的任务只启动一次, 多次连接订阅同一个任务
|
||||
- 断开连接不会取消任务 (除非显式调用 cancel)
|
||||
- 结果保留 5 分钟供重连
|
||||
|
||||
事件类型:
|
||||
- progress: {day, total, date, equity}
|
||||
- done: {result} (完整回测结果)
|
||||
- error: {message}
|
||||
"""
|
||||
from app.backtest.strategy import StrategyBacktestService, StrategyBacktestConfig
|
||||
|
||||
engine = _get_engine(request)
|
||||
strategy_engine = request.app.state.strategy_engine
|
||||
svc = StrategyBacktestService(engine, strategy_engine)
|
||||
|
||||
end_date = date.fromisoformat(end) if end else date.today()
|
||||
if start:
|
||||
start_date = date.fromisoformat(start)
|
||||
else:
|
||||
# 空 start = 全部历史: 用本地最早日K日期, 查不到再回退到默认窗口
|
||||
earliest = request.app.state.repo.earliest_daily_date()
|
||||
start_date = earliest or (end_date - timedelta(days=FACTOR_DEFAULT_DAYS))
|
||||
|
||||
# 服务端范围保护
|
||||
guard_violated = False
|
||||
if settings.backtest_range_guard:
|
||||
days = (end_date - start_date).days + 1
|
||||
if days > BACKTEST_MAX_SERVER_DAYS:
|
||||
guard_violated = True
|
||||
|
||||
job_key = _make_job_key(
|
||||
strategy_id, symbols, start, end,
|
||||
matching, entry_fill, exit_fill,
|
||||
fees_pct, slippage_bps, max_positions, max_exposure_pct, initial_capital, position_sizing,
|
||||
params, overrides,
|
||||
mode, holding_days,
|
||||
)
|
||||
|
||||
_cleanup_stale_jobs()
|
||||
|
||||
# 获取或创建任务
|
||||
with _jobs_lock:
|
||||
job = _running_jobs.get(job_key)
|
||||
if job is None:
|
||||
job = _BacktestJob(job_key)
|
||||
_running_jobs[job_key] = job
|
||||
is_new = True
|
||||
else:
|
||||
is_new = False
|
||||
|
||||
async def event_generator():
|
||||
# 范围保护: 直接报错
|
||||
if guard_violated:
|
||||
yield f"event: error\ndata: {json.dumps({'message': BACKTEST_SERVER_GUARD_MESSAGE}, ensure_ascii=False)}\n\n"
|
||||
return
|
||||
|
||||
# 如果是新任务, 启动回测线程
|
||||
if is_new and not job.done:
|
||||
cfg = StrategyBacktestConfig(
|
||||
strategy_id=strategy_id,
|
||||
symbols=[s.strip() for s in symbols.split(",") if s.strip()] if symbols else None,
|
||||
start=start_date,
|
||||
end=end_date,
|
||||
params=json.loads(params) if params else None,
|
||||
overrides=json.loads(overrides) if overrides else None,
|
||||
matching=matching,
|
||||
entry_fill=entry_fill,
|
||||
exit_fill=exit_fill,
|
||||
fees_pct=fees_pct,
|
||||
slippage_bps=slippage_bps,
|
||||
max_positions=int(max_positions),
|
||||
max_exposure_pct=float(max_exposure_pct),
|
||||
initial_capital=float(initial_capital),
|
||||
position_sizing=position_sizing,
|
||||
mode=mode,
|
||||
holding_days=int(holding_days),
|
||||
)
|
||||
|
||||
def _run_backtest():
|
||||
try:
|
||||
result = svc.run(cfg, lambda d: job.progress.append(d), job.cancel_event)
|
||||
job.result = result
|
||||
job.done = True
|
||||
job.finish_ts = time.time()
|
||||
except Exception as e:
|
||||
job.error = str(e)
|
||||
job.done = True
|
||||
job.finish_ts = time.time()
|
||||
|
||||
# 启动后台线程 (不阻塞事件循环)
|
||||
threading.Thread(target=_run_backtest, daemon=True).start()
|
||||
|
||||
# 订阅进度: 用读指针读 job.progress 列表 (多连接互不干扰)
|
||||
cursor = 0
|
||||
tick = 0
|
||||
|
||||
try:
|
||||
while True:
|
||||
# 已完成: 推送最终结果/错误并退出
|
||||
if job.done:
|
||||
if job.error:
|
||||
yield f"event: error\ndata: {json.dumps({'message': job.error}, ensure_ascii=False)}\n\n"
|
||||
elif job.result is not None:
|
||||
r = job.result
|
||||
if hasattr(r, "error") and r.error == "cancelled":
|
||||
yield f"event: error\ndata: {json.dumps({'message': '回测已取消'}, ensure_ascii=False)}\n\n"
|
||||
elif hasattr(r, "error") and r.error:
|
||||
yield f"event: error\ndata: {json.dumps({'message': r.error}, ensure_ascii=False)}\n\n"
|
||||
else:
|
||||
yield f"event: done\ndata: {json.dumps(asdict(r), ensure_ascii=False, default=str)}\n\n"
|
||||
return
|
||||
|
||||
# 断开检测: 每 4 轮检查一次 (降低 GIL 抢占频率)
|
||||
tick += 1
|
||||
if tick % 4 == 0 and await request.is_disconnected():
|
||||
break
|
||||
|
||||
# 推送新进度 (从 cursor 开始读)
|
||||
prog_list = job.progress
|
||||
while cursor < len(prog_list):
|
||||
msg = prog_list[cursor]
|
||||
cursor += 1
|
||||
yield f"event: progress\ndata: {json.dumps(msg, ensure_ascii=False, default=str)}\n\n"
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
|
||||
return StreamingResponse(event_generator(), media_type="text/event-stream")
|
||||
|
||||
|
||||
@router.post("/strategy/cancel")
|
||||
async def strategy_cancel(request: Request):
|
||||
"""取消正在运行的回测任务 (前端传 query string, 后端算 job_key)。"""
|
||||
body = await request.json()
|
||||
qs = body.get("qs", "")
|
||||
# 解析 qs 得到参数
|
||||
from urllib.parse import parse_qs
|
||||
p = parse_qs(qs)
|
||||
def _get(key: str, default: str = "") -> str:
|
||||
return p.get(key, [default])[0]
|
||||
job_key = _make_job_key(
|
||||
_get("strategy_id"),
|
||||
_get("symbols") or None,
|
||||
_get("start") or None,
|
||||
_get("end") or None,
|
||||
_get("matching", "open_t+1"),
|
||||
_get("entry_fill") or None,
|
||||
_get("exit_fill") or None,
|
||||
float(_get("fees_pct", "0.0002")),
|
||||
float(_get("slippage_bps", "5")),
|
||||
int(_get("max_positions", "10")),
|
||||
float(_get("max_exposure_pct", "1")),
|
||||
float(_get("initial_capital", "1000000")),
|
||||
_get("position_sizing", "equal"),
|
||||
_get("params") or None,
|
||||
_get("overrides") or None,
|
||||
_get("mode", "position"),
|
||||
int(_get("holding_days", "5")),
|
||||
)
|
||||
job = _running_jobs.get(job_key)
|
||||
if job and not job.done:
|
||||
job.cancel_event.set()
|
||||
return {"ok": True}
|
||||
return {"ok": False, "message": "任务不存在或已完成"}
|
||||
|
||||
@@ -0,0 +1,863 @@
|
||||
"""数据画像 API —— 让前端知道"我们本地有什么数据"。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from app.indicators.pipeline import ENRICHED_COLUMNS
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/data", tags=["data"])
|
||||
|
||||
# ===== 缓存:storage(文件扫描) + 每张表 aggregate 各自缓存 =====
|
||||
# 同步期间前端 2s 轮一次 status,每张表 aggregate 全表 count + min/max + distinct
|
||||
# 太重,加 TTL + 事件失效。stage 写完只清对应那张表的缓存。
|
||||
|
||||
_TABLE_TTL = 30.0 # 兜底 TTL,即使没人调 invalidate 也会过期
|
||||
_TABLE_TTL_LARGE = 120.0 # 大表(分钟K等)单独 TTL,避免多分区聚合反复重算
|
||||
_STORAGE_TTL = 60.0 # storage 文件扫描独立 TTL,stage 写完不触发重算
|
||||
|
||||
# 聚合慢的大表(分区数多、行数多),使用更长的 TTL
|
||||
_LARGE_TABLES = {"minute"}
|
||||
|
||||
_storage_cache: dict[str, Any] | None = None
|
||||
_storage_cache_ts: float = 0.0
|
||||
_storage_lock = threading.Lock()
|
||||
|
||||
_table_cache: dict[str, dict | None] = {
|
||||
"daily": None,
|
||||
"enriched": None,
|
||||
"index_daily": None,
|
||||
"index_enriched": None,
|
||||
"index_instruments": None,
|
||||
"etf_daily": None,
|
||||
"etf_enriched": None,
|
||||
"etf_instruments": None,
|
||||
"minute": None,
|
||||
"adj_factor": None,
|
||||
"instruments": None,
|
||||
"financials": None,
|
||||
}
|
||||
_table_cache_ts: dict[str, float] = {k: 0.0 for k in _table_cache}
|
||||
_table_cache_lock = threading.Lock()
|
||||
|
||||
_last_finished_cache: dict[str, str | None] | None = None
|
||||
_last_finished_lock = threading.Lock()
|
||||
|
||||
|
||||
def invalidate_data_cache(table: str | None = None) -> None:
|
||||
"""数据写入/清除后调用。
|
||||
|
||||
table=None 时清所有表 cache + storage(粗粒度,用于 pipeline 完成/clear);
|
||||
指定 table 时只清那张表,不影响 storage(细粒度,用于单 stage 写完)。
|
||||
"""
|
||||
with _table_cache_lock:
|
||||
if table is None:
|
||||
global _storage_cache, _storage_cache_ts, _last_finished_cache
|
||||
_storage_cache = None
|
||||
_storage_cache_ts = 0.0
|
||||
_last_finished_cache = None
|
||||
for k in _table_cache:
|
||||
_table_cache[k] = None
|
||||
_table_cache_ts[k] = 0.0
|
||||
elif table in _table_cache:
|
||||
_table_cache[table] = None
|
||||
_table_cache_ts[table] = 0.0
|
||||
|
||||
|
||||
def invalidate_storage_cache() -> None:
|
||||
"""向后兼容入口 — 清全部缓存。新代码请用 invalidate_data_cache(table)。"""
|
||||
invalidate_data_cache(None)
|
||||
|
||||
|
||||
def _get_table_stats(name: str, fetch: Callable[[], dict | None]) -> dict | None:
|
||||
"""走 TTL+事件 双重缓存。fetch 在锁外执行避免阻塞别的请求。"""
|
||||
ttl = _TABLE_TTL_LARGE if name in _LARGE_TABLES else _TABLE_TTL
|
||||
now = time.time()
|
||||
with _table_cache_lock:
|
||||
cached = _table_cache.get(name)
|
||||
cached_ts = _table_cache_ts.get(name, 0.0)
|
||||
if cached is not None and (now - cached_ts) < ttl:
|
||||
return cached
|
||||
|
||||
fresh = fetch()
|
||||
|
||||
with _table_cache_lock:
|
||||
_table_cache[name] = fresh
|
||||
_table_cache_ts[name] = now
|
||||
return fresh
|
||||
|
||||
|
||||
def _safe_aggregate(repo, view: str) -> dict | None:
|
||||
"""聚合视图基础统计;视图不存在或为空时返 None。"""
|
||||
try:
|
||||
row = repo.execute_one(
|
||||
f"""SELECT count(*) AS rows,
|
||||
min(date) AS earliest,
|
||||
max(date) AS latest,
|
||||
count(DISTINCT symbol) AS symbols,
|
||||
count(DISTINCT date) AS trading_days
|
||||
FROM {view}"""
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("aggregate %s failed: %s", view, e)
|
||||
return None
|
||||
if not row or not row[0]:
|
||||
return None
|
||||
return {
|
||||
"rows": int(row[0]),
|
||||
"earliest_date": str(row[1]) if row[1] else None,
|
||||
"latest_date": str(row[2]) if row[2] else None,
|
||||
"symbols_covered": int(row[3] or 0),
|
||||
"trading_days": int(row[4] or 0),
|
||||
}
|
||||
|
||||
|
||||
def _safe_aggregate_daily(repo, view: str = "kline_daily") -> dict | None:
|
||||
"""日K轻量统计 — 零数据扫描。
|
||||
|
||||
从分区目录名获取日期范围和交易日数,不读任何 parquet。
|
||||
标的数从 instruments 小表获取(~5000行,毫秒级)。
|
||||
"""
|
||||
daily_dir = repo.store.data_dir / "kline_daily"
|
||||
if not daily_dir.exists():
|
||||
return None
|
||||
dates: list[str] = []
|
||||
for d in daily_dir.iterdir():
|
||||
if d.is_dir() and d.name.startswith("date="):
|
||||
dates.append(d.name[5:])
|
||||
if not dates:
|
||||
return None
|
||||
dates.sort()
|
||||
|
||||
symbols = _count_instruments_symbols(repo)
|
||||
|
||||
return {
|
||||
"rows": 0,
|
||||
"earliest_date": dates[0],
|
||||
"latest_date": dates[-1],
|
||||
"symbols_covered": symbols,
|
||||
"trading_days": len(dates),
|
||||
}
|
||||
|
||||
|
||||
def _safe_aggregate_enriched(repo) -> dict | None:
|
||||
"""Enriched 轻量统计 — 零数据扫描。
|
||||
|
||||
字段数从 DESCRIBE 读 schema(不碰数据),毫秒级。
|
||||
日期范围从分区目录名获取(同 minute 策略),不读任何 parquet。
|
||||
标的数从 instruments 小表取。
|
||||
"""
|
||||
# 字段数:读 schema,不碰数据
|
||||
fields = 0
|
||||
try:
|
||||
cols = repo.execute_all("DESCRIBE kline_enriched")
|
||||
fields = len(cols)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
# 日期范围:从分区目录名获取,不扫数据
|
||||
enriched_dir = repo.store.data_dir / "kline_daily_enriched"
|
||||
if not enriched_dir.exists():
|
||||
return None
|
||||
dates: list[str] = []
|
||||
for d in enriched_dir.iterdir():
|
||||
if d.is_dir() and d.name.startswith("date="):
|
||||
dates.append(d.name[5:])
|
||||
if not dates:
|
||||
return None
|
||||
dates.sort()
|
||||
|
||||
symbols = _count_instruments_symbols(repo)
|
||||
|
||||
return {
|
||||
"rows": 0,
|
||||
"fields": fields,
|
||||
"earliest_date": dates[0],
|
||||
"latest_date": dates[-1],
|
||||
"symbols_covered": symbols,
|
||||
"trading_days": len(dates),
|
||||
}
|
||||
|
||||
|
||||
def _count_instruments_symbols(repo) -> int:
|
||||
"""从 instruments 小表取标的数(~5000行,毫秒级)。"""
|
||||
try:
|
||||
sym_row = repo.execute_one(
|
||||
"SELECT count(DISTINCT symbol) FROM instruments"
|
||||
)
|
||||
if sym_row and sym_row[0]:
|
||||
return int(sym_row[0])
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
def _safe_aggregate_instruments(repo) -> dict | None:
|
||||
"""instruments 视图统计(无 date 列,用 as_of)。"""
|
||||
try:
|
||||
row = repo.execute_one(
|
||||
"""SELECT count(*) AS rows,
|
||||
count(DISTINCT symbol) AS symbols,
|
||||
max(as_of) AS latest_as_of,
|
||||
count_if(name IS NOT NULL AND name != '') AS named
|
||||
FROM instruments"""
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("aggregate instruments failed: %s", e)
|
||||
return None
|
||||
if not row or not row[0]:
|
||||
return None
|
||||
return {
|
||||
"rows": int(row[0]),
|
||||
"symbols_covered": int(row[1] or 0),
|
||||
"latest_as_of": str(row[2]) if row[2] else None,
|
||||
"named": int(row[3] or 0),
|
||||
}
|
||||
|
||||
|
||||
def _safe_aggregate_index_daily(repo) -> dict | None:
|
||||
"""指数日K统计。指数数据量较小,直接读取 parquet 元数据统计真实行数。"""
|
||||
return _safe_aggregate(repo, "kline_index_daily")
|
||||
|
||||
|
||||
def _safe_aggregate_index_enriched(repo) -> dict | None:
|
||||
"""指数 enriched 统计。指数数据量较小,直接读取 parquet 元数据统计真实行数。"""
|
||||
fields = 0
|
||||
try:
|
||||
cols = repo.execute_all("DESCRIBE kline_index_enriched")
|
||||
fields = len(cols)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
stats = _safe_aggregate(repo, "kline_index_enriched")
|
||||
if not stats:
|
||||
return None
|
||||
return {**stats, "fields": fields}
|
||||
|
||||
|
||||
def _safe_aggregate_index_instruments(repo) -> dict | None:
|
||||
"""指数 instruments 视图统计。"""
|
||||
try:
|
||||
row = repo.execute_one(
|
||||
"""SELECT count(*) AS rows,
|
||||
count(DISTINCT symbol) AS symbols,
|
||||
count_if(name IS NOT NULL AND name != '') AS named
|
||||
FROM instruments_index"""
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("aggregate instruments_index failed: %s", e)
|
||||
return None
|
||||
if not row or not row[0]:
|
||||
return None
|
||||
return {
|
||||
"rows": int(row[0]),
|
||||
"symbols_covered": int(row[1] or 0),
|
||||
"latest_as_of": None,
|
||||
"named": int(row[2] or 0),
|
||||
}
|
||||
|
||||
|
||||
def _safe_aggregate_etf_instruments(repo) -> dict | None:
|
||||
"""ETF instruments 统计 — 优先独立 instruments_etf,兼容旧 instruments_index。"""
|
||||
queries = [
|
||||
"""SELECT count(*) AS rows,
|
||||
count(DISTINCT symbol) AS symbols,
|
||||
count_if(name IS NOT NULL AND name != '') AS named
|
||||
FROM instruments_etf""",
|
||||
"""SELECT count(*) AS rows,
|
||||
count(DISTINCT symbol) AS symbols,
|
||||
count_if(name IS NOT NULL AND name != '') AS named
|
||||
FROM instruments_index
|
||||
WHERE asset_type = 'etf'""",
|
||||
]
|
||||
for sql in queries:
|
||||
try:
|
||||
row = repo.execute_one(sql)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("aggregate etf instruments fallback failed: %s", e)
|
||||
continue
|
||||
if row and row[0]:
|
||||
return {
|
||||
"rows": int(row[0]),
|
||||
"symbols_covered": int(row[1] or 0),
|
||||
"latest_as_of": None,
|
||||
"named": int(row[2] or 0),
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def _safe_aggregate_etf_enriched(repo) -> dict | None:
|
||||
"""ETF enriched 统计 — 独立 kline_etf_enriched。"""
|
||||
fields = 0
|
||||
try:
|
||||
cols = repo.execute_all("DESCRIBE kline_etf_enriched")
|
||||
fields = len(cols)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
stats = _safe_aggregate(repo, "kline_etf_enriched")
|
||||
if not stats:
|
||||
return None
|
||||
return {**stats, "fields": fields}
|
||||
|
||||
|
||||
def _safe_aggregate_etf_daily(repo) -> dict | None:
|
||||
"""ETF 日K统计 — 优先独立 kline_etf_daily,兼容旧 index 存储。"""
|
||||
queries = [
|
||||
"""SELECT count(*) AS rows,
|
||||
min(date) AS earliest,
|
||||
max(date) AS latest,
|
||||
count(DISTINCT symbol) AS symbols,
|
||||
count(DISTINCT date) AS trading_days
|
||||
FROM kline_etf_daily""",
|
||||
"""SELECT count(*) AS rows,
|
||||
min(date) AS earliest,
|
||||
max(date) AS latest,
|
||||
count(DISTINCT symbol) AS symbols,
|
||||
count(DISTINCT date) AS trading_days
|
||||
FROM kline_index_daily
|
||||
WHERE symbol IN (
|
||||
SELECT DISTINCT symbol FROM instruments_index WHERE asset_type = 'etf'
|
||||
)""",
|
||||
]
|
||||
for sql in queries:
|
||||
try:
|
||||
row = repo.execute_one(sql)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("aggregate etf daily fallback failed: %s", e)
|
||||
continue
|
||||
if row and row[0]:
|
||||
return {
|
||||
"rows": int(row[0]),
|
||||
"earliest_date": str(row[1]) if row[1] else None,
|
||||
"latest_date": str(row[2]) if row[2] else None,
|
||||
"symbols_covered": int(row[3] or 0),
|
||||
"trading_days": int(row[4] or 0),
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def _safe_aggregate_adj_factor(repo) -> dict | None:
|
||||
"""adj_factor 视图统计,日期范围对齐日 K 覆盖区间。"""
|
||||
try:
|
||||
# 取日 K 的日期范围作为过滤条件
|
||||
dr = repo.execute_one(
|
||||
"SELECT min(date), max(date) FROM kline_daily"
|
||||
)
|
||||
if not dr or not dr[0]:
|
||||
return None
|
||||
d_min, d_max = dr[0], dr[1]
|
||||
row = repo.execute_one(
|
||||
"""SELECT count(*) AS rows,
|
||||
count(DISTINCT symbol) AS symbols,
|
||||
count(DISTINCT trade_date) AS trading_days
|
||||
FROM adj_factor
|
||||
WHERE trade_date BETWEEN ? AND ?""",
|
||||
[str(d_min), str(d_max)],
|
||||
)
|
||||
if not row or not row[0]:
|
||||
return None
|
||||
return {
|
||||
"rows": int(row[0]),
|
||||
"symbols_covered": int(row[1]) if isinstance(row[1], (int, float)) else 0,
|
||||
"earliest_date": str(d_min),
|
||||
"latest_date": str(d_max),
|
||||
"trading_days": int(row[2] or 0),
|
||||
}
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("aggregate adj_factor failed: %s", e)
|
||||
return None
|
||||
|
||||
|
||||
def _safe_aggregate_minute(repo) -> dict | None:
|
||||
"""kline_minute 统计 — 从分区目录名获取交易日数,跳过全表扫描。
|
||||
|
||||
分钟 K 按 date=YYYY-MM-DD 分区存储,直接数目录即可,
|
||||
无需 count(*) / count(DISTINCT ...) 等昂贵查询。
|
||||
"""
|
||||
minute_dir = repo.store.data_dir / "kline_minute"
|
||||
if not minute_dir.exists():
|
||||
return None
|
||||
|
||||
# 从 date=YYYY-MM-DD 目录名提取交易日
|
||||
dates: list[str] = []
|
||||
for d in minute_dir.iterdir():
|
||||
if d.is_dir() and d.name.startswith("date="):
|
||||
dates.append(d.name[5:])
|
||||
|
||||
if not dates:
|
||||
return None
|
||||
|
||||
dates.sort()
|
||||
return {
|
||||
"rows": 0, # 不再查询行数
|
||||
"earliest_date": dates[0],
|
||||
"latest_date": dates[-1],
|
||||
"symbols_covered": 0, # 不再查询标的数
|
||||
"trading_days": len(dates),
|
||||
}
|
||||
|
||||
|
||||
def _safe_aggregate_financials(repo) -> dict | None:
|
||||
"""财务数据统计 — 检查各表文件是否存在及行数。"""
|
||||
data_dir = repo.store.data_dir
|
||||
tables_info: dict[str, dict] = {}
|
||||
total_rows = 0
|
||||
|
||||
for table in ("metrics", "income", "balance_sheet", "cash_flow"):
|
||||
path = data_dir / "financials" / table / "part.parquet"
|
||||
if path.exists():
|
||||
try:
|
||||
import polars as pl
|
||||
df = pl.read_parquet(path, columns=["symbol"])
|
||||
rows = len(df)
|
||||
symbols = df["symbol"].n_unique() if not df.is_empty() else 0
|
||||
tables_info[table] = {"rows": rows, "symbols": symbols}
|
||||
total_rows += rows
|
||||
except Exception:
|
||||
tables_info[table] = {"rows": 0, "symbols": 0}
|
||||
else:
|
||||
tables_info[table] = {"rows": 0, "symbols": 0}
|
||||
|
||||
if total_rows == 0:
|
||||
return None
|
||||
|
||||
return {
|
||||
"rows": total_rows,
|
||||
"tables": tables_info,
|
||||
}
|
||||
|
||||
|
||||
def _scan_dir_stats(dirpath: Path) -> tuple[int, float]:
|
||||
"""单次遍历统计目录下文件数和总大小(MB)。比 rglob+stat 快很多。"""
|
||||
if not dirpath.exists():
|
||||
return 0, 0.0
|
||||
count = 0
|
||||
total = 0
|
||||
for entry in os.scandir(dirpath):
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
c, s = _scan_dir_recursive(entry)
|
||||
count += c
|
||||
total += s
|
||||
elif entry.is_file(follow_symlinks=False):
|
||||
try:
|
||||
total += entry.stat().st_size
|
||||
except OSError:
|
||||
pass
|
||||
count += 1
|
||||
return count, round(total / 1048576, 2)
|
||||
|
||||
|
||||
def _scan_dir_recursive(entry: os.DirEntry) -> tuple[int, int]:
|
||||
"""递归统计一个 DirEntry 下的文件数和总字节数。"""
|
||||
count = 0
|
||||
total = 0
|
||||
try:
|
||||
for sub in os.scandir(entry.path):
|
||||
if sub.is_dir(follow_symlinks=False):
|
||||
c, s = _scan_dir_recursive(sub)
|
||||
count += c
|
||||
total += s
|
||||
elif sub.is_file(follow_symlinks=False):
|
||||
try:
|
||||
total += sub.stat().st_size
|
||||
except OSError:
|
||||
pass
|
||||
count += 1
|
||||
except PermissionError:
|
||||
pass
|
||||
return count, total
|
||||
|
||||
|
||||
def _compute_storage(data_dir: Path) -> dict:
|
||||
"""单次遍历计算 storage 统计,避免多次 rglob。"""
|
||||
import os
|
||||
|
||||
# 只统计关心的子目录
|
||||
subdirs = {
|
||||
"daily": data_dir / "kline_daily",
|
||||
"enriched": data_dir / "kline_daily_enriched",
|
||||
"index_daily": data_dir / "kline_index_daily",
|
||||
"index_enriched": data_dir / "kline_index_enriched",
|
||||
"index_instruments": data_dir / "instruments_index",
|
||||
"etf_daily": data_dir / "kline_etf_daily",
|
||||
"etf_enriched": data_dir / "kline_etf_enriched",
|
||||
"etf_instruments": data_dir / "instruments_etf",
|
||||
"etf_adj_factor": data_dir / "adj_factor_etf",
|
||||
"minute": data_dir / "kline_minute",
|
||||
"adj_factor": data_dir / "adj_factor",
|
||||
"instruments": data_dir / "instruments",
|
||||
"ext_data": data_dir / "ext_data",
|
||||
}
|
||||
stats = {}
|
||||
total_size = 0
|
||||
for key, d in subdirs.items():
|
||||
fc, sz = _scan_dir_stats(d)
|
||||
total_size += sz
|
||||
stats[f"{key}_files"] = fc
|
||||
stats[f"{key}_size_mb"] = sz
|
||||
|
||||
# total: 再加上其他零散文件(pools, financials, capabilities.json 等)
|
||||
other_dirs = ["pools", "financials", "backtest_results", "screener_results", "ai_cache"]
|
||||
for name in other_dirs:
|
||||
d = data_dir / name
|
||||
if d.exists():
|
||||
_, s = _scan_dir_stats(d)
|
||||
total_size += s
|
||||
|
||||
# financials 单独统计
|
||||
fin_dir = data_dir / "financials"
|
||||
if fin_dir.exists():
|
||||
fc, sz = _scan_dir_stats(fin_dir)
|
||||
stats["financials_files"] = fc
|
||||
stats["financials_size_mb"] = sz
|
||||
total_size += sz
|
||||
for name in other_dirs:
|
||||
d = data_dir / name
|
||||
if d.exists():
|
||||
_, s = _scan_dir_stats(d)
|
||||
total_size += s
|
||||
# 根目录散文件
|
||||
for entry in os.scandir(data_dir):
|
||||
if entry.is_file(follow_symlinks=False):
|
||||
try:
|
||||
total_size += entry.stat().st_size / 1048576
|
||||
except OSError:
|
||||
pass
|
||||
stats["total_size_mb"] = round(total_size, 2)
|
||||
return stats
|
||||
|
||||
|
||||
def _next_cron_run(scheduler, job_id: str) -> str | None:
|
||||
"""读 APScheduler 下次执行时间。"""
|
||||
if not scheduler:
|
||||
return None
|
||||
try:
|
||||
job = scheduler.get_job(job_id)
|
||||
if job and job.next_run_time:
|
||||
return job.next_run_time.isoformat(timespec="seconds")
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _get_storage(data_dir: Path) -> dict:
|
||||
"""返回缓存的 storage 统计;走独立 TTL,stage 写完不触发重算。"""
|
||||
global _storage_cache, _storage_cache_ts
|
||||
now = time.time()
|
||||
with _storage_lock:
|
||||
if _storage_cache is not None and (now - _storage_cache_ts) < _STORAGE_TTL:
|
||||
return _storage_cache
|
||||
fresh = _compute_storage(data_dir)
|
||||
with _storage_lock:
|
||||
_storage_cache = fresh
|
||||
_storage_cache_ts = now
|
||||
return fresh
|
||||
|
||||
|
||||
def _last_finished(job_label: str) -> str | None:
|
||||
"""从 JobStore 读最近一次该类型任务的完成时间(缓存到 pipeline 终态失效)。"""
|
||||
global _last_finished_cache
|
||||
with _last_finished_lock:
|
||||
if _last_finished_cache is not None:
|
||||
return _last_finished_cache.get(job_label)
|
||||
|
||||
from app.services.pipeline_jobs import job_store
|
||||
jobs = job_store.list_recent(limit=50)
|
||||
cache: dict[str, str | None] = {}
|
||||
for j in jobs:
|
||||
if j["status"] not in ("succeeded", "failed"):
|
||||
continue
|
||||
if "instruments_rows" in (j.get("result") or {}) and "instruments" not in cache:
|
||||
cache["instruments"] = j["finished_at"]
|
||||
if "daily_days" in (j.get("result") or {}) and "pipeline" not in cache:
|
||||
cache["pipeline"] = j["finished_at"]
|
||||
with _last_finished_lock:
|
||||
_last_finished_cache = cache
|
||||
return cache.get(job_label)
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
def status(request: Request) -> dict:
|
||||
repo = request.app.state.repo
|
||||
scheduler = getattr(request.app.state, "scheduler", None)
|
||||
data_dir = repo.store.data_dir
|
||||
|
||||
return {
|
||||
"daily": _get_table_stats("daily", lambda: _safe_aggregate_daily(repo)),
|
||||
"enriched": _get_table_stats("enriched", lambda: _safe_aggregate_enriched(repo)),
|
||||
"index_daily": _get_table_stats("index_daily", lambda: _safe_aggregate_index_daily(repo)),
|
||||
"index_enriched": _get_table_stats("index_enriched", lambda: _safe_aggregate_index_enriched(repo)),
|
||||
"index_instruments": _get_table_stats("index_instruments", lambda: _safe_aggregate_index_instruments(repo)),
|
||||
"etf_daily": _get_table_stats("etf_daily", lambda: _safe_aggregate_etf_daily(repo)),
|
||||
"etf_enriched": _get_table_stats("etf_enriched", lambda: _safe_aggregate_etf_enriched(repo)),
|
||||
"etf_instruments": _get_table_stats("etf_instruments", lambda: _safe_aggregate_etf_instruments(repo)),
|
||||
"minute": _get_table_stats("minute", lambda: _safe_aggregate_minute(repo)),
|
||||
"adj_factor": _get_table_stats("adj_factor", lambda: _safe_aggregate_adj_factor(repo)),
|
||||
"instruments": _get_table_stats("instruments", lambda: _safe_aggregate_instruments(repo)),
|
||||
"financials": _get_table_stats("financials", lambda: _safe_aggregate_financials(repo)),
|
||||
|
||||
# 文件层面信息(缓存)
|
||||
"storage": _get_storage(data_dir),
|
||||
|
||||
# 调度
|
||||
"next_instruments_run": _next_cron_run(scheduler, "pre_market_instruments"),
|
||||
"next_pipeline_run": _next_cron_run(scheduler, "daily_pipeline"),
|
||||
"last_instruments_run": _last_finished("instruments"),
|
||||
"last_pipeline_run": _last_finished("pipeline"),
|
||||
"checked_at": datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/clear")
|
||||
def clear_data(request: Request):
|
||||
"""清除所有本地 Parquet 数据(保留 capabilities.json 和目录结构)。"""
|
||||
import shutil
|
||||
|
||||
repo = request.app.state.repo
|
||||
data_dir = repo.store.data_dir
|
||||
deleted = 0
|
||||
|
||||
for sub in (
|
||||
"kline_daily", "kline_daily_enriched", "kline_index_daily", "kline_index_enriched",
|
||||
"kline_etf_daily", "kline_etf_enriched", "kline_etf_minute", "kline_minute",
|
||||
"adj_factor", "adj_factor_etf", "instruments", "instruments_index", "instruments_etf", "pools", "financials",
|
||||
"backtest_results", "screener_results", "ai_cache",
|
||||
):
|
||||
d = data_dir / sub
|
||||
if d.exists():
|
||||
# 先删所有 parquet 文件
|
||||
for f in d.rglob("*.parquet"):
|
||||
f.unlink()
|
||||
deleted += 1
|
||||
# 再删除空的日期分区子目录(date=YYYY-MM-DD 等)
|
||||
for child in list(d.iterdir()):
|
||||
if child.is_dir():
|
||||
shutil.rmtree(child, ignore_errors=True)
|
||||
|
||||
# 清除同步历史(内存 + 磁盘 job_store/ 文件夹)
|
||||
from app.services.pipeline_jobs import job_store
|
||||
job_store.clear()
|
||||
|
||||
# 清除财务数据
|
||||
fin_dir = data_dir / "financials"
|
||||
for sub in ("metrics", "income", "balance_sheet", "cash_flow"):
|
||||
fp = fin_dir / sub / "part.parquet"
|
||||
if fp.exists():
|
||||
fp.unlink()
|
||||
deleted += 1
|
||||
|
||||
# 清除监控运行数据 (user_data 下仅清运行产物, 不动 monitor_rules/preferences/secrets 等用户配置)
|
||||
# - 触发记录 alerts.jsonl
|
||||
from app.services import alert_store
|
||||
alert_store.clear(data_dir)
|
||||
# - 待推送的实时通知队列 (进程内存)
|
||||
qs = getattr(request.app.state, "quote_service", None)
|
||||
if qs is not None:
|
||||
with qs._lock:
|
||||
qs._pending_alerts.clear()
|
||||
|
||||
# 清除 Polars 缓存
|
||||
# 先 clear_cache 无条件清空内存 (refresh_cache 在磁盘无数据时会提前 return,
|
||||
# 导致 _enriched_cache 等旧数据残留 —— 清数据后看板仍显示旧数据的根因),
|
||||
# 再 refresh_cache 尝试重载 (磁盘有数据则重建缓存)。
|
||||
repo.clear_cache()
|
||||
repo.refresh_cache()
|
||||
|
||||
# 清除 Screener 进程级 _history_cache (TTL 缓存)
|
||||
from app.services.screener import ScreenerService
|
||||
ScreenerService.clear_history_cache()
|
||||
|
||||
# 清除 Overview 总览聚合结果缓存 (5s TTL)
|
||||
from app.api.overview import invalidate_overview_cache
|
||||
invalidate_overview_cache()
|
||||
|
||||
# 刷新 DuckDB 视图(空 parquet 目录也需要重新挂载)
|
||||
d = data_dir.as_posix()
|
||||
for name, path in {
|
||||
"kline_daily": f"{d}/kline_daily/**/*.parquet",
|
||||
"kline_enriched": f"{d}/kline_daily_enriched/**/*.parquet",
|
||||
"kline_index_daily": f"{d}/kline_index_daily/**/*.parquet",
|
||||
"kline_index_enriched": f"{d}/kline_index_enriched/**/*.parquet",
|
||||
"kline_etf_daily": f"{d}/kline_etf_daily/**/*.parquet",
|
||||
"kline_etf_enriched": f"{d}/kline_etf_enriched/**/*.parquet",
|
||||
"kline_etf_minute": f"{d}/kline_etf_minute/**/*.parquet",
|
||||
"kline_minute": f"{d}/kline_minute/**/*.parquet",
|
||||
"adj_factor": f"{d}/adj_factor/**/*.parquet",
|
||||
"adj_factor_etf": f"{d}/adj_factor_etf/**/*.parquet",
|
||||
"instruments": f"{d}/instruments/**/*.parquet",
|
||||
"instruments_index": f"{d}/instruments_index/**/*.parquet",
|
||||
"instruments_etf": f"{d}/instruments_etf/**/*.parquet",
|
||||
}.items():
|
||||
try:
|
||||
repo.db.execute(
|
||||
f"CREATE OR REPLACE VIEW {name} AS "
|
||||
f"SELECT * FROM read_parquet('{path}', union_by_name=true)"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
logger.info("数据已清除: 删除 %d 个 parquet 文件", deleted)
|
||||
invalidate_data_cache(None)
|
||||
return {"deleted_files": deleted}
|
||||
|
||||
|
||||
# 各表字段说明
|
||||
_TABLE_FIELD_DESC: dict[str, dict[str, str]] = {
|
||||
"kline_daily": {
|
||||
"symbol": "股票代码",
|
||||
"date": "交易日期",
|
||||
"open": "开盘价",
|
||||
"high": "最高价",
|
||||
"low": "最低价",
|
||||
"close": "收盘价",
|
||||
"volume": "成交量",
|
||||
"amount": "成交额",
|
||||
},
|
||||
"kline_enriched": ENRICHED_COLUMNS,
|
||||
"kline_index_daily": {
|
||||
"symbol": "指数代码",
|
||||
"date": "交易日期",
|
||||
"open": "开盘点位",
|
||||
"high": "最高点位",
|
||||
"low": "最低点位",
|
||||
"close": "收盘点位",
|
||||
"volume": "成交量",
|
||||
"amount": "成交额",
|
||||
},
|
||||
"kline_index_enriched": ENRICHED_COLUMNS,
|
||||
"kline_etf_daily": {
|
||||
"symbol": "ETF代码",
|
||||
"date": "交易日期",
|
||||
"open": "开盘价",
|
||||
"high": "最高价",
|
||||
"low": "最低价",
|
||||
"close": "收盘价",
|
||||
"volume": "成交量",
|
||||
"amount": "成交额",
|
||||
},
|
||||
"kline_etf_enriched": ENRICHED_COLUMNS,
|
||||
"kline_minute": {
|
||||
"symbol": "股票代码",
|
||||
"datetime": "分钟时间戳",
|
||||
"open": "开盘价",
|
||||
"high": "最高价",
|
||||
"low": "最低价",
|
||||
"close": "收盘价",
|
||||
"volume": "成交量",
|
||||
"amount": "成交额",
|
||||
},
|
||||
"adj_factor": {
|
||||
"symbol": "股票代码",
|
||||
"timestamp": "除权除息时间戳(ms)",
|
||||
"trade_date": "除权除息日",
|
||||
"ex_factor": "复权因子",
|
||||
},
|
||||
"instruments": {
|
||||
"symbol": "股票代码",
|
||||
"name": "股票名称",
|
||||
"code": "股票编码(纯数字)",
|
||||
"exchange": "交易所(SH/SZ/BJ)",
|
||||
"region": "地区",
|
||||
"type": "证券类型",
|
||||
"listing_date": "上市日期",
|
||||
"total_shares": "总股本",
|
||||
"float_shares": "流通股本",
|
||||
"tick_size": "最小价格变动单位",
|
||||
"limit_up": "涨停限制(%)",
|
||||
"limit_down": "跌停限制(%)",
|
||||
"as_of": "快照日期",
|
||||
},
|
||||
"instruments_index": {
|
||||
"symbol": "指数代码",
|
||||
"name": "指数名称",
|
||||
"code": "指数编码(纯数字)",
|
||||
"asset_type": "资产类型(index)",
|
||||
},
|
||||
"instruments_etf": {
|
||||
"symbol": "ETF代码",
|
||||
"name": "ETF名称",
|
||||
"code": "ETF编码(纯数字)",
|
||||
"asset_type": "资产类型(etf)",
|
||||
"source": "数据源",
|
||||
},
|
||||
}
|
||||
|
||||
# view 名 → DuckDB 视图名
|
||||
_SCHEMA_VIEWS: dict[str, str] = {
|
||||
"daily": "kline_daily",
|
||||
"enriched": "kline_enriched",
|
||||
"index_daily": "kline_index_daily",
|
||||
"index_enriched": "kline_index_enriched",
|
||||
"index_instruments": "instruments_index",
|
||||
"etf_daily": "kline_etf_daily",
|
||||
"etf_enriched": "kline_etf_enriched",
|
||||
"etf_instruments": "instruments_etf",
|
||||
"minute": "kline_minute",
|
||||
"adj_factor": "adj_factor",
|
||||
"instruments": "instruments",
|
||||
}
|
||||
|
||||
|
||||
@router.get("/schema/{table}")
|
||||
def table_schema(request: Request, table: str) -> list[dict]:
|
||||
"""返回指定表的字段名、类型和中文说明。
|
||||
|
||||
优先从 DuckDB DESCRIBE 读取(有数据时含精确类型);
|
||||
视图不存在(无数据)时回退到 _TABLE_FIELD_DESC 静态定义。
|
||||
"""
|
||||
view = _SCHEMA_VIEWS.get(table)
|
||||
if not view:
|
||||
return []
|
||||
desc_map = _TABLE_FIELD_DESC.get(view, {})
|
||||
repo = request.app.state.repo
|
||||
fields: list[dict] = []
|
||||
try:
|
||||
cols = repo.execute_all(f"DESCRIBE {view}")
|
||||
for col in cols:
|
||||
name = col[0]
|
||||
dtype = col[1]
|
||||
fields.append({
|
||||
"name": name,
|
||||
"type": dtype,
|
||||
"desc": desc_map.get(name, ""),
|
||||
})
|
||||
except Exception: # noqa: BLE001
|
||||
# 视图不存在(本地无数据),用静态字段定义兜底
|
||||
if desc_map:
|
||||
for name, desc in desc_map.items():
|
||||
fields.append({"name": name, "type": "—", "desc": desc})
|
||||
return fields
|
||||
|
||||
|
||||
@router.get("/version")
|
||||
def get_version(request: Request) -> dict:
|
||||
"""返回当前项目版本号。
|
||||
|
||||
优先读 app.__version__ (与 /health 接口同源, 唯一权威版本),
|
||||
回退到项目根 VERSION 文件, 最后兜底 v0.0.0。
|
||||
"""
|
||||
from app import __version__
|
||||
|
||||
# 1. 优先用 app.__version__ (唯一权威版本, 打包期由 PyInstaller 注入)
|
||||
if __version__:
|
||||
v = __version__.strip()
|
||||
return {"version": v if v.startswith("v") else f"v{v}"}
|
||||
|
||||
# 2. 回退到项目根 VERSION 文件
|
||||
from app.config import settings
|
||||
project_root = Path(settings.data_dir).parent
|
||||
version_file = project_root / "VERSION"
|
||||
if version_file.exists():
|
||||
v = version_file.read_text(encoding="utf-8").strip()
|
||||
if v:
|
||||
return {"version": v}
|
||||
|
||||
return {"version": "v0.0.0"}
|
||||
@@ -0,0 +1,871 @@
|
||||
"""扩展数据 API — CRUD + 文件上传 + JSON 写入 + 定时拉取 + schema 发现。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import shutil
|
||||
import tempfile
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import polars as pl
|
||||
from fastapi import APIRouter, File, HTTPException, Query, Request, UploadFile
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.services.ext_data import (
|
||||
ExtConfig,
|
||||
ExtConfigStore,
|
||||
ExtField,
|
||||
PullConfig,
|
||||
ensure_utf8_csv,
|
||||
fix_symbol_format,
|
||||
normalize_symbol,
|
||||
parse_upload_file,
|
||||
write_ext_parquet,
|
||||
rows_to_parquet,
|
||||
)
|
||||
from app.services.ext_pull import fetch_and_ingest, pull_scheduler
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/api/ext-data", tags=["ext-data"])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pydantic 模型
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class FieldDef(BaseModel):
|
||||
name: str
|
||||
dtype: str = "string" # string | int | float | bool
|
||||
label: str = ""
|
||||
|
||||
|
||||
class CreateExtReq(BaseModel):
|
||||
id: str = Field(..., min_length=1, max_length=64, pattern=r"^[a-zA-Z0-9_]+$")
|
||||
label: str = Field(..., min_length=1, max_length=64)
|
||||
mode: Literal["snapshot", "timeseries"]
|
||||
fields: list[FieldDef] = Field(..., min_length=1)
|
||||
description: str = ""
|
||||
symbol_map: dict = {} # {"type": "mapped", "col": "..."} 或 {"type": "computed", "from": "code", "method": "append_exchange"}
|
||||
code_map: dict = {} # {"type": "mapped", "col": "..."} 或 {"type": "computed", "from": "symbol", "method": "strip_exchange"}
|
||||
|
||||
|
||||
class UpdateExtReq(BaseModel):
|
||||
label: str | None = None
|
||||
fields: list[FieldDef] | None = None
|
||||
description: str | None = None
|
||||
symbol_map: dict | None = None
|
||||
code_map: dict | None = None
|
||||
|
||||
|
||||
class IngestReq(BaseModel):
|
||||
"""JSON 批量写入请求。"""
|
||||
date: str | None = None # YYYY-MM-DD,不传默认今天
|
||||
rows: list[dict] = Field(..., min_length=1)
|
||||
|
||||
|
||||
class PullConfigReq(BaseModel):
|
||||
"""定时拉取配置请求。"""
|
||||
url: str = Field(..., min_length=1)
|
||||
method: str = "GET"
|
||||
headers: dict[str, str] | None = None
|
||||
body: str | None = None
|
||||
response_path: str = "" # dot-path to rows array
|
||||
field_map: dict[str, str] | None = None # external → internal field name
|
||||
schedule_minutes: int = Field(1440, ge=1)
|
||||
enabled: bool = False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 辅助
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _store(request: Request) -> ExtConfigStore:
|
||||
return ExtConfigStore(request.app.state.repo.store.data_dir)
|
||||
|
||||
|
||||
def _data_dir(request: Request) -> Path:
|
||||
return request.app.state.repo.store.data_dir
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CRUD
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _apply_mapping(df: pl.DataFrame, config: ExtConfig, data_dir: Path) -> pl.DataFrame:
|
||||
"""根据 config 的 symbol_map / code_map 自动生成 symbol 和 code 列。
|
||||
|
||||
执行顺序:先 mapped(从文件列复制),再 computed(从已生成的列计算)。
|
||||
"""
|
||||
sm = config.symbol_map or {}
|
||||
cm = config.code_map or {}
|
||||
|
||||
# --- 第一步:mapped 类型,直接从文件列映射 ---
|
||||
if sm.get("type") == "mapped" and sm["col"] in df.columns:
|
||||
df = df.with_columns(df[sm["col"]].cast(pl.Utf8).alias("symbol"))
|
||||
|
||||
if cm.get("type") == "mapped" and cm["col"] in df.columns:
|
||||
df = df.with_columns(df[cm["col"]].cast(pl.Utf8).alias("code"))
|
||||
|
||||
# --- 第二步:computed 类型,从已生成的列计算 ---
|
||||
if "symbol" not in df.columns and sm.get("type") == "computed":
|
||||
if sm.get("from") == "code" and "code" in df.columns:
|
||||
# code → symbol: 000001 → 000001.SZ
|
||||
from app.services.ext_data import build_code_lookup
|
||||
lookup = build_code_lookup(data_dir)
|
||||
df = df.with_columns(normalize_symbol(df["code"].cast(pl.Utf8), lookup).alias("symbol"))
|
||||
|
||||
if "code" not in df.columns and cm.get("type") == "computed":
|
||||
if cm.get("from") == "symbol" and "symbol" in df.columns:
|
||||
# symbol → code: 000001.SZ → 000001
|
||||
df = df.with_columns(
|
||||
df["symbol"].cast(pl.Utf8).str.split(".").list.first().alias("code")
|
||||
)
|
||||
|
||||
# --- 兜底:如果只有一个,自动生成另一个 ---
|
||||
if "symbol" in df.columns and "code" not in df.columns:
|
||||
df = df.with_columns(
|
||||
df["symbol"].cast(pl.Utf8).str.split(".").list.first().alias("code")
|
||||
)
|
||||
elif "code" in df.columns and "symbol" not in df.columns:
|
||||
from app.services.ext_data import build_code_lookup
|
||||
lookup = build_code_lookup(data_dir)
|
||||
df = df.with_columns(normalize_symbol(df["code"].cast(pl.Utf8), lookup).alias("symbol"))
|
||||
|
||||
# 标准化 symbol 列
|
||||
if "symbol" in df.columns:
|
||||
from app.services.ext_data import build_code_lookup
|
||||
lookup = build_code_lookup(data_dir)
|
||||
df = df.with_columns(normalize_symbol(df["symbol"].cast(pl.Utf8), lookup))
|
||||
|
||||
return df
|
||||
|
||||
|
||||
def _clean_col_names(df: pl.DataFrame) -> pl.DataFrame:
|
||||
"""清洗列名:去掉所有 (...) 及其内容,避免时间戳导致列名不稳定。"""
|
||||
import re
|
||||
renames = {col: re.sub(r"\([^)]*\)", "", col).strip() for col in df.columns}
|
||||
# 去重:如果清洗后重名,加序号后缀
|
||||
seen: dict[str, int] = {}
|
||||
final = {}
|
||||
for old, new in renames.items():
|
||||
if new in seen:
|
||||
seen[new] += 1
|
||||
final[old] = f"{new}_{seen[new]}"
|
||||
else:
|
||||
seen[new] = 0
|
||||
final[old] = new
|
||||
return df.rename(final)
|
||||
|
||||
|
||||
def _ext_data_dir(config: ExtConfig, data_dir: Path) -> Path:
|
||||
"""返回扩展数据的数据目录。
|
||||
|
||||
- snapshot: data/ext_data/{id}/(part.parquet 与 config.json 同级)
|
||||
- timeseries: data/ext_data/{id}/timeseries/
|
||||
"""
|
||||
cfg_dir = data_dir / "ext_data" / config.id
|
||||
if config.mode == "timeseries":
|
||||
return cfg_dir / "timeseries"
|
||||
return cfg_dir
|
||||
|
||||
|
||||
def _parquet_glob(config: ExtConfig, data_dir: Path) -> str:
|
||||
"""返回该扩展配置下所有 parquet 文件的 glob 模式。
|
||||
|
||||
snapshot: 'data/ext_data/{id}/*.parquet'(只有 part.parquet)
|
||||
timeseries: 'data/ext_data/{id}/timeseries/**/*.parquet'
|
||||
"""
|
||||
cfg_dir = data_dir / "ext_data" / config.id
|
||||
if config.mode == "snapshot":
|
||||
return str(cfg_dir / "*.parquet")
|
||||
return str(cfg_dir / "timeseries" / "**" / "*.parquet")
|
||||
|
||||
|
||||
def _safe_json_value(value):
|
||||
if isinstance(value, float) and not math.isfinite(value):
|
||||
return None
|
||||
if isinstance(value, (date, datetime)):
|
||||
return value.isoformat()
|
||||
return value
|
||||
|
||||
|
||||
def _read_ext_dataframe(
|
||||
config: ExtConfig,
|
||||
data_dir: Path,
|
||||
snapshot_date: str | None = None,
|
||||
) -> tuple[pl.DataFrame, str | None]:
|
||||
cfg_dir = data_dir / "ext_data" / config.id
|
||||
|
||||
if config.mode == "snapshot":
|
||||
path = cfg_dir / "part.parquet"
|
||||
if not path.exists():
|
||||
return pl.DataFrame(), None
|
||||
return pl.read_parquet(path), _latest_sync_date(config, data_dir)
|
||||
|
||||
base = cfg_dir / "timeseries"
|
||||
if not base.exists():
|
||||
return pl.DataFrame(), None
|
||||
|
||||
if snapshot_date:
|
||||
path = base / f"date={snapshot_date}" / "part.parquet"
|
||||
if not path.exists():
|
||||
return pl.DataFrame(), snapshot_date
|
||||
return pl.read_parquet(path), snapshot_date
|
||||
|
||||
partitions = sorted(
|
||||
d for d in base.iterdir()
|
||||
if d.is_dir() and d.name.startswith("date=") and (d / "part.parquet").exists()
|
||||
)
|
||||
if not partitions:
|
||||
return pl.DataFrame(), None
|
||||
|
||||
latest = partitions[-1]
|
||||
latest_date = latest.name[5:]
|
||||
return pl.read_parquet(latest / "part.parquet"), latest_date
|
||||
|
||||
|
||||
def _with_instrument_name(df: pl.DataFrame, data_dir: Path) -> pl.DataFrame:
|
||||
if df.is_empty() or "symbol" not in df.columns or "name" in df.columns:
|
||||
return df
|
||||
path = data_dir / "instruments" / "instruments.parquet"
|
||||
if not path.exists():
|
||||
return df
|
||||
try:
|
||||
inst = pl.read_parquet(path)
|
||||
if "symbol" in inst.columns and "name" in inst.columns:
|
||||
inst = inst.select(["symbol", "name"]).unique(subset=["symbol"], keep="last")
|
||||
return df.join(inst, on="symbol", how="left")
|
||||
except Exception:
|
||||
return df
|
||||
return df
|
||||
|
||||
|
||||
def _latest_sync_date(config: ExtConfig, data_dir: Path) -> str | None:
|
||||
"""扫描数据文件,返回该扩展配置的最新同步时间(含时分秒)。
|
||||
|
||||
- snapshot: 直接取 ext_data/{id}/part.parquet 的 mtime
|
||||
- timeseries: 扫描 ext_data/{id}/timeseries/date=xxx 分区目录
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
if config.mode == "snapshot":
|
||||
# 快照: part.parquet 与 config.json 同级
|
||||
p = data_dir / "ext_data" / config.id / "part.parquet"
|
||||
if p.exists():
|
||||
ts = datetime.fromtimestamp(p.stat().st_mtime).strftime("%Y-%m-%d %H:%M:%S")
|
||||
return ts
|
||||
# 兼容旧路径
|
||||
old = data_dir / "instruments_ext"
|
||||
if old.exists():
|
||||
return _latest_sync_from_partitions(old)
|
||||
return None
|
||||
|
||||
# 时序: 扫描 timeseries/date=xxx
|
||||
base = _ext_data_dir(config, data_dir)
|
||||
if not base.exists():
|
||||
# 兼容旧路径
|
||||
base = data_dir / "kline_ext"
|
||||
if not base.exists():
|
||||
return None
|
||||
return _latest_sync_from_partitions(base)
|
||||
|
||||
|
||||
def _latest_sync_from_partitions(base: Path) -> str | None:
|
||||
"""从 date=xxx 分区目录中找到最新分区的修改时间。"""
|
||||
from datetime import datetime
|
||||
latest_ts: float = 0
|
||||
latest_date: str | None = None
|
||||
for d in base.iterdir():
|
||||
if d.is_dir() and d.name.startswith("date="):
|
||||
for f in d.glob("*.parquet"):
|
||||
mtime = f.stat().st_mtime
|
||||
if mtime > latest_ts:
|
||||
latest_ts = mtime
|
||||
latest_date = d.name[5:]
|
||||
if latest_date and latest_ts > 0:
|
||||
ts = datetime.fromtimestamp(latest_ts).strftime("%H:%M:%S")
|
||||
return f"{latest_date} {ts}"
|
||||
return latest_date
|
||||
|
||||
|
||||
def _date_range(config: ExtConfig, data_dir: Path) -> list[str] | None:
|
||||
"""返回时序型扩展数据的日期范围 [最早, 最新]。"""
|
||||
if config.mode != "timeseries":
|
||||
return None
|
||||
base = _ext_data_dir(config, data_dir)
|
||||
if not base.exists():
|
||||
# 兼容旧路径
|
||||
base = data_dir / "kline_ext"
|
||||
if not base.exists():
|
||||
return None
|
||||
dates: list[str] = []
|
||||
for d in base.iterdir():
|
||||
if d.is_dir() and d.name.startswith("date="):
|
||||
dates.append(d.name[5:])
|
||||
if len(dates) < 1:
|
||||
return None
|
||||
dates.sort()
|
||||
return [dates[0], dates[-1]]
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_configs(request: Request):
|
||||
"""列出所有扩展数据配置。"""
|
||||
configs = _store(request).load_all()
|
||||
data_dir = _data_dir(request)
|
||||
items = []
|
||||
for c in configs:
|
||||
d = c.to_dict()
|
||||
d["latest_sync_date"] = _latest_sync_date(c, data_dir)
|
||||
d["date_range"] = _date_range(c, data_dir)
|
||||
items.append(d)
|
||||
return {"items": items}
|
||||
|
||||
|
||||
@router.post("/presets/{config_id}/fetch")
|
||||
async def fetch_preset_data(request: Request, config_id: str):
|
||||
"""手动触发内置预设 (概念/行业) 的数据拉取。
|
||||
|
||||
注意: 必须在 /{config_id}/... 动态路由之前声明, 否则 'presets' 会被当成 config_id。
|
||||
与通用 pull/run 不同: 走 ext_presets 的结构转换 (接口的 concepts/industries
|
||||
数组 → 拼接成字符串), 保证 schema 与现有数据一致。
|
||||
"""
|
||||
from app.services.ext_presets import fetch_preset
|
||||
|
||||
try:
|
||||
n = await fetch_preset(config_id, _data_dir(request))
|
||||
except ValueError as e:
|
||||
raise HTTPException(404, str(e)) from e
|
||||
except Exception as e:
|
||||
raise HTTPException(400, f"拉取失败: {e}") from e
|
||||
|
||||
_refresh_views(request)
|
||||
return {"status": "ok", "rows": n}
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_config(request: Request, body: CreateExtReq):
|
||||
"""创建扩展数据配置。"""
|
||||
store = _store(request)
|
||||
if store.get(body.id):
|
||||
raise HTTPException(400, f"配置 '{body.id}' 已存在")
|
||||
config = ExtConfig(
|
||||
id=body.id,
|
||||
label=body.label,
|
||||
mode=body.mode,
|
||||
fields=[ExtField(f.name, f.dtype, f.label) for f in body.fields],
|
||||
description=body.description,
|
||||
symbol_map=body.symbol_map,
|
||||
code_map=body.code_map,
|
||||
)
|
||||
store.upsert(config)
|
||||
return config.to_dict()
|
||||
|
||||
|
||||
@router.put("/{config_id}")
|
||||
def update_config(request: Request, config_id: str, body: UpdateExtReq):
|
||||
"""更新扩展数据配置。"""
|
||||
store = _store(request)
|
||||
config = store.get(config_id)
|
||||
if not config:
|
||||
raise HTTPException(404, f"配置 '{config_id}' 不存在")
|
||||
if body.label is not None:
|
||||
config.label = body.label
|
||||
if body.fields is not None:
|
||||
config.fields = [ExtField(f.name, f.dtype, f.label) for f in body.fields]
|
||||
if body.description is not None:
|
||||
config.description = body.description
|
||||
if body.symbol_map is not None:
|
||||
config.symbol_map = body.symbol_map
|
||||
if body.code_map is not None:
|
||||
config.code_map = body.code_map
|
||||
store.upsert(config)
|
||||
return config.to_dict()
|
||||
|
||||
|
||||
@router.delete("/{config_id}")
|
||||
def delete_config(request: Request, config_id: str):
|
||||
"""删除扩展数据配置。"""
|
||||
store = _store(request)
|
||||
if not store.delete(config_id):
|
||||
raise HTTPException(404, f"配置 '{config_id}' 不存在")
|
||||
return {"status": "deleted"}
|
||||
|
||||
|
||||
@router.get("/{config_id}/rows")
|
||||
def list_rows(
|
||||
request: Request,
|
||||
config_id: str,
|
||||
snapshot_date: str | None = Query(None, alias="date"),
|
||||
columns: str | None = Query(None, description="逗号分隔的字段列表"),
|
||||
limit: int = Query(1000, ge=1, le=20000),
|
||||
):
|
||||
"""读取扩展数据明细。
|
||||
|
||||
- snapshot: 返回当前快照。
|
||||
- timeseries: 默认返回最新日期分区,也可通过 date=YYYY-MM-DD 指定。
|
||||
"""
|
||||
config = _store(request).get(config_id)
|
||||
if not config:
|
||||
raise HTTPException(404, f"配置 '{config_id}' 不存在")
|
||||
|
||||
data_dir = _data_dir(request)
|
||||
df, active_date = _read_ext_dataframe(config, data_dir, snapshot_date)
|
||||
df = _with_instrument_name(df, data_dir)
|
||||
requested = [c.strip() for c in (columns or "").split(",") if c.strip()]
|
||||
if requested:
|
||||
keep = [c for c in ["symbol", "code", "name", *requested] if c in df.columns]
|
||||
if keep:
|
||||
df = df.select(list(dict.fromkeys(keep)))
|
||||
total = len(df)
|
||||
if total > limit:
|
||||
df = df.head(limit)
|
||||
|
||||
rows = []
|
||||
for row in df.to_dicts():
|
||||
rows.append({k: _safe_json_value(v) for k, v in row.items()})
|
||||
|
||||
return {
|
||||
"id": config.id,
|
||||
"label": config.label,
|
||||
"mode": config.mode,
|
||||
"date": active_date,
|
||||
"total": total,
|
||||
"limit": limit,
|
||||
"fields": [f.to_dict() for f in config.fields],
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 文件上传
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.post("/{config_id}/upload")
|
||||
async def upload_data(
|
||||
request: Request,
|
||||
config_id: str,
|
||||
file: UploadFile = File(...),
|
||||
snapshot_date: str | None = None,
|
||||
):
|
||||
"""上传 CSV/Excel 文件写入扩展数据。"""
|
||||
store = _store(request)
|
||||
config = store.get(config_id)
|
||||
if not config:
|
||||
raise HTTPException(404, f"配置 '{config_id}' 不存在")
|
||||
|
||||
# 校验文件后缀
|
||||
suffix = Path(file.filename or "").suffix.lower()
|
||||
if suffix not in (".csv", ".xlsx", ".xls"):
|
||||
raise HTTPException(400, "仅支持 CSV / Excel 文件")
|
||||
|
||||
# 写到临时文件再解析
|
||||
tmp_dir = Path(tempfile.mkdtemp())
|
||||
tmp_path = tmp_dir / f"upload{suffix}"
|
||||
try:
|
||||
with tmp_path.open("wb") as f:
|
||||
content = await file.read()
|
||||
f.write(content)
|
||||
|
||||
# 直接读取文件,不做列重命名
|
||||
if suffix == ".csv":
|
||||
df = pl.read_csv(ensure_utf8_csv(tmp_path), infer_schema_length=10000)
|
||||
elif suffix in (".xlsx", ".xls"):
|
||||
df = pl.read_excel(tmp_path)
|
||||
else:
|
||||
raise HTTPException(400, f"不支持的文件格式: {suffix}")
|
||||
|
||||
# 清洗列名:去掉括号内的时间戳等信息
|
||||
df = _clean_col_names(df)
|
||||
|
||||
# 按映射关系自动生成 symbol 和 code 列
|
||||
df = _apply_mapping(df, config, _data_dir(request))
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
finally:
|
||||
shutil.rmtree(tmp_dir, ignore_errors=True)
|
||||
|
||||
# 确保配置的字段列存在于上传数据中(symbol/code 由映射自动生成,不校验)
|
||||
auto_fields = {"symbol", "code"}
|
||||
config_cols = {f.name for f in config.fields} - auto_fields
|
||||
missing = config_cols - set(df.columns)
|
||||
if missing:
|
||||
raise HTTPException(400, f"上传数据缺少字段: {', '.join(sorted(missing))}")
|
||||
|
||||
# 只保留配置中定义的列(包括自动生成的 symbol/code),忽略文件中多余的字段
|
||||
all_config_cols = {f.name for f in config.fields}
|
||||
keep = [c for c in df.columns if c in all_config_cols]
|
||||
df = df.select(keep)
|
||||
|
||||
# 解析快照日期
|
||||
snap = date.fromisoformat(snapshot_date) if snapshot_date else date.today()
|
||||
|
||||
rows = write_ext_parquet(df, config, _data_dir(request), snapshot_date=snap)
|
||||
|
||||
# 刷新 DuckDB 视图
|
||||
_refresh_views(request)
|
||||
|
||||
return {"status": "ok", "rows": rows, "date": snap.isoformat()}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# JSON 接口写入
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.post("/{config_id}/ingest")
|
||||
def ingest_data(request: Request, config_id: str, body: IngestReq):
|
||||
"""通过 JSON 接口批量写入扩展数据。"""
|
||||
store = _store(request)
|
||||
config = store.get(config_id)
|
||||
if not config:
|
||||
raise HTTPException(404, f"配置 '{config_id}' 不存在")
|
||||
|
||||
# 校验必填字段
|
||||
configured = {f.name for f in config.fields}
|
||||
required = configured - {"symbol"}
|
||||
for i, row in enumerate(body.rows):
|
||||
if "symbol" not in row:
|
||||
raise HTTPException(400, f"第 {i + 1} 行缺少 symbol 字段")
|
||||
missing = required - set(row.keys())
|
||||
if missing:
|
||||
raise HTTPException(400, f"第 {i + 1} 行缺少字段: {', '.join(sorted(missing))}")
|
||||
|
||||
snap = date.fromisoformat(body.date) if body.date else date.today()
|
||||
|
||||
rows_written = rows_to_parquet(body.rows, config, _data_dir(request), snapshot_date=snap)
|
||||
|
||||
_refresh_views(request)
|
||||
|
||||
return {"status": "ok", "rows": rows_written, "date": snap.isoformat()}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 定时拉取
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.put("/{config_id}/pull")
|
||||
def configure_pull(request: Request, config_id: str, body: PullConfigReq):
|
||||
"""配置(或更新)定时拉取。"""
|
||||
store = _store(request)
|
||||
config = store.get(config_id)
|
||||
if not config:
|
||||
raise HTTPException(404, f"配置 '{config_id}' 不存在")
|
||||
|
||||
# 保留历史状态字段
|
||||
old_pull = config.pull
|
||||
config.pull = PullConfig(
|
||||
url=body.url,
|
||||
method=body.method,
|
||||
headers=body.headers,
|
||||
body=body.body,
|
||||
response_path=body.response_path,
|
||||
field_map=body.field_map,
|
||||
schedule_minutes=body.schedule_minutes,
|
||||
enabled=body.enabled,
|
||||
last_run=old_pull.last_run if old_pull else None,
|
||||
last_status=old_pull.last_status if old_pull else None,
|
||||
last_message=old_pull.last_message if old_pull else None,
|
||||
last_rows=old_pull.last_rows if old_pull else None,
|
||||
)
|
||||
store.upsert(config)
|
||||
|
||||
# 刷新调度器
|
||||
pull_scheduler.refresh(_data_dir(request))
|
||||
|
||||
# 关闭定时拉取时清理残留的 next_run, 避免前端展示一个永不执行的"下次"
|
||||
if not config.pull.enabled:
|
||||
cleared = store.get(config_id)
|
||||
if cleared and cleared.pull and cleared.pull.next_run:
|
||||
cleared.pull.next_run = None
|
||||
store.upsert(cleared)
|
||||
|
||||
return {"status": "ok", "pull": config.pull.to_dict()}
|
||||
|
||||
|
||||
@router.post("/{config_id}/pull/test")
|
||||
async def test_pull(request: Request, config_id: str):
|
||||
"""测试拉取:请求外部 API 并返回预览数据,不写入。"""
|
||||
store = _store(request)
|
||||
config = store.get(config_id)
|
||||
if not config:
|
||||
raise HTTPException(404, f"配置 '{config_id}' 不存在")
|
||||
if not config.pull or not config.pull.url:
|
||||
raise HTTPException(400, "拉取未配置或 URL 为空")
|
||||
|
||||
# 临时构建一个带新配置的 config 用于测试
|
||||
from app.services.ext_pull import _extract_rows, _apply_field_map
|
||||
import httpx
|
||||
|
||||
pull = config.pull
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
headers = pull.headers or {}
|
||||
kwargs: dict = {"headers": headers}
|
||||
if pull.method.upper() == "POST" and pull.body:
|
||||
kwargs["content"] = pull.body
|
||||
if "content-type" not in {k.lower() for k in headers}:
|
||||
kwargs["headers"]["Content-Type"] = "application/json"
|
||||
resp = await client.request(pull.method.upper(), pull.url, **kwargs)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
|
||||
rows = _extract_rows(data, pull.response_path)
|
||||
preview = _apply_field_map(rows[:5], pull.field_map)
|
||||
return {
|
||||
"status": "ok",
|
||||
"total_rows": len(rows),
|
||||
"preview": preview,
|
||||
"has_symbol": bool(rows and "symbol" in rows[0]),
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(400, f"测试失败: {e}") from e
|
||||
|
||||
|
||||
@router.post("/{config_id}/pull/run")
|
||||
async def run_pull(request: Request, config_id: str):
|
||||
"""手动触发一次拉取并写入。"""
|
||||
store = _store(request)
|
||||
config = store.get(config_id)
|
||||
if not config:
|
||||
raise HTTPException(404, f"配置 '{config_id}' 不存在")
|
||||
if not config.pull or not config.pull.url:
|
||||
raise HTTPException(400, "拉取未配置或 URL 为空")
|
||||
|
||||
try:
|
||||
n, d = await fetch_and_ingest(config, _data_dir(request))
|
||||
_refresh_views(request)
|
||||
# 写回执行状态, 让前端"上次执行"面板立即反映
|
||||
updated = store.get(config_id)
|
||||
if updated and updated.pull:
|
||||
from datetime import datetime, timezone
|
||||
updated.pull.last_run = datetime.now(timezone.utc).isoformat()
|
||||
updated.pull.last_status = "success"
|
||||
updated.pull.last_message = f"{n} rows @ {d}"
|
||||
updated.pull.last_rows = n
|
||||
store.upsert(updated)
|
||||
return {"status": "ok", "rows": n, "date": d}
|
||||
except Exception as e:
|
||||
# 失败也写回状态, 记录错误信息
|
||||
failed = store.get(config_id)
|
||||
if failed and failed.pull:
|
||||
from datetime import datetime, timezone
|
||||
failed.pull.last_run = datetime.now(timezone.utc).isoformat()
|
||||
failed.pull.last_status = "error"
|
||||
failed.pull.last_message = str(e)[:200]
|
||||
store.upsert(failed)
|
||||
raise HTTPException(400, f"拉取失败: {e}") from e
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------
|
||||
# Symbol 格式修复
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.post("/{config_id}/fix-symbol")
|
||||
def fix_symbol(request: Request, config_id: str):
|
||||
"""扫描已有 Parquet 数据,将 symbol 列标准化为 代码.交易所 格式。"""
|
||||
store = _store(request)
|
||||
config = store.get(config_id)
|
||||
if not config:
|
||||
raise HTTPException(404, f"配置 '{config_id}' 不存在")
|
||||
|
||||
fixed = fix_symbol_format(config, _data_dir(request))
|
||||
_refresh_views(request)
|
||||
return {"status": "ok", "fixed_files": fixed}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Schema 发现
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_POLARS_TYPE_MAP = {
|
||||
"Int64": "int", "Int32": "int", "Int16": "int", "Int8": "int",
|
||||
"UInt64": "int", "UInt32": "int", "UInt16": "int", "UInt8": "int",
|
||||
"Float64": "float", "Float32": "float",
|
||||
"Boolean": "bool",
|
||||
"Utf8": "string", "String": "string",
|
||||
"Date": "string", "Datetime": "string", "Duration": "string",
|
||||
"Categorical": "string",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/detect-fields")
|
||||
async def detect_fields(
|
||||
request: Request,
|
||||
file: UploadFile = File(...),
|
||||
):
|
||||
"""上传 CSV/Excel 文件,自动检测列名和类型。
|
||||
|
||||
返回 symbol_candidates(数据匹配 000001.SZ 格式的列)和
|
||||
code_candidates(数据匹配 6位纯数字的列)。
|
||||
"""
|
||||
suffix = Path(file.filename or "").suffix.lower()
|
||||
if suffix not in (".csv", ".xlsx", ".xls"):
|
||||
raise HTTPException(400, "仅支持 CSV / Excel 文件")
|
||||
|
||||
tmp_dir = Path(tempfile.mkdtemp())
|
||||
tmp_path = tmp_dir / f"upload{suffix}"
|
||||
try:
|
||||
with tmp_path.open("wb") as f:
|
||||
content = await file.read()
|
||||
f.write(content)
|
||||
|
||||
# 直接读取,不要求 symbol 列
|
||||
if suffix == ".csv":
|
||||
df = pl.read_csv(ensure_utf8_csv(tmp_path), infer_schema_length=10000)
|
||||
elif suffix in (".xlsx", ".xls"):
|
||||
df = pl.read_excel(tmp_path)
|
||||
else:
|
||||
raise HTTPException(400, f"不支持的文件格式: {suffix}")
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
finally:
|
||||
shutil.rmtree(tmp_dir, ignore_errors=True)
|
||||
|
||||
# 清洗列名:去掉括号内的时间戳等信息
|
||||
df = _clean_col_names(df)
|
||||
|
||||
# 构建字段列表
|
||||
fields = []
|
||||
for col_name in df.columns:
|
||||
pl_type = df[col_name].dtype
|
||||
dtype = _POLARS_TYPE_MAP.get(str(pl_type.base_type()), "string")
|
||||
fields.append({"name": col_name, "dtype": dtype, "label": col_name})
|
||||
|
||||
# --- 分别检测 symbol 候选 (000001.SZ) 和 code 候选 (6位纯数字) ---
|
||||
import re
|
||||
_CODE_PAT = re.compile(r"^\d{6}$")
|
||||
_SYMBOL_PAT = re.compile(r"^\d{6}\.[A-Z]{2}$")
|
||||
|
||||
symbol_candidates: list[str] = [] # 数据匹配 000001.SZ 格式
|
||||
code_candidates: list[str] = [] # 数据匹配 000001 格式
|
||||
|
||||
for col in df.columns:
|
||||
col_data = df[col].cast(pl.Utf8).drop_nulls()
|
||||
if len(col_data) == 0:
|
||||
continue
|
||||
sample = col_data.head(200).to_list()
|
||||
sym_hits = sum(1 for v in sample if _SYMBOL_PAT.match(str(v).strip()))
|
||||
code_hits = sum(1 for v in sample if _CODE_PAT.match(str(v).strip()))
|
||||
total = len(sample)
|
||||
if total > 0:
|
||||
if sym_hits / total > 0.5:
|
||||
symbol_candidates.append(col)
|
||||
elif code_hits / total > 0.5:
|
||||
code_candidates.append(col)
|
||||
|
||||
return {
|
||||
"fields": fields,
|
||||
"rows": len(df),
|
||||
"symbol_candidates": symbol_candidates,
|
||||
"code_candidates": code_candidates,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/schema/{config_id}")
|
||||
def discover_schema(request: Request, config_id: str):
|
||||
"""发现扩展数据的实际 Parquet schema(基于已有数据)。"""
|
||||
config = _store(request).get(config_id)
|
||||
if not config:
|
||||
raise HTTPException(404, f"配置 '{config_id}' 不存在")
|
||||
|
||||
data_dir = _data_dir(request)
|
||||
glob = _parquet_glob(config, data_dir)
|
||||
|
||||
try:
|
||||
import duckdb
|
||||
rows = duckdb.query(
|
||||
f"SELECT column_name, data_type FROM (DESCRIBE SELECT * FROM read_parquet('{glob}', union_by_name=true))"
|
||||
).fetchall()
|
||||
return {"columns": [{"name": r[0], "type": r[1]} for r in rows]}
|
||||
except Exception:
|
||||
# 无数据时返回配置中定义的字段
|
||||
return {"columns": [f.to_dict() for f in config.fields]}
|
||||
|
||||
|
||||
@router.get("/schema-all")
|
||||
def discover_all_schemas(request: Request):
|
||||
"""发现所有扩展表的 schema(用于前端动态列选择)。"""
|
||||
configs = _store(request).load_all()
|
||||
result = []
|
||||
for config in configs:
|
||||
data_dir = _data_dir(request)
|
||||
glob = _parquet_glob(config, data_dir)
|
||||
|
||||
try:
|
||||
import duckdb
|
||||
cols = duckdb.query(
|
||||
f"SELECT column_name, data_type FROM (DESCRIBE SELECT * FROM read_parquet('{glob}', union_by_name=true))"
|
||||
).fetchall()
|
||||
field_labels = {f.name: f.label for f in config.fields}
|
||||
columns = [{"name": r[0], "type": r[1], "label": field_labels.get(r[0], r[0])} for r in cols]
|
||||
except Exception:
|
||||
columns = [f.to_dict() for f in config.fields]
|
||||
|
||||
result.append({
|
||||
"id": config.id,
|
||||
"label": config.label,
|
||||
"mode": config.mode,
|
||||
"columns": columns,
|
||||
})
|
||||
return {"items": result}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 视图刷新
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _refresh_views(request: Request) -> None:
|
||||
"""重新注册 DuckDB 视图以包含新的扩展数据。"""
|
||||
repo = request.app.state.repo
|
||||
db = repo.store.db
|
||||
d = repo.store.data_dir.as_posix()
|
||||
|
||||
# 注册旧路径视图(兼容)
|
||||
for name, subdir in [("instruments_ext", "instruments_ext"), ("kline_ext", "kline_ext")]:
|
||||
old_glob = f"{d}/{subdir}/**/*.parquet"
|
||||
old_dir = Path(d) / subdir
|
||||
if old_dir.exists():
|
||||
sql = (
|
||||
f"CREATE OR REPLACE VIEW {name} AS "
|
||||
f"SELECT * FROM read_parquet('{old_glob}', union_by_name=true)"
|
||||
)
|
||||
try:
|
||||
db.execute(sql)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 注册新路径视图:每个扩展表一个视图 ext_{config_id}
|
||||
ext_base = Path(d) / "ext_data"
|
||||
if ext_base.exists():
|
||||
for cfg_dir in ext_base.iterdir():
|
||||
if not cfg_dir.is_dir():
|
||||
continue
|
||||
cp = cfg_dir / "config.json"
|
||||
if not cp.exists():
|
||||
continue
|
||||
try:
|
||||
raw = json.loads(cp.read_text(encoding="utf-8"))
|
||||
cfg_id = raw["id"]
|
||||
# 检查是否有数据文件(snapshot: part.parquet, timeseries: timeseries/ 目录)
|
||||
has_data = (cfg_dir / "part.parquet").exists() or (cfg_dir / "timeseries").exists()
|
||||
if has_data:
|
||||
view_name = f"ext_{cfg_id}"
|
||||
# snapshot: part.parquet 在 cfg_dir/ 根下; timeseries: 在 timeseries/ 子目录
|
||||
mode = raw.get("mode", "snapshot")
|
||||
if mode == "snapshot":
|
||||
glob_pattern = f"{cfg_dir.as_posix()}/*.parquet"
|
||||
else:
|
||||
glob_pattern = f"{cfg_dir.as_posix()}/timeseries/**/*.parquet"
|
||||
sql = (
|
||||
f"CREATE OR REPLACE VIEW {view_name} AS "
|
||||
f"SELECT * FROM read_parquet('{glob_pattern}', union_by_name=true)"
|
||||
)
|
||||
db.execute(sql)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,217 @@
|
||||
"""财务数据 API — 独立路由, Cap.FINANCIAL 门控。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import polars as pl
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.services.financial_sync import get_financial_df
|
||||
from app.services.financial_analyzer import analyze_financials_stream
|
||||
from app.services import ai_reports
|
||||
from app.tickflow.capabilities import Cap
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/financials", tags=["financials"])
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
def financial_status(request: Request):
|
||||
"""返回各财务表的同步状态。无需 FINANCIAL 权限(前端根据 available 决定是否展示)。"""
|
||||
capset = request.app.state.capabilities
|
||||
if not capset.has(Cap.FINANCIAL):
|
||||
return {"available": False, "tables": {}}
|
||||
|
||||
data_dir = request.app.state.repo.store.data_dir
|
||||
tables = {}
|
||||
|
||||
for table in ("metrics", "income", "balance_sheet", "cash_flow"):
|
||||
path = data_dir / "financials" / table / "part.parquet"
|
||||
if path.exists():
|
||||
try:
|
||||
df = pl.read_parquet(path, columns=["symbol"])
|
||||
tables[table] = {
|
||||
"rows": len(df),
|
||||
"symbols": df["symbol"].n_unique() if not df.is_empty() else 0,
|
||||
}
|
||||
except Exception:
|
||||
tables[table] = {"rows": 0, "symbols": 0}
|
||||
else:
|
||||
tables[table] = {"rows": 0, "symbols": 0}
|
||||
|
||||
fs = getattr(request.app.state, "financial_scheduler", None)
|
||||
last_sync = fs.last_sync if fs else {}
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"tables": tables,
|
||||
"last_sync": last_sync,
|
||||
# 服务端是否正在同步(手动触发)——前端据此显示"同步中"并防重复点击,
|
||||
# 且刷新页面后仍能正确反映服务端状态。
|
||||
"syncing": bool(fs and fs.is_syncing),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/metrics")
|
||||
def get_metrics(request: Request, symbol: str | None = None):
|
||||
"""查询核心财务指标。"""
|
||||
capset = request.app.state.capabilities
|
||||
capset.require(Cap.FINANCIAL)
|
||||
|
||||
df = get_financial_df(request.app.state.repo.store.data_dir, "metrics")
|
||||
if df.is_empty():
|
||||
return {"data": []}
|
||||
if symbol:
|
||||
df = df.filter(pl.col("symbol") == symbol)
|
||||
return {"data": df.to_dicts()}
|
||||
|
||||
|
||||
@router.get("/income")
|
||||
def get_income(request: Request, symbol: str | None = None):
|
||||
"""查询利润表。"""
|
||||
capset = request.app.state.capabilities
|
||||
capset.require(Cap.FINANCIAL)
|
||||
|
||||
df = get_financial_df(request.app.state.repo.store.data_dir, "income")
|
||||
if df.is_empty():
|
||||
return {"data": []}
|
||||
if symbol:
|
||||
df = df.filter(pl.col("symbol") == symbol)
|
||||
return {"data": df.to_dicts()}
|
||||
|
||||
|
||||
@router.get("/balance-sheet")
|
||||
def get_balance_sheet(request: Request, symbol: str | None = None):
|
||||
"""查询资产负债表。"""
|
||||
capset = request.app.state.capabilities
|
||||
capset.require(Cap.FINANCIAL)
|
||||
|
||||
df = get_financial_df(request.app.state.repo.store.data_dir, "balance_sheet")
|
||||
if df.is_empty():
|
||||
return {"data": []}
|
||||
if symbol:
|
||||
df = df.filter(pl.col("symbol") == symbol)
|
||||
return {"data": df.to_dicts()}
|
||||
|
||||
|
||||
@router.get("/cash-flow")
|
||||
def get_cash_flow(request: Request, symbol: str | None = None):
|
||||
"""查询现金流量表。"""
|
||||
capset = request.app.state.capabilities
|
||||
capset.require(Cap.FINANCIAL)
|
||||
|
||||
df = get_financial_df(request.app.state.repo.store.data_dir, "cash_flow")
|
||||
if df.is_empty():
|
||||
return {"data": []}
|
||||
if symbol:
|
||||
df = df.filter(pl.col("symbol") == symbol)
|
||||
return {"data": df.to_dicts()}
|
||||
|
||||
|
||||
@router.post("/sync/{table}")
|
||||
def sync_table(request: Request, table: str):
|
||||
"""手动触发同步(立即返回,后台异步执行)。
|
||||
|
||||
table: metrics / income / balance_sheet / cash_flow / all
|
||||
同步在后台线程执行,全量同步需数分钟。本接口立即返回 started 状态,
|
||||
前端通过轮询 GET /status 的 syncing 字段观察进度。
|
||||
"""
|
||||
capset = request.app.state.capabilities
|
||||
capset.require(Cap.FINANCIAL)
|
||||
|
||||
valid_tables = {"metrics", "income", "balance_sheet", "cash_flow", "all"}
|
||||
if table not in valid_tables:
|
||||
raise HTTPException(400, f"invalid table: {table}, expected one of {valid_tables}")
|
||||
|
||||
fs = getattr(request.app.state, "financial_scheduler", None)
|
||||
if not fs:
|
||||
return {"status": "error", "message": "FinancialScheduler not available"}
|
||||
|
||||
target = None if table == "all" else table
|
||||
result = fs.trigger(target)
|
||||
|
||||
return {"status": "ok", "synced": result}
|
||||
|
||||
|
||||
class AnalyzeRequest(BaseModel):
|
||||
"""AI 财务分析请求。"""
|
||||
symbol: str
|
||||
focus: str = "" # 可选:用户追加的分析关注点
|
||||
|
||||
|
||||
@router.post("/analyze")
|
||||
async def analyze_financials(request: Request, req: AnalyzeRequest):
|
||||
"""AI 财务分析 — SSE 流式返回。
|
||||
|
||||
后端读取该标的 4 张财务表 → 注入 CFA 分析师级提示词 → 流式调用 LLM →
|
||||
逐 chunk 以 SSE 形式推给前端(JSON per line, 非 text/event-stream,
|
||||
以便前端用 ReadableStream 逐行解析,更简单可靠)。
|
||||
"""
|
||||
capset = request.app.state.capabilities
|
||||
capset.require(Cap.FINANCIAL)
|
||||
|
||||
if not req.symbol:
|
||||
raise HTTPException(400, "symbol 不能为空")
|
||||
|
||||
data_dir = request.app.state.repo.store.data_dir
|
||||
|
||||
async def stream_gen():
|
||||
async for chunk in analyze_financials_stream(data_dir, req.symbol, req.focus):
|
||||
yield chunk + "\n"
|
||||
|
||||
return StreamingResponse(
|
||||
stream_gen(),
|
||||
media_type="application/x-ndjson",
|
||||
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# AI 报告 CRUD(历史报告持久化)
|
||||
# ================================================================
|
||||
|
||||
class SaveReportRequest(BaseModel):
|
||||
"""保存一条 AI 财务分析报告。"""
|
||||
symbol: str
|
||||
name: str = ""
|
||||
focus: str = ""
|
||||
content: str
|
||||
periods: int | None = None
|
||||
summary: str = ""
|
||||
|
||||
|
||||
@router.get("/reports")
|
||||
def list_reports(request: Request):
|
||||
"""获取全部历史报告(按时间降序,后端已裁剪到上限)。无需 FINANCIAL 能力读取列表元信息。"""
|
||||
capset = request.app.state.capabilities
|
||||
if not capset.has(Cap.FINANCIAL):
|
||||
return {"reports": []}
|
||||
return {"reports": ai_reports.list_reports()}
|
||||
|
||||
|
||||
@router.post("/reports")
|
||||
def save_report(request: Request, req: SaveReportRequest):
|
||||
"""保存一条报告。"""
|
||||
capset = request.app.state.capabilities
|
||||
capset.require(Cap.FINANCIAL)
|
||||
report = ai_reports.save_report({
|
||||
"symbol": req.symbol,
|
||||
"name": req.name,
|
||||
"focus": req.focus,
|
||||
"content": req.content,
|
||||
"periods": req.periods,
|
||||
"summary": req.summary,
|
||||
})
|
||||
return {"ok": True, "report": report}
|
||||
|
||||
|
||||
@router.delete("/reports/{report_id}")
|
||||
def delete_report(request: Request, report_id: str):
|
||||
"""删除一条报告。"""
|
||||
capset = request.app.state.capabilities
|
||||
capset.require(Cap.FINANCIAL)
|
||||
ok = ai_reports.delete_report(report_id)
|
||||
return {"ok": ok}
|
||||
@@ -0,0 +1,149 @@
|
||||
"""指数 API。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import polars as pl
|
||||
from fastapi import APIRouter, HTTPException, Query, Request
|
||||
|
||||
from app.indicators.pipeline import compute_enriched
|
||||
from app.services import index_sync, kline_sync
|
||||
from app.tickflow.capabilities import Cap
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/index", tags=["index"])
|
||||
|
||||
|
||||
def _index_info(repo, symbol: str) -> dict:
|
||||
df = repo.get_index_instruments()
|
||||
if df.is_empty() or "symbol" not in df.columns:
|
||||
return {}
|
||||
hit = df.filter(pl.col("symbol") == symbol).head(1)
|
||||
if hit.is_empty():
|
||||
return {}
|
||||
return hit.to_dicts()[0]
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
def list_indices(request: Request):
|
||||
"""返回已缓存的 CN_Index 指数列表。"""
|
||||
repo = request.app.state.repo
|
||||
df = repo.get_index_instruments()
|
||||
if df.is_empty():
|
||||
return {"results": [], "count": 0}
|
||||
cols = [c for c in ["symbol", "name", "code", "asset_type"] if c in df.columns]
|
||||
rows = df.select(cols).sort("symbol").to_dicts()
|
||||
return {"results": rows, "count": len(rows)}
|
||||
|
||||
|
||||
@router.get("/search")
|
||||
def search_indices(
|
||||
request: Request,
|
||||
q: str = Query("", min_length=0, max_length=50, description="搜索关键词"),
|
||||
limit: int = Query(20, ge=1, le=100),
|
||||
):
|
||||
"""模糊搜索指数。"""
|
||||
repo = request.app.state.repo
|
||||
df = repo.get_index_instruments()
|
||||
if df.is_empty():
|
||||
return {"results": []}
|
||||
if not q.strip():
|
||||
rows = df.head(limit).to_dicts()
|
||||
return {"results": rows}
|
||||
|
||||
keyword = q.strip().upper()
|
||||
masks = []
|
||||
if "code" in df.columns:
|
||||
masks.append(pl.col("code").cast(pl.Utf8).str.contains(keyword, literal=True))
|
||||
masks.append(pl.col("symbol").cast(pl.Utf8).str.to_uppercase().str.contains(keyword, literal=True))
|
||||
if "name" in df.columns:
|
||||
masks.append(pl.col("name").cast(pl.Utf8).str.contains(q.strip(), literal=True))
|
||||
|
||||
mask = masks[0]
|
||||
for m in masks[1:]:
|
||||
mask = mask | m
|
||||
rows = df.filter(mask).head(limit).to_dicts()
|
||||
return {"results": rows}
|
||||
|
||||
|
||||
@router.get("/daily")
|
||||
def get_index_daily(
|
||||
request: Request,
|
||||
symbol: str = Query(..., description="指数代码, 如 000001.SH"),
|
||||
days: int = Query(120, ge=10, le=2000),
|
||||
start_date: Optional[str] = Query(None, description="起始日期 YYYY-MM-DD, 优先于 days"),
|
||||
end_date: Optional[str] = Query(None, description="截止日期 YYYY-MM-DD, 默认今天"),
|
||||
):
|
||||
"""读取指数日 K。指数数据使用独立 kline_index_* parquet。"""
|
||||
repo = request.app.state.repo
|
||||
end = date.fromisoformat(end_date) if end_date else date.today()
|
||||
start = date.fromisoformat(start_date) if start_date else end - timedelta(days=days)
|
||||
info = _index_info(repo, symbol)
|
||||
|
||||
df = repo.get_index_daily(symbol, start, end)
|
||||
if not df.is_empty():
|
||||
return {"symbol": symbol, "name": info.get("name"), "index_info": info, "rows": df.to_dicts(), "source": "index_enriched"}
|
||||
|
||||
capset = request.app.state.capabilities
|
||||
if not capset.has(Cap.KLINE_DAILY_BATCH):
|
||||
return {"symbol": symbol, "name": info.get("name"), "index_info": info, "rows": [], "source": "none"}
|
||||
|
||||
try:
|
||||
raw = kline_sync.sync_daily_batch([symbol], count=days + 150)
|
||||
except Exception as e: # noqa: BLE001
|
||||
raise HTTPException(status_code=502, detail=f"TickFlow fetch failed: {e}") from e
|
||||
if raw.is_empty():
|
||||
return {"symbol": symbol, "name": info.get("name"), "index_info": info, "rows": [], "source": "none"}
|
||||
|
||||
enriched = compute_enriched(raw, factors=None, instruments=None)
|
||||
rows = enriched.filter((pl.col("date") >= start) & (pl.col("date") <= end)).to_dicts()
|
||||
return {"symbol": symbol, "name": info.get("name"), "index_info": info, "rows": rows, "source": "live"}
|
||||
|
||||
|
||||
@router.get("/minute")
|
||||
def get_index_minute(
|
||||
request: Request,
|
||||
symbol: str = Query(..., description="指数代码, 如 000001.SH"),
|
||||
trade_date: date | None = Query(None, alias="date", description="交易日期, 默认今天"),
|
||||
):
|
||||
"""实时读取指数分钟 K。不写入股票分钟 parquet。"""
|
||||
repo = request.app.state.repo
|
||||
info = _index_info(repo, symbol)
|
||||
day = trade_date or date.today()
|
||||
df = kline_sync.fetch_minute_single(symbol, day)
|
||||
return {
|
||||
"symbol": symbol,
|
||||
"name": info.get("name"),
|
||||
"index_info": info,
|
||||
"date": str(day),
|
||||
"rows": df.to_dicts(),
|
||||
"source": "live" if not df.is_empty() else "none",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/sync_instruments")
|
||||
def sync_index_instruments(request: Request):
|
||||
"""同步 CN_Index 指数标的列表。"""
|
||||
repo = request.app.state.repo
|
||||
count = index_sync.sync_index_instruments(repo)
|
||||
return {"status": "ok", "count": count}
|
||||
|
||||
|
||||
@router.post("/sync_daily")
|
||||
def sync_index_daily(
|
||||
request: Request,
|
||||
days: int = Query(365, ge=30, le=5000),
|
||||
):
|
||||
"""同步指数日K到独立 parquet。"""
|
||||
repo = request.app.state.repo
|
||||
capset = request.app.state.capabilities
|
||||
if not capset.has(Cap.KLINE_DAILY_BATCH):
|
||||
raise HTTPException(status_code=403, detail="需要 Pro+ 权限 (batch K-line)")
|
||||
end = datetime.now()
|
||||
start = end - timedelta(days=days)
|
||||
count = index_sync.sync_index_instruments(repo)
|
||||
rows = index_sync.sync_and_persist_index_daily(repo, capset, start_date=start, end_date=end)
|
||||
return {"status": "ok", "index_count": count, "rows_written": rows}
|
||||
@@ -0,0 +1,212 @@
|
||||
"""行情状态 / SSE 推送 API。
|
||||
|
||||
盘中选股相关端点已迁移至策略页面,此处仅保留全局行情基础设施。
|
||||
SSE 推送三种事件 (使用标准 SSE event 字段):
|
||||
- quotes_updated: 行情数据刷新,前端 invalidate 对应 query
|
||||
- strategy_alert: 策略监控/告警触发,前端弹通知
|
||||
- depth_updated: 五档盘口修正完成,前端刷新连板梯队/看板封单数据
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Query, Request
|
||||
from sse_starlette.sse import EventSourceResponse
|
||||
|
||||
router = APIRouter(prefix="/api/intraday", tags=["quotes"])
|
||||
|
||||
|
||||
def _get_quote_service(request: Request):
|
||||
"""获取全局 QuoteService。"""
|
||||
return getattr(request.app.state, "quote_service", None)
|
||||
|
||||
|
||||
def _fallback_index_quotes_from_daily(request: Request, symbols: list[str] | None = None) -> list[dict]:
|
||||
"""实时指数缓存为空时,从本地指数日 K 取最近收盘价作为兜底。"""
|
||||
repo = getattr(request.app.state, "repo", None)
|
||||
if not repo:
|
||||
return []
|
||||
|
||||
params: list[str] = []
|
||||
symbol_filter = ""
|
||||
if symbols:
|
||||
placeholders = ", ".join("?" for _ in symbols)
|
||||
symbol_filter = f"WHERE symbol IN ({placeholders})"
|
||||
params.extend(symbols)
|
||||
|
||||
try:
|
||||
rows = repo.execute_all(
|
||||
f"""
|
||||
WITH ranked AS (
|
||||
SELECT symbol, date, close,
|
||||
row_number() OVER (PARTITION BY symbol ORDER BY date DESC) AS rn
|
||||
FROM kline_index_daily
|
||||
{symbol_filter}
|
||||
), latest AS (
|
||||
SELECT symbol,
|
||||
max(CASE WHEN rn = 1 THEN date END) AS date,
|
||||
max(CASE WHEN rn = 1 THEN close END) AS last_price,
|
||||
max(CASE WHEN rn = 2 THEN close END) AS prev_close
|
||||
FROM ranked
|
||||
WHERE rn <= 2
|
||||
GROUP BY symbol
|
||||
)
|
||||
SELECT latest.symbol, latest.date, latest.last_price, latest.prev_close
|
||||
FROM latest
|
||||
ORDER BY latest.symbol
|
||||
""",
|
||||
params,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
|
||||
out: list[dict] = []
|
||||
for symbol, dt, last_price, prev_close in rows:
|
||||
change_amount = None
|
||||
change_pct = None
|
||||
if last_price is not None and prev_close not in (None, 0):
|
||||
change_amount = float(last_price) - float(prev_close)
|
||||
change_pct = change_amount / float(prev_close) * 100
|
||||
out.append({
|
||||
"symbol": symbol,
|
||||
"name": None,
|
||||
"date": str(dt) if dt else None,
|
||||
"last_price": float(last_price) if last_price is not None else None,
|
||||
"close": float(last_price) if last_price is not None else None,
|
||||
"prev_close": float(prev_close) if prev_close is not None else None,
|
||||
"change_amount": change_amount,
|
||||
"change_pct": change_pct,
|
||||
"source": "index_daily",
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
def status(request: Request):
|
||||
"""行情状态 (来自全局 QuoteService)。"""
|
||||
qs = _get_quote_service(request)
|
||||
if qs:
|
||||
return qs.status()
|
||||
return {"enabled": False, "running": False, "symbol_count": 0, "index_symbol_count": 0,
|
||||
"quote_age_ms": None, "is_trading_hours": False, "last_fetch_ms": None}
|
||||
|
||||
|
||||
@router.get("/indices")
|
||||
def index_quotes(
|
||||
request: Request,
|
||||
symbols: str | None = Query(None, description="逗号分隔的指数 symbol 列表"),
|
||||
):
|
||||
"""返回实时指数行情缓存,不触发 TickFlow 请求。"""
|
||||
symbol_list = [s.strip() for s in symbols.split(",") if s.strip()] if symbols else None
|
||||
qs = _get_quote_service(request)
|
||||
if not qs:
|
||||
rows = _fallback_index_quotes_from_daily(request, symbol_list)
|
||||
return {"rows": rows, "count": len(rows), "source": "index_daily"}
|
||||
df = qs.get_index_quotes(symbol_list)
|
||||
rows = df.to_dicts() if not df.is_empty() else []
|
||||
if not rows:
|
||||
rows = _fallback_index_quotes_from_daily(request, symbol_list)
|
||||
return {"rows": rows, "count": len(rows), "source": "index_daily"}
|
||||
return {"rows": rows, "count": len(rows), "source": "realtime"}
|
||||
|
||||
|
||||
@router.get("/stream")
|
||||
async def quote_stream(request: Request):
|
||||
"""SSE 端点: 行情更新 + 告警推送 + 五档修正。
|
||||
|
||||
使用 sse-starlette EventSourceResponse:
|
||||
- 标准 SSE event 字段,前端按 event name 监听
|
||||
- 内置断线检测,客户端断开立即终止 generator
|
||||
- 内置 ping 心跳,保持连接活跃
|
||||
"""
|
||||
qs = _get_quote_service(request)
|
||||
|
||||
async def event_generator():
|
||||
while True:
|
||||
# 同时等待三类信号: 行情更新 / 告警 / 五档修正
|
||||
tasks: dict[str, asyncio.Future] = {
|
||||
"quote": asyncio.ensure_future(
|
||||
asyncio.to_thread(qs.wait_for_update, timeout=5.0) if qs else asyncio.sleep(5)
|
||||
),
|
||||
"alert": asyncio.ensure_future(
|
||||
asyncio.to_thread(qs.wait_for_alert, timeout=5.0) if qs else asyncio.sleep(5)
|
||||
),
|
||||
"depth": asyncio.ensure_future(
|
||||
asyncio.to_thread(qs.wait_for_depth_update, timeout=5.0) if qs else asyncio.sleep(5)
|
||||
),
|
||||
"review": asyncio.ensure_future(
|
||||
asyncio.to_thread(qs.wait_for_review, timeout=5.0) if qs else asyncio.sleep(5)
|
||||
),
|
||||
}
|
||||
|
||||
done, pending = await asyncio.wait(
|
||||
list(tasks.values()),
|
||||
timeout=30.0,
|
||||
return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
for t in pending:
|
||||
t.cancel()
|
||||
|
||||
# 先推送告警 (如果有)
|
||||
if qs:
|
||||
alerts = qs.pop_alerts()
|
||||
if alerts:
|
||||
for chunk_start in range(0, len(alerts), 20):
|
||||
chunk = alerts[chunk_start:chunk_start + 20]
|
||||
yield {
|
||||
"event": "strategy_alert",
|
||||
"data": json.dumps({
|
||||
"ts": int(time.time() * 1000),
|
||||
"alerts": chunk,
|
||||
}, ensure_ascii=False),
|
||||
}
|
||||
|
||||
# 推送复盘进度 (定时复盘流式生成时) — 前端 reviewStore 直接消费
|
||||
# 事件已是 recap_market_stream 产出的 JSON 字符串, 逐条转发
|
||||
for evt_json in qs.pop_review_events():
|
||||
yield {
|
||||
"event": "review_progress",
|
||||
"data": evt_json,
|
||||
}
|
||||
|
||||
# 推送行情更新 (行情信号触发)
|
||||
if tasks["quote"] in done:
|
||||
try:
|
||||
update_result = tasks["quote"].result()
|
||||
except Exception: # noqa: BLE001
|
||||
update_result = False
|
||||
if update_result:
|
||||
yield {
|
||||
"event": "quotes_updated",
|
||||
"data": json.dumps({
|
||||
"ts": int(time.time() * 1000),
|
||||
"symbol_count": qs._symbol_count if qs else 0,
|
||||
}),
|
||||
}
|
||||
|
||||
# 推送五档修正完成 (depth 信号触发) — 前端刷新连板梯队封单数据
|
||||
if tasks["depth"] in done:
|
||||
try:
|
||||
depth_result = tasks["depth"].result()
|
||||
except Exception: # noqa: BLE001
|
||||
depth_result = False
|
||||
if depth_result:
|
||||
yield {
|
||||
"event": "depth_updated",
|
||||
"data": json.dumps({
|
||||
"ts": int(time.time() * 1000),
|
||||
}),
|
||||
}
|
||||
|
||||
return EventSourceResponse(event_generator())
|
||||
|
||||
|
||||
@router.post("/refresh")
|
||||
def refresh_quotes(request: Request):
|
||||
"""手动刷新一次行情数据。"""
|
||||
qs = _get_quote_service(request)
|
||||
if qs:
|
||||
return qs.refresh()
|
||||
return {"error": "QuoteService not available"}
|
||||
@@ -0,0 +1,822 @@
|
||||
"""K 线 / 同步 API。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import date, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, Request
|
||||
|
||||
from app.indicators.pipeline import compute_enriched, compute_enriched_single
|
||||
from app.services import kline_sync
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/kline", tags=["kline"])
|
||||
|
||||
|
||||
@router.get("/instruments/search")
|
||||
def search_instruments(
|
||||
request: Request,
|
||||
q: str = Query("", min_length=0, max_length=50, description="搜索关键词"),
|
||||
limit: int = Query(20, ge=1, le=50),
|
||||
):
|
||||
"""模糊搜索标的 (代码 / 名称)。从内存 instruments 缓存中查。"""
|
||||
repo = request.app.state.repo
|
||||
df = repo.get_instruments()
|
||||
if df.is_empty() or not q.strip():
|
||||
return {"results": []}
|
||||
|
||||
keyword = q.strip().upper()
|
||||
import polars as pl
|
||||
|
||||
# code/symbol 前缀优先,再 name 包含匹配
|
||||
prefix_mask = (
|
||||
pl.col("code").str.starts_with(keyword)
|
||||
| pl.col("symbol").str.to_uppercase().str.starts_with(keyword)
|
||||
)
|
||||
contains_mask = (
|
||||
pl.col("code").str.contains(keyword, literal=True)
|
||||
| pl.col("symbol").str.to_uppercase().str.contains(keyword, literal=True)
|
||||
| pl.col("name").str.contains(keyword, literal=True)
|
||||
)
|
||||
|
||||
# 前缀匹配优先,剩余名额用包含匹配补充
|
||||
prefix_hits = df.filter(prefix_mask).head(limit)
|
||||
if prefix_hits.height >= limit:
|
||||
matched = prefix_hits
|
||||
else:
|
||||
remaining = limit - prefix_hits.height
|
||||
# 排除已匹配的 symbol
|
||||
prefix_symbols = set(prefix_hits["symbol"].to_list()) if not prefix_hits.is_empty() else set()
|
||||
contain_hits = df.filter(contains_mask & ~pl.col("symbol").is_in(prefix_symbols)).head(remaining)
|
||||
matched = pl.concat([prefix_hits, contain_hits]) if not prefix_hits.is_empty() else contain_hits
|
||||
rows = matched.select(["symbol", "name", "code"]).to_dicts()
|
||||
return {"results": rows}
|
||||
|
||||
|
||||
@router.post("/instruments/names")
|
||||
def instruments_names(request: Request, symbols: list[str]):
|
||||
"""批量查股票名称。传入 symbol 列表, 返回 {symbol: name}。"""
|
||||
if not symbols:
|
||||
return {"names": {}}
|
||||
repo = request.app.state.repo
|
||||
df = repo.get_instruments()
|
||||
if df.is_empty():
|
||||
return {"names": {}}
|
||||
import polars as pl
|
||||
matched = df.filter(pl.col("symbol").is_in(symbols)).select(["symbol", "name"])
|
||||
names = {row["symbol"]: row["name"] for row in matched.iter_rows(named=True)}
|
||||
return {"names": names}
|
||||
|
||||
|
||||
def _get_stock_info(repo, symbol: str) -> dict:
|
||||
"""从 instruments 视图查标的名称 + 股本。"""
|
||||
try:
|
||||
row = repo.execute_one(
|
||||
"SELECT name, total_shares, float_shares FROM instruments WHERE symbol = ? LIMIT 1",
|
||||
[symbol],
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
if not row:
|
||||
return {}
|
||||
return {
|
||||
"name": row[0],
|
||||
"total_shares": row[1],
|
||||
"float_shares": row[2],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/daily")
|
||||
def get_daily(
|
||||
request: Request,
|
||||
symbol: str = Query(..., description="标的代码,如 000001.SZ"),
|
||||
days: int = Query(120, ge=10, le=2000),
|
||||
start_date: Optional[str] = Query(None, description="起始日期 YYYY-MM-DD, 优先于 days"),
|
||||
end_date: Optional[str] = Query(None, description="截止日期 YYYY-MM-DD, 默认今天"),
|
||||
ext_columns: Optional[str] = Query(None, description="逗号分隔的 ext 列: config_id.field_name"),
|
||||
):
|
||||
"""读取本地 enriched 表中某只股票的日 K。
|
||||
|
||||
- 若 QuoteService 有实时行情, 追加/覆盖今日实时蜡烛
|
||||
- Free 用户: 若 enriched 表里没有该股票, 实时拉取 + 本地算 enriched 返回
|
||||
- ext_columns: 可选,动态 LEFT JOIN 扩展数据表,结果平铺到 stock_info.ext 下
|
||||
(key 为 "{config_id}__{field_name}"),供日K信息条等场景展示自定义字段
|
||||
"""
|
||||
import polars as pl
|
||||
|
||||
repo = request.app.state.repo
|
||||
end = date.fromisoformat(end_date) if end_date else date.today()
|
||||
if start_date:
|
||||
start = date.fromisoformat(start_date)
|
||||
else:
|
||||
start = end - timedelta(days=days)
|
||||
|
||||
stock_info = _get_stock_info(repo, symbol)
|
||||
stock_name = stock_info.get("name")
|
||||
|
||||
# 从 enriched 表读取 (已含前复权 OHLCV + 技术指标 + 信号)
|
||||
df = repo.get_daily(symbol, start, end)
|
||||
|
||||
if df.is_empty():
|
||||
try:
|
||||
raw = kline_sync.sync_daily_batch([symbol], count=days + 30)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=502, detail=f"TickFlow fetch failed: {e}") from e
|
||||
if raw.is_empty():
|
||||
return {"symbol": symbol, "name": stock_name, "stock_info": stock_info, "rows": []}
|
||||
# 拉除权因子做前复权 (Starter+ 有权限), 否则空 df → compute_enriched 退回未复权
|
||||
factors = pl.DataFrame()
|
||||
capset = getattr(request.app.state, "capabilities", None)
|
||||
try:
|
||||
from app.tickflow.capabilities import Cap
|
||||
if capset and capset.has(Cap.ADJ_FACTOR):
|
||||
factors = kline_sync.fetch_adj_factor_single(symbol)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("单股除权因子拉取失败 %s: %s", symbol, e)
|
||||
enriched = compute_enriched(raw, factors=factors)
|
||||
rows = enriched.tail(days).to_dicts()
|
||||
# 即使 live 模式也尝试追加实时蜡烛
|
||||
rows = _maybe_inject_live_candle(request, symbol, rows)
|
||||
resp = {"symbol": symbol, "name": stock_name, "stock_info": stock_info, "rows": rows, "source": "live"}
|
||||
return _attach_ext(resp, repo, symbol, ext_columns)
|
||||
|
||||
rows = df.to_dicts()
|
||||
|
||||
# 追加/覆盖今日实时蜡烛
|
||||
rows = _maybe_inject_live_candle(request, symbol, rows)
|
||||
|
||||
resp = {"symbol": symbol, "name": stock_name, "stock_info": stock_info, "rows": rows, "source": "enriched"}
|
||||
return _attach_ext(resp, repo, symbol, ext_columns)
|
||||
|
||||
|
||||
def _attach_ext(resp: dict, repo, symbol: str, ext_columns: Optional[str]) -> dict:
|
||||
"""按 ext_columns 规格为单只股票 LEFT JOIN 扩展数据,平铺到 stock_info['ext']。
|
||||
|
||||
key 形如 "{config_id}__{field_name}",与自选列表 enriched 接口保持一致。
|
||||
JOIN 逻辑参考 watchlist.watchlist_enriched;任何 ext 表/字段缺失都静默跳过。
|
||||
"""
|
||||
if not ext_columns or not ext_columns.strip():
|
||||
return resp
|
||||
|
||||
specs: list[tuple[str, str]] = []
|
||||
for part in ext_columns.split(","):
|
||||
part = part.strip()
|
||||
if "." not in part:
|
||||
continue
|
||||
config_id, field_name = part.split(".", 1)
|
||||
config_id, field_name = config_id.strip(), field_name.strip()
|
||||
if config_id and field_name:
|
||||
specs.append((config_id, field_name))
|
||||
if not specs:
|
||||
return resp
|
||||
|
||||
import polars as pl
|
||||
data_dir = repo.store.data_dir
|
||||
try:
|
||||
from app.services.ext_data import ExtConfigStore
|
||||
from app.api.ext_data import _read_ext_dataframe
|
||||
ext_store = ExtConfigStore(data_dir)
|
||||
configs = {c.id: c for c in ext_store.load_all()}
|
||||
except Exception: # noqa: BLE001
|
||||
configs = {}
|
||||
|
||||
ext_values: dict = {}
|
||||
for config_id, field_name in specs:
|
||||
ext_col_name = f"{config_id}__{field_name}"
|
||||
value = None
|
||||
try:
|
||||
cfg = configs.get(config_id)
|
||||
if cfg:
|
||||
ext_df, _ = _read_ext_dataframe(cfg, data_dir)
|
||||
else:
|
||||
ext_df = pl.from_arrow(
|
||||
repo.store.db.query(
|
||||
f'SELECT symbol, "{field_name}" FROM ext_{config_id}'
|
||||
).arrow()
|
||||
)
|
||||
if not ext_df.is_empty() and "symbol" in ext_df.columns and field_name in ext_df.columns:
|
||||
# 时序表取最新分区,避免一个 symbol 多行
|
||||
row = (
|
||||
ext_df
|
||||
.select(["symbol", field_name])
|
||||
.unique(subset=["symbol"], keep="last")
|
||||
.filter(pl.col("symbol") == symbol)
|
||||
)
|
||||
if not row.is_empty():
|
||||
value = row[field_name][0]
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("kline ext join failed for %s.%s: %s", config_id, field_name, e)
|
||||
ext_values[ext_col_name] = value
|
||||
|
||||
stock_info = dict(resp.get("stock_info") or {})
|
||||
stock_info["ext"] = ext_values
|
||||
resp["stock_info"] = stock_info
|
||||
return resp
|
||||
|
||||
|
||||
def _maybe_inject_live_candle(request: Request, symbol: str, rows: list[dict]) -> list[dict]:
|
||||
"""如果 QuoteService 有实时 enriched 数据, 用实时数据生成今日蜡烛并追加/覆盖。"""
|
||||
qs = getattr(request.app.state, "quote_service", None)
|
||||
if not qs:
|
||||
return rows
|
||||
|
||||
df_today, enriched_date = qs.get_enriched_today()
|
||||
if df_today.is_empty():
|
||||
return rows
|
||||
|
||||
# 非交易日(周末/假日)缓存的行情日期 != 今天,跳过注入避免产生重复蜡烛
|
||||
if not enriched_date or enriched_date != date.today():
|
||||
return rows
|
||||
|
||||
# 查找该 symbol 的实时 enriched 行
|
||||
import polars as pl
|
||||
try:
|
||||
q = df_today.filter(pl.col("symbol") == symbol).to_dicts()
|
||||
if not q:
|
||||
return rows
|
||||
q = q[0]
|
||||
except Exception: # noqa: BLE001
|
||||
return rows
|
||||
|
||||
close_price = q.get("close")
|
||||
if not close_price or close_price <= 0:
|
||||
return rows
|
||||
|
||||
today_str = str(enriched_date)
|
||||
|
||||
# enriched 行已包含 OHLCV + 全套指标, 直接用它
|
||||
# 修复: API 在非交易时段可能返回 open/high/low=0, 用 close 填充避免异常蜡烛
|
||||
raw_open = q.get("open")
|
||||
raw_high = q.get("high")
|
||||
raw_low = q.get("low")
|
||||
live_row: dict = {
|
||||
"date": today_str,
|
||||
"symbol": symbol,
|
||||
"open": raw_open if raw_open and raw_open > 0 else close_price,
|
||||
"high": raw_high if raw_high and raw_high > 0 else close_price,
|
||||
"low": raw_low if raw_low and raw_low > 0 else close_price,
|
||||
"close": close_price,
|
||||
"volume": q.get("volume"),
|
||||
"amount": q.get("amount"),
|
||||
"change_pct": q.get("change_pct"),
|
||||
"is_live": True,
|
||||
}
|
||||
# 补上 enriched 的技术指标字段
|
||||
for key in ("ma5", "ma10", "ma20", "ma30", "ma60",
|
||||
"macd_dif", "macd_dea", "macd_hist",
|
||||
"kdj_k", "kdj_d", "kdj_j",
|
||||
"boll_upper", "boll_lower",
|
||||
"rsi_6", "rsi_14", "rsi_24",
|
||||
"atr_14", "vol_ratio_5d"):
|
||||
if key in q and q[key] is not None:
|
||||
live_row[key] = q[key]
|
||||
|
||||
# 如果已有今天的 enriched 行, 覆盖; 否则追加
|
||||
found = False
|
||||
for i, r in enumerate(rows):
|
||||
if str(r.get("date")) == today_str:
|
||||
r.update(live_row)
|
||||
found = True
|
||||
break
|
||||
|
||||
if not found:
|
||||
rows.append(live_row)
|
||||
|
||||
return rows
|
||||
|
||||
|
||||
class DailyBatchRequest:
|
||||
"""批量日K请求。"""
|
||||
symbols: list[str]
|
||||
days: int = 12
|
||||
|
||||
|
||||
@router.post("/daily-batch")
|
||||
def get_daily_batch(request: Request, body: dict):
|
||||
"""批量获取多只股票最近 N 天日K (OHLCV)。
|
||||
|
||||
用于自选列表迷你蜡烛图等场景,只返回基础列,不返回全部 enriched 指标。
|
||||
"""
|
||||
symbols = body.get("symbols", [])
|
||||
days = body.get("days", 12)
|
||||
if not symbols:
|
||||
return {"data": {}}
|
||||
days = max(5, min(60, days))
|
||||
|
||||
repo = request.app.state.repo
|
||||
import polars as pl
|
||||
from datetime import date, timedelta
|
||||
|
||||
end = date.today()
|
||||
start = end - timedelta(days=days * 2) # 多取一些确保交易日够
|
||||
|
||||
cols = ["symbol", "date", "open", "high", "low", "close", "volume"]
|
||||
df = repo.get_daily_batch(symbols, start, end, columns=cols)
|
||||
|
||||
if df.is_empty():
|
||||
return {"data": {}}
|
||||
|
||||
# 按 symbol 分组, 每只取最近 N 条
|
||||
result: dict[str, list[dict]] = {}
|
||||
for sym in symbols:
|
||||
sub = df.filter(pl.col("symbol") == sym).sort("date").tail(days)
|
||||
if not sub.is_empty():
|
||||
result[sym] = sub.to_dicts()
|
||||
|
||||
return {"data": result}
|
||||
|
||||
|
||||
@router.get("/minute")
|
||||
def get_minute(
|
||||
request: Request,
|
||||
symbol: str = Query(..., description="标的代码"),
|
||||
trade_date: date | None = Query(None, alias="date", description="交易日期, 默认最新"),
|
||||
):
|
||||
"""读取某只股票某天的分钟 K 线。
|
||||
|
||||
- 本地有完整数据(240条) → 直接返回
|
||||
- 本地无数据或不完整 → 从 TickFlow 实时拉取返回(不写入)
|
||||
"""
|
||||
repo = request.app.state.repo
|
||||
stock_info = _get_stock_info(repo, symbol)
|
||||
stock_name = stock_info.get("name")
|
||||
|
||||
if trade_date is None:
|
||||
trade_date = repo.latest_minute_date(symbol)
|
||||
if trade_date is None:
|
||||
# 本地无任何分钟K,尝试从 TickFlow 拉取当天
|
||||
trade_date = date.today()
|
||||
df = kline_sync.fetch_minute_single(symbol, trade_date)
|
||||
return {
|
||||
"symbol": symbol, "name": stock_name, "stock_info": stock_info,
|
||||
"date": str(trade_date), "rows": df.to_dicts(), "source": "live",
|
||||
}
|
||||
|
||||
df = repo.get_minute(symbol, trade_date)
|
||||
|
||||
# 完整交易日应有 240 条分钟K;如果是今天(盘中),期望条数按已交易分钟估算
|
||||
expected = 240
|
||||
today = date.today()
|
||||
if trade_date == today:
|
||||
from datetime import datetime as _dt
|
||||
now = _dt.now()
|
||||
h, m = now.hour, now.minute
|
||||
if h < 9 or (h == 9 and m < 30):
|
||||
expected = 0 # 还没开盘
|
||||
elif h < 12 or (h == 12 and m == 0):
|
||||
expected = (h - 9) * 60 + m - 30 # 9:30 起
|
||||
elif h < 13:
|
||||
expected = 120 # 午休
|
||||
elif h < 15:
|
||||
expected = 120 + (h - 13) * 60 + m
|
||||
else:
|
||||
expected = 240
|
||||
|
||||
is_complete = not df.is_empty() and len(df) >= expected * 0.9 # 允许 10% 容差
|
||||
|
||||
if is_complete:
|
||||
return {
|
||||
"symbol": symbol, "name": stock_name, "stock_info": stock_info,
|
||||
"date": str(trade_date), "rows": df.to_dicts(), "source": "local",
|
||||
}
|
||||
|
||||
# 本地不完整或无数据 → 从 TickFlow 实时拉取
|
||||
live_df = kline_sync.fetch_minute_single(symbol, trade_date)
|
||||
return {
|
||||
"symbol": symbol, "name": stock_name, "stock_info": stock_info,
|
||||
"date": str(trade_date), "rows": live_df.to_dicts(),
|
||||
"source": "live" if not live_df.is_empty() else "none",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/sync")
|
||||
def sync_symbol(
|
||||
request: Request,
|
||||
symbol: str = Query(...),
|
||||
days: int = Query(250, ge=10, le=2000),
|
||||
):
|
||||
"""手动触发单股同步(Free 用户在 K 线页用)。"""
|
||||
repo = request.app.state.repo
|
||||
capset = request.app.state.capabilities
|
||||
n = kline_sync.sync_and_persist_daily_batch([symbol], repo, capset, count=days)
|
||||
return {"symbol": symbol, "rows_written": n}
|
||||
|
||||
|
||||
@router.post("/sync_batch")
|
||||
def sync_batch(
|
||||
request: Request,
|
||||
symbols: list[str],
|
||||
days: int = Query(250, ge=10, le=2000),
|
||||
):
|
||||
repo = request.app.state.repo
|
||||
capset = request.app.state.capabilities
|
||||
n = kline_sync.sync_and_persist_daily_batch(symbols, repo, capset, count=days)
|
||||
return {"symbols": symbols, "rows_written": n}
|
||||
|
||||
|
||||
@router.post("/refresh_views")
|
||||
def refresh_views(request: Request):
|
||||
"""刷新所有 DuckDB 视图(解决视图状态不一致问题)。"""
|
||||
from app.jobs.daily_pipeline import _refresh_views
|
||||
repo = request.app.state.repo
|
||||
_refresh_views(repo)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/sync_minute")
|
||||
async def sync_minute(request: Request):
|
||||
"""手动触发分钟 K 同步(全市场)。返回 pipeline job_id 可轮询进度。"""
|
||||
import asyncio
|
||||
|
||||
from app.services.pipeline_jobs import job_store
|
||||
from app.api.data import invalidate_storage_cache
|
||||
from app.services.preferences import get_minute_sync_days
|
||||
from app.tickflow.capabilities import Cap
|
||||
from app.tickflow.pools import get_pool
|
||||
|
||||
repo = request.app.state.repo
|
||||
capset = request.app.state.capabilities
|
||||
|
||||
if not capset.has(Cap.KLINE_MINUTE_BATCH):
|
||||
raise HTTPException(status_code=403, detail="需要 Pro+ 权限")
|
||||
|
||||
job_id = job_store.create()
|
||||
existing = job_store.get(job_id)
|
||||
if existing and existing["status"] == "running":
|
||||
return {"status": "reused", "job_id": job_id}
|
||||
|
||||
async def task() -> None:
|
||||
job_store.start(job_id)
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
def progress(stage: str, pct: int, msg: str) -> None:
|
||||
job_store.progress(job_id, stage, pct, msg)
|
||||
|
||||
try:
|
||||
progress("sync_minute", 5, "解析标的池…")
|
||||
universe = sorted(set(get_pool("watchlist")) | set(get_pool("CN_Equity_A")))
|
||||
# 补充 instruments 全量标的,覆盖北交所、新股等
|
||||
inst_path = repo.store.data_dir / "instruments" / "instruments.parquet"
|
||||
if inst_path.exists():
|
||||
try:
|
||||
import polars as pl
|
||||
inst = pl.read_parquet(inst_path, columns=["symbol"])
|
||||
universe = sorted(set(universe) | set(inst["symbol"].to_list()))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
progress("sync_minute", 10, f"标的池 {len(universe)} 只")
|
||||
|
||||
days = get_minute_sync_days()
|
||||
|
||||
def _run():
|
||||
return kline_sync.sync_and_persist_minute(universe, repo, capset, days=days)
|
||||
|
||||
written = await loop.run_in_executor(_long_task_executor, _run)
|
||||
|
||||
# 刷新视图
|
||||
from app.jobs.daily_pipeline import _refresh_single_view
|
||||
_refresh_single_view(repo, "kline_minute")
|
||||
|
||||
progress("done", 100, f"分钟 K 同步完成,{written} 行")
|
||||
job_store.succeed(job_id, {"minute_rows": written, "universe_size": len(universe)})
|
||||
invalidate_storage_cache()
|
||||
except Exception as e: # noqa: BLE001
|
||||
job_store.fail(job_id, str(e))
|
||||
invalidate_storage_cache()
|
||||
|
||||
asyncio.create_task(task())
|
||||
return {"status": "started", "job_id": job_id}
|
||||
|
||||
|
||||
@router.post("/extend_history")
|
||||
async def extend_history(request: Request):
|
||||
"""向前扩展历史日K数据 — 独立于盘后管道。
|
||||
|
||||
body: { "value": int, "unit": "day"|"month"|"year" }
|
||||
返回 job_id,可轮询 /api/pipeline/jobs 查看进度。
|
||||
"""
|
||||
import asyncio
|
||||
import traceback as _tb
|
||||
try:
|
||||
body = await request.json()
|
||||
value = body.get("value")
|
||||
unit = body.get("unit", "month")
|
||||
if not value or value <= 0:
|
||||
raise HTTPException(status_code=400, detail="value 必须为正整数")
|
||||
if unit not in ("day", "month", "year"):
|
||||
raise HTTPException(status_code=400, detail="unit 只支持 day/month/year")
|
||||
|
||||
repo = request.app.state.repo
|
||||
capset = request.app.state.capabilities
|
||||
|
||||
from app.tickflow.capabilities import Cap
|
||||
if not capset.has(Cap.KLINE_DAILY_BATCH):
|
||||
raise HTTPException(status_code=403, detail="需要 Pro+ 权限 (batch K-line)")
|
||||
|
||||
from app.services.extend_history import run_extend_history
|
||||
from app.services.pipeline_jobs import job_store
|
||||
from app.api.data import invalidate_storage_cache
|
||||
|
||||
job_id = job_store.create()
|
||||
existing = job_store.get(job_id)
|
||||
if existing and existing["status"] == "running":
|
||||
return {"status": "reused", "job_id": job_id}
|
||||
|
||||
async def task() -> None:
|
||||
job_store.start(job_id)
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
def progress(stage: str, pct: int, msg: str,
|
||||
stage_pct: int | None = None, skip_log: bool = False) -> None:
|
||||
job_store.progress(job_id, stage, pct, msg,
|
||||
stage_pct=stage_pct, skip_log=skip_log)
|
||||
|
||||
try:
|
||||
result = await loop.run_in_executor(
|
||||
_long_task_executor,
|
||||
lambda: run_extend_history(repo, capset, value, unit, on_progress=progress),
|
||||
)
|
||||
if "error" in result:
|
||||
job_store.fail(job_id, result["error"])
|
||||
else:
|
||||
job_store.succeed(job_id, result)
|
||||
invalidate_storage_cache()
|
||||
except Exception as e:
|
||||
logger.exception("extend_history failed: job_id=%s", job_id)
|
||||
job_store.fail(job_id, str(e))
|
||||
invalidate_storage_cache()
|
||||
|
||||
asyncio.create_task(task())
|
||||
return {"status": "started", "job_id": job_id}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error("extend_history error: %s\n%s", e, _tb.format_exc())
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
||||
@router.post("/rebuild_enriched")
|
||||
async def rebuild_enriched(request: Request):
|
||||
"""全量重算 enriched 表 — 不获取任何数据,仅基于已有 kline_daily + adj_factor 重算复权+指标。
|
||||
|
||||
返回 job_id,可轮询 /api/pipeline/jobs 查看进度。
|
||||
"""
|
||||
import asyncio
|
||||
try:
|
||||
repo = request.app.state.repo
|
||||
|
||||
from app.services.pipeline_jobs import job_store
|
||||
from app.api.data import invalidate_storage_cache
|
||||
|
||||
job_id = job_store.create()
|
||||
existing = job_store.get(job_id)
|
||||
if existing and existing["status"] == "running":
|
||||
return {"status": "reused", "job_id": job_id}
|
||||
|
||||
async def task() -> None:
|
||||
job_store.start(job_id)
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
def progress(stage: str, pct: int, msg: str,
|
||||
stage_pct: int | None = None, skip_log: bool = False) -> None:
|
||||
job_store.progress(job_id, stage, pct, msg,
|
||||
stage_pct=stage_pct, skip_log=skip_log)
|
||||
|
||||
try:
|
||||
progress("rebuild_enriched", 10, "全量计算 enriched…")
|
||||
from app.indicators.pipeline import run_pipeline
|
||||
|
||||
def _batch_progress(cur: int, tot: int) -> None:
|
||||
pct = 10 + int(85 * cur / tot)
|
||||
progress("rebuild_enriched", pct,
|
||||
f"计算指标 批次 {cur}/{tot}",
|
||||
stage_pct=int(100 * cur / tot), skip_log=True)
|
||||
|
||||
written = await loop.run_in_executor(
|
||||
_long_task_executor,
|
||||
lambda: run_pipeline(on_batch_done=_batch_progress),
|
||||
)
|
||||
|
||||
enriched_dir = repo.store.data_dir / "kline_daily_enriched"
|
||||
enriched_days = len(list(enriched_dir.glob("date=*"))) if enriched_dir.exists() else 0
|
||||
|
||||
# 刷新视图
|
||||
d = repo.store.data_dir.as_posix()
|
||||
for view_name, glob in [
|
||||
("kline_enriched", f"{d}/kline_daily_enriched/**/*.parquet"),
|
||||
]:
|
||||
try:
|
||||
repo.db.execute(
|
||||
f"CREATE OR REPLACE VIEW {view_name} AS "
|
||||
f"SELECT * FROM read_parquet('{glob}', union_by_name=true)"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
progress("rebuild_enriched", 100, f"完成,覆盖 {enriched_days} 天")
|
||||
job_store.succeed(job_id, {
|
||||
"enriched_days": enriched_days,
|
||||
"enriched_rows": written,
|
||||
})
|
||||
invalidate_storage_cache()
|
||||
except Exception as e:
|
||||
logger.exception("rebuild_enriched failed: job_id=%s", job_id)
|
||||
job_store.fail(job_id, str(e))
|
||||
invalidate_storage_cache()
|
||||
|
||||
asyncio.create_task(task())
|
||||
return {"status": "started", "job_id": job_id}
|
||||
except Exception as e:
|
||||
import traceback as _tb
|
||||
logger.error("rebuild_enriched error: %s\n%s", e, _tb.format_exc())
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
||||
# 长时间任务专用线程池(隔离于 FastAPI 默认线程池,防止阻塞请求处理)
|
||||
import concurrent.futures as _cf
|
||||
_long_task_executor = _cf.ThreadPoolExecutor(max_workers=2, thread_name_prefix="long-task")
|
||||
|
||||
|
||||
@router.post("/extend_minute_history")
|
||||
async def extend_minute_history(request: Request):
|
||||
"""向前扩展分钟K历史数据 — 仅拉数据,不做任何后续处理。
|
||||
|
||||
body: { "value": int, "unit": "day"|"month" }
|
||||
- day 单位:1~15 天(所有有分钟K权限的套餐可用)
|
||||
- month 单位:1~6 月(每月按 30 天计,即最多 180 天)—— 仅 Expert+ 可用
|
||||
返回 job_id,可轮询 /api/pipeline/jobs 查看进度。
|
||||
"""
|
||||
import asyncio
|
||||
import traceback as _tb
|
||||
try:
|
||||
body = await request.json()
|
||||
value = body.get("value")
|
||||
unit = body.get("unit", "day")
|
||||
if not value or value <= 0:
|
||||
raise HTTPException(status_code=400, detail="value 必须为正整数")
|
||||
if unit not in ("day", "month"):
|
||||
raise HTTPException(status_code=400, detail="unit 只支持 day/month")
|
||||
|
||||
repo = request.app.state.repo
|
||||
capset = request.app.state.capabilities
|
||||
|
||||
from app.tickflow.capabilities import Cap
|
||||
if not capset.has(Cap.KLINE_MINUTE_BATCH):
|
||||
raise HTTPException(status_code=403, detail="需要 Pro+ 权限 (batch minute K-line)")
|
||||
|
||||
# month 单位(按月扩展更长的分钟K历史)仅 Expert+ 开放;Pro 仅可用 day
|
||||
if unit == "month":
|
||||
from app.tickflow.policy import tier_label
|
||||
base_tier = tier_label().split()[0].split("+")[0].strip().lower()
|
||||
if base_tier != "expert":
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="按月扩展分钟K历史需要 Expert 及以上套餐",
|
||||
)
|
||||
|
||||
# 计算天数上限:day 最多 15 天;month 最多 6 月(180 天)
|
||||
from datetime import timedelta
|
||||
if unit == "month":
|
||||
total_days = min(value * 30, 180)
|
||||
else:
|
||||
total_days = min(value, 15)
|
||||
|
||||
if total_days <= 0:
|
||||
raise HTTPException(status_code=400, detail="扩展范围无效")
|
||||
|
||||
from app.services.pipeline_jobs import job_store
|
||||
from app.api.data import invalidate_storage_cache
|
||||
|
||||
job_id = job_store.create()
|
||||
existing = job_store.get(job_id)
|
||||
if existing and existing["status"] == "running":
|
||||
return {"status": "reused", "job_id": job_id}
|
||||
|
||||
async def task() -> None:
|
||||
job_store.start(job_id)
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
def progress(stage: str, pct: int, msg: str,
|
||||
stage_pct: int | None = None, skip_log: bool = False) -> None:
|
||||
job_store.progress(job_id, stage, pct, msg,
|
||||
stage_pct=stage_pct, skip_log=skip_log)
|
||||
|
||||
try:
|
||||
# 获取当前最早日期
|
||||
earliest = repo.earliest_minute_date()
|
||||
if not earliest:
|
||||
# 本地无分钟K数据 → 以今天为基准往前获取
|
||||
from datetime import date as _date
|
||||
latest = _date.today()
|
||||
else:
|
||||
latest = earliest
|
||||
|
||||
new_start = latest - timedelta(days=total_days)
|
||||
if new_start >= latest:
|
||||
job_store.fail(job_id, "扩展范围无效")
|
||||
invalidate_storage_cache()
|
||||
return
|
||||
|
||||
start_str = new_start.strftime("%Y-%m-%d")
|
||||
end_str = latest.strftime("%Y-%m-%d")
|
||||
|
||||
progress("extend_minute", 5, "解析标的池…")
|
||||
universe = _resolve_minute_universe(capset, repo)
|
||||
progress("extend_minute", 8, f"标的池: {len(universe)} 只")
|
||||
|
||||
from app.tickflow.capabilities import Cap
|
||||
|
||||
lim = capset.limits(Cap.KLINE_MINUTE_BATCH)
|
||||
batch_size = lim.batch if lim and lim.batch else 100
|
||||
rpm = lim.rpm if lim else 30
|
||||
|
||||
def _run():
|
||||
"""全部在 executor 线程里完成,避免阻塞事件循环。"""
|
||||
from app.services.kline_sync import sync_minute_batch
|
||||
from datetime import datetime as _dt
|
||||
|
||||
def _chunk(cur: int, tot: int) -> None:
|
||||
progress("extend_minute", 8 + int(85 * cur / tot),
|
||||
f"分钟K 批次 {cur}/{tot}", stage_pct=int(100 * cur / tot), skip_log=True)
|
||||
|
||||
df = sync_minute_batch(
|
||||
universe,
|
||||
start_time=_dt.combine(new_start, _dt.min.time()),
|
||||
end_time=_dt.combine(latest, _dt.min.time()),
|
||||
batch_size=batch_size, rpm=rpm,
|
||||
on_chunk_done=_chunk,
|
||||
)
|
||||
|
||||
written = 0
|
||||
day_count = 0
|
||||
if not df.is_empty():
|
||||
import polars as pl
|
||||
df = df.with_columns(pl.col("datetime").dt.date().alias("_trade_date"))
|
||||
for day_df in df.partition_by("_trade_date"):
|
||||
trade_date = day_df["_trade_date"][0]
|
||||
out = repo.store.data_dir / "kline_minute" / f"date={trade_date}" / "part.parquet"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
if out.exists():
|
||||
existing_df = pl.read_parquet(out)
|
||||
if "datetime" in existing_df.columns:
|
||||
existing_df = existing_df.filter(pl.col("datetime").is_not_null())
|
||||
day_df = pl.concat([existing_df, day_df.drop("_trade_date")]).unique(
|
||||
subset=["symbol", "datetime"], keep="last",
|
||||
)
|
||||
else:
|
||||
day_df = day_df.drop("_trade_date")
|
||||
day_df = day_df.sort("symbol", "datetime")
|
||||
day_df.write_parquet(out)
|
||||
written += day_df.height
|
||||
day_count += 1
|
||||
|
||||
# 刷新视图
|
||||
d = repo.store.data_dir.as_posix()
|
||||
try:
|
||||
repo.db.execute(
|
||||
f"CREATE OR REPLACE VIEW kline_minute AS "
|
||||
f"SELECT * FROM read_parquet('{d}/kline_minute/**/*.parquet', union_by_name=true)"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return written, day_count
|
||||
|
||||
progress("extend_minute", 10, f"获取分钟K [{start_str} ~ {end_str}]…")
|
||||
written, day_count = await loop.run_in_executor(_long_task_executor, _run)
|
||||
|
||||
progress("extend_minute", 95, f"分钟K 完成,{day_count} 天")
|
||||
job_store.succeed(job_id, {
|
||||
"minute_days": day_count,
|
||||
"universe_size": len(universe),
|
||||
"earliest_before": (earliest or latest).isoformat(),
|
||||
"earliest_after": new_start.isoformat(),
|
||||
})
|
||||
invalidate_storage_cache()
|
||||
except Exception as e:
|
||||
logger.exception("extend_minute_history failed: job_id=%s", job_id)
|
||||
job_store.fail(job_id, str(e))
|
||||
invalidate_storage_cache()
|
||||
|
||||
asyncio.create_task(task())
|
||||
return {"status": "started", "job_id": job_id}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error("extend_minute_history error: %s\n%s", e, _tb.format_exc())
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
||||
def _resolve_minute_universe(capset, repo) -> list[str]:
|
||||
"""分钟K标的池解析。"""
|
||||
from app.tickflow.capabilities import Cap
|
||||
if capset.has(Cap.KLINE_MINUTE_BATCH):
|
||||
try:
|
||||
from app.tickflow.pools import get_pool
|
||||
all_a = get_pool("CN_Equity_A", refresh=True)
|
||||
if all_a:
|
||||
return sorted(all_a)
|
||||
except Exception:
|
||||
pass
|
||||
return []
|
||||
@@ -0,0 +1,115 @@
|
||||
"""AI 大盘复盘 API — 流式复盘 + 报告持久化。
|
||||
|
||||
路由前缀: /api/market-recap
|
||||
|
||||
端点:
|
||||
POST /analyze AI 流式大盘复盘(NDJSON)
|
||||
GET /reports 历史复盘列表
|
||||
POST /reports 保存一条复盘报告
|
||||
DELETE /reports/{report_id} 删除一条复盘报告
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.services import market_recap_reports
|
||||
from app.services.market_recap import recap_market_stream
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/market-recap", tags=["market-recap"])
|
||||
|
||||
|
||||
class AnalyzeRequest(BaseModel):
|
||||
"""AI 大盘复盘请求。"""
|
||||
as_of: str | None = None # 可选:复盘日期(YYYY-MM-DD),缺省取最新有数据日
|
||||
focus: str = "" # 可选:用户追加的复盘关注点
|
||||
|
||||
|
||||
@router.post("/analyze")
|
||||
async def analyze_market(request: Request, req: AnalyzeRequest):
|
||||
"""AI 大盘复盘 — NDJSON 流式返回。
|
||||
|
||||
装配市场总览(指数/涨跌/连板/封板/板块/情绪雷达)→ 复盘提示词 →
|
||||
流式调用 LLM → 逐 chunk 以 NDJSON 推给前端(每行一个 JSON)。
|
||||
|
||||
协议:
|
||||
{"type":"meta","as_of","emotion_score","emotion_label","summary"}
|
||||
{"type":"delta","content":"..."}
|
||||
{"type":"error","message":"..."}
|
||||
{"type":"done"}
|
||||
"""
|
||||
from datetime import date as date_cls
|
||||
|
||||
repo = request.app.state.repo
|
||||
quote_service = getattr(request.app.state, "quote_service", None)
|
||||
depth_service = getattr(request.app.state, "depth_service", None)
|
||||
|
||||
as_of = None
|
||||
if req.as_of:
|
||||
try:
|
||||
as_of = date_cls.fromisoformat(req.as_of)
|
||||
except ValueError:
|
||||
raise HTTPException(400, f"as_of 格式应为 YYYY-MM-DD,收到: {req.as_of}")
|
||||
|
||||
async def stream_gen():
|
||||
async for chunk in recap_market_stream(repo, quote_service, depth_service, as_of, req.focus):
|
||||
yield chunk + "\n"
|
||||
|
||||
return StreamingResponse(
|
||||
stream_gen(),
|
||||
media_type="application/x-ndjson",
|
||||
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 报告 CRUD(历史复盘持久化)
|
||||
# ================================================================
|
||||
|
||||
class SaveReportRequest(BaseModel):
|
||||
"""保存一条 AI 大盘复盘报告。"""
|
||||
as_of: str
|
||||
focus: str = ""
|
||||
content: str
|
||||
summary: str = ""
|
||||
emotion_score: int | None = None
|
||||
emotion_label: str = ""
|
||||
|
||||
|
||||
@router.get("/reports")
|
||||
def list_reports(request: Request):
|
||||
"""获取全部历史复盘(按时间降序,后端已裁剪到上限)。"""
|
||||
return {"reports": market_recap_reports.list_reports()}
|
||||
|
||||
|
||||
@router.post("/reports")
|
||||
def save_report(request: Request, req: SaveReportRequest):
|
||||
"""保存一条复盘报告。"""
|
||||
report = market_recap_reports.save_report({
|
||||
"as_of": req.as_of,
|
||||
"focus": req.focus,
|
||||
"content": req.content,
|
||||
"summary": req.summary,
|
||||
"emotion_score": req.emotion_score,
|
||||
"emotion_label": req.emotion_label,
|
||||
})
|
||||
# 推送到飞书(可选): 与定时复盘共用同一开关 review_push_enabled 与 _maybe_push_review。
|
||||
# 内部 try/except 静默降级, 不影响归档返回值。
|
||||
from app.jobs.daily_pipeline import _maybe_push_review
|
||||
_maybe_push_review(req.content, {
|
||||
"as_of": req.as_of,
|
||||
"emotion_label": req.emotion_label,
|
||||
})
|
||||
return {"ok": True, "report": report}
|
||||
|
||||
|
||||
@router.delete("/reports/{report_id}")
|
||||
def delete_report(request: Request, report_id: str):
|
||||
"""删除一条复盘报告。"""
|
||||
ok = market_recap_reports.delete_report(report_id)
|
||||
return {"ok": ok}
|
||||
@@ -0,0 +1,499 @@
|
||||
"""监控规则 API 路由 — HTTP 请求 → 调用 monitor_rules 模块 → 同步引擎内存态。
|
||||
|
||||
只做胶水: 校验 → 持久化 → 失效引擎内存态。不含评估逻辑。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.strategy import monitor_rules
|
||||
|
||||
router = APIRouter(prefix="/api/monitor-rules", tags=["monitor-rules"])
|
||||
|
||||
|
||||
def _data_dir(request: Request) -> Path:
|
||||
return request.app.state.repo.store.data_dir
|
||||
|
||||
|
||||
def _sync_engine(request: Request) -> None:
|
||||
"""保存/删除后,把最新规则集 reload 到引擎内存态。"""
|
||||
engine = getattr(request.app.state, "monitor_engine", None)
|
||||
if engine is not None:
|
||||
rules = monitor_rules.load_all(_data_dir(request))
|
||||
engine.set_rules(rules)
|
||||
|
||||
|
||||
# ── Pydantic 模型 ───────────────────────────────────────
|
||||
class ConditionModel(BaseModel):
|
||||
field: str
|
||||
op: str # truth | > >= < <= == !=
|
||||
value: float | None = None # op 非 truth 时必填
|
||||
|
||||
|
||||
class RuleModel(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
enabled: bool = True
|
||||
type: str # strategy | signal | price | market
|
||||
scope: str = "symbols" # symbols | all | sector
|
||||
symbols: list[str] = []
|
||||
sector: str | None = None
|
||||
strategy_id: str | None = None
|
||||
direction: str = "entry" # entry | exit | both
|
||||
conditions: list[ConditionModel] = []
|
||||
logic: str = "and" # and | or
|
||||
cooldown_seconds: int = 3600
|
||||
severity: str = "info" # info | warn | critical
|
||||
webhook_url: str = "" # Webhook 推送地址 (推送到 QMT 等外部软件, 待定)
|
||||
webhook_enabled: bool = False
|
||||
message: str = ""
|
||||
# ladder 专属 (连板梯队封单监控)
|
||||
metric: str = "sealed_vol" # sealed_vol=封单量(手) | sealed_amount=封单额(元)
|
||||
threshold: float = 0 # 封单 <= 此值时报警 (原始单位: 量=手, 额=元)
|
||||
|
||||
|
||||
# ── 字段选项 ─────────────────────────────────────────────
|
||||
@router.get("/options")
|
||||
def get_options(request: Request):
|
||||
"""返回可选字段、信号列、运算符、枚举,供前端表单使用。"""
|
||||
from app.indicators.pipeline import ENRICHED_COLUMNS
|
||||
from app.strategy.custom_signals import ALLOWED_FIELDS, load_all as load_csg
|
||||
|
||||
# 阈值字段 (带中文标签)
|
||||
threshold_fields = [
|
||||
{"key": f, "label": ENRICHED_COLUMNS.get(f, f)}
|
||||
for f in sorted(ALLOWED_FIELDS)
|
||||
]
|
||||
# 内置信号列 (布尔, 用于 op=truth)
|
||||
builtin_signals = [
|
||||
{"key": k, "label": v}
|
||||
for k, v in ENRICHED_COLUMNS.items()
|
||||
if k.startswith("signal_")
|
||||
]
|
||||
# 自定义信号列 (csg_)
|
||||
custom_sigs = []
|
||||
try:
|
||||
for cs in load_csg(_data_dir(request)):
|
||||
if cs.get("enabled") is not False:
|
||||
custom_sigs.append({
|
||||
"key": f"csg_{cs['id']}",
|
||||
"label": cs.get("name", cs["id"]),
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {
|
||||
"threshold_fields": threshold_fields,
|
||||
"builtin_signals": builtin_signals,
|
||||
"custom_signals": custom_sigs,
|
||||
"operators": [">", ">=", "<", "<=", "==", "!="],
|
||||
"types": [
|
||||
{"key": "signal", "label": "个股信号"},
|
||||
{"key": "price", "label": "价格/涨跌"},
|
||||
{"key": "market", "label": "市场异动"},
|
||||
{"key": "strategy", "label": "策略监控"},
|
||||
],
|
||||
"scopes": [
|
||||
{"key": "symbols", "label": "指定股票"},
|
||||
{"key": "all", "label": "全市场"},
|
||||
{"key": "sector", "label": "板块"},
|
||||
],
|
||||
"logics": [
|
||||
{"key": "and", "label": "全部满足 (AND)"},
|
||||
{"key": "or", "label": "任一满足 (OR)"},
|
||||
],
|
||||
"severities": [
|
||||
{"key": "info", "label": "普通"},
|
||||
{"key": "warn", "label": "警告"},
|
||||
{"key": "critical", "label": "重要"},
|
||||
],
|
||||
"directions": [
|
||||
{"key": "entry", "label": "买入"},
|
||||
{"key": "exit", "label": "卖出"},
|
||||
{"key": "both", "label": "买卖都报"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
# ── 列表 ───────────────────────────────────────────────
|
||||
@router.get("")
|
||||
def list_rules(request: Request):
|
||||
rules = monitor_rules.load_all(_data_dir(request))
|
||||
# 按 created_at 倒序
|
||||
rules.sort(key=lambda r: r.get("created_at", ""), reverse=True)
|
||||
return {"rules": rules}
|
||||
|
||||
|
||||
# ── 新建 / 更新 ────────────────────────────────────────
|
||||
@router.post("")
|
||||
def save_rule(req: RuleModel, request: Request):
|
||||
rule = monitor_rules.normalize(req.model_dump())
|
||||
# 连板梯队封单监控 (type=ladder) 依赖五档盘口数据, 需 Pro+ (DEPTH5_BATCH 能力)。
|
||||
# 无能力时拒绝创建, 避免规则存了却永远无法触发。
|
||||
if rule.get("type") == "ladder":
|
||||
from app.tickflow.capabilities import Cap
|
||||
capset = getattr(request.app.state, "capabilities", None)
|
||||
if capset is None or not capset.has(Cap.DEPTH5_BATCH):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="封单监控需要 Pro+ 套餐 (批量五档能力),请升级后在「设置」页配置",
|
||||
)
|
||||
# 编辑现有规则时, 保留原 created_at (避免按时间排序时位置跳动)
|
||||
existing = monitor_rules.load_one(_data_dir(request), rule["id"])
|
||||
if existing and existing.get("created_at"):
|
||||
rule["created_at"] = existing["created_at"]
|
||||
try:
|
||||
monitor_rules.validate(rule)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
monitor_rules.save_one(_data_dir(request), rule)
|
||||
_sync_engine(request)
|
||||
return {"ok": True, "rule": rule}
|
||||
|
||||
|
||||
# ── 删除 ───────────────────────────────────────────────
|
||||
@router.delete("/{rule_id}")
|
||||
def delete_rule(rule_id: str, request: Request):
|
||||
if not monitor_rules.ID_RE.match(rule_id):
|
||||
raise HTTPException(status_code=400, detail="规则 id 非法")
|
||||
deleted = monitor_rules.delete_one(_data_dir(request), rule_id)
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=404, detail="规则不存在")
|
||||
_sync_engine(request)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ── 演示数据生成 (仅 Dev 页用) ─────────────────────────
|
||||
|
||||
import time as _time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def _demo_rule(rule_id: str, name: str, rtype: str, scope: str, symbols: list[str],
|
||||
conditions: list[dict], logic: str = "or", cooldown: int = 3600,
|
||||
severity: str = "info", message: str = "",
|
||||
strategy_id: str | None = None, direction: str = "entry") -> dict:
|
||||
rule = monitor_rules.normalize({
|
||||
"id": rule_id,
|
||||
"name": name,
|
||||
"type": rtype,
|
||||
"scope": scope,
|
||||
"symbols": symbols,
|
||||
"conditions": conditions,
|
||||
"logic": logic,
|
||||
"cooldown_seconds": cooldown,
|
||||
"severity": severity,
|
||||
"message": message,
|
||||
"enabled": True,
|
||||
})
|
||||
if rtype == "strategy":
|
||||
rule["strategy_id"] = strategy_id
|
||||
rule["direction"] = direction
|
||||
return rule
|
||||
|
||||
|
||||
_DEMO_RULES_TEMPLATE = [
|
||||
("个股信号 · 茅台放量突破", "signal", "symbols", ["600519.SH"],
|
||||
[{"field": "signal_volume_surge", "op": "truth"},
|
||||
{"field": "signal_n_day_high", "op": "truth"}], "or", "info"),
|
||||
("个股信号 · 宁德金叉", "signal", "symbols", ["300750.SZ"],
|
||||
[{"field": "signal_ma_golden_5_20", "op": "truth"}], "or", "info"),
|
||||
("价格 · 平安跌幅监控", "price", "symbols", ["000001.SZ"],
|
||||
[{"field": "change_pct", "op": "<", "value": -0.03}], "or", "warn", "warn"),
|
||||
("价格 · 比亚迪RSI超卖", "price", "symbols", ["002594.SZ"],
|
||||
[{"field": "rsi_14", "op": "<", "value": 30}], "and", "warn", "warn"),
|
||||
("市场异动 · 全市场涨停", "market", "all", [],
|
||||
[{"field": "signal_limit_up", "op": "truth"}], "or", "critical", "critical"),
|
||||
("市场异动 · 全市场炸板", "market", "all", [],
|
||||
[{"field": "signal_broken_limit_up", "op": "truth"}], "or", "warn", "warn"),
|
||||
("市场异动 · 跌幅超5%", "market", "all", [],
|
||||
[{"field": "change_pct", "op": "<", "value": -0.05}], "or", "warn", "warn"),
|
||||
("个股信号 · 茅台跌破MA20", "signal", "symbols", ["600519.SH"],
|
||||
[{"field": "signal_ma20_breakdown", "op": "truth"}], "or", "info"),
|
||||
]
|
||||
|
||||
# 策略类型单独声明 (格式不同: 含 strategy_id + direction)
|
||||
_DEMO_STRATEGY_RULES: list[dict] = [
|
||||
{"name": "策略监控 · 趋势突破", "strategy_id": "trend_breakout", "direction": "entry"},
|
||||
{"name": "策略监控 · MACD金叉", "strategy_id": "macd_golden", "direction": "both"},
|
||||
]
|
||||
|
||||
|
||||
@router.post("/seed")
|
||||
def seed_demo_rules(request: Request):
|
||||
"""生成演示监控规则 (Dev 页用)。覆盖 signal/price/market/strategy 四类。"""
|
||||
ts = int(_time.time() * 1000)
|
||||
created = []
|
||||
i = 0
|
||||
for (name, rtype, scope, symbols, conditions, logic, severity, sev) in _DEMO_RULES_TEMPLATE:
|
||||
rule_id = f"demo_{ts}_{i}"
|
||||
rule = _demo_rule(rule_id, name, rtype, scope, symbols, conditions, logic, 3600, sev)
|
||||
monitor_rules.save_one(_data_dir(request), rule)
|
||||
created.append(rule_id)
|
||||
i += 1
|
||||
# 策略类型规则
|
||||
for sr in _DEMO_STRATEGY_RULES:
|
||||
rule_id = f"demo_{ts}_{i}"
|
||||
rule = _demo_rule(
|
||||
rule_id, sr["name"], "strategy", "all", [], [], "and", 3600, "info",
|
||||
strategy_id=sr["strategy_id"], direction=sr.get("direction", "entry"),
|
||||
)
|
||||
monitor_rules.save_one(_data_dir(request), rule)
|
||||
created.append(rule_id)
|
||||
i += 1
|
||||
_sync_engine(request)
|
||||
return {"ok": True, "generated": len(created), "ids": created}
|
||||
|
||||
|
||||
# ── 封单监控模拟触发 (Dev 调试用) ─────────────────────
|
||||
@router.post("/test-ladder")
|
||||
def test_ladder(request: Request):
|
||||
"""模拟触发所有 ladder 规则, 返回命中结果 (不落盘、不推送飞书)。
|
||||
|
||||
用当前 depth_service 的封单数据 + enriched 最新日 close 构造 mock DataFrame,
|
||||
跑 _evaluate_ladder 判断哪些规则会触发。供 Dev 页面调试验证。
|
||||
"""
|
||||
import polars as pl
|
||||
|
||||
repo = request.app.state.repo
|
||||
depth_svc = getattr(request.app.state, "depth_service", None)
|
||||
engine = getattr(request.app.state, "monitor_engine", None)
|
||||
|
||||
if not depth_svc:
|
||||
raise HTTPException(status_code=503, detail="depth 服务未初始化")
|
||||
if not engine or not engine.has_rule_type("ladder"):
|
||||
raise HTTPException(status_code=400, detail="无 ladder 类型监控规则")
|
||||
|
||||
# 最新交易日
|
||||
latest = repo.enriched_latest_date()
|
||||
if not latest:
|
||||
raise HTTPException(status_code=400, detail="无 enriched 数据")
|
||||
|
||||
# 取涨停+跌停封单 {symbol: vol}
|
||||
sealed: dict[str, int] = {}
|
||||
for is_down in (False, True):
|
||||
m = depth_svc.get_sealed_map(latest, is_down=is_down)
|
||||
for sym, info in m.items():
|
||||
vol = (info or {}).get("vol")
|
||||
if vol and vol > 0:
|
||||
sealed[sym] = vol
|
||||
|
||||
if not sealed:
|
||||
raise HTTPException(status_code=400, detail="无封单数据 (depth 未拉取或无涨停/跌停股)")
|
||||
|
||||
# 取这些 symbol 的 close (算封单额用)
|
||||
enriched_today, _ = repo.get_enriched_latest()
|
||||
cols = ["symbol", "close", "change_pct"]
|
||||
avail = [c for c in cols if c in enriched_today.columns]
|
||||
mock = enriched_today.select(avail).filter(pl.col("symbol").is_in(list(sealed.keys())))
|
||||
|
||||
# 注入 _sealed_vol
|
||||
sealed_df = pl.DataFrame({
|
||||
"symbol": list(sealed.keys()),
|
||||
"_sealed_vol": list(sealed.values()),
|
||||
})
|
||||
mock = mock.join(sealed_df, on="symbol", how="inner")
|
||||
|
||||
# 取所有 ladder 规则, 逐条纯条件判断 (绕过引擎 cooldown, 不污染 _last_fire)
|
||||
ladder_rules = [r for r in engine.rules.values() if r.get("type") == "ladder" and r.get("enabled", True)]
|
||||
all_events = []
|
||||
not_triggered = []
|
||||
|
||||
for rule in ladder_rules:
|
||||
syms = rule.get("symbols", [])
|
||||
sym = syms[0] if syms else None
|
||||
metric = rule.get("metric", "sealed_vol")
|
||||
thr = rule.get("threshold", 0)
|
||||
direction = rule.get("direction", "up")
|
||||
warn_label = "炸板预警" if direction == "up" else "翘板预警"
|
||||
|
||||
# 取该 symbol 的封单数据
|
||||
cur_vol = sealed.get(sym) if sym else None
|
||||
row = mock.filter(pl.col("symbol") == sym) if sym else mock.clear()
|
||||
cur_close = row["close"][0] if len(row) and "close" in row.columns else None
|
||||
cur_amt = (cur_vol * 100 * cur_close) if (cur_vol and cur_close) else None
|
||||
cur_val = cur_amt if metric == "sealed_amount" else cur_vol
|
||||
|
||||
# 条件判断: 封单 > 0 且 比较值 <= 阈值
|
||||
if cur_val is not None and cur_val > 0 and cur_val <= thr:
|
||||
if metric == "sealed_amount":
|
||||
sv_text = f"{cur_val / 1e4:.0f}万元"
|
||||
th_text = f"{thr / 1e4:.0f}万元"
|
||||
else:
|
||||
sv_text = f"{cur_val:,.0f} 手"
|
||||
th_text = f"{thr:,.0f} 手"
|
||||
all_events.append({
|
||||
"rule_id": rule["id"],
|
||||
"rule_name": rule.get("name", ""),
|
||||
"symbol": sym,
|
||||
"name": sym,
|
||||
"type": warn_label,
|
||||
"message": f"{warn_label} · 封单 {sv_text} ≤ {th_text}",
|
||||
"severity": rule.get("severity", "warn"),
|
||||
"sealed_value": cur_val,
|
||||
"sealed_metric": metric,
|
||||
"current_sealed_vol": cur_vol,
|
||||
"current_sealed_amount": cur_amt,
|
||||
})
|
||||
else:
|
||||
reason = "封单数据缺失" if cur_val is None else (
|
||||
f"封单 {cur_val:,.0f} > 阈值 {thr:,.0f}" if cur_val > thr else "封单为 0"
|
||||
)
|
||||
not_triggered.append({
|
||||
"rule_id": rule["id"],
|
||||
"rule_name": rule.get("name", ""),
|
||||
"symbol": sym,
|
||||
"metric": metric,
|
||||
"threshold": thr,
|
||||
"current_value": cur_val,
|
||||
"current_sealed_vol": cur_vol,
|
||||
"current_sealed_amount": cur_amt,
|
||||
"reason": reason,
|
||||
})
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"as_of": str(latest),
|
||||
"sealed_count": len(sealed),
|
||||
"triggered": all_events,
|
||||
"not_triggered": not_triggered,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/trigger-ladder")
|
||||
def trigger_ladder(request: Request):
|
||||
"""真实触发一次 ladder 预警 (落盘 + 飞书推送 + SSE), 供 Dev 调试验证完整效果。
|
||||
|
||||
与 test-ladder 区别: 本端点会真的把预警写入 alerts.jsonl、推送飞书、触发 SSE,
|
||||
让用户看到真实的预警通知。绕过 cooldown 强制触发。
|
||||
"""
|
||||
import time
|
||||
from app.services import alert_store
|
||||
|
||||
repo = request.app.state.repo
|
||||
depth_svc = getattr(request.app.state, "depth_service", None)
|
||||
engine = getattr(request.app.state, "monitor_engine", None)
|
||||
quote_svc = getattr(request.app.state, "quote_service", None)
|
||||
|
||||
if not depth_svc:
|
||||
raise HTTPException(status_code=503, detail="depth 服务未初始化")
|
||||
if not engine or not engine.has_rule_type("ladder"):
|
||||
raise HTTPException(status_code=400, detail="无 ladder 类型监控规则")
|
||||
|
||||
latest = repo.enriched_latest_date()
|
||||
if not latest:
|
||||
raise HTTPException(status_code=400, detail="无 enriched 数据")
|
||||
|
||||
# 取封单
|
||||
sealed: dict[str, int] = {}
|
||||
for is_down in (False, True):
|
||||
m = depth_svc.get_sealed_map(latest, is_down=is_down)
|
||||
for sym, info in m.items():
|
||||
vol = (info or {}).get("vol")
|
||||
if vol and vol > 0:
|
||||
sealed[sym] = vol
|
||||
if not sealed:
|
||||
raise HTTPException(status_code=400, detail="无封单数据")
|
||||
|
||||
# 构造真实 rule_events (与 _evaluate_ladder 产出格式一致)
|
||||
import polars as pl
|
||||
enriched_today, _ = repo.get_enriched_latest()
|
||||
cols = [c for c in ["symbol", "close", "change_pct"] if c in enriched_today.columns]
|
||||
mock = enriched_today.select(cols).filter(pl.col("symbol").is_in(list(sealed.keys())))
|
||||
sealed_df = pl.DataFrame({"symbol": list(sealed.keys()), "_sealed_vol": list(sealed.values())})
|
||||
mock = mock.join(sealed_df, on="symbol", how="inner")
|
||||
|
||||
now = time.time()
|
||||
rule_events: list[dict] = []
|
||||
name_map = {}
|
||||
try:
|
||||
inst = repo.get_instruments()
|
||||
if not inst.is_empty() and "name" in inst.columns:
|
||||
name_map = {r["symbol"]: r["name"] for r in inst.select(["symbol", "name"]).iter_rows(named=True) if r.get("name")}
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
for rule in engine.rules.values():
|
||||
if rule.get("type") != "ladder" or not rule.get("enabled", True):
|
||||
continue
|
||||
sym = rule.get("symbols", [""])[0] if rule.get("symbols") else ""
|
||||
metric = rule.get("metric", "sealed_vol")
|
||||
thr = rule.get("threshold", 0)
|
||||
direction = rule.get("direction", "up")
|
||||
warn_label = "炸板预警" if direction == "up" else "翘板预警"
|
||||
|
||||
row = mock.filter(pl.col("symbol") == sym)
|
||||
if row.is_empty():
|
||||
continue
|
||||
cur_vol = row["_sealed_vol"][0]
|
||||
close_v = row["close"][0] if "close" in row.columns else None
|
||||
cur_val = cur_vol * 100 * close_v if metric == "sealed_amount" else cur_vol
|
||||
if not cur_val or cur_val <= 0 or cur_val > thr:
|
||||
continue # 不满足条件, 跳过
|
||||
|
||||
if metric == "sealed_amount":
|
||||
sv_text = f"{cur_val / 1e4:.0f}万元"
|
||||
th_text = f"{thr / 1e4:.0f}万元"
|
||||
else:
|
||||
sv_text = f"{cur_val:,.0f} 手"
|
||||
th_text = f"{thr:,.0f} 手"
|
||||
|
||||
rule_events.append({
|
||||
"ts": int(now * 1000),
|
||||
"rule_id": rule["id"],
|
||||
"rule_name": rule.get("name", ""),
|
||||
"source": "ladder",
|
||||
"type": warn_label,
|
||||
"symbol": sym,
|
||||
"name": name_map.get(sym, sym),
|
||||
"message": f"{warn_label} · 封单 {sv_text} ≤ {th_text}",
|
||||
"price": close_v,
|
||||
"change_pct": row["change_pct"][0] if "change_pct" in row.columns else None,
|
||||
"signals": [],
|
||||
"severity": rule.get("severity", "warn"),
|
||||
"conditions": [],
|
||||
"logic": "and",
|
||||
"sealed_value": cur_val,
|
||||
"sealed_metric": metric,
|
||||
})
|
||||
|
||||
if not rule_events:
|
||||
raise HTTPException(status_code=400, detail="当前无 ladder 规则满足触发条件 (封单均 > 阈值)")
|
||||
|
||||
# 1. 落盘到 alerts.jsonl
|
||||
try:
|
||||
alert_store.append_many(repo.store.data_dir, rule_events)
|
||||
except Exception as e: # noqa: BLE001
|
||||
pass # 落盘失败不阻断推送
|
||||
|
||||
# 2. SSE 推送 (入 pending_alerts 队列)
|
||||
if quote_svc:
|
||||
sse_alerts = [{
|
||||
"source": ev["source"], "type": ev["type"], "rule_id": ev["rule_id"],
|
||||
"strategy_id": None, "symbol": ev["symbol"], "name": ev["name"],
|
||||
"message": ev["message"], "price": ev["price"], "change_pct": ev["change_pct"],
|
||||
"signals": ev["signals"], "severity": ev["severity"],
|
||||
"conditions": ev["conditions"], "logic": ev["logic"],
|
||||
} for ev in rule_events]
|
||||
try:
|
||||
with quote_svc._lock:
|
||||
quote_svc._pending_alerts.extend(sse_alerts)
|
||||
quote_svc._alert_event.set()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
# 3. 飞书推送
|
||||
if quote_svc:
|
||||
try:
|
||||
quote_svc._maybe_send_webhook(rule_events, engine)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"triggered": len(rule_events),
|
||||
"events": [{"symbol": ev["symbol"], "name": ev["name"], "message": ev["message"]} for ev in rule_events],
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
"""市场总览聚合 API。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
import time
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
import polars as pl
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from app.services.ext_data import ExtConfig, ExtConfigStore
|
||||
from app.services.screener import ScreenerService
|
||||
|
||||
router = APIRouter(prefix="/api/overview", tags=["overview"])
|
||||
|
||||
_CACHE_TTL = 5.0
|
||||
_cache: dict[str, Any] | None = None
|
||||
_cache_key: str | None = None
|
||||
_cache_ts: float = 0.0
|
||||
|
||||
|
||||
def invalidate_overview_cache() -> None:
|
||||
"""清空总览聚合结果缓存。
|
||||
|
||||
清除数据后调用, 避免看板在 TTL 窗口内继续返回旧的聚合结果。
|
||||
"""
|
||||
global _cache, _cache_key, _cache_ts
|
||||
_cache = None
|
||||
_cache_key = None
|
||||
_cache_ts = 0.0
|
||||
|
||||
|
||||
CORE_INDEX_NAMES = {
|
||||
"000001.SH": "上证指数",
|
||||
"399001.SZ": "深证成指",
|
||||
"399006.SZ": "创业板指",
|
||||
"000680.SH": "科创综指",
|
||||
}
|
||||
CORE_INDEX_SYMBOLS = tuple(CORE_INDEX_NAMES.keys())
|
||||
|
||||
_DIMENSION_SEP = re.compile(r"[、,,;;|/\s]+")
|
||||
|
||||
|
||||
def _dimension_field(config: ExtConfig, kind: str) -> str | None:
|
||||
candidates = ["概念", "concept", "theme"] if kind == "concept" else ["行业", "industry", "sector"]
|
||||
for candidate in candidates:
|
||||
needle = candidate.lower()
|
||||
for field in config.fields:
|
||||
haystack = f"{field.name} {field.label}".lower()
|
||||
if needle in haystack:
|
||||
return field.name
|
||||
return None
|
||||
|
||||
|
||||
def _ext_files(data_dir, config: ExtConfig) -> list[str]:
|
||||
base = data_dir / "ext_data" / config.id
|
||||
if config.mode == "timeseries":
|
||||
root = base / "timeseries"
|
||||
return [str(p) for p in sorted(root.rglob("*.parquet")) if p.is_file()]
|
||||
return [str(p) for p in sorted(base.glob("*.parquet")) if p.is_file()]
|
||||
|
||||
|
||||
def _read_ext_rows(data_dir, config: ExtConfig, dimension_field: str) -> list[dict]:
|
||||
files = _ext_files(data_dir, config)
|
||||
if not files:
|
||||
return []
|
||||
try:
|
||||
df = pl.read_parquet(files, hive_partitioning=True)
|
||||
except TypeError:
|
||||
try:
|
||||
df = pl.read_parquet(files)
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
if df.is_empty() or dimension_field not in df.columns:
|
||||
return []
|
||||
|
||||
if config.mode == "timeseries" and "date" in df.columns:
|
||||
latest = df.get_column("date").max()
|
||||
if latest is not None:
|
||||
df = df.filter(pl.col("date") == latest)
|
||||
|
||||
symbol_cols = ["symbol", "code", "股票代码", "代码"]
|
||||
for mapping in (config.symbol_map, config.code_map):
|
||||
if isinstance(mapping, dict) and mapping.get("type") == "mapped" and mapping.get("col"):
|
||||
symbol_cols.append(str(mapping["col"]))
|
||||
cols = []
|
||||
for col in [dimension_field, *symbol_cols]:
|
||||
if col in df.columns and col not in cols:
|
||||
cols.append(col)
|
||||
return df.select(cols).to_dicts()
|
||||
|
||||
|
||||
def _dimension_values(raw: Any) -> list[str]:
|
||||
if raw is None:
|
||||
return []
|
||||
values = [v.strip() for v in _DIMENSION_SEP.split(str(raw).strip()) if v.strip()]
|
||||
return values
|
||||
|
||||
|
||||
def _symbol_keys(row: dict, config: ExtConfig) -> list[str]:
|
||||
fields = ["symbol", "code", "股票代码", "代码"]
|
||||
for mapping in (config.symbol_map, config.code_map):
|
||||
if isinstance(mapping, dict) and mapping.get("type") == "mapped" and mapping.get("col"):
|
||||
fields.append(str(mapping["col"]))
|
||||
|
||||
keys: list[str] = []
|
||||
for field in fields:
|
||||
raw = row.get(field)
|
||||
if raw is None:
|
||||
continue
|
||||
text = str(raw).strip().upper()
|
||||
if not text:
|
||||
continue
|
||||
keys.append(text)
|
||||
if "." in text:
|
||||
keys.append(text.split(".", 1)[0])
|
||||
return keys
|
||||
|
||||
|
||||
def _dimension_rank(rows: list[dict], request: Request, kind: str, limit: int = 5, level: int | None = None) -> dict:
|
||||
if not rows:
|
||||
return {"leading": [], "lagging": []}
|
||||
|
||||
quote_map: dict[str, dict] = {}
|
||||
for row in rows:
|
||||
symbol = str(row.get("symbol") or "").strip().upper()
|
||||
if not symbol:
|
||||
continue
|
||||
quote_map[symbol] = row
|
||||
quote_map[symbol.split(".", 1)[0]] = row
|
||||
|
||||
store = ExtConfigStore(request.app.state.repo.store.data_dir)
|
||||
groups: dict[str, dict[str, dict]] = {}
|
||||
for config in store.load_all():
|
||||
field = _dimension_field(config, kind)
|
||||
if not field:
|
||||
continue
|
||||
for ext_row in _read_ext_rows(request.app.state.repo.store.data_dir, config, field):
|
||||
quote = None
|
||||
for key in _symbol_keys(ext_row, config):
|
||||
quote = quote_map.get(key)
|
||||
if quote:
|
||||
break
|
||||
if not quote:
|
||||
continue
|
||||
symbol = str(quote.get("symbol") or "")
|
||||
for value in _dimension_values(ext_row.get(field)):
|
||||
# 行业按 "-" 拆分级: "银行-银行-股份制银行" → level=2 取"银行"(二级)
|
||||
if level is not None and "-" in value:
|
||||
parts = value.split("-")
|
||||
value = parts[level - 1] if level <= len(parts) else parts[-1]
|
||||
groups.setdefault(value, {})[symbol] = quote
|
||||
|
||||
items = []
|
||||
for name, by_symbol in groups.items():
|
||||
stocks = list(by_symbol.values())
|
||||
changes = [_finite(s.get("change_pct")) for s in stocks]
|
||||
changes = [v for v in changes if v is not None]
|
||||
if not changes:
|
||||
continue
|
||||
leader = max(stocks, key=lambda s: _finite(s.get("change_pct")) or -999)
|
||||
items.append({
|
||||
"name": name,
|
||||
"count": len(stocks),
|
||||
"avg_pct": sum(changes) / len(changes),
|
||||
"up_count": sum(1 for v in changes if v > 0),
|
||||
"down_count": sum(1 for v in changes if v < 0),
|
||||
"amount": sum(_finite(s.get("amount")) or 0 for s in stocks),
|
||||
"leader": {
|
||||
"symbol": leader.get("symbol"),
|
||||
"name": leader.get("name"),
|
||||
"change_pct": _finite(leader.get("change_pct")),
|
||||
},
|
||||
})
|
||||
|
||||
leading = sorted(items, key=lambda x: x["avg_pct"], reverse=True)[:limit]
|
||||
lagging = sorted(items, key=lambda x: x["avg_pct"])[:limit]
|
||||
return {"leading": leading, "lagging": lagging}
|
||||
|
||||
|
||||
def _finite(v: Any) -> float | None:
|
||||
if v is None:
|
||||
return None
|
||||
try:
|
||||
f = float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return f if math.isfinite(f) else None
|
||||
|
||||
|
||||
def _json_safe(value: Any) -> Any:
|
||||
if isinstance(value, dict):
|
||||
return {k: _json_safe(v) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_json_safe(v) for v in value]
|
||||
if isinstance(value, float) and not math.isfinite(value):
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def _board(symbol: str) -> str:
|
||||
if symbol.endswith(".BJ"):
|
||||
return "北交所"
|
||||
if symbol.startswith(("300", "301")):
|
||||
return "创业板"
|
||||
if symbol.startswith(("688", "689")):
|
||||
return "科创板"
|
||||
if symbol.endswith(".SH"):
|
||||
return "沪主板"
|
||||
if symbol.endswith(".SZ"):
|
||||
return "深主板"
|
||||
return "其他"
|
||||
|
||||
|
||||
def _score(value: float, low: float, high: float) -> int:
|
||||
if high <= low:
|
||||
return 50
|
||||
return max(0, min(100, round((value - low) / (high - low) * 100)))
|
||||
|
||||
|
||||
def _quote_status(request: Request) -> dict:
|
||||
qs = getattr(request.app.state, "quote_service", None)
|
||||
if not qs:
|
||||
return {"enabled": False, "running": False, "quote_age_ms": None, "is_trading_hours": False}
|
||||
return qs.status()
|
||||
|
||||
|
||||
def _index_quotes(request: Request, as_of: date | None = None) -> list[dict]:
|
||||
qs = getattr(request.app.state, "quote_service", None)
|
||||
rows: list[dict] = []
|
||||
if qs and as_of is None:
|
||||
df = qs.get_index_quotes(list(CORE_INDEX_SYMBOLS))
|
||||
if not df.is_empty():
|
||||
rows = df.to_dicts()
|
||||
|
||||
if not rows:
|
||||
repo = getattr(request.app.state, "repo", None)
|
||||
if repo:
|
||||
placeholders = ", ".join("?" for _ in CORE_INDEX_SYMBOLS)
|
||||
try:
|
||||
db_rows = repo.execute_all(
|
||||
f"""
|
||||
WITH ranked AS (
|
||||
SELECT symbol, date, close,
|
||||
row_number() OVER (PARTITION BY symbol ORDER BY date DESC) AS rn
|
||||
FROM kline_index_daily
|
||||
WHERE symbol IN ({placeholders})
|
||||
AND (? IS NULL OR date <= ?)
|
||||
), latest AS (
|
||||
SELECT symbol,
|
||||
max(CASE WHEN rn = 1 THEN date END) AS date,
|
||||
max(CASE WHEN rn = 1 THEN close END) AS last_price,
|
||||
max(CASE WHEN rn = 2 THEN close END) AS prev_close
|
||||
FROM ranked
|
||||
WHERE rn <= 2
|
||||
GROUP BY symbol
|
||||
)
|
||||
SELECT symbol, date, last_price, prev_close
|
||||
FROM latest
|
||||
""",
|
||||
[*CORE_INDEX_SYMBOLS, as_of, as_of],
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
db_rows = []
|
||||
for symbol, dt, last_price, prev_close in db_rows:
|
||||
change_amount = None
|
||||
change_pct = None
|
||||
lp = _finite(last_price)
|
||||
pc = _finite(prev_close)
|
||||
if lp is not None and pc not in (None, 0):
|
||||
change_amount = lp - pc
|
||||
change_pct = change_amount / pc * 100
|
||||
rows.append({
|
||||
"symbol": symbol,
|
||||
"name": CORE_INDEX_NAMES.get(symbol),
|
||||
"date": str(dt) if dt else None,
|
||||
"last_price": lp,
|
||||
"close": lp,
|
||||
"prev_close": pc,
|
||||
"change_amount": change_amount,
|
||||
"change_pct": change_pct,
|
||||
})
|
||||
|
||||
by_symbol = {r.get("symbol"): r for r in rows}
|
||||
out = []
|
||||
for symbol in CORE_INDEX_SYMBOLS:
|
||||
r = by_symbol.get(symbol, {"symbol": symbol})
|
||||
out.append({
|
||||
"symbol": symbol,
|
||||
"name": r.get("name") or CORE_INDEX_NAMES[symbol],
|
||||
"last_price": _finite(r.get("last_price") if r.get("last_price") is not None else r.get("close")),
|
||||
"change_pct": _finite(r.get("change_pct")),
|
||||
"change_amount": _finite(r.get("change_amount")),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _top_rows(rows: list[dict], key: str, descending: bool, limit: int = 8) -> list[dict]:
|
||||
filtered = [r for r in rows if _finite(r.get(key)) is not None]
|
||||
filtered.sort(key=lambda r: _finite(r.get(key)) or 0, reverse=descending)
|
||||
return [
|
||||
{
|
||||
"symbol": r.get("symbol"),
|
||||
"name": r.get("name"),
|
||||
"close": _finite(r.get("close")),
|
||||
"change_pct": _finite(r.get("change_pct")),
|
||||
"amount": _finite(r.get("amount")),
|
||||
"turnover_rate": _finite(r.get("turnover_rate")),
|
||||
"board": _board(str(r.get("symbol") or "")),
|
||||
}
|
||||
for r in filtered[:limit]
|
||||
]
|
||||
|
||||
|
||||
def _pct_band_rows(values: list[float]) -> list[dict]:
|
||||
bands = [
|
||||
("<-5%", None, -0.05),
|
||||
("-5~-3%", -0.05, -0.03),
|
||||
("-3~-1%", -0.03, -0.01),
|
||||
("-1~0%", -0.01, 0),
|
||||
("0~1%", 0, 0.01),
|
||||
("1~3%", 0.01, 0.03),
|
||||
("3~5%", 0.03, 0.05),
|
||||
(">5%", 0.05, None),
|
||||
]
|
||||
total = len(values) or 1
|
||||
out = []
|
||||
for label, low, high in bands:
|
||||
count = 0
|
||||
for v in values:
|
||||
if low is None and v < high:
|
||||
count += 1
|
||||
elif high is None and v >= low:
|
||||
count += 1
|
||||
elif low is not None and high is not None and low <= v < high:
|
||||
count += 1
|
||||
out.append({"label": label, "count": count, "pct": count / total * 100})
|
||||
return out
|
||||
|
||||
|
||||
def _build_overview(request: Request, as_of: date | None = None) -> dict:
|
||||
"""装配市场总览(委托给 services.market_overview_builder,保持行为一致)。
|
||||
|
||||
逻辑已抽离至 build_market_overview,以解耦对 Request 的依赖,
|
||||
使大盘复盘等无 Request 的调用方可复用同一装配逻辑。
|
||||
"""
|
||||
from app.services.market_overview_builder import build_market_overview
|
||||
return build_market_overview(
|
||||
repo=request.app.state.repo,
|
||||
quote_service=getattr(request.app.state, "quote_service", None),
|
||||
depth_service=getattr(request.app.state, "depth_service", None),
|
||||
as_of=as_of,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/market")
|
||||
def market_overview(request: Request, as_of: date | None = None):
|
||||
"""总览页单次请求聚合数据,避免前端拉全市场明细后再计算。"""
|
||||
global _cache, _cache_key, _cache_ts
|
||||
now = time.time()
|
||||
cache_key = as_of.isoformat() if as_of else "latest"
|
||||
if _cache is not None and _cache_key == cache_key and (now - _cache_ts) < _CACHE_TTL:
|
||||
return _cache
|
||||
data = _build_overview(request, as_of)
|
||||
_cache = data
|
||||
_cache_key = cache_key
|
||||
_cache_ts = now
|
||||
return data
|
||||
@@ -0,0 +1,107 @@
|
||||
"""盘后管道 API — 异步触发 + 进度跟踪。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import concurrent.futures as _cf
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
|
||||
from app.jobs import daily_pipeline
|
||||
from app.services.pipeline_jobs import job_store
|
||||
from app.api.data import invalidate_storage_cache
|
||||
|
||||
# 长时间任务专用线程池(隔离于 FastAPI 默认线程池,防止阻塞请求处理)
|
||||
_long_task_executor = _cf.ThreadPoolExecutor(max_workers=2, thread_name_prefix="long-task")
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/pipeline", tags=["pipeline"])
|
||||
|
||||
|
||||
@router.post("/run")
|
||||
async def run_now(request: Request) -> dict:
|
||||
"""异步触发盘后管道,立即返回 job_id。客户端轮询 /jobs/{id} 拿进度。
|
||||
|
||||
若已有任务在跑,**返回该任务 id 而不是开新任务**(防止并发拉数据撞限流)。
|
||||
但如果该任务已运行超过 10 分钟 (可能因 reload 卡死), 强制标记为失败后重新创建。
|
||||
"""
|
||||
repo = request.app.state.repo
|
||||
capset = request.app.state.capabilities
|
||||
|
||||
# 检测卡死的 running job (如 reload 后孤儿 task)
|
||||
existing_id = job_store.active_id()
|
||||
if existing_id:
|
||||
existing = job_store.get(existing_id)
|
||||
if existing and existing["status"] == "running":
|
||||
from datetime import datetime, timezone
|
||||
started = existing.get("started_at")
|
||||
if started:
|
||||
try:
|
||||
start_dt = datetime.fromisoformat(started.replace("Z", "+00:00"))
|
||||
elapsed = (datetime.now(timezone.utc) - start_dt).total_seconds()
|
||||
if elapsed > 600: # 超过 10 分钟视为卡死
|
||||
logger.warning("强制取消卡死 job %s (已运行 %.0fs)", existing_id, elapsed)
|
||||
job_store.fail(existing_id, "超时自动取消 (疑似 reload 后孤儿 task)")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
job_id = job_store.create()
|
||||
|
||||
# 如果是复用的 active job,直接返回(不重启)
|
||||
existing = job_store.get(job_id)
|
||||
if existing and existing["status"] == "running":
|
||||
return {"job_id": job_id, "reused": True}
|
||||
|
||||
# 在 executor 里跑同步任务(pipeline 内部都是阻塞 IO + CPU)
|
||||
async def task() -> None:
|
||||
job_store.start(job_id)
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
def progress(stage: str, pct: int, msg: str, stage_pct: int | None = None,
|
||||
skip_log: bool = False) -> None:
|
||||
job_store.progress(job_id, stage, pct, msg, stage_pct=stage_pct, skip_log=skip_log)
|
||||
|
||||
try:
|
||||
result = await loop.run_in_executor(
|
||||
_long_task_executor,
|
||||
lambda: daily_pipeline.run_now(repo, capset, on_progress=progress),
|
||||
)
|
||||
job_store.succeed(job_id, result)
|
||||
invalidate_storage_cache()
|
||||
repo.refresh_cache() # 刷新 Polars 缓存
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception("pipeline failed")
|
||||
job_store.fail(job_id, str(e))
|
||||
invalidate_storage_cache()
|
||||
|
||||
asyncio.create_task(task())
|
||||
return {"job_id": job_id, "reused": False}
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}")
|
||||
def get_job(job_id: str) -> dict:
|
||||
j = job_store.get(job_id)
|
||||
if not j:
|
||||
raise HTTPException(status_code=404, detail="job not found")
|
||||
return j
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/cancel")
|
||||
def cancel_job(job_id: str) -> dict:
|
||||
"""手动取消一个 running 的 job。"""
|
||||
j = job_store.get(job_id)
|
||||
if not j:
|
||||
raise HTTPException(status_code=404, detail="job not found")
|
||||
if j["status"] not in ("running", "pending"):
|
||||
raise HTTPException(status_code=400, detail=f"job status is {j['status']}, cannot cancel")
|
||||
job_store.fail(job_id, "用户手动取消")
|
||||
return {"cancelled": job_id}
|
||||
|
||||
|
||||
@router.get("/jobs")
|
||||
def list_jobs(limit: int = 20) -> dict:
|
||||
return {
|
||||
"active_id": job_store.active_id(),
|
||||
"jobs": job_store.list_recent(limit=limit),
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
"""API 路由 — Phase 0 仅 /health 与 /api/capabilities。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app import __version__
|
||||
from app.tickflow import client as tf_client
|
||||
from app.tickflow.policy import detect_capabilities, tier_label
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health() -> dict:
|
||||
return {
|
||||
"status": "ok",
|
||||
"version": __version__,
|
||||
# 三态: none(无key/无效) / free(免费key) / api_key(付费档)
|
||||
"mode": tf_client.current_mode(),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/capabilities")
|
||||
def capabilities() -> dict:
|
||||
"""前端用来决定哪些功能可用、哪些灰显。"""
|
||||
capset = detect_capabilities()
|
||||
return {
|
||||
"label": tier_label(),
|
||||
"capabilities": capset.to_dict(),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/capabilities/redetect")
|
||||
def redetect() -> dict:
|
||||
"""用户在设置页"重新检测"按钮。"""
|
||||
capset = detect_capabilities(force=True)
|
||||
return {
|
||||
"label": tier_label(),
|
||||
"capabilities": capset.to_dict(),
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
"""涨幅轮动矩阵 API。
|
||||
|
||||
供「概念分析 → 涨幅RPS轮动」对话框调用。返回最近 N 个交易日的概念涨幅
|
||||
排名矩阵:每列(日期)各自把所有概念按当天涨幅从高到低排序。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Query, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.services import rps_rotation
|
||||
from app.services.concept_rotation_analyzer import analyze_rotation_stream
|
||||
|
||||
router = APIRouter(prefix="/api/rps", tags=["rps"])
|
||||
|
||||
|
||||
@router.get("/rotation")
|
||||
def get_rotation(
|
||||
request: Request,
|
||||
days: int = Query(12, ge=7, le=30, description="最近 N 个交易日(7-30)"),
|
||||
) -> dict:
|
||||
"""概念涨幅轮动矩阵。
|
||||
|
||||
Returns:
|
||||
dates: 日期字符串列表(最新在最前)
|
||||
columns: {日期: [[概念名, 涨幅小数], ...]} 每列各自降序
|
||||
concept_count: 去重概念总数
|
||||
"""
|
||||
return rps_rotation.build_rps_rotation(request.app.state.repo, days)
|
||||
|
||||
|
||||
class AnalyzeRequest(BaseModel):
|
||||
"""AI 概念轮动分析请求。"""
|
||||
days: int = 12 # 分析最近 N 个交易日
|
||||
focus: str = "" # 用户追加的关注点
|
||||
|
||||
|
||||
@router.post("/rotation-analyze")
|
||||
async def analyze_rotation(request: Request, req: AnalyzeRequest):
|
||||
"""AI 概念轮动分析 — NDJSON 流式返回。
|
||||
|
||||
装配轮动矩阵信号 + 大盘背景 → 分析提示词 → 流式调用 LLM →
|
||||
逐 chunk 以 NDJSON 推给前端(每行一个 JSON)。
|
||||
|
||||
协议:
|
||||
{"type":"meta","days","summary"}
|
||||
{"type":"delta","content":"..."}
|
||||
{"type":"error","message":"..."}
|
||||
{"type":"done"}
|
||||
"""
|
||||
repo = request.app.state.repo
|
||||
quote_service = getattr(request.app.state, "quote_service", None)
|
||||
depth_service = getattr(request.app.state, "depth_service", None)
|
||||
days = max(7, min(30, req.days))
|
||||
|
||||
async def stream_gen():
|
||||
async for chunk in analyze_rotation_stream(
|
||||
repo, days, req.focus, quote_service, depth_service,
|
||||
):
|
||||
yield chunk + "\n"
|
||||
|
||||
return StreamingResponse(
|
||||
stream_gen(),
|
||||
media_type="application/x-ndjson",
|
||||
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
@@ -0,0 +1,730 @@
|
||||
"""Screener API。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
import re
|
||||
import time
|
||||
from dataclasses import asdict
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.services.screener import PRESET_STRATEGIES, ScreenerService
|
||||
from app.services import strategy_cache
|
||||
from app.strategy import config as strategy_config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/screener", tags=["screener"])
|
||||
|
||||
|
||||
class CustomRequest(BaseModel):
|
||||
conditions: list[str]
|
||||
order_by: Optional[str] = None
|
||||
limit: int = 30
|
||||
pool: Optional[list[str]] = None
|
||||
as_of: Optional[date] = None
|
||||
ext_columns: Optional[str] = None
|
||||
|
||||
|
||||
class PresetRequest(BaseModel):
|
||||
strategy_id: str
|
||||
pool: Optional[list[str]] = None
|
||||
as_of: Optional[date] = None
|
||||
ext_columns: Optional[str] = None
|
||||
|
||||
|
||||
def _safe(result_dict: dict) -> dict:
|
||||
"""sanitize for JSON(NaN / Inf → None)."""
|
||||
rows = result_dict.get("rows", [])
|
||||
for r in rows:
|
||||
for k, v in list(r.items()):
|
||||
if isinstance(v, float) and not math.isfinite(v):
|
||||
r[k] = None
|
||||
return result_dict
|
||||
|
||||
|
||||
_EXT_IDENT_RE = re.compile(r"^[A-Za-z0-9_]+$")
|
||||
|
||||
|
||||
def _safe_ext_value(value: Any) -> Any:
|
||||
if isinstance(value, float) and not math.isfinite(value):
|
||||
return None
|
||||
if isinstance(value, (date, datetime)):
|
||||
return value.isoformat()
|
||||
return value
|
||||
|
||||
|
||||
def _quote_ident(name: str) -> str:
|
||||
return '"' + name.replace('"', '""') + '"'
|
||||
|
||||
|
||||
def _load_ext_value_maps(repo, ext_columns: Optional[str]) -> dict[str, dict[str, Any]]:
|
||||
"""按请求加载扩展列,返回 {输出列名: {symbol: value}}。
|
||||
|
||||
策略结果缓存是共享文件,不能被不同 ext_columns 组合污染;因此扩展列只在
|
||||
返回前通过该投影映射追加到结果副本中。
|
||||
"""
|
||||
ext_specs = _parse_ext_columns(ext_columns) if ext_columns else []
|
||||
if not ext_specs:
|
||||
return {}
|
||||
|
||||
import polars as pl
|
||||
from app.api.ext_data import _read_ext_dataframe
|
||||
from app.services.ext_data import ExtConfigStore
|
||||
|
||||
db = repo.store.db
|
||||
data_dir = repo.store.data_dir
|
||||
ext_store = ExtConfigStore(data_dir)
|
||||
configs = {c.id: c for c in ext_store.load_all()}
|
||||
value_maps: dict[str, dict[str, Any]] = {}
|
||||
|
||||
for config_id, field_name in ext_specs:
|
||||
out_col = f"{config_id}__{field_name}"
|
||||
cfg = configs.get(config_id)
|
||||
try:
|
||||
if cfg:
|
||||
# 时序扩展表只取最新分区,避免历史分区把同一 symbol JOIN 放大。
|
||||
ext_df, _ = _read_ext_dataframe(cfg, data_dir)
|
||||
else:
|
||||
view_name = f"ext_{config_id}"
|
||||
ext_df = pl.from_arrow(db.query(
|
||||
f"SELECT symbol, {_quote_ident(field_name)} FROM {view_name}"
|
||||
).arrow())
|
||||
|
||||
if ext_df.is_empty() or "symbol" not in ext_df.columns or field_name not in ext_df.columns:
|
||||
continue
|
||||
|
||||
ext_df = ext_df.select(["symbol", field_name]).unique(subset=["symbol"], keep="last")
|
||||
value_maps[out_col] = {
|
||||
str(row["symbol"]): _safe_ext_value(row.get(field_name))
|
||||
for row in ext_df.to_dicts()
|
||||
if row.get("symbol")
|
||||
}
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("screener ext column join skipped for %s.%s: %s", config_id, field_name, e)
|
||||
|
||||
return value_maps
|
||||
|
||||
|
||||
def _row_with_ext(row: dict, ext_values: dict[str, dict[str, Any]], symbol: Optional[str] = None) -> dict:
|
||||
next_row = dict(row)
|
||||
sym = symbol or next_row.get("symbol")
|
||||
for out_col, value_map in ext_values.items():
|
||||
next_row[out_col] = value_map.get(str(sym)) if sym else None
|
||||
return next_row
|
||||
|
||||
|
||||
def _rows_with_ext(rows: list[dict], ext_values: dict[str, dict[str, Any]]) -> list[dict]:
|
||||
if not ext_values:
|
||||
return rows
|
||||
return [_row_with_ext(r, ext_values) for r in rows]
|
||||
|
||||
|
||||
def _result_with_ext(result_dict: dict, ext_values: dict[str, dict[str, Any]]) -> dict:
|
||||
if not ext_values:
|
||||
return result_dict
|
||||
return {**result_dict, "rows": _rows_with_ext(result_dict.get("rows", []), ext_values)}
|
||||
|
||||
|
||||
def _results_with_ext(results: dict[str, dict], ext_values: dict[str, dict[str, Any]]) -> dict[str, dict]:
|
||||
if not ext_values:
|
||||
return results
|
||||
return {sid: _result_with_ext(r, ext_values) for sid, r in results.items()}
|
||||
|
||||
|
||||
def _cache_payload_with_ext(cached: dict, ext_values: dict[str, dict[str, Any]]) -> dict:
|
||||
if not ext_values:
|
||||
return cached
|
||||
|
||||
payload = dict(cached)
|
||||
payload["results"] = _results_with_ext(cached.get("results", {}), ext_values)
|
||||
|
||||
ever_rows = cached.get("today_ever_rows")
|
||||
if isinstance(ever_rows, dict):
|
||||
enriched_ever: dict[str, dict[str, dict]] = {}
|
||||
for sid, sym_map in ever_rows.items():
|
||||
if not isinstance(sym_map, dict):
|
||||
continue
|
||||
enriched_ever[sid] = {
|
||||
sym: _row_with_ext(row, ext_values, symbol=sym)
|
||||
for sym, row in sym_map.items()
|
||||
if isinstance(row, dict)
|
||||
}
|
||||
payload["today_ever_rows"] = enriched_ever
|
||||
|
||||
return payload
|
||||
|
||||
|
||||
def _update_cache_strategy(data_dir, as_of: str, strategy_id: str, safe_data: dict) -> None:
|
||||
"""单跑后更新缓存中该策略的结果,保持缓存与最新计算一致。"""
|
||||
from app.services import strategy_cache
|
||||
cached = strategy_cache.read_cache(data_dir)
|
||||
if cached and cached.get("as_of") == as_of:
|
||||
results = cached.get("results", {})
|
||||
results[strategy_id] = {
|
||||
"total": safe_data.get("total", 0),
|
||||
"as_of": as_of,
|
||||
"rows": safe_data.get("rows", []),
|
||||
}
|
||||
strategy_cache.write_cache(data_dir, as_of, results)
|
||||
|
||||
|
||||
@router.get("/strategies")
|
||||
def strategies(request: Request):
|
||||
"""策略清单(内置 + 自定义 + AI)。"""
|
||||
data_dir = request.app.state.repo.store.data_dir
|
||||
presets = []
|
||||
seen_ids: set[str] = set()
|
||||
|
||||
# 内置策略
|
||||
for k, v in PRESET_STRATEGIES.items():
|
||||
overrides = strategy_config.load_override(data_dir, k)
|
||||
name = (overrides.get("name") or v["name"]) if overrides else v["name"]
|
||||
desc = (overrides.get("description") or v["description"]) if overrides else v["description"]
|
||||
presets.append({"id": k, "name": name, "description": desc, "source": "builtin"})
|
||||
seen_ids.add(k)
|
||||
|
||||
# 自定义/AI 策略(不在 PRESET_STRATEGIES 中的)
|
||||
engine = getattr(request.app.state, "strategy_engine", None)
|
||||
if engine:
|
||||
for meta in engine.list_strategies():
|
||||
sid = meta["id"]
|
||||
if sid not in seen_ids:
|
||||
overrides = strategy_config.load_override(data_dir, sid)
|
||||
name = (overrides.get("name") or meta["name"]) if overrides else meta["name"]
|
||||
desc = (overrides.get("description") or meta.get("description", "")) if overrides else meta.get("description", "")
|
||||
presets.append({"id": sid, "name": name, "description": desc, "source": meta.get("source", "custom")})
|
||||
seen_ids.add(sid)
|
||||
|
||||
return {"presets": presets}
|
||||
|
||||
|
||||
@router.post("/run")
|
||||
def run_custom(req: CustomRequest, request: Request):
|
||||
repo = request.app.state.repo
|
||||
svc = ScreenerService(repo)
|
||||
as_of = req.as_of or svc.latest_date()
|
||||
if not as_of:
|
||||
raise HTTPException(status_code=400,
|
||||
detail="无可用数据日期 — enriched 表为空,请先运行盘后管道")
|
||||
result = svc.run(
|
||||
as_of=as_of,
|
||||
conditions=req.conditions,
|
||||
order_by=req.order_by,
|
||||
limit=req.limit,
|
||||
pool=req.pool,
|
||||
)
|
||||
safe_data = _safe(asdict(result))
|
||||
ext_values = _load_ext_value_maps(repo, req.ext_columns)
|
||||
return _result_with_ext(safe_data, ext_values)
|
||||
|
||||
|
||||
@router.post("/run_preset")
|
||||
def run_preset(req: PresetRequest, request: Request):
|
||||
repo = request.app.state.repo
|
||||
svc = ScreenerService(repo)
|
||||
as_of = req.as_of or svc.latest_date()
|
||||
if not as_of:
|
||||
raise HTTPException(status_code=400, detail="无可用数据日期")
|
||||
|
||||
# 加载用户保存的策略配置
|
||||
data_dir = request.app.state.repo.store.data_dir
|
||||
ext_values = _load_ext_value_maps(repo, req.ext_columns)
|
||||
overrides = strategy_config.load_override(data_dir, req.strategy_id)
|
||||
bf = overrides.get("basic_filter") if overrides else None
|
||||
dl = overrides.get("display_limit") if overrides else None
|
||||
if dl is None and overrides and "display_limit" in overrides:
|
||||
dl = 0
|
||||
|
||||
# 内置策略
|
||||
if req.strategy_id in PRESET_STRATEGIES:
|
||||
try:
|
||||
result = svc.run_preset(req.strategy_id, as_of=as_of, pool=req.pool, basic_filter=bf, display_limit=dl)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||
safe_data = _safe(asdict(result))
|
||||
_update_cache_strategy(data_dir, str(as_of), req.strategy_id, safe_data)
|
||||
return _result_with_ext(safe_data, ext_values)
|
||||
|
||||
# 自定义/AI 策略 — 通过 StrategyEngine 执行
|
||||
engine = getattr(request.app.state, "strategy_engine", None)
|
||||
if not engine:
|
||||
raise HTTPException(status_code=404, detail=f"策略引擎未初始化或策略 {req.strategy_id} 不存在")
|
||||
|
||||
try:
|
||||
result = engine.run(req.strategy_id, as_of, pool=req.pool, overrides=overrides or None)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||
|
||||
data = asdict(result)
|
||||
|
||||
if dl is not None and dl > 0:
|
||||
data["rows"] = data["rows"][:dl]
|
||||
data["total"] = min(data["total"], dl)
|
||||
|
||||
# 单跑后更新缓存中该策略的结果(保持缓存最新)
|
||||
safe_data = _safe(data)
|
||||
_update_cache_strategy(data_dir, str(as_of), req.strategy_id, safe_data)
|
||||
|
||||
return _result_with_ext(safe_data, ext_values)
|
||||
|
||||
|
||||
@router.get("/cached")
|
||||
def get_cached(
|
||||
request: Request,
|
||||
ext_columns: Optional[str] = Query(None, description="逗号分隔: config_id.field_name"),
|
||||
):
|
||||
"""读取策略结果缓存, 并叠加监控引擎本轮实时算出的结果。
|
||||
|
||||
- 盘后缓存 (strategy_cache.json): 非监控策略 / 页面秒加载用, run_all 写入。
|
||||
- 监控引擎内存结果 (latest_strategy_results): 实时行情每轮对「加入监控的策略」算出,
|
||||
不落盘 (避免与 read_cache 的 mtime 校验冲突), 在此直接叠加覆盖盘后结果。
|
||||
被监控的策略拿到新鲜数据, 非监控策略仍用盘后缓存。
|
||||
"""
|
||||
data_dir = request.app.state.repo.store.data_dir
|
||||
cached = strategy_cache.read_cache(data_dir)
|
||||
if cached is None:
|
||||
cached = {"as_of": None, "results": {}, "updated_at": None}
|
||||
|
||||
# 叠加监控引擎内存里的实时结果 (若有), 用新鲜数据覆盖同策略的盘后结果
|
||||
monitor_engine = getattr(request.app.state, "monitor_engine", None)
|
||||
if monitor_engine is not None:
|
||||
realtime_results = monitor_engine.latest_strategy_results()
|
||||
if realtime_results:
|
||||
results = dict(cached.get("results") or {})
|
||||
results.update(realtime_results)
|
||||
cached = dict(cached)
|
||||
cached["results"] = results
|
||||
# 有实时数据时, 以最新时间戳为准
|
||||
import time as _time
|
||||
cached["updated_at"] = int(_time.time() * 1000)
|
||||
|
||||
# 无任何数据 (盘后缓存空 + 无实时结果) → 返回空标记, 前端据此提示
|
||||
if not cached.get("results") and cached.get("as_of") is None:
|
||||
return {"as_of": None, "results": {}, "updated_at": None}
|
||||
|
||||
ext_values = _load_ext_value_maps(request.app.state.repo, ext_columns)
|
||||
return _cache_payload_with_ext(cached, ext_values)
|
||||
|
||||
|
||||
@router.get("/market-snapshot")
|
||||
def market_snapshot(request: Request):
|
||||
"""最新全市场轻量行情快照,供板块/概念聚合分析使用。"""
|
||||
import polars as pl
|
||||
|
||||
repo = request.app.state.repo
|
||||
svc = ScreenerService(repo)
|
||||
as_of = svc.latest_date()
|
||||
if not as_of:
|
||||
return {"as_of": None, "rows": []}
|
||||
|
||||
df = svc._load_enriched_for_date(as_of)
|
||||
if df.is_empty():
|
||||
return {"as_of": str(as_of), "rows": []}
|
||||
|
||||
if "close" in df.columns and "total_shares" in df.columns and "market_cap" not in df.columns:
|
||||
df = df.with_columns((pl.col("close") * pl.col("total_shares")).alias("market_cap"))
|
||||
if "close" in df.columns and "float_shares" in df.columns and "float_market_cap" not in df.columns:
|
||||
df = df.with_columns((pl.col("close") * pl.col("float_shares")).alias("float_market_cap"))
|
||||
|
||||
cols = [
|
||||
"symbol", "name", "close", "change_pct", "amount", "volume",
|
||||
"turnover_rate", "vol_ratio_5d", "total_shares", "float_shares",
|
||||
"market_cap", "float_market_cap", "consecutive_limit_ups",
|
||||
]
|
||||
df = df.select([c for c in cols if c in df.columns])
|
||||
rows = df.to_dicts()
|
||||
for r in rows:
|
||||
for k, v in list(r.items()):
|
||||
if isinstance(v, float) and not math.isfinite(v):
|
||||
r[k] = None
|
||||
|
||||
return {"as_of": str(as_of), "rows": rows}
|
||||
|
||||
|
||||
@router.post("/run_all")
|
||||
def run_all(request: Request, body: Optional[dict] = None):
|
||||
"""批量运行指定策略,只返回每个策略的命中数。
|
||||
|
||||
优化: 从 enriched 读取一次目标日期数据, 所有策略共享。
|
||||
body.strategy_ids: 只跑指定的策略 ID 列表, 为空则跑全部。
|
||||
"""
|
||||
from datetime import date as date_type
|
||||
|
||||
t_total = time.perf_counter()
|
||||
|
||||
body = body or {}
|
||||
repo = request.app.state.repo
|
||||
svc = ScreenerService(repo)
|
||||
|
||||
# 解析日期
|
||||
raw_date = body.get("as_of")
|
||||
if raw_date:
|
||||
as_of = date_type.fromisoformat(str(raw_date)) if isinstance(raw_date, str) else raw_date
|
||||
else:
|
||||
as_of = svc.latest_date()
|
||||
if not as_of:
|
||||
return {"as_of": None, "results": {}}
|
||||
|
||||
# 一次读取目标日期的全部数据
|
||||
t0 = time.perf_counter()
|
||||
precomputed = svc._load_enriched_for_date(as_of)
|
||||
logger.info("run_all: _load_enriched_for_date took %.1fms", (time.perf_counter() - t0) * 1000)
|
||||
|
||||
results: dict[str, dict] = {}
|
||||
data_dir = request.app.state.repo.store.data_dir
|
||||
|
||||
# 收集需要运行的策略 ID (如果指定了 strategy_ids 则只跑这些)
|
||||
requested_ids = body.get("strategy_ids")
|
||||
all_ids = list(PRESET_STRATEGIES.keys())
|
||||
engine = getattr(request.app.state, "strategy_engine", None)
|
||||
if engine:
|
||||
for meta in engine.list_strategies():
|
||||
sid = meta["id"]
|
||||
if sid not in PRESET_STRATEGIES:
|
||||
all_ids.append(sid)
|
||||
|
||||
if requested_ids and isinstance(requested_ids, list):
|
||||
id_set = set(requested_ids)
|
||||
all_ids = [sid for sid in all_ids if sid in id_set]
|
||||
|
||||
if not all_ids:
|
||||
return {"as_of": str(as_of), "results": {}}
|
||||
|
||||
# 批量预加载所有 override 配置
|
||||
t0 = time.perf_counter()
|
||||
all_overrides = strategy_config.list_overrides(data_dir)
|
||||
logger.info("run_all: list_overrides took %.1fms (%d overrides)", (time.perf_counter() - t0) * 1000, len(all_overrides))
|
||||
|
||||
# 历史策略: 只在需要时加载 (只加载 all_ids 中包含的 filter_history 策略)
|
||||
t0 = time.perf_counter()
|
||||
shared_history = None
|
||||
id_set = set(all_ids)
|
||||
if engine:
|
||||
history_strats = [
|
||||
(sid, s) for sid, s in engine._strategies.items()
|
||||
if s.filter_history_fn and sid in id_set
|
||||
]
|
||||
if history_strats:
|
||||
max_lb = min(max(s.lookback_days for _, s in history_strats), 30)
|
||||
shared_history = svc._load_enriched_history(as_of, max(1, max_lb))
|
||||
else:
|
||||
history_strats = []
|
||||
logger.info("run_all: _load_enriched_history took %.1fms (history_strats=%d)", (time.perf_counter() - t0) * 1000, len(history_strats))
|
||||
|
||||
for sid in all_ids:
|
||||
try:
|
||||
overrides = all_overrides.get(sid, {})
|
||||
bf = overrides.get("basic_filter") if overrides else None
|
||||
dl = overrides.get("display_limit") if overrides else None
|
||||
if dl is None and overrides and "display_limit" in overrides:
|
||||
dl = 0
|
||||
|
||||
if sid in PRESET_STRATEGIES:
|
||||
r = svc.run_preset(sid, as_of=as_of, precomputed=precomputed, basic_filter=bf, display_limit=dl)
|
||||
else:
|
||||
r = engine.run(
|
||||
sid, as_of, overrides=overrides or None,
|
||||
precomputed=precomputed, precomputed_history=shared_history,
|
||||
)
|
||||
if dl is not None and dl > 0:
|
||||
r.rows = r.rows[:dl]
|
||||
r.total = min(r.total, dl)
|
||||
|
||||
safe_rows = _safe(asdict(r)).get("rows", [])
|
||||
results[sid] = {"total": r.total, "as_of": str(as_of), "rows": safe_rows}
|
||||
except (ValueError, Exception):
|
||||
continue
|
||||
|
||||
elapsed = (time.perf_counter() - t_total) * 1000
|
||||
logger.info("run_all: total took %.1fms (%d strategies)", elapsed, len(all_ids))
|
||||
|
||||
# 写入策略缓存 (供页面秒加载)
|
||||
if results:
|
||||
try:
|
||||
strategy_cache.write_cache(data_dir, str(as_of), results)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
ext_values = _load_ext_value_maps(repo, body.get("ext_columns"))
|
||||
return {"as_of": str(as_of), "results": _results_with_ext(results, ext_values)}
|
||||
|
||||
|
||||
@router.get("/limit-ladder")
|
||||
def limit_ladder(
|
||||
request: Request,
|
||||
as_of: Optional[date] = None,
|
||||
direction: str = Query("up", description="up=涨停梯队 | down=跌停梯队"),
|
||||
ext_columns: Optional[str] = Query(None, description="逗号分隔: config_id.field_name"),
|
||||
):
|
||||
"""连板/连跌梯队 — 按连板数分组, 含三状态。
|
||||
返回: tiers = [{ boards, count, stocks: [{symbol,name,change_pct,status,...}] }]
|
||||
|
||||
direction=up (默认):
|
||||
status: limit_up=涨停 | broken=炸板(摸板未封) | failed=断板(晋级失败)
|
||||
direction=down:
|
||||
status: limit_down=跌停 | recovery=翘板(跌停后回升,含收阳条件) | failed=止跌(昨日跌停今日未跌停也未翘板)
|
||||
|
||||
ext_columns: 动态 JOIN 扩展数据, 如 "concept.concept,industry.industry"
|
||||
"""
|
||||
from datetime import timedelta
|
||||
|
||||
import polars as pl
|
||||
|
||||
is_down = direction == "down"
|
||||
|
||||
# 按 direction 参数化字段映射
|
||||
if is_down:
|
||||
sig_col = "signal_limit_down"
|
||||
consec_col = "consecutive_limit_downs"
|
||||
broken_col = "signal_limit_down_recovery"
|
||||
status_main, status_broken, status_failed = "limit_down", "recovery", "failed"
|
||||
else:
|
||||
sig_col = "signal_limit_up"
|
||||
consec_col = "consecutive_limit_ups"
|
||||
broken_col = "signal_broken_limit_up"
|
||||
status_main, status_broken, status_failed = "limit_up", "broken", "failed"
|
||||
|
||||
repo = request.app.state.repo
|
||||
svc = ScreenerService(repo)
|
||||
as_of = as_of or svc.latest_date()
|
||||
if not as_of:
|
||||
raise HTTPException(status_code=400, detail="无可用数据日期")
|
||||
|
||||
df = svc._load_enriched_for_date(as_of)
|
||||
if df.is_empty():
|
||||
return {"as_of": str(as_of), "tiers": [], "counts": {"up": 0, "down": 0}}
|
||||
|
||||
# 双方向涨跌停计数(不论当前 direction, 前端始终同时显示)
|
||||
count_up_raw = int(df.filter(pl.col("signal_limit_up").fill_null(False)).height) if "signal_limit_up" in df.columns else 0
|
||||
count_down_raw = int(df.filter(pl.col("signal_limit_down").fill_null(False)).height) if "signal_limit_down" in df.columns else 0
|
||||
|
||||
# 双方向 sealed 修正: 减去各自的假涨停(假涨停已归炸板, 不计入涨停数)
|
||||
depth_svc_global = getattr(request.app.state, "depth_service", None)
|
||||
fake_up = 0
|
||||
fake_down = 0
|
||||
sealed_up_ready = False
|
||||
sealed_down_ready = False
|
||||
if depth_svc_global:
|
||||
up_map = depth_svc_global.get_sealed_map(as_of, is_down=False)
|
||||
down_map = depth_svc_global.get_sealed_map(as_of, is_down=True)
|
||||
sealed_up_ready = bool(up_map) and depth_svc_global.is_sealed_ready(as_of)
|
||||
sealed_down_ready = bool(down_map) and depth_svc_global.is_sealed_ready(as_of)
|
||||
if up_map:
|
||||
fake_up = sum(1 for v in up_map.values() if v.get("sealed") is False)
|
||||
if down_map:
|
||||
fake_down = sum(1 for v in down_map.values() if v.get("sealed") is False)
|
||||
count_up = count_up_raw - fake_up if sealed_up_ready else count_up_raw
|
||||
count_down = count_down_raw - fake_down if sealed_down_ready else count_down_raw
|
||||
|
||||
# 双方向 sealed 明细(供前端弹窗同时显示涨跌停)
|
||||
def _count_sealed(m: dict, ready: bool):
|
||||
if not m or not ready:
|
||||
return {"real": 0, "fake": 0, "pending": 0}
|
||||
real = sum(1 for v in m.values() if v.get("sealed") is True)
|
||||
fake = sum(1 for v in m.values() if v.get("sealed") is False)
|
||||
pending = sum(1 for v in m.values() if v.get("sealed") is None)
|
||||
return {"real": real, "fake": fake, "pending": pending}
|
||||
sealed_counts_up = _count_sealed(up_map, sealed_up_ready)
|
||||
sealed_counts_down = _count_sealed(down_map, sealed_down_ready)
|
||||
|
||||
# 加载前一日数据获取 prev consecutive_limit_ups/downs
|
||||
prev_consec: pl.DataFrame = pl.DataFrame()
|
||||
for delta in range(1, 10):
|
||||
candidate = as_of - timedelta(days=delta)
|
||||
df_prev = svc._load_enriched_for_date(candidate)
|
||||
if not df_prev.is_empty() and consec_col in df_prev.columns:
|
||||
prev_consec = df_prev.select(
|
||||
"symbol",
|
||||
pl.col(consec_col).alias("prev_consec"),
|
||||
)
|
||||
break
|
||||
|
||||
if not prev_consec.is_empty():
|
||||
df = df.join(prev_consec, on="symbol", how="left")
|
||||
else:
|
||||
df = df.with_columns(pl.lit(0).cast(pl.UInt32).alias("prev_consec"))
|
||||
|
||||
# 表达式
|
||||
is_limit = pl.col(sig_col).fill_null(False) if sig_col in df.columns else pl.lit(False)
|
||||
is_broken = pl.col(broken_col).fill_null(False) if broken_col in df.columns else pl.lit(False)
|
||||
consec = pl.col(consec_col).fill_null(0) if consec_col in df.columns else pl.lit(0)
|
||||
prev_c = pl.col("prev_consec").fill_null(0)
|
||||
|
||||
# 计算 status + boards (结构涨跌停对称, 仅字段与字面量不同)
|
||||
is_failed = ~is_limit & ~is_broken & (prev_c > 0)
|
||||
df = df.with_columns([
|
||||
pl.when(is_limit).then(pl.lit(status_main))
|
||||
.when(is_broken).then(pl.lit(status_broken))
|
||||
.when(is_failed).then(pl.lit(status_failed))
|
||||
.otherwise(None).alias("status"),
|
||||
pl.when(is_limit).then(consec)
|
||||
.when(is_broken | is_failed).then(prev_c + 1)
|
||||
.otherwise(0).cast(pl.UInt32).alias("boards"),
|
||||
])
|
||||
|
||||
df = df.filter(pl.col("status").is_not_null() & (pl.col("boards") > 0))
|
||||
|
||||
# ── 五档 sealed 叠加(独立旁路, 不改 signal_limit_up) ──
|
||||
# 假涨停(收盘价=涨停价但卖一有量)从 limit 降级为 broken(归炸板视图)
|
||||
# 真涨停保留 + 附封单量; sealed=null(待确认/降级)保持原状
|
||||
depth_svc = getattr(request.app.state, "depth_service", None)
|
||||
sealed_ready = False
|
||||
sealed_age: float | None = None
|
||||
if depth_svc:
|
||||
sealed_map = depth_svc.get_sealed_map(as_of, is_down=is_down)
|
||||
sealed_ready = bool(sealed_map) and depth_svc.is_sealed_ready(as_of)
|
||||
sealed_age = depth_svc.get_sealed_age(as_of) if sealed_ready else None
|
||||
|
||||
if sealed_map:
|
||||
# 构建 sealed 列(symbol → sealed bool, vol)
|
||||
sym_sealed = {s: v.get("sealed") for s, v in sealed_map.items()}
|
||||
sym_vol = {s: v.get("vol") for s, v in sealed_map.items()}
|
||||
|
||||
# JOIN sealed: 对每只 status=main 的票, 看 sealed 值
|
||||
sealed_rows = pl.DataFrame({
|
||||
"symbol": list(sym_sealed.keys()),
|
||||
"_sealed": list(sym_sealed.values()),
|
||||
"_sealed_vol": list(sym_vol.values()),
|
||||
}) if sym_sealed else pl.DataFrame()
|
||||
|
||||
if not sealed_rows.is_empty():
|
||||
df = df.join(sealed_rows, on="symbol", how="left")
|
||||
# 假涨停(main 状态但 sealed=False)→ 降级为 broken
|
||||
df = df.with_columns(
|
||||
pl.when(
|
||||
(pl.col("status") == status_main)
|
||||
& pl.col("_sealed").is_not_null()
|
||||
& (pl.col("_sealed") == False) # noqa: E712
|
||||
).then(pl.lit(status_broken))
|
||||
.otherwise(pl.col("status")).alias("status"),
|
||||
# sealed_status: real/fake/pending/null
|
||||
pl.when(
|
||||
(pl.col("status") == status_main)
|
||||
& (pl.col("_sealed") == True) # noqa: E712
|
||||
).then(pl.lit("real"))
|
||||
.when(
|
||||
(pl.col("_sealed") == False) # noqa: E712
|
||||
).then(pl.lit("fake"))
|
||||
.when(
|
||||
(pl.col("status") == status_main)
|
||||
& pl.col("_sealed").is_null()
|
||||
).then(pl.lit("pending"))
|
||||
.otherwise(None).alias("sealed_status"),
|
||||
pl.col("_sealed_vol").alias("sealed_vol"),
|
||||
).drop(["_sealed", "_sealed_vol"])
|
||||
else:
|
||||
df = df.with_columns(
|
||||
pl.lit(None).alias("sealed_status"),
|
||||
pl.lit(None).alias("sealed_vol"),
|
||||
)
|
||||
else:
|
||||
df = df.with_columns(
|
||||
pl.lit(None).alias("sealed_status"),
|
||||
pl.lit(None).alias("sealed_vol"),
|
||||
)
|
||||
else:
|
||||
df = df.with_columns(
|
||||
pl.lit(None).alias("sealed_status"),
|
||||
pl.lit(None).alias("sealed_vol"),
|
||||
)
|
||||
|
||||
# 动态 JOIN 扩展数据
|
||||
ext_specs = _parse_ext_columns(ext_columns) if ext_columns else []
|
||||
ext_col_names: list[str] = []
|
||||
if ext_specs:
|
||||
db = repo.store.db
|
||||
data_dir = repo.store.data_dir
|
||||
from app.services.ext_data import ExtConfigStore
|
||||
|
||||
ext_store = ExtConfigStore(data_dir)
|
||||
configs = {c.id: c for c in ext_store.load_all()}
|
||||
|
||||
for config_id, field_name in ext_specs:
|
||||
view_name = f"ext_{config_id}"
|
||||
ext_col_name = f"{config_id}__{field_name}"
|
||||
try:
|
||||
ext_df = pl.from_arrow(db.query(
|
||||
f"SELECT symbol, \"{field_name}\" FROM {view_name}"
|
||||
).arrow())
|
||||
if not ext_df.is_empty() and "symbol" in ext_df.columns:
|
||||
ext_df = ext_df.rename({field_name: ext_col_name})
|
||||
df = df.join(ext_df.select(["symbol", ext_col_name]), on="symbol", how="left")
|
||||
ext_col_names.append(ext_col_name)
|
||||
except Exception:
|
||||
cfg = configs.get(config_id)
|
||||
if cfg:
|
||||
try:
|
||||
from app.api.ext_data import _parquet_glob
|
||||
glob = _parquet_glob(cfg, data_dir)
|
||||
ext_df = pl.read_parquet(glob)
|
||||
if not ext_df.is_empty() and "symbol" in ext_df.columns and field_name in ext_df.columns:
|
||||
ext_df = ext_df.select(["symbol", field_name]).rename({field_name: ext_col_name})
|
||||
df = df.join(ext_df, on="symbol", how="left")
|
||||
ext_col_names.append(ext_col_name)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 选择输出列
|
||||
cols = ["symbol", "name", "close", "change_pct", "boards", "status", consec_col, "sealed_status", "sealed_vol"] + ext_col_names
|
||||
df = df.select([c for c in cols if c in df.columns])
|
||||
# 排序: boards 降序, status 按主状态→炸/翘→断/止
|
||||
status_order = pl.when(pl.col("status") == status_main).then(0)
|
||||
status_order = status_order.when(pl.col("status") == status_broken).then(1)
|
||||
status_order = status_order.otherwise(2).alias("_status_order")
|
||||
df = df.with_columns(status_order).sort(["boards", "_status_order"], descending=[True, False]).drop("_status_order")
|
||||
|
||||
rows = df.to_dicts()
|
||||
for r in rows:
|
||||
for k, v in list(r.items()):
|
||||
if isinstance(v, float) and not math.isfinite(v):
|
||||
r[k] = None
|
||||
|
||||
# 按 boards 分组
|
||||
tiers: dict[int, list] = {}
|
||||
for r in rows:
|
||||
n = int(r.get("boards") or 0)
|
||||
tiers.setdefault(n, []).append(r)
|
||||
|
||||
tier_list = [
|
||||
{"boards": n, "count": len(stocks), "stocks": stocks}
|
||||
for n, stocks in sorted(tiers.items(), key=lambda x: -x[0])
|
||||
]
|
||||
|
||||
return {
|
||||
"as_of": str(as_of),
|
||||
"tiers": tier_list,
|
||||
"counts": {"up": count_up, "down": count_down},
|
||||
"counts_raw": {"up": count_up_raw, "down": count_down_raw},
|
||||
"sealed_ready": sealed_ready,
|
||||
"sealed_age": round(sealed_age, 0) if sealed_age is not None else None,
|
||||
"sealed_counts": {
|
||||
"real": sum(1 for t in tier_list for s in t.get("stocks", []) if s.get("sealed_status") == "real"),
|
||||
"fake": sum(1 for t in tier_list for s in t.get("stocks", []) if s.get("sealed_status") == "fake"),
|
||||
"pending": sum(1 for t in tier_list for s in t.get("stocks", []) if s.get("sealed_status") == "pending"),
|
||||
},
|
||||
"sealed_counts_up": sealed_counts_up,
|
||||
"sealed_counts_down": sealed_counts_down,
|
||||
}
|
||||
|
||||
|
||||
def _parse_ext_columns(ext_columns: str) -> list[tuple[str, str]]:
|
||||
"""解析 'config_id1.field1,config_id2.field2' 为 [(config_id, field_name), ...]。"""
|
||||
result = []
|
||||
for part in ext_columns.split(","):
|
||||
part = part.strip()
|
||||
if "." not in part:
|
||||
continue
|
||||
config_id, field_name = part.split(".", 1)
|
||||
config_id = config_id.strip()
|
||||
field_name = field_name.strip()
|
||||
if not config_id or not field_name:
|
||||
continue
|
||||
if not _EXT_IDENT_RE.match(config_id) or "\x00" in field_name:
|
||||
continue
|
||||
result.append((config_id, field_name))
|
||||
return result
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,100 @@
|
||||
"""自定义信号 API 路由 — HTTP 请求 → 调用 custom_signals 模块 → 返回响应。
|
||||
|
||||
只做胶水:校验 → 持久化 → 失效缓存。不含表达式编译逻辑。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.strategy import custom_signals
|
||||
|
||||
router = APIRouter(prefix="/api/custom-signals", tags=["custom-signals"])
|
||||
|
||||
|
||||
def _data_dir(request: Request) -> Path:
|
||||
return request.app.state.repo.store.data_dir
|
||||
|
||||
|
||||
def _invalidate() -> None:
|
||||
"""失效 pipeline 的自定义信号缓存,下次计算重新加载。"""
|
||||
from app.indicators.pipeline import invalidate_custom_signals
|
||||
invalidate_custom_signals()
|
||||
|
||||
|
||||
class ConditionModel(BaseModel):
|
||||
left: str # 字段名(须在白名单)
|
||||
op: str # > >= < <= == !=
|
||||
right: str # "field:xxx" 或数字字符串
|
||||
|
||||
|
||||
class SignalModel(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
kind: str # entry | exit | both
|
||||
conditions: list[ConditionModel]
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
# ── 字段选项 / 运算符 ───────────────────────────────────
|
||||
|
||||
|
||||
@router.get("/options")
|
||||
def get_options():
|
||||
"""返回可选字段与运算符,供前端下拉框使用。"""
|
||||
# 字段带中文标签(取自 ENRICHED_COLUMNS,回退为字段名本身)
|
||||
from app.indicators.pipeline import ENRICHED_COLUMNS
|
||||
|
||||
fields = [
|
||||
{"key": f, "label": ENRICHED_COLUMNS.get(f, f)}
|
||||
for f in sorted(custom_signals.ALLOWED_FIELDS)
|
||||
]
|
||||
return {
|
||||
"fields": fields,
|
||||
"operators": [">", ">=", "<", "<=", "==", "!="],
|
||||
"kinds": [
|
||||
{"key": "entry", "label": "买入"},
|
||||
{"key": "exit", "label": "卖出"},
|
||||
{"key": "both", "label": "买卖通用"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
# ── 列表 ───────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_signals(request: Request):
|
||||
sigs = custom_signals.load_all(_data_dir(request))
|
||||
return {"signals": sigs}
|
||||
|
||||
|
||||
# ── 新建 / 更新 ────────────────────────────────────────
|
||||
|
||||
|
||||
@router.post("")
|
||||
def save_signal(req: SignalModel, request: Request):
|
||||
sig = req.model_dump()
|
||||
try:
|
||||
custom_signals.validate(sig)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
custom_signals.save_one(_data_dir(request), sig)
|
||||
_invalidate()
|
||||
return {"ok": True, "signal": sig}
|
||||
|
||||
|
||||
# ── 删除 ───────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.delete("/{signal_id}")
|
||||
def delete_signal(signal_id: str, request: Request):
|
||||
if not custom_signals.ID_RE.match(signal_id):
|
||||
raise HTTPException(status_code=400, detail="信号 id 非法")
|
||||
deleted = custom_signals.delete_one(_data_dir(request), signal_id)
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=404, detail="信号不存在")
|
||||
_invalidate()
|
||||
return {"ok": True}
|
||||
@@ -0,0 +1,217 @@
|
||||
"""个股分析 API — 关键价位 + AI 四维分析 + 报告持久化。
|
||||
|
||||
路由前缀: /api/stock-analysis
|
||||
|
||||
端点:
|
||||
GET /levels?symbol= 11 类关键价位(图表 markLine 数据源)
|
||||
POST /analyze AI 流式四维分析(NDJSON)
|
||||
GET /reports 历史报告列表
|
||||
POST /reports 保存一条报告
|
||||
DELETE /reports/{report_id} 删除一条报告
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
from datetime import date, timedelta
|
||||
|
||||
import polars as pl
|
||||
from fastapi import APIRouter, HTTPException, Query, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.indicators.levels import compute_levels, summarize_levels
|
||||
from app.services import stock_reports
|
||||
from app.services.stock_analyzer import analyze_stock_stream
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/stock-analysis", tags=["stock-analysis"])
|
||||
|
||||
|
||||
def _to_float_list(series: pl.Series) -> list:
|
||||
"""polars Series → JSON 安全的 float 列表(null/NaN → None)。"""
|
||||
out: list = []
|
||||
for v in series.to_list():
|
||||
if v is None:
|
||||
out.append(None)
|
||||
continue
|
||||
try:
|
||||
f = float(v)
|
||||
out.append(round(f, 2) if math.isfinite(f) else None)
|
||||
except (TypeError, ValueError):
|
||||
out.append(None)
|
||||
return out
|
||||
|
||||
|
||||
def _build_series(df: pl.DataFrame) -> dict:
|
||||
"""提取带状指标(布林带 / Keltner通道 / ATR止损)的每日时间序列。
|
||||
|
||||
这些指标的本质是"每日一条线",随 MA/ATR/σ 漂移,画成曲线才能体现通道形态。
|
||||
其余固定价位(枢轴/前高前低等)不在此,仍用水平 markLine。
|
||||
|
||||
返回结构(每个 value 都是按日期对齐的数组):
|
||||
{
|
||||
"boll": {"upper": [...], "lower": [...]},
|
||||
"keltner_s": {"upper": [...], "lower": [...]}, # 短期 MA20±2ATR
|
||||
"keltner_m": {"upper": [...], "lower": [...]}, # 中期 MA60±2.5ATR
|
||||
"keltner_l": {"upper": [...], "lower": [...]}, # 长期 MA120±3ATR
|
||||
"atr": {"stop_loss": [...], "take_profit": [...]}, # close∓2ATR
|
||||
}
|
||||
"""
|
||||
if df.is_empty() or "close" not in df.columns:
|
||||
return {}
|
||||
|
||||
out: dict[str, dict] = {}
|
||||
close = df["close"]
|
||||
has_atr = "atr_14" in df.columns
|
||||
|
||||
# 布林带(上/下/中轨;中轨 = MA20,数据层已预计算)
|
||||
if "boll_upper" in df.columns and "boll_lower" in df.columns:
|
||||
out["boll"] = {
|
||||
"upper": _to_float_list(df["boll_upper"]),
|
||||
"lower": _to_float_list(df["boll_lower"]),
|
||||
"mid": _to_float_list(df["ma20"]) if "ma20" in df.columns else None,
|
||||
}
|
||||
|
||||
# Keltner 通道三档(需要 ATR)
|
||||
if has_atr:
|
||||
atr = df["atr_14"]
|
||||
# MA120 现场算(不在预计算列中)
|
||||
ma120 = df.select(pl.col("close").rolling_mean(120))["close"] if df.height >= 120 else None
|
||||
|
||||
def _channel(ma: pl.Series, n: float) -> dict:
|
||||
return {
|
||||
"upper": _to_float_list(ma + n * atr),
|
||||
"lower": _to_float_list(ma - n * atr),
|
||||
}
|
||||
|
||||
if "ma20" in df.columns:
|
||||
out["keltner_s"] = _channel(df["ma20"], 2.0)
|
||||
if "ma60" in df.columns:
|
||||
out["keltner_m"] = _channel(df["ma60"], 2.5)
|
||||
if ma120 is not None:
|
||||
out["keltner_l"] = _channel(ma120, 3.0)
|
||||
|
||||
# ATR 止损/止盈: close ± 2×ATR(跟随行情漂移的动态止损线)
|
||||
out["atr"] = {
|
||||
"stop_loss": _to_float_list(close - 2 * atr),
|
||||
"take_profit": _to_float_list(close + 2 * atr),
|
||||
}
|
||||
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/levels")
|
||||
def get_levels(
|
||||
request: Request,
|
||||
symbol: str = Query(..., description="标的代码,如 000001.SZ"),
|
||||
days: int = Query(120, ge=30, le=500, description="计算样本天数"),
|
||||
):
|
||||
"""计算 11 类关键价位(成交密集区压力支撑 / 枢轴点 / 前高前低 /
|
||||
布林带 / Keltner短中长 / ATR止损 / 缺口 / 斐波那契 / 整数关口)。
|
||||
|
||||
返回 {levels: {sr, pivot, extreme, boll, keltner_s, keltner_m, keltner_l,
|
||||
atr_stop, gap, fib, round}, close, summary, dates, series}。
|
||||
前端按 levels 的 key 渲染开关按钮,逐组显隐 markLine / 曲线。
|
||||
"""
|
||||
if not symbol:
|
||||
raise HTTPException(400, "symbol 不能为空")
|
||||
|
||||
repo = request.app.state.repo
|
||||
end = date.today()
|
||||
start = end - timedelta(days=days * 2)
|
||||
df = repo.get_daily(symbol, start, end)
|
||||
if df.is_empty():
|
||||
return {"levels": {"sr": [], "pivot": [], "extreme": [],
|
||||
"boll": [], "keltner_s": [], "keltner_m": [], "keltner_l": [],
|
||||
"atr_stop": [], "gap": [], "fib": [], "round": []},
|
||||
"close": None, "summary": "无数据", "symbol": symbol,
|
||||
"dates": [], "series": {}}
|
||||
|
||||
levels = compute_levels(df)
|
||||
close = float(df.tail(1)["close"][0]) if "close" in df.columns else None
|
||||
# 日期 + 带状曲线序列(供前端画 Keltner/ATR/布林带曲线)
|
||||
dates = df["date"].to_list()
|
||||
series = _build_series(df)
|
||||
return {
|
||||
"levels": levels,
|
||||
"close": close,
|
||||
"summary": summarize_levels(levels, close),
|
||||
"symbol": symbol,
|
||||
"dates": [str(d) for d in dates],
|
||||
"series": series,
|
||||
}
|
||||
|
||||
|
||||
class AnalyzeRequest(BaseModel):
|
||||
"""AI 个股分析请求。"""
|
||||
symbol: str
|
||||
focus: str = "" # 可选:用户追加的分析关注点
|
||||
|
||||
|
||||
@router.post("/analyze")
|
||||
async def analyze_stock(request: Request, req: AnalyzeRequest):
|
||||
"""AI 个股四维分析 — NDJSON 流式返回。
|
||||
|
||||
组合 K 线(技术指标)+ 财务表 + 关键价位 → 实战派提示词 →
|
||||
流式调用 LLM → 逐 chunk 以 NDJSON 推给前端(每行一个 JSON)。
|
||||
"""
|
||||
if not req.symbol:
|
||||
raise HTTPException(400, "symbol 不能为空")
|
||||
|
||||
repo = request.app.state.repo
|
||||
data_dir = repo.store.data_dir
|
||||
|
||||
async def stream_gen():
|
||||
async for chunk in analyze_stock_stream(repo, data_dir, req.symbol, req.focus):
|
||||
yield chunk + "\n"
|
||||
|
||||
return StreamingResponse(
|
||||
stream_gen(),
|
||||
media_type="application/x-ndjson",
|
||||
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 报告 CRUD(历史报告持久化)
|
||||
# ================================================================
|
||||
|
||||
class SaveReportRequest(BaseModel):
|
||||
"""保存一条 AI 个股分析报告。"""
|
||||
symbol: str
|
||||
name: str = ""
|
||||
focus: str = ""
|
||||
content: str
|
||||
summary: str = ""
|
||||
close: float | None = None
|
||||
levels: dict | None = None
|
||||
|
||||
|
||||
@router.get("/reports")
|
||||
def list_reports(request: Request):
|
||||
"""获取全部历史报告(按时间降序,后端已裁剪到上限)。"""
|
||||
return {"reports": stock_reports.list_reports()}
|
||||
|
||||
|
||||
@router.post("/reports")
|
||||
def save_report(request: Request, req: SaveReportRequest):
|
||||
"""保存一条报告。"""
|
||||
report = stock_reports.save_report({
|
||||
"symbol": req.symbol,
|
||||
"name": req.name,
|
||||
"focus": req.focus,
|
||||
"content": req.content,
|
||||
"summary": req.summary,
|
||||
"close": req.close,
|
||||
"levels": req.levels,
|
||||
})
|
||||
return {"ok": True, "report": report}
|
||||
|
||||
|
||||
@router.delete("/reports/{report_id}")
|
||||
def delete_report(request: Request, report_id: str):
|
||||
"""删除一条报告。"""
|
||||
ok = stock_reports.delete_report(report_id)
|
||||
return {"ok": ok}
|
||||
@@ -0,0 +1,441 @@
|
||||
"""策略 API 路由 — HTTP 请求 → 调用策略模块 → 返回响应。
|
||||
|
||||
只做胶水,不含业务逻辑。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import asdict
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.strategy import config as strategy_config
|
||||
from app.strategy.engine import StrategyEngine, StrategyDef
|
||||
from app.strategy.ai_generator import AIStrategyGenerator
|
||||
from app.strategy.prompt_builder import build_step1, build_step2
|
||||
from app.strategy.monitor import StrategyMonitorService, StrategyAlert
|
||||
|
||||
router = APIRouter(prefix="/api/strategies", tags=["strategies"])
|
||||
|
||||
# ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _get_engine(request: Request) -> StrategyEngine:
|
||||
engine = getattr(request.app.state, "strategy_engine", None)
|
||||
if not engine:
|
||||
raise HTTPException(status_code=503, detail="策略引擎未初始化")
|
||||
return engine
|
||||
|
||||
|
||||
def _get_monitor(request: Request) -> StrategyMonitorService:
|
||||
mon = getattr(request.app.state, "strategy_monitor", None)
|
||||
if not mon:
|
||||
raise HTTPException(status_code=503, detail="策略监控未初始化")
|
||||
return mon
|
||||
|
||||
|
||||
def _data_dir(request: Request) -> Path:
|
||||
return request.app.state.repo.store.data_dir
|
||||
|
||||
|
||||
def _safe(result_dict: dict) -> dict:
|
||||
rows = result_dict.get("rows", [])
|
||||
for r in rows:
|
||||
for k, v in list(r.items()):
|
||||
if isinstance(v, float) and not math.isfinite(v):
|
||||
r[k] = None
|
||||
return result_dict
|
||||
|
||||
|
||||
def _strategy_detail(s: StrategyDef, overrides: dict | None = None) -> dict:
|
||||
"""策略详情(含用户覆盖)"""
|
||||
bf = {**s.basic_filter}
|
||||
scoring = dict(s.meta.get("scoring", {}))
|
||||
params_defaults = {p["id"]: p["default"] for p in s.meta.get("params", [])}
|
||||
|
||||
if overrides:
|
||||
if overrides.get("basic_filter"):
|
||||
bf.update(overrides["basic_filter"])
|
||||
if overrides.get("scoring"):
|
||||
scoring.update(overrides["scoring"])
|
||||
# 用户保存的参数覆盖默认值: 合并进 params_defaults, 前端据此回显
|
||||
if overrides.get("params"):
|
||||
params_defaults.update(overrides["params"])
|
||||
|
||||
# 名称/描述可被用户覆盖
|
||||
name = overrides.get("name", s.meta.get("name", "")) if overrides else s.meta.get("name", "")
|
||||
description = overrides.get("description", s.meta.get("description", "")) if overrides else s.meta.get("description", "")
|
||||
|
||||
return {
|
||||
"id": s.meta["id"],
|
||||
"name": name or s.meta.get("name", ""),
|
||||
"description": description or s.meta.get("description", ""),
|
||||
"tags": s.meta.get("tags", []),
|
||||
"source": s.source,
|
||||
"version": s.meta.get("version", "1.0.0"),
|
||||
"basic_filter": bf,
|
||||
"params": s.meta.get("params", []),
|
||||
"params_defaults": params_defaults,
|
||||
"scoring": scoring,
|
||||
"entry_signals": s.entry_signals,
|
||||
"exit_signals": s.exit_signals,
|
||||
"stop_loss": overrides.get("stop_loss", s.stop_loss) if overrides else s.stop_loss,
|
||||
"take_profit": getattr(s, "take_profit", None),
|
||||
"trailing_stop": getattr(s, "trailing_stop", None),
|
||||
"trailing_take_profit_activate": getattr(s, "trailing_take_profit_activate", None),
|
||||
"trailing_take_profit_drawdown": getattr(s, "trailing_take_profit_drawdown", None),
|
||||
"max_hold_days": overrides.get("max_hold_days", s.max_hold_days) if overrides else s.max_hold_days,
|
||||
"alerts": s.alerts,
|
||||
"order_by": s.meta.get("order_by", "score"),
|
||||
"descending": s.meta.get("descending", True),
|
||||
"limit": s.meta.get("limit", 30),
|
||||
"display_limit": overrides.get("display_limit") if overrides and "display_limit" in overrides else None,
|
||||
}
|
||||
|
||||
|
||||
# ── Request Models ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
class RunRequest(BaseModel):
|
||||
strategy_id: str
|
||||
as_of: date | None = None
|
||||
pool: list[str] | None = None
|
||||
params: dict | None = None
|
||||
|
||||
|
||||
class RunAllRequest(BaseModel):
|
||||
as_of: date | None = None
|
||||
|
||||
|
||||
class SaveConfigRequest(BaseModel):
|
||||
strategy_id: str
|
||||
overrides: dict
|
||||
|
||||
|
||||
class AIGenerateRequest(BaseModel):
|
||||
prompt: str
|
||||
|
||||
|
||||
class AISaveRequest(BaseModel):
|
||||
code: str
|
||||
strategy_id: str
|
||||
|
||||
|
||||
class MonitorStartRequest(BaseModel):
|
||||
strategy_id: str
|
||||
|
||||
|
||||
# ── 列表 / 详情 ─────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_strategies(request: Request):
|
||||
engine = _get_engine(request)
|
||||
data_dir = _data_dir(request)
|
||||
all_overrides = strategy_config.list_overrides(data_dir)
|
||||
|
||||
result = []
|
||||
for meta in engine.list_strategies():
|
||||
sid = meta["id"]
|
||||
s = engine.get(sid)
|
||||
overrides = all_overrides.get(sid)
|
||||
result.append(_strategy_detail(s, overrides))
|
||||
return {"strategies": result}
|
||||
|
||||
|
||||
@router.get("/{strategy_id}")
|
||||
def get_strategy(strategy_id: str, request: Request):
|
||||
engine = _get_engine(request)
|
||||
try:
|
||||
s = engine.get(strategy_id)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||
overrides = strategy_config.load_override(_data_dir(request), strategy_id)
|
||||
return _strategy_detail(s, overrides or None)
|
||||
|
||||
|
||||
# ── 执行选股 ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.post("/run")
|
||||
def run_strategy(req: RunRequest, request: Request):
|
||||
engine = _get_engine(request)
|
||||
data_dir = _data_dir(request)
|
||||
|
||||
# 读取用户覆盖配置
|
||||
overrides = strategy_config.load_override(data_dir, req.strategy_id)
|
||||
params = req.params or {}
|
||||
# 合并用户保存的策略参数
|
||||
if overrides.get("params"):
|
||||
merged = dict(overrides["params"])
|
||||
merged.update(params) # 请求里的优先
|
||||
params = merged
|
||||
|
||||
# 确定日期
|
||||
as_of = req.as_of
|
||||
if not as_of:
|
||||
from app.services.screener import ScreenerService
|
||||
svc = ScreenerService(request.app.state.repo)
|
||||
as_of = svc.latest_date()
|
||||
if not as_of:
|
||||
raise HTTPException(status_code=400, detail="无可用数据日期")
|
||||
|
||||
try:
|
||||
result = engine.run(
|
||||
req.strategy_id, as_of,
|
||||
pool=req.pool,
|
||||
params=params,
|
||||
overrides=overrides or None,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||
|
||||
return _safe(asdict(result))
|
||||
|
||||
|
||||
@router.post("/run-all")
|
||||
def run_all(req: RunAllRequest, request: Request):
|
||||
engine = _get_engine(request)
|
||||
data_dir = _data_dir(request)
|
||||
|
||||
as_of = req.as_of
|
||||
if not as_of:
|
||||
from app.services.screener import ScreenerService
|
||||
svc = ScreenerService(request.app.state.repo)
|
||||
as_of = svc.latest_date()
|
||||
if not as_of:
|
||||
return {"as_of": None, "results": {}}
|
||||
|
||||
all_overrides = strategy_config.list_overrides(data_dir)
|
||||
results: dict[str, dict] = {}
|
||||
for sid, result in engine.run_all(as_of, overrides_map=all_overrides).items():
|
||||
results[sid] = {"total": result.total, "as_of": str(as_of)}
|
||||
|
||||
return {"as_of": str(as_of), "results": results}
|
||||
|
||||
|
||||
# ── 配置持久化 ───────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.post("/config")
|
||||
def save_config(req: SaveConfigRequest, request: Request):
|
||||
engine = _get_engine(request)
|
||||
if not engine.has(req.strategy_id):
|
||||
raise HTTPException(status_code=404, detail=f"策略 {req.strategy_id} 不存在")
|
||||
|
||||
# 剥离与策略默认值相同的字段,只保存用户真正修改过的值
|
||||
overrides = _strip_defaults(req.strategy_id, req.overrides, engine)
|
||||
|
||||
strategy_config.save_override(_data_dir(request), req.strategy_id, overrides)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
def _strip_defaults(strategy_id: str, overrides: dict, engine) -> dict:
|
||||
"""剥离与策略默认值相同的字段,避免默认值被固化到 override 中。
|
||||
|
||||
核心问题: 前端把策略的默认 basic_filter 全量发回后端保存,
|
||||
导致隐含的默认过滤条件 (如 market_cap_min, amount_min) 被写入 override 文件。
|
||||
即使前端 UI 不展示这些字段,它们仍会在策略运行时生效。
|
||||
"""
|
||||
s = engine.get(strategy_id)
|
||||
result = dict(overrides)
|
||||
|
||||
# 处理 basic_filter: 只保留与策略默认值不同的键
|
||||
bf = result.get("basic_filter")
|
||||
if bf and isinstance(bf, dict):
|
||||
default_bf = s.basic_filter if s else {}
|
||||
stripped_bf = {}
|
||||
for k, v in bf.items():
|
||||
default_val = default_bf.get(k)
|
||||
# 保留与默认值不同的键,以及没有默认值的键
|
||||
if k not in default_bf or v != default_val:
|
||||
stripped_bf[k] = v
|
||||
if stripped_bf:
|
||||
result["basic_filter"] = stripped_bf
|
||||
else:
|
||||
del result["basic_filter"]
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.delete("/config/{strategy_id}")
|
||||
def reset_config(strategy_id: str, request: Request):
|
||||
strategy_config.delete_override(_data_dir(request), strategy_id)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ── AI 生成 ───────────────────────────────────────────────────────────
|
||||
|
||||
class BuildRequest(BaseModel):
|
||||
"""两步策略构建请求"""
|
||||
step: int # 1 / 2
|
||||
# step1 字段
|
||||
name: str = ""
|
||||
description: str = ""
|
||||
direction: str = "long"
|
||||
rules: str = ""
|
||||
strategy_id: str = ""
|
||||
# step2 字段
|
||||
current_code: str = ""
|
||||
instruction: str = ""
|
||||
|
||||
|
||||
@router.get("/ai/status")
|
||||
def ai_status(request: Request):
|
||||
"""Check whether the selected AI provider is configured."""
|
||||
from app import secrets_store
|
||||
from app.services.ai_provider import ai_configured, current_ai_model, current_ai_provider
|
||||
|
||||
has_key = bool(secrets_store.get_ai_key())
|
||||
model = current_ai_model()
|
||||
provider = current_ai_provider()
|
||||
return {
|
||||
"configured": ai_configured(provider) and bool(model or provider == "codex_cli"),
|
||||
"has_key": has_key,
|
||||
"has_model": bool(model),
|
||||
"provider": provider,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{strategy_id}/source")
|
||||
def get_strategy_source(strategy_id: str, request: Request):
|
||||
"""获取策略源文件内容(用于 AI 修改)"""
|
||||
from pathlib import Path
|
||||
|
||||
# 先查 StrategyEngine 获取文件路径
|
||||
engine = _get_engine(request)
|
||||
try:
|
||||
s = engine.get(strategy_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=404, detail=f"策略 {strategy_id} 不存在")
|
||||
|
||||
path = s.file_path
|
||||
if not path or not path.exists():
|
||||
raise HTTPException(status_code=404, detail="策略源文件不存在")
|
||||
|
||||
return {"code": path.read_text(encoding="utf-8"), "source": s.source}
|
||||
|
||||
|
||||
@router.post("/ai/test")
|
||||
async def ai_test(request: Request):
|
||||
"""Send a small prompt through the selected AI provider."""
|
||||
from app.services.ai_provider import current_ai_model, current_ai_provider, generate_ai_text
|
||||
|
||||
try:
|
||||
text = await generate_ai_text(
|
||||
[{"role": "user", "content": "Reply exactly: OK"}],
|
||||
temperature=0,
|
||||
max_tokens=8,
|
||||
timeout=15,
|
||||
)
|
||||
return {"ok": True, "model": current_ai_model() or current_ai_provider(), "response": text[:80]}
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": str(e)}
|
||||
|
||||
|
||||
@router.post("/build")
|
||||
async def build_strategy(req: BuildRequest, request: Request):
|
||||
"""两步策略构建。
|
||||
step1: name + description + direction + rules → 完整策略
|
||||
step2: current_code + instruction → 修改任意部分
|
||||
"""
|
||||
gen = AIStrategyGenerator()
|
||||
|
||||
if req.step == 1:
|
||||
prompt = build_step1(req.name, req.description, req.direction, req.rules, req.strategy_id)
|
||||
elif req.step == 2:
|
||||
prompt = build_step2(req.current_code, req.instruction)
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail=f"无效步骤: {req.step}")
|
||||
|
||||
try:
|
||||
result = await gen.generate(prompt)
|
||||
except RuntimeError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
return result
|
||||
|
||||
|
||||
|
||||
@router.post("/ai/generate")
|
||||
async def ai_generate(req: AIGenerateRequest, request: Request):
|
||||
try:
|
||||
gen = AIStrategyGenerator()
|
||||
result = await gen.generate(req.prompt)
|
||||
except RuntimeError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"AI生成失败: {e}") from e
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/ai/save")
|
||||
async def ai_save(req: AISaveRequest, request: Request):
|
||||
data_dir = _data_dir(request)
|
||||
out_dir = data_dir / "strategies" / "ai"
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = out_dir / f"{req.strategy_id}.py"
|
||||
previous_code = path.read_text(encoding="utf-8") if path.exists() else None
|
||||
path.write_text(req.code, encoding="utf-8")
|
||||
|
||||
# 热重载,并确认保存的策略真的被引擎加载。
|
||||
engine = _get_engine(request)
|
||||
engine.reload()
|
||||
if not engine.has(req.strategy_id):
|
||||
if previous_code is None:
|
||||
path.unlink(missing_ok=True)
|
||||
else:
|
||||
path.write_text(previous_code, encoding="utf-8")
|
||||
engine.reload()
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"策略保存成功但加载失败: {req.strategy_id},请检查代码语法和 META.id 是否一致",
|
||||
)
|
||||
return {"ok": True, "path": str(path)}
|
||||
|
||||
|
||||
@router.delete("/{strategy_id}")
|
||||
def delete_strategy(strategy_id: str, request: Request):
|
||||
"""删除自定义策略 — 清除 .py 文件 + overrides + 热重载。内置策略不可删除。"""
|
||||
from pathlib import Path
|
||||
|
||||
engine = _get_engine(request)
|
||||
try:
|
||||
s = engine.get(strategy_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=404, detail=f"策略 {strategy_id} 不存在")
|
||||
|
||||
if s.source == "builtin":
|
||||
raise HTTPException(status_code=403, detail="内置策略不可删除")
|
||||
|
||||
# 删除策略文件
|
||||
if s.file_path and s.file_path.exists():
|
||||
s.file_path.unlink()
|
||||
|
||||
# 删除 overrides
|
||||
data_dir = _data_dir(request)
|
||||
override_path = data_dir / "user_data" / "strategy_overrides" / f"{strategy_id}.json"
|
||||
if override_path.exists():
|
||||
override_path.unlink()
|
||||
|
||||
# 热重载
|
||||
engine.reload()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ── 监控 ─────────────────────────────────────────────────────────────
|
||||
# 注: 策略监控已统一迁移到 MonitorRuleEngine (监控通知页), 旧的 start/stop/status
|
||||
# 路由已移除。StrategyMonitorService 类保留 (其 _check_signals 被 MonitorRuleEngine 复用)。
|
||||
|
||||
|
||||
# ── 热重载 ───────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.post("/reload")
|
||||
def reload_strategies(request: Request):
|
||||
engine = _get_engine(request)
|
||||
engine.reload()
|
||||
return {"ok": True, "count": len(engine.list_strategies())}
|
||||
@@ -0,0 +1,222 @@
|
||||
"""自选股 API。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
import time
|
||||
from datetime import date
|
||||
|
||||
import polars as pl
|
||||
from fastapi import APIRouter, Query, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.services import watchlist
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/watchlist", tags=["watchlist"])
|
||||
|
||||
|
||||
class AddRequest(BaseModel):
|
||||
symbol: str
|
||||
note: str = ""
|
||||
|
||||
|
||||
class BatchAddRequest(BaseModel):
|
||||
symbols: list[str]
|
||||
note: str = ""
|
||||
|
||||
|
||||
def _with_names(rows: list[dict], request: Request) -> list[dict]:
|
||||
if not rows:
|
||||
return rows
|
||||
try:
|
||||
df_i = request.app.state.repo.get_instruments()
|
||||
if df_i.is_empty() or "symbol" not in df_i.columns or "name" not in df_i.columns:
|
||||
return rows
|
||||
name_by_symbol = dict(df_i.select(["symbol", "name"]).iter_rows())
|
||||
return [{**row, "name": name_by_symbol.get(row.get("symbol"))} for row in rows]
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("attach watchlist names failed: %s", e)
|
||||
return rows
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_all(request: Request):
|
||||
return {"symbols": _with_names(watchlist.list_symbols(), request)}
|
||||
|
||||
|
||||
@router.post("")
|
||||
def add_one(req: AddRequest, request: Request):
|
||||
rows = watchlist.add(req.symbol, req.note)
|
||||
return {"symbols": _with_names(rows, request)}
|
||||
|
||||
|
||||
@router.post("/batch")
|
||||
def add_batch(req: BatchAddRequest, request: Request):
|
||||
for sym in req.symbols:
|
||||
watchlist.add(sym, req.note)
|
||||
return {"symbols": _with_names(watchlist.list_symbols(), request), "added": len(req.symbols)}
|
||||
|
||||
|
||||
@router.post("/{symbol}/top")
|
||||
def move_one_to_top(symbol: str, request: Request):
|
||||
rows = watchlist.move_to_top(symbol)
|
||||
return {"symbols": _with_names(rows, request)}
|
||||
|
||||
|
||||
@router.delete("/{symbol}")
|
||||
def remove_one(symbol: str, request: Request):
|
||||
rows = watchlist.remove(symbol)
|
||||
return {"symbols": _with_names(rows, request)}
|
||||
|
||||
|
||||
@router.delete("")
|
||||
def clear_all():
|
||||
"""清空自选列表。"""
|
||||
count = watchlist.clear()
|
||||
return {"removed": count}
|
||||
|
||||
|
||||
# 自选页需要的列
|
||||
_WATCHLIST_COLS = [
|
||||
"symbol", "close", "change_pct", "change_amount", "amount",
|
||||
"turnover_rate",
|
||||
"amplitude", "annual_vol_20d",
|
||||
"vol_ratio_5d",
|
||||
"ma5", "ma10", "ma20", "ma60",
|
||||
"vol_ma5", "vol_ma10",
|
||||
"high_60d", "low_60d",
|
||||
"rsi_6", "rsi_14", "rsi_24",
|
||||
"macd_dif", "macd_dea", "macd_hist",
|
||||
"kdj_k", "kdj_d", "kdj_j",
|
||||
"boll_upper", "boll_lower",
|
||||
"atr_14",
|
||||
"momentum_5d", "momentum_10d", "momentum_20d", "momentum_30d", "momentum_60d",
|
||||
"consecutive_limit_ups", "consecutive_limit_downs",
|
||||
"signal_limit_up", "signal_limit_down", "signal_volume_surge",
|
||||
"signal_ma_golden_5_20", "signal_macd_golden", "signal_n_day_high",
|
||||
"signal_boll_breakout_upper", "signal_ma20_breakout",
|
||||
"signal_ma_dead_5_20", "signal_macd_dead", "signal_n_day_low",
|
||||
"signal_boll_breakdown_lower", "signal_ma20_breakdown",
|
||||
]
|
||||
|
||||
|
||||
@router.get("/enriched")
|
||||
def watchlist_enriched(
|
||||
request: Request,
|
||||
ext_columns: str | None = Query(None, description="逗号分隔的 ext 列: config_id.field_name"),
|
||||
):
|
||||
"""自选股 enriched 数据 — 直接从 enriched 最新日读取, 无即时计算。
|
||||
|
||||
ext_columns 参数示例: "industry_rating.score,fund_flow.net_inflow"
|
||||
会动态 LEFT JOIN 对应的 ext_{config_id} DuckDB view。
|
||||
"""
|
||||
t0 = time.perf_counter()
|
||||
|
||||
repo = request.app.state.repo
|
||||
symbols = [r["symbol"] for r in watchlist.list_symbols()]
|
||||
if not symbols:
|
||||
return {"rows": [], "as_of": None, "elapsed_ms": 0}
|
||||
|
||||
df_e, cache_date = repo.get_enriched_latest()
|
||||
if df_e.is_empty():
|
||||
return {"rows": [], "as_of": None, "elapsed_ms": 0}
|
||||
|
||||
# 按 symbol 过滤
|
||||
df = df_e.filter(pl.col("symbol").is_in(symbols))
|
||||
if df.is_empty():
|
||||
return {"rows": [], "as_of": str(cache_date) if cache_date else None, "elapsed_ms": 0}
|
||||
|
||||
# JOIN instruments 取 name + float_shares
|
||||
df_i = repo.get_instruments()
|
||||
if not df_i.is_empty() and "name" in df_i.columns:
|
||||
inst_cols = [c for c in ["symbol", "name", "float_shares"] if c in df_i.columns]
|
||||
df = df.join(df_i.select(inst_cols), on="symbol", how="left")
|
||||
|
||||
# 选择内置需要的列
|
||||
keep = [c for c in _WATCHLIST_COLS + ["name", "float_shares"] if c in df.columns]
|
||||
df = df.select(keep)
|
||||
|
||||
# 动态 JOIN 扩展数据表
|
||||
ext_specs = _parse_ext_columns(ext_columns) if ext_columns else []
|
||||
if ext_specs:
|
||||
db = repo.store.db
|
||||
data_dir = repo.store.data_dir
|
||||
from app.services.ext_data import ExtConfigStore
|
||||
from app.api.ext_data import _read_ext_dataframe
|
||||
|
||||
ext_store = ExtConfigStore(data_dir)
|
||||
configs = {c.id: c for c in ext_store.load_all()}
|
||||
|
||||
for config_id, field_name in ext_specs:
|
||||
view_name = f"ext_{config_id}"
|
||||
ext_col_name = f"{config_id}__{field_name}"
|
||||
try:
|
||||
# 扩展时序数据必须只取最新分区;否则一个 symbol 会按历史分区数被 JOIN 放大。
|
||||
cfg = configs.get(config_id)
|
||||
if cfg:
|
||||
ext_df, _ = _read_ext_dataframe(cfg, data_dir)
|
||||
else:
|
||||
ext_df = pl.from_arrow(db.query(
|
||||
f"SELECT symbol, \"{field_name}\" FROM {view_name}"
|
||||
).arrow())
|
||||
if not ext_df.is_empty() and "symbol" in ext_df.columns:
|
||||
ext_df = (
|
||||
ext_df
|
||||
.select(["symbol", field_name])
|
||||
.unique(subset=["symbol"], keep="last")
|
||||
.rename({field_name: ext_col_name})
|
||||
)
|
||||
df = df.join(ext_df.select(["symbol", ext_col_name]), on="symbol", how="left")
|
||||
except Exception:
|
||||
# view 不存在或字段不存在,尝试直接读 parquet
|
||||
cfg = configs.get(config_id)
|
||||
if cfg:
|
||||
try:
|
||||
ext_df, _ = _read_ext_dataframe(cfg, data_dir)
|
||||
if not ext_df.is_empty() and "symbol" in ext_df.columns and field_name in ext_df.columns:
|
||||
ext_df = (
|
||||
ext_df
|
||||
.select(["symbol", field_name])
|
||||
.unique(subset=["symbol"], keep="last")
|
||||
.rename({field_name: ext_col_name})
|
||||
)
|
||||
df = df.join(ext_df, on="symbol", how="left")
|
||||
except Exception as e2:
|
||||
logger.debug("ext join fallback failed for %s.%s: %s", config_id, field_name, e2)
|
||||
|
||||
# sanitize NaN / Inf
|
||||
float_cols = [c for c in df.columns if df[c].dtype.is_float()]
|
||||
if float_cols:
|
||||
df = df.with_columns([
|
||||
pl.when(pl.col(c).is_nan() | pl.col(c).is_infinite())
|
||||
.then(None)
|
||||
.otherwise(pl.col(c))
|
||||
.alias(c)
|
||||
for c in float_cols
|
||||
])
|
||||
|
||||
# 按自选添加顺序(新加的在前)重排行
|
||||
order_map = {s: i for i, s in enumerate(symbols)}
|
||||
df = df.with_columns(pl.col("symbol").map_elements(lambda s: order_map.get(s, len(symbols)), return_dtype=pl.Int32).alias("_sort_order"))
|
||||
df = df.sort("_sort_order").drop("_sort_order")
|
||||
|
||||
rows = df.to_dicts()
|
||||
elapsed = (time.perf_counter() - t0) * 1000
|
||||
return {"rows": rows, "as_of": str(cache_date) if cache_date else None, "elapsed_ms": elapsed}
|
||||
|
||||
|
||||
def _parse_ext_columns(ext_columns: str) -> list[tuple[str, str]]:
|
||||
"""解析 'config_id1.field1,config_id2.field2' 为 [(config_id, field_name), ...]"""
|
||||
result = []
|
||||
for part in ext_columns.split(","):
|
||||
part = part.strip()
|
||||
if "." not in part:
|
||||
continue
|
||||
config_id, field_name = part.split(".", 1)
|
||||
config_id = config_id.strip()
|
||||
field_name = field_name.strip()
|
||||
if config_id and field_name:
|
||||
result.append((config_id, field_name))
|
||||
return result
|
||||
@@ -0,0 +1,4 @@
|
||||
"""回测模块 — 因子回测 + 策略回测 + 信号回测。
|
||||
|
||||
架构: BacktestEngine (共享) → FactorBacktestService / StrategyBacktestService
|
||||
"""
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,480 @@
|
||||
"""因子回测服务 — IC/IR 分析 + 分层回测 + 多空组合。
|
||||
|
||||
纯 Polars 向量化实现,无 pandas 依赖。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, timedelta
|
||||
from typing import Literal
|
||||
|
||||
import numpy as np
|
||||
import polars as pl
|
||||
|
||||
from app.backtest.engine import BacktestEngine
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 可用因子列 (从 ENRICHED_COLUMNS 过滤出数值型指标)
|
||||
FACTOR_COLUMNS: list[dict] = [
|
||||
{"id": "momentum_5d", "label": "5日动量", "group": "动量", "desc": "5日涨跌幅,正值表示上涨趋势"},
|
||||
{"id": "momentum_10d", "label": "10日动量", "group": "动量", "desc": "10日涨跌幅,中短期趋势指标"},
|
||||
{"id": "momentum_20d", "label": "20日动量", "group": "动量", "desc": "月度涨跌幅,常用因子"},
|
||||
{"id": "momentum_30d", "label": "30日动量", "group": "动量", "desc": "30日涨跌幅"},
|
||||
{"id": "momentum_60d", "label": "60日动量", "group": "动量", "desc": "季度涨跌幅,中期动量"},
|
||||
{"id": "rsi_6", "label": "RSI(6)", "group": "超买超卖", "desc": "6日相对强弱指标,敏感度高"},
|
||||
{"id": "rsi_14", "label": "RSI(14)", "group": "超买超卖", "desc": "14日相对强弱指标,经典周期"},
|
||||
{"id": "rsi_24", "label": "RSI(24)", "group": "超买超卖", "desc": "24日相对强弱指标"},
|
||||
{"id": "annual_vol_20d","label": "20日波动率", "group": "波动率", "desc": "20日年化波动率"},
|
||||
{"id": "atr_14", "label": "ATR(14)", "group": "波动率", "desc": "14日平均真实波幅"},
|
||||
{"id": "vol_ratio_5d", "label": "量比(5日)", "group": "量价", "desc": "当日成交量 / 5日均量"},
|
||||
{"id": "turnover_rate", "label": "换手率", "group": "量价", "desc": "当日换手率"},
|
||||
{"id": "macd_hist", "label": "MACD柱", "group": "趋势", "desc": "MACD柱状图值"},
|
||||
{"id": "kdj_k", "label": "KDJ-K", "group": "趋势", "desc": "KDJ指标K值"},
|
||||
{"id": "change_pct", "label": "日涨跌幅", "group": "基础", "desc": "当日涨跌幅"},
|
||||
{"id": "amplitude", "label": "日振幅", "group": "基础", "desc": "当日振幅 (最高-最低)/昨收"},
|
||||
]
|
||||
|
||||
FACTOR_WARMUP_DAYS = 120
|
||||
|
||||
|
||||
@dataclass
|
||||
class FactorConfig:
|
||||
factor_name: str
|
||||
symbols: list[str] | None
|
||||
start: date
|
||||
end: date
|
||||
n_groups: int = 5
|
||||
rebalance: Literal["daily", "weekly", "monthly"] = "monthly"
|
||||
weight: Literal["equal", "factor_weight"] = "equal"
|
||||
fees_pct: float = 0.0002
|
||||
slippage_bps: float = 5.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class GroupStats:
|
||||
group: int
|
||||
label: str
|
||||
total_return: float
|
||||
annual_return: float
|
||||
max_drawdown: float
|
||||
sharpe: float
|
||||
win_rate: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class FactorResult:
|
||||
run_id: str
|
||||
config: dict
|
||||
# IC 分析
|
||||
ic_mean: float | None = None
|
||||
ic_std: float | None = None
|
||||
ir: float | None = None
|
||||
ic_win_rate: float | None = None
|
||||
ic_series: list[dict] = field(default_factory=list)
|
||||
# 分层
|
||||
group_stats: list[dict] = field(default_factory=list)
|
||||
group_nav: list[dict] = field(default_factory=list)
|
||||
# 多空
|
||||
long_short_stats: dict = field(default_factory=dict)
|
||||
long_short_nav: list[dict] = field(default_factory=list)
|
||||
# 元信息
|
||||
elapsed_ms: float = 0.0
|
||||
n_symbols: int = 0
|
||||
n_dates: int = 0
|
||||
error: str | None = None
|
||||
|
||||
|
||||
class FactorBacktestService:
|
||||
def __init__(self, engine: BacktestEngine) -> None:
|
||||
self.engine = engine
|
||||
|
||||
def run(self, config: FactorConfig) -> FactorResult:
|
||||
t0 = time.perf_counter()
|
||||
run_id = uuid.uuid4().hex[:10]
|
||||
|
||||
def _err(msg: str) -> FactorResult:
|
||||
return FactorResult(
|
||||
run_id=run_id,
|
||||
config=self._config_to_dict(config),
|
||||
error=msg,
|
||||
elapsed_ms=(time.perf_counter() - t0) * 1000,
|
||||
)
|
||||
|
||||
# 加载基础面板: 当前 enriched parquet 只持久化基础列, 指标因子可能需要运行时计算。
|
||||
panel_columns = ["symbol", "date", "open", "high", "low", "close", "volume", "turnover_rate"]
|
||||
if config.factor_name not in panel_columns:
|
||||
panel_columns.append(config.factor_name)
|
||||
load_start = config.start
|
||||
if config.factor_name not in {"turnover_rate"}:
|
||||
load_start = config.start - timedelta(days=FACTOR_WARMUP_DAYS)
|
||||
|
||||
panel = self.engine.load_panel(
|
||||
config.symbols,
|
||||
load_start,
|
||||
config.end,
|
||||
columns=panel_columns,
|
||||
)
|
||||
if panel.is_empty():
|
||||
return _err("无数据,请检查日期范围或先运行盘后管道")
|
||||
|
||||
factor_col = config.factor_name
|
||||
if factor_col not in panel.columns:
|
||||
panel = self._compute_missing_factor(panel, factor_col)
|
||||
if factor_col not in panel.columns:
|
||||
return _err(f"因子列 '{factor_col}' 不存在于 enriched 数据中, 且无法从基础行情计算")
|
||||
if "close" not in panel.columns:
|
||||
return _err("enriched 数据缺少收盘价 close")
|
||||
panel = panel.select(["symbol", "date", "close", factor_col])
|
||||
panel = panel.filter((pl.col("date") >= config.start) & (pl.col("date") <= config.end))
|
||||
|
||||
# 过滤有效行
|
||||
panel = panel.filter(
|
||||
pl.col(factor_col).is_not_null()
|
||||
& pl.col("close").is_not_null()
|
||||
& (pl.col("close") > 0)
|
||||
)
|
||||
if panel.is_empty():
|
||||
return _err("过滤后无有效数据")
|
||||
|
||||
n_symbols = panel["symbol"].n_unique()
|
||||
n_dates = panel["date"].n_unique()
|
||||
|
||||
# 计算下期收益
|
||||
# 根据调仓频率计算不同周期的 forward return
|
||||
if config.rebalance == "daily":
|
||||
panel = panel.with_columns(
|
||||
(pl.col("close").shift(-1).over("symbol") / pl.col("close") - 1)
|
||||
.alias("_next_return")
|
||||
)
|
||||
else:
|
||||
# weekly/monthly: 计算到下个调仓日的收益
|
||||
panel = self._calc_period_return(panel, config.rebalance)
|
||||
|
||||
# ── 1. IC 分析 ──
|
||||
ic_df = self._calc_ic(panel, factor_col)
|
||||
ic_series = [
|
||||
{"date": str(row["date"]), "ic": round(float(row["ic"]), 4)}
|
||||
for row in ic_df.iter_rows(named=True)
|
||||
if row["ic"] is not None and not np.isnan(float(row["ic"]))
|
||||
]
|
||||
ic_values = [r["ic"] for r in ic_series]
|
||||
ic_mean = float(np.mean(ic_values)) if ic_values else None
|
||||
ic_std = float(np.std(ic_values)) if ic_values else None
|
||||
ir = (ic_mean / ic_std) if (ic_mean is not None and ic_std and ic_std > 1e-8) else None
|
||||
ic_win_rate = (sum(1 for v in ic_values if v > 0) / len(ic_values)) if ic_values else None
|
||||
|
||||
# ── 2. 分层回测 ──
|
||||
panel = self._add_groups(panel, factor_col, config.n_groups)
|
||||
group_nav = self._calc_group_nav(panel, config)
|
||||
group_stats = self._calc_group_stats(group_nav, config.start, config.end)
|
||||
|
||||
# ── 3. 多空组合 ──
|
||||
long_short_nav, long_short_stats = self._calc_long_short(group_nav, config)
|
||||
|
||||
elapsed = (time.perf_counter() - t0) * 1000
|
||||
return FactorResult(
|
||||
run_id=run_id,
|
||||
config=self._config_to_dict(config),
|
||||
ic_mean=round(ic_mean, 4) if ic_mean is not None else None,
|
||||
ic_std=round(ic_std, 4) if ic_std is not None else None,
|
||||
ir=round(ir, 4) if ir is not None else None,
|
||||
ic_win_rate=round(ic_win_rate, 4) if ic_win_rate is not None else None,
|
||||
ic_series=ic_series,
|
||||
group_stats=group_stats,
|
||||
group_nav=group_nav,
|
||||
long_short_stats=long_short_stats,
|
||||
long_short_nav=long_short_nav,
|
||||
elapsed_ms=round(elapsed, 1),
|
||||
n_symbols=n_symbols,
|
||||
n_dates=n_dates,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _compute_missing_factor(panel: pl.DataFrame, factor_col: str) -> pl.DataFrame:
|
||||
required = {"symbol", "date", "open", "high", "low", "close", "volume"}
|
||||
if not required.issubset(panel.columns):
|
||||
missing = sorted(required - set(panel.columns))
|
||||
logger.warning("factor %s cannot be computed, missing columns: %s", factor_col, missing)
|
||||
return panel
|
||||
|
||||
from app.indicators.pipeline import compute_indicators
|
||||
|
||||
computed = compute_indicators(panel)
|
||||
if factor_col not in computed.columns:
|
||||
return panel
|
||||
return computed.select(["symbol", "date", "close", factor_col])
|
||||
|
||||
# ── IC 计算 ──
|
||||
|
||||
@staticmethod
|
||||
def _calc_ic(panel: pl.DataFrame, factor_col: str) -> pl.DataFrame:
|
||||
"""计算截面 Rank IC (因子值 rank vs 下期收益 rank 的相关系数)。"""
|
||||
return (
|
||||
panel.filter(pl.col("_next_return").is_not_null())
|
||||
.group_by("date")
|
||||
.agg(
|
||||
pl.corr(
|
||||
pl.col(factor_col).rank(method="random"),
|
||||
pl.col("_next_return").rank(method="random"),
|
||||
).alias("ic")
|
||||
)
|
||||
.sort("date")
|
||||
)
|
||||
|
||||
# ── 调仓期收益 ──
|
||||
|
||||
@staticmethod
|
||||
def _calc_period_return(panel: pl.DataFrame, rebalance: str) -> pl.DataFrame:
|
||||
"""计算到下个调仓日的收益。
|
||||
|
||||
weekly: 下周一的 open / 今日 close - 1
|
||||
monthly: 下月首个交易日的 open / 今日 close - 1
|
||||
只在调仓日标记行有效,其他行为 null。
|
||||
"""
|
||||
import datetime as _dt
|
||||
|
||||
all_dates = sorted(panel["date"].unique().to_list())
|
||||
date_set = set(all_dates)
|
||||
|
||||
if rebalance == "weekly":
|
||||
# 调仓日 = 每周一
|
||||
rebalance_dates = set()
|
||||
for d in all_dates:
|
||||
if hasattr(d, "weekday"):
|
||||
wd = d.weekday()
|
||||
else:
|
||||
wd = _dt.date.fromisoformat(str(d)).weekday()
|
||||
if wd == 0: # Monday
|
||||
rebalance_dates.add(d)
|
||||
else: # monthly
|
||||
# 调仓日 = 每月首个交易日
|
||||
seen_months: set[str] = set()
|
||||
rebalance_dates = set()
|
||||
for d in sorted(all_dates):
|
||||
m = str(d)[:7] # "YYYY-MM"
|
||||
if m not in seen_months:
|
||||
seen_months.add(m)
|
||||
rebalance_dates.add(d)
|
||||
|
||||
if not rebalance_dates:
|
||||
panel = panel.with_columns(pl.lit(None).cast(pl.Float64).alias("_next_return"))
|
||||
return panel
|
||||
|
||||
# 对每个调仓日,找到下一个调仓日
|
||||
sorted_rebalance = sorted(rebalance_dates)
|
||||
next_rebalance_map: dict = {}
|
||||
for i, d in enumerate(sorted_rebalance):
|
||||
if i + 1 < len(sorted_rebalance):
|
||||
next_rebalance_map[d] = sorted_rebalance[i + 1]
|
||||
# 最后一个调仓日没有下一个,不计算收益
|
||||
|
||||
# 构建 (date, symbol) → next_rebalance_date 的 close 价格映射
|
||||
# 简化: 用下个调仓日的 close / 当前 close
|
||||
panel = panel.sort(["symbol", "date"])
|
||||
dates_col = panel["date"].to_list()
|
||||
close_col = panel["close"].to_list()
|
||||
symbol_col = panel["symbol"].to_list()
|
||||
|
||||
# 先找下个调仓日的 close
|
||||
# 建立 (date, symbol) → close 的快速查找
|
||||
price_map: dict[tuple, float] = {}
|
||||
for i in range(len(dates_col)):
|
||||
price_map[(str(dates_col[i]), symbol_col[i])] = close_col[i]
|
||||
|
||||
next_returns = [None] * len(panel)
|
||||
for i in range(len(panel)):
|
||||
d = dates_col[i]
|
||||
d_val = d if isinstance(d, _dt.date) else _dt.date.fromisoformat(str(d))
|
||||
if d not in rebalance_dates:
|
||||
continue
|
||||
next_d = next_rebalance_map.get(d)
|
||||
if next_d is None:
|
||||
continue
|
||||
next_d_str = str(next_d)[:10]
|
||||
d_str = str(d)[:10]
|
||||
sym = symbol_col[i]
|
||||
next_close = price_map.get((next_d_str, sym))
|
||||
cur_close = close_col[i]
|
||||
if next_close is not None and cur_close and cur_close > 0:
|
||||
next_returns[i] = (next_close / cur_close - 1.0)
|
||||
|
||||
panel = panel.with_columns(
|
||||
pl.Series("_next_return", next_returns, dtype=pl.Float64)
|
||||
)
|
||||
return panel
|
||||
|
||||
# ── 分组 ──
|
||||
|
||||
@staticmethod
|
||||
def _add_groups(panel: pl.DataFrame, factor_col: str, n_groups: int) -> pl.DataFrame:
|
||||
"""截面分位数分组。"""
|
||||
return panel.with_columns(
|
||||
pl.col(factor_col)
|
||||
.qcut(n_groups, labels=[f"Q{i+1}" for i in range(n_groups)])
|
||||
.over("date")
|
||||
.alias("_group")
|
||||
)
|
||||
|
||||
# ── 分组净值 ──
|
||||
|
||||
@staticmethod
|
||||
def _calc_group_nav(panel: pl.DataFrame, config: FactorConfig) -> list[dict]:
|
||||
"""计算分组净值曲线 — 只在调仓日更新净值。"""
|
||||
# 只保留有下期收益的行 (= 调仓日)
|
||||
group_ret = (
|
||||
panel.filter(pl.col("_next_return").is_not_null() & pl.col("_group").is_not_null())
|
||||
.group_by(["date", "_group"])
|
||||
.agg(pl.col("_next_return").mean().alias("group_return"))
|
||||
)
|
||||
|
||||
# pivot: date × group
|
||||
pivot = group_ret.pivot(index="date", columns="_group", values="group_return").sort("date")
|
||||
|
||||
if pivot.is_empty():
|
||||
return []
|
||||
|
||||
group_cols = [c for c in pivot.columns if c != "date"]
|
||||
|
||||
# 累乘净值曲线
|
||||
result: list[dict] = []
|
||||
nav_values: dict[str, float] = {c: 1.0 for c in group_cols}
|
||||
|
||||
for row in pivot.iter_rows(named=True):
|
||||
entry: dict = {"date": str(row["date"])[:10]}
|
||||
for c in group_cols:
|
||||
ret = float(row[c]) if row[c] is not None else 0.0
|
||||
nav_values[c] *= (1 + ret)
|
||||
entry[c] = round(nav_values[c], 4)
|
||||
result.append(entry)
|
||||
|
||||
return result
|
||||
|
||||
# ── 分组统计 ──
|
||||
|
||||
@staticmethod
|
||||
def _calc_group_stats(
|
||||
group_nav: list[dict], start: date, end: date,
|
||||
) -> list[dict]:
|
||||
if not group_nav:
|
||||
return []
|
||||
|
||||
group_cols = [k for k in group_nav[0] if k != "date"]
|
||||
n_days = max((end - start).days, 1)
|
||||
years = n_days / 365.25
|
||||
|
||||
stats = []
|
||||
for i, c in enumerate(sorted(group_cols)):
|
||||
values = [r[c] for r in group_nav if r.get(c) is not None]
|
||||
if not values:
|
||||
continue
|
||||
total_return = values[-1] - 1.0
|
||||
annual_return = (values[-1]) ** (1 / max(years, 0.01)) - 1 if values[-1] > 0 else 0.0
|
||||
|
||||
# 最大回撤
|
||||
peak = 1.0
|
||||
max_dd = 0.0
|
||||
for v in values:
|
||||
peak = max(peak, v)
|
||||
dd = (v - peak) / peak
|
||||
max_dd = min(max_dd, dd)
|
||||
|
||||
# 日收益序列
|
||||
daily_rets = []
|
||||
for j in range(1, len(values)):
|
||||
if values[j - 1] > 0:
|
||||
daily_rets.append(values[j] / values[j - 1] - 1)
|
||||
|
||||
# 夏普
|
||||
if daily_rets:
|
||||
arr = np.array(daily_rets)
|
||||
sharpe = float(np.mean(arr) / np.std(arr)) * np.sqrt(252) if np.std(arr) > 0 else 0.0
|
||||
win_rate = float(np.mean(arr > 0))
|
||||
else:
|
||||
sharpe = 0.0
|
||||
win_rate = 0.0
|
||||
|
||||
stats.append({
|
||||
"group": i + 1,
|
||||
"label": c,
|
||||
"total_return": round(total_return, 4),
|
||||
"annual_return": round(annual_return, 4),
|
||||
"max_drawdown": round(max_dd, 4),
|
||||
"sharpe": round(sharpe, 2),
|
||||
"win_rate": round(win_rate, 4),
|
||||
})
|
||||
|
||||
return stats
|
||||
|
||||
# ── 多空组合 ──
|
||||
|
||||
@staticmethod
|
||||
def _calc_long_short(
|
||||
group_nav: list[dict], config: FactorConfig,
|
||||
) -> tuple[list[dict], dict]:
|
||||
"""多空组合: 做多最高组 + 做空最低组。"""
|
||||
if not group_nav:
|
||||
return [], {}
|
||||
|
||||
group_cols = sorted([k for k in group_nav[0] if k != "date"])
|
||||
if len(group_cols) < 2:
|
||||
return [], {}
|
||||
|
||||
top_col = group_cols[-1] # Q5 (最高)
|
||||
bottom_col = group_cols[0] # Q1 (最低)
|
||||
|
||||
# 独立计算 top 和 bottom 的日收益,然后合成
|
||||
ls_value = 1.0
|
||||
prev_top = 1.0
|
||||
prev_bot = 1.0
|
||||
peak = 1.0
|
||||
max_dd = 0.0
|
||||
ls_nav: list[dict] = []
|
||||
|
||||
for row in group_nav:
|
||||
top_nav = float(row.get(top_col, 1.0)) if row.get(top_col) is not None else 1.0
|
||||
bot_nav = float(row.get(bottom_col, 1.0)) if row.get(bottom_col) is not None else 1.0
|
||||
|
||||
# top 组收益 (做多)
|
||||
top_ret = (top_nav / prev_top - 1) if prev_top > 0 else 0.0
|
||||
# bottom 组收益 (做空 = 取反)
|
||||
bot_ret = -(bot_nav / prev_bot - 1) if prev_bot > 0 else 0.0
|
||||
# 多空组合收益
|
||||
ls_ret = (top_ret + bot_ret) / 2 # 各分配 50% 资金
|
||||
ls_value *= (1 + ls_ret)
|
||||
|
||||
prev_top = top_nav
|
||||
prev_bot = bot_nav
|
||||
|
||||
peak = max(peak, ls_value)
|
||||
dd = (ls_value - peak) / peak if peak > 0 else 0.0
|
||||
max_dd = min(max_dd, dd)
|
||||
|
||||
ls_nav.append({"date": row["date"], "value": round(ls_value, 4)})
|
||||
|
||||
total_ret = ls_value - 1.0
|
||||
ls_stats = {
|
||||
"total_return": round(total_ret, 4),
|
||||
"max_drawdown": round(max_dd, 4),
|
||||
"top_group": top_col,
|
||||
"bottom_group": bottom_col,
|
||||
}
|
||||
|
||||
return ls_nav, ls_stats
|
||||
|
||||
@staticmethod
|
||||
def _config_to_dict(c: FactorConfig) -> dict:
|
||||
return {
|
||||
"factor_name": c.factor_name,
|
||||
"symbols": c.symbols,
|
||||
"start": str(c.start),
|
||||
"end": str(c.end),
|
||||
"n_groups": c.n_groups,
|
||||
"rebalance": c.rebalance,
|
||||
"weight": c.weight,
|
||||
"fees_pct": c.fees_pct,
|
||||
"slippage_bps": c.slippage_bps,
|
||||
}
|
||||
@@ -0,0 +1,721 @@
|
||||
"""策略回测服务 — 复用 StrategyDef 体系做全周期回测。
|
||||
|
||||
核心优化: 向量化 filter_fn,不逐日调用 StrategyEngine.run()。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, timedelta
|
||||
from typing import Callable, Literal
|
||||
|
||||
import numpy as np
|
||||
import polars as pl
|
||||
|
||||
from app.backtest.engine import BacktestEngine, MatcherConfig, SimResult
|
||||
from app.strategy.engine import StrategyEngine, StrategyDef
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BENCHMARK_SYMBOL = "000001.SH"
|
||||
|
||||
|
||||
@dataclass
|
||||
class StrategyBacktestConfig:
|
||||
strategy_id: str
|
||||
symbols: list[str] | None
|
||||
start: date
|
||||
end: date
|
||||
params: dict | None = None
|
||||
overrides: dict | None = None
|
||||
# matching 为向后兼容入口; 显式传 entry_fill/exit_fill 时以二者为准。
|
||||
matching: Literal["close_t", "open_t+1"] = "open_t+1"
|
||||
entry_fill: Literal["close_t", "open_t+1"] | None = None
|
||||
exit_fill: Literal["close_t", "open_t+1"] | None = None
|
||||
fees_pct: float = 0.0002
|
||||
slippage_bps: float = 5.0
|
||||
max_positions: int = 10
|
||||
max_exposure_pct: float = 1.0
|
||||
initial_capital: float = 1_000_000.0
|
||||
position_sizing: Literal["equal", "score_weight"] = "equal"
|
||||
mode: Literal["position", "full"] = "position"
|
||||
holding_days: int = 5
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.entry_fill is None:
|
||||
self.entry_fill = self.matching
|
||||
if self.exit_fill is None:
|
||||
self.exit_fill = self.matching
|
||||
|
||||
|
||||
@dataclass
|
||||
class StrategyBacktestResult:
|
||||
run_id: str
|
||||
config: dict
|
||||
stats: dict = field(default_factory=dict)
|
||||
equity_curve: list[dict] = field(default_factory=list)
|
||||
drawdown_curve: list[dict] = field(default_factory=list)
|
||||
benchmark_curve: list[dict] = field(default_factory=list)
|
||||
trades: list[dict] = field(default_factory=list)
|
||||
per_symbol_stats: list[dict] = field(default_factory=list)
|
||||
strategy_info: dict = field(default_factory=dict)
|
||||
elapsed_ms: float = 0.0
|
||||
error: str | None = None
|
||||
|
||||
|
||||
class StrategyBacktestService:
|
||||
def __init__(
|
||||
self,
|
||||
engine: BacktestEngine,
|
||||
strategy_engine: StrategyEngine,
|
||||
) -> None:
|
||||
self.engine = engine
|
||||
self.strategy_engine = strategy_engine
|
||||
|
||||
def run(
|
||||
self,
|
||||
config: StrategyBacktestConfig,
|
||||
progress_cb: "Callable[[dict], None] | None" = None,
|
||||
cancel_event: "threading.Event | None" = None,
|
||||
) -> StrategyBacktestResult:
|
||||
t0 = time.perf_counter()
|
||||
run_id = uuid.uuid4().hex[:10]
|
||||
|
||||
def _err(msg: str) -> StrategyBacktestResult:
|
||||
return StrategyBacktestResult(
|
||||
run_id=run_id,
|
||||
config=self._config_to_dict(config),
|
||||
error=msg,
|
||||
elapsed_ms=(time.perf_counter() - t0) * 1000,
|
||||
)
|
||||
|
||||
# 获取策略定义
|
||||
try:
|
||||
s = self.strategy_engine.get(config.strategy_id)
|
||||
except ValueError as e:
|
||||
return _err(str(e))
|
||||
|
||||
params = self._normalize_params(config.params or {}, s)
|
||||
overrides = config.overrides or {}
|
||||
basic_filter = self._effective_basic_filter(s, overrides)
|
||||
entry_signals = self._effective_signals(overrides, "entry_signals", s.entry_signals)
|
||||
exit_signals = self._effective_signals(overrides, "exit_signals", s.exit_signals)
|
||||
stop_loss = self._override_value(overrides, "stop_loss", s.stop_loss)
|
||||
take_profit = self._normalize_pct(
|
||||
self._override_value(overrides, "take_profit", getattr(s, "take_profit", None)),
|
||||
0.01,
|
||||
5.0,
|
||||
)
|
||||
trailing_stop = self._normalize_pct(
|
||||
self._override_value(overrides, "trailing_stop", getattr(s, "trailing_stop", None)),
|
||||
0.005,
|
||||
0.5,
|
||||
)
|
||||
trailing_take_profit_activate = self._normalize_pct(
|
||||
self._override_value(overrides, "trailing_take_profit_activate", getattr(s, "trailing_take_profit_activate", None)),
|
||||
0.01,
|
||||
2.0,
|
||||
)
|
||||
trailing_take_profit_drawdown = self._normalize_pct(
|
||||
self._override_value(overrides, "trailing_take_profit_drawdown", getattr(s, "trailing_take_profit_drawdown", None)),
|
||||
0.005,
|
||||
0.5,
|
||||
)
|
||||
if trailing_take_profit_activate is not None and trailing_take_profit_drawdown is not None:
|
||||
trailing_take_profit_drawdown = min(trailing_take_profit_drawdown, trailing_take_profit_activate)
|
||||
max_hold_days = self._override_value(overrides, "max_hold_days", s.max_hold_days)
|
||||
score_min, score_max = self._normalize_score_range(
|
||||
overrides.get("score_min"),
|
||||
overrides.get("score_max"),
|
||||
)
|
||||
|
||||
timing_ms: dict[str, float] = {}
|
||||
|
||||
# 加载面板 (含 warmup + 全量指标 + 信号)。warmup 只用于指标/形态计算, 不参与正式交易。
|
||||
warmup_days = max(120, int(max(s.lookback_days or 1, 1) * 1.5))
|
||||
load_start = config.start - timedelta(days=warmup_days)
|
||||
|
||||
# 全量模式: entries 只在正式区间触发, exits 需要 end 之后的尾部数据继续执行策略卖点。
|
||||
# 若策略有 max_hold_days, 用它决定尾部窗口;否则 holding_days 只作为兜底观察上限。
|
||||
full_horizon_days = int(max_hold_days or config.holding_days or 5)
|
||||
full_horizon_days = max(full_horizon_days, 1)
|
||||
load_end = config.end
|
||||
if config.mode == "full":
|
||||
fwd_buffer = full_horizon_days + 5 # 多取几天, 容错停牌缺口/open_t+1
|
||||
load_end = config.end + timedelta(days=fwd_buffer * 2) # 日历日放宽, 确保覆盖 N 个交易日
|
||||
|
||||
t_load = time.perf_counter()
|
||||
panel = self.engine.load_panel(config.symbols, load_start, load_end)
|
||||
timing_ms["load_panel"] = round((time.perf_counter() - t_load) * 1000, 1)
|
||||
if panel.is_empty():
|
||||
return _err("无数据,请检查日期范围或先运行盘后管道")
|
||||
|
||||
formal_range = self._date_range_mask(panel, config.start, config.end)
|
||||
if not formal_range.any():
|
||||
return _err("正式回测区间内无数据")
|
||||
|
||||
t_signal = time.perf_counter()
|
||||
|
||||
# basic_filter 只影响买入候选, 不能删除行情 panel, 否则持仓 mark / 卖出 / full forward return 都会失真。
|
||||
basic_mask = pl.Series("_basic", [True] * len(panel), dtype=pl.Boolean)
|
||||
if basic_filter and basic_filter.get("enabled", True):
|
||||
expr = StrategyEngine._basic_filter_expr(panel, basic_filter)
|
||||
if expr is not None:
|
||||
try:
|
||||
basic_mask = panel.select(expr.alias("_basic"))["_basic"].fill_null(False).cast(pl.Boolean)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("basic_filter mask failed: %s", e)
|
||||
return _err(f"基础过滤计算失败: {e}")
|
||||
|
||||
# 策略候选层用于评分归一化;entry_signals 只是买点层, 不参与 score universe。
|
||||
candidate_filter_mask = self._build_candidate_filter_mask(panel, s, params)
|
||||
candidate_mask = basic_mask & candidate_filter_mask
|
||||
panel = self._apply_score(panel, s, overrides, universe_mask=candidate_mask)
|
||||
|
||||
entry_mask = self._build_entry_mask_from_candidate(panel, candidate_mask, s, entry_signals)
|
||||
entry_mask = entry_mask & formal_range
|
||||
raw_exit_mask = self._build_signal_mask(panel, exit_signals, "_exit")
|
||||
exit_mask = raw_exit_mask & (self._date_range_mask(panel, config.start, load_end) if config.mode == "full" else formal_range)
|
||||
timing_ms["signals_score"] = round((time.perf_counter() - t_signal) * 1000, 1)
|
||||
|
||||
if not entry_mask.any():
|
||||
return _err("在指定区间内未产生买入信号")
|
||||
|
||||
# warmup 之后才交给撮合;full mode 保留 end 之后前瞻段用于 shift(-N)。
|
||||
sim_end = load_end if config.mode == "full" else config.end
|
||||
sim_range = self._date_range_mask(panel, config.start, sim_end)
|
||||
sim_panel = panel.filter(sim_range)
|
||||
sim_entry_mask = entry_mask.filter(sim_range)
|
||||
sim_exit_mask = exit_mask.filter(sim_range)
|
||||
if sim_panel.is_empty():
|
||||
return _err("正式回测区间内无数据")
|
||||
|
||||
t_sim = time.perf_counter()
|
||||
matcher_config = MatcherConfig(
|
||||
matching=config.matching,
|
||||
entry_fill=config.entry_fill,
|
||||
exit_fill=config.exit_fill,
|
||||
fees_pct=config.fees_pct,
|
||||
slippage_bps=config.slippage_bps,
|
||||
stop_loss_pct=stop_loss,
|
||||
take_profit_pct=take_profit,
|
||||
trailing_stop_pct=trailing_stop,
|
||||
trailing_take_profit_activate_pct=trailing_take_profit_activate,
|
||||
trailing_take_profit_drawdown_pct=trailing_take_profit_drawdown,
|
||||
max_hold_days=max_hold_days,
|
||||
max_positions=config.max_positions,
|
||||
max_exposure_pct=config.max_exposure_pct,
|
||||
score_min=score_min,
|
||||
score_max=score_max,
|
||||
initial_capital=config.initial_capital,
|
||||
position_sizing=config.position_sizing,
|
||||
)
|
||||
# 撮合 — full 为全候选独立执行;position 为账户级仓位模拟。
|
||||
if config.mode == "full":
|
||||
result = self.engine.simulate_independent_candidates(
|
||||
sim_panel,
|
||||
sim_entry_mask,
|
||||
sim_exit_mask,
|
||||
matcher_config,
|
||||
progress_cb,
|
||||
cancel_event,
|
||||
)
|
||||
else:
|
||||
result = self.engine.simulate_portfolio(sim_panel, sim_entry_mask, sim_exit_mask, matcher_config, progress_cb, cancel_event)
|
||||
timing_ms["simulate"] = round((time.perf_counter() - t_sim) * 1000, 1)
|
||||
|
||||
# 检查是否被取消
|
||||
if cancel_event is not None and cancel_event.is_set():
|
||||
return StrategyBacktestResult(
|
||||
run_id=run_id,
|
||||
config=self._config_to_dict(config),
|
||||
error="cancelled",
|
||||
elapsed_ms=round((time.perf_counter() - t0) * 1000, 1),
|
||||
)
|
||||
|
||||
if result.stats.get("error"):
|
||||
return _err(result.stats["error"])
|
||||
|
||||
timing_ms["total"] = round((time.perf_counter() - t0) * 1000, 1)
|
||||
result.stats["timing_ms"] = timing_ms
|
||||
result.stats["panel_rows"] = int(sim_panel.height)
|
||||
|
||||
benchmark_curve = self._build_benchmark_curve(config.start, config.end)
|
||||
|
||||
# 构建策略信息
|
||||
strategy_info = {
|
||||
"id": s.meta.get("id", config.strategy_id),
|
||||
"name": s.meta.get("name", config.strategy_id),
|
||||
"description": s.meta.get("description", ""),
|
||||
"entry_signals": entry_signals,
|
||||
"exit_signals": exit_signals,
|
||||
"stop_loss": stop_loss,
|
||||
"take_profit": take_profit,
|
||||
"trailing_stop": trailing_stop,
|
||||
"trailing_take_profit_activate": trailing_take_profit_activate,
|
||||
"trailing_take_profit_drawdown": trailing_take_profit_drawdown,
|
||||
"max_hold_days": max_hold_days,
|
||||
"full_horizon_days": full_horizon_days,
|
||||
"score_min": score_min,
|
||||
"score_max": score_max,
|
||||
"source": s.source,
|
||||
}
|
||||
|
||||
elapsed = (time.perf_counter() - t0) * 1000
|
||||
|
||||
return StrategyBacktestResult(
|
||||
run_id=run_id,
|
||||
config=self._config_to_dict(config),
|
||||
stats=result.stats,
|
||||
equity_curve=result.equity_curve,
|
||||
drawdown_curve=result.drawdown_curve,
|
||||
benchmark_curve=benchmark_curve,
|
||||
trades=[self._trade_to_dict(t) for t in result.trades],
|
||||
per_symbol_stats=result.per_symbol_stats,
|
||||
strategy_info=strategy_info,
|
||||
elapsed_ms=round(elapsed, 1),
|
||||
)
|
||||
|
||||
# ── 全量模拟 (选股能力统计, 不建组合不算净值) ──
|
||||
|
||||
def _run_full_simulation(
|
||||
self,
|
||||
panel: pl.DataFrame,
|
||||
entry_mask: pl.Series,
|
||||
holding_days: int,
|
||||
) -> SimResult:
|
||||
"""对 entry_mask 命中的全部候选, 算持有 N 天后的前瞻收益统计。
|
||||
|
||||
不受 max_positions/资金约束, 反映策略选股能力本身。
|
||||
equity_curve 复用为"累计日均超额收益曲线"(基准归零)。
|
||||
"""
|
||||
n = holding_days if holding_days and holding_days > 0 else 5
|
||||
|
||||
df = panel.with_columns([
|
||||
entry_mask.cast(pl.Boolean).alias("_is_candidate"),
|
||||
(pl.col("close").shift(-n).over("symbol") / pl.col("close") - 1).alias("_fwd_return"),
|
||||
]).filter(
|
||||
pl.col("_is_candidate")
|
||||
& pl.col("_fwd_return").is_not_null()
|
||||
& pl.col("_fwd_return").is_not_nan()
|
||||
)
|
||||
|
||||
if df.is_empty():
|
||||
return self.engine._empty_result()
|
||||
|
||||
fwd = df["_fwd_return"].to_numpy()
|
||||
wins = fwd[fwd > 0]
|
||||
losses = fwd[fwd <= 0]
|
||||
avg_win = float(wins.mean()) if wins.size else 0.0
|
||||
avg_loss = abs(float(losses.mean())) if losses.size else 0.0
|
||||
|
||||
# 按日聚合: 当日候选的平均前瞻收益
|
||||
daily = (
|
||||
df.group_by("date").agg(
|
||||
pl.col("_fwd_return").mean().alias("avg_ret"),
|
||||
pl.col("_fwd_return").count().alias("n_cand"),
|
||||
).sort("date")
|
||||
)
|
||||
|
||||
# 累计超额曲线: 每日复利平均收益 (基准归零, 故 equity 即累计策略收益)
|
||||
equity_curve: list[dict] = []
|
||||
equity = 1.0
|
||||
peak = 1.0
|
||||
drawdown_curve: list[dict] = []
|
||||
for row in daily.iter_rows(named=True):
|
||||
ret = float(row["avg_ret"] or 0.0)
|
||||
equity *= (1 + ret)
|
||||
peak = max(peak, equity)
|
||||
dd = (equity - peak) / peak if peak > 0 else 0.0
|
||||
d_str = str(row["date"])[:10]
|
||||
equity_curve.append({
|
||||
"date": d_str,
|
||||
"value": round(equity, 4),
|
||||
"positions": int(row["n_cand"]),
|
||||
})
|
||||
drawdown_curve.append({"date": d_str, "value": round(dd, 4)})
|
||||
|
||||
# 同期上证收益 (用 benchmark close 算)
|
||||
benchmark_curve = self._build_benchmark_curve(
|
||||
daily["date"].min(), daily["date"].max()
|
||||
)
|
||||
benchmark_return = 0.0
|
||||
if benchmark_curve:
|
||||
closes = [b["close"] for b in benchmark_curve if b.get("close")]
|
||||
if len(closes) >= 2 and closes[0] > 0:
|
||||
benchmark_return = closes[-1] / closes[0] - 1
|
||||
|
||||
total_return = equity - 1.0
|
||||
max_dd = min((d["value"] for d in drawdown_curve), default=0.0)
|
||||
|
||||
# 日收益序列算 Sharpe (年化)
|
||||
daily_rets = daily["avg_ret"].to_numpy()
|
||||
sharpe = (
|
||||
float(daily_rets.mean() / daily_rets.std() * np.sqrt(252))
|
||||
if daily_rets.size > 1 and daily_rets.std() > 0 else 0.0
|
||||
)
|
||||
|
||||
# 收益分布直方图: 按 [-20%, +20%] 分 21 档 (每档 2%), 超出归入首尾档
|
||||
lo, hi, nbins = -0.20, 0.20, 20
|
||||
clipped = np.clip(fwd, lo, hi)
|
||||
counts, edges = np.histogram(clipped, bins=nbins, range=(lo, hi))
|
||||
dist = [
|
||||
{
|
||||
"range": f"{(edges[i]*100):+.0f}~{(edges[i+1]*100):+.0f}%",
|
||||
"count": int(counts[i]),
|
||||
"ratio": round(float(counts[i] / fwd.size), 4) if fwd.size else 0.0,
|
||||
}
|
||||
for i in range(nbins)
|
||||
]
|
||||
|
||||
stats = {
|
||||
"mode": "full",
|
||||
"n_candidates": int(fwd.size),
|
||||
"n_days": int(daily.height),
|
||||
"avg_daily_candidates": round(float(daily["n_cand"].mean()), 1),
|
||||
"avg_return": round(float(fwd.mean()), 4),
|
||||
"median_return": round(float(np.median(fwd)), 4),
|
||||
"win_rate": round(float(wins.size / fwd.size), 4) if fwd.size else 0.0,
|
||||
"profit_factor": round(avg_win / avg_loss, 2) if avg_loss > 0 else None,
|
||||
"best": round(float(fwd.max()), 4),
|
||||
"worst": round(float(fwd.min()), 4),
|
||||
"total_return": round(float(total_return), 4),
|
||||
"max_drawdown": round(float(max_dd), 4),
|
||||
"sharpe": round(sharpe, 2),
|
||||
"benchmark_return": round(float(benchmark_return), 4),
|
||||
"excess": round(float(total_return - benchmark_return), 4),
|
||||
"return_distribution": dist,
|
||||
}
|
||||
|
||||
return SimResult(
|
||||
equity_curve=equity_curve,
|
||||
drawdown_curve=drawdown_curve,
|
||||
trades=[],
|
||||
per_symbol_stats=[],
|
||||
stats=stats,
|
||||
)
|
||||
|
||||
# ── 向量化信号生成 ──
|
||||
|
||||
@staticmethod
|
||||
def _date_range_mask(panel: pl.DataFrame, start: date, end: date) -> pl.Series:
|
||||
return panel.select(
|
||||
((pl.col("date") >= start) & (pl.col("date") <= end)).alias("_range")
|
||||
)["_range"].fill_null(False).cast(pl.Boolean)
|
||||
|
||||
def _build_candidate_filter_mask(
|
||||
self,
|
||||
panel: pl.DataFrame,
|
||||
s: StrategyDef,
|
||||
params: dict,
|
||||
) -> pl.Series:
|
||||
"""生成策略候选层 mask。filter_history/filter 决定候选池, 不包含 entry_signals。"""
|
||||
false_mask = pl.Series("_candidate_filter", [False] * len(panel), dtype=pl.Boolean)
|
||||
true_mask = pl.Series("_candidate_filter", [True] * len(panel), dtype=pl.Boolean)
|
||||
|
||||
history_failed = False
|
||||
# 优先: filter_history_fn 策略 (涨停/反包等多日形态, 与选股路径共用同一逻辑)
|
||||
if s.filter_history_fn:
|
||||
try:
|
||||
hit_df = s.filter_history_fn(panel, params)
|
||||
if hit_df is None or hit_df.is_empty():
|
||||
return false_mask
|
||||
# 命中行 (symbol,date) → 转 panel 等长布尔 mask
|
||||
hits = hit_df.select(["symbol", "date"]).unique()
|
||||
marked = (
|
||||
panel.select(["symbol", "date"])
|
||||
.join(
|
||||
hits.with_columns(pl.lit(True).alias("_hit")),
|
||||
on=["symbol", "date"],
|
||||
how="left",
|
||||
)
|
||||
)
|
||||
return marked["_hit"].fill_null(False).cast(pl.Boolean)
|
||||
except Exception as e:
|
||||
history_failed = True
|
||||
logger.warning("strategy filter_history_fn failed: %s", e)
|
||||
# 失败则回退到 filter_fn (若存在)
|
||||
|
||||
# 策略 filter_fn: 候选层 (filter_history 不可用或失败时)
|
||||
if s.filter_fn:
|
||||
try:
|
||||
expr = s.filter_fn(panel, params)
|
||||
if expr is not None:
|
||||
result = panel.select(expr.alias("_candidate_filter"))
|
||||
if not result.is_empty():
|
||||
return result["_candidate_filter"].fill_null(False).cast(pl.Boolean)
|
||||
except Exception as e:
|
||||
logger.warning("strategy filter_fn failed: %s", e)
|
||||
return false_mask
|
||||
|
||||
if history_failed:
|
||||
return false_mask
|
||||
|
||||
# 没有策略候选层时, 由 entry_signals 直接决定买点。
|
||||
return true_mask
|
||||
|
||||
def _build_entry_mask_from_candidate(
|
||||
self,
|
||||
panel: pl.DataFrame,
|
||||
candidate_mask: pl.Series,
|
||||
s: StrategyDef,
|
||||
entry_signals: list[str],
|
||||
) -> pl.Series:
|
||||
"""向量化生成买入掩码:候选层 AND 买点层;无买点时只用策略候选层。"""
|
||||
signal_mask = self._build_signal_mask(panel, entry_signals, "_entry_signal")
|
||||
if entry_signals:
|
||||
return candidate_mask & signal_mask
|
||||
if s.filter_history_fn or s.filter_fn:
|
||||
return candidate_mask
|
||||
return pl.Series("_entry", [False] * len(panel), dtype=pl.Boolean)
|
||||
|
||||
def _build_entry_mask(
|
||||
self,
|
||||
panel: pl.DataFrame,
|
||||
s: StrategyDef,
|
||||
params: dict,
|
||||
entry_signals: list[str],
|
||||
) -> pl.Series:
|
||||
"""兼容旧调用: 候选层 AND 买点层。"""
|
||||
candidate_mask = self._build_candidate_filter_mask(panel, s, params)
|
||||
return self._build_entry_mask_from_candidate(panel, candidate_mask, s, entry_signals)
|
||||
|
||||
@staticmethod
|
||||
def _build_signal_mask(panel: pl.DataFrame, signals: list[str], name: str) -> pl.Series:
|
||||
"""向量化合并信号列,多个信号 OR。支持内置 signal_ 与自定义 csg_ 前缀。"""
|
||||
masks: list[pl.Series] = []
|
||||
for sig in signals:
|
||||
# csg_ (自定义信号) 直接用;否则按 signal_ 解析
|
||||
col = sig if (sig.startswith("signal_") or sig.startswith("csg_")) else f"signal_{sig}"
|
||||
if col in panel.columns:
|
||||
masks.append(panel[col].fill_null(False).cast(pl.Boolean))
|
||||
|
||||
if not masks:
|
||||
return pl.Series(name, [False] * len(panel), dtype=pl.Boolean)
|
||||
|
||||
combined = masks[0]
|
||||
for m in masks[1:]:
|
||||
combined = combined | m
|
||||
return combined
|
||||
|
||||
def _build_benchmark_curve(self, start: date, end: date) -> list[dict]:
|
||||
try:
|
||||
df = self.engine.repo.get_index_daily(BENCHMARK_SYMBOL, start, end, columns=["date", "close"])
|
||||
except Exception as e:
|
||||
logger.warning("load benchmark %s failed: %s", BENCHMARK_SYMBOL, e)
|
||||
return []
|
||||
|
||||
if df.is_empty() or "close" not in df.columns:
|
||||
return []
|
||||
|
||||
df = df.filter(pl.col("close").is_not_null() & (pl.col("close") > 0)).sort("date")
|
||||
if df.is_empty():
|
||||
return []
|
||||
|
||||
return [
|
||||
{
|
||||
"date": str(row["date"])[:10],
|
||||
"value": round(float(row["close"]), 4),
|
||||
"close": round(float(row["close"]), 4),
|
||||
"name": "上证指数",
|
||||
"symbol": BENCHMARK_SYMBOL,
|
||||
}
|
||||
for row in df.iter_rows(named=True)
|
||||
if row["close"] is not None
|
||||
]
|
||||
|
||||
# ── 工具 ──
|
||||
|
||||
@staticmethod
|
||||
def _effective_basic_filter(s: StrategyDef, overrides: dict) -> dict:
|
||||
basic_filter = dict(s.basic_filter or {})
|
||||
override_filter = overrides.get("basic_filter")
|
||||
if isinstance(override_filter, dict):
|
||||
basic_filter.update(override_filter)
|
||||
return basic_filter
|
||||
|
||||
@staticmethod
|
||||
def _effective_signals(overrides: dict, key: str, default: list[str]) -> list[str]:
|
||||
value = overrides.get(key)
|
||||
if isinstance(value, list):
|
||||
return [str(v) for v in value if v]
|
||||
return list(default or [])
|
||||
|
||||
@staticmethod
|
||||
def _override_value(overrides: dict, key: str, default):
|
||||
if key in overrides:
|
||||
return overrides.get(key)
|
||||
return default
|
||||
|
||||
@staticmethod
|
||||
def _normalize_pct(value, min_value: float, max_value: float) -> float | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
pct = abs(float(value))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return min(max(pct, min_value), max_value)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_score_range(min_value, max_value) -> tuple[float | None, float | None]:
|
||||
def _bound(value) -> float | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
score = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if not np.isfinite(score):
|
||||
return None
|
||||
return min(max(score, 0.0), 100.0)
|
||||
|
||||
score_min = _bound(min_value)
|
||||
score_max = _bound(max_value)
|
||||
if score_min is not None and score_max is not None and score_min > score_max:
|
||||
score_min, score_max = score_max, score_min
|
||||
return score_min, score_max
|
||||
|
||||
@staticmethod
|
||||
def _normalize_params(params: dict, s: StrategyDef) -> dict:
|
||||
normalized = dict(params)
|
||||
for param in s.meta.get("params", []):
|
||||
pid = param.get("id")
|
||||
if not pid:
|
||||
continue
|
||||
value = normalized.get(pid, param.get("default"))
|
||||
p_type = param.get("type")
|
||||
if p_type in {"float", "int"}:
|
||||
try:
|
||||
num = float(value)
|
||||
except (TypeError, ValueError):
|
||||
num = float(param.get("default", 0) or 0)
|
||||
if param.get("min") is not None:
|
||||
num = max(num, float(param["min"]))
|
||||
if param.get("max") is not None:
|
||||
num = min(num, float(param["max"]))
|
||||
normalized[pid] = int(num) if p_type == "int" else num
|
||||
elif p_type == "select" and param.get("options"):
|
||||
normalized[pid] = value if value in param["options"] else param.get("default")
|
||||
elif p_type == "bool":
|
||||
if isinstance(value, bool):
|
||||
normalized[pid] = value
|
||||
elif isinstance(value, str):
|
||||
normalized[pid] = value.lower() == "true"
|
||||
else:
|
||||
normalized[pid] = bool(param.get("default", False))
|
||||
else:
|
||||
normalized[pid] = value
|
||||
return normalized
|
||||
|
||||
@staticmethod
|
||||
def _trade_to_dict(t) -> dict:
|
||||
return {
|
||||
"symbol": t.symbol,
|
||||
"name": t.name,
|
||||
"entry_date": str(t.entry_date) if isinstance(t.entry_date, date) else str(t.entry_date),
|
||||
"exit_date": str(t.exit_date) if isinstance(t.exit_date, date) else str(t.exit_date),
|
||||
"entry_price": t.entry_price,
|
||||
"exit_price": t.exit_price,
|
||||
"pnl_pct": t.pnl_pct,
|
||||
"duration": t.duration,
|
||||
"exit_reason": t.exit_reason,
|
||||
"shares": t.shares,
|
||||
"lots": t.lots,
|
||||
"position_pct": t.position_pct,
|
||||
"entry_value": t.entry_value,
|
||||
"exit_value": t.exit_value,
|
||||
"pnl_amount": t.pnl_amount,
|
||||
"entry_score": getattr(t, "entry_score", None),
|
||||
"entry_signal_date": str(t.entry_signal_date) if getattr(t, "entry_signal_date", None) is not None else None,
|
||||
"exit_signal_date": str(t.exit_signal_date) if getattr(t, "exit_signal_date", None) is not None else None,
|
||||
"blocked_exit_days": getattr(t, "blocked_exit_days", 0),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _config_to_dict(c: StrategyBacktestConfig) -> dict:
|
||||
score_min, score_max = StrategyBacktestService._normalize_score_range(
|
||||
(c.overrides or {}).get("score_min"),
|
||||
(c.overrides or {}).get("score_max"),
|
||||
)
|
||||
return {
|
||||
"strategy_id": c.strategy_id,
|
||||
"symbols": c.symbols,
|
||||
"start": str(c.start),
|
||||
"end": str(c.end),
|
||||
"params": c.params,
|
||||
"overrides": c.overrides,
|
||||
"score_min": score_min,
|
||||
"score_max": score_max,
|
||||
"matching": c.matching,
|
||||
"entry_fill": c.entry_fill,
|
||||
"exit_fill": c.exit_fill,
|
||||
"fees_pct": c.fees_pct,
|
||||
"slippage_bps": c.slippage_bps,
|
||||
"max_positions": c.max_positions,
|
||||
"max_exposure_pct": c.max_exposure_pct,
|
||||
"initial_capital": c.initial_capital,
|
||||
"position_sizing": c.position_sizing,
|
||||
"mode": c.mode,
|
||||
"holding_days": c.holding_days,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _apply_score(
|
||||
panel: pl.DataFrame,
|
||||
s: StrategyDef,
|
||||
overrides: dict | None,
|
||||
universe_mask: pl.Series | None = None,
|
||||
) -> pl.DataFrame:
|
||||
scoring = s.meta.get("scoring", {})
|
||||
scoring_overrides = (overrides or {}).get("scoring")
|
||||
if scoring_overrides:
|
||||
scoring = {**scoring, **scoring_overrides}
|
||||
|
||||
work = panel
|
||||
has_universe = universe_mask is not None and len(universe_mask) == len(panel)
|
||||
if has_universe:
|
||||
work = work.with_columns(universe_mask.rename("_score_universe"))
|
||||
|
||||
def _value_in_universe(col: str) -> pl.Expr:
|
||||
if has_universe:
|
||||
return pl.when(pl.col("_score_universe")).then(pl.col(col)).otherwise(None)
|
||||
return pl.col(col)
|
||||
|
||||
def _finish(df: pl.DataFrame) -> pl.DataFrame:
|
||||
return df.drop("_score_universe") if "_score_universe" in df.columns else df
|
||||
|
||||
if scoring:
|
||||
total_weight = sum(scoring.values())
|
||||
if total_weight > 0:
|
||||
score_parts: list[pl.Expr] = []
|
||||
for col, weight in scoring.items():
|
||||
if col not in work.columns:
|
||||
continue
|
||||
w = weight / total_weight
|
||||
value = _value_in_universe(col)
|
||||
col_min = value.min().over("date")
|
||||
col_max = value.max().over("date")
|
||||
col_range = col_max - col_min
|
||||
normalized = pl.when(col_range > 0).then(
|
||||
(pl.col(col) - col_min) / col_range
|
||||
).otherwise(pl.lit(0.5))
|
||||
if has_universe:
|
||||
normalized = pl.when(pl.col("_score_universe")).then(normalized).otherwise(0.0)
|
||||
score_parts.append(normalized * w)
|
||||
if score_parts:
|
||||
score_expr = score_parts[0]
|
||||
for part in score_parts[1:]:
|
||||
score_expr = score_expr + part
|
||||
return _finish(work.with_columns((score_expr * 100).fill_null(0).alias("score")))
|
||||
|
||||
order_by = s.meta.get("order_by")
|
||||
if order_by and order_by != "score" and order_by in work.columns:
|
||||
direction = 1 if s.meta.get("descending", True) else -1
|
||||
score_expr = pl.col(order_by).fill_null(0) * direction
|
||||
if has_universe:
|
||||
score_expr = pl.when(pl.col("_score_universe")).then(score_expr).otherwise(0.0)
|
||||
return _finish(work.with_columns(score_expr.alias("score")))
|
||||
return _finish(work.with_columns(pl.lit(0.0).alias("score")))
|
||||
@@ -0,0 +1,127 @@
|
||||
"""全局配置 — 从环境变量 / .env 读取。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
# ── 运行环境检测 ──────────────────────────────────────────
|
||||
# PyInstaller 打包后: __file__ 指向临时解压目录 _MEIPASS, 不能作为路径基准。
|
||||
# 此时:
|
||||
# - 只读资源 (tiers.yaml / 前端 dist) 放在 _MEIPASS 内
|
||||
# - 可写用户数据 (data_dir) 放在可执行文件旁的用户目录
|
||||
# 非 frozen 模式 (开发/Docker): 保持原有 __file__ 推导, 行为完全不变。
|
||||
_IS_FROZEN = getattr(sys, "frozen", False)
|
||||
|
||||
|
||||
def _user_data_root() -> Path:
|
||||
"""桌面版用户数据根目录。
|
||||
|
||||
定位策略 (按优先级):
|
||||
1. 环境变量 DATA_DIR (pydantic-settings 自动注入到 settings.data_dir, 不在此处理)
|
||||
2. 打包桌面版: exe 同级的 data/ 子目录 (<安装目录>/data/)
|
||||
—— 与程序同处一个总目录 (用户选择的安装目录), 视觉直观, 便于备份/迁移。
|
||||
3. 非 frozen (开发模式): 项目根 data/
|
||||
|
||||
为什么不用 platformdirs 默认 (%LOCALAPPDATA%) 作为主路径:
|
||||
- 落在 C 盘系统目录, 用户不易察觉, 占系统盘空间
|
||||
- 用户期望「数据跟随程序」(便于备份/迁移)
|
||||
为什么放 {app}/data (exe 旁的 data/) 而非 {app} 外的兄弟目录:
|
||||
- 用户体验: 用户选了安装目录, 自然期望「程序和数据都在这」, 单一总目录更直观。
|
||||
- 数据安全: Inno Setup 覆盖安装(升级)时只往 {app} 写新程序文件, 不会清空
|
||||
目录里不在安装清单上的运行时文件 (data/ 即此类), 故覆盖安装不丢数据。
|
||||
(注意: 卸载时需在 .iss 中豁免 data/, 见 packaging/tickflow.iss 的 [UninstallDelete]。)
|
||||
旧版本数据迁移: 见 DataStore._migrate_legacy_data_dir(), 老用户首次启动自动搬迁。
|
||||
"""
|
||||
# 打包桌面版: exe 同级的 data/ 子目录 (与程序同一总目录, 覆盖安装不丢数据)
|
||||
if _IS_FROZEN:
|
||||
exe_dir = Path(sys.executable).resolve().parent
|
||||
return exe_dir / "data"
|
||||
|
||||
# 开发模式: 项目根 data/
|
||||
return _PROJECT_ROOT / "data"
|
||||
|
||||
|
||||
def _resource_root() -> Path:
|
||||
"""只读资源根目录。
|
||||
|
||||
frozen: PyInstaller 解压目录 (_MEIPASS)
|
||||
非 frozen: 项目根目录 (源码树)
|
||||
"""
|
||||
if _IS_FROZEN:
|
||||
# sys._MEIPASS 是 PyInstaller 注入的解压根
|
||||
return Path(getattr(sys, "_MEIPASS", Path(sys.executable).resolve().parent))
|
||||
return Path(__file__).resolve().parent.parent.parent
|
||||
|
||||
|
||||
def _project_root() -> Path:
|
||||
"""项目根目录 (非 frozen 用)。"""
|
||||
return Path(__file__).resolve().parent.parent.parent
|
||||
|
||||
|
||||
_PROJECT_ROOT = _project_root()
|
||||
_RESOURCE_ROOT = _resource_root()
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=str(_RESOURCE_ROOT / ".env") if not _IS_FROZEN else ".env",
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore",
|
||||
)
|
||||
|
||||
# TickFlow
|
||||
tickflow_api_key: str = Field(default="", description="留空启用 free 模式")
|
||||
|
||||
# AI
|
||||
ai_provider: str = "openai_compat"
|
||||
ai_base_url: str = "https://api.alysc.top"
|
||||
ai_api_key: str = ""
|
||||
ai_model: str = "gpt-5.5"
|
||||
ai_codex_command: str = "codex"
|
||||
# 默认浏览器风格 UA,绕过 Cloudflare 等 CDN/WAF 的 Bot 拦截(Issue #8)。
|
||||
# 用户可在 AI 设置页按需修改。
|
||||
ai_user_agent: str = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/131.0.0.0 Safari/537.36"
|
||||
)
|
||||
|
||||
# Server
|
||||
host: str = "0.0.0.0"
|
||||
port: int = 3018
|
||||
log_level: str = "INFO"
|
||||
backtest_range_guard: bool = False
|
||||
|
||||
# Auth — 首次启动时预置访问密码(明文, 仅用于初始化, 详见 services/auth.bootstrap_from_env)
|
||||
# 公网服务器部署时免去 SSH 端口转发设密码的麻烦。写入 auth.json(哈希)后即不再读取。
|
||||
auth_password: str = ""
|
||||
|
||||
# Data — frozen: exe 同级 data/ 子目录; 非 frozen: 项目根 data/
|
||||
# (均可被环境变量 DATA_DIR 覆盖, pydantic-settings 自动注入)
|
||||
data_dir: Path = _user_data_root()
|
||||
|
||||
# tiers.yaml 路径 — frozen: 资源目录内; 非 frozen: 项目根目录
|
||||
tiers_yaml: Path = _RESOURCE_ROOT / "tiers.yaml" if _IS_FROZEN else _PROJECT_ROOT / "tiers.yaml"
|
||||
|
||||
# 静态文件(前端 dist) — frozen: 资源目录的 static/; 非 frozen: frontend/dist
|
||||
static_dir: Path = _RESOURCE_ROOT / "static" if _IS_FROZEN else (_PROJECT_ROOT / "frontend" / "dist")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _resolve_paths(self) -> Settings:
|
||||
"""确保 data_dir 是绝对路径(环境变量传入的相对路径基于项目根目录解析)。"""
|
||||
if not self.data_dir.is_absolute():
|
||||
# 相对路径基于项目根目录解析,而非 CWD
|
||||
self.data_dir = (_PROJECT_ROOT / self.data_dir).resolve()
|
||||
return self
|
||||
|
||||
@property
|
||||
def use_free_mode(self) -> bool:
|
||||
"""是否走 Free 模式。优先看 secrets.json,其次看 .env。"""
|
||||
from app import secrets_store
|
||||
return not secrets_store.get_tickflow_key()
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,8 @@
|
||||
"""Market data provider abstraction.
|
||||
|
||||
Providers normalize external data sources into the internal parquet schema.
|
||||
"""
|
||||
from app.data_providers.base import AssetType, MarketDataProvider, ProviderCapabilities
|
||||
from app.data_providers.registry import get_provider
|
||||
|
||||
__all__ = ["AssetType", "MarketDataProvider", "ProviderCapabilities", "get_provider"]
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Provider contracts for external market data sources.
|
||||
|
||||
The first implementation wraps TickFlow. Other providers (Tushare/AkShare/etc.)
|
||||
should return the same normalized Polars schemas so storage, indicators and
|
||||
backtests stay data-source agnostic.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Literal, Protocol
|
||||
|
||||
import polars as pl
|
||||
|
||||
AssetType = Literal["stock", "index", "etf"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProviderCapabilities:
|
||||
instruments: bool = False
|
||||
daily: bool = False
|
||||
adj_factor: bool = False
|
||||
minute: bool = False
|
||||
realtime: bool = False
|
||||
financial: bool = False
|
||||
|
||||
|
||||
class MarketDataProvider(Protocol):
|
||||
name: str
|
||||
capabilities: ProviderCapabilities
|
||||
|
||||
def get_instruments(self, asset_type: AssetType) -> pl.DataFrame:
|
||||
"""Return normalized instruments: symbol/name/code/exchange/asset_type/source."""
|
||||
|
||||
def get_daily(
|
||||
self,
|
||||
symbols: list[str],
|
||||
start_time: datetime | None,
|
||||
end_time: datetime | None,
|
||||
asset_type: AssetType,
|
||||
) -> pl.DataFrame:
|
||||
"""Return normalized daily K rows."""
|
||||
|
||||
def get_adj_factors(
|
||||
self,
|
||||
symbols: list[str],
|
||||
start_time: datetime | None,
|
||||
end_time: datetime | None,
|
||||
asset_type: AssetType,
|
||||
) -> pl.DataFrame:
|
||||
"""Return normalized adjustment factors: symbol/trade_date/ex_factor."""
|
||||
|
||||
def get_minute(
|
||||
self,
|
||||
symbols: list[str],
|
||||
start_time: datetime | None,
|
||||
end_time: datetime | None,
|
||||
asset_type: AssetType,
|
||||
freq: str = "1m",
|
||||
) -> pl.DataFrame:
|
||||
"""Return normalized minute K rows. Implementations may return empty."""
|
||||
|
||||
def get_realtime(
|
||||
self,
|
||||
universes: list[str] | None = None,
|
||||
symbols: list[str] | None = None,
|
||||
) -> pl.DataFrame:
|
||||
"""Return normalized realtime quotes. Implementations may return empty."""
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Normalize provider responses into internal Polars schemas."""
|
||||
from __future__ import annotations
|
||||
|
||||
import polars as pl
|
||||
|
||||
from app.indicators.pipeline import filter_halt_days
|
||||
|
||||
DAILY_COLS = ["symbol", "date", "open", "high", "low", "close", "volume", "amount"]
|
||||
ADJ_FACTOR_COLS = ["symbol", "trade_date", "ex_factor"]
|
||||
INSTRUMENT_COLS = ["symbol", "name", "code", "exchange", "asset_type", "source"]
|
||||
|
||||
|
||||
def to_polars(data) -> pl.DataFrame:
|
||||
if data is None:
|
||||
return pl.DataFrame()
|
||||
if isinstance(data, pl.DataFrame):
|
||||
return data
|
||||
if isinstance(data, dict):
|
||||
rows: list[dict] = []
|
||||
for sym, values in data.items():
|
||||
for item in values or []:
|
||||
row = dict(item or {})
|
||||
row.setdefault("symbol", sym)
|
||||
rows.append(row)
|
||||
return pl.DataFrame(rows) if rows else pl.DataFrame()
|
||||
if hasattr(data, "reset_index"):
|
||||
return pl.from_pandas(data.reset_index())
|
||||
try:
|
||||
return pl.DataFrame(data)
|
||||
except Exception: # noqa: BLE001
|
||||
return pl.DataFrame()
|
||||
|
||||
|
||||
def normalize_daily(data, default_symbol: str | None = None, source: str = "tickflow") -> pl.DataFrame: # noqa: ARG001
|
||||
df = to_polars(data)
|
||||
if df.is_empty():
|
||||
return df
|
||||
rename_map = {
|
||||
"ts_code": "symbol",
|
||||
"trade_date": "date",
|
||||
"datetime": "date",
|
||||
"vol": "volume",
|
||||
"amt": "amount",
|
||||
}
|
||||
df = df.rename({k: v for k, v in rename_map.items() if k in df.columns})
|
||||
if "symbol" not in df.columns and default_symbol:
|
||||
df = df.with_columns(pl.lit(default_symbol).alias("symbol"))
|
||||
if "date" in df.columns and df.schema["date"] != pl.Date:
|
||||
df = df.with_columns(pl.col("date").cast(pl.Date, strict=False))
|
||||
for col in ("open", "high", "low", "close", "volume", "amount"):
|
||||
if col in df.columns:
|
||||
df = df.with_columns(pl.col(col).cast(pl.Float64, strict=False))
|
||||
df = filter_halt_days(df)
|
||||
keep = [c for c in DAILY_COLS if c in df.columns]
|
||||
return df.select(keep) if keep else pl.DataFrame()
|
||||
|
||||
|
||||
def normalize_adj_factors(data, source: str = "tickflow") -> pl.DataFrame: # noqa: ARG001
|
||||
df = to_polars(data)
|
||||
if df.is_empty():
|
||||
return df
|
||||
rename_map = {
|
||||
"timestamp": "trade_date",
|
||||
"date": "trade_date",
|
||||
"adj_factor": "ex_factor",
|
||||
}
|
||||
df = df.rename({k: v for k, v in rename_map.items() if k in df.columns})
|
||||
if "trade_date" in df.columns:
|
||||
if df.schema["trade_date"] in {pl.Int64, pl.Int32, pl.UInt64, pl.UInt32, pl.Float64, pl.Float32}:
|
||||
df = df.with_columns(
|
||||
pl.from_epoch(pl.col("trade_date").cast(pl.Int64), time_unit="ms").dt.date().alias("trade_date")
|
||||
)
|
||||
else:
|
||||
df = df.with_columns(pl.col("trade_date").cast(pl.Date, strict=False))
|
||||
if "ex_factor" in df.columns:
|
||||
df = df.with_columns(pl.col("ex_factor").cast(pl.Float64, strict=False))
|
||||
keep = [c for c in ADJ_FACTOR_COLS if c in df.columns]
|
||||
return df.select(keep).drop_nulls() if len(keep) == len(ADJ_FACTOR_COLS) else pl.DataFrame()
|
||||
|
||||
|
||||
def normalize_instruments(rows: list[dict], asset_type: str, source: str = "tickflow") -> pl.DataFrame:
|
||||
if not rows:
|
||||
return pl.DataFrame()
|
||||
out: list[dict] = []
|
||||
for item in rows:
|
||||
symbol = item.get("symbol")
|
||||
if not symbol:
|
||||
continue
|
||||
out.append({
|
||||
"symbol": str(symbol),
|
||||
"name": item.get("name") or str(symbol),
|
||||
"code": item.get("code") or str(symbol).split(".")[0],
|
||||
"exchange": item.get("exchange"),
|
||||
"asset_type": asset_type,
|
||||
"source": source,
|
||||
})
|
||||
if not out:
|
||||
return pl.DataFrame()
|
||||
return pl.DataFrame(out).select(INSTRUMENT_COLS).unique(subset=["symbol"], keep="last").sort("symbol")
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Provider registry."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.data_providers.tickflow_provider import TickFlowProvider
|
||||
|
||||
_PROVIDERS = {
|
||||
"tickflow": TickFlowProvider,
|
||||
}
|
||||
|
||||
|
||||
def get_provider(name: str = "tickflow"):
|
||||
provider_cls = _PROVIDERS.get((name or "tickflow").lower())
|
||||
if provider_cls is None:
|
||||
raise ValueError(f"Unsupported data provider: {name}")
|
||||
return provider_cls()
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Internal provider schema column lists."""
|
||||
from __future__ import annotations
|
||||
|
||||
DAILY_COLUMNS = [
|
||||
"symbol", "asset_type", "source", "date", "open", "high", "low", "close",
|
||||
"volume", "amount", "pre_close", "change_pct",
|
||||
]
|
||||
|
||||
ADJ_FACTOR_COLUMNS = ["symbol", "asset_type", "source", "trade_date", "ex_factor"]
|
||||
|
||||
INSTRUMENT_COLUMNS = [
|
||||
"symbol", "name", "exchange", "asset_type", "source", "list_date", "status",
|
||||
]
|
||||
|
||||
MINUTE_COLUMNS = [
|
||||
"symbol", "asset_type", "source", "datetime", "open", "high", "low", "close",
|
||||
"volume", "amount", "freq",
|
||||
]
|
||||
@@ -0,0 +1,120 @@
|
||||
"""TickFlow provider implementation."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
import polars as pl
|
||||
|
||||
from app.data_providers.base import AssetType, ProviderCapabilities
|
||||
from app.data_providers.normalizer import normalize_adj_factors, normalize_daily, normalize_instruments
|
||||
from app.tickflow.client import get_client
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_EXCHANGES = ["SH", "SZ", "BJ"]
|
||||
|
||||
|
||||
class TickFlowProvider:
|
||||
name = "tickflow"
|
||||
capabilities = ProviderCapabilities(
|
||||
instruments=True,
|
||||
daily=True,
|
||||
adj_factor=True,
|
||||
minute=True,
|
||||
realtime=True,
|
||||
financial=True,
|
||||
)
|
||||
|
||||
def get_instruments(self, asset_type: AssetType) -> pl.DataFrame:
|
||||
tf = get_client()
|
||||
instrument_type = "stock" if asset_type == "stock" else asset_type
|
||||
rows: list[dict] = []
|
||||
for ex in _EXCHANGES:
|
||||
try:
|
||||
items = tf.exchanges.get_instruments(ex, instrument_type=instrument_type)
|
||||
rows.extend([it for it in (items or []) if isinstance(it, dict)])
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("TickFlow instruments %s/%s failed: %s", ex, instrument_type, e)
|
||||
return normalize_instruments(rows, asset_type=asset_type, source=self.name)
|
||||
|
||||
def get_daily(
|
||||
self,
|
||||
symbols: list[str],
|
||||
start_time: datetime | None,
|
||||
end_time: datetime | None,
|
||||
asset_type: AssetType, # noqa: ARG002
|
||||
) -> pl.DataFrame:
|
||||
if not symbols:
|
||||
return pl.DataFrame()
|
||||
tf = get_client()
|
||||
kwargs = {
|
||||
"period": "1d",
|
||||
"adjust": "none",
|
||||
"count": 10000 if start_time and end_time else 250,
|
||||
"as_dataframe": True,
|
||||
"show_progress": False,
|
||||
}
|
||||
if start_time and end_time:
|
||||
from app.services.kline_sync import _datetime_to_ms
|
||||
kwargs["start_time"] = _datetime_to_ms(start_time)
|
||||
kwargs["end_time"] = _datetime_to_ms(end_time)
|
||||
raw = tf.klines.batch(symbols, **kwargs)
|
||||
frames: list[pl.DataFrame] = []
|
||||
if isinstance(raw, dict):
|
||||
for sym, sub in raw.items():
|
||||
normalized = normalize_daily(sub, default_symbol=sym, source=self.name)
|
||||
if not normalized.is_empty():
|
||||
frames.append(normalized)
|
||||
else:
|
||||
normalized = normalize_daily(raw, source=self.name)
|
||||
if not normalized.is_empty():
|
||||
frames.append(normalized)
|
||||
return pl.concat(frames, how="diagonal_relaxed") if frames else pl.DataFrame()
|
||||
|
||||
def get_adj_factors(
|
||||
self,
|
||||
symbols: list[str],
|
||||
start_time: datetime | None,
|
||||
end_time: datetime | None,
|
||||
asset_type: AssetType, # noqa: ARG002
|
||||
) -> pl.DataFrame:
|
||||
if not symbols:
|
||||
return pl.DataFrame()
|
||||
tf = get_client()
|
||||
kwargs = {"as_dataframe": False}
|
||||
if start_time or end_time:
|
||||
from app.services.kline_sync import _datetime_to_ms
|
||||
if start_time:
|
||||
kwargs["start_time"] = _datetime_to_ms(start_time)
|
||||
if end_time:
|
||||
kwargs["end_time"] = _datetime_to_ms(end_time)
|
||||
raw = tf.klines.ex_factors(symbols, **kwargs)
|
||||
return normalize_adj_factors(raw, source=self.name)
|
||||
|
||||
def get_minute(
|
||||
self,
|
||||
symbols: list[str],
|
||||
start_time: datetime | None,
|
||||
end_time: datetime | None,
|
||||
asset_type: AssetType, # noqa: ARG002
|
||||
freq: str = "1m", # noqa: ARG002
|
||||
) -> pl.DataFrame:
|
||||
# Existing minute sync remains in app.services.kline_sync for now.
|
||||
return pl.DataFrame()
|
||||
|
||||
def get_realtime(
|
||||
self,
|
||||
universes: list[str] | None = None,
|
||||
symbols: list[str] | None = None,
|
||||
) -> pl.DataFrame:
|
||||
tf = get_client()
|
||||
if universes and symbols:
|
||||
raise ValueError("TickFlow realtime accepts either universes or symbols, not both")
|
||||
if universes:
|
||||
resp = tf.quotes.get_by_universes(universes=universes)
|
||||
elif symbols:
|
||||
resp = tf.quotes.get(symbols=symbols)
|
||||
else:
|
||||
return pl.DataFrame()
|
||||
return pl.DataFrame(resp or [])
|
||||
@@ -0,0 +1,241 @@
|
||||
"""桌面客户端入口 — uvicorn 后台服务 + pywebview 桌面窗口。
|
||||
|
||||
运行方式:
|
||||
开发模式: python -m app.desktop (需 pip install pywebview)
|
||||
打包后: 双击可执行文件即可
|
||||
|
||||
职责:
|
||||
1. 单实例锁 — 已运行则聚焦已有窗口并退出
|
||||
2. 选可用端口 — 从 settings.port 起, 被占则递增
|
||||
3. 后台线程起 uvicorn (仅监听 127.0.0.1, 不暴露外网)
|
||||
4. 主线程起 pywebview 窗口渲染前端
|
||||
5. 窗口关闭 → 优雅停止 uvicorn → 进程退出
|
||||
|
||||
不含: 业务逻辑、配置持久化、监控告警 (全在 app.main 里)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_APP_NAME = "TickFlow 股票面板"
|
||||
_BASE_PORT = 3018
|
||||
_PORT_PROBE_RANGE = 50 # 从 3018 起最多试 50 个端口
|
||||
|
||||
|
||||
def _ensure_data_dir_writable() -> None:
|
||||
"""确保用户数据目录可写 (lifespan 会创建子目录, 这里只验证根目录)。
|
||||
|
||||
data_dir 在 frozen 模式下指向用户目录 (见 config.py), 非可写会导致
|
||||
DuckDB 视图 / parquet 落盘全失败。提前失败胜过启动后乱报错。
|
||||
"""
|
||||
from app.config import settings
|
||||
|
||||
data_root = settings.data_dir
|
||||
try:
|
||||
data_root.mkdir(parents=True, exist_ok=True)
|
||||
probe = data_root / ".write_probe"
|
||||
probe.write_text("ok", encoding="utf-8")
|
||||
probe.unlink(missing_ok=True)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error("数据目录不可写, 桌面版无法运行: %s (%s)", data_root, e)
|
||||
raise
|
||||
|
||||
|
||||
def _acquire_single_instance() -> bool:
|
||||
"""单实例锁。已运行返回 False (本进程应退出), 否则 True。
|
||||
|
||||
用 data_dir/.desktop.lock 文件锁实现。跨进程, 文件存在即视为已运行
|
||||
(简单可靠; 不引入 msvcrt/fcntl 平台差异)。
|
||||
"""
|
||||
from app.config import settings
|
||||
|
||||
lock_path = settings.data_dir / ".desktop.lock"
|
||||
if lock_path.exists():
|
||||
# 软检测: 写入进程 PID, 若该 PID 已不存在则视为残留锁, 允许接管
|
||||
try:
|
||||
pid_str = lock_path.read_text(encoding="utf-8").strip()
|
||||
pid = int(pid_str) if pid_str.isdigit() else None
|
||||
except Exception: # noqa: BLE001
|
||||
pid = None
|
||||
|
||||
if pid is not None and _pid_alive(pid):
|
||||
logger.warning("检测到已有实例运行 (PID %d), 本进程退出", pid)
|
||||
return False
|
||||
# 残留锁: 清理后继续
|
||||
logger.info("清理残留单实例锁 (PID %s 已不存在)", pid)
|
||||
|
||||
lock_path.write_text(str(_current_pid()), encoding="utf-8")
|
||||
return True
|
||||
|
||||
|
||||
def _release_single_instance() -> None:
|
||||
from app.config import settings
|
||||
|
||||
lock_path = settings.data_dir / ".desktop.lock"
|
||||
try:
|
||||
lock_path.unlink(missing_ok=True)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
def _pid_alive(pid: int) -> bool:
|
||||
"""检查指定 PID 的进程是否存活。"""
|
||||
import os
|
||||
|
||||
if os.name == "nt":
|
||||
# Windows: 0 表示存在, 其它是异常
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
else:
|
||||
try:
|
||||
os.kill(pid, 0) # signal 0 = 探测存活, 不实际发信号
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _current_pid() -> int:
|
||||
import os
|
||||
|
||||
return os.getpid()
|
||||
|
||||
|
||||
def _find_free_port(start: int, count: int = _PORT_PROBE_RANGE) -> int:
|
||||
"""从 start 起找第一个可用端口。全部被占则返回 start (交给 uvicorn 报错)。"""
|
||||
for port in range(start, start + count):
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
try:
|
||||
s.bind(("127.0.0.1", port))
|
||||
return port
|
||||
except OSError:
|
||||
continue
|
||||
return start
|
||||
|
||||
|
||||
def _run_uvmicorn(port: int, ready_event: threading.Event) -> None:
|
||||
"""后台线程: 启动 uvicorn 服务。ready_event 在线程退出时置位 (通知主线程)。"""
|
||||
import uvicorn
|
||||
|
||||
# 延迟 import app, 确保配置层已就绪 (frozen 检测在 config.py 导入时完成)
|
||||
from app.main import app
|
||||
|
||||
config = uvicorn.Config(
|
||||
app,
|
||||
host="127.0.0.1", # 仅本机, 不暴露外网 (桌面版无需远程访问)
|
||||
port=port,
|
||||
log_level="info",
|
||||
access_log=False, # 桌面版不需要访问日志
|
||||
loop="auto",
|
||||
)
|
||||
server = uvicorn.Server(config)
|
||||
|
||||
# 线程结束时通知主线程 (无论正常退出还是异常)
|
||||
def _signal_done(*exc):
|
||||
ready_event.set()
|
||||
server.config.callback_notify = None # 不用 notify 机制
|
||||
|
||||
try:
|
||||
server.run()
|
||||
finally:
|
||||
ready_event.set()
|
||||
|
||||
|
||||
def _wait_for_server(port: int, timeout: float = 60.0) -> bool:
|
||||
"""轮询 health 接口直到后端就绪或超时。
|
||||
|
||||
比 monkey-patch uvicorn 内部方法更健壮, 不依赖版本内部实现。
|
||||
"""
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
url = f"http://127.0.0.1:{port}/health"
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return True
|
||||
except (urllib.error.URLError, ConnectionError, OSError):
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def _open_window(url: str) -> None:
|
||||
"""主线程: 用 pywebview 打开桌面窗口。"""
|
||||
import webview # type: ignore[import-not-found]
|
||||
|
||||
window = webview.create_window(
|
||||
_APP_NAME,
|
||||
url,
|
||||
width=1440,
|
||||
height=900,
|
||||
min_size=(1024, 700),
|
||||
# 桌面版固定单窗口, 禁用外部浏览器跳转
|
||||
confirm_close=False,
|
||||
)
|
||||
# pywebview 会阻塞主线程直到窗口关闭
|
||||
webview.start(debug=False)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""桌面客户端主入口。返回进程退出码。"""
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
)
|
||||
|
||||
try:
|
||||
_ensure_data_dir_writable()
|
||||
except Exception:
|
||||
# 数据目录不可写是致命错误, 无法继续
|
||||
return 1
|
||||
|
||||
# 单实例: 已运行则退出
|
||||
if not _acquire_single_instance():
|
||||
return 0
|
||||
|
||||
try:
|
||||
port = _find_free_port(_BASE_PORT)
|
||||
logger.info("桌面版后端将监听 127.0.0.1:%d", port)
|
||||
|
||||
# 后台线程起 uvicorn
|
||||
ready = threading.Event()
|
||||
server_thread = threading.Thread(
|
||||
target=_run_uvmicorn, args=(port, ready), daemon=True,
|
||||
name="uvicorn",
|
||||
)
|
||||
server_thread.start()
|
||||
|
||||
# 轮询 health 接口等后端就绪 (含 lifespan 初始化, 最多 60s)
|
||||
if not _wait_for_server(port, timeout=60.0):
|
||||
logger.error("后端启动超时, 桌面版退出")
|
||||
_release_single_instance()
|
||||
return 1
|
||||
|
||||
url = f"http://127.0.0.1:{port}"
|
||||
logger.info("打开桌面窗口: %s", url)
|
||||
_open_window(url)
|
||||
|
||||
# 窗口关闭后, 进程退出 (daemon 线程会被回收)
|
||||
logger.info("窗口已关闭, 桌面版退出")
|
||||
return 0
|
||||
except KeyboardInterrupt:
|
||||
return 0
|
||||
finally:
|
||||
_release_single_instance()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
"""技术指标 — Polars 实现(§7.5 / §7.7)。"""
|
||||
@@ -0,0 +1,600 @@
|
||||
"""关键价位计算 —— 独立模块,纯函数,无 IO / 无存储。
|
||||
|
||||
输入: 已经包含 OHLCV 的 polars 日 K DataFrame(内存中,通常来自 KlineRepository 缓存)。
|
||||
输出: 4 类结构化价位点,供:
|
||||
- 图表 markLine 渲染(压力位 / 支撑位 / 成交密集区 / 枢轴点 / 前高前低)
|
||||
- AI 个股分析提示词(价位上下文)
|
||||
|
||||
设计:
|
||||
- 纯函数 + polars 向量化,毫秒级,无需落盘。
|
||||
- 每个点位带 {value, label, type, side, strength?},前端直接画水平价格线。
|
||||
- NaN/Inf 全部过滤,空数据返回空列表,不抛异常。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import polars as pl
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 输出结构
|
||||
# ================================================================
|
||||
|
||||
class PriceLevel:
|
||||
"""单个价位点的数据结构(用 dict 表达,这里只作文档说明)。
|
||||
|
||||
{
|
||||
"value": 12.34, # 价格
|
||||
"label": "压力位 R1", # 显示标签
|
||||
"type": "pivot", # 类型分组(同类型用一个开关按钮控制显隐)
|
||||
"side": "resistance", # 方向:resistance(压力) / support(支撑) / neutral
|
||||
"strength": "medium", # 强度:strong / medium / weak(可选,影响线型)
|
||||
"rank": 1, # 档位(仅 pivot 有):0=P,1=R1/S1,2=R2/S2,3=R3/S3
|
||||
# 前端按"显示到第几档"过滤,非 pivot 点位无此字段
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
# 价位分组 → 开关 key。前端按这个 type 显隐。
|
||||
LEVEL_TYPES = {
|
||||
"sr": "压力支撑", # 成交密集区(价量:Volume Profile POC + 高成交密集区)
|
||||
"pivot": "枢轴点", # 经典 Pivot P/R/S
|
||||
"extreme": "前高前低", # 60/250 日极值 + 近期 swing 高低点
|
||||
"boll": "布林带", # MA20 ± 2σ,标准差波动带(参考性,非真实支撑压力)
|
||||
"keltner_s": "Keltner短期", # MA20 ± 2×ATR
|
||||
"keltner_m": "Keltner中期", # MA60 ± 2.5×ATR
|
||||
"keltner_l": "Keltner长期", # MA120 ± 3×ATR(牛熊趋势边界)
|
||||
"atr_stop": "ATR止损", # close±nATR 动态止盈止损
|
||||
"gap": "缺口位", # 未回补跳空缺口
|
||||
"fib": "斐波那契", # 回撤位 0.236~0.786
|
||||
"round": "整数关口", # 心理整数位
|
||||
}
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 1. 压力位 / 支撑位 —— 成交量分布 (Volume Profile)
|
||||
# ================================================================
|
||||
|
||||
def _support_resistance(df: pl.DataFrame, bins: int = 40) -> list[dict]:
|
||||
"""成交量分布 (Volume Profile) —— 真正基于价+量的支撑/压力位。
|
||||
|
||||
把每个价位层按价格分桶,统计落在该桶的累计成交量,取高成交密集区作为关键
|
||||
价位带。与 BOLL/Keltner 等"波动通道"不同,成交密集区反映的是真实换手堆积,
|
||||
是经典意义的支撑/压力。
|
||||
|
||||
密集区 = 成交量高于均值的桶,按成交量降序取前 3 个作为关键价位带:
|
||||
- POC(控制点):成交量最大的桶,标记为 strong
|
||||
- 其他高成交区:高于均值,标记为 medium
|
||||
"""
|
||||
if df.is_empty() or "volume" not in df.columns or df.height < 20:
|
||||
return []
|
||||
|
||||
hi = float(df["high"].max())
|
||||
lo = float(df["low"].min())
|
||||
if not (hi > lo > 0):
|
||||
return []
|
||||
|
||||
# 每根 K 的价格区间中点 × 成交量 ≈ 该价位层贡献的成交量(简化模型)
|
||||
df2 = df.select([
|
||||
((pl.col("high") + pl.col("low")) / 2).alias("mid"),
|
||||
pl.col("volume").alias("vol"),
|
||||
]).drop_nulls()
|
||||
|
||||
# 桶边界:bins 个桶需要 bins-1 个内部 break,cut 据此切成 bins 段
|
||||
step = (hi - lo) / bins
|
||||
edges = [lo + i * step for i in range(bins + 1)] # 含首尾,共 bins+1 个边界值
|
||||
breaks = edges[1:-1] # 内部 break,bins-1 个
|
||||
bin_labels = [f"{i}" for i in range(bins)] # 桶序号 0..bins-1
|
||||
# 至少要有 1 个不同的内部 break
|
||||
if len(set(f"{b:.6f}" for b in breaks)) < 1:
|
||||
return []
|
||||
|
||||
df2 = df2.with_columns(
|
||||
pl.col("mid").cut(breaks, labels=bin_labels).alias("bin")
|
||||
)
|
||||
prof = df2.group_by("bin").agg(pl.col("vol").sum())
|
||||
if prof.is_empty():
|
||||
return []
|
||||
|
||||
# 把桶序号字符串还原为 int,以便回查 edges;并按序号排序保证可索引
|
||||
prof = prof.with_columns(pl.col("bin").cast(pl.Int64).alias("bi")).sort("bi")
|
||||
bin_ids = prof["bi"].to_list()
|
||||
vols = prof["vol"].to_list()
|
||||
mean_vol = sum(vols) / len(vols) if vols else 0
|
||||
|
||||
def bin_mid(bin_id: int) -> float:
|
||||
return (edges[bin_id] + edges[bin_id + 1]) / 2
|
||||
|
||||
close = float(df.tail(1)["close"][0])
|
||||
|
||||
out: list[dict] = []
|
||||
# POC:成交量最大的桶
|
||||
poc_pos = max(range(len(vols)), key=lambda i: vols[i])
|
||||
poc_mid = bin_mid(bin_ids[poc_pos])
|
||||
out.append({"value": round(poc_mid, 2), "label": "成交密集区(POC)",
|
||||
"type": "sr", "side": _side(poc_mid, close), "strength": "strong"})
|
||||
|
||||
# 其他高成交区(高于均值,排除 POC),按成交量降序取 2 个
|
||||
candidates = [(i, v) for i, v in enumerate(vols) if v > mean_vol and i != poc_pos]
|
||||
candidates.sort(key=lambda x: x[1], reverse=True)
|
||||
for i, _v in candidates[:2]:
|
||||
mid = bin_mid(bin_ids[i])
|
||||
out.append({"value": round(mid, 2), "label": "成交密集区",
|
||||
"type": "sr", "side": _side(mid, close), "strength": "medium"})
|
||||
return out
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 2. 枢轴点 (Pivot Point) —— 经典公式,基于最近完整交易日
|
||||
# ================================================================
|
||||
|
||||
def _pivot_points(df: pl.DataFrame) -> list[dict]:
|
||||
"""经典 Pivot:P = (H+L+C)/3, R1/R2/R3, S1/S2/S3。
|
||||
|
||||
基准:最后 1 根 K(代表"上一交易日")。实务中常用前一日,这里取最后一根。
|
||||
"""
|
||||
if df.is_empty():
|
||||
return []
|
||||
last = df.tail(1)
|
||||
h = last["high"][0]
|
||||
l = last["low"][0]
|
||||
c = last["close"][0]
|
||||
if not _ok(h) or not _ok(l) or not _ok(c):
|
||||
return []
|
||||
|
||||
h, l, c = float(h), float(l), float(c)
|
||||
p = (h + l + c) / 3
|
||||
r1 = 2 * p - l
|
||||
s1 = 2 * p - h
|
||||
r2 = p + (h - l)
|
||||
s2 = p - (h - l)
|
||||
r3 = h + 2 * (p - l)
|
||||
s3 = l - 2 * (h - p)
|
||||
|
||||
def lv(v: float, label: str, side: str, strength: str, rank: int) -> dict:
|
||||
# rank:档位标记,前端据此按"显示到第几档"过滤
|
||||
# 0 = 枢轴位 P(始终显示)
|
||||
# 1 = R1/S1(第一档压力/支撑)
|
||||
# 2 = R2/S2(第二档)
|
||||
# 3 = R3/S3(第三档,极端,实际很少触及)
|
||||
return {"value": round(v, 2), "label": label, "type": "pivot",
|
||||
"side": side, "strength": strength, "rank": rank}
|
||||
|
||||
return [
|
||||
lv(p, "枢轴位 P", "neutral", "strong", 0),
|
||||
lv(r1, "压力位 R1", "resistance", "medium", 1),
|
||||
lv(r2, "压力位 R2", "resistance", "medium", 2),
|
||||
lv(r3, "压力位 R3", "resistance", "weak", 3),
|
||||
lv(s1, "支撑位 S1", "support", "medium", 1),
|
||||
lv(s2, "支撑位 S2", "support", "medium", 2),
|
||||
lv(s3, "支撑位 S3", "support", "weak", 3),
|
||||
]
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 3. 前高 / 前低 —— 60 / 120 / 250 日极值
|
||||
# ================================================================
|
||||
|
||||
def _extreme_levels(df: pl.DataFrame) -> list[dict]:
|
||||
"""关键前高 / 前低 —— 历史极值 + 近期 swing 高低点(收敛后)。
|
||||
|
||||
设计:把所有"前高前低"类点位集中在本组,与 sr(通道)区分:
|
||||
- 60 日极值:近一季度高低点(短期参照)
|
||||
- 250 日极值:年度高低点(牛熊分界参照);跳过 120 日(被 250 日包含,信息冗余)
|
||||
- swing 高低点:近期局部转折点,每侧只取距当前价最近的 2 个
|
||||
"""
|
||||
if df.is_empty():
|
||||
return []
|
||||
close = float(df.tail(1)["close"][0]) if "close" in df.columns else None
|
||||
out: list[dict] = []
|
||||
|
||||
# —— 历史极值(只取 60 / 250,避免中间档冗余)——
|
||||
for n in (60, 250):
|
||||
if df.height < n:
|
||||
continue
|
||||
sub = df.tail(n)
|
||||
hi = float(sub["high"].max())
|
||||
lo = float(sub["low"].min())
|
||||
if _ok(hi):
|
||||
out.append({"value": round(hi, 2), "label": f"{n}日新高",
|
||||
"type": "extreme", "side": "resistance", "strength": "strong"})
|
||||
if _ok(lo):
|
||||
out.append({"value": round(lo, 2), "label": f"{n}日新低",
|
||||
"type": "extreme", "side": "support", "strength": "strong"})
|
||||
|
||||
# —— 近期 swing 高低点(每侧只取距当前价最近的 2 个,避免点位爆炸)——
|
||||
win = 5
|
||||
if df.height > win * 2 and close:
|
||||
highs = df["high"].to_list()
|
||||
lows = df["low"].to_list()
|
||||
swing_highs: list[float] = []
|
||||
swing_lows: list[float] = []
|
||||
for i in range(win, len(highs) - win):
|
||||
if highs[i] == max(highs[i - win:i + win + 1]):
|
||||
swing_highs.append(float(highs[i]))
|
||||
if lows[i] == min(lows[i - win:i + win + 1]):
|
||||
swing_lows.append(float(lows[i]))
|
||||
|
||||
# 聚合 ±1% 相近价位,再按距当前价排序取最近 2 个
|
||||
agg_h = _aggregate_levels(swing_highs, 0.01)
|
||||
agg_h = [v for v in agg_h if v > close * 1.001]
|
||||
agg_h.sort(key=lambda v: abs(v - close))
|
||||
for v in agg_h[:2]:
|
||||
out.append({"value": round(v, 2), "label": "前高",
|
||||
"type": "extreme", "side": "resistance", "strength": "medium"})
|
||||
|
||||
agg_l = _aggregate_levels(swing_lows, 0.01)
|
||||
agg_l = [v for v in agg_l if v < close * 0.999]
|
||||
agg_l.sort(key=lambda v: abs(v - close))
|
||||
for v in agg_l[:2]:
|
||||
out.append({"value": round(v, 2), "label": "前低",
|
||||
"type": "extreme", "side": "support", "strength": "medium"})
|
||||
|
||||
return out
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 4. 波动通道 —— 布林带 + Keltner 三档,各自独立开关
|
||||
# ================================================================
|
||||
|
||||
def _ma_value(df: pl.DataFrame, ma_col: str | None, window: int) -> float | None:
|
||||
"""取某档均线值:优先用预计算列,缺失则现场 rolling_mean。"""
|
||||
last = df.tail(1)
|
||||
if ma_col and ma_col in df.columns:
|
||||
v = last[ma_col][0]
|
||||
return float(v) if _ok(v) else None
|
||||
if df.height >= window:
|
||||
v = df.select(pl.col("close").rolling_mean(window)).tail(1)["close"][0]
|
||||
return float(v) if _ok(v) else None
|
||||
return None
|
||||
|
||||
|
||||
def _keltner_band(
|
||||
df: pl.DataFrame, ma_col: str | None, window: int, n: float,
|
||||
label_short: str, type_key: str,
|
||||
) -> list[dict]:
|
||||
"""单档 Keltner 通道:均线 ± n×ATR。
|
||||
|
||||
ATR 自适应波动,通道宽度随行情自动收缩/扩张。type_key 决定归入哪一组
|
||||
(keltner_s / keltner_m / keltner_l),前端各自独立开关。
|
||||
"""
|
||||
if df.is_empty() or df.height < 20 or "atr_14" not in df.columns:
|
||||
return []
|
||||
last = df.tail(1)
|
||||
close = float(last["close"][0]) if "close" in df.columns else 0
|
||||
atr = float(last["atr_14"][0])
|
||||
if not close or not _ok(atr):
|
||||
return []
|
||||
|
||||
ma_val = _ma_value(df, ma_col, window)
|
||||
if ma_val is None:
|
||||
return []
|
||||
upper = ma_val + n * atr
|
||||
lower = ma_val - n * atr
|
||||
return [
|
||||
{"value": round(upper, 2), "label": f"{label_short}通道上轨",
|
||||
"type": type_key, "side": _side(upper, close), "strength": "medium"},
|
||||
{"value": round(lower, 2), "label": f"{label_short}通道下轨",
|
||||
"type": type_key, "side": _side(lower, close), "strength": "medium"},
|
||||
]
|
||||
|
||||
|
||||
def _boll_channel(df: pl.DataFrame) -> list[dict]:
|
||||
"""布林带上下轨(MA20 ± 2σ)。
|
||||
|
||||
基于标准差的波动带,反映价格相对均线的统计偏离;非真实支撑压力,
|
||||
仅作波动边界参考。数据直接取预计算列 boll_upper/boll_lower。
|
||||
"""
|
||||
if df.is_empty() or "boll_upper" not in df.columns or "boll_lower" not in df.columns:
|
||||
return []
|
||||
last = df.tail(1)
|
||||
close = float(last["close"][0]) if "close" in df.columns else 0
|
||||
if not close:
|
||||
return []
|
||||
bu = last["boll_upper"][0]
|
||||
bl = last["boll_lower"][0]
|
||||
if not _ok(bu) or not _ok(bl):
|
||||
return []
|
||||
bu, bl = float(bu), float(bl)
|
||||
out = [
|
||||
{"value": round(bu, 2), "label": "布林上轨",
|
||||
"type": "boll", "side": _side(bu, close), "strength": "medium"},
|
||||
{"value": round(bl, 2), "label": "布林下轨",
|
||||
"type": "boll", "side": _side(bl, close), "strength": "medium"},
|
||||
]
|
||||
# 布林中轨 = MA20(多空平衡线,价格在其上下分强弱);数据层已预计算 ma20
|
||||
if "ma20" in df.columns:
|
||||
mid = last["ma20"][0]
|
||||
if _ok(mid):
|
||||
mid = float(mid)
|
||||
out.append({"value": round(mid, 2), "label": "布林中轨",
|
||||
"type": "boll", "side": _side(mid, close), "strength": "medium"})
|
||||
return out
|
||||
|
||||
|
||||
def _keltner_short(df: pl.DataFrame) -> list[dict]:
|
||||
"""Keltner 短期:MA20 ± 2×ATR(近期波动带,约一个月)。"""
|
||||
return _keltner_band(df, "ma20", 20, 2.0, "短期", "keltner_s")
|
||||
|
||||
|
||||
def _keltner_mid(df: pl.DataFrame) -> list[dict]:
|
||||
"""Keltner 中期:MA60 ± 2.5×ATR(季度波动带)。"""
|
||||
return _keltner_band(df, "ma60", 60, 2.5, "中期", "keltner_m")
|
||||
|
||||
|
||||
def _keltner_long(df: pl.DataFrame) -> list[dict]:
|
||||
"""Keltner 长期:MA120 ± 3×ATR(半年波动带,牛熊趋势边界)。"""
|
||||
return _keltner_band(df, None, 120, 3.0, "长期", "keltner_l")
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 5. ATR 止损位 —— close ± n × ATR,动态止盈止损
|
||||
# ================================================================
|
||||
|
||||
def _atr_stops(df: pl.DataFrame) -> list[dict]:
|
||||
"""基于 ATR 的动态止损/止盈位。
|
||||
|
||||
ATR 衡量平均真实波幅,close ± n×ATR 是交易者最常用的止损位算法:
|
||||
- 止损位:close - 2×ATR (跌破即趋势破坏)
|
||||
- 止盈位:close + 2×ATR (突破即顺势扩展)
|
||||
- 近端波动带:close ± 1.5×ATR (中短期风控参考)
|
||||
"""
|
||||
if df.is_empty() or "atr_14" not in df.columns:
|
||||
return []
|
||||
last = df.tail(1)
|
||||
close = float(last["close"][0])
|
||||
atr = float(last["atr_14"][0])
|
||||
if not _ok(close) or not _ok(atr):
|
||||
return []
|
||||
|
||||
def lv(v: float, label: str, side: str, strength: str) -> dict:
|
||||
return {"value": round(v, 2), "label": label, "type": "atr_stop",
|
||||
"side": side, "strength": strength}
|
||||
|
||||
return [
|
||||
lv(close + 2 * atr, "ATR 止盈(+2)", "resistance", "medium"),
|
||||
lv(close + 1.5 * atr, "ATR 上轨(+1.5)", "resistance", "weak"),
|
||||
lv(close - 1.5 * atr, "ATR 下轨(-1.5)", "support", "weak"),
|
||||
lv(close - 2 * atr, "ATR 止损(-2)", "support", "medium"),
|
||||
]
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 6. 缺口位 (Gap) —— 未回补的跳空缺口
|
||||
# ================================================================
|
||||
|
||||
def _gap_levels(df: pl.DataFrame, lookback: int = 120) -> list[dict]:
|
||||
"""近期未回补的向上/向下跳空缺口。
|
||||
|
||||
向上缺口:当日 low > 前日 high(开盘跳空高开,全天未回补)
|
||||
向下缺口:当日 high < 前日 low(开盘跳空低开,全天未回补)
|
||||
|
||||
缺口是天然的支撑/阻力位。只保留"未回补"的(后续价格未回到缺口区间内),
|
||||
并按价格聚合相近缺口(±0.5%),每方向只取距当前价最近的 2~3 个。
|
||||
"""
|
||||
if df.is_empty() or df.height < 5:
|
||||
return []
|
||||
sub = df.tail(lookback) if df.height > lookback else df
|
||||
close = float(df.tail(1)["close"][0])
|
||||
highs = sub["high"].to_list()
|
||||
lows = sub["low"].to_list()
|
||||
|
||||
up_gaps: list[tuple[float, float]] = [] # (缺口低点, 缺口高点)
|
||||
dn_gaps: list[tuple[float, float]] = []
|
||||
for i in range(1, len(highs)):
|
||||
if _ok(highs[i]) and _ok(lows[i]) and _ok(highs[i - 1]) and _ok(lows[i - 1]):
|
||||
if lows[i] > highs[i - 1]: # 向上缺口
|
||||
up_gaps.append((highs[i - 1], lows[i]))
|
||||
elif highs[i] < lows[i - 1]: # 向下缺口
|
||||
dn_gaps.append((highs[i], lows[i - 1]))
|
||||
|
||||
def _filter_unfilled(gaps: list[tuple[float, float]], is_up: bool) -> list[float]:
|
||||
"""过滤掉已被后续价格回补的缺口,取缺口价位中点。"""
|
||||
mids: list[float] = []
|
||||
for g_lo, g_hi in gaps:
|
||||
# 未回补判定:当前价不在缺口区间内
|
||||
if is_up and close >= g_hi: # 向上缺口:价格已超过缺口上沿 = 未回补(站在缺口上方)
|
||||
mids.append((g_lo + g_hi) / 2)
|
||||
elif not is_up and close <= g_lo: # 向下缺口:价格已低于缺口下沿 = 未回补
|
||||
mids.append((g_lo + g_hi) / 2)
|
||||
# 聚合相近缺口 + 按距当前价排序取最近 3 个
|
||||
agg = _aggregate_levels(mids, 0.005)
|
||||
agg.sort(key=lambda v: abs(v - close))
|
||||
return agg[:3]
|
||||
|
||||
out: list[dict] = []
|
||||
for mid in _filter_unfilled(up_gaps, True):
|
||||
out.append({"value": round(mid, 2), "label": "向上缺口",
|
||||
"type": "gap", "side": _side(mid, close), "strength": "medium"})
|
||||
for mid in _filter_unfilled(dn_gaps, False):
|
||||
out.append({"value": round(mid, 2), "label": "向下缺口",
|
||||
"type": "gap", "side": _side(mid, close), "strength": "medium"})
|
||||
return out
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 7. 斐波那契回撤 —— 基于近期波段的回撤位
|
||||
# ================================================================
|
||||
|
||||
def _fibonacci_levels(df: pl.DataFrame, window: int = 120) -> list[dict]:
|
||||
"""基于近期一段明确趋势的斐波那契回撤位。
|
||||
|
||||
取近 window 个交易日的最高/最低点:
|
||||
- 若高点出现在低点之后(上涨波段):从低到高,回撤 = high - range × ratio
|
||||
- 若低点出现在高点之后(下跌波段):从高到低,回撤 = low + range × ratio
|
||||
比率:0.236 / 0.382 / 0.5 / 0.618 / 0.786
|
||||
"""
|
||||
if df.is_empty() or df.height < 10:
|
||||
return []
|
||||
sub = df.tail(window) if df.height > window else df
|
||||
close = float(df.tail(1)["close"][0])
|
||||
|
||||
highs = sub["high"].to_list()
|
||||
lows = sub["low"].to_list()
|
||||
hi_pos = highs.index(max(highs))
|
||||
lo_pos = lows.index(min(lows))
|
||||
hi_val = float(highs[hi_pos])
|
||||
lo_val = float(lows[lo_pos])
|
||||
if not _ok(hi_val) or not _ok(lo_val) or hi_val <= lo_val:
|
||||
return []
|
||||
|
||||
ratios = [0.236, 0.382, 0.5, 0.618, 0.786]
|
||||
rng = hi_val - lo_val
|
||||
|
||||
out: list[dict] = []
|
||||
# 判断波段方向:高点在低点之后 = 上涨波段(从低回撤)
|
||||
up_trend = hi_pos > lo_pos
|
||||
for r in ratios:
|
||||
if up_trend:
|
||||
val = hi_val - rng * r # 从高点向下回撤
|
||||
else:
|
||||
val = lo_val + rng * r # 从低点向上回撤
|
||||
out.append({"value": round(val, 2), "label": f"Fib {int(r * 1000) / 10:.1f}%",
|
||||
"type": "fib", "side": _side(val, close), "strength": "medium"})
|
||||
return out
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 8. 整数关口 —— 心理支撑/阻力位
|
||||
# ================================================================
|
||||
|
||||
def _round_numbers(df: pl.DataFrame, pct: float = 0.10, max_count: int = 8) -> list[dict]:
|
||||
"""当前价附近的心理整数关口。
|
||||
|
||||
整数位(如 10/11/12元,或 60/65/70元)是天然的心理支撑/阻力,
|
||||
低价股尤其明显。按价格量级自适应步长:
|
||||
- 价格 < 10: 步长 0.5 (如 6.5, 7.0, 7.5)
|
||||
- 价格 < 20: 步长 1 (如 11, 12, 13)
|
||||
- 价格 < 100: 步长 5 (如 60, 65, 70)
|
||||
- 价格 < 500: 步长 10 (如 110, 120, 130)
|
||||
- 价格 >= 500: 步长 50 (如 1100, 1150, 1200)
|
||||
过滤掉距当前价 <1% 的(太近,无分析价值),最多 max_count 个。
|
||||
"""
|
||||
if df.is_empty():
|
||||
return []
|
||||
close = float(df.tail(1)["close"][0])
|
||||
if not _ok(close):
|
||||
return []
|
||||
|
||||
if close < 10:
|
||||
step = 0.5
|
||||
elif close < 20:
|
||||
step = 1.0
|
||||
elif close < 100:
|
||||
step = 5.0
|
||||
elif close < 500:
|
||||
step = 10.0
|
||||
else:
|
||||
step = 50.0
|
||||
|
||||
lo = close * (1 - pct)
|
||||
hi = close * (1 + pct)
|
||||
# 找区间 [lo, hi] 内所有 step 的整数倍(严格限定在区间内)
|
||||
start = (int(lo / step) + (1 if lo % step > 0 else 0)) * step
|
||||
candidates: list[float] = []
|
||||
v = start
|
||||
while v <= hi:
|
||||
if v > 0:
|
||||
candidates.append(round(v, 2))
|
||||
v += step
|
||||
|
||||
# 按距当前价从近到远排序,取前 max_count 个
|
||||
candidates.sort(key=lambda x: abs(x - close))
|
||||
out: list[dict] = []
|
||||
for v in candidates[:max_count]:
|
||||
# 过滤距当前价 <1% 的(太近,无分析价值)
|
||||
if abs(v - close) / close < 0.01:
|
||||
continue
|
||||
out.append({"value": round(v, 2), "label": f"整数关口 {v:g}",
|
||||
"type": "round", "side": _side(v, close), "strength": "weak"})
|
||||
return out
|
||||
|
||||
def compute_levels(df: pl.DataFrame) -> dict[str, list[dict]]:
|
||||
"""计算 11 类价位点,返回 {分组key: [点位...]}。
|
||||
|
||||
分组 key 与 LEVEL_TYPES 一致(sr / pivot / extreme / boll /
|
||||
keltner_s / keltner_m / keltner_l / atr_stop / gap / fib / round),
|
||||
前端按 key 渲染开关按钮,逐组显隐。
|
||||
"""
|
||||
if df.is_empty():
|
||||
return {k: [] for k in LEVEL_TYPES}
|
||||
|
||||
try:
|
||||
return {
|
||||
"sr": _support_resistance(df),
|
||||
"pivot": _pivot_points(df),
|
||||
"extreme": _extreme_levels(df),
|
||||
"boll": _boll_channel(df),
|
||||
"keltner_s": _keltner_short(df),
|
||||
"keltner_m": _keltner_mid(df),
|
||||
"keltner_l": _keltner_long(df),
|
||||
"atr_stop": _atr_stops(df),
|
||||
"gap": _gap_levels(df),
|
||||
"fib": _fibonacci_levels(df),
|
||||
"round": _round_numbers(df),
|
||||
}
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("compute_levels failed: %s", e)
|
||||
return {k: [] for k in LEVEL_TYPES}
|
||||
|
||||
|
||||
def summarize_levels(levels: dict[str, list[dict]], close: float | None) -> str:
|
||||
"""生成给 AI 提示词的价位摘要文本(紧凑,供上下文)。"""
|
||||
if not close:
|
||||
return "无价位数据"
|
||||
parts: list[str] = []
|
||||
# 当前价
|
||||
parts.append(f"当前价 {close:.2f}")
|
||||
# 每组取前 2 个最相关的(距当前价近的优先)
|
||||
for key, label in LEVEL_TYPES.items():
|
||||
pts = levels.get(key, [])
|
||||
if not pts:
|
||||
continue
|
||||
# 按距当前价排序,取前 2
|
||||
ranked = sorted(pts, key=lambda p: abs(p["value"] - close))[:2]
|
||||
desc = "、".join(
|
||||
f"{p['label']}={p['value']}" for p in ranked
|
||||
)
|
||||
parts.append(f"{label}: {desc}")
|
||||
return " · ".join(parts)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 内部工具
|
||||
# ================================================================
|
||||
|
||||
def _ok(v: Any) -> bool:
|
||||
"""数值有效(非空/非 NaN/非 Inf/正数)。"""
|
||||
try:
|
||||
f = float(v)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
import math
|
||||
return math.isfinite(f) and f > 0
|
||||
|
||||
|
||||
def _side(level: float, close: float) -> str:
|
||||
"""价位相对当前价的方向。"""
|
||||
if level > close * 1.001:
|
||||
return "resistance"
|
||||
if level < close * 0.999:
|
||||
return "support"
|
||||
return "neutral"
|
||||
|
||||
|
||||
def _aggregate_levels(values: list[float], tol: float) -> list[float]:
|
||||
"""把相近的价位聚合(±tol),返回去重后的代表值(保留最新)。"""
|
||||
if not values:
|
||||
return []
|
||||
values = sorted(values)
|
||||
out: list[float] = [values[0]]
|
||||
for v in values[1:]:
|
||||
if abs(v - out[-1]) / out[-1] <= tol:
|
||||
out[-1] = v # 聚合到最新(更近期)
|
||||
else:
|
||||
out.append(v)
|
||||
return out
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
"""APScheduler 任务。"""
|
||||
@@ -0,0 +1,839 @@
|
||||
"""盘后管道 + 盘前维表同步。
|
||||
|
||||
调度:
|
||||
09:10 盘前 — 同步个股维表 instruments (全量覆盖)
|
||||
15:30 盘后 — 日K同步 + 增量除权因子 + enriched 计算 + 刷新视图
|
||||
|
||||
盘后同步策略:
|
||||
日 K: QuoteService 交易时段已实时落盘 → 有数据时跳过 batch,首次拉 1 年区间
|
||||
除权因子: 从已有数据最新日期的下一天开始增量获取,避免重复拉取和计算
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import polars as pl
|
||||
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
|
||||
from app.indicators.pipeline import run_pipeline
|
||||
from app.config import settings
|
||||
from app.services import index_sync, instrument_sync, kline_sync, preferences as _prefs
|
||||
from app.tickflow.capabilities import Cap, CapabilitySet
|
||||
from app.tickflow.pools import DEMO_SYMBOLS, get_pool
|
||||
from app.tickflow.repository import KlineRepository
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ProgressCb = Callable[..., None]
|
||||
|
||||
|
||||
def _noop(stage: str, pct: int, msg: str, **kwargs) -> None: # noqa: ARG001
|
||||
pass
|
||||
|
||||
|
||||
def _invalidate(table: str | None = None) -> None:
|
||||
"""stage 写完调用,让 /api/data/status 只重算被影响的那张表。"""
|
||||
from app.api.data import invalidate_data_cache
|
||||
invalidate_data_cache(table)
|
||||
|
||||
|
||||
def _resolve_universe(capset: CapabilitySet) -> list[str]:
|
||||
"""解析标的池 — 以 CN_Equity_A (沪深京A股 ~5522只) 为主。
|
||||
|
||||
有 batch 能力 → 直接拉 CN_Equity_A universe
|
||||
其他用户 → 用 instruments parquet + watchlist 兜底
|
||||
"""
|
||||
if capset.has(Cap.KLINE_DAILY_BATCH):
|
||||
try:
|
||||
all_a = get_pool("CN_Equity_A", refresh=True)
|
||||
if all_a:
|
||||
return sorted(all_a)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("CN_Equity_A pool unavailable, fallback: %s", e)
|
||||
|
||||
# Free 用户兜底: instruments parquet + watchlist + demo
|
||||
base: set[str] = set(DEMO_SYMBOLS)
|
||||
base.update(get_pool("watchlist"))
|
||||
d = Path(settings.data_dir)
|
||||
inst_path = d / "instruments" / "instruments.parquet"
|
||||
if inst_path.exists():
|
||||
try:
|
||||
inst = pl.read_parquet(inst_path, columns=["symbol"])
|
||||
base.update(inst["symbol"].to_list())
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("instruments supplement failed: %s", e)
|
||||
return sorted(base)
|
||||
|
||||
|
||||
def run_instruments_sync(repo: KlineRepository) -> dict:
|
||||
"""盘前同步个股维表。"""
|
||||
rows = instrument_sync.sync_instruments(repo.store.data_dir)
|
||||
_refresh_instruments_view(repo)
|
||||
_invalidate("instruments")
|
||||
return {"instruments_rows": rows}
|
||||
|
||||
|
||||
def run_now(
|
||||
repo: KlineRepository,
|
||||
capset: CapabilitySet,
|
||||
on_progress: ProgressCb | None = None,
|
||||
) -> dict:
|
||||
"""立即执行一次盘后管道,支持进度回调。
|
||||
|
||||
跳过的 stage **不 emit**,避免前端把"无 capability"的卡片错误标记为 active/done。
|
||||
result 里带 skipped_stages 列表供前端展示。
|
||||
"""
|
||||
emit = on_progress or _noop
|
||||
skipped: list[str] = []
|
||||
|
||||
# Step 0: 先同步个股维表, 再解析标的池 — 确保标的池基于最新 instruments
|
||||
emit("sync_instruments", 2, "同步个股维表…")
|
||||
inst_rows = instrument_sync.sync_instruments(repo.store.data_dir)
|
||||
if inst_rows > 0:
|
||||
_refresh_instruments_view(repo)
|
||||
emit("sync_instruments", 8, f"个股维表同步完成,{inst_rows} 只标的")
|
||||
_invalidate("instruments")
|
||||
|
||||
emit("resolve_universe", 9, "解析标的池…")
|
||||
universe = _resolve_universe(capset)
|
||||
emit("resolve_universe", 10, f"标的池规模:{len(universe)} 只")
|
||||
|
||||
# Step 1: 日 K 同步
|
||||
# 付费档 + 今天有数据 → 实时行情接口拉一次覆写(1请求全市场)
|
||||
# 有历史数据 → batch K-line API 补齐缺口
|
||||
# 无任何数据 → batch K-line API 拉首次 1 年
|
||||
from datetime import date as _date, timedelta as _td, datetime as _dt
|
||||
latest_daily = repo.latest_daily_date()
|
||||
today = _date.today()
|
||||
today_exists = latest_daily and latest_daily >= today
|
||||
new_daily_days = 0
|
||||
# 日K范围拉取的起点(分支3补缺口/分支4首次); 实时增量/跳过时为 None。
|
||||
# 供 Step 1.5 除权因子回溯范围对齐: 范围拉取→用日K范围, 非范围→最近N天兜底。
|
||||
daily_range_start: _date | None = None
|
||||
|
||||
# A 股日K拉取开关(默认开);关闭时跳过日K同步,保留已有数据
|
||||
pull_a_share = _prefs.get_pipeline_pull_a_share()
|
||||
if not pull_a_share:
|
||||
emit("sync_daily", 45, "已跳过 A 股日K同步(拉取内容未勾选)")
|
||||
logger.info("sync_daily: skipped (pipeline_pull_a_share=False)")
|
||||
elif today_exists and capset.has(Cap.QUOTE_POOL):
|
||||
# 付费档:今天有数据(QuoteService 已落盘)→ 实时行情覆写,确保最新。
|
||||
# free/none 档无 quote.pool 能力,即便今天已有数据(如从 expert 降级),
|
||||
# 也降级到下方 batch 路径刷新,避免调用无权限的实时行情接口。
|
||||
emit("sync_daily", 12, f"获取日K [{today} ~ {today}] 实时行情…")
|
||||
written_daily = kline_sync.sync_daily_by_quotes(repo)
|
||||
new_daily_days = 1
|
||||
emit("sync_daily", 45, f"日K 完成,{written_daily} 只标的")
|
||||
logger.info("sync_daily: [%s ~ %s] live quotes, %d symbols", today, today, written_daily)
|
||||
elif latest_daily:
|
||||
# 有历史 → batch 补齐缺口。
|
||||
# 也覆盖"今天已有数据但无实时行情权限(free/none)"的降级场景:
|
||||
# 此时 start_date = latest_daily = today,batch 刷新当天日K。
|
||||
start_date = latest_daily
|
||||
daily_range_start = start_date
|
||||
emit("sync_daily", 12, f"获取日K [{start_date} ~ {today}]…")
|
||||
logger.info("sync_daily: [%s ~ %s] %s", start_date, today,
|
||||
"refresh today" if today_exists else "gap fill")
|
||||
|
||||
def _daily_chunk_progress(cur: int, tot: int) -> None:
|
||||
emit("sync_daily", 12 + int(33 * cur / tot),
|
||||
f"日K 批次 {cur}/{tot}", stage_pct=int(100 * cur / tot), skip_log=True)
|
||||
written_daily = kline_sync.sync_and_persist_daily_batch(
|
||||
universe, repo, capset,
|
||||
start_date=_dt.combine(start_date, _dt.min.time()),
|
||||
end_date=_dt.combine(today, _dt.min.time()),
|
||||
on_chunk_done=_daily_chunk_progress,
|
||||
)
|
||||
gap_days = (today - start_date).days
|
||||
new_daily_days = gap_days
|
||||
emit("sync_daily", 45, f"日K 完成,覆盖 {gap_days} 天")
|
||||
logger.info("sync_daily: [%s ~ %s] done, %d days", start_date, today, gap_days)
|
||||
else:
|
||||
# 首次:无任何数据 → batch 拉 1 年
|
||||
start_date = today - _td(days=365)
|
||||
daily_range_start = start_date
|
||||
emit("sync_daily", 12, f"获取日K [{start_date} ~ {today}]…")
|
||||
logger.info("sync_daily: [%s ~ %s] initial fetch", start_date, today)
|
||||
|
||||
def _daily_chunk_progress(cur: int, tot: int) -> None:
|
||||
emit("sync_daily", 12 + int(33 * cur / tot),
|
||||
f"日K 批次 {cur}/{tot}", stage_pct=int(100 * cur / tot), skip_log=True)
|
||||
written_daily = kline_sync.sync_and_persist_daily_batch(
|
||||
universe, repo, capset,
|
||||
start_date=_dt.combine(start_date, _dt.min.time()),
|
||||
end_date=_dt.combine(today, _dt.min.time()),
|
||||
on_chunk_done=_daily_chunk_progress,
|
||||
)
|
||||
new_daily_days = 365
|
||||
emit("sync_daily", 45, "日K 完成")
|
||||
logger.info("sync_daily: [%s ~ %s] done", start_date, today)
|
||||
_invalidate("daily")
|
||||
|
||||
# Step 1.5: 同步除权因子 — 范围与日K拉取方式对齐
|
||||
# 日K范围拉取(补缺口/首次) → 除权用日K范围 [daily_range_start, now]
|
||||
# 首次会覆盖整个日K区间内的历史除权事件; 补缺口天然只增量(起点=latest_daily≈昨天)
|
||||
# 日K实时增量/跳过(分支2/分支1) → 除权兜底拉最近 30 天, 补可能遗漏的新除权
|
||||
# (这两类分支不拉历史日K, 除权不能用日K范围, 只能兜底最近几日)
|
||||
written_adj = 0
|
||||
affected_symbols: list[str] = []
|
||||
if capset.has(Cap.ADJ_FACTOR):
|
||||
from datetime import datetime, timedelta
|
||||
adj_end = datetime.now()
|
||||
if daily_range_start is not None:
|
||||
adj_start = datetime.combine(daily_range_start, datetime.min.time())
|
||||
else:
|
||||
# 日K实时增量/跳过时, 除权兜底拉最近 N 天, 覆盖周末/长假/停机期间的新除权事件。
|
||||
# 15 天: 覆盖春节/国庆最长约10天长假 + 故障恢复缓冲; sync_adj_factor 内部 merge+unique 幂等, 多拉无副作用。
|
||||
adj_start = adj_end - timedelta(days=15)
|
||||
adj_start_str = adj_start.strftime("%Y-%m-%d")
|
||||
adj_end_str = adj_end.strftime("%Y-%m-%d")
|
||||
emit("sync_adj", 50, f"获取除权因子 [{adj_start_str} ~ {adj_end_str}]…")
|
||||
logger.info("sync_adj: [%s ~ %s] start", adj_start_str, adj_end_str)
|
||||
|
||||
def _adj_chunk_progress(cur: int, tot: int) -> None:
|
||||
emit("sync_adj", 50 + int(10 * cur / tot),
|
||||
f"除权因子批次 {cur}/{tot}", stage_pct=int(100 * cur / tot), skip_log=True)
|
||||
written_adj, affected_symbols = kline_sync.sync_adj_factor(
|
||||
universe, repo, capset,
|
||||
start_time=adj_start, end_time=adj_end,
|
||||
on_chunk_done=_adj_chunk_progress,
|
||||
)
|
||||
if affected_symbols:
|
||||
_refresh_single_view(repo, "adj_factor")
|
||||
emit("sync_adj", 60, f"除权因子完成,新增 {len(affected_symbols)} 只个股")
|
||||
logger.info("sync_adj: [%s ~ %s] done, %d symbols", adj_start_str, adj_end_str, len(affected_symbols))
|
||||
else:
|
||||
emit("sync_adj", 60, "除权因子完成,无新增")
|
||||
logger.info("sync_adj: [%s ~ %s] no new factors", adj_start_str, adj_end_str)
|
||||
_invalidate("adj_factor")
|
||||
else:
|
||||
skipped.append("sync_adj")
|
||||
logger.info("sync_adj skipped: no ADJ_FACTOR capability")
|
||||
|
||||
# Step 2: 计算 enriched
|
||||
# 判断策略:
|
||||
# - 首次 (enriched 目录不存在) → 全量
|
||||
# - 往前扩展历史 (新日期 < enriched 已有最早日期) → 全量
|
||||
# 前面的除权因子会改变累积因子链,影响后面所有日期的复权价格
|
||||
# - 往后新增日期 (新日期 > enriched 已有最晚日期)
|
||||
# → 增量补新区块(所有标的) + 受除权影响个股全日期重算
|
||||
# - 无新日期 + 有新除权因子 → 增量: 只重算受影响个股的全部日期
|
||||
# - 无新日期 + 无变化 → 跳过
|
||||
enriched_dir = repo.store.data_dir / "kline_daily_enriched"
|
||||
enriched_exists = enriched_dir.exists() and any(enriched_dir.glob("date=*"))
|
||||
daily_dir = repo.store.data_dir / "kline_daily"
|
||||
daily_days = len(list(daily_dir.glob("date=*"))) if daily_dir.exists() else 0
|
||||
prev_enriched_days = len(list(enriched_dir.glob("date=*"))) if enriched_exists else 0
|
||||
|
||||
# 判断新日期方向: 找 daily 和 enriched 的日期集合做比较
|
||||
forward_incremental = False
|
||||
backward_extension = False
|
||||
|
||||
if daily_days > prev_enriched_days and enriched_exists:
|
||||
daily_dates = sorted(d.stem.split("=")[1] for d in daily_dir.glob("date=*"))
|
||||
enriched_dates = sorted(d.stem.split("=")[1] for d in enriched_dir.glob("date=*"))
|
||||
earliest_enriched = enriched_dates[0]
|
||||
latest_enriched = enriched_dates[-1]
|
||||
new_dates = set(daily_dates) - set(enriched_dates)
|
||||
if new_dates:
|
||||
# 有新日期早于 enriched 最早日期 → 往前扩展
|
||||
if any(d < earliest_enriched for d in new_dates):
|
||||
backward_extension = True
|
||||
# 有新日期晚于 enriched 最晚日期 → 往后新增
|
||||
if any(d > latest_enriched for d in new_dates):
|
||||
forward_incremental = True
|
||||
|
||||
def _enriched_batch_progress(cur: int, tot: int) -> None:
|
||||
emit("compute_enriched", 65 + int(23 * cur / tot),
|
||||
f"计算指标 批次 {cur}/{tot}", stage_pct=int(100 * cur / tot), skip_log=True)
|
||||
|
||||
if not enriched_exists or backward_extension:
|
||||
# 首次 或 往前扩展 → 全量
|
||||
emit("compute_enriched", 65, "全量计算 enriched…")
|
||||
logger.info("compute_enriched: full rebuild (first=%s, backward=%s, daily=%d, enriched=%d)",
|
||||
not enriched_exists, backward_extension, daily_days, prev_enriched_days)
|
||||
written_enriched = run_pipeline(on_batch_done=_enriched_batch_progress)
|
||||
new_enriched_days = len(list(enriched_dir.glob("date=*")))
|
||||
emit("compute_enriched", 88, f"enriched 完成,覆盖 {new_enriched_days} 天")
|
||||
logger.info("compute_enriched: full rebuild done, %d days", new_enriched_days)
|
||||
elif forward_incremental:
|
||||
# 往后新增日期: 增量补新区块 + 受影响个股全日期重算
|
||||
symbols_to_recompute = list(set(affected_symbols)) if affected_symbols else []
|
||||
emit("compute_enriched", 65,
|
||||
f"增量计算 enriched (新日期 + {len(symbols_to_recompute)} 只个股重算)…"
|
||||
if symbols_to_recompute else "增量计算 enriched (新日期)…")
|
||||
logger.info("compute_enriched: forward incremental, %d symbols to recompute",
|
||||
len(symbols_to_recompute))
|
||||
written_enriched = run_pipeline(
|
||||
new_dates_only=True,
|
||||
symbols=symbols_to_recompute or None,
|
||||
on_batch_done=_enriched_batch_progress,
|
||||
)
|
||||
new_enriched_days = len(list(enriched_dir.glob("date=*")))
|
||||
emit("compute_enriched", 88, f"enriched 完成,覆盖 {new_enriched_days} 天")
|
||||
logger.info("compute_enriched: forward incremental done, %d days", new_enriched_days)
|
||||
elif affected_symbols:
|
||||
# 无新日期,仅除权因子变更 → 只重算受影响个股的全部日期
|
||||
emit("compute_enriched", 65, f"增量计算 enriched ({len(affected_symbols)} 只个股)…")
|
||||
logger.info("compute_enriched: adj_factor incremental, %d symbols", len(affected_symbols))
|
||||
written_enriched = run_pipeline(symbols=affected_symbols, on_batch_done=_enriched_batch_progress)
|
||||
emit("compute_enriched", 88, f"enriched 完成,{len(affected_symbols)} 只个股")
|
||||
else:
|
||||
written_enriched = 0
|
||||
logger.info("compute_enriched: skip (no new daily, no adj_factor changes)")
|
||||
_refresh_single_view(repo, "kline_enriched")
|
||||
_invalidate("enriched")
|
||||
|
||||
# Step 2.3: 指数 / ETF 同步 — 物理分开存储;ETF 可复权,指数不复权。
|
||||
written_index_daily = 0
|
||||
written_etf_daily = 0
|
||||
index_count = 0
|
||||
etf_count = 0
|
||||
etf_adj_symbols = 0
|
||||
pull_index = _prefs.get_pipeline_pull_index()
|
||||
pull_etf = _prefs.get_pipeline_pull_etf()
|
||||
|
||||
if capset.has(Cap.KLINE_DAILY_BATCH) and (pull_index or pull_etf):
|
||||
_types = []
|
||||
if pull_index:
|
||||
_types.append("指数")
|
||||
if pull_etf:
|
||||
_types.append("ETF")
|
||||
emit("sync_index", 88, f"同步{'+'.join(_types)}日K…")
|
||||
# 子阶段进度分配: 88.0(开始) → 89.0(完成), 指数占前半, ETF 占后半
|
||||
try:
|
||||
if pull_index:
|
||||
emit("sync_index", 88, "同步指数维表…")
|
||||
index_count = index_sync.sync_index_instruments(repo, pull_index=True, pull_etf=False)
|
||||
emit("sync_index", 88, f"指数维表完成,{index_count} 只")
|
||||
index_dir = repo.store.data_dir / "kline_index_enriched"
|
||||
index_dates = sorted(
|
||||
d.name[5:] for d in index_dir.glob("date=*")
|
||||
if d.is_dir() and d.name.startswith("date=")
|
||||
) if index_dir.exists() else []
|
||||
index_start = _date.fromisoformat(index_dates[-1]) if index_dates else today - _td(days=365)
|
||||
|
||||
def _index_chunk(cur: int, tot: int) -> None:
|
||||
emit("sync_index", 88, f"指数日K批次 {cur}/{tot}",
|
||||
stage_pct=int(100 * cur / tot) if tot else 100, skip_log=cur < tot)
|
||||
|
||||
written_index_daily = index_sync.sync_and_persist_index_daily(
|
||||
repo,
|
||||
capset,
|
||||
start_date=_dt.combine(index_start, _dt.min.time()),
|
||||
end_date=_dt.combine(today, _dt.min.time()),
|
||||
on_chunk_done=_index_chunk,
|
||||
)
|
||||
emit("sync_index", 88, f"指数日K完成,{written_index_daily} 行")
|
||||
_invalidate("index_instruments")
|
||||
_invalidate("index_daily")
|
||||
_invalidate("index_enriched")
|
||||
|
||||
if pull_etf:
|
||||
emit("sync_index", 88, "同步 ETF 维表…")
|
||||
etf_count = index_sync.sync_etf_instruments(repo)
|
||||
emit("sync_index", 88, f"ETF 维表完成,{etf_count} 只")
|
||||
etf_symbols: list[str] = []
|
||||
etf_inst = repo.get_etf_instruments()
|
||||
if not etf_inst.is_empty() and "symbol" in etf_inst.columns:
|
||||
etf_symbols = sorted(set(etf_inst["symbol"].to_list()))
|
||||
if etf_symbols and capset.has(Cap.ADJ_FACTOR):
|
||||
try:
|
||||
emit("sync_index", 88, "同步 ETF 除权因子…")
|
||||
from datetime import datetime, timedelta
|
||||
adj_end = datetime.now()
|
||||
adj_path = repo.store.data_dir / "adj_factor_etf" / "all.parquet"
|
||||
fallback_start = adj_end - timedelta(days=30)
|
||||
adj_start = fallback_start
|
||||
if adj_path.exists():
|
||||
max_date = pl.scan_parquet(adj_path).select(pl.col("trade_date").max()).collect().item()
|
||||
if max_date is not None:
|
||||
if isinstance(max_date, str):
|
||||
adj_start = datetime.combine(_date.fromisoformat(max_date), datetime.min.time())
|
||||
elif isinstance(max_date, datetime):
|
||||
adj_start = datetime.combine(max_date.date(), datetime.min.time())
|
||||
else:
|
||||
adj_start = datetime.combine(max_date, datetime.min.time())
|
||||
_, affected_etfs = index_sync.sync_etf_adj_factor(
|
||||
etf_symbols,
|
||||
repo,
|
||||
capset,
|
||||
start_time=adj_start,
|
||||
end_time=adj_end,
|
||||
)
|
||||
etf_adj_symbols = len(affected_etfs)
|
||||
emit("sync_index", 88, f"ETF 除权因子完成,{etf_adj_symbols} 只")
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("ETF adj_factor skipped: %s", e)
|
||||
etf_dir = repo.store.data_dir / "kline_etf_enriched"
|
||||
etf_dates = sorted(
|
||||
d.name[5:] for d in etf_dir.glob("date=*")
|
||||
if d.is_dir() and d.name.startswith("date=")
|
||||
) if etf_dir.exists() else []
|
||||
etf_start = _date.fromisoformat(etf_dates[-1]) if etf_dates else today - _td(days=365)
|
||||
|
||||
def _etf_chunk(cur: int, tot: int) -> None:
|
||||
emit("sync_index", 88, f"ETF 日K批次 {cur}/{tot}",
|
||||
stage_pct=int(100 * cur / tot) if tot else 100, skip_log=cur < tot)
|
||||
|
||||
written_etf_daily = index_sync.sync_and_persist_etf_daily(
|
||||
repo,
|
||||
capset,
|
||||
start_date=_dt.combine(etf_start, _dt.min.time()),
|
||||
end_date=_dt.combine(today, _dt.min.time()),
|
||||
on_chunk_done=_etf_chunk,
|
||||
)
|
||||
emit("sync_index", 88, f"ETF 日K完成,{written_etf_daily} 行")
|
||||
_invalidate("etf_instruments")
|
||||
_invalidate("etf_daily")
|
||||
|
||||
repo.refresh_index_views()
|
||||
emit(
|
||||
"sync_index",
|
||||
89,
|
||||
f"同步完成,指数 {index_count} 只/{written_index_daily} 行, ETF {etf_count} 只/{written_etf_daily} 行"
|
||||
+ (f", ETF复权 {etf_adj_symbols} 只" if etf_adj_symbols else ""),
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("sync_index/etf failed: %s", e)
|
||||
emit("sync_index", 89, f"指数/ETF同步失败:{e}")
|
||||
else:
|
||||
skipped.append("sync_index")
|
||||
|
||||
# Step 2.5: 分钟 K 同步(可选) — 未启用或无 capability 时静默跳过(不 emit)
|
||||
from app.services import preferences
|
||||
minute_on = preferences.get_minute_sync_enabled()
|
||||
minute_days = preferences.get_minute_sync_days()
|
||||
written_minute = 0
|
||||
if minute_on and capset.has(Cap.KLINE_MINUTE_BATCH):
|
||||
minute_start = today - _td(days=minute_days)
|
||||
emit("sync_minute", 90, f"获取分钟K [{minute_start} ~ {today}]…")
|
||||
logger.info("sync_minute: [%s ~ %s] start", minute_start, today)
|
||||
minute_symbols = _resolve_minute_symbols(capset)
|
||||
def _minute_chunk_progress(cur: int, tot: int) -> None:
|
||||
emit("sync_minute", 90 + int(3 * cur / tot),
|
||||
f"分钟K 批次 {cur}/{tot}", stage_pct=int(100 * cur / tot), skip_log=True)
|
||||
written_minute = kline_sync.sync_and_persist_minute(
|
||||
minute_symbols, repo, capset, days=minute_days,
|
||||
on_chunk_done=_minute_chunk_progress,
|
||||
)
|
||||
minute_dir = repo.store.data_dir / "kline_minute"
|
||||
minute_cover_days = len(list(minute_dir.glob("date=*"))) if minute_dir.exists() else 0
|
||||
emit("sync_minute", 93, f"分钟K完成,覆盖 {minute_cover_days} 天")
|
||||
logger.info("sync_minute: [%s ~ %s] done, %d days", minute_start, today, minute_cover_days)
|
||||
_invalidate("minute")
|
||||
else:
|
||||
skipped.append("sync_minute")
|
||||
if minute_on:
|
||||
logger.info("sync_minute skipped: no KLINE_MINUTE_BATCH capability")
|
||||
else:
|
||||
logger.info("sync_minute skipped: user disabled")
|
||||
|
||||
# Step 3: 刷新视图
|
||||
emit("refresh_views", 95, "刷新 DuckDB 视图…")
|
||||
_refresh_views(repo)
|
||||
|
||||
emit("done", 100, "完成")
|
||||
_invalidate(None) # 兜底:全清
|
||||
|
||||
return {
|
||||
"universe_size": len(universe),
|
||||
"daily_days": new_daily_days,
|
||||
"adj_factor_symbols": len(affected_symbols),
|
||||
"enriched_days": written_enriched,
|
||||
"index_count": index_count,
|
||||
"index_daily_rows": written_index_daily,
|
||||
"etf_count": etf_count,
|
||||
"etf_daily_rows": written_etf_daily,
|
||||
"etf_adj_factor_symbols": etf_adj_symbols,
|
||||
"minute_rows": written_minute,
|
||||
"skipped_stages": skipped,
|
||||
}
|
||||
|
||||
|
||||
def _refresh_views(repo: KlineRepository) -> None:
|
||||
"""刷新所有 DuckDB 视图。"""
|
||||
d = repo.store.data_dir.as_posix()
|
||||
views = {
|
||||
"kline_daily": f"{d}/kline_daily/**/*.parquet",
|
||||
"kline_enriched": f"{d}/kline_daily_enriched/**/*.parquet",
|
||||
"kline_index_daily": f"{d}/kline_index_daily/**/*.parquet",
|
||||
"kline_index_enriched": f"{d}/kline_index_enriched/**/*.parquet",
|
||||
"kline_etf_daily": f"{d}/kline_etf_daily/**/*.parquet",
|
||||
"kline_etf_enriched": f"{d}/kline_etf_enriched/**/*.parquet",
|
||||
"kline_etf_minute": f"{d}/kline_etf_minute/**/*.parquet",
|
||||
"kline_minute": f"{d}/kline_minute/**/*.parquet",
|
||||
"adj_factor": f"{d}/adj_factor/**/*.parquet",
|
||||
"adj_factor_etf": f"{d}/adj_factor_etf/**/*.parquet",
|
||||
"instruments": f"{d}/instruments/**/*.parquet",
|
||||
"instruments_index": f"{d}/instruments_index/**/*.parquet",
|
||||
"instruments_etf": f"{d}/instruments_etf/**/*.parquet",
|
||||
}
|
||||
for name, path in views.items():
|
||||
try:
|
||||
repo.db.execute(
|
||||
f"CREATE OR REPLACE VIEW {name} AS "
|
||||
f"SELECT * FROM read_parquet('{path}', union_by_name=true)"
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("refresh view %s failed: %s", name, e)
|
||||
repo.store._register_unified_views()
|
||||
|
||||
|
||||
def _refresh_single_view(repo: KlineRepository, name: str) -> None:
|
||||
"""刷新单个 DuckDB 视图。"""
|
||||
d = repo.store.data_dir.as_posix()
|
||||
paths = {
|
||||
"kline_daily": f"{d}/kline_daily/**/*.parquet",
|
||||
"kline_enriched": f"{d}/kline_daily_enriched/**/*.parquet",
|
||||
"kline_index_daily": f"{d}/kline_index_daily/**/*.parquet",
|
||||
"kline_index_enriched": f"{d}/kline_index_enriched/**/*.parquet",
|
||||
"kline_etf_daily": f"{d}/kline_etf_daily/**/*.parquet",
|
||||
"kline_etf_enriched": f"{d}/kline_etf_enriched/**/*.parquet",
|
||||
"kline_etf_minute": f"{d}/kline_etf_minute/**/*.parquet",
|
||||
"kline_minute": f"{d}/kline_minute/**/*.parquet",
|
||||
"adj_factor": f"{d}/adj_factor/**/*.parquet",
|
||||
"adj_factor_etf": f"{d}/adj_factor_etf/**/*.parquet",
|
||||
"instruments": f"{d}/instruments/**/*.parquet",
|
||||
"instruments_index": f"{d}/instruments_index/**/*.parquet",
|
||||
"instruments_etf": f"{d}/instruments_etf/**/*.parquet",
|
||||
}
|
||||
path = paths.get(name)
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
repo.db.execute(
|
||||
f"CREATE OR REPLACE VIEW {name} AS "
|
||||
f"SELECT * FROM read_parquet('{path}', union_by_name=true)"
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("refresh view %s failed: %s", name, e)
|
||||
|
||||
|
||||
def _resolve_minute_symbols(capset: CapabilitySet) -> list[str]:
|
||||
"""分钟 K 同步标的 — 与日K共用同一标的池。"""
|
||||
return _resolve_universe(capset)
|
||||
|
||||
|
||||
def _refresh_instruments_view(repo: KlineRepository) -> None:
|
||||
"""单独刷新 instruments 视图。"""
|
||||
d = repo.store.data_dir.as_posix()
|
||||
try:
|
||||
repo.db.execute(
|
||||
f"CREATE OR REPLACE VIEW instruments AS "
|
||||
f"SELECT * FROM read_parquet('{d}/instruments/**/*.parquet', union_by_name=true)"
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("refresh instruments view failed: %s", e)
|
||||
|
||||
|
||||
def _run_tracked(fn, job_label: str) -> None:
|
||||
"""调度触发时包装 JobStore 跟踪,确保同步历史有记录。"""
|
||||
from app.services.pipeline_jobs import job_store
|
||||
|
||||
job_id = job_store.create()
|
||||
job_store.start(job_id)
|
||||
|
||||
def progress(stage: str, pct: int, msg: str, stage_pct: int | None = None,
|
||||
skip_log: bool = False) -> None:
|
||||
job_store.progress(job_id, stage, pct, msg, stage_pct=stage_pct, skip_log=skip_log)
|
||||
|
||||
try:
|
||||
result = fn(on_progress=progress)
|
||||
job_store.succeed(job_id, result)
|
||||
logger.info("scheduled %s completed: job_id=%s", job_label, job_id)
|
||||
except Exception:
|
||||
logger.exception("scheduled %s failed: job_id=%s", job_label, job_id)
|
||||
job_store.fail(job_id, f"scheduled {job_label} failed")
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 定时复盘 (AI 大盘复盘报告)
|
||||
# ================================================================
|
||||
|
||||
REVIEW_JOB_ID = "scheduled_review"
|
||||
|
||||
|
||||
async def _run_scheduled_review(repo) -> None:
|
||||
"""定时复盘 job: 流式生成复盘 → 实时推 SSE(开着页面可见) → 落盘归档 → 推飞书。
|
||||
|
||||
与手动「生成复盘」体验一致: 流式事件经 quote_service.push_review_event →
|
||||
/api/intraday/stream 的 review_progress 事件 → 前端 reviewStore, 用户开着复盘页
|
||||
即可看到报告边生成边显示, 切走再回来也能看到生成中/已生成。
|
||||
LLM 偶发断流(peer closed connection)时自动重试最多 2 次。
|
||||
任何异常都吞掉只记日志, 绝不影响调度器主循环。
|
||||
"""
|
||||
import json
|
||||
|
||||
try:
|
||||
from app.services import market_recap_reports
|
||||
from app import secrets_store as ss
|
||||
|
||||
# AI Key 未配置时跳过(避免每日报错刷日志)
|
||||
if not ss.get_ai_key():
|
||||
logger.info("scheduled review skipped: AI key not configured")
|
||||
return
|
||||
|
||||
app_state = _get_app_state()
|
||||
quote_service = getattr(app_state, "quote_service", None) if app_state else None
|
||||
depth_service = getattr(app_state, "depth_service", None) if app_state else None
|
||||
|
||||
content, meta = await _stream_review_with_retry(repo, quote_service, depth_service)
|
||||
if not content:
|
||||
logger.warning("scheduled review produced no content (meta=%s)", meta)
|
||||
# 通知前端进入 error 态(若有页面在听)
|
||||
if quote_service:
|
||||
quote_service.push_review_event(json.dumps(
|
||||
{"type": "error", "message": "复盘生成失败,请稍后手动重试"},
|
||||
ensure_ascii=False))
|
||||
return
|
||||
|
||||
# 落盘: 与手动生成完全相同的归档格式
|
||||
market_recap_reports.save_report({
|
||||
"as_of": meta.get("as_of"),
|
||||
"focus": "",
|
||||
"content": content,
|
||||
"summary": meta.get("summary", ""),
|
||||
"emotion_score": meta.get("emotion_score"),
|
||||
"emotion_label": meta.get("emotion_label", ""),
|
||||
})
|
||||
logger.info("scheduled review saved: as_of=%s", meta.get("as_of"))
|
||||
|
||||
# 通知前端: 生成完成且已归档(archived=true 让前端只刷新列表, 不重复归档)
|
||||
if quote_service:
|
||||
quote_service.push_review_event(json.dumps(
|
||||
{"type": "done", "archived": True}, ensure_ascii=False))
|
||||
|
||||
# 推送到飞书(可选): 运行时读取配置, 用户改设置下次触发即生效。
|
||||
# 失败静默降级, 不影响已归档的报告。
|
||||
_maybe_push_review(content, meta)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception("scheduled review failed: %s", e)
|
||||
# 兜底: 异常时通知前端停止「生成中」状态, 避免页面卡在 streaming
|
||||
try:
|
||||
app_state = _get_app_state()
|
||||
qs = getattr(app_state, "quote_service", None) if app_state else None
|
||||
if qs:
|
||||
import json as _json
|
||||
qs.push_review_event(_json.dumps(
|
||||
{"type": "error", "message": "复盘生成异常,请稍后手动重试"},
|
||||
ensure_ascii=False))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
async def _stream_review_with_retry(repo, quote_service, depth_service) -> tuple[str, dict]:
|
||||
"""流式生成复盘, 每个事件推 SSE + 累积内容。LLM 断流时最多重试 2 次。
|
||||
|
||||
返回 (content, meta)。重试时推一个 retry 事件让前端清空已累积内容重新开始。
|
||||
成功(收到 done/无 error)或耗尽重试后返回。
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
from app.services.market_recap import recap_market_stream
|
||||
|
||||
max_attempts = 3 # 初次 + 2 次重试
|
||||
last_meta: dict = {}
|
||||
content_parts: list[str] = []
|
||||
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
content_parts = [] # 每次重试重新累积
|
||||
failed = False
|
||||
try:
|
||||
async for evt_json in recap_market_stream(repo, quote_service, depth_service):
|
||||
evt = json.loads(evt_json)
|
||||
t = evt.get("type")
|
||||
|
||||
# 推给前端(让开着页面的用户实时看到, 与手动一致)
|
||||
if quote_service:
|
||||
quote_service.push_review_event(evt_json)
|
||||
|
||||
if t == "meta":
|
||||
last_meta = evt
|
||||
elif t == "delta" and evt.get("content"):
|
||||
content_parts.append(evt["content"])
|
||||
elif t == "error":
|
||||
failed = True
|
||||
logger.warning("scheduled review stream error (attempt %d/%d): %s",
|
||||
attempt, max_attempts, evt.get("message"))
|
||||
break # 触发重试
|
||||
elif t == "done":
|
||||
# 正常完成
|
||||
return "".join(content_parts), last_meta
|
||||
# 流自然结束(无 done 事件)且有内容, 视为成功
|
||||
if content_parts and not failed:
|
||||
return "".join(content_parts), last_meta
|
||||
except Exception as e: # noqa: BLE001
|
||||
# LLM 断流等异常(httpx.RemoteProtocolError)落到这里
|
||||
failed = True
|
||||
logger.warning("scheduled review stream exception (attempt %d/%d): %s",
|
||||
attempt, max_attempts, e)
|
||||
|
||||
# 失败: 决定是否重试
|
||||
if attempt < max_attempts:
|
||||
logger.info("scheduled review retrying in 3s (attempt %d → %d)", attempt, attempt + 1)
|
||||
# 通知前端: 即将重试, 清空已累积内容重新开始
|
||||
if quote_service:
|
||||
quote_service.push_review_event(json.dumps(
|
||||
{"type": "retry", "attempt": attempt + 1}, ensure_ascii=False))
|
||||
await asyncio.sleep(3)
|
||||
|
||||
# 耗尽重试, 返回已累积内容(可能为空)和最后 meta
|
||||
return "".join(content_parts), last_meta
|
||||
|
||||
|
||||
def _maybe_push_review(content: str, meta: dict) -> None:
|
||||
"""复盘报告归档后, 按 review_push_channels 选定的外部工具逐个推送完整报告。
|
||||
|
||||
定时生成与手动生成共用本函数 (手动归档端点 POST /api/market-recap/reports 也会调用)。
|
||||
channels 为空则不推送; 'feishu' 复用监控中心的全局飞书 Webhook 通道。
|
||||
推送失败静默降级 (Webhook 是辅助通道), 不影响已归档的报告。
|
||||
"""
|
||||
try:
|
||||
from app.services import preferences, webhook_adapter
|
||||
|
||||
channels = preferences.get_review_push_channels()
|
||||
if not channels:
|
||||
return
|
||||
|
||||
emotion = f"{meta.get('emotion_label') or ''}".strip()
|
||||
as_of = meta.get("as_of") or ""
|
||||
subtitle = as_of + (f" · 情绪 {emotion}" if emotion else "")
|
||||
|
||||
for ch in channels:
|
||||
if ch == "feishu":
|
||||
url = preferences.get_feishu_webhook_url()
|
||||
if not url:
|
||||
logger.info("review push(feishu) skipped: webhook not configured")
|
||||
continue
|
||||
secret = preferences.get_feishu_webhook_secret()
|
||||
ok = webhook_adapter.send_feishu_card(
|
||||
url, "TickFlow · 每日复盘", subtitle, content, secret
|
||||
)
|
||||
logger.info("review push(feishu) %s", "sent" if ok else "failed")
|
||||
# 未来更多渠道在此追加分支
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("review push error: %s", e)
|
||||
|
||||
|
||||
def _register_review_job(scheduler, repo, hour: int, minute: int) -> None:
|
||||
"""注册/更新定时复盘 job(工作日 mon-fri, Asia/Shanghai)。
|
||||
|
||||
供 start_scheduler(启动时) 和 settings API(改时间时) 共用。
|
||||
用 replace_existing=True, 重复注册只更新 trigger。
|
||||
|
||||
注意: _run_scheduled_review 是协程函数, 必须把函数对象本身(配合 args)传给
|
||||
add_job, 而非用 lambda 包裹 —— 否则 APScheduler 会把 lambda 当同步函数在线程池
|
||||
执行, 仅得到一个未 await 的协程对象, 复盘实际不会运行。
|
||||
"""
|
||||
scheduler.add_job(
|
||||
_run_scheduled_review,
|
||||
args=[repo],
|
||||
trigger=CronTrigger(day_of_week="mon-fri",
|
||||
hour=hour, minute=minute,
|
||||
timezone="Asia/Shanghai"),
|
||||
id=REVIEW_JOB_ID,
|
||||
misfire_grace_time=7200, # 复盘非关键, 允许 2 小时内补跑
|
||||
replace_existing=True,
|
||||
)
|
||||
|
||||
|
||||
def start_scheduler(repo: KlineRepository, capset: CapabilitySet) -> AsyncIOScheduler:
|
||||
"""启动调度器。
|
||||
|
||||
工作日 09:10 — 同步个股维表
|
||||
工作日 HH:MM — 盘后管道(时间由用户偏好决定,默认 15:30)
|
||||
"""
|
||||
from app.services import preferences
|
||||
sched = preferences.get_pipeline_schedule()
|
||||
inst_sched = preferences.get_instruments_schedule()
|
||||
|
||||
scheduler = AsyncIOScheduler(timezone="Asia/Shanghai")
|
||||
|
||||
# 盘前: 同步 instruments(时间由偏好决定)
|
||||
def _instruments_task(on_progress=None):
|
||||
emit = on_progress or _noop
|
||||
emit("sync_instruments", 0, "同步个股维表…")
|
||||
result = run_instruments_sync(repo)
|
||||
emit("done", 100, f"个股维表同步完成,{result.get('instruments_rows', 0)} 只标的")
|
||||
return result
|
||||
|
||||
scheduler.add_job(
|
||||
lambda: _run_tracked(_instruments_task, "instruments_sync"),
|
||||
trigger=CronTrigger(day_of_week="mon-fri",
|
||||
hour=inst_sched["hour"], minute=inst_sched["minute"],
|
||||
timezone="Asia/Shanghai"),
|
||||
id="pre_market_instruments",
|
||||
misfire_grace_time=1800,
|
||||
replace_existing=True,
|
||||
)
|
||||
|
||||
# 盘后: 日 K + enriched(时间由偏好决定)
|
||||
def _pipeline_then_refresh(on_progress=None):
|
||||
# 与手动触发 (/api/pipeline/run) 对齐: 管道落盘后重建 Polars 内存缓存,
|
||||
# 否则 live_agg 的昨日连板数等基准列会停留在旧交易日, 次日开盘连板梯队
|
||||
# 整体少算一档 (仅手动触发或重启才会刷缓存, cron 调度路径此前漏了这步)。
|
||||
result = run_now(repo, capset, on_progress=on_progress)
|
||||
repo.refresh_cache()
|
||||
return result
|
||||
|
||||
scheduler.add_job(
|
||||
lambda: _run_tracked(_pipeline_then_refresh, "daily_pipeline"),
|
||||
trigger=CronTrigger(day_of_week="mon-fri",
|
||||
hour=sched["hour"], minute=sched["minute"],
|
||||
timezone="Asia/Shanghai"),
|
||||
id="daily_pipeline",
|
||||
misfire_grace_time=3600,
|
||||
replace_existing=True,
|
||||
)
|
||||
|
||||
# 盘后: 五档盘口 sealed 定版(时间由偏好决定, 默认15:02, 范围15:01~18:00)
|
||||
depth_sched = preferences.get_depth_finalize_time()
|
||||
|
||||
def _depth_finalize():
|
||||
depth_svc = getattr(_get_app_state(), "depth_service", None) if _get_app_state() else None
|
||||
if depth_svc:
|
||||
depth_svc.finalize()
|
||||
|
||||
scheduler.add_job(
|
||||
_depth_finalize,
|
||||
trigger=CronTrigger(day_of_week="mon-fri",
|
||||
hour=depth_sched["hour"], minute=depth_sched["minute"],
|
||||
timezone="Asia/Shanghai"),
|
||||
id="depth_finalize",
|
||||
misfire_grace_time=3600,
|
||||
replace_existing=True,
|
||||
)
|
||||
|
||||
# 定时复盘 (AI 大盘复盘报告): 工作日到点自动生成并归档。
|
||||
# 默认关闭 —— 仅当用户在复盘页开启时才注册 job。
|
||||
# 复用 recap_market_once(非流式) + market_recap_reports.save_report(落盘)。
|
||||
# quote_service / depth_service 通过 _get_app_state() 延迟取用。
|
||||
review_sched = preferences.get_review_schedule()
|
||||
if review_sched["enabled"]:
|
||||
_register_review_job(scheduler, repo, review_sched["hour"], review_sched["minute"])
|
||||
logger.info("scheduled_review enabled @%02d:%02d mon-fri",
|
||||
review_sched["hour"], review_sched["minute"])
|
||||
|
||||
scheduler.start()
|
||||
logger.info("scheduler started; instruments@%02d:%02d, pipeline@%02d:%02d, depth@%02d:%02d mon-fri",
|
||||
inst_sched["hour"], inst_sched["minute"], sched["hour"], sched["minute"],
|
||||
depth_sched["hour"], depth_sched["minute"])
|
||||
return scheduler
|
||||
|
||||
|
||||
# app_state 延迟引用(start_scheduler 在 lifespan 早期调用, app.state 可能还没就绪)
|
||||
_app_state_ref = None
|
||||
|
||||
|
||||
def set_app_state(app_state) -> None:
|
||||
"""lifespan 注册 app.state 引用, 供 scheduled job 访问 depth_service 等单例。"""
|
||||
global _app_state_ref
|
||||
_app_state_ref = app_state
|
||||
|
||||
|
||||
def _get_app_state():
|
||||
return _app_state_ref
|
||||
@@ -0,0 +1,306 @@
|
||||
"""FastAPI 入口。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from app import __version__
|
||||
from app.api import analysis, auth as auth_api, backtest, data, ext_data, financials, indices, intraday, kline, market_recap, monitor_rules, alerts, overview, pipeline, rps, screener, settings as settings_api, signals, stock_analysis, strategy, watchlist
|
||||
from app.api.routes import router as core_router
|
||||
from app.config import settings
|
||||
from app.jobs import daily_pipeline
|
||||
from app.services.quote_service import QuoteService
|
||||
from app.tickflow import client as tf_client
|
||||
from app.tickflow.policy import detect_capabilities
|
||||
from app.tickflow.repository import DataStore, KlineRepository
|
||||
|
||||
logging.basicConfig(
|
||||
level=settings.log_level,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
logger.info(
|
||||
"TickFlow Stock Panel v%s starting (mode=%s)",
|
||||
__version__, tf_client.current_mode(),
|
||||
)
|
||||
|
||||
# 首次启动: 若配置了 AUTH_PASSWORD 环境变量且未设过密码, 用它初始化。
|
||||
# 公网部署免 SSH 端口转发; 已设过密码则不覆盖 (改密码走 UI)。
|
||||
try:
|
||||
from app.services import auth as auth_service
|
||||
auth_service.bootstrap_from_env()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("auth bootstrap failed: %s", e)
|
||||
|
||||
# 数据层
|
||||
store = DataStore()
|
||||
repo = KlineRepository(store)
|
||||
app.state.datastore = store
|
||||
app.state.repo = repo
|
||||
|
||||
# Polars 缓存预热
|
||||
repo.refresh_cache()
|
||||
|
||||
# 能力探测
|
||||
capset = detect_capabilities()
|
||||
app.state.capabilities = capset
|
||||
logger.info("ready; %d capabilities active", len(capset.all()))
|
||||
|
||||
# 全局行情服务
|
||||
qs = QuoteService()
|
||||
app.state.quote_service = qs
|
||||
qs.set_repo(repo)
|
||||
qs.boot_check()
|
||||
|
||||
# QuoteService 需要访问 strategy_monitor 等单例
|
||||
# 先创建 strategy_monitor,再注入 app.state
|
||||
from app.strategy.monitor import StrategyMonitorService
|
||||
strategy_monitor = StrategyMonitorService()
|
||||
app.state.strategy_monitor = strategy_monitor
|
||||
qs.set_app_state(app.state)
|
||||
|
||||
# 五档盘口 sealed 服务(真假涨停/跌停, 独立旁路线)
|
||||
from app.services.depth_service import DepthService
|
||||
depth_service = DepthService()
|
||||
depth_service.set_repo(repo)
|
||||
depth_service.set_app_state(app.state)
|
||||
app.state.depth_service = depth_service
|
||||
|
||||
# 启动调度器(若 enriched 数据为空,首次启动可手动 POST /api/pipeline/run)
|
||||
try:
|
||||
daily_pipeline.set_app_state(app.state) # 供 depth_finalize job 访问 depth_service
|
||||
scheduler = daily_pipeline.start_scheduler(repo, capset)
|
||||
app.state.scheduler = scheduler
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("scheduler not started: %s", e)
|
||||
app.state.scheduler = None
|
||||
|
||||
# depth sealed: 启动补跑(当天文件不存在) + 盘中轮询(有能力时)
|
||||
try:
|
||||
depth_service.boot_check()
|
||||
depth_service.start_polling()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("depth_service init failed: %s", e)
|
||||
|
||||
# 扩展数据定时拉取
|
||||
from app.services.ext_pull import pull_scheduler
|
||||
pull_scheduler.start(store.data_dir)
|
||||
pull_scheduler.refresh(store.data_dir)
|
||||
app.state.pull_scheduler = pull_scheduler
|
||||
|
||||
# 内置扩展表 (概念/行业): 只创建 config (含拉取配置), 不自动拉数据
|
||||
# 数据获取由用户在概念/行业页点「获取数据」手动触发 (POST /api/ext-data/presets/{id}/fetch)
|
||||
try:
|
||||
from app.services.ext_presets import ensure_builtin_presets
|
||||
await ensure_builtin_presets(store.data_dir)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("内置扩展表初始化失败 (不影响启动): %s", e)
|
||||
|
||||
# 财务数据 (需 Expert 套餐): 仅初始化调度器供 /api/financials/sync/* 手动同步,
|
||||
# 不启动自动调度——用户在「财务分析」页点「同步」手动拉取。
|
||||
from app.services.financial_sync import financial_scheduler
|
||||
financial_scheduler.start(store.data_dir, capset)
|
||||
app.state.financial_scheduler = financial_scheduler
|
||||
|
||||
# 策略引擎
|
||||
from app.strategy.engine import StrategyEngine
|
||||
from app.strategy.monitor import StrategyMonitorService
|
||||
from app.services.screener import ScreenerService
|
||||
|
||||
_screener_svc = ScreenerService(repo)
|
||||
strategy_dirs = [
|
||||
Path(__file__).resolve().parent / "strategy" / "builtin",
|
||||
store.data_dir / "strategies" / "custom",
|
||||
store.data_dir / "strategies" / "ai",
|
||||
]
|
||||
strategy_engine = StrategyEngine(
|
||||
enriched_loader=_screener_svc._load_enriched_for_date,
|
||||
enriched_history_loader=_screener_svc._load_enriched_history,
|
||||
strategy_dirs=strategy_dirs,
|
||||
)
|
||||
app.state.strategy_engine = strategy_engine
|
||||
logger.info("strategy engine loaded: %d strategies", len(strategy_engine.list_strategies()))
|
||||
|
||||
# 通用监控规则引擎: 启动时 reload 规则到内存态 (修复重启后告警失效)
|
||||
from app.strategy.monitor import MonitorRuleEngine
|
||||
from app.strategy import monitor_rules as mr_store
|
||||
from app.services import preferences
|
||||
monitor_engine = MonitorRuleEngine()
|
||||
monitor_engine.set_strategy_engine(strategy_engine)
|
||||
monitor_engine.set_data_dir(store.data_dir)
|
||||
# 复用 ScreenerService 的历史窗口加载器 (三级缓存, 启动预计算命中 ~0ms),
|
||||
# 让声明 filter_history 的策略 (如反包) 也能在实时监控里跑选股 → 盘中触发通知。
|
||||
monitor_engine.set_history_loader(_screener_svc._load_enriched_history)
|
||||
|
||||
# 自动迁移: 把旧 strategy_monitor_ids 同步为 type=strategy 规则 (统一到监控页)
|
||||
try:
|
||||
if preferences.get_strategy_monitor_enabled():
|
||||
ids = preferences.get_strategy_monitor_ids()
|
||||
if ids:
|
||||
names = {s.id: s.name for s in strategy_engine.list_strategies()}
|
||||
mr_store.migrate_strategy_monitors(store.data_dir, ids, names)
|
||||
logger.info("strategy monitor migrated: %d strategies", len(ids))
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("strategy monitor migration failed: %s", e)
|
||||
|
||||
try:
|
||||
rules = mr_store.load_all(store.data_dir)
|
||||
monitor_engine.set_rules(rules)
|
||||
logger.info("monitor engine loaded: %d rules", monitor_engine.rule_count)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("monitor engine load failed: %s", e)
|
||||
app.state.monitor_engine = monitor_engine
|
||||
|
||||
yield
|
||||
|
||||
if app.state.scheduler:
|
||||
app.state.scheduler.shutdown(wait=False)
|
||||
ps = getattr(app.state, "pull_scheduler", None)
|
||||
if ps:
|
||||
ps.stop()
|
||||
fsc = getattr(app.state, "financial_scheduler", None)
|
||||
if fsc:
|
||||
fsc.stop()
|
||||
qs = getattr(app.state, "quote_service", None)
|
||||
if qs:
|
||||
qs.stop()
|
||||
dsvc = getattr(app.state, "depth_service", None)
|
||||
if dsvc:
|
||||
dsvc.stop_polling()
|
||||
logger.info("shutdown")
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="TickFlow Stock Panel",
|
||||
version=__version__,
|
||||
description="A 股选股 + 回测面板 — TickFlow 适配",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
# CORS: 允许局域网访问 (自托管场景, 放开所有来源)
|
||||
# 注: allow_credentials=True 与 allow_origins=['*'] 不能共存 (浏览器规范),
|
||||
# 本项目认证走 header (API Key), 不依赖 cookie, 故关闭 credentials 换取通配来源。
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=False,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 访问认证中间件
|
||||
# ================================================================
|
||||
# 拦截所有 /api/ 请求, 三种状态:
|
||||
# 1. 未设密码 + 本机/内网 → 放行(让本机用户访问面板 + 调 /api/auth/setup 设密码)
|
||||
# 2. 未设密码 + 公网 → 拒绝(403, 防裸奔也防抢占; 引导本机设密码)
|
||||
# 3. 已设密码 → 检查 session, 无效则 401(前端跳登录)
|
||||
# 白名单: /api/auth/* (设密码/登录本身)、/health 等探活。
|
||||
_AUTH_WHITELIST_PREFIX = ("/api/auth/",)
|
||||
_AUTH_WHITELIST_EXACT = ("/health", "/api/health", "/openapi.json", "/docs", "/redoc")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def auth_middleware(request: Request, call_next):
|
||||
path = request.url.path
|
||||
# 仅 /api/ 走认证; 静态资源(前端页面/assets)放行, 由前端处理跳转
|
||||
if not path.startswith("/api/"):
|
||||
return await call_next(request)
|
||||
# 白名单放行(设密码/登录/探活本身不拦)
|
||||
if path.startswith(_AUTH_WHITELIST_PREFIX) or path in _AUTH_WHITELIST_EXACT:
|
||||
return await call_next(request)
|
||||
|
||||
from app.services import auth as auth_service
|
||||
# 情况 1+2: 未设密码
|
||||
if not auth_service.is_configured():
|
||||
# 本机/内网 → 放行(服务器主人可访问, 并去 /login 设密码)
|
||||
if auth_api._is_local_network(auth_api._client_ip(request)):
|
||||
return await call_next(request)
|
||||
# 公网 → 拒绝。不裸奔, 也不给公网设密码的机会(防抢占)
|
||||
return JSONResponse(
|
||||
status_code=403,
|
||||
content={
|
||||
"detail": "面板尚未初始化访问密码,请通过 SSH/本机浏览器访问以设置密码",
|
||||
"code": "NOT_INITIALIZED",
|
||||
},
|
||||
)
|
||||
|
||||
# 情况 3: 已设密码, 检查会话
|
||||
token = request.cookies.get(auth_api.COOKIE_NAME)
|
||||
if token and auth_service.is_valid_session(token):
|
||||
return await call_next(request)
|
||||
# 未登录: 401(前端跳登录页)
|
||||
return JSONResponse(status_code=401, content={"detail": "未登录或会话已过期"})
|
||||
|
||||
|
||||
# 路由
|
||||
app.include_router(core_router)
|
||||
app.include_router(auth_api.router)
|
||||
app.include_router(kline.router)
|
||||
app.include_router(watchlist.router)
|
||||
app.include_router(screener.router)
|
||||
app.include_router(backtest.router)
|
||||
app.include_router(intraday.router)
|
||||
app.include_router(indices.router)
|
||||
app.include_router(overview.router)
|
||||
app.include_router(analysis.router)
|
||||
app.include_router(pipeline.router)
|
||||
app.include_router(data.router)
|
||||
app.include_router(ext_data.router)
|
||||
app.include_router(financials.router)
|
||||
app.include_router(stock_analysis.router)
|
||||
app.include_router(market_recap.router)
|
||||
app.include_router(settings_api.router)
|
||||
app.include_router(strategy.router)
|
||||
app.include_router(signals.router)
|
||||
app.include_router(monitor_rules.router)
|
||||
app.include_router(alerts.router)
|
||||
app.include_router(rps.router)
|
||||
|
||||
|
||||
# 能力门控异常 → 403(而非默认 500)
|
||||
# 业务代码用 capset.require(Cap.X) 断言能力,缺失时抛 CapabilityDenied;
|
||||
# 若不注册 handler 会冒泡成 500 Internal Server Error,对前端不友好且语义错误。
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from app.tickflow.capabilities import CapabilityDenied
|
||||
|
||||
|
||||
@app.exception_handler(CapabilityDenied)
|
||||
async def capability_denied_handler(request: Request, exc: CapabilityDenied) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=403,
|
||||
content={"detail": str(exc), "suggestion": exc.suggestion},
|
||||
)
|
||||
|
||||
# 生产期静态文件(前端 dist)
|
||||
_static = Path(settings.static_dir)
|
||||
if _static.exists():
|
||||
if (_static / "assets").exists():
|
||||
app.mount("/assets", StaticFiles(directory=_static / "assets"), name="assets")
|
||||
|
||||
@app.get("/{full_path:path}", include_in_schema=False)
|
||||
def spa_fallback(full_path: str): # noqa: ARG001
|
||||
"""所有未匹配路径回退到 index.html — React Router 接管。
|
||||
|
||||
index.html 禁止缓存 (Cache-Control: no-store), 确保浏览器每次拿到
|
||||
最新版本引用的 JS/CSS 文件名 (assets 带 hash, 可长缓存)。
|
||||
"""
|
||||
index = _static / "index.html"
|
||||
if index.exists():
|
||||
return FileResponse(
|
||||
index,
|
||||
headers={"Cache-Control": "no-store, must-revalidate"},
|
||||
)
|
||||
return {"error": "frontend not built"}
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Key / 凭据本地存储(§14)。
|
||||
|
||||
存储位置:`data/user_data/secrets.json`,权限 0600。
|
||||
优先级:secrets.json > .env > 空(Free 模式)。
|
||||
|
||||
UI 改 Key 时只动这个文件,不动 .env。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _path() -> Path:
|
||||
from app.config import settings
|
||||
p = settings.data_dir / "user_data" / "secrets.json"
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
|
||||
|
||||
def load() -> dict:
|
||||
p = _path()
|
||||
if p.exists():
|
||||
try:
|
||||
return json.loads(p.read_text(encoding="utf-8"))
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("secrets.json malformed: %s", e)
|
||||
return {}
|
||||
|
||||
|
||||
def save(updates: dict) -> dict:
|
||||
"""合并写入(不会清掉未提及的字段)。返回新内容。"""
|
||||
current = load()
|
||||
current.update({k: v for k, v in updates.items() if v is not None})
|
||||
p = _path()
|
||||
p.write_text(json.dumps(current, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
try:
|
||||
os.chmod(p, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
return current
|
||||
|
||||
|
||||
def clear(*keys: str) -> dict:
|
||||
"""清掉指定字段(留空清全部)。"""
|
||||
p = _path()
|
||||
if not p.exists():
|
||||
return {}
|
||||
if not keys:
|
||||
p.unlink()
|
||||
return {}
|
||||
current = load()
|
||||
for k in keys:
|
||||
current.pop(k, None)
|
||||
p.write_text(json.dumps(current, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
return current
|
||||
|
||||
|
||||
def get_tickflow_key() -> str:
|
||||
"""取当前 TickFlow Key:secrets.json 优先,否则 .env。"""
|
||||
val = load().get("tickflow_api_key")
|
||||
if val:
|
||||
return val
|
||||
from app.config import settings
|
||||
return settings.tickflow_api_key or ""
|
||||
|
||||
|
||||
def get_ai_key() -> str:
|
||||
"""取当前 AI Key:secrets.json 优先,否则 .env。"""
|
||||
val = load().get("ai_api_key")
|
||||
if val:
|
||||
return val
|
||||
from app.config import settings
|
||||
return settings.ai_api_key or ""
|
||||
|
||||
|
||||
def get_ai_config(key: str, default: str = "") -> str:
|
||||
"""取 AI 配置项:secrets.json 优先,否则 config。"""
|
||||
val = load().get(key)
|
||||
if val:
|
||||
return val
|
||||
from app.config import settings
|
||||
return getattr(settings, key, default) or default
|
||||
|
||||
|
||||
def mask(key: str, prefix: int = 4, suffix: int = 4) -> str:
|
||||
"""脱敏显示。"""
|
||||
if not key:
|
||||
return ""
|
||||
if len(key) <= prefix + suffix:
|
||||
return "•" * len(key)
|
||||
return f"{key[:prefix]}{'•' * 6}{key[-suffix:]}"
|
||||
@@ -0,0 +1 @@
|
||||
"""业务服务层。"""
|
||||
@@ -0,0 +1,429 @@
|
||||
"""AI provider adapter for OpenAI-compatible APIs and local Codex CLI."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import tomllib
|
||||
from collections.abc import AsyncIterator, Sequence
|
||||
from pathlib import Path
|
||||
|
||||
from app import secrets_store
|
||||
from app.config import settings
|
||||
|
||||
OPENAI_COMPAT_PROVIDER = "openai_compat"
|
||||
CODEX_CLI_PROVIDER = "codex_cli"
|
||||
CODEX_DEFAULT_COMMAND = "codex"
|
||||
CODEX_SERVICE_TIER_FALLBACK = "fast"
|
||||
CODEX_SUPPORTED_SERVICE_TIERS = {"fast", "flex"}
|
||||
|
||||
Message = dict[str, str]
|
||||
|
||||
_ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")
|
||||
|
||||
|
||||
def current_ai_provider() -> str:
|
||||
return secrets_store.get_ai_config("ai_provider", settings.ai_provider) or OPENAI_COMPAT_PROVIDER
|
||||
|
||||
|
||||
def current_ai_model() -> str:
|
||||
if current_ai_provider() == CODEX_CLI_PROVIDER:
|
||||
return normalize_codex_model(str(secrets_store.load().get("ai_model") or ""))
|
||||
return secrets_store.get_ai_config("ai_model", settings.ai_model)
|
||||
|
||||
|
||||
def current_codex_command() -> str:
|
||||
return normalize_codex_command(
|
||||
secrets_store.get_ai_config("ai_codex_command", settings.ai_codex_command),
|
||||
strict=False,
|
||||
)
|
||||
|
||||
|
||||
def is_codex_cli_provider(provider: str | None = None) -> bool:
|
||||
return (provider or current_ai_provider()) == CODEX_CLI_PROVIDER
|
||||
|
||||
|
||||
def normalize_codex_model(model: str) -> str:
|
||||
value = model.strip()
|
||||
aliases = {
|
||||
"gpt5": "gpt-5",
|
||||
"gpt5.5": "gpt-5.5",
|
||||
}
|
||||
return aliases.get(value.lower(), value)
|
||||
|
||||
|
||||
def normalize_codex_command(command: str | None, *, strict: bool = True) -> str:
|
||||
value = (command or "").strip()
|
||||
if not value or value.lower() == CODEX_DEFAULT_COMMAND:
|
||||
return CODEX_DEFAULT_COMMAND
|
||||
if strict:
|
||||
raise ValueError("Codex CLI 仅支持使用默认 codex 命令自动解析, 不支持自定义可执行路径")
|
||||
return CODEX_DEFAULT_COMMAND
|
||||
|
||||
|
||||
def normalize_openai_base_url(url: str) -> str:
|
||||
"""Return the OpenAI-compatible base URL expected by the OpenAI SDK."""
|
||||
base = (url or "").strip().rstrip("/")
|
||||
if base.endswith("/chat/completions"):
|
||||
base = base[: -len("/chat/completions")].rstrip("/")
|
||||
if not base.endswith("/v1"):
|
||||
base = f"{base}/v1"
|
||||
return base
|
||||
|
||||
|
||||
def codex_cli_available() -> bool:
|
||||
try:
|
||||
_codex_base_command()
|
||||
return True
|
||||
except RuntimeError:
|
||||
return False
|
||||
|
||||
|
||||
def ai_configured(provider: str | None = None) -> bool:
|
||||
provider = provider or current_ai_provider()
|
||||
if is_codex_cli_provider(provider):
|
||||
return codex_cli_available()
|
||||
return bool(secrets_store.get_ai_key())
|
||||
|
||||
|
||||
async def generate_ai_text(
|
||||
messages: Sequence[Message],
|
||||
*,
|
||||
temperature: float = 0.3,
|
||||
max_tokens: int = 3000,
|
||||
timeout: float = 180.0,
|
||||
) -> str:
|
||||
"""Return a complete AI response from the currently configured provider."""
|
||||
if is_codex_cli_provider():
|
||||
return await _run_codex_cli(messages, max_tokens=max_tokens, timeout=max(timeout, 600.0))
|
||||
return await _run_openai_once(
|
||||
messages,
|
||||
temperature=temperature,
|
||||
max_tokens=max_tokens,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
async def stream_ai_text(
|
||||
messages: Sequence[Message],
|
||||
*,
|
||||
temperature: float = 0.5,
|
||||
max_tokens: int = 4000,
|
||||
timeout: float = 180.0,
|
||||
) -> AsyncIterator[str]:
|
||||
"""Yield text deltas from the configured provider.
|
||||
|
||||
Codex CLI only exposes the final assistant message for this use case, so it
|
||||
yields one complete chunk after the command exits.
|
||||
"""
|
||||
if is_codex_cli_provider():
|
||||
yield await _run_codex_cli(messages, max_tokens=max_tokens, timeout=max(timeout, 600.0))
|
||||
return
|
||||
|
||||
async for chunk in _stream_openai(
|
||||
messages,
|
||||
temperature=temperature,
|
||||
max_tokens=max_tokens,
|
||||
timeout=timeout,
|
||||
):
|
||||
yield chunk
|
||||
|
||||
|
||||
async def _run_openai_once(
|
||||
messages: Sequence[Message],
|
||||
*,
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
timeout: float,
|
||||
) -> str:
|
||||
ai_key = secrets_store.get_ai_key()
|
||||
if not ai_key:
|
||||
raise RuntimeError("AI API Key 未配置, 请在设置页配置")
|
||||
|
||||
client = _openai_client(ai_key, timeout)
|
||||
resp = await client.chat.completions.create(
|
||||
model=current_ai_model(),
|
||||
messages=list(messages),
|
||||
temperature=temperature,
|
||||
max_tokens=max_tokens,
|
||||
)
|
||||
if not resp.choices:
|
||||
return ""
|
||||
return (resp.choices[0].message.content or "").strip()
|
||||
|
||||
|
||||
async def _stream_openai(
|
||||
messages: Sequence[Message],
|
||||
*,
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
timeout: float,
|
||||
) -> AsyncIterator[str]:
|
||||
ai_key = secrets_store.get_ai_key()
|
||||
if not ai_key:
|
||||
raise RuntimeError("AI API Key 未配置, 请在设置页配置")
|
||||
|
||||
client = _openai_client(ai_key, timeout)
|
||||
stream = await client.chat.completions.create(
|
||||
model=current_ai_model(),
|
||||
messages=list(messages),
|
||||
temperature=temperature,
|
||||
max_tokens=max_tokens,
|
||||
stream=True,
|
||||
)
|
||||
|
||||
async for chunk in stream:
|
||||
delta = chunk.choices[0].delta if chunk.choices else None
|
||||
if delta and delta.content:
|
||||
yield delta.content
|
||||
|
||||
|
||||
def _openai_client(api_key: str, timeout: float):
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
user_agent = secrets_store.get_ai_config("ai_user_agent", "") or settings.ai_user_agent
|
||||
return AsyncOpenAI(
|
||||
api_key=api_key,
|
||||
base_url=normalize_openai_base_url(secrets_store.get_ai_config("ai_base_url", settings.ai_base_url)),
|
||||
timeout=timeout,
|
||||
max_retries=2,
|
||||
default_headers={"User-Agent": user_agent},
|
||||
)
|
||||
|
||||
|
||||
async def _run_codex_cli(
|
||||
messages: Sequence[Message],
|
||||
*,
|
||||
max_tokens: int,
|
||||
timeout: float,
|
||||
) -> str:
|
||||
prompt = _codex_prompt(messages, max_tokens=max_tokens)
|
||||
with tempfile.TemporaryDirectory(prefix="tickflow-codex-run-") as run_dir:
|
||||
run_path = Path(run_dir)
|
||||
codex_home_path = run_path / "codex-home"
|
||||
workspace_path = run_path / "workspace"
|
||||
codex_home_path.mkdir()
|
||||
workspace_path.mkdir()
|
||||
output_path = codex_home_path / "last-message.txt"
|
||||
_prepare_codex_home(codex_home_path)
|
||||
|
||||
args = [
|
||||
*_codex_base_command(),
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"--sandbox",
|
||||
"read-only",
|
||||
"--skip-git-repo-check",
|
||||
"--color",
|
||||
"never",
|
||||
"--output-last-message",
|
||||
str(output_path),
|
||||
]
|
||||
model = current_ai_model().strip()
|
||||
if model:
|
||||
args.extend(["--model", model])
|
||||
args.extend(["--cd", str(workspace_path), "-"])
|
||||
|
||||
env = os.environ.copy()
|
||||
env.setdefault("NO_COLOR", "1")
|
||||
env["CODEX_HOME"] = str(codex_home_path)
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*args,
|
||||
stdin=asyncio.subprocess.PIPE,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
env=env,
|
||||
)
|
||||
try:
|
||||
stdout, stderr = await asyncio.wait_for(
|
||||
proc.communicate(prompt.encode("utf-8")),
|
||||
timeout=timeout,
|
||||
)
|
||||
except TimeoutError as exc:
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
raise RuntimeError("Codex CLI 调用超时, 请稍后重试或检查本机 Codex 登录状态") from exc
|
||||
|
||||
out = _clean_process_text(stdout)
|
||||
err = _clean_process_text(stderr)
|
||||
final_message = _read_output_file(output_path)
|
||||
if proc.returncode != 0:
|
||||
detail = err or out or f"exit code {proc.returncode}"
|
||||
raise RuntimeError(f"Codex CLI 调用失败: {detail[-1200:]}")
|
||||
result = final_message or out
|
||||
if not result:
|
||||
raise RuntimeError("Codex CLI 未返回内容")
|
||||
return result
|
||||
|
||||
|
||||
def _codex_prompt(messages: Sequence[Message], *, max_tokens: int) -> str:
|
||||
parts = [
|
||||
"You are TickFlow Stock Panel's local AI provider.",
|
||||
"This is a text-generation task. The working directory is intentionally empty.",
|
||||
"Use only the user-provided prompt content below; do not inspect or modify local files.",
|
||||
"Return only the final requested content; do not include execution logs.",
|
||||
]
|
||||
if max_tokens > 0:
|
||||
parts.append(f"Keep the final answer within about {max_tokens} output tokens.")
|
||||
for message in messages:
|
||||
role = message.get("role", "user")
|
||||
content = message.get("content", "")
|
||||
parts.append(f"\n<{role}>\n{content}\n</{role}>")
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def _codex_base_command() -> list[str]:
|
||||
command = current_codex_command()
|
||||
resolved = _resolve_command(command)
|
||||
if not resolved:
|
||||
raise RuntimeError(f"未找到 Codex CLI 命令: {command}")
|
||||
|
||||
if sys.platform == "win32" and resolved.lower().endswith(".ps1"):
|
||||
return ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", resolved]
|
||||
return [resolved]
|
||||
|
||||
|
||||
def _resolve_command(command: str) -> str | None:
|
||||
if command.lower() != CODEX_DEFAULT_COMMAND:
|
||||
return None
|
||||
|
||||
if sys.platform == "win32":
|
||||
desktop_codex = _resolve_windows_desktop_codex()
|
||||
if desktop_codex:
|
||||
return desktop_codex
|
||||
|
||||
resolved = shutil.which(command)
|
||||
if sys.platform == "win32" and resolved:
|
||||
resolved_path = Path(resolved)
|
||||
if not resolved_path.suffix:
|
||||
cmd_path = resolved_path.with_suffix(".cmd")
|
||||
if cmd_path.exists():
|
||||
return str(cmd_path)
|
||||
if not resolved and sys.platform == "win32" and not command.lower().endswith(".cmd"):
|
||||
resolved = shutil.which(f"{command}.cmd")
|
||||
if not resolved and sys.platform == "win32":
|
||||
resolved = _resolve_windows_codex_command(command)
|
||||
return resolved
|
||||
|
||||
|
||||
def _resolve_windows_codex_command(command: str) -> str | None:
|
||||
"""Find npm-installed Codex when the backend process has a minimal PATH."""
|
||||
raw = Path(command)
|
||||
if raw.parent != Path("."):
|
||||
return None
|
||||
|
||||
names = [command]
|
||||
if not raw.suffix:
|
||||
names = [f"{command}.cmd", f"{command}.exe", f"{command}.bat", f"{command}.ps1", command]
|
||||
|
||||
dirs: list[Path] = []
|
||||
appdata = os.environ.get("APPDATA")
|
||||
if appdata:
|
||||
dirs.append(Path(appdata) / "npm")
|
||||
dirs.append(Path.home() / "AppData" / "Roaming" / "npm")
|
||||
|
||||
for env_name in ("ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"):
|
||||
value = os.environ.get(env_name)
|
||||
if value:
|
||||
dirs.append(Path(value) / "nodejs")
|
||||
|
||||
for directory in dirs:
|
||||
for name in names:
|
||||
candidate = directory / name
|
||||
if candidate.exists():
|
||||
return str(candidate)
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_windows_desktop_codex() -> str | None:
|
||||
"""Prefer the Codex Desktop bundled CLI over an older npm shim."""
|
||||
local_appdata = os.environ.get("LOCALAPPDATA")
|
||||
if not local_appdata:
|
||||
return None
|
||||
|
||||
root = Path(local_appdata) / "OpenAI" / "Codex" / "bin"
|
||||
if not root.exists():
|
||||
return None
|
||||
|
||||
candidates = list(root.glob("*/codex.exe"))
|
||||
direct = root / "codex.exe"
|
||||
if direct.exists():
|
||||
candidates.append(direct)
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
newest = max(candidates, key=lambda p: p.stat().st_mtime)
|
||||
return str(newest)
|
||||
|
||||
|
||||
def _prepare_codex_home(target: Path) -> None:
|
||||
"""Create an isolated CODEX_HOME that reuses auth but not fragile config."""
|
||||
source = _codex_home()
|
||||
auth_file = source / "auth.json"
|
||||
if auth_file.exists():
|
||||
shutil.copy2(auth_file, target / "auth.json")
|
||||
_write_compatible_codex_config(target / "config.toml")
|
||||
|
||||
|
||||
def _codex_home() -> Path:
|
||||
return Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
|
||||
|
||||
|
||||
def _write_compatible_codex_config(path: Path) -> None:
|
||||
config = _read_codex_config()
|
||||
lines: list[str] = []
|
||||
|
||||
tier = str(config.get("service_tier") or "").strip()
|
||||
if tier not in CODEX_SUPPORTED_SERVICE_TIERS:
|
||||
tier = CODEX_SERVICE_TIER_FALLBACK
|
||||
lines.append(_toml_string("service_tier", tier))
|
||||
lines.append(_toml_string("approval_policy", "never"))
|
||||
lines.append(_toml_string("sandbox_mode", "read-only"))
|
||||
|
||||
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def _read_codex_config() -> dict:
|
||||
path = _codex_home() / "config.toml"
|
||||
if not path.exists():
|
||||
return {}
|
||||
try:
|
||||
with path.open("rb") as f:
|
||||
return tomllib.load(f)
|
||||
except tomllib.TOMLDecodeError:
|
||||
return _read_codex_config_lenient(path)
|
||||
except OSError:
|
||||
return {}
|
||||
|
||||
|
||||
def _read_codex_config_lenient(path: Path) -> dict:
|
||||
config: dict[str, str] = {}
|
||||
pattern = re.compile(r'^\s*([A-Za-z0-9_-]+)\s*=\s*"([^"]*)"\s*$')
|
||||
try:
|
||||
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
|
||||
match = pattern.match(line)
|
||||
if match:
|
||||
config[match.group(1)] = match.group(2)
|
||||
except OSError:
|
||||
pass
|
||||
return config
|
||||
|
||||
|
||||
def _toml_string(key: str, value: str) -> str:
|
||||
escaped = value.replace("\\", "\\\\").replace('"', '\\"')
|
||||
return f'{key} = "{escaped}"'
|
||||
|
||||
|
||||
def _clean_process_text(raw: bytes) -> str:
|
||||
text = raw.decode("utf-8", errors="replace")
|
||||
return _ANSI_RE.sub("", text).strip()
|
||||
|
||||
|
||||
def _read_output_file(path: Path) -> str:
|
||||
if path.exists():
|
||||
return _ANSI_RE.sub("", path.read_text(encoding="utf-8", errors="replace")).strip()
|
||||
return ""
|
||||
@@ -0,0 +1,101 @@
|
||||
"""AI 财务分析报告持久化存储。
|
||||
|
||||
存储位置: data/user_data/ai_reports.json (数组,按 created_at 降序)
|
||||
保留最近 MAX_REPORTS 条;超出自动裁剪最旧的。
|
||||
|
||||
每条报告结构:
|
||||
{
|
||||
"id": "rpt_xxx", # 唯一 id
|
||||
"symbol": "600519.SH",
|
||||
"name": "贵州茅台",
|
||||
"focus": "", # 用户追加的关心点(可为空)
|
||||
"content": "# ...markdown", # 报告正文
|
||||
"periods": 4, # 基于几期数据生成
|
||||
"summary": "metrics: 1期...", # 数据摘要
|
||||
"created_at": "2026-06-25T10:00:00"
|
||||
}
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_REPORTS = 20
|
||||
|
||||
|
||||
def _path() -> Path:
|
||||
from app.config import settings
|
||||
p = settings.data_dir / "user_data" / "ai_reports.json"
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
|
||||
|
||||
def list_reports() -> list[dict]:
|
||||
"""返回全部报告(按 created_at 降序)。"""
|
||||
p = _path()
|
||||
if not p.exists():
|
||||
return []
|
||||
try:
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
if isinstance(data, list):
|
||||
return sorted(data, key=lambda r: r.get("created_at", ""), reverse=True)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("ai_reports.json malformed: %s", e)
|
||||
return []
|
||||
|
||||
|
||||
def _save_all(reports: list[dict]) -> None:
|
||||
"""全量写入(裁剪到 MAX_REPORTS)。"""
|
||||
# 保持降序
|
||||
reports.sort(key=lambda r: r.get("created_at", ""), reverse=True)
|
||||
if len(reports) > MAX_REPORTS:
|
||||
reports = reports[:MAX_REPORTS]
|
||||
_path().write_text(
|
||||
json.dumps(reports, indent=2, ensure_ascii=False), encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def save_report(report: dict) -> dict:
|
||||
"""新增一条报告并持久化。返回保存后的报告(含 id / created_at)。
|
||||
|
||||
自动补全 id 与 created_at(若缺),并裁剪到上限。
|
||||
"""
|
||||
reports = list_reports()
|
||||
if not report.get("id"):
|
||||
report["id"] = f"rpt_{int(time.time() * 1000)}_{report.get('symbol', 'x')}"
|
||||
if not report.get("created_at"):
|
||||
report["created_at"] = _now_iso()
|
||||
reports.append(report)
|
||||
_save_all(reports)
|
||||
logger.info("AI report saved: %s (%s), total %d", report.get("symbol"), report.get("id"), len(reports))
|
||||
return report
|
||||
|
||||
|
||||
def delete_report(report_id: str) -> bool:
|
||||
"""删除指定报告。返回是否删除成功。"""
|
||||
reports = list_reports()
|
||||
before = len(reports)
|
||||
reports = [r for r in reports if r.get("id") != report_id]
|
||||
if len(reports) < before:
|
||||
_save_all(reports)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def clear_reports() -> int:
|
||||
"""清空全部报告。返回删除数量。"""
|
||||
reports = list_reports()
|
||||
n = len(reports)
|
||||
if n > 0:
|
||||
_save_all([])
|
||||
return n
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
"""当前本地时间 ISO 字符串(带秒精度,前端 toLocaleString 友好)。"""
|
||||
from datetime import datetime
|
||||
return datetime.now().isoformat(timespec="seconds")
|
||||
@@ -0,0 +1,209 @@
|
||||
"""告警触发记录存储 — JSONL 追加写 + 滚动清理。
|
||||
|
||||
职责:
|
||||
- 把每次触发的 AlertEvent 追加写入 data/user_data/alerts.jsonl
|
||||
- 提供查询 (按来源/类型过滤、时间倒序、限量)
|
||||
- 滚动清理: 保留近 N 天 + 上限 M 条 (取交集)
|
||||
|
||||
设计:
|
||||
- JSONL 每行一个 JSON 对象,便于增量追加和流式读取
|
||||
- 清理策略: 追加后按需 prune (按 ts 删旧),避免文件无限膨胀
|
||||
- 读时全量加载到内存过滤 (记录量受上限约束, 5000 条量级无压力)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 保留策略
|
||||
MAX_DAYS = 7
|
||||
MAX_RECORDS = 5000
|
||||
# 每隔多少次写入触发一次清理 (避免每次写都 prune)
|
||||
PRUNE_EVERY = 20
|
||||
|
||||
_lock = threading.Lock()
|
||||
_write_count = 0
|
||||
|
||||
|
||||
def _path(data_dir: Path) -> Path:
|
||||
p = data_dir / "user_data" / "alerts.jsonl"
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
|
||||
|
||||
def append(data_dir: Path, event: dict) -> None:
|
||||
"""追加一条触发记录。event 应含 ts(毫秒)、rule_id、source 等字段。"""
|
||||
line = json.dumps(event, ensure_ascii=False)
|
||||
with _lock:
|
||||
p = _path(data_dir)
|
||||
with p.open("a", encoding="utf-8") as f:
|
||||
f.write(line + "\n")
|
||||
global _write_count
|
||||
_write_count += 1
|
||||
if _write_count >= PRUNE_EVERY:
|
||||
_write_count = 0
|
||||
_prune_locked(p)
|
||||
|
||||
|
||||
def append_many(data_dir: Path, events: list[dict]) -> None:
|
||||
"""批量追加。"""
|
||||
if not events:
|
||||
return
|
||||
with _lock:
|
||||
p = _path(data_dir)
|
||||
with p.open("a", encoding="utf-8") as f:
|
||||
for ev in events:
|
||||
f.write(json.dumps(ev, ensure_ascii=False) + "\n")
|
||||
global _write_count
|
||||
_write_count += len(events)
|
||||
if _write_count >= PRUNE_EVERY:
|
||||
_write_count = 0
|
||||
_prune_locked(p)
|
||||
|
||||
|
||||
def list_recent(
|
||||
data_dir: Path,
|
||||
days: int = MAX_DAYS,
|
||||
limit: int = MAX_RECORDS,
|
||||
source: str | None = None,
|
||||
type: str | None = None,
|
||||
) -> list[dict]:
|
||||
"""读取近 N 天记录,按时间倒序,支持按 source/type 过滤。"""
|
||||
import time
|
||||
cutoff = (time.time() - days * 86400) * 1000 # 毫秒
|
||||
out: list[dict] = []
|
||||
p = _path(data_dir)
|
||||
if not p.exists():
|
||||
return []
|
||||
try:
|
||||
with p.open("r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
ev = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
if ev.get("ts", 0) < cutoff:
|
||||
continue
|
||||
if source and ev.get("source") != source:
|
||||
continue
|
||||
if type and ev.get("type") != type:
|
||||
continue
|
||||
out.append(ev)
|
||||
except Exception as e:
|
||||
logger.warning("alert_store read failed: %s", e)
|
||||
return []
|
||||
# 时间倒序 + 截断
|
||||
out.sort(key=lambda x: x.get("ts", 0), reverse=True)
|
||||
return out[:limit]
|
||||
|
||||
|
||||
def clear(data_dir: Path) -> int:
|
||||
"""清空全部记录,返回清除的条数。"""
|
||||
with _lock:
|
||||
p = _path(data_dir)
|
||||
if not p.exists():
|
||||
return 0
|
||||
count = 0
|
||||
try:
|
||||
with p.open("r", encoding="utf-8") as f:
|
||||
count = sum(1 for line in f if line.strip())
|
||||
except Exception:
|
||||
pass
|
||||
p.write_text("", encoding="utf-8")
|
||||
return count
|
||||
|
||||
|
||||
def delete_one(data_dir: Path, ts: int) -> bool:
|
||||
"""删除指定 ts 的单条记录,返回是否删除成功。
|
||||
|
||||
JSONL 无主键, 用 ts(毫秒时间戳) 作为标识。
|
||||
若存在多条同 ts, 只删第一条。
|
||||
"""
|
||||
with _lock:
|
||||
p = _path(data_dir)
|
||||
if not p.exists():
|
||||
return False
|
||||
kept: list[dict] = []
|
||||
deleted = False
|
||||
try:
|
||||
with p.open("r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
ev = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
if not deleted and ev.get("ts") == ts:
|
||||
deleted = True
|
||||
continue
|
||||
kept.append(ev)
|
||||
except Exception as e:
|
||||
logger.warning("alert_store delete_one read failed: %s", e)
|
||||
return False
|
||||
if not deleted:
|
||||
return False
|
||||
try:
|
||||
with p.open("w", encoding="utf-8") as f:
|
||||
for ev in kept:
|
||||
f.write(json.dumps(ev, ensure_ascii=False) + "\n")
|
||||
except Exception as e:
|
||||
logger.warning("alert_store delete_one write failed: %s", e)
|
||||
return False
|
||||
return True
|
||||
return count
|
||||
|
||||
|
||||
def count(data_dir: Path) -> int:
|
||||
"""返回当前记录总数。"""
|
||||
p = _path(data_dir)
|
||||
if not p.exists():
|
||||
return 0
|
||||
try:
|
||||
with p.open("r", encoding="utf-8") as f:
|
||||
return sum(1 for line in f if line.strip())
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
def _prune_locked(p: Path) -> None:
|
||||
"""(调用方需持锁) 保留近 MAX_DAYS 天 + 上限 MAX_RECORDS 条。"""
|
||||
import time
|
||||
cutoff = (time.time() - MAX_DAYS * 86400) * 1000
|
||||
kept: list[dict] = []
|
||||
try:
|
||||
with p.open("r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
ev = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
if ev.get("ts", 0) >= cutoff:
|
||||
kept.append(ev)
|
||||
except FileNotFoundError:
|
||||
return
|
||||
except Exception as e:
|
||||
logger.warning("alert_store prune read failed: %s", e)
|
||||
return
|
||||
# 上限截断 (保留最新的)
|
||||
if len(kept) > MAX_RECORDS:
|
||||
kept.sort(key=lambda x: x.get("ts", 0))
|
||||
kept = kept[-MAX_RECORDS:]
|
||||
# 重写文件
|
||||
try:
|
||||
with p.open("w", encoding="utf-8") as f:
|
||||
for ev in kept:
|
||||
f.write(json.dumps(ev, ensure_ascii=False) + "\n")
|
||||
except Exception as e:
|
||||
logger.warning("alert_store prune write failed: %s", e)
|
||||
@@ -0,0 +1,201 @@
|
||||
"""访问密码认证 — 单用户, 自托管场景。
|
||||
|
||||
设计:
|
||||
- 密码用 PBKDF2-HMAC-SHA256 哈希(标准库 hashlib, 无新依赖), 加随机 salt。
|
||||
即使 auth.json 泄露, 也无法逆向出明文密码。
|
||||
- 会话用随机 token(token_urlsafe), 内存 + 文件双存(支持多进程/重启不丢失)。
|
||||
- 存储: data/user_data/auth.json (chmod 0600), 仿 secrets_store 模式。
|
||||
|
||||
安全要点:
|
||||
- 设密码接口必须限制本机/内网(见 auth router), 防黑客抢占域名抢先设密码。
|
||||
- 登录限流: 错5次锁5分钟(见 auth router 内存计数)。
|
||||
- 单密码, 不做多用户(避免重构全项目数据层)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import secrets as _secrets
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# PBKDF2 参数(NIST 推荐, 单次校验 ~100ms, 兼顾安全与响应)
|
||||
_PBKDF2_ITER = 200_000
|
||||
_SALT_LEN = 16
|
||||
_TOKEN_BYTES = 32
|
||||
|
||||
# 会话有效期: 30 天(自托管单用户, 长一点减少重登频率)
|
||||
SESSION_TTL = 30 * 24 * 3600
|
||||
|
||||
_lock = threading.Lock()
|
||||
# 内存中的有效会话: { token: expire_ts }。进程重启后从磁盘恢复。
|
||||
_sessions: dict[str, float] = {}
|
||||
|
||||
|
||||
def _path() -> Path:
|
||||
from app.config import settings
|
||||
p = settings.data_dir / "user_data" / "auth.json"
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
|
||||
|
||||
def _load() -> dict:
|
||||
p = _path()
|
||||
if p.exists():
|
||||
try:
|
||||
return json.loads(p.read_text(encoding="utf-8"))
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("auth.json malformed: %s", e)
|
||||
return {}
|
||||
|
||||
|
||||
def _save(data: dict) -> None:
|
||||
p = _path()
|
||||
p.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
try:
|
||||
os.chmod(p, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _hash_password(password: str, salt: bytes | None = None) -> tuple[str, str]:
|
||||
"""返回 (salt_hex, hash_hex)。salt 为 None 时生成新 salt。"""
|
||||
if salt is None:
|
||||
salt = os.urandom(_SALT_LEN)
|
||||
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, _PBKDF2_ITER)
|
||||
return salt.hex(), dk.hex()
|
||||
|
||||
|
||||
def _verify_password(password: str, salt_hex: str, hash_hex: str) -> bool:
|
||||
"""恒定时间比较, 防时序攻击。"""
|
||||
try:
|
||||
salt = bytes.fromhex(salt_hex)
|
||||
expected = bytes.fromhex(hash_hex)
|
||||
except ValueError:
|
||||
return False
|
||||
actual = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, _PBKDF2_ITER)
|
||||
return _secrets.compare_digest(actual, expected)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 密码管理
|
||||
# ================================================================
|
||||
|
||||
def is_configured() -> bool:
|
||||
"""是否已设置访问密码。"""
|
||||
d = _load()
|
||||
return bool(d.get("password_hash"))
|
||||
|
||||
|
||||
def set_password(password: str) -> None:
|
||||
"""设置/修改访问密码。清空所有现有会话(强制重新登录)。"""
|
||||
if len(password) < 6:
|
||||
raise ValueError("密码至少 6 位")
|
||||
salt_hex, hash_hex = _hash_password(password)
|
||||
with _lock:
|
||||
_sessions.clear() # 改密码 = 旧会话全部失效
|
||||
_save({
|
||||
"password_hash": hash_hex,
|
||||
"password_salt": salt_hex,
|
||||
"updated_at": int(time.time()),
|
||||
"sessions": {}, # 清空持久化会话
|
||||
})
|
||||
logger.info("access password set")
|
||||
|
||||
|
||||
def bootstrap_from_env() -> bool:
|
||||
"""首次初始化: 若环境变量 AUTH_PASSWORD 已配置且尚未设过密码, 则用它设密码。
|
||||
|
||||
公网服务器部署场景: 避免每次都要 SSH 端口转发才能设首个密码。
|
||||
明文密码只在内存/配置中, 经 set_password() 哈希后写入 auth.json (chmod 0600)。
|
||||
一旦设置成功, 后续重启不再覆盖 (用户改密码走 UI, 不受环境变量影响)。
|
||||
|
||||
Returns:
|
||||
True 表示本次用环境变量初始化了密码; False 表示无需初始化。
|
||||
"""
|
||||
from app.config import settings
|
||||
|
||||
pwd = (settings.auth_password or "").strip()
|
||||
if not pwd:
|
||||
return False
|
||||
if is_configured():
|
||||
# 已设过密码, 不覆盖 (避免环境变量反复重置用户在 UI 改的密码)
|
||||
return False
|
||||
try:
|
||||
set_password(pwd)
|
||||
logger.info("access password bootstrapped from AUTH_PASSWORD env (one-time)")
|
||||
return True
|
||||
except ValueError as e:
|
||||
# 密码不合规 (< 6 位), 记日志但不阻断启动
|
||||
logger.warning("AUTH_PASSWORD bootstrap skipped: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def verify_and_create_session(password: str) -> str | None:
|
||||
"""验证密码, 成功则创建会话并返回 token, 失败返回 None。"""
|
||||
d = _load()
|
||||
if not d.get("password_hash"):
|
||||
return None
|
||||
if not _verify_password(password, d.get("password_salt", ""), d["password_hash"]):
|
||||
return None
|
||||
token = _secrets.token_urlsafe(_TOKEN_BYTES)
|
||||
expire = time.time() + SESSION_TTL
|
||||
with _lock:
|
||||
_sessions[token] = expire
|
||||
_persist_sessions_locked()
|
||||
return token
|
||||
|
||||
|
||||
def revoke_session(token: str) -> None:
|
||||
"""注销会话(登出)。"""
|
||||
with _lock:
|
||||
_sessions.pop(token, None)
|
||||
_persist_sessions_locked()
|
||||
|
||||
|
||||
def is_valid_session(token: str) -> bool:
|
||||
"""检查会话是否有效(存在且未过期)。过期则清理。"""
|
||||
if not token:
|
||||
return False
|
||||
with _lock:
|
||||
expire = _sessions.get(token)
|
||||
if expire is None:
|
||||
return False
|
||||
if time.time() > expire:
|
||||
_sessions.pop(token, None)
|
||||
_persist_sessions_locked()
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _persist_sessions_locked() -> None:
|
||||
"""把当前内存会话写回 auth.json(需持锁调用)。"""
|
||||
d = _load()
|
||||
d["sessions"] = {t: exp for t, exp in _sessions.items()}
|
||||
_save(d)
|
||||
|
||||
|
||||
def _restore_sessions() -> None:
|
||||
"""启动时从 auth.json 恢复未过期会话(支持进程重启不丢登录态)。"""
|
||||
with _lock:
|
||||
d = _load()
|
||||
now = time.time()
|
||||
saved = d.get("sessions") or {}
|
||||
for token, expire in saved.items():
|
||||
if isinstance(expire, (int, float)) and expire > now:
|
||||
_sessions[token] = expire
|
||||
if len(_sessions) != len(saved):
|
||||
# 有过期会话被清理, 落盘一次
|
||||
_persist_sessions_locked()
|
||||
|
||||
|
||||
# 模块加载时恢复会话
|
||||
try:
|
||||
_restore_sessions()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("restore sessions failed: %s", e)
|
||||
@@ -0,0 +1,392 @@
|
||||
"""回测服务(§6.7)。
|
||||
|
||||
包 vectorbt — 全项目唯一一处出现 pandas。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from typing import Literal
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import polars as pl
|
||||
|
||||
from app.config import settings
|
||||
from app.tickflow.repository import KlineRepository
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# vectorbt 是 optional extras(见 pyproject.toml).未装时只有 backtest 不可用,其他功能正常.
|
||||
_vbt = None
|
||||
_vbt_unavailable_reason: str | None = None
|
||||
|
||||
|
||||
class VectorbtUnavailable(RuntimeError):
|
||||
"""vectorbt 未安装 — 提示用户 `uv sync --extra backtest`."""
|
||||
|
||||
|
||||
def _get_vbt():
|
||||
global _vbt, _vbt_unavailable_reason
|
||||
if _vbt is not None:
|
||||
return _vbt
|
||||
if _vbt_unavailable_reason is not None:
|
||||
raise VectorbtUnavailable(_vbt_unavailable_reason)
|
||||
try:
|
||||
import vectorbt as vbt
|
||||
_vbt = vbt
|
||||
return _vbt
|
||||
except ImportError as e:
|
||||
_vbt_unavailable_reason = (
|
||||
"vectorbt 未安装 — 它是回测的可选依赖.macOS Intel 用户先 `brew install cmake` "
|
||||
"然后 `uv sync --extra backtest`"
|
||||
)
|
||||
logger.warning("vectorbt unavailable: %s", e)
|
||||
raise VectorbtUnavailable(_vbt_unavailable_reason) from e
|
||||
|
||||
|
||||
def is_available() -> bool:
|
||||
"""供 API 层快速检测."""
|
||||
try:
|
||||
_get_vbt()
|
||||
return True
|
||||
except VectorbtUnavailable:
|
||||
return False
|
||||
|
||||
|
||||
SignalKind = Literal[
|
||||
"macd_golden", "macd_dead",
|
||||
"ma_golden_5_20", "ma_dead_5_20",
|
||||
"ma_golden_20_60",
|
||||
"ma20_breakout", "ma20_breakdown",
|
||||
"n_day_high", "n_day_low",
|
||||
"boll_breakout_upper", "boll_breakdown_lower",
|
||||
"volume_surge",
|
||||
"rsi_oversold", "rsi_overbought",
|
||||
"stop_loss", "trailing_stop", "max_hold",
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class BacktestConfig:
|
||||
symbols: list[str]
|
||||
start: date
|
||||
end: date
|
||||
# 买入信号(任一触发即买)
|
||||
entries: list[str] = field(default_factory=list)
|
||||
# 卖出信号(任一触发即卖)
|
||||
exits: list[str] = field(default_factory=list)
|
||||
# 其他参数
|
||||
stop_loss_pct: float | None = None # 例 -0.05 = -5%
|
||||
max_hold_days: int | None = None
|
||||
fees_pct: float = 0.0002 # 万二佣金
|
||||
slippage_bps: float = 5 # 5 bps
|
||||
# 撮合
|
||||
matching: Literal["close_t", "open_t+1"] = "close_t"
|
||||
rsi_oversold_threshold: float = 30
|
||||
rsi_overbought_threshold: float = 70
|
||||
|
||||
|
||||
@dataclass
|
||||
class BacktestResult:
|
||||
run_id: str
|
||||
config: dict
|
||||
stats: dict
|
||||
equity_curve: list[dict] # [{date, value}]
|
||||
trades: list[dict] # [{symbol, entry_date, exit_date, pnl_pct, ...}]
|
||||
per_symbol_stats: list[dict] # 每只股票的统计
|
||||
|
||||
|
||||
# enriched 表里的信号列名映射
|
||||
_SIGNAL_COLS: dict[SignalKind, str] = {
|
||||
"macd_golden": "signal_macd_golden",
|
||||
"macd_dead": "signal_macd_dead",
|
||||
"ma_golden_5_20": "signal_ma_golden_5_20",
|
||||
"ma_dead_5_20": "signal_ma_dead_5_20",
|
||||
"ma_golden_20_60": "signal_ma_golden_20_60",
|
||||
"ma20_breakout": "signal_ma20_breakout",
|
||||
"ma20_breakdown": "signal_ma20_breakdown",
|
||||
"n_day_high": "signal_n_day_high",
|
||||
"n_day_low": "signal_n_day_low",
|
||||
"boll_breakout_upper": "signal_boll_breakout_upper",
|
||||
"boll_breakdown_lower": "signal_boll_breakdown_lower",
|
||||
"volume_surge": "signal_volume_surge",
|
||||
}
|
||||
|
||||
|
||||
class BacktestService:
|
||||
def __init__(self, repo: KlineRepository) -> None:
|
||||
self.repo = repo
|
||||
|
||||
def _load_panel(
|
||||
self,
|
||||
symbols: list[str],
|
||||
start: date,
|
||||
end: date,
|
||||
) -> pd.DataFrame:
|
||||
"""加载 [date × symbol] 价格面板 — Polars scan_parquet + 即时计算指标。
|
||||
|
||||
**全项目唯一从 Polars 转 pandas 的边界**(§7.4 / ADR-19)。
|
||||
"""
|
||||
try:
|
||||
enriched_glob = str(self.repo.store.data_dir / "kline_daily_enriched" / "**" / "*.parquet")
|
||||
df = (
|
||||
pl.scan_parquet(enriched_glob)
|
||||
.filter(
|
||||
(pl.col("symbol").is_in(symbols))
|
||||
& (pl.col("date") >= start)
|
||||
& (pl.col("date") <= end)
|
||||
)
|
||||
.sort(["date", "symbol"])
|
||||
.collect()
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("backtest load failed: %s", e)
|
||||
return pd.DataFrame()
|
||||
|
||||
if df.is_empty():
|
||||
return pd.DataFrame()
|
||||
|
||||
# 即时计算指标 + 信号
|
||||
from app.indicators.pipeline import compute_all
|
||||
df = compute_all(df)
|
||||
|
||||
# 选择需要的列
|
||||
needed_cols = [
|
||||
"date", "symbol", "open", "high", "low", "close", "volume",
|
||||
"rsi_14", "signal_macd_golden", "signal_macd_dead",
|
||||
"signal_ma_golden_5_20", "signal_ma_dead_5_20",
|
||||
"signal_ma_golden_20_60",
|
||||
"signal_ma20_breakout", "signal_ma20_breakdown",
|
||||
"signal_n_day_high", "signal_n_day_low",
|
||||
"signal_boll_breakout_upper", "signal_boll_breakdown_lower",
|
||||
"signal_volume_surge",
|
||||
]
|
||||
existing = [c for c in needed_cols if c in df.columns]
|
||||
df = df.select(existing)
|
||||
|
||||
# to_pandas 边界
|
||||
return df.to_pandas(use_pyarrow_extension_array=False)
|
||||
|
||||
def _build_signal_matrix(
|
||||
self,
|
||||
panel: pd.DataFrame,
|
||||
kinds: list[str],
|
||||
config: BacktestConfig,
|
||||
) -> pd.DataFrame:
|
||||
"""从面板构造 [date × symbol] 的布尔信号矩阵。"""
|
||||
if not kinds or panel.empty:
|
||||
return pd.DataFrame()
|
||||
|
||||
# pivot 成 [date × symbol] 形式
|
||||
result = None
|
||||
for kind in kinds:
|
||||
mat = None
|
||||
if kind in _SIGNAL_COLS:
|
||||
col = _SIGNAL_COLS[kind]
|
||||
mat = panel.pivot(index="date", columns="symbol", values=col).fillna(False).astype(bool)
|
||||
elif kind == "rsi_oversold":
|
||||
mat = (panel.pivot(index="date", columns="symbol", values="rsi_14")
|
||||
< config.rsi_oversold_threshold)
|
||||
elif kind == "rsi_overbought":
|
||||
mat = (panel.pivot(index="date", columns="symbol", values="rsi_14")
|
||||
> config.rsi_overbought_threshold)
|
||||
# stop_loss / trailing / max_hold 通过 vectorbt 参数处理,不参与信号矩阵
|
||||
|
||||
if mat is not None:
|
||||
result = mat if result is None else (result | mat)
|
||||
return result if result is not None else pd.DataFrame()
|
||||
|
||||
def run(self, config: BacktestConfig) -> BacktestResult:
|
||||
vbt = _get_vbt()
|
||||
run_id = uuid.uuid4().hex[:10]
|
||||
|
||||
panel = self._load_panel(config.symbols, config.start, config.end)
|
||||
if panel.empty:
|
||||
return BacktestResult(
|
||||
run_id=run_id,
|
||||
config=_config_to_dict(config),
|
||||
stats={"error": "no data"},
|
||||
equity_curve=[],
|
||||
trades=[],
|
||||
per_symbol_stats=[],
|
||||
)
|
||||
|
||||
# 价格面板
|
||||
close = panel.pivot(index="date", columns="symbol", values="close")
|
||||
|
||||
# 信号矩阵
|
||||
entries = self._build_signal_matrix(panel, config.entries, config)
|
||||
exits = self._build_signal_matrix(panel, config.exits, config)
|
||||
|
||||
# 对齐 index/columns
|
||||
if not entries.empty:
|
||||
entries = entries.reindex_like(close).fillna(False).astype(bool)
|
||||
else:
|
||||
entries = pd.DataFrame(False, index=close.index, columns=close.columns)
|
||||
if not exits.empty:
|
||||
exits = exits.reindex_like(close).fillna(False).astype(bool)
|
||||
else:
|
||||
exits = pd.DataFrame(False, index=close.index, columns=close.columns)
|
||||
|
||||
if not entries.any().any():
|
||||
return BacktestResult(
|
||||
run_id=run_id,
|
||||
config=_config_to_dict(config),
|
||||
stats={"error": "no buy signals"},
|
||||
equity_curve=[],
|
||||
trades=[],
|
||||
per_symbol_stats=[],
|
||||
)
|
||||
|
||||
# T+1 适配:vectorbt 默认信号当根 K 撮合
|
||||
# close_t 撮合:维持默认
|
||||
# open_t+1 撮合:shift 信号 1 根 + 用 open 作为价
|
||||
if config.matching == "open_t+1":
|
||||
entries = entries.shift(1).fillna(False).astype(bool)
|
||||
exits = exits.shift(1).fillna(False).astype(bool)
|
||||
price = panel.pivot(index="date", columns="symbol", values="open")
|
||||
else:
|
||||
price = close
|
||||
|
||||
# 跑回测
|
||||
try:
|
||||
pf_kwargs = dict(
|
||||
close=close,
|
||||
entries=entries,
|
||||
exits=exits,
|
||||
price=price,
|
||||
fees=config.fees_pct,
|
||||
slippage=config.slippage_bps / 10000.0,
|
||||
freq="1D",
|
||||
)
|
||||
if config.stop_loss_pct is not None:
|
||||
pf_kwargs["sl_stop"] = abs(config.stop_loss_pct)
|
||||
if config.max_hold_days is not None:
|
||||
# vectorbt 没有内置 max-hold;用时间退出近似:
|
||||
# 在 max_hold_days 后强制 exit
|
||||
exits_idx = entries.copy()
|
||||
for col in entries.columns:
|
||||
entry_rows = np.where(entries[col].values)[0]
|
||||
for i in entry_rows:
|
||||
end_i = min(i + config.max_hold_days, len(entries) - 1)
|
||||
if end_i > i:
|
||||
exits_idx.iloc[end_i][col] = True
|
||||
pf_kwargs["exits"] = (exits | exits_idx).astype(bool)
|
||||
|
||||
pf = vbt.Portfolio.from_signals(**pf_kwargs)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception("vectorbt backtest failed")
|
||||
return BacktestResult(
|
||||
run_id=run_id,
|
||||
config=_config_to_dict(config),
|
||||
stats={"error": str(e)},
|
||||
equity_curve=[],
|
||||
trades=[],
|
||||
per_symbol_stats=[],
|
||||
)
|
||||
|
||||
# 提取结果
|
||||
try:
|
||||
stats_series = pf.stats(silence_warnings=True)
|
||||
if isinstance(stats_series, pd.DataFrame):
|
||||
# 多列时取 agg
|
||||
stats_dict = stats_series.mean(numeric_only=True).to_dict()
|
||||
else:
|
||||
stats_dict = stats_series.to_dict()
|
||||
except Exception: # noqa: BLE001
|
||||
stats_dict = {}
|
||||
|
||||
# 净值曲线(组合平均)
|
||||
equity = pf.value().mean(axis=1) if isinstance(pf.value(), pd.DataFrame) else pf.value()
|
||||
equity_curve = [
|
||||
{"date": str(idx.date() if hasattr(idx, "date") else idx), "value": float(v)}
|
||||
for idx, v in equity.items() if pd.notna(v)
|
||||
]
|
||||
|
||||
# 交易记录
|
||||
try:
|
||||
trades_df = pf.trades.records_readable
|
||||
trades = trades_df.to_dict(orient="records") if not trades_df.empty else []
|
||||
# 字段名美化
|
||||
trades = [
|
||||
{
|
||||
"symbol": t.get("Column", t.get("Symbol", "")),
|
||||
"entry_date": str(t.get("Entry Timestamp", t.get("Entry Date", ""))),
|
||||
"exit_date": str(t.get("Exit Timestamp", t.get("Exit Date", ""))),
|
||||
"entry_price": float(t.get("Avg Entry Price", t.get("Avg. Entry Price", 0))),
|
||||
"exit_price": float(t.get("Avg Exit Price", t.get("Avg. Exit Price", 0))),
|
||||
"pnl_pct": float(t.get("Return", t.get("PnL %", 0))),
|
||||
"duration": str(t.get("Duration", "")),
|
||||
}
|
||||
for t in trades
|
||||
]
|
||||
except Exception: # noqa: BLE001
|
||||
trades = []
|
||||
|
||||
# 每标的统计
|
||||
per_symbol = []
|
||||
try:
|
||||
total_ret = pf.total_return()
|
||||
if isinstance(total_ret, pd.Series):
|
||||
for sym, ret in total_ret.items():
|
||||
if pd.notna(ret):
|
||||
per_symbol.append({"symbol": sym, "total_return": float(ret)})
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
result = BacktestResult(
|
||||
run_id=run_id,
|
||||
config=_config_to_dict(config),
|
||||
stats={k: _json_safe(v) for k, v in stats_dict.items()},
|
||||
equity_curve=equity_curve,
|
||||
trades=trades,
|
||||
per_symbol_stats=per_symbol,
|
||||
)
|
||||
|
||||
# 落盘
|
||||
self._persist(result)
|
||||
return result
|
||||
|
||||
def _persist(self, result: BacktestResult) -> None:
|
||||
out_dir = settings.data_dir / "backtest_results"
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
# 用 polars 写一份汇总
|
||||
summary = pl.DataFrame({
|
||||
"run_id": [result.run_id],
|
||||
"stats_json": [str(result.stats)],
|
||||
"n_trades": [len(result.trades)],
|
||||
})
|
||||
summary.write_parquet(out_dir / f"run_id={result.run_id}.parquet")
|
||||
|
||||
def get_result(self, run_id: str) -> BacktestResult | None:
|
||||
# Phase 1:只保留近似落盘,完整结果保存在内存的近期 cache 中
|
||||
# 简化:重新 run 比缓存复杂结果代价小,暂不实现 get_result
|
||||
return None
|
||||
|
||||
|
||||
def _config_to_dict(c: BacktestConfig) -> dict:
|
||||
return {
|
||||
"symbols": c.symbols,
|
||||
"start": str(c.start),
|
||||
"end": str(c.end),
|
||||
"entries": c.entries,
|
||||
"exits": c.exits,
|
||||
"stop_loss_pct": c.stop_loss_pct,
|
||||
"max_hold_days": c.max_hold_days,
|
||||
"fees_pct": c.fees_pct,
|
||||
"slippage_bps": c.slippage_bps,
|
||||
"matching": c.matching,
|
||||
}
|
||||
|
||||
|
||||
def _json_safe(v):
|
||||
if isinstance(v, (int, float, str, bool)) or v is None:
|
||||
return v
|
||||
if isinstance(v, (np.floating, np.integer)):
|
||||
return float(v) if not np.isnan(float(v)) else None
|
||||
if hasattr(v, "isoformat"):
|
||||
return v.isoformat()
|
||||
return str(v)
|
||||
@@ -0,0 +1,357 @@
|
||||
"""AI 概念轮动分析 — 从概念涨幅排名矩阵提炼主线/新晋/退潮信号。
|
||||
|
||||
数据来源:
|
||||
- rps_rotation.build_rps_rotation: 概念涨幅排名矩阵 (N 日 × ~387 概念)
|
||||
- market_overview_builder.build_market_overview: 大盘背景 (指数/情绪/涨停)
|
||||
|
||||
架构 (复刻 market_recap):
|
||||
预计算轮动信号 → 拼装 prompt → stream_ai_text 流式调用 → NDJSON 协议输出
|
||||
协议事件: meta(摘要) / delta(文本片段) / error / done
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# System Prompt — 轮动策略师人格 + 固定章节模板
|
||||
# ================================================================
|
||||
|
||||
_SYSTEM_PROMPT = """你是一位专注 A 股题材轮动的资深策略师,拥有 12 年一线实战经验,擅长从概念板块的**涨幅排名矩阵**中识别主力资金脉络,区分机构主导的持续性主线与游资驱动的脉冲式轮动,产出可直接指导题材跟踪与节奏把握的轮动分析。
|
||||
|
||||
## 输出规范
|
||||
|
||||
用 **Markdown** 格式输出,严格遵循以下结构。不要输出任何 JSON 或代码块,直接输出 Markdown 正文。
|
||||
|
||||
### 1. 🎯 主线研判(2-3 句)
|
||||
点名当前最核心的 1-2 条主线题材(连续多日霸榜的强势概念),用一句话概括其逻辑(政策/产业/业绩/事件驱动),并判断是**主升期/加速期/扩散期/见顶期**。结尾用【主线强度:强 / 中 / 弱】定性。
|
||||
|
||||
### 2. 🆕 新晋强势
|
||||
列出排名快速跃升的概念(从榜单中后段冲进前列的),逐个给出:
|
||||
- 概念名 + 近 N 日排名变化(如 `45→20→8`)
|
||||
- 涨幅加速度(连日递增 = 趋势加强)
|
||||
- 可能的驱动逻辑(从板块属性推断,不要编造具体消息)
|
||||
- 判断是**主力切入**还是**消息脉冲**
|
||||
|
||||
### 3. 📉 退潮预警
|
||||
列出从高位明显滑落的概念(连续排名下滑或涨幅骤降),逐个给出:
|
||||
- 概念名 + 排名下滑轨迹
|
||||
- 退潮性质(高位分歧/资金撤离/补跌)
|
||||
- 是否扩散风险
|
||||
|
||||
### 4. 🏛️ 机构主线 vs 🎰 游资轮动
|
||||
基于排名稳定性区分两类资金行为:
|
||||
- **机构主线**:排名标准差小、长期稳居前列的概念 → 持续性判断、是否可作底仓方向
|
||||
- **游资轮动**:排名剧烈波动、脉冲式冲高的概念 → 短线节奏提示、追高风险
|
||||
给出当前市场**整体轮动节奏**(快轮动/慢轮动/主线聚焦)的判断。
|
||||
|
||||
### 5. 🌐 结合大盘
|
||||
结合提供的大盘数据(指数涨跌/情绪/涨停数),判断:
|
||||
- 当前大盘环境对题材轮动是助力还是阻力
|
||||
- 情绪温度与轮动节奏的匹配度(如情绪冰点但题材活跃 = 抱团;情绪火热但轮动快 = 末段)
|
||||
|
||||
### 6. 🎯 操作建议
|
||||
- **跟踪方向**:主线延续 + 新晋确认的概念
|
||||
- **规避方向**:明确退潮 + 高位脉冲的概念
|
||||
- **节奏提示**:当前适合追高 / 低吸 / 观望,及切换信号(如"主线概念连续 2 日跌出前 10 则确认退潮")
|
||||
|
||||
### 7. ⚠️ 风险提示
|
||||
列出需要盯的风险(如主线断层、情绪与轮动背离、成交萎缩)。末尾附一行:
|
||||
"> ⚠️ 本报告由 AI 基于公开行情数据生成,仅供参考,不构成任何投资建议。交易有风险,入市需谨慎。"
|
||||
|
||||
## 分析准则(务必遵守)
|
||||
|
||||
0. **只输出结论,不输出思考过程**:禁止复述你的分析步骤。不要写"我先看...""基于上述数据我认为"——直接给结论。
|
||||
1. **数据说话**:每个判断引用具体排名/涨幅数值,严禁空泛套话("强势"必须改成"连续 4 日稳居前 5,均涨 +4.2%")。
|
||||
2. **诚实中立**:数据不支持的结论就直言"信号不足,暂无法判断",不要硬凑。
|
||||
3. **区分资金性质**:这是本分析的核心价值——机构 vs 游资的判断必须基于排名稳定性(标准差),不要凭感觉。
|
||||
4. **不重复数字**:正文负责解读信号含义,不要照抄罗列已提供的全部原始数据。
|
||||
5. **简明实战**:总字数 1000-1800 字,重在可执行。
|
||||
6. **客观推断**:若无明确消息,从量价异动推断可能逻辑并给结论,不要标注"[推断]"或编造具体新闻。
|
||||
|
||||
现在请基于下方概念轮动数据进行分析。"""
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 预计算: 把排名矩阵转成结构化轮动信号
|
||||
# ================================================================
|
||||
|
||||
# 每类信号最多取多少个概念喂给 AI (控制 token)
|
||||
_TOP_N = 8
|
||||
|
||||
|
||||
def _compute_rotation_signals(dates: list[str], columns: dict) -> dict:
|
||||
"""从概念涨幅排名矩阵计算轮动信号。
|
||||
|
||||
Args:
|
||||
dates: 日期列表 (最新在最前, 与 columns key 一致)
|
||||
columns: {日期: [[概念, 涨幅], ...]} 每列各自降序
|
||||
|
||||
Returns:
|
||||
{
|
||||
"persistent_leaders": [...], # 连续多日稳居前列 (主线)
|
||||
"rising": [...], # 排名快速跃升 (新晋)
|
||||
"fading": [...], # 从高位滑落 (退潮)
|
||||
"institutional": [...], # 排名稳定 (机构特征)
|
||||
"hot_money": [...], # 排名波动大 (游资特征)
|
||||
}
|
||||
每项含: concept, ranks (按 dates 顺序), pcts, avg_rank, rank_std
|
||||
ranks 时间方向: ranks[0] = 最早日, ranks[-1] = 最新日 (已反转, 左老右新)
|
||||
"""
|
||||
if not dates or not columns:
|
||||
return {}
|
||||
|
||||
# 按时间正序 (左老右新) 处理
|
||||
dates_asc = list(reversed(dates))
|
||||
|
||||
# 收集每个概念在各日期的 (排名, 涨幅)。排名 = 该日在列中的索引 + 1。
|
||||
concept_data: dict[str, list[tuple[int, float]]] = {}
|
||||
for d in dates_asc:
|
||||
col = columns.get(d) or []
|
||||
for idx, (name, pct) in enumerate(col):
|
||||
concept_data.setdefault(name, []).append((idx + 1, pct))
|
||||
|
||||
n_dates = len(dates_asc)
|
||||
|
||||
def _stats(ranks_pcts: list[tuple[int, float]]) -> dict:
|
||||
ranks = [r for r, _ in ranks_pcts]
|
||||
pcts = [p for _, p in ranks_pcts]
|
||||
avg = sum(ranks) / len(ranks) if ranks else 0
|
||||
var = sum((r - avg) ** 2 for r in ranks) / len(ranks) if ranks else 0
|
||||
return {
|
||||
"ranks": ranks,
|
||||
"pcts": [round(p, 4) for p in pcts],
|
||||
"avg_rank": round(avg, 1),
|
||||
"rank_std": round(math.sqrt(var), 1),
|
||||
}
|
||||
|
||||
persistent: list[dict] = []
|
||||
rising: list[dict] = []
|
||||
fading: list[dict] = []
|
||||
institutional: list[dict] = []
|
||||
hot_money: list[dict] = []
|
||||
|
||||
for concept, rp in concept_data.items():
|
||||
# 缺失日补 (大排名, 0 涨幅) 保持时间轴对齐
|
||||
if len(rp) < n_dates:
|
||||
rp = rp + [(999, 0.0)] * (n_dates - len(rp))
|
||||
s = _stats(rp)
|
||||
s["concept"] = concept
|
||||
|
||||
ranks = s["ranks"]
|
||||
latest_rank = ranks[-1]
|
||||
earliest_rank = ranks[0]
|
||||
# 最近 3 日 (不足则全部) 均排名, 判断近期强度
|
||||
recent = ranks[-min(3, len(ranks)):]
|
||||
recent_avg = sum(recent) / len(recent)
|
||||
|
||||
# 主线: 近期稳居前 10
|
||||
if recent_avg <= 10 and latest_rank <= 10:
|
||||
persistent.append(s)
|
||||
|
||||
# 新晋: 早期排名靠后(>30), 最新冲进前 20, 跃升幅度大
|
||||
jump = earliest_rank - latest_rank
|
||||
if earliest_rank > 30 and latest_rank <= 20 and jump >= 20:
|
||||
rising.append(s)
|
||||
|
||||
# 退潮: 早期排名靠前(<=10), 最新滑落到 30 外
|
||||
drop = latest_rank - earliest_rank
|
||||
if earliest_rank <= 10 and latest_rank > 30 and drop >= 20:
|
||||
fading.append(s)
|
||||
|
||||
# 机构: 排名标准差小且平均排名靠前 (稳定强势)
|
||||
if s["rank_std"] <= 5 and s["avg_rank"] <= 20:
|
||||
institutional.append(s)
|
||||
|
||||
# 游资: 排名标准差大 (波动剧烈)
|
||||
if s["rank_std"] >= 20:
|
||||
hot_money.append(s)
|
||||
|
||||
# 排序: 主线按近期排名升序; 新晋按跃升幅度降序; 退潮按跌幅降序
|
||||
persistent.sort(key=lambda x: x["avg_rank"])
|
||||
rising.sort(key=lambda x: x["ranks"][0] - x["ranks"][-1], reverse=True)
|
||||
fading.sort(key=lambda x: x["ranks"][-1] - x["ranks"][0], reverse=True)
|
||||
institutional.sort(key=lambda x: (x["rank_std"], x["avg_rank"]))
|
||||
hot_money.sort(key=lambda x: x["rank_std"], reverse=True)
|
||||
|
||||
return {
|
||||
"persistent_leaders": persistent[:_TOP_N],
|
||||
"rising": rising[:_TOP_N],
|
||||
"fading": fading[:_TOP_N],
|
||||
"institutional": institutional[:_TOP_N],
|
||||
"hot_money": hot_money[:_TOP_N],
|
||||
}
|
||||
|
||||
|
||||
# ================================================================
|
||||
# Prompt 构建
|
||||
# ================================================================
|
||||
|
||||
def _fmt_pct(v) -> str:
|
||||
if v is None:
|
||||
return "—"
|
||||
return f"{v*100:+.2f}%"
|
||||
|
||||
|
||||
def _build_market_block(overview: dict) -> str:
|
||||
"""大盘背景精简块 (复用 market_overview 已算好的字段)。"""
|
||||
indices = overview.get("indices") or []
|
||||
emo = overview.get("emotion") or {}
|
||||
lim = overview.get("limit") or {}
|
||||
amt = overview.get("amount") or {}
|
||||
|
||||
idx_lines = []
|
||||
for idx in indices[:4]:
|
||||
name = idx.get("name") or idx.get("symbol") or "?"
|
||||
chg = idx.get("change_pct")
|
||||
idx_lines.append(f"{name} {_fmt_pct(chg)}")
|
||||
idx_str = " / ".join(idx_lines) or "指数缺失"
|
||||
|
||||
total_amount = (amt.get("total") or 0) / 1e8 # 元 → 亿
|
||||
|
||||
return (
|
||||
f"- 指数: {idx_str}\n"
|
||||
f"- 情绪: {emo.get('score', 50)} ({emo.get('label', '—')})\n"
|
||||
f"- 涨停/炸板/跌停: {lim.get('limit_up', 0)} / {lim.get('broken', 0)} / {lim.get('limit_down', 0)}"
|
||||
f" (最高连板 {lim.get('max_boards', 0)})\n"
|
||||
f"- 两市成交额: {total_amount:.0f} 亿元"
|
||||
)
|
||||
|
||||
|
||||
def _build_signal_block(title: str, items: list[dict]) -> str:
|
||||
"""轮动信号块: 把预计算的概念信号转成紧凑文本。"""
|
||||
if not items:
|
||||
return f"### {title}\n(本类无明显信号)"
|
||||
lines = [f"### {title}"]
|
||||
for it in items:
|
||||
ranks_str = "→".join(str(r) if r < 999 else "—" for r in it["ranks"])
|
||||
avg_pct = sum(it["pcts"]) / len(it["pcts"]) if it["pcts"] else 0
|
||||
lines.append(
|
||||
f"- {it['concept']}: 排名 {ranks_str} | 均排名 {it['avg_rank']} "
|
||||
f"| 排名波动σ {it['rank_std']} | 区间均涨 {_fmt_pct(avg_pct)}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _build_user_prompt(signals: dict, overview: dict, days: int, dates: list[str], focus: str) -> str:
|
||||
"""组装 user 消息: 大盘背景 + 轮动信号 + focus。"""
|
||||
dates_asc = list(reversed(dates))
|
||||
date_range = f"{dates_asc[0]} ~ {dates_asc[-1]}" if dates_asc else "—"
|
||||
|
||||
parts = [
|
||||
f"# 概念涨幅轮动数据 (最近 {days} 个交易日: {date_range})",
|
||||
"",
|
||||
"## 大盘背景",
|
||||
_build_market_block(overview),
|
||||
"",
|
||||
"## 轮动信号 (排名时间方向: 左→右 = 旧→新, 排名越小越强)",
|
||||
"",
|
||||
_build_signal_block("🎯 主线 (连续霸榜)", signals.get("persistent_leaders", [])),
|
||||
"",
|
||||
_build_signal_block("🆕 新晋强势 (排名跃升)", signals.get("rising", [])),
|
||||
"",
|
||||
_build_signal_block("📉 退潮预警 (高位滑落)", signals.get("fading", [])),
|
||||
"",
|
||||
_build_signal_block("🏛️ 机构特征 (排名稳定)", signals.get("institutional", [])),
|
||||
"",
|
||||
_build_signal_block("🎰 游资特征 (排名波动大)", signals.get("hot_money", [])),
|
||||
]
|
||||
|
||||
if focus.strip():
|
||||
parts.extend(["", f"## 用户关注点\n{focus.strip()}"])
|
||||
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def _build_summary(signals: dict) -> str:
|
||||
"""meta 事件的摘要 (前端可立即展示)。"""
|
||||
leaders = signals.get("persistent_leaders", [])
|
||||
rising = signals.get("rising", [])
|
||||
fading = signals.get("fading", [])
|
||||
leader_names = "、".join(it["concept"] for it in leaders[:3]) or "暂无明确主线"
|
||||
return f"主线: {leader_names} | 新晋 {len(rising)} | 退潮 {len(fading)}"
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 流式主入口
|
||||
# ================================================================
|
||||
|
||||
async def analyze_rotation_stream(
|
||||
repo,
|
||||
days: int = 12,
|
||||
focus: str = "",
|
||||
quote_service=None,
|
||||
depth_service=None,
|
||||
) -> AsyncIterator[str]:
|
||||
"""流式概念轮动分析: yield 出每个 NDJSON 事件。
|
||||
|
||||
Args:
|
||||
repo: KlineRepository (必填)。
|
||||
days: 分析最近 N 个交易日 (7-30)。
|
||||
focus: 用户追加的关注点。
|
||||
quote_service / depth_service: 可选, 大盘背景装配依赖。
|
||||
"""
|
||||
from app.services.rps_rotation import build_rps_rotation
|
||||
from app.services.market_overview_builder import build_market_overview
|
||||
|
||||
# 1. 取轮动矩阵
|
||||
rotation = build_rps_rotation(repo, days)
|
||||
dates = rotation.get("dates") or []
|
||||
columns = rotation.get("columns") or {}
|
||||
|
||||
if not dates or not columns:
|
||||
yield json.dumps({
|
||||
"type": "error",
|
||||
"message": "暂无概念轮动数据,请先在「概念分析」页获取概念数据源",
|
||||
}, ensure_ascii=False)
|
||||
return
|
||||
|
||||
# 2. 预计算轮动信号
|
||||
signals = _compute_rotation_signals(dates, columns)
|
||||
|
||||
# 3. 大盘背景 (失败不阻断, 降级为空)
|
||||
try:
|
||||
overview = build_market_overview(repo, quote_service, depth_service)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("rotation analyze: 大盘背景获取失败, 降级为空: %s", e)
|
||||
overview = {}
|
||||
|
||||
# 4. meta 事件
|
||||
yield json.dumps({
|
||||
"type": "meta",
|
||||
"days": days,
|
||||
"summary": _build_summary(signals),
|
||||
}, ensure_ascii=False)
|
||||
|
||||
# 5. 构建 prompt + 流式调用 LLM
|
||||
try:
|
||||
from app.services.ai_provider import stream_ai_text, ai_configured
|
||||
|
||||
if not ai_configured():
|
||||
yield json.dumps({
|
||||
"type": "error",
|
||||
"message": "AI 未配置,请在「设置」页填写 API Key 与接口地址",
|
||||
}, ensure_ascii=False)
|
||||
return
|
||||
|
||||
user_prompt = _build_user_prompt(signals, overview, days, dates, focus)
|
||||
async for delta in stream_ai_text(
|
||||
[
|
||||
{"role": "system", "content": _SYSTEM_PROMPT},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
temperature=0.5,
|
||||
max_tokens=4000,
|
||||
):
|
||||
yield json.dumps({"type": "delta", "content": delta}, ensure_ascii=False)
|
||||
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception("AI concept rotation analyze failed: %s", e)
|
||||
yield json.dumps({"type": "error", "message": f"AI 轮动分析失败: {e}"}, ensure_ascii=False)
|
||||
|
||||
yield json.dumps({"type": "done"}, ensure_ascii=False)
|
||||
@@ -0,0 +1,586 @@
|
||||
"""五档盘口 sealed(真假涨停/跌停) 服务 — 独立旁路线。
|
||||
|
||||
架构(完全解耦):
|
||||
- 只读 enriched(拿涨跌停名单), 不写回 enriched(14列不动)
|
||||
- sealed 存独立 parquet(data/depth5/date=xxx/part.parquet)
|
||||
- limit_ladder API 查询时 LEFT JOIN(同 ext_columns 机制)
|
||||
- signal_limit_up 永远是"价格涨停", sealed 是叠加的真假判定层
|
||||
|
||||
数据流:
|
||||
盘中轮询线程(交易时段, 独立 sleep, 不绑行情轮询):
|
||||
读 enriched 内存缓存(线程安全) → 涨跌停名单 → tf.depth.batch
|
||||
→ 算 sealed → 更新内存缓存(不落盘) → sealed_ready=True
|
||||
盘后定版 job(可配置时间, 默认15:02):
|
||||
最后拉一次 → 落盘 depth5 parquet(定版)
|
||||
|
||||
三层防护节流("设过大设上限, 设过小设最小值"):
|
||||
① 套餐范围 clamp: Pro 10~120s, Expert 3~300s
|
||||
② 限速安全 clamp: safe = 60/((rpm*0.8)/batches), 涨跌停多就自动放慢
|
||||
③ 系统接管通知: 用户设置会超限时, 推 toast 告知已自动调整
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
from datetime import date, datetime, time as dt_time
|
||||
from pathlib import Path
|
||||
|
||||
import polars as pl
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# 套餐 → (轮询间隔下限s, 上限s)
|
||||
TIER_INTERVAL_RANGE: dict[str, tuple[float, float]] = {
|
||||
"pro": (10.0, 120.0),
|
||||
"expert": (3.0, 300.0),
|
||||
}
|
||||
# 兜底: 其他有 DEPTH5_BATCH 的套餐按 pro 范围
|
||||
DEFAULT_RANGE = (10.0, 120.0)
|
||||
|
||||
# 限速余量: 只用 rpm 的 80%, 给系统其他 depth 调用留空间
|
||||
RPM_MARGIN = 0.8
|
||||
# 间隔硬下限/上限(任何套餐)
|
||||
INTERVAL_HARD_MIN = 10.0
|
||||
INTERVAL_HARD_MAX = 300.0
|
||||
|
||||
|
||||
class DepthService:
|
||||
"""五档盘口 sealed 服务 — 单例。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self._running = False
|
||||
self._thread: threading.Thread | None = None
|
||||
self._repo = None # 延迟注入(KlineRepository)
|
||||
self._app_state = None # 延迟注入(FastAPI app.state)
|
||||
|
||||
# 内存缓存: {symbol: SealedEntry}
|
||||
# SealedEntry = {sealed_up, sealed_down, ask1_vol, bid1_vol, status, fetched_ts}
|
||||
self._sealed_cache: dict[str, dict] = {}
|
||||
self._sealed_ready = False
|
||||
self._sealed_date: date | None = None # sealed 数据对应的交易日(可能是昨天,如休市)
|
||||
self._sealed_fetched_ts: float = 0.0 # 上次拉取的 perf_counter
|
||||
self._sealed_fetched_at: float = 0.0 # 上次拉取的 wall-clock 时间戳
|
||||
self._persisted_date: date | None = None # 已落盘的日期
|
||||
|
||||
# 系统接管状态(防通知刷屏)
|
||||
self._last_taken_over: bool | None = None
|
||||
self._last_user_interval: float | None = None
|
||||
|
||||
# ================================================================
|
||||
# 注入
|
||||
# ================================================================
|
||||
|
||||
def set_repo(self, repo) -> None:
|
||||
self._repo = repo
|
||||
|
||||
def set_app_state(self, app_state) -> None:
|
||||
self._app_state = app_state
|
||||
|
||||
# ================================================================
|
||||
# 生命周期
|
||||
# ================================================================
|
||||
|
||||
def boot_check(self) -> None:
|
||||
"""启动补跑: 当天 depth5 文件不存在则 finalize 一次; 已存在则恢复内存缓存。"""
|
||||
if not self._has_capability():
|
||||
logger.info("depth sealed: 无 DEPTH5_BATCH 能力, 跳过启动补跑")
|
||||
return
|
||||
today = date.today()
|
||||
if self._persisted_for_date(today):
|
||||
# parquet 已存在: 恢复内存缓存(避免重启后每次查询都读 parquet)
|
||||
self._restore_from_parquet(today)
|
||||
return
|
||||
logger.info("depth sealed: 启动补跑今天定版")
|
||||
try:
|
||||
self.finalize()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("depth sealed 启动补跑失败: %s", e)
|
||||
|
||||
def _restore_from_parquet(self, d: date) -> None:
|
||||
"""从 parquet 恢复内存缓存(服务重启后)。"""
|
||||
if not self._repo:
|
||||
return
|
||||
out = self._repo.store.data_dir / "depth5" / f"date={d.isoformat()}" / "part.parquet"
|
||||
if not out.exists():
|
||||
return
|
||||
try:
|
||||
df = pl.read_parquet(out)
|
||||
cache: dict[str, dict] = {}
|
||||
for row in df.to_dicts():
|
||||
sym = row.get("symbol")
|
||||
if not sym:
|
||||
continue
|
||||
cache[sym] = {
|
||||
"sealed_up": row.get("sealed_up"),
|
||||
"sealed_down": row.get("sealed_down"),
|
||||
"ask1_vol": row.get("ask1_vol"),
|
||||
"bid1_vol": row.get("bid1_vol"),
|
||||
"status": row.get("status"),
|
||||
"fetched_ts": row.get("fetched_at"),
|
||||
}
|
||||
with self._lock:
|
||||
self._sealed_cache = cache
|
||||
self._sealed_ready = True
|
||||
self._sealed_date = d
|
||||
self._persisted_date = d
|
||||
logger.info("depth sealed: 从 parquet 恢复 %d 只 (日期=%s)", len(cache), d)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("depth sealed 从 parquet 恢复失败: %s", e)
|
||||
|
||||
def start_polling(self) -> None:
|
||||
"""启动盘中轮询线程(连板梯队监控开启 + 有能力 + 交易时段)。"""
|
||||
if self._running:
|
||||
return
|
||||
if not self._has_capability():
|
||||
return
|
||||
from app.services import preferences
|
||||
if not preferences.get_limit_ladder_monitor_enabled():
|
||||
return
|
||||
self._running = True
|
||||
self._thread = threading.Thread(target=self._poll_loop, daemon=True)
|
||||
self._thread.start()
|
||||
logger.info("depth sealed 盘中轮询已启动")
|
||||
|
||||
def stop_polling(self) -> None:
|
||||
"""停止盘中轮询线程。"""
|
||||
self._running = False
|
||||
if self._thread:
|
||||
self._thread.join(timeout=10)
|
||||
self._thread = None
|
||||
logger.info("depth sealed 盘中轮询已停止")
|
||||
|
||||
def apply_monitor_toggle(self, enabled: bool) -> None:
|
||||
"""连板梯队监控开关切换时调用: 开启→启动轮询, 关闭→停止轮询。"""
|
||||
if enabled:
|
||||
self.start_polling()
|
||||
else:
|
||||
self.stop_polling()
|
||||
|
||||
def run_once(self) -> dict:
|
||||
"""手动触发一次修正(立即拉取 depth + 更新内存缓存)。
|
||||
|
||||
不受监控开关限制 — 用户可随时手动修正一次。
|
||||
返回 {"ok": bool, "count": int, "msg": str}
|
||||
"""
|
||||
if not self._has_capability():
|
||||
return {"ok": False, "count": 0, "msg": "无五档盘口能力(需 Pro+)"}
|
||||
try:
|
||||
self._fetch_and_seal(persist=True) # 落盘, 刷新页面不丢
|
||||
with self._lock:
|
||||
count = len(self._sealed_cache)
|
||||
return {"ok": True, "count": count, "msg": f"已修正 {count} 只"}
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("depth run_once 失败: %s", e)
|
||||
return {"ok": False, "count": 0, "msg": f"修正失败: {e}"}
|
||||
|
||||
# ================================================================
|
||||
# 核心拉取
|
||||
# ================================================================
|
||||
|
||||
def _fetch_and_seal(self, persist: bool = False) -> None:
|
||||
"""拉一次 depth.batch, 算 sealed, 更新内存缓存(可选落盘)。
|
||||
|
||||
persist=True: 盘后定版, 写 depth5 parquet
|
||||
persist=False: 盘中轮询, 只更新内存缓存
|
||||
"""
|
||||
if not self._repo:
|
||||
return
|
||||
|
||||
# 只读 enriched 内存缓存(线程安全, 避免和 quote_service 写盘竞态)
|
||||
enriched, enriched_date = self._repo.get_enriched_latest()
|
||||
if enriched.is_empty():
|
||||
return
|
||||
|
||||
# 筛涨跌停名单(用 fill_null 防止列缺失)
|
||||
syms_up: list[str] = []
|
||||
syms_down: list[str] = []
|
||||
if "signal_limit_up" in enriched.columns:
|
||||
syms_up = enriched.filter(
|
||||
pl.col("signal_limit_up").fill_null(False)
|
||||
)["symbol"].to_list()
|
||||
if "signal_limit_down" in enriched.columns:
|
||||
syms_down = enriched.filter(
|
||||
pl.col("signal_limit_down").fill_null(False)
|
||||
)["symbol"].to_list()
|
||||
|
||||
all_syms = list(dict.fromkeys(syms_up + syms_down)) # 去重保序
|
||||
if not all_syms:
|
||||
logger.debug("depth sealed: 当日无涨跌停股, 跳过")
|
||||
return
|
||||
|
||||
# 拉 depth(涨跌停一次拉, 按 capset batch 切片)
|
||||
depth_data = self._call_depth_batch(all_syms)
|
||||
if not depth_data:
|
||||
logger.warning("depth sealed: depth.batch 返回空")
|
||||
return
|
||||
|
||||
up_set = set(syms_up)
|
||||
down_set = set(syms_down)
|
||||
now_perf = time.perf_counter()
|
||||
now_wall = time.time()
|
||||
|
||||
new_cache: dict[str, dict] = {}
|
||||
for sym, d in depth_data.items():
|
||||
ask_vols = d.get("ask_volumes") or []
|
||||
bid_vols = d.get("bid_volumes") or []
|
||||
ask1 = ask_vols[0] if ask_vols else None
|
||||
bid1 = bid_vols[0] if bid_vols else None
|
||||
# depth 返回的 timestamp(毫秒 epoch), 回退到当前 wall-clock
|
||||
depth_ts = d.get("timestamp")
|
||||
fetched = (depth_ts / 1000.0) if isinstance(depth_ts, (int, float)) and depth_ts else now_wall
|
||||
entry = {
|
||||
# 涨停真封: 涨停价上卖一(主动卖压)为 0
|
||||
"sealed_up": (ask1 == 0) if sym in up_set and ask1 is not None else None,
|
||||
# 跌停真封: 跌停价上买一为 0
|
||||
"sealed_down": (bid1 == 0) if sym in down_set and bid1 is not None else None,
|
||||
"ask1_vol": ask1,
|
||||
"bid1_vol": bid1,
|
||||
"status": "limit_down" if sym in down_set and sym not in up_set else "limit_up",
|
||||
"fetched_ts": fetched,
|
||||
}
|
||||
new_cache[sym] = entry
|
||||
|
||||
with self._lock:
|
||||
self._sealed_cache = new_cache
|
||||
self._sealed_ready = True
|
||||
self._sealed_date = enriched_date # 记录数据对应的交易日(可能是昨天,如休市)
|
||||
self._sealed_fetched_ts = now_perf
|
||||
self._sealed_fetched_at = now_wall
|
||||
|
||||
logger.info("depth sealed: 拉取 %d 只 (涨停%d/跌停%d) 日期=%s%s",
|
||||
len(new_cache), len(syms_up), len(syms_down),
|
||||
enriched_date, " → 落盘" if persist else "")
|
||||
|
||||
# 缓存已更新: 通知 SSE 推 depth_updated, 触发连板梯队刷新封单数据。
|
||||
self._notify_depth_updated(len(new_cache))
|
||||
|
||||
if persist and enriched_date:
|
||||
self._persist(enriched_date)
|
||||
|
||||
def _call_depth_batch(self, symbols: list[str]) -> dict:
|
||||
"""调 tf.depth.batch, 按 capset 的 batch 切片 + 节流。返回 {symbol: MarketDepth}。"""
|
||||
from app.tickflow.client import get_client
|
||||
tf = get_client()
|
||||
|
||||
capset = self._get_capset()
|
||||
lim = capset.limits(__import__("app.tickflow.capabilities", fromlist=["Cap"]).Cap.DEPTH5_BATCH)
|
||||
batch_size = (lim.batch if lim and lim.batch else 100)
|
||||
rpm = (lim.rpm if lim and lim.rpm else 30)
|
||||
# 批间隔 = 60/rpm(匀速)
|
||||
inter_batch = 60.0 / rpm if rpm > 0 else 2.0
|
||||
|
||||
result: dict = {}
|
||||
chunks = [symbols[i:i + batch_size] for i in range(0, len(symbols), batch_size)]
|
||||
for i, chunk in enumerate(chunks):
|
||||
if i > 0:
|
||||
time.sleep(inter_batch)
|
||||
try:
|
||||
# SDK 的 batch 内部已按 batch_size 切, 这里再切一层防单请求过大
|
||||
data = tf.depth.batch(chunk)
|
||||
if isinstance(data, dict):
|
||||
result.update(data)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("depth.batch 第 %d 批失败(%d 只): %s", i + 1, len(chunk), e)
|
||||
# 单批失败不影响其他批
|
||||
return result
|
||||
|
||||
def finalize(self) -> None:
|
||||
"""盘后定版: 拉一次 + 落盘。"""
|
||||
if not self._has_capability():
|
||||
return
|
||||
self._fetch_and_seal(persist=True)
|
||||
|
||||
# ================================================================
|
||||
# 落盘
|
||||
# ================================================================
|
||||
|
||||
def _persist(self, today: date) -> None:
|
||||
"""把内存缓存写 depth5/date=今天/part.parquet。"""
|
||||
with self._lock:
|
||||
cache = dict(self._sealed_cache)
|
||||
if not cache:
|
||||
return
|
||||
|
||||
rows = []
|
||||
for sym, e in cache.items():
|
||||
rows.append({
|
||||
"symbol": sym,
|
||||
"sealed_up": e.get("sealed_up"),
|
||||
"sealed_down": e.get("sealed_down"),
|
||||
"ask1_vol": e.get("ask1_vol"),
|
||||
"bid1_vol": e.get("bid1_vol"),
|
||||
"status": e.get("status"),
|
||||
"fetched_at": e.get("fetched_ts"),
|
||||
})
|
||||
# 显式 schema: sealed_up/sealed_down 是 bool 与 None 混合, 不指定 schema
|
||||
# polars 会按首行推断类型, 后续遇到不一致 (bool vs null) 报
|
||||
# "could not append value: false of type: bool to the builder"。
|
||||
df = pl.DataFrame(rows, schema={
|
||||
"symbol": pl.Utf8,
|
||||
"sealed_up": pl.Boolean,
|
||||
"sealed_down": pl.Boolean,
|
||||
"ask1_vol": pl.Int64,
|
||||
"bid1_vol": pl.Int64,
|
||||
"status": pl.Utf8,
|
||||
"fetched_at": pl.Float64,
|
||||
})
|
||||
ds = today.isoformat()
|
||||
out = self._repo.store.data_dir / "depth5" / f"date={ds}" / "part.parquet"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
df.write_parquet(out)
|
||||
self._persisted_date = today
|
||||
logger.info("depth sealed 落盘: %d 行 → %s", df.height, out)
|
||||
|
||||
def _persisted_for_date(self, d: date) -> bool:
|
||||
"""检查某日 depth5 文件是否已存在。"""
|
||||
if not self._repo:
|
||||
return False
|
||||
out = self._repo.store.data_dir / "depth5" / f"date={d.isoformat()}" / "part.parquet"
|
||||
return out.exists()
|
||||
|
||||
# ================================================================
|
||||
# 查询(供 limit_ladder API 用)
|
||||
# ================================================================
|
||||
|
||||
def get_sealed_map(self, target_date: date, is_down: bool) -> dict:
|
||||
"""返回 {symbol: {sealed, vol, ready, age}} 供 JOIN。
|
||||
|
||||
优先内存缓存(盘中), 回退 parquet(历史/盘后)。
|
||||
sealed: bool | None (None=待确认或降级)
|
||||
vol: 封单量(int) | None
|
||||
ready: sealed 数据是否就绪(False→降级标识)
|
||||
age: 距上次拉取秒数(盘后定版为 None)
|
||||
"""
|
||||
# 内存缓存(sealed 数据对应的交易日 = target_date 时才用)
|
||||
if self._sealed_date and target_date == self._sealed_date and self._sealed_ready and self._sealed_cache:
|
||||
return self._read_from_memory(is_down)
|
||||
# parquet(历史或盘后定版)
|
||||
return self._read_from_parquet(target_date, is_down)
|
||||
|
||||
def _read_from_memory(self, is_down: bool) -> dict:
|
||||
sealed_key = "sealed_down" if is_down else "sealed_up"
|
||||
# 封单量: 涨停=买一量(涨停价买单堆积), 跌停=卖一量(跌停价卖单堆积)
|
||||
vol_key = "ask1_vol" if is_down else "bid1_vol"
|
||||
now = time.perf_counter()
|
||||
with self._lock:
|
||||
cache = dict(self._sealed_cache)
|
||||
fetched_ts = self._sealed_fetched_ts
|
||||
age = (now - fetched_ts) if fetched_ts else 0.0
|
||||
result = {}
|
||||
for sym, e in cache.items():
|
||||
result[sym] = {
|
||||
"sealed": e.get(sealed_key),
|
||||
"vol": e.get(vol_key),
|
||||
"ready": True,
|
||||
"age": age,
|
||||
}
|
||||
return result
|
||||
|
||||
def _read_from_parquet(self, target_date: date, is_down: bool) -> dict:
|
||||
if not self._repo:
|
||||
return {}
|
||||
out = self._repo.store.data_dir / "depth5" / f"date={target_date.isoformat()}" / "part.parquet"
|
||||
if not out.exists():
|
||||
return {}
|
||||
try:
|
||||
df = pl.read_parquet(out)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("depth5 parquet 读取失败: %s", e)
|
||||
return {}
|
||||
sealed_key = "sealed_down" if is_down else "sealed_up"
|
||||
# 封单量: 涨停=买一量, 跌停=卖一量
|
||||
vol_key = "ask1_vol" if is_down else "bid1_vol"
|
||||
result = {}
|
||||
for row in df.to_dicts():
|
||||
sym = row.get("symbol")
|
||||
if not sym:
|
||||
continue
|
||||
result[sym] = {
|
||||
"sealed": row.get(sealed_key),
|
||||
"vol": row.get(vol_key),
|
||||
"ready": True,
|
||||
"age": None, # 盘后定版, 无 age
|
||||
}
|
||||
return result
|
||||
|
||||
def is_sealed_ready(self, target_date: date) -> bool:
|
||||
"""sealed 数据是否就绪(供前端降级判定)。"""
|
||||
# 内存缓存对应的数据日 == 查询日 → 看内存就绪状态
|
||||
if self._sealed_date and target_date == self._sealed_date:
|
||||
return self._sealed_ready
|
||||
# 其他日期: 有 parquet 就 ready
|
||||
return self._persisted_for_date(target_date)
|
||||
|
||||
def get_sealed_age(self, target_date: date) -> float | None:
|
||||
"""返回 sealed 数据 age(秒), 盘后定版为 None。"""
|
||||
if self._sealed_date and target_date == self._sealed_date and self._sealed_ready and self._sealed_fetched_ts:
|
||||
return time.perf_counter() - self._sealed_fetched_ts
|
||||
return None
|
||||
|
||||
# ================================================================
|
||||
# 盘中轮询线程
|
||||
# ================================================================
|
||||
|
||||
def _poll_loop(self) -> None:
|
||||
"""盘中轮询: 按 capset 自适应间隔拉 depth, 更新内存缓存。"""
|
||||
while self._running:
|
||||
try:
|
||||
if self._is_trading_hours():
|
||||
self._poll_once()
|
||||
else:
|
||||
logger.debug("depth sealed: 非交易时段, 跳过")
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("depth sealed 轮询异常: %s", e)
|
||||
|
||||
# 等待下一轮(用 _running 检查保证能及时退出)
|
||||
interval = self._current_sleep_interval()
|
||||
waited = 0.0
|
||||
while self._running and waited < interval:
|
||||
time.sleep(0.5)
|
||||
waited += 0.5
|
||||
|
||||
def _poll_once(self) -> None:
|
||||
"""单次轮询: 算间隔(三层防护) → 拉取 → 检测系统接管通知。"""
|
||||
# 数当前涨跌停股
|
||||
n = self._count_limit_stocks()
|
||||
if n == 0:
|
||||
return
|
||||
|
||||
interval, taken_over, user_interval = self._compute_interval(n)
|
||||
|
||||
# 系统接管通知(状态切换时才推, 防刷屏)
|
||||
if taken_over and (self._last_taken_over is False or self._last_user_interval != user_interval):
|
||||
self._notify_takeover(n, user_interval, interval)
|
||||
self._last_taken_over = taken_over
|
||||
self._last_user_interval = user_interval
|
||||
|
||||
self._fetch_and_seal(persist=False)
|
||||
|
||||
def _current_sleep_interval(self) -> float:
|
||||
"""计算当前 sleep 间隔(供 _poll_loop 等待用)。"""
|
||||
n = self._count_limit_stocks()
|
||||
if n == 0:
|
||||
return 30.0 # 无涨跌停, 慢轮询
|
||||
interval, _, _ = self._compute_interval(n)
|
||||
return interval
|
||||
|
||||
# ================================================================
|
||||
# 三层防护节流
|
||||
# ================================================================
|
||||
|
||||
def _compute_interval(self, n_symbols: int) -> tuple[float, bool, float]:
|
||||
"""三层防护计算实际轮询间隔。
|
||||
|
||||
返回 (actual_interval, taken_over, user_interval)
|
||||
- actual_interval: 实际使用的间隔(秒)
|
||||
- taken_over: 是否被系统接管(用户设置会超限)
|
||||
- user_interval: 用户设置(经套餐 clamp 后)的间隔
|
||||
"""
|
||||
from app.services import preferences
|
||||
from app.tickflow.policy import tier_label
|
||||
|
||||
capset = self._get_capset()
|
||||
lim = capset.limits(__import__("app.tickflow.capabilities", fromlist=["Cap"]).Cap.DEPTH5_BATCH)
|
||||
batch_size = (lim.batch if lim and lim.batch else 100)
|
||||
rpm = (lim.rpm if lim and lim.rpm else 30)
|
||||
|
||||
# ① 套餐范围 clamp
|
||||
tier = tier_label().split()[0].split("+")[0].strip().lower()
|
||||
lo, hi = TIER_INTERVAL_RANGE.get(tier, DEFAULT_RANGE)
|
||||
raw_user = preferences.get_depth_polling_interval()
|
||||
user_interval = max(lo, min(hi, raw_user))
|
||||
|
||||
# ② 限速安全 clamp
|
||||
batches = max(1, math.ceil(n_symbols / batch_size))
|
||||
usable_rpm = rpm * RPM_MARGIN
|
||||
calls_per_min = usable_rpm / batches if batches > 0 else usable_rpm
|
||||
safe_interval = 60.0 / calls_per_min if calls_per_min > 0 else INTERVAL_HARD_MAX
|
||||
|
||||
# 实际: 取用户设置和安全的较大值
|
||||
actual = max(user_interval, safe_interval)
|
||||
# 硬上下限
|
||||
actual = max(INTERVAL_HARD_MIN, min(actual, INTERVAL_HARD_MAX))
|
||||
taken_over = safe_interval > user_interval
|
||||
|
||||
return actual, taken_over, user_interval
|
||||
|
||||
def _count_limit_stocks(self) -> int:
|
||||
"""数当前涨跌停股总数(供节流计算)。"""
|
||||
if not self._repo:
|
||||
return 0
|
||||
enriched, _ = self._repo.get_enriched_latest()
|
||||
if enriched.is_empty():
|
||||
return 0
|
||||
n = 0
|
||||
if "signal_limit_up" in enriched.columns:
|
||||
n += enriched.filter(pl.col("signal_limit_up").fill_null(False)).height
|
||||
if "signal_limit_down" in enriched.columns:
|
||||
n += enriched.filter(pl.col("signal_limit_down").fill_null(False)).height
|
||||
return n
|
||||
|
||||
# ================================================================
|
||||
# 通知
|
||||
# ================================================================
|
||||
|
||||
def _notify_takeover(self, n_stocks: int, user_interval: float, actual_interval: float) -> None:
|
||||
"""系统接管通知: 复用 quote_service 的 _pending_alerts 通道。"""
|
||||
if not self._app_state:
|
||||
return
|
||||
qs = getattr(self._app_state, "quote_service", None)
|
||||
if not qs:
|
||||
return
|
||||
msg = (f"五档轮询: 当前涨跌停 {n_stocks} 只, 您设置的 {user_interval:.0f} 秒间隔会超限, "
|
||||
f"系统已自动调整为 {actual_interval:.0f} 秒")
|
||||
alert = {
|
||||
"source": "depth",
|
||||
"type": "takeover",
|
||||
"message": msg,
|
||||
}
|
||||
try:
|
||||
with qs._lock:
|
||||
qs._pending_alerts.append(alert)
|
||||
qs._alert_event.set()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("depth 接管通知推送失败: %s", e)
|
||||
|
||||
def _notify_depth_updated(self, count: int) -> None:
|
||||
"""修正完成通知: set quote_service._depth_update_event, SSE 推 depth_updated 刷新连板梯队。"""
|
||||
if not self._app_state:
|
||||
return
|
||||
qs = getattr(self._app_state, "quote_service", None)
|
||||
if not qs:
|
||||
return
|
||||
try:
|
||||
qs.notify_depth_updated()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("depth 更新通知推送失败: %s", e)
|
||||
|
||||
# ================================================================
|
||||
# 工具
|
||||
# ================================================================
|
||||
|
||||
def _has_capability(self) -> bool:
|
||||
capset = self._get_capset()
|
||||
from app.tickflow.capabilities import Cap
|
||||
return capset.has(Cap.DEPTH5_BATCH)
|
||||
|
||||
def _get_capset(self):
|
||||
"""获取当前 capset(优先 app.state, 回退 detect)。"""
|
||||
if self._app_state:
|
||||
cs = getattr(self._app_state, "capabilities", None)
|
||||
if cs:
|
||||
return cs
|
||||
from app.tickflow.policy import detect_capabilities
|
||||
return detect_capabilities()
|
||||
|
||||
@staticmethod
|
||||
def _is_trading_hours() -> bool:
|
||||
now = datetime.now()
|
||||
t = now.time()
|
||||
morning = dt_time(9, 25) <= t <= dt_time(11, 35)
|
||||
afternoon = dt_time(12, 55) <= t <= dt_time(15, 5)
|
||||
return now.weekday() < 5 and (morning or afternoon)
|
||||
@@ -0,0 +1,521 @@
|
||||
"""扩展数据服务 — 配置管理 + 文件解析 + Parquet 存储。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import polars as pl
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 配置模型
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class ExtField:
|
||||
"""扩展字段定义。"""
|
||||
__slots__ = ("name", "dtype", "label")
|
||||
|
||||
def __init__(self, name: str, dtype: str = "string", label: str = "") -> None:
|
||||
self.name = name
|
||||
self.dtype = dtype # string | int | float | bool
|
||||
self.label = label or name
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"name": self.name, "dtype": self.dtype, "label": self.label}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, d: dict) -> ExtField:
|
||||
return cls(d["name"], d.get("dtype", "string"), d.get("label", ""))
|
||||
|
||||
|
||||
class PullConfig:
|
||||
"""定时拉取配置。"""
|
||||
__slots__ = (
|
||||
"url", "method", "headers", "body", "response_path",
|
||||
"field_map", "schedule_minutes", "enabled",
|
||||
"last_run", "last_status", "last_message", "last_rows",
|
||||
"next_run",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
url: str = "",
|
||||
method: str = "GET",
|
||||
headers: dict[str, str] | None = None,
|
||||
body: str | None = None,
|
||||
response_path: str = "",
|
||||
field_map: dict[str, str] | None = None,
|
||||
schedule_minutes: int = 1440,
|
||||
enabled: bool = False,
|
||||
last_run: str | None = None,
|
||||
last_status: str | None = None,
|
||||
last_message: str | None = None,
|
||||
last_rows: int | None = None,
|
||||
next_run: str | None = None,
|
||||
) -> None:
|
||||
self.url = url
|
||||
self.method = method # GET | POST
|
||||
self.headers = headers or {}
|
||||
self.body = body # JSON string (POST body template)
|
||||
self.response_path = response_path # dot-path to rows array, e.g. "data.list"
|
||||
self.field_map = field_map or {} # external_name → config_field_name
|
||||
self.schedule_minutes = schedule_minutes
|
||||
self.enabled = enabled
|
||||
self.last_run = last_run
|
||||
self.last_status = last_status # "success" | "error"
|
||||
self.last_message = last_message
|
||||
self.last_rows = last_rows
|
||||
self.next_run = next_run # 下次预计运行 (ISO, 调度器写入)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"url": self.url,
|
||||
"method": self.method,
|
||||
"headers": self.headers,
|
||||
"body": self.body,
|
||||
"response_path": self.response_path,
|
||||
"field_map": self.field_map,
|
||||
"schedule_minutes": self.schedule_minutes,
|
||||
"enabled": self.enabled,
|
||||
"last_run": self.last_run,
|
||||
"last_status": self.last_status,
|
||||
"last_message": self.last_message,
|
||||
"last_rows": self.last_rows,
|
||||
"next_run": self.next_run,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, d: dict) -> PullConfig:
|
||||
if not d:
|
||||
return cls()
|
||||
return cls(
|
||||
url=d.get("url", ""),
|
||||
method=d.get("method", "GET"),
|
||||
headers=d.get("headers"),
|
||||
body=d.get("body"),
|
||||
response_path=d.get("response_path", ""),
|
||||
field_map=d.get("field_map"),
|
||||
schedule_minutes=d.get("schedule_minutes", 1440),
|
||||
enabled=d.get("enabled", False),
|
||||
last_run=d.get("last_run"),
|
||||
last_status=d.get("last_status"),
|
||||
last_message=d.get("last_message"),
|
||||
last_rows=d.get("last_rows"),
|
||||
next_run=d.get("next_run"),
|
||||
)
|
||||
|
||||
|
||||
class ExtConfig:
|
||||
"""一个扩展数据源的完整配置。"""
|
||||
__slots__ = (
|
||||
"id", "label", "mode", "fields", "description",
|
||||
"symbol_map", "code_map",
|
||||
"created_at", "updated_at", "pull",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
id: str,
|
||||
label: str,
|
||||
mode: Literal["snapshot", "timeseries"],
|
||||
fields: list[ExtField],
|
||||
description: str = "",
|
||||
symbol_map: dict | None = None,
|
||||
code_map: dict | None = None,
|
||||
created_at: str | None = None,
|
||||
updated_at: str | None = None,
|
||||
pull: PullConfig | None = None,
|
||||
) -> None:
|
||||
self.id = id
|
||||
self.label = label
|
||||
self.mode = mode
|
||||
self.fields = fields
|
||||
self.description = description
|
||||
# 映射关系: {"type": "mapped", "col": "原始列名"} 或 {"type": "computed", "from": "symbol|code", "method": "strip_exchange|append_exchange"}
|
||||
self.symbol_map = symbol_map or {}
|
||||
self.code_map = code_map or {}
|
||||
self.created_at = created_at or datetime.now().isoformat()
|
||||
self.updated_at = updated_at or datetime.now().isoformat()
|
||||
self.pull = pull
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
d = {
|
||||
"id": self.id,
|
||||
"label": self.label,
|
||||
"mode": self.mode,
|
||||
"fields": [f.to_dict() for f in self.fields],
|
||||
"description": self.description,
|
||||
"symbol_map": self.symbol_map,
|
||||
"code_map": self.code_map,
|
||||
"created_at": self.created_at,
|
||||
"updated_at": self.updated_at,
|
||||
}
|
||||
if self.pull:
|
||||
d["pull"] = self.pull.to_dict()
|
||||
return d
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, d: dict) -> ExtConfig:
|
||||
return cls(
|
||||
id=d["id"],
|
||||
label=d["label"],
|
||||
mode=d["mode"],
|
||||
fields=[ExtField.from_dict(f) for f in d.get("fields", [])],
|
||||
description=d.get("description", ""),
|
||||
symbol_map=d.get("symbol_map"),
|
||||
code_map=d.get("code_map"),
|
||||
created_at=d.get("created_at"),
|
||||
updated_at=d.get("updated_at"),
|
||||
pull=PullConfig.from_dict(d["pull"]) if d.get("pull") else None,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 配置持久化
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class ExtConfigStore:
|
||||
"""扩展数据配置文件读写 — 每个表独立目录 data/ext/{config_id}/config.json。"""
|
||||
|
||||
def __init__(self, data_dir: Path) -> None:
|
||||
self._base = data_dir / "ext_data"
|
||||
|
||||
def _config_path(self, config_id: str) -> Path:
|
||||
return self._base / config_id / "config.json"
|
||||
|
||||
def load_all(self) -> list[ExtConfig]:
|
||||
# 兼容旧版: 如果目录为空且旧配置文件存在则迁移
|
||||
if not self._base.exists() or not any(self._base.iterdir()):
|
||||
old = self._base.parent / "ext_configs.json"
|
||||
if not old.exists():
|
||||
old = self._base.parent / "ext_configs.json.bak"
|
||||
if old.exists():
|
||||
self._migrate_legacy(old)
|
||||
if not self._base.exists():
|
||||
return []
|
||||
configs = []
|
||||
for d in sorted(self._base.iterdir()):
|
||||
cp = d / "config.json"
|
||||
if d.is_dir() and cp.exists():
|
||||
try:
|
||||
raw = json.loads(cp.read_text(encoding="utf-8"))
|
||||
configs.append(ExtConfig.from_dict(raw))
|
||||
except Exception as e:
|
||||
logger.warning("扩展表配置解析失败 %s: %s", cp, e)
|
||||
return configs
|
||||
|
||||
def get(self, config_id: str) -> ExtConfig | None:
|
||||
cp = self._config_path(config_id)
|
||||
if not cp.exists():
|
||||
return None
|
||||
try:
|
||||
raw = json.loads(cp.read_text(encoding="utf-8"))
|
||||
return ExtConfig.from_dict(raw)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def upsert(self, config: ExtConfig) -> None:
|
||||
config.updated_at = datetime.now().isoformat()
|
||||
cp = self._config_path(config.id)
|
||||
cp.parent.mkdir(parents=True, exist_ok=True)
|
||||
cp.write_text(
|
||||
json.dumps(config.to_dict(), ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
def delete(self, config_id: str) -> bool:
|
||||
import shutil
|
||||
cp = self._config_path(config_id)
|
||||
if not cp.exists():
|
||||
return False
|
||||
shutil.rmtree(cp.parent, ignore_errors=True)
|
||||
return True
|
||||
|
||||
def _migrate_legacy(self, old_path: Path) -> None:
|
||||
"""一次性迁移旧版 ext_configs.json 到独立目录结构。"""
|
||||
try:
|
||||
raw = json.loads(old_path.read_text(encoding="utf-8"))
|
||||
configs = [ExtConfig.from_dict(d) for d in raw]
|
||||
for c in configs:
|
||||
cp = self._config_path(c.id)
|
||||
cp.parent.mkdir(parents=True, exist_ok=True)
|
||||
cp.write_text(
|
||||
json.dumps(c.to_dict(), ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
# 迁移完成后重命名旧文件作为备份
|
||||
backup = old_path.with_suffix(".json.bak")
|
||||
old_path.rename(backup)
|
||||
logger.info("ext_configs.json 已迁移至 ext/ (备份: %s)", backup.name)
|
||||
except Exception as e:
|
||||
logger.warning("ext_configs 迁移失败: %s", e)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CSV / Excel 解析 → Parquet 写入
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_POLARS_DTYPE_MAP = {
|
||||
"string": pl.Utf8,
|
||||
"int": pl.Int64,
|
||||
"float": pl.Float64,
|
||||
"bool": pl.Boolean,
|
||||
}
|
||||
|
||||
|
||||
def build_code_lookup(data_dir: Path) -> dict[str, str]:
|
||||
"""从 instruments 维表构建 code → symbol 映射。"""
|
||||
path = data_dir / "instruments" / "instruments.parquet"
|
||||
if not path.exists():
|
||||
return {}
|
||||
try:
|
||||
df = pl.read_parquet(path, columns=["code", "symbol"])
|
||||
return dict(zip(df["code"].to_list(), df["symbol"].to_list()))
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def normalize_symbol(series: pl.Series, lookup: dict[str, str] | None = None) -> pl.Series:
|
||||
"""将 symbol 列标准化为 代码.交易所 格式。
|
||||
|
||||
优先使用 instruments 维表查找 code → symbol,确保 100% 准确。
|
||||
查不到时按规则兜底:6开头 → .SH,其余 → .SZ。
|
||||
"""
|
||||
_lookup = lookup or {}
|
||||
|
||||
def _fix_one(val: str) -> str:
|
||||
if not val:
|
||||
return val
|
||||
val = val.strip()
|
||||
# 已经是标准格式(含 .),直接返回
|
||||
if "." in val:
|
||||
return val
|
||||
# 纯6位数字代码 → 优先查维表
|
||||
if len(val) == 6 and val.isdigit():
|
||||
mapped = _lookup.get(val)
|
||||
if mapped:
|
||||
return mapped
|
||||
# 兜底规则
|
||||
if val.startswith(("6",)):
|
||||
return f"{val}.SH"
|
||||
else:
|
||||
return f"{val}.SZ"
|
||||
return val
|
||||
|
||||
return series.map_elements(_fix_one, return_dtype=pl.Utf8)
|
||||
|
||||
|
||||
def ensure_utf8_csv(file_path: Path) -> Path:
|
||||
"""确保 CSV 文件以 UTF-8 编码可读,非 UTF-8(如 GBK/GB18030)则转换。
|
||||
|
||||
国内行情软件(同花顺/东财/通达信)和 Windows 中文 Excel 导出的 CSV 多为
|
||||
GBK 系编码,Polars 的 read_csv 默认按 UTF-8 解析会抛 "invalid utf-8 sequence"。
|
||||
这里在交给 Polars 前做一次编码规范化。
|
||||
|
||||
返回值:若已是 UTF-8 则返回原路径;否则在同目录写一个 *.utf8 文件并返回它
|
||||
(调用方用临时目录,随目录一起清理)。
|
||||
"""
|
||||
raw = file_path.read_bytes()
|
||||
# BOM 处理:UTF-8-SIG 等带 BOM 文件直接交给 Polars(它认识 BOM)
|
||||
try:
|
||||
raw.decode("utf-8")
|
||||
return file_path # 已是合法 UTF-8
|
||||
except UnicodeDecodeError:
|
||||
pass
|
||||
# 依次尝试常见中文编码,第一个能完整解码的即为命中
|
||||
for enc in ("gb18030", "gbk", "gb2312", "big5"):
|
||||
try:
|
||||
text = raw.decode(enc)
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
out_path = file_path.with_suffix(file_path.suffix + ".utf8")
|
||||
out_path.write_text(text, encoding="utf-8")
|
||||
logger.info("CSV 编码转换 %s → %s (%s)", file_path.name, out_path.name, enc)
|
||||
return out_path
|
||||
# 都无法解码:返回原路径,让 Polars 抛出更精确的原始错误
|
||||
return file_path
|
||||
|
||||
|
||||
def parse_upload_file(file_path: Path, symbol_col: str = "symbol", data_dir: Path | None = None) -> pl.DataFrame:
|
||||
"""解析上传的 CSV / Excel 文件为 Polars DataFrame。"""
|
||||
suffix = file_path.suffix.lower()
|
||||
if suffix == ".csv":
|
||||
df = pl.read_csv(ensure_utf8_csv(file_path), infer_schema_length=10000)
|
||||
elif suffix in (".xlsx", ".xls"):
|
||||
df = pl.read_excel(file_path)
|
||||
else:
|
||||
raise ValueError(f"不支持的文件格式: {suffix}")
|
||||
|
||||
if symbol_col not in df.columns:
|
||||
# 尝试模糊匹配
|
||||
candidates = [c for c in df.columns if c.lower() in ("symbol", "code", "代码", "标的")]
|
||||
if candidates:
|
||||
df = df.rename({candidates[0]: symbol_col})
|
||||
else:
|
||||
raise ValueError(f"未找到标的代码列 (symbol),可选列: {df.columns}")
|
||||
|
||||
# 确保 symbol 列为字符串并标准化
|
||||
lookup = build_code_lookup(data_dir) if data_dir else None
|
||||
df = df.with_columns(normalize_symbol(df[symbol_col].cast(pl.Utf8), lookup))
|
||||
return df
|
||||
|
||||
|
||||
def cast_df_to_schema(df: pl.DataFrame, fields: list[ExtField]) -> pl.DataFrame:
|
||||
"""按配置的字段类型转换 DataFrame 列类型。"""
|
||||
for f in fields:
|
||||
if f.name in df.columns:
|
||||
target = _POLARS_DTYPE_MAP.get(f.dtype, pl.Utf8)
|
||||
df = df.with_columns(pl.col(f.name).cast(target))
|
||||
return df
|
||||
|
||||
|
||||
def _config_dir(config_id: str, data_dir: Path) -> Path:
|
||||
"""返回扩展配置的根目录 data/ext_data/{config_id}/。"""
|
||||
return data_dir / "ext_data" / config_id
|
||||
|
||||
|
||||
def write_ext_parquet(
|
||||
df: pl.DataFrame,
|
||||
config: ExtConfig,
|
||||
data_dir: Path,
|
||||
snapshot_date: date | None = None,
|
||||
) -> int:
|
||||
"""将 DataFrame 写入扩展数据 Parquet。
|
||||
|
||||
目录结构:
|
||||
- snapshot: data/ext_data/{id}/part.parquet(与 config.json 同级,覆盖写)
|
||||
- timeseries: data/ext_data/{id}/timeseries/date=xxx/part.parquet(按日分区)
|
||||
|
||||
Returns:
|
||||
写入行数。
|
||||
"""
|
||||
snap = snapshot_date or date.today()
|
||||
cfg_dir = _config_dir(config.id, data_dir)
|
||||
|
||||
# 标准化 symbol 列: 用维表查找 → 准确匹配交易所
|
||||
if "symbol" in df.columns:
|
||||
lookup = build_code_lookup(data_dir)
|
||||
df = df.with_columns(normalize_symbol(df["symbol"], lookup))
|
||||
|
||||
if config.mode == "snapshot":
|
||||
# 快照: 与 config.json 同级,直接覆盖
|
||||
cfg_dir.mkdir(parents=True, exist_ok=True)
|
||||
out_path = cfg_dir / "part.parquet"
|
||||
|
||||
# 如果已有文件,合并去重后覆盖
|
||||
if out_path.exists():
|
||||
try:
|
||||
existing = pl.read_parquet(out_path)
|
||||
key = "symbol" if "symbol" in df.columns else df.columns[0]
|
||||
df = pl.concat([existing, df]).unique(subset=[key], keep="last")
|
||||
except Exception as e:
|
||||
# schema 不一致 (列不同) 时 concat 失败 → 直接用新 df 覆盖。
|
||||
# 记日志而非静默吞掉, 便于排查"数据结构错乱"类问题。
|
||||
logger.warning("扩展表 %s 合并去重失败, 将覆盖写入: %s", config.id, e)
|
||||
else:
|
||||
# 时序: timeseries/ 下按日期分区
|
||||
out_dir = cfg_dir / "timeseries" / f"date={snap}"
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
out_path = out_dir / "part.parquet"
|
||||
|
||||
# 如果已有文件,合并去重
|
||||
if out_path.exists():
|
||||
try:
|
||||
existing = pl.read_parquet(out_path)
|
||||
key = "symbol" if "symbol" in df.columns else df.columns[0]
|
||||
df = pl.concat([existing, df]).unique(subset=[key], keep="last")
|
||||
except Exception as e:
|
||||
logger.warning("扩展表 %s 合并去重失败, 将覆盖写入: %s", config.id, e)
|
||||
|
||||
df = cast_df_to_schema(df, config.fields)
|
||||
df.write_parquet(out_path)
|
||||
logger.info("扩展表写入: %s → %s (%d 行)", config.id, out_path, len(df))
|
||||
return len(df)
|
||||
|
||||
|
||||
def delete_ext_parquet(config_id: str, data_dir: Path) -> None:
|
||||
"""删除扩展数据源关联的所有 Parquet 数据(保留 config.json)。
|
||||
|
||||
- snapshot: 删除 ext_data/{id}/part.parquet
|
||||
- timeseries: 删除 ext_data/{id}/timeseries/ 目录
|
||||
"""
|
||||
cfg_dir = _config_dir(config_id, data_dir)
|
||||
# 删除快照文件
|
||||
snap = cfg_dir / "part.parquet"
|
||||
if snap.exists():
|
||||
snap.unlink()
|
||||
# 删除时序目录
|
||||
ts_dir = cfg_dir / "timeseries"
|
||||
if ts_dir.exists():
|
||||
import shutil
|
||||
shutil.rmtree(ts_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def fix_symbol_format(config: ExtConfig, data_dir: Path) -> int:
|
||||
"""扫描该扩展配置的所有 Parquet 文件,将 symbol 列标准化为 代码.交易所 格式。
|
||||
|
||||
- snapshot: 扫描 ext_data/{id}/part.parquet
|
||||
- timeseries: 扫描 ext_data/{id}/timeseries/date=xxx/part.parquet
|
||||
|
||||
Returns:
|
||||
修复的文件数。
|
||||
"""
|
||||
cfg_dir = _config_dir(config.id, data_dir)
|
||||
if not cfg_dir.exists():
|
||||
return 0
|
||||
|
||||
# 收集需要扫描的 parquet 文件列表
|
||||
parquet_files: list[Path] = []
|
||||
if config.mode == "snapshot":
|
||||
p = cfg_dir / "part.parquet"
|
||||
if p.exists():
|
||||
parquet_files.append(p)
|
||||
else:
|
||||
ts_dir = cfg_dir / "timeseries"
|
||||
if ts_dir.exists():
|
||||
for part_dir in sorted(ts_dir.iterdir()):
|
||||
if not part_dir.is_dir() or not part_dir.name.startswith("date="):
|
||||
continue
|
||||
p = part_dir / "part.parquet"
|
||||
if p.exists():
|
||||
parquet_files.append(p)
|
||||
|
||||
fixed = 0
|
||||
lookup = build_code_lookup(data_dir)
|
||||
for parquet_path in parquet_files:
|
||||
try:
|
||||
df = pl.read_parquet(parquet_path)
|
||||
if "symbol" not in df.columns:
|
||||
continue
|
||||
old = df["symbol"].to_list()
|
||||
df = df.with_columns(normalize_symbol(df["symbol"], lookup))
|
||||
new = df["symbol"].to_list()
|
||||
if old != new:
|
||||
df.write_parquet(parquet_path)
|
||||
fixed += 1
|
||||
logger.info("代码格式修复: %s/%s (%d 行)", config.id, parquet_path.parent.name, len(df))
|
||||
except Exception as e:
|
||||
logger.warning("代码格式修复跳过 %s: %s", parquet_path, e)
|
||||
|
||||
return fixed
|
||||
|
||||
|
||||
def rows_to_parquet(
|
||||
rows: list[dict],
|
||||
config: ExtConfig,
|
||||
data_dir: Path,
|
||||
snapshot_date: date | None = None,
|
||||
) -> int:
|
||||
"""将 JSON 行列表转为 DataFrame 写入 Parquet,复用 write_ext_parquet 的存储逻辑。
|
||||
|
||||
Returns:
|
||||
写入行数。
|
||||
"""
|
||||
df = pl.DataFrame(rows)
|
||||
if "symbol" in df.columns:
|
||||
df = df.with_columns(pl.col("symbol").cast(pl.Utf8))
|
||||
return write_ext_parquet(df, config, data_dir, snapshot_date=snapshot_date)
|
||||
@@ -0,0 +1,236 @@
|
||||
"""内置扩展数据预设 — 概念/行业首次启动自动拉取。
|
||||
|
||||
设计原则:
|
||||
- 扩展数据通用逻辑零改动 (ExtConfig / fetch_and_ingest / API / 前端均不动)
|
||||
- 仅在本模块做「接口结构 → 本地 schema」的转换
|
||||
- 「已存在则跳过」: 绝不覆盖用户已有数据, 老用户零影响
|
||||
- 拉取失败只记 warning, 不阻断启动 (保持「没数据也能跑」)
|
||||
|
||||
种子数据来源: https://files.688798.xyz/ths/{concepts,industries}.json
|
||||
作者更新数据只需改接口上的 JSON, 用户下次拉取自动同步, 无需发版。
|
||||
|
||||
接入点: app.main.lifespan → ensure_builtin_presets(store.data_dir)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from app.services.ext_data import (
|
||||
ExtConfig,
|
||||
ExtConfigStore,
|
||||
ExtField,
|
||||
PullConfig,
|
||||
rows_to_parquet,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 种子数据源 (作者维护, 改这里即对所有用户生效)
|
||||
_THS_BASE = "https://files.688798.xyz/ths"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 预设定义: 字段结构 + 拉取配方
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _concept_preset() -> ExtConfig:
|
||||
"""扩展概念 (ext_gn_ths)。
|
||||
|
||||
接口结构: [{symbol, name, concepts: [概念1, 概念2, ...]}]
|
||||
本地 schema: 股票代码 / 股票简称 / 所属概念(分号拼接) / symbol / code
|
||||
"""
|
||||
return ExtConfig(
|
||||
id="ext_gn_ths",
|
||||
label="扩展概念",
|
||||
mode="snapshot",
|
||||
fields=[
|
||||
ExtField("symbol", "string", "标的代码"),
|
||||
ExtField("code", "string", "代码"),
|
||||
ExtField("股票代码", "string", "股票代码"),
|
||||
ExtField("股票简称", "string", "股票简称"),
|
||||
ExtField("所属概念", "string", "所属概念"),
|
||||
],
|
||||
description="同花顺概念分类 (首次启动自动拉取, 可在扩展数据页手动更新)",
|
||||
symbol_map={"type": "mapped", "col": "股票代码"},
|
||||
code_map={"type": "computed", "from": "symbol", "method": "strip_exchange"},
|
||||
pull=PullConfig(
|
||||
url=f"{_THS_BASE}/concepts.json",
|
||||
method="GET",
|
||||
schedule_minutes=1440,
|
||||
enabled=False,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _industry_preset() -> ExtConfig:
|
||||
"""扩展行业 (ext_hy_ths)。
|
||||
|
||||
接口结构: [{symbol, name, industries: [一级行业, 二级行业, 三级行业]}]
|
||||
本地 schema: 股票代码 / 股票简称 / 所属同花顺行业(横杠拼接) / symbol / code
|
||||
"""
|
||||
return ExtConfig(
|
||||
id="ext_hy_ths",
|
||||
label="扩展行业",
|
||||
mode="snapshot",
|
||||
fields=[
|
||||
ExtField("symbol", "string", "标的代码"),
|
||||
ExtField("code", "string", "代码"),
|
||||
ExtField("股票代码", "string", "股票代码"),
|
||||
ExtField("股票简称", "string", "股票简称"),
|
||||
ExtField("所属同花顺行业", "string", "所属同花顺行业"),
|
||||
],
|
||||
description="同花顺行业分类 (首次启动自动拉取, 可在扩展数据页手动更新)",
|
||||
symbol_map={"type": "mapped", "col": "股票代码"},
|
||||
code_map={"type": "computed", "from": "symbol", "method": "strip_exchange"},
|
||||
pull=PullConfig(
|
||||
url=f"{_THS_BASE}/industries.json",
|
||||
method="GET",
|
||||
schedule_minutes=1440,
|
||||
enabled=False,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _presets() -> list[ExtConfig]:
|
||||
return [_concept_preset(), _industry_preset()]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 接口结构 → 本地 schema 转换 (仅预设使用)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _symbol_to_code(symbol: str) -> str:
|
||||
"""symbol (000001.SZ) → code (000001)。"""
|
||||
return symbol.split(".", 1)[0] if "." in symbol else symbol
|
||||
|
||||
|
||||
def _flatten_concept_rows(raw_rows: list[dict]) -> list[dict]:
|
||||
"""概念: concepts 数组 → 分号拼接成「所属概念」字符串。
|
||||
|
||||
[{symbol, name, concepts:[...]}] → [{股票代码, 股票简称, 所属概念, symbol, code}]
|
||||
注: code 由 symbol 派生 (000001.SZ → 000001), 因 rows_to_parquet 不执行 code_map。
|
||||
"""
|
||||
out: list[dict] = []
|
||||
for r in raw_rows:
|
||||
sym = (r.get("symbol") or "").strip()
|
||||
if not sym:
|
||||
continue
|
||||
concepts = r.get("concepts") or []
|
||||
out.append({
|
||||
"股票代码": sym,
|
||||
"股票简称": r.get("name") or "",
|
||||
"所属概念": ";".join(str(c) for c in concepts if c),
|
||||
"symbol": sym,
|
||||
"code": _symbol_to_code(sym),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _flatten_industry_rows(raw_rows: list[dict]) -> list[dict]:
|
||||
"""行业: industries 数组 → 横杠拼接成「所属同花顺行业」字符串。
|
||||
|
||||
[{symbol, name, industries:[...]}] → [{股票代码, 股票简称, 所属同花顺行业, symbol, code}]
|
||||
"""
|
||||
out: list[dict] = []
|
||||
for r in raw_rows:
|
||||
sym = (r.get("symbol") or "").strip()
|
||||
if not sym:
|
||||
continue
|
||||
inds = r.get("industries") or []
|
||||
out.append({
|
||||
"股票代码": sym,
|
||||
"股票简称": r.get("name") or "",
|
||||
"所属同花顺行业": "-".join(str(i) for i in inds if i),
|
||||
"symbol": sym,
|
||||
"code": _symbol_to_code(sym),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 拉取执行 (复用 httpx, 不依赖 fetch_and_ingest 的 PullConfig 路径)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def _fetch_json(url: str) -> list[dict]:
|
||||
"""请求 JSON 接口, 返回行数组。超时 30s, 失败抛异常由调用方兜底。"""
|
||||
import httpx
|
||||
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
resp = await client.get(url)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
if not isinstance(data, list):
|
||||
raise ValueError(f"接口返回不是数组: {type(data)}")
|
||||
return data
|
||||
|
||||
|
||||
async def _seed_one(config: ExtConfig, flatten, data_dir: Path) -> int:
|
||||
"""拉取 + 转换 + 写入单个预设。返回写入行数。"""
|
||||
from datetime import date
|
||||
|
||||
raw = await _fetch_json(config.pull.url)
|
||||
rows = flatten(raw)
|
||||
if not rows:
|
||||
raise ValueError(f"接口返回 0 行: {config.pull.url}")
|
||||
n = rows_to_parquet(rows, config, data_dir, snapshot_date=date.today())
|
||||
return n
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 对外入口
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def get_preset(config_id: str) -> ExtConfig | None:
|
||||
"""按 id 取预设定义 (供 API 层校验 id 合法性)。"""
|
||||
for c in _presets():
|
||||
if c.id == config_id:
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
async def ensure_builtin_presets(data_dir: Path) -> None:
|
||||
"""启动时: 为缺失的预设创建 config.json (含 pull 配置), 但【不拉取数据】。
|
||||
|
||||
设计: 数据获取改为用户在概念/行业页手动点「获取数据」触发, 避免启动时
|
||||
网络请求阻塞, 也避免「自动拉取」与「用户自主控制」的预期冲突。
|
||||
|
||||
安全保证:
|
||||
- 已存在则完全跳过 (绝不覆盖用户数据)
|
||||
- 只写 config.json, 失败只记 warning 不阻断启动
|
||||
"""
|
||||
store = ExtConfigStore(data_dir)
|
||||
|
||||
for config in _presets():
|
||||
existing = store.get(config.id)
|
||||
if existing is not None:
|
||||
# 用户已有此表 (老用户 / 自己重建过) → 一律不动
|
||||
continue
|
||||
try:
|
||||
store.upsert(config)
|
||||
logger.info("内置扩展表 %s 配置已就绪 (待用户手动获取数据)", config.id)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("内置扩展表 %s 配置写入失败 (不影响启动): %s", config.id, e)
|
||||
|
||||
|
||||
async def fetch_preset(config_id: str, data_dir: Path) -> int:
|
||||
"""手动触发某个预设的数据拉取 (供 API 调用)。
|
||||
|
||||
Raises:
|
||||
ValueError: config_id 不是内置预设
|
||||
Exception: 网络请求/解析/写入失败 (由 API 层转 HTTP 错误)
|
||||
"""
|
||||
config = get_preset(config_id)
|
||||
if config is None:
|
||||
raise ValueError(f"未知的内置预设: {config_id}")
|
||||
|
||||
flatten = _flatten_concept_rows if config_id == "ext_gn_ths" else _flatten_industry_rows
|
||||
|
||||
# 确保 config.json 存在 (用户可能从未启动过 ensure_builtin_presets)
|
||||
store = ExtConfigStore(data_dir)
|
||||
if store.get(config_id) is None:
|
||||
store.upsert(config)
|
||||
|
||||
n = await _seed_one(config, flatten, data_dir)
|
||||
logger.info("内置扩展表 %s 手动拉取成功: %d 行", config_id, n)
|
||||
return n
|
||||
@@ -0,0 +1,339 @@
|
||||
"""扩展数据定时拉取引擎 — 从外部 API 拉取数据写入 Parquet。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
from datetime import date, datetime, timezone
|
||||
from functools import reduce
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from app.services.ext_data import (
|
||||
ExtConfig,
|
||||
ExtConfigStore,
|
||||
PullConfig,
|
||||
rows_to_parquet,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 响应解析
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _extract_rows(data: Any, path: str) -> list[dict]:
|
||||
"""按 dot-path 从 JSON 响应中提取行数组。
|
||||
|
||||
例: path="data.list" → response["data"]["list"]
|
||||
如果 path 为空,直接将 data 视为数组。
|
||||
"""
|
||||
if not path:
|
||||
if isinstance(data, list):
|
||||
return data
|
||||
raise ValueError("response_path 为空但响应不是数组")
|
||||
|
||||
keys = path.split(".")
|
||||
current = data
|
||||
for key in keys:
|
||||
if isinstance(current, dict):
|
||||
if key not in current:
|
||||
raise ValueError(f"响应中不存在路径 '{path}',缺失键 '{key}'")
|
||||
current = current[key]
|
||||
elif isinstance(current, list):
|
||||
try:
|
||||
current = current[int(key)]
|
||||
except (ValueError, IndexError) as e:
|
||||
raise ValueError(f"响应路径 '{path}' 解析失败: {e}") from e
|
||||
else:
|
||||
raise ValueError(f"响应路径 '{path}' 中间值不是 dict/list: {type(current)}")
|
||||
|
||||
if not isinstance(current, list):
|
||||
raise ValueError(f"路径 '{path}' 指向的不是数组,而是 {type(current)}")
|
||||
|
||||
return current
|
||||
|
||||
|
||||
def _apply_field_map(rows: list[dict], field_map: dict[str, str]) -> list[dict]:
|
||||
"""将外部字段名映射为内部配置字段名。field_map: {外部名: 内部名}。"""
|
||||
if not field_map:
|
||||
return rows
|
||||
mapped = []
|
||||
for row in rows:
|
||||
new_row: dict = {}
|
||||
for k, v in row.items():
|
||||
mapped_key = field_map.get(k, k)
|
||||
new_row[mapped_key] = v
|
||||
mapped.append(new_row)
|
||||
return mapped
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 拉取执行
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _apply_preset_flatten(config_id: str, rows: list[dict]) -> list[dict]:
|
||||
"""对内置预设 (概念/行业) 应用结构转换, 与 fetch_preset 保持一致。
|
||||
|
||||
延迟导入避免与 ext_presets 形成循环依赖。
|
||||
非预设 id 原样返回。
|
||||
"""
|
||||
if config_id not in ("ext_gn_ths", "ext_hy_ths"):
|
||||
return rows
|
||||
from app.services.ext_presets import _flatten_concept_rows, _flatten_industry_rows
|
||||
flatten = _flatten_concept_rows if config_id == "ext_gn_ths" else _flatten_industry_rows
|
||||
return flatten(rows)
|
||||
|
||||
|
||||
async def fetch_and_ingest(
|
||||
config: ExtConfig,
|
||||
data_dir,
|
||||
) -> tuple[int, str]:
|
||||
"""执行一次拉取: 请求外部 API → 解析响应 → 写入 Parquet。
|
||||
|
||||
Returns:
|
||||
(rows_written, date_str)
|
||||
"""
|
||||
pull = config.pull
|
||||
if not pull or not pull.url:
|
||||
raise ValueError("拉取未配置或 URL 为空")
|
||||
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
headers = pull.headers or {}
|
||||
kwargs: dict[str, Any] = {"headers": headers}
|
||||
|
||||
if pull.method.upper() == "POST" and pull.body:
|
||||
kwargs["content"] = pull.body
|
||||
if "content-type" not in {k.lower() for k in headers}:
|
||||
kwargs["headers"]["Content-Type"] = "application/json"
|
||||
|
||||
resp = await client.request(pull.method.upper(), pull.url, **kwargs)
|
||||
resp.raise_for_status()
|
||||
|
||||
# 解析 JSON
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
raise ValueError(f"响应不是有效 JSON: {e}") from e
|
||||
|
||||
# 提取行
|
||||
rows = _extract_rows(data, pull.response_path)
|
||||
if not rows:
|
||||
raise ValueError("提取到的行数为 0")
|
||||
|
||||
# 内置预设 (概念/行业): 应用结构转换, 让产出 schema 与分析页一致。
|
||||
# 否则 raw 接口列 (concepts/industries 数组、name) 会直接覆盖正确的 part.parquet,
|
||||
# 导致分析页因找不到维度字段 (所属概念/所属同花顺行业) 而"数据消失"。
|
||||
# 见 ext_presets._flatten_* —— 手动拉取 / 定时拉取都必须走同一套转换。
|
||||
rows = _apply_preset_flatten(config.id, rows)
|
||||
|
||||
# 字段映射
|
||||
rows = _apply_field_map(rows, pull.field_map)
|
||||
|
||||
# 校验 symbol 列
|
||||
if rows and "symbol" not in rows[0]:
|
||||
raise ValueError("数据行中缺少 symbol 字段,请配置 field_map 映射")
|
||||
|
||||
# 写入
|
||||
snap = date.today()
|
||||
n = rows_to_parquet(rows, config, data_dir, snapshot_date=snap)
|
||||
return n, snap.isoformat()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 调度器
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class PullScheduler:
|
||||
"""后台调度器:为每个启用了 pull 的 ExtConfig 维护定时任务。
|
||||
|
||||
线程安全说明:
|
||||
refresh()/stop() 可能从主事件循环 (lifespan startup) 或同步路由的
|
||||
worker 线程 (configure_pull 是 def 而非 async def, FastAPI 丢进线程池)
|
||||
调用。worker 线程里没有 running loop, 直接 asyncio.create_task 会抛
|
||||
"no running event loop"。因此对 task 的增删一律通过
|
||||
call_soon_threadsafe 提交到主循环执行 —— 同一套代码两种调用场景都安全。
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._tasks: dict[str, asyncio.Task] = {}
|
||||
self._running = False
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
|
||||
def start(self, data_dir) -> None:
|
||||
"""启动调度(在 lifespan startup 调用,主事件循环内)。"""
|
||||
self._running = True
|
||||
self._data_dir = data_dir
|
||||
try:
|
||||
self._loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
self._loop = None
|
||||
logger.info("PullScheduler started")
|
||||
|
||||
def _submit(self, fn, *args) -> None:
|
||||
"""把一个 callable 提交到主事件循环执行 (线程安全)。
|
||||
|
||||
startup 在主循环内调用时 fn 立即排队; worker 线程调用时跨线程排队。
|
||||
两者都通过 call_soon_threadsafe, 保证 _tasks 字典的读写只在主循环里发生。
|
||||
"""
|
||||
loop = self._loop
|
||||
if loop is None or loop.is_closed():
|
||||
raise RuntimeError(
|
||||
"PullScheduler: 事件循环不可用 (start() 未在事件循环中调用?)"
|
||||
)
|
||||
loop.call_soon_threadsafe(fn, *args)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""停止所有任务 (从 shutdown 调用)。"""
|
||||
self._running = False
|
||||
for task in self._tasks.values():
|
||||
task.cancel()
|
||||
self._tasks.clear()
|
||||
logger.info("PullScheduler stopped")
|
||||
|
||||
def refresh(self, data_dir) -> None:
|
||||
"""重新加载配置,更新调度任务(增/删/改)。线程安全。"""
|
||||
self._data_dir = data_dir
|
||||
store = ExtConfigStore(data_dir)
|
||||
configs = store.load_all()
|
||||
|
||||
active_ids: set[str] = set()
|
||||
new_configs: list[ExtConfig] = []
|
||||
|
||||
for config in configs:
|
||||
if not config.pull or not config.pull.enabled or not config.pull.url:
|
||||
continue
|
||||
active_ids.add(config.id)
|
||||
if config.id not in self._tasks:
|
||||
new_configs.append(config)
|
||||
|
||||
# 需要移除的 id (快照当前 task 字典的键, 避免遍历时改字典)
|
||||
remove_ids = [cid for cid in list(self._tasks) if cid not in active_ids]
|
||||
|
||||
# 所有对 _tasks 的修改都提交到主循环里执行, 保证线程安全
|
||||
def _apply() -> None:
|
||||
for config in new_configs:
|
||||
if config.id not in self._tasks: # 二次校验, 防重复
|
||||
self._tasks[config.id] = self._loop.create_task(
|
||||
self._run_loop(config)
|
||||
)
|
||||
logger.info(
|
||||
"PullScheduler: scheduled %s (every %d min)",
|
||||
config.id, config.pull.schedule_minutes,
|
||||
)
|
||||
for cid in remove_ids:
|
||||
task = self._tasks.pop(cid, None)
|
||||
if task is not None:
|
||||
task.cancel()
|
||||
logger.info("PullScheduler: removed %s", cid)
|
||||
|
||||
self._submit(_apply)
|
||||
|
||||
async def _run_loop(self, config: ExtConfig) -> None:
|
||||
"""单个配置的定时拉取循环。
|
||||
|
||||
策略: 启用后立即执行一次, 之后按 interval 循环。
|
||||
每次循环重读最新配置 (fresh), interval 取自 fresh.pull.schedule_minutes,
|
||||
这样用户中途修改间隔也能立即生效 (无需重启)。
|
||||
"""
|
||||
try:
|
||||
while self._running:
|
||||
# 每轮重读最新配置 — 用户可能修改了 url / interval / enabled
|
||||
store = ExtConfigStore(self._data_dir)
|
||||
fresh = store.get(config.id)
|
||||
if not fresh or not fresh.pull or not fresh.pull.enabled:
|
||||
break
|
||||
pull = fresh.pull
|
||||
|
||||
# 先执行一次 (启用即拉取, 让用户立刻看到生效)
|
||||
try:
|
||||
n, d = await fetch_and_ingest(fresh, self._data_dir)
|
||||
fresh.pull.last_run = datetime.now(timezone.utc).isoformat()
|
||||
fresh.pull.last_status = "success"
|
||||
fresh.pull.last_message = f"{n} rows @ {d}"
|
||||
fresh.pull.last_rows = n
|
||||
store.upsert(fresh)
|
||||
logger.info("PullScheduler: %s success, %d rows", config.id, n)
|
||||
except Exception as e:
|
||||
fresh2 = store.get(config.id)
|
||||
if fresh2 and fresh2.pull:
|
||||
fresh2.pull.last_run = datetime.now(timezone.utc).isoformat()
|
||||
fresh2.pull.last_status = "error"
|
||||
fresh2.pull.last_message = str(e)[:200]
|
||||
store.upsert(fresh2)
|
||||
logger.warning("PullScheduler: %s error: %s", config.id, e)
|
||||
|
||||
# 间隔取自最新配置 (每次重新读取, 修复改间隔不生效)
|
||||
interval = max(pull.schedule_minutes * 60, 60) # 至少 60s
|
||||
# 预告下次运行时间, 供前端展示
|
||||
next_dt = datetime.now(timezone.utc).timestamp() + interval
|
||||
latest = store.get(config.id)
|
||||
if latest and latest.pull:
|
||||
latest.pull.next_run = datetime.fromtimestamp(
|
||||
next_dt, tz=timezone.utc
|
||||
).isoformat()
|
||||
store.upsert(latest)
|
||||
|
||||
await asyncio.sleep(interval)
|
||||
if not self._running:
|
||||
break
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
async def _run_loop(self, config: ExtConfig) -> None:
|
||||
"""单个配置的定时拉取循环。
|
||||
|
||||
策略: 启用后立即执行一次, 之后按 interval 循环。
|
||||
每次循环重读最新配置 (fresh), interval 取自 fresh.pull.schedule_minutes,
|
||||
这样用户中途修改间隔也能立即生效 (无需重启)。
|
||||
"""
|
||||
try:
|
||||
while self._running:
|
||||
# 每轮重读最新配置 — 用户可能修改了 url / interval / enabled
|
||||
store = ExtConfigStore(self._data_dir)
|
||||
fresh = store.get(config.id)
|
||||
if not fresh or not fresh.pull or not fresh.pull.enabled:
|
||||
break
|
||||
pull = fresh.pull
|
||||
|
||||
# 先执行一次 (启用即拉取, 让用户立刻看到生效)
|
||||
try:
|
||||
n, d = await fetch_and_ingest(fresh, self._data_dir)
|
||||
fresh.pull.last_run = datetime.now(timezone.utc).isoformat()
|
||||
fresh.pull.last_status = "success"
|
||||
fresh.pull.last_message = f"{n} rows @ {d}"
|
||||
fresh.pull.last_rows = n
|
||||
store.upsert(fresh)
|
||||
logger.info("PullScheduler: %s success, %d rows", config.id, n)
|
||||
except Exception as e:
|
||||
fresh2 = store.get(config.id)
|
||||
if fresh2 and fresh2.pull:
|
||||
fresh2.pull.last_run = datetime.now(timezone.utc).isoformat()
|
||||
fresh2.pull.last_status = "error"
|
||||
fresh2.pull.last_message = str(e)[:200]
|
||||
store.upsert(fresh2)
|
||||
logger.warning("PullScheduler: %s error: %s", config.id, e)
|
||||
|
||||
# 间隔取自最新配置 (每次重新读取, 修复改间隔不生效)
|
||||
interval = max(pull.schedule_minutes * 60, 60) # 至少 60s
|
||||
# 预告下次运行时间, 供前端展示
|
||||
next_dt = datetime.now(timezone.utc).timestamp() + interval
|
||||
latest = store.get(config.id)
|
||||
if latest and latest.pull:
|
||||
latest.pull.next_run = datetime.fromtimestamp(
|
||||
next_dt, tz=timezone.utc
|
||||
).isoformat()
|
||||
store.upsert(latest)
|
||||
|
||||
await asyncio.sleep(interval)
|
||||
if not self._running:
|
||||
break
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
|
||||
# 全局单例
|
||||
pull_scheduler = PullScheduler()
|
||||
@@ -0,0 +1,224 @@
|
||||
"""向前扩展历史数据 — 完全独立于 daily_pipeline 的盘后管道。
|
||||
|
||||
用户从日 K 卡片手动触发,指定往前补的时长 (x 天/月/年)。
|
||||
流程:
|
||||
1. 获取当前最早日期
|
||||
2. 向前拉日 K batch (start = 最早日期 - offset, end = 最早日期)
|
||||
3. 向前拉除权因子 (同范围)
|
||||
4. 全量重算 enriched
|
||||
5. 刷新视图 + 缓存
|
||||
|
||||
⚠️ 本模块不导入 daily_pipeline 的任何函数,只复用基础设施:
|
||||
- kline_sync.sync_and_persist_daily_batch / sync_adj_factor
|
||||
- indicators.pipeline.run_pipeline
|
||||
- pipeline_jobs.JobStore
|
||||
- tickflow.repository.KlineRepository
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from app.services import kline_sync
|
||||
from app.services.pipeline_jobs import job_store
|
||||
from app.tickflow.capabilities import Cap, CapabilitySet
|
||||
from app.tickflow.repository import KlineRepository
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _noop(stage: str, pct: int, msg: str, **kwargs) -> None: # noqa: ARG001
|
||||
pass
|
||||
|
||||
|
||||
def _invalidate(table: str | None = None) -> None:
|
||||
from app.api.data import invalidate_data_cache
|
||||
invalidate_data_cache(table)
|
||||
|
||||
|
||||
def _resolve_universe(capset: CapabilitySet) -> list[str]:
|
||||
"""解析标的池 — 与 daily_pipeline 独立的副本。"""
|
||||
if capset.has(Cap.KLINE_DAILY_BATCH):
|
||||
try:
|
||||
from app.tickflow.pools import get_pool
|
||||
all_a = get_pool("CN_Equity_A", refresh=True)
|
||||
if all_a:
|
||||
return sorted(all_a)
|
||||
except Exception as e:
|
||||
logger.warning("CN_Equity_A pool unavailable: %s", e)
|
||||
|
||||
from app.tickflow.pools import DEMO_SYMBOLS, get_pool as _get_pool
|
||||
from app.config import settings
|
||||
from pathlib import Path
|
||||
import polars as pl
|
||||
base: set[str] = set(DEMO_SYMBOLS)
|
||||
base.update(_get_pool("watchlist"))
|
||||
d = Path(settings.data_dir)
|
||||
inst_path = d / "instruments" / "instruments.parquet"
|
||||
if inst_path.exists():
|
||||
try:
|
||||
inst = pl.read_parquet(inst_path, columns=["symbol"])
|
||||
base.update(inst["symbol"].to_list())
|
||||
except Exception as e:
|
||||
logger.warning("instruments supplement failed: %s", e)
|
||||
return sorted(base)
|
||||
|
||||
|
||||
def _refresh_single_view(repo: KlineRepository, name: str) -> None:
|
||||
"""刷新单个 DuckDB 视图。"""
|
||||
d = repo.store.data_dir.as_posix()
|
||||
paths = {
|
||||
"kline_daily": f"{d}/kline_daily/**/*.parquet",
|
||||
"kline_enriched": f"{d}/kline_daily_enriched/**/*.parquet",
|
||||
"kline_minute": f"{d}/kline_minute/**/*.parquet",
|
||||
"adj_factor": f"{d}/adj_factor/**/*.parquet",
|
||||
"instruments": f"{d}/instruments/**/*.parquet",
|
||||
}
|
||||
path = paths.get(name)
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
repo.db.execute(
|
||||
f"CREATE OR REPLACE VIEW {name} AS "
|
||||
f"SELECT * FROM read_parquet('{path}', union_by_name=true)"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("refresh view %s failed: %s", name, e)
|
||||
|
||||
|
||||
def compute_offset(value: int, unit: str) -> timedelta:
|
||||
"""将用户输入的 value + unit 转成 timedelta。"""
|
||||
if unit == "day":
|
||||
return timedelta(days=value)
|
||||
elif unit == "month":
|
||||
return timedelta(days=value * 30)
|
||||
elif unit == "year":
|
||||
return timedelta(days=value * 365)
|
||||
else:
|
||||
raise ValueError(f"不支持的单位: {unit}")
|
||||
|
||||
|
||||
def run_extend_history(
|
||||
repo: KlineRepository,
|
||||
capset: CapabilitySet,
|
||||
value: int,
|
||||
unit: str,
|
||||
on_progress: Callable | None = None,
|
||||
) -> dict:
|
||||
"""向前扩展历史数据的主函数。
|
||||
|
||||
完全独立于 daily_pipeline.run_now(),不调用其任何逻辑。
|
||||
返回结果 dict 供 job_store 记录。
|
||||
"""
|
||||
emit = on_progress or _noop
|
||||
|
||||
# 0. 计算时间偏移
|
||||
offset = compute_offset(value, unit)
|
||||
today = date.today()
|
||||
|
||||
# 1. 获取当前最早日期
|
||||
emit("extend_history", 2, "检查当前数据范围…")
|
||||
earliest = repo.earliest_daily_date()
|
||||
|
||||
if not earliest:
|
||||
return {"error": "本地无日K数据,请先执行一次完整同步"}
|
||||
|
||||
new_start = earliest - offset
|
||||
# 不能超过今天
|
||||
if new_start >= earliest:
|
||||
return {"error": "扩展范围无效,请增大时间跨度"}
|
||||
|
||||
# 2. 解析标的池
|
||||
emit("extend_history", 5, "解析标的池…")
|
||||
universe = _resolve_universe(capset)
|
||||
if not universe:
|
||||
return {"error": "标的池为空"}
|
||||
emit("extend_history", 8, f"标的池: {len(universe)} 只")
|
||||
|
||||
start_str = new_start.strftime("%Y-%m-%d")
|
||||
end_str = earliest.strftime("%Y-%m-%d")
|
||||
|
||||
# 3. 拉日 K
|
||||
emit("extend_history", 10, f"获取日K [{start_str} ~ {end_str}]…")
|
||||
logger.info("extend_history: daily K [%s ~ %s], %d symbols", start_str, end_str, len(universe))
|
||||
|
||||
def _daily_chunk(cur: int, tot: int) -> None:
|
||||
emit("extend_history", 10 + int(35 * cur / tot),
|
||||
f"日K 批次 {cur}/{tot}", stage_pct=int(100 * cur / tot), skip_log=True)
|
||||
|
||||
written_daily = kline_sync.sync_and_persist_daily_batch(
|
||||
universe, repo, capset,
|
||||
start_date=datetime.combine(new_start, datetime.min.time()),
|
||||
end_date=datetime.combine(earliest, datetime.min.time()),
|
||||
on_chunk_done=_daily_chunk,
|
||||
)
|
||||
emit("extend_history", 45, f"日K 完成,写入 {written_daily} 行")
|
||||
logger.info("extend_history: daily K done, %d rows", written_daily)
|
||||
_refresh_single_view(repo, "kline_daily")
|
||||
_invalidate("daily")
|
||||
|
||||
# 4. 拉除权因子 (新范围)
|
||||
written_adj = 0
|
||||
adj_start = datetime.combine(new_start, datetime.min.time())
|
||||
adj_end = datetime.combine(today, datetime.min.time())
|
||||
adj_start_str = new_start.strftime("%Y-%m-%d")
|
||||
adj_end_str = today.strftime("%Y-%m-%d")
|
||||
|
||||
if capset.has(Cap.ADJ_FACTOR):
|
||||
emit("extend_history", 48, f"获取除权因子 [{adj_start_str} ~ {adj_end_str}]…")
|
||||
logger.info("extend_history: adj_factor [%s ~ %s]", adj_start_str, adj_end_str)
|
||||
|
||||
def _adj_chunk(cur: int, tot: int) -> None:
|
||||
emit("extend_history", 48 + int(10 * cur / tot),
|
||||
f"除权因子批次 {cur}/{tot}", stage_pct=int(100 * cur / tot), skip_log=True)
|
||||
|
||||
written_adj, _affected = kline_sync.sync_adj_factor(
|
||||
universe, repo, capset,
|
||||
start_time=adj_start, end_time=adj_end,
|
||||
on_chunk_done=_adj_chunk,
|
||||
)
|
||||
emit("extend_history", 60, f"除权因子完成,{written_adj} 行")
|
||||
logger.info("extend_history: adj_factor done, %d rows", written_adj)
|
||||
_refresh_single_view(repo, "adj_factor")
|
||||
_invalidate("adj_factor")
|
||||
else:
|
||||
emit("extend_history", 60, "除权因子跳过(无权限)")
|
||||
logger.info("extend_history: adj_factor skipped, no ADJ_FACTOR capability")
|
||||
|
||||
# 5. 全量重算 enriched
|
||||
emit("extend_history", 65, "全量计算 enriched…")
|
||||
logger.info("extend_history: full enriched rebuild start")
|
||||
|
||||
from app.indicators.pipeline import run_pipeline
|
||||
written_enriched = run_pipeline()
|
||||
|
||||
enriched_dir = repo.store.data_dir / "kline_daily_enriched"
|
||||
enriched_days = len(list(enriched_dir.glob("date=*"))) if enriched_dir.exists() else 0
|
||||
emit("extend_history", 92, f"enriched 完成,覆盖 {enriched_days} 天")
|
||||
logger.info("extend_history: enriched done, %d days", enriched_days)
|
||||
_refresh_single_view(repo, "kline_enriched")
|
||||
_invalidate("enriched")
|
||||
|
||||
# 6. 刷新视图
|
||||
emit("extend_history", 95, "刷新视图…")
|
||||
_refresh_single_view(repo, "kline_daily")
|
||||
_refresh_single_view(repo, "kline_enriched")
|
||||
_refresh_single_view(repo, "adj_factor")
|
||||
_invalidate(None)
|
||||
|
||||
# 7. 统计结果
|
||||
daily_dir = repo.store.data_dir / "kline_daily"
|
||||
daily_days = len(list(daily_dir.glob("date=*"))) if daily_dir.exists() else 0
|
||||
|
||||
emit("extend_history", 100, f"完成,已扩展至 {new_start}")
|
||||
|
||||
return {
|
||||
"earliest_before": earliest.isoformat(),
|
||||
"earliest_after": new_start.isoformat(),
|
||||
"daily_rows": written_daily,
|
||||
"daily_days": daily_days,
|
||||
"adj_factor_rows": written_adj,
|
||||
"enriched_days": enriched_days,
|
||||
"universe_size": len(universe),
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
"""AI 财务分析服务 — 读取个股财务数据 → 构建专业提示词 → 流式调用 LLM。
|
||||
|
||||
职责: 拉取单只标的的 4 张财务表 → 转成紧凑 JSON → 拼装 CFA 分析师级系统提示词
|
||||
→ 流式调用 OpenAI 兼容 API → 逐 chunk 吐给前端。
|
||||
|
||||
不知道: HTTP、前端、配置持久化。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import AsyncIterator
|
||||
|
||||
import polars as pl
|
||||
|
||||
from app.services.financial_sync import get_financial_df
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 最多注入的报告期数(最新 N 期),避免上下文爆炸 / token 浪费
|
||||
_MAX_PERIODS = 4
|
||||
|
||||
|
||||
def _load_stock_financials(data_dir: Path, symbol: str) -> dict[str, list[dict]]:
|
||||
"""读取该标的的 4 张财务表,返回 {table: [records...]}(按 period_end 降序,截取最新 N 期)。
|
||||
|
||||
数值统一做 NaN/Inf → null 清洗,保证 JSON 序列化不报错。
|
||||
"""
|
||||
result: dict[str, list[dict]] = {}
|
||||
for table in ("metrics", "income", "balance_sheet", "cash_flow"):
|
||||
df = get_financial_df(data_dir, table)
|
||||
if df.is_empty():
|
||||
result[table] = []
|
||||
continue
|
||||
df = df.filter(pl.col("symbol") == symbol)
|
||||
if df.is_empty():
|
||||
result[table] = []
|
||||
continue
|
||||
# 按 period_end 降序,截取最新 N 期
|
||||
if "period_end" in df.columns:
|
||||
df = df.sort("period_end", descending=True).head(_MAX_PERIODS)
|
||||
# 清洗 NaN/Inf,转成 JSON 安全的 dict 列表
|
||||
rows = []
|
||||
for rec in df.to_dicts():
|
||||
clean = {}
|
||||
for k, v in rec.items():
|
||||
if k == "symbol":
|
||||
continue # 不需要重复回传 symbol
|
||||
if isinstance(v, float):
|
||||
import math
|
||||
clean[k] = None if not math.isfinite(v) else v
|
||||
else:
|
||||
clean[k] = v
|
||||
rows.append(clean)
|
||||
result[table] = rows
|
||||
return result
|
||||
|
||||
|
||||
def _summarize(fins: dict[str, list[dict]]) -> str:
|
||||
"""生成一行业务摘要,便于 LLM 快速把握数据全貌(行数/期数)。"""
|
||||
parts = []
|
||||
for table in ("metrics", "income", "balance_sheet", "cash_flow"):
|
||||
rows = fins.get(table, [])
|
||||
if rows:
|
||||
periods = [r.get("period_end") for r in rows if r.get("period_end")]
|
||||
parts.append(f"{table}: {len(rows)}期 ({', '.join(str(p) for p in periods[:3])})")
|
||||
else:
|
||||
parts.append(f"{table}: 无数据")
|
||||
return " · ".join(parts)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 系统提示词 —— CFA 分析师级,九维分析框架
|
||||
# ================================================================
|
||||
|
||||
_SYSTEM_PROMPT = """你是一位拥有 15 年 A 股投研经验的资深财务分析师(CFA + CPA),服务于专业机构投资者。你的任务是:基于提供的上市公司财务数据,产出一份**严谨、专业、可直接用于投资决策**的财务分析报告。
|
||||
|
||||
## 输出规范
|
||||
|
||||
用 **Markdown** 格式输出,严格遵循以下结构。不要输出任何 JSON 或代码块,直接输出 Markdown 正文。
|
||||
|
||||
### 1. 📌 核心摘要(1-2 句)
|
||||
用一句话概括该公司的财务画像:盈利质量、成长动能、财务健康度的最关键判断。结尾用【综合评级:★★★☆☆】给出 1-5 星评级。
|
||||
|
||||
### 2. ✅ 亮点(2-3 条)
|
||||
列出最值得关注的**积极信号**,每条用加粗短语领起,配数据支撑。例如盈利高增、ROE 持续提升、现金流充沛等。
|
||||
|
||||
### 3. ⚠️ 风险提示(2-3 条)
|
||||
客观指出**潜在风险或值得警惕的信号**,例如应收激增、存货堆积、经营现金流与净利润背离、债务攀升等。宁可保守,不要回避。
|
||||
|
||||
### 4. 📊 分项诊断
|
||||
用**表格**呈现各维度的诊断结论,列为「维度 / 关键指标 / 判断」。维度包括:
|
||||
- **盈利能力**:ROE / ROA / 毛利率 / 净利率
|
||||
- **成长性**:营收同比 / 净利润同比
|
||||
- **偿债能力**:资产负债率 / 流动比率(用资产/负债估算)
|
||||
- **现金流**:经营现金流净额 / 与净利润的匹配度
|
||||
- **营运效率**:存货周转率等(有数据时)
|
||||
|
||||
每个判断给「优秀 / 良好 / 一般 / 偏弱 / 警惕」之一,并一句话说明依据。
|
||||
|
||||
### 5. 🎯 综合评估与展望
|
||||
2-3 段总结:该公司当前的财务状态(优秀/稳健/承压/恶化)、核心驱动力、未来需重点跟踪的指标。**结尾给出"投资参考"**:从纯财务质量角度,该股属于(高质量蓝筹 / 稳健成长 / 周期波动 / 财务承压 / 高风险)中的哪一类。
|
||||
|
||||
## 分析准则(务必遵守)
|
||||
|
||||
1. **数据说话**:每个判断必须引用具体数值(如"营收同比 +28.5%"),严禁空泛套话
|
||||
2. **纵向对比**:利用多期数据看趋势(改善/恶化),而非只看单期
|
||||
3. **交叉验证**:经营现金流 vs 净利润(是否造血)、毛利率 vs 费用率(盈利结构)、负债 vs 资产(杠杆)
|
||||
4. **行业常识**:对照 A 股常识判断水平(如 ROE>15% 优秀,资产负债率>70% 偏高,毛利率<20% 偏低)
|
||||
5. **诚实中立**:数据不支持时直言"数据不足,无法判断",绝不编造或过度演绎
|
||||
6. **简明有力**:避免冗长,用专业投资者能扫读的密度输出,总字数 800-1500 字
|
||||
|
||||
## 重要免责
|
||||
报告末尾附一行:"> ⚠️ 本报告由 AI 基于公开财务数据生成,仅供参考,不构成任何投资建议。"
|
||||
|
||||
现在请基于下方数据进行分析。"""
|
||||
|
||||
|
||||
def _build_user_prompt(fins: dict[str, list[dict]], symbol: str, focus: str) -> str:
|
||||
"""构建用户消息:标的代码 + 数据 JSON + 可选关注点。"""
|
||||
data_json = json.dumps(fins, ensure_ascii=False, indent=2)
|
||||
lines = [
|
||||
f"标的标准代码: {symbol}",
|
||||
f"数据概览: {_summarize(fins)}",
|
||||
"",
|
||||
"以下是该标的最新财务数据(JSON 格式,金额单位为元,比率类指标为百分点):",
|
||||
"```json",
|
||||
data_json,
|
||||
"```",
|
||||
]
|
||||
if focus.strip():
|
||||
lines.extend([
|
||||
"",
|
||||
f"本次分析请特别关注: {focus.strip()}",
|
||||
])
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
async def analyze_financials_stream(
|
||||
data_dir: Path,
|
||||
symbol: str,
|
||||
focus: str = "",
|
||||
) -> AsyncIterator[str]:
|
||||
"""流式分析:yield 出每个文本 chunk。
|
||||
|
||||
- 启动时先 yield 一条 {"type":"meta",...} 让前端显示数据摘要
|
||||
- 之后逐 chunk yield {"type":"delta","content":"..."}
|
||||
- 出错时 yield {"type":"error","message":"..."}
|
||||
- 结束 yield {"type":"done"}
|
||||
"""
|
||||
# 1. 加载数据
|
||||
fins = _load_stock_financials(data_dir, symbol)
|
||||
total_rows = sum(len(v) for v in fins.values())
|
||||
if total_rows == 0:
|
||||
yield json.dumps({"type": "error", "message": f"标的 {symbol} 暂无任何财务数据,请先同步财务表"}, ensure_ascii=False)
|
||||
return
|
||||
|
||||
# 2. meta
|
||||
yield json.dumps({
|
||||
"type": "meta",
|
||||
"symbol": symbol,
|
||||
"summary": _summarize(fins),
|
||||
"periods": total_rows,
|
||||
}, ensure_ascii=False)
|
||||
|
||||
# 3. 调用 LLM 流式
|
||||
try:
|
||||
from app.services.ai_provider import stream_ai_text
|
||||
|
||||
user_prompt = _build_user_prompt(fins, symbol, focus)
|
||||
async for delta in stream_ai_text(
|
||||
[
|
||||
{"role": "system", "content": _SYSTEM_PROMPT},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
temperature=0.4,
|
||||
max_tokens=4000,
|
||||
):
|
||||
yield json.dumps({"type": "delta", "content": delta}, ensure_ascii=False)
|
||||
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception("AI financial analysis failed for %s: %s", symbol, e)
|
||||
yield json.dumps({"type": "error", "message": f"AI 分析失败: {e}"}, ensure_ascii=False)
|
||||
return
|
||||
|
||||
yield json.dumps({"type": "done"}, ensure_ascii=False)
|
||||
@@ -0,0 +1,410 @@
|
||||
"""财务数据独立同步服务。
|
||||
|
||||
解耦于 K-line 管道, 自有调度 + 自有存储。
|
||||
能力门控: Cap.FINANCIAL (Expert 套餐)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import polars as pl
|
||||
|
||||
from app.tickflow.capabilities import Cap, CapabilitySet
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 每个 API 请求最多 100 个标的
|
||||
_BATCH_SIZE = 100
|
||||
|
||||
# 4 张财务表
|
||||
FINANCIAL_TABLES = ("metrics", "income", "balance_sheet", "cash_flow")
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 同步函数
|
||||
# ================================================================
|
||||
|
||||
def _get_symbols(data_dir: Path) -> list[str]:
|
||||
"""从 instruments 表获取标的列表。"""
|
||||
inst_path = data_dir / "instruments" / "instruments.parquet"
|
||||
if not inst_path.exists():
|
||||
return []
|
||||
try:
|
||||
df = pl.read_parquet(inst_path, columns=["symbol"])
|
||||
return df["symbol"].to_list()
|
||||
except Exception as e:
|
||||
logger.warning("读取 instruments 失败: %s", e)
|
||||
return []
|
||||
|
||||
|
||||
def _sync_table(
|
||||
table: str,
|
||||
symbols: list[str],
|
||||
data_dir: Path,
|
||||
capset: CapabilitySet,
|
||||
latest_only: bool = True,
|
||||
) -> int:
|
||||
"""同步单张财务表。返回写入的行数。"""
|
||||
if not capset.has(Cap.FINANCIAL):
|
||||
logger.info("sync_%s skipped: no FINANCIAL capability", table)
|
||||
return 0
|
||||
if not symbols:
|
||||
logger.warning("sync_%s skipped: no symbols", table)
|
||||
return 0
|
||||
|
||||
from app.tickflow.client import get_client
|
||||
tf = get_client()
|
||||
|
||||
# 分批拉取
|
||||
api_method = {
|
||||
"metrics": tf.financials.metrics,
|
||||
"income": tf.financials.income,
|
||||
"balance_sheet": tf.financials.balance_sheet,
|
||||
"cash_flow": tf.financials.cash_flow,
|
||||
}[table]
|
||||
|
||||
all_records: list[dict] = []
|
||||
total_batches = (len(symbols) + _BATCH_SIZE - 1) // _BATCH_SIZE
|
||||
|
||||
for i in range(0, len(symbols), _BATCH_SIZE):
|
||||
chunk = symbols[i : i + _BATCH_SIZE]
|
||||
batch_num = i // _BATCH_SIZE + 1
|
||||
try:
|
||||
data = api_method(chunk, latest=latest_only)
|
||||
# data 格式: { "600519.SH": [record, ...], ... }
|
||||
if isinstance(data, dict):
|
||||
for sym, records in data.items():
|
||||
if isinstance(records, list):
|
||||
for rec in records:
|
||||
if isinstance(rec, dict):
|
||||
rec["symbol"] = sym
|
||||
all_records.append(rec)
|
||||
logger.debug("sync_%s batch %d/%d: %d records", table, batch_num, total_batches, len(data) if isinstance(data, dict) else 0)
|
||||
except Exception as e:
|
||||
logger.warning("sync_%s batch %d/%d failed: %s", table, batch_num, total_batches, e)
|
||||
|
||||
if not all_records:
|
||||
return 0
|
||||
|
||||
df = pl.DataFrame(all_records)
|
||||
if df.is_empty():
|
||||
return 0
|
||||
|
||||
# 确保 symbol 列存在
|
||||
if "symbol" not in df.columns:
|
||||
return 0
|
||||
|
||||
# 写入 Parquet (全量覆盖)
|
||||
out_dir = data_dir / "financials" / table
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
out_file = out_dir / "part.parquet"
|
||||
df.write_parquet(out_file)
|
||||
|
||||
logger.info("sync_%s done: %d records written", table, len(df))
|
||||
return len(df)
|
||||
|
||||
|
||||
def sync_metrics(data_dir: Path, capset: CapabilitySet) -> int:
|
||||
"""同步核心财务指标 (metrics)。"""
|
||||
symbols = _get_symbols(data_dir)
|
||||
return _sync_table("metrics", symbols, data_dir, capset, latest_only=True)
|
||||
|
||||
|
||||
def sync_income(data_dir: Path, capset: CapabilitySet) -> int:
|
||||
"""同步利润表。"""
|
||||
symbols = _get_symbols(data_dir)
|
||||
return _sync_table("income", symbols, data_dir, capset, latest_only=True)
|
||||
|
||||
|
||||
def sync_balance_sheet(data_dir: Path, capset: CapabilitySet) -> int:
|
||||
"""同步资产负债表。"""
|
||||
symbols = _get_symbols(data_dir)
|
||||
return _sync_table("balance_sheet", symbols, data_dir, capset, latest_only=True)
|
||||
|
||||
|
||||
def sync_cash_flow(data_dir: Path, capset: CapabilitySet) -> int:
|
||||
"""同步现金流量表。"""
|
||||
symbols = _get_symbols(data_dir)
|
||||
return _sync_table("cash_flow", symbols, data_dir, capset, latest_only=True)
|
||||
|
||||
|
||||
def sync_all(data_dir: Path, capset: CapabilitySet) -> dict[str, int]:
|
||||
"""同步所有财务表。返回 {table: rows}。"""
|
||||
if not capset.has(Cap.FINANCIAL):
|
||||
logger.info("sync_all financials skipped: no FINANCIAL capability")
|
||||
return {}
|
||||
|
||||
symbols = _get_symbols(data_dir)
|
||||
results: dict[str, int] = {}
|
||||
for table in FINANCIAL_TABLES:
|
||||
results[table] = _sync_table(table, symbols, data_dir, capset, latest_only=True)
|
||||
|
||||
# 同步完成后注册 DuckDB 视图
|
||||
_refresh_financials_views(data_dir)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
# ================================================================
|
||||
# DuckDB 视图
|
||||
# ================================================================
|
||||
|
||||
def _refresh_financials_views(data_dir: Path) -> None:
|
||||
"""刷新财务表 DuckDB 视图 (在 DataStore.db 上注册)。"""
|
||||
d = data_dir.as_posix()
|
||||
views = {
|
||||
"financials_metrics": f"{d}/financials/metrics/*.parquet",
|
||||
"financials_income": f"{d}/financials/income/*.parquet",
|
||||
"financials_balance_sheet": f"{d}/financials/balance_sheet/*.parquet",
|
||||
"financials_cash_flow": f"{d}/financials/cash_flow/*.parquet",
|
||||
}
|
||||
for name, path in views.items():
|
||||
out = data_dir / "financials" / name.replace("financials_", "") / "part.parquet"
|
||||
if not out.exists():
|
||||
continue
|
||||
# 视图注册需要由 DataStore 完成,这里只做日志
|
||||
logger.debug("financial parquet ready: %s (%d rows)", name, out.stat().st_size)
|
||||
|
||||
|
||||
def get_financial_df(data_dir: Path, table: str) -> pl.DataFrame:
|
||||
"""读取本地财务 Parquet。"""
|
||||
path = data_dir / "financials" / table / "part.parquet"
|
||||
if not path.exists():
|
||||
return pl.DataFrame()
|
||||
try:
|
||||
return pl.read_parquet(path)
|
||||
except Exception as e:
|
||||
logger.warning("读取 financials/%s 失败: %s", table, e)
|
||||
return pl.DataFrame()
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 调度器
|
||||
# ================================================================
|
||||
|
||||
class FinancialScheduler:
|
||||
"""独立调度器: 每周同步 metrics, 每季度同步三张报表。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._task: asyncio.Task | None = None
|
||||
self._running = False
|
||||
self._data_dir: Path | None = None
|
||||
self._capset: CapabilitySet | None = None
|
||||
self._lock = threading.Lock()
|
||||
self._last_sync: dict[str, str] = {} # {table: iso_timestamp}
|
||||
# 手动同步(run_now)是否正在进行。前端据此显示"同步中"并防重复点击。
|
||||
self._is_syncing = False
|
||||
|
||||
def start(self, data_dir: Path, capset: CapabilitySet, *, auto_schedule: bool = False) -> None:
|
||||
"""初始化调度器,并按需启动周期同步后台任务。
|
||||
|
||||
auto_schedule=False (默认): 仅初始化 (设置数据目录/能力 + 恢复 last_sync),
|
||||
供 /api/financials/sync/* 手动同步使用, 不启动自动调度。
|
||||
auto_schedule=True: 额外启动每周一次的 metrics 自动同步 (启动后 60s 首跑)。
|
||||
"""
|
||||
# 先记录 data_dir/capset, 即使当前无 FINANCIAL 也保留引用:
|
||||
# 用户稍后在「设置」页升级到 Expert Key 时, update_capabilities() 会把新 capset
|
||||
# 推进来,trigger()/run_now() 才能用上 FINANCIAL。否则 _capset 永远是 None,
|
||||
# 即便 app.state.capabilities 已更新, 调度器仍报 "no FINANCIAL capability"。
|
||||
self._data_dir = data_dir
|
||||
self._capset = capset
|
||||
if not capset.has(Cap.FINANCIAL):
|
||||
logger.info("FinancialScheduler skipped: no FINANCIAL capability")
|
||||
return
|
||||
# 从持久化恢复上次同步时间: 重启后前端仍能显示真实最后同步时间,而非"尚未同步"
|
||||
try:
|
||||
from app.services import preferences
|
||||
restored = dict(preferences.get_financial_sync_times())
|
||||
# 老用户迁移兜底: 若某表在 preferences 无记录但 parquet 已存在(升级前同步过),
|
||||
# 用 parquet 文件的修改时间作为同步时间并补写持久化。
|
||||
for table in FINANCIAL_TABLES:
|
||||
if table in restored:
|
||||
continue
|
||||
parquet = data_dir / "financials" / table / "part.parquet"
|
||||
if parquet.exists():
|
||||
mtime = datetime.fromtimestamp(parquet.stat().st_mtime, tz=timezone.utc).isoformat()
|
||||
restored[table] = mtime
|
||||
preferences.set_financial_sync_time(table, mtime)
|
||||
logger.info("FinancialScheduler backfilled last_sync for %s from parquet mtime", table)
|
||||
self._last_sync = restored
|
||||
if self._last_sync:
|
||||
logger.info("FinancialScheduler restored last_sync: %s", list(self._last_sync.keys()))
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("restore financial_sync_times failed: %s", e)
|
||||
|
||||
if not auto_schedule:
|
||||
# 仅初始化 (手动同步用), 不启动周期任务。
|
||||
logger.info("FinancialScheduler initialized (auto-schedule disabled; manual sync only)")
|
||||
return
|
||||
|
||||
self._running = True
|
||||
self._task = asyncio.create_task(self._run_loop())
|
||||
logger.info("FinancialScheduler started (auto-schedule enabled)")
|
||||
|
||||
def _record_sync(self, table: str) -> None:
|
||||
"""记录一张表的同步完成时间: 更新内存 + 持久化到 preferences.json。
|
||||
|
||||
持久化确保即使重启,前端 /status 仍返回真实的最后同步时间,
|
||||
不会错误地显示"尚未同步"。
|
||||
"""
|
||||
ts = datetime.now(timezone.utc).isoformat()
|
||||
self._last_sync[table] = ts
|
||||
try:
|
||||
from app.services import preferences
|
||||
preferences.set_financial_sync_time(table, ts)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("persist financial_sync_time(%s) failed: %s", e)
|
||||
|
||||
def update_capabilities(self, capset: CapabilitySet) -> None:
|
||||
"""刷新调度器持有的能力集。
|
||||
|
||||
用户在「设置」页新增/清除 API Key 后, settings API 会重新探测能力并更新
|
||||
app.state.capabilities; 必须同步推给本调度器, 否则 trigger()/run_now() 仍读
|
||||
启动时的旧 capset, 即便 app.state 已含 FINANCIAL, 调度器仍报
|
||||
"no FINANCIAL capability" 而拒绝同步 (表现为前端「全部同步」按钮闪一下无动作)。
|
||||
"""
|
||||
prev = self._capset
|
||||
self._capset = capset
|
||||
had = bool(prev) and prev.has(Cap.FINANCIAL)
|
||||
now = capset.has(Cap.FINANCIAL)
|
||||
if had != now:
|
||||
logger.info(
|
||||
"FinancialScheduler capabilities updated: FINANCIAL %s -> %s", had, now
|
||||
)
|
||||
|
||||
def stop(self) -> None:
|
||||
self._running = False
|
||||
if self._task:
|
||||
self._task.cancel()
|
||||
self._task = None
|
||||
logger.info("FinancialScheduler stopped")
|
||||
|
||||
async def _run_loop(self) -> None:
|
||||
"""每周执行一次 metrics 同步。"""
|
||||
try:
|
||||
while self._running:
|
||||
# 首次启动等 60s, 之后每 7 天执行一次
|
||||
await asyncio.sleep(60)
|
||||
if not self._running:
|
||||
break
|
||||
|
||||
# 每周: 只同步 metrics
|
||||
try:
|
||||
rows = sync_metrics(self._data_dir, self._capset)
|
||||
self._record_sync("metrics")
|
||||
logger.info("FinancialScheduler: metrics synced, %d rows", rows)
|
||||
except Exception as e:
|
||||
logger.warning("FinancialScheduler: metrics sync failed: %s", e)
|
||||
|
||||
# 等待下一次 (7天)
|
||||
for _ in range(7 * 24 * 60): # 每分钟检查一次 _running
|
||||
if not self._running:
|
||||
break
|
||||
await asyncio.sleep(60)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
def _run_body(self, table: str | None) -> dict[str, int]:
|
||||
"""同步逻辑本体(不加锁,假设调用方已持有 _is_syncing)。
|
||||
|
||||
table=None 同步全部 4 张表;否则只同步指定表。
|
||||
每张表完成立即更新 last_sync,让前端轮询 /status 能看到进度递增。
|
||||
"""
|
||||
if table:
|
||||
fn = {
|
||||
"metrics": sync_metrics,
|
||||
"income": sync_income,
|
||||
"balance_sheet": sync_balance_sheet,
|
||||
"cash_flow": sync_cash_flow,
|
||||
}.get(table)
|
||||
if not fn:
|
||||
return {}
|
||||
rows = fn(self._data_dir, self._capset)
|
||||
self._record_sync(table)
|
||||
return {table: rows}
|
||||
# 全部同步
|
||||
symbols = _get_symbols(self._data_dir)
|
||||
result: dict[str, int] = {}
|
||||
for t in FINANCIAL_TABLES:
|
||||
result[t] = _sync_table(t, symbols, self._data_dir, self._capset, latest_only=True)
|
||||
self._record_sync(t)
|
||||
_refresh_financials_views(self._data_dir)
|
||||
return result
|
||||
|
||||
def run_now(self, table: str | None = None) -> dict[str, int]:
|
||||
"""同步执行一次同步(阻塞调用线程)。
|
||||
|
||||
⚠ 全量同步需数分钟,务必在后台线程调用,不要直接在 HTTP 请求线程里阻塞,
|
||||
否则请求会长时间 pending 直至被浏览器/代理超时掐断(表现为"点击无反应")。
|
||||
HTTP 接口应调用 trigger() 立即返回,再让前端轮询 /status.syncing 看进度。
|
||||
|
||||
用 _is_syncing 标志防并发:若已有同步在进行,本次直接跳过,
|
||||
避免重复请求拖慢服务端 / 触发上游限流。
|
||||
"""
|
||||
if not self._capset or not self._capset.has(Cap.FINANCIAL):
|
||||
return {}
|
||||
with self._lock:
|
||||
if self._is_syncing:
|
||||
logger.info("financial sync skipped: already running")
|
||||
return {"_skipped": 1}
|
||||
self._is_syncing = True
|
||||
try:
|
||||
return self._run_body(table)
|
||||
finally:
|
||||
with self._lock:
|
||||
self._is_syncing = False
|
||||
|
||||
def trigger(self, table: str | None = None) -> dict[str, int]:
|
||||
"""触发一次同步(非阻塞,立即返回)。
|
||||
|
||||
在后台线程执行同步体,HTTP 请求无需等待。
|
||||
返回 {"started": True/False}:
|
||||
- False = 能力不足或已有同步在进行(被防并发跳过)
|
||||
- True = 已在后台开始,前端应轮询 /status.syncing 观察进度
|
||||
|
||||
⚠ _is_syncing 在此处置 True(持锁),确保 trigger 返回时前端轮询
|
||||
/status 已能看到 syncing=True,无竞态窗口;同时防止快速重复点击
|
||||
启动多个后台线程。后台线程复用 _run_body 执行真正的同步逻辑。
|
||||
"""
|
||||
if not self._capset or not self._capset.has(Cap.FINANCIAL):
|
||||
return {"started": False, "reason": "no FINANCIAL capability"}
|
||||
with self._lock:
|
||||
if self._is_syncing:
|
||||
logger.info("financial sync trigger skipped: already running")
|
||||
return {"started": False, "reason": "already running"}
|
||||
# 持锁置位:保证 trigger 返回前 syncing 已为 True
|
||||
self._is_syncing = True
|
||||
|
||||
def _bg() -> None:
|
||||
try:
|
||||
self._run_body(table)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception("background financial sync failed: %s", e)
|
||||
finally:
|
||||
with self._lock:
|
||||
self._is_syncing = False
|
||||
|
||||
t = threading.Thread(target=_bg, name="financial-sync", daemon=True)
|
||||
t.start()
|
||||
logger.info("financial sync triggered in background: table=%s", table or "all")
|
||||
return {"started": True}
|
||||
|
||||
@property
|
||||
def is_syncing(self) -> bool:
|
||||
"""手动同步是否正在进行(供 /status 返回,前端据此显示"同步中")。"""
|
||||
with self._lock:
|
||||
return self._is_syncing
|
||||
|
||||
@property
|
||||
def last_sync(self) -> dict[str, str]:
|
||||
return dict(self._last_sync)
|
||||
|
||||
|
||||
# 全局单例
|
||||
financial_scheduler = FinancialScheduler()
|
||||
@@ -0,0 +1,360 @@
|
||||
"""指数 / ETF 数据同步服务。
|
||||
|
||||
标的列表优先用免费的 exchanges.get_instruments(type=index/etf) 拉取
|
||||
(None/Free 档均可用,无需 quote.pool 权限);付费档可额外用
|
||||
quotes.get_by_universes 作为补充来源。日K统一走 klines.batch。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import gc
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import polars as pl
|
||||
|
||||
from app.indicators.pipeline import compute_enriched
|
||||
from app.services import kline_sync, preferences
|
||||
from app.tickflow.capabilities import Cap, CapabilitySet
|
||||
from app.tickflow.client import get_client
|
||||
from app.tickflow.repository import KlineRepository
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# exchanges.get_instruments 查询的交易所(沪深京)
|
||||
_EXCHANGES = ["SH", "SZ", "BJ"]
|
||||
|
||||
|
||||
def _quotes_to_index_instruments(resp) -> pl.DataFrame:
|
||||
"""将 TickFlow quotes 响应(get_by_universes)规范为指数 instruments。
|
||||
|
||||
付费档(Starter+)的补充来源,免费档用不到。
|
||||
"""
|
||||
if resp is None:
|
||||
return pl.DataFrame()
|
||||
|
||||
if isinstance(resp, pl.DataFrame):
|
||||
df = resp
|
||||
elif hasattr(resp, "columns"):
|
||||
df = pl.from_pandas(resp.reset_index() if hasattr(resp, "reset_index") else resp)
|
||||
else:
|
||||
rows: list[dict] = []
|
||||
for q in resp or []:
|
||||
item = q if isinstance(q, dict) else {}
|
||||
ext = item.get("ext") or {}
|
||||
symbol = item.get("symbol")
|
||||
if not symbol:
|
||||
continue
|
||||
rows.append({
|
||||
"symbol": str(symbol),
|
||||
"name": ext.get("name") or item.get("name") or str(symbol),
|
||||
})
|
||||
df = pl.DataFrame(rows)
|
||||
|
||||
if df.is_empty() or "symbol" not in df.columns:
|
||||
return pl.DataFrame()
|
||||
|
||||
rename = {"ts_code": "symbol"}
|
||||
df = df.rename({k: v for k, v in rename.items() if k in df.columns})
|
||||
|
||||
if "name" not in df.columns:
|
||||
if "ext" in df.columns:
|
||||
df = df.with_columns(pl.col("symbol").cast(pl.Utf8).alias("name"))
|
||||
else:
|
||||
df = df.with_columns(pl.col("symbol").cast(pl.Utf8).alias("name"))
|
||||
|
||||
result = df.select([
|
||||
pl.col("symbol").cast(pl.Utf8),
|
||||
pl.col("name").cast(pl.Utf8),
|
||||
]).with_columns([
|
||||
pl.col("symbol").str.split(".").list.first().alias("code"),
|
||||
pl.lit("index").alias("asset_type"),
|
||||
])
|
||||
return result.unique(subset=["symbol"], keep="last").sort("symbol")
|
||||
|
||||
|
||||
def _fetch_instruments_by_type(instrument_type: str, asset_type_label: str) -> pl.DataFrame:
|
||||
"""用免费的 exchanges.get_instruments 拉取指定类型的标的列表。
|
||||
|
||||
None/Free 档均可使用(标的信息查询免费开放)。
|
||||
instrument_type: 'index' / 'etf'
|
||||
asset_type_label: 写入 instruments 表的 asset_type 标记('index' / 'etf')
|
||||
"""
|
||||
tf = get_client()
|
||||
rows: list[dict] = []
|
||||
for ex in _EXCHANGES:
|
||||
try:
|
||||
items = tf.exchanges.get_instruments(ex, instrument_type=instrument_type)
|
||||
for it in items or []:
|
||||
item = it if isinstance(it, dict) else {}
|
||||
symbol = item.get("symbol")
|
||||
if not symbol:
|
||||
continue
|
||||
rows.append({
|
||||
"symbol": str(symbol),
|
||||
"name": item.get("name") or str(symbol),
|
||||
})
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("get_instruments(%s, type=%s) failed: %s", ex, instrument_type, e)
|
||||
|
||||
if not rows:
|
||||
return pl.DataFrame()
|
||||
|
||||
return (
|
||||
pl.DataFrame(rows)
|
||||
.with_columns([
|
||||
pl.col("symbol").str.split(".").list.first().alias("code"),
|
||||
pl.lit(asset_type_label).alias("asset_type"),
|
||||
])
|
||||
.unique(subset=["symbol"], keep="last")
|
||||
.sort("symbol")
|
||||
)
|
||||
|
||||
|
||||
def sync_index_instruments(
|
||||
repo: KlineRepository,
|
||||
pull_index: bool = True,
|
||||
pull_etf: bool = True,
|
||||
) -> int:
|
||||
"""同步指数 / ETF 标的维表,返回标的总数。
|
||||
|
||||
新版物理分开保存: 指数写 instruments_index, ETF 写 instruments_etf。
|
||||
读取层仍兼容旧版 instruments_index 中 asset_type='etf' 的历史数据。
|
||||
"""
|
||||
index_parts: list[pl.DataFrame] = []
|
||||
etf_parts: list[pl.DataFrame] = []
|
||||
|
||||
# 1) 免费通道:按开关分别拉 index / etf
|
||||
if pull_index:
|
||||
index_df = _fetch_instruments_by_type("index", "index")
|
||||
if not index_df.is_empty():
|
||||
index_parts.append(index_df)
|
||||
if pull_etf:
|
||||
etf_df = _fetch_instruments_by_type("etf", "etf")
|
||||
if not etf_df.is_empty():
|
||||
etf_parts.append(etf_df)
|
||||
|
||||
# 2) 付费补充:Starter+ 用 get_by_universes 补指数(仅当开启指数拉取)
|
||||
if pull_index:
|
||||
capset = None
|
||||
try:
|
||||
from app.tickflow import policy
|
||||
capset = policy.detect_capabilities(force=False)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
if capset is not None and capset.has(Cap.QUOTE_POOL):
|
||||
tf = get_client()
|
||||
for kwargs in (
|
||||
{"universes": ["CN_Index"]},
|
||||
{"universes": ["CN_Index"], "as_dataframe": False},
|
||||
):
|
||||
try:
|
||||
resp = tf.quotes.get_by_universes(**kwargs)
|
||||
if resp is not None and len(resp) > 0:
|
||||
sup = _quotes_to_index_instruments(resp)
|
||||
if not sup.is_empty():
|
||||
index_parts.append(sup)
|
||||
break
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("CN_Index universe supplement failed: %s", e)
|
||||
|
||||
total = 0
|
||||
if index_parts:
|
||||
index_inst = pl.concat(index_parts, how="diagonal_relaxed").unique(subset=["symbol"], keep="last").sort("symbol")
|
||||
if not index_inst.is_empty():
|
||||
repo.save_index_instruments(index_inst)
|
||||
total += index_inst.height
|
||||
if etf_parts:
|
||||
etf_inst = pl.concat(etf_parts, how="diagonal_relaxed").unique(subset=["symbol"], keep="last").sort("symbol")
|
||||
if not etf_inst.is_empty():
|
||||
repo.save_etf_instruments(etf_inst)
|
||||
total += etf_inst.height
|
||||
|
||||
if total == 0:
|
||||
logger.warning("指数/ETF 标的列表为空(pull_index=%s, pull_etf=%s)", pull_index, pull_etf)
|
||||
return 0
|
||||
repo.refresh_index_views()
|
||||
logger.info("指数/ETF 标的同步完成: %d 只", total)
|
||||
return total
|
||||
|
||||
|
||||
def sync_etf_instruments(repo: KlineRepository) -> int:
|
||||
"""单独同步 ETF 标的维表(返回 ETF 数量)。"""
|
||||
etf_df = _fetch_instruments_by_type("etf", "etf")
|
||||
if etf_df.is_empty():
|
||||
return 0
|
||||
repo.save_etf_instruments(etf_df)
|
||||
repo.refresh_index_views()
|
||||
return etf_df.height
|
||||
|
||||
|
||||
def sync_and_persist_index_daily(
|
||||
repo: KlineRepository,
|
||||
capset: CapabilitySet,
|
||||
count: int | None = None,
|
||||
start_date: datetime | None = None,
|
||||
end_date: datetime | None = None,
|
||||
symbols_override: list[str] | None = None,
|
||||
on_chunk_done: Callable[[int, int], None] | None = None,
|
||||
) -> int:
|
||||
"""同步指数/ETF 日K到独立 parquet,并计算 enriched。
|
||||
|
||||
symbols_override 非空时,只拉这些代码(跳过 instruments 表),用于自定义范围。
|
||||
否则取 index_instruments 表全量(指数+ETF 合并存储)。
|
||||
on_chunk_done(current, total) 每个批次完成后回调。
|
||||
"""
|
||||
if not capset.has(Cap.KLINE_DAILY_BATCH):
|
||||
return 0
|
||||
|
||||
if symbols_override:
|
||||
symbols = sorted(set(s for s in symbols_override if s))
|
||||
if not symbols:
|
||||
return 0
|
||||
else:
|
||||
instruments = repo.get_index_instruments()
|
||||
if instruments.is_empty():
|
||||
sync_index_instruments(repo, pull_index=True, pull_etf=False)
|
||||
instruments = repo.get_index_instruments()
|
||||
if not instruments.is_empty() and "asset_type" in instruments.columns:
|
||||
instruments = instruments.filter(pl.col("asset_type") != "etf")
|
||||
if instruments.is_empty() or "symbol" not in instruments.columns:
|
||||
return 0
|
||||
symbols = sorted(set(instruments["symbol"].to_list()))
|
||||
lim = capset.limits(Cap.KLINE_DAILY_BATCH)
|
||||
batch_size = preferences.get_index_daily_batch_size()
|
||||
if lim and lim.batch:
|
||||
batch_size = min(batch_size, lim.batch)
|
||||
rpm = lim.rpm if lim else None
|
||||
|
||||
end_time = end_date or datetime.now()
|
||||
start_time = start_date or (end_time - timedelta(days=365))
|
||||
|
||||
total_rows = 0
|
||||
interval = (60.0 / rpm) if rpm else 0
|
||||
chunks = [symbols[i:i + batch_size] for i in range(0, len(symbols), batch_size)]
|
||||
for i, chunk in enumerate(chunks):
|
||||
if i > 0 and interval > 0 and len(chunks) > rpm:
|
||||
import time
|
||||
time.sleep(interval)
|
||||
raw = kline_sync.sync_daily_batch(
|
||||
chunk,
|
||||
count=count,
|
||||
batch_size=None,
|
||||
start_time=start_time,
|
||||
end_time=end_time,
|
||||
)
|
||||
if raw.is_empty():
|
||||
continue
|
||||
|
||||
repo.append_index_daily(raw)
|
||||
enriched = compute_enriched(raw, factors=None, instruments=None)
|
||||
repo.append_index_enriched(enriched)
|
||||
total_rows += raw.height
|
||||
logger.info("index/etf daily synced: %d/%d chunks, +%d rows", i + 1, len(chunks), raw.height)
|
||||
if on_chunk_done:
|
||||
on_chunk_done(i + 1, len(chunks))
|
||||
del raw, enriched
|
||||
gc.collect()
|
||||
repo.refresh_index_views()
|
||||
return total_rows
|
||||
|
||||
|
||||
def _load_etf_factors(repo: KlineRepository) -> pl.DataFrame:
|
||||
factor_path = repo.store.data_dir / "adj_factor_etf" / "all.parquet"
|
||||
if not factor_path.exists():
|
||||
return pl.DataFrame()
|
||||
try:
|
||||
return pl.read_parquet(factor_path)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("ETF 复权因子读取失败: %s", e)
|
||||
return pl.DataFrame()
|
||||
|
||||
|
||||
def sync_etf_adj_factor(
|
||||
symbols: list[str],
|
||||
repo: KlineRepository,
|
||||
capset: CapabilitySet,
|
||||
start_time: datetime | None = None,
|
||||
end_time: datetime | None = None,
|
||||
on_chunk_done=None,
|
||||
) -> tuple[int, list[str]]:
|
||||
"""同步 ETF 复权因子;失败由调用方降级为 warning。"""
|
||||
return kline_sync.sync_adj_factor(
|
||||
symbols,
|
||||
repo,
|
||||
capset,
|
||||
start_time=start_time,
|
||||
end_time=end_time,
|
||||
on_chunk_done=on_chunk_done,
|
||||
asset_type="etf",
|
||||
)
|
||||
|
||||
|
||||
def sync_and_persist_etf_daily(
|
||||
repo: KlineRepository,
|
||||
capset: CapabilitySet,
|
||||
count: int | None = None,
|
||||
start_date: datetime | None = None,
|
||||
end_date: datetime | None = None,
|
||||
symbols_override: list[str] | None = None,
|
||||
on_chunk_done: Callable[[int, int], None] | None = None,
|
||||
) -> int:
|
||||
"""同步 ETF 日K到独立 kline_etf_* parquet,并计算 ETF enriched。
|
||||
on_chunk_done(current, total) 每个批次完成后回调。
|
||||
"""
|
||||
if not capset.has(Cap.KLINE_DAILY_BATCH):
|
||||
return 0
|
||||
|
||||
if symbols_override:
|
||||
symbols = sorted(set(s for s in symbols_override if s))
|
||||
else:
|
||||
instruments = repo.get_etf_instruments()
|
||||
if instruments.is_empty():
|
||||
sync_etf_instruments(repo)
|
||||
instruments = repo.get_etf_instruments()
|
||||
if instruments.is_empty() or "symbol" not in instruments.columns:
|
||||
return 0
|
||||
symbols = sorted(set(instruments["symbol"].to_list()))
|
||||
if not symbols:
|
||||
return 0
|
||||
|
||||
lim = capset.limits(Cap.KLINE_DAILY_BATCH)
|
||||
batch_size = preferences.get_index_daily_batch_size()
|
||||
if lim and lim.batch:
|
||||
batch_size = min(batch_size, lim.batch)
|
||||
rpm = lim.rpm if lim else None
|
||||
|
||||
end_time = end_date or datetime.now()
|
||||
start_time = start_date or (end_time - timedelta(days=365))
|
||||
|
||||
total_rows = 0
|
||||
interval = (60.0 / rpm) if rpm else 0
|
||||
chunks = [symbols[i:i + batch_size] for i in range(0, len(symbols), batch_size)]
|
||||
factors = _load_etf_factors(repo)
|
||||
for i, chunk in enumerate(chunks):
|
||||
if i > 0 and interval > 0 and len(chunks) > rpm:
|
||||
import time
|
||||
time.sleep(interval)
|
||||
raw = kline_sync.sync_daily_batch(
|
||||
chunk,
|
||||
count=count,
|
||||
batch_size=None,
|
||||
start_time=start_time,
|
||||
end_time=end_time,
|
||||
)
|
||||
if raw.is_empty():
|
||||
continue
|
||||
|
||||
repo.append_etf_daily(raw)
|
||||
batch_factors = factors.filter(pl.col("symbol").is_in(chunk)) if not factors.is_empty() else factors
|
||||
# ETF 使用复权和通用技术指标;不传 instruments,避免套用 A股涨跌停/连板逻辑。
|
||||
enriched = compute_enriched(raw, factors=batch_factors, instruments=None)
|
||||
repo.append_etf_enriched(enriched)
|
||||
total_rows += raw.height
|
||||
logger.info("etf daily synced: %d/%d chunks, +%d rows", i + 1, len(chunks), raw.height)
|
||||
if on_chunk_done:
|
||||
on_chunk_done(i + 1, len(chunks))
|
||||
del raw, enriched
|
||||
gc.collect()
|
||||
repo.refresh_index_views()
|
||||
return total_rows
|
||||
@@ -0,0 +1,122 @@
|
||||
"""标的维表同步服务。
|
||||
|
||||
盘前 9:10 调用 tf.exchanges.get_instruments("SH"/"SZ"/"BJ", type="stock")
|
||||
获取全量标的元数据,flatten ext 字段,写入 instruments.parquet。
|
||||
|
||||
Starter+ 盘后可用 quotes.get(universes) 顺便补充 name。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import polars as pl
|
||||
|
||||
from app.tickflow.client import get_client
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_EXCHANGES = ["SH", "SZ", "BJ"]
|
||||
|
||||
|
||||
def _flatten_instruments(items: list[dict]) -> list[dict]:
|
||||
"""把 SDK 返回的 Instrument 列表 flatten 成扁平行。"""
|
||||
rows = []
|
||||
for item in items:
|
||||
row = {
|
||||
"symbol": item.get("symbol"),
|
||||
"name": item.get("name"),
|
||||
"code": item.get("code"),
|
||||
"exchange": item.get("exchange"),
|
||||
"region": item.get("region"),
|
||||
"type": item.get("type"),
|
||||
}
|
||||
ext = item.get("ext") or {}
|
||||
row["listing_date"] = ext.get("listing_date")
|
||||
row["total_shares"] = ext.get("total_shares")
|
||||
row["float_shares"] = ext.get("float_shares")
|
||||
row["tick_size"] = ext.get("tick_size")
|
||||
row["limit_up"] = ext.get("limit_up")
|
||||
row["limit_down"] = ext.get("limit_down")
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def sync_instruments(data_dir: Path) -> int:
|
||||
"""全量同步标的维表 → data/instruments/instruments.parquet。
|
||||
|
||||
返回写入的行数。
|
||||
"""
|
||||
tf = get_client()
|
||||
all_rows: list[dict] = []
|
||||
|
||||
for ex in _EXCHANGES:
|
||||
try:
|
||||
items = tf.exchanges.get_instruments(ex, instrument_type="stock")
|
||||
if items:
|
||||
all_rows.extend(_flatten_instruments(items))
|
||||
logger.info("instruments %s: %d stocks", ex, len(items))
|
||||
except Exception as e:
|
||||
logger.warning("get_instruments(%s) failed: %s", ex, e)
|
||||
|
||||
if not all_rows:
|
||||
return 0
|
||||
|
||||
df = pl.DataFrame(all_rows)
|
||||
df = df.with_columns(pl.lit(date.today()).alias("as_of"))
|
||||
|
||||
out = data_dir / "instruments" / "instruments.parquet"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
df.write_parquet(out)
|
||||
|
||||
logger.info("instruments synced: %d rows → %s", df.height, out)
|
||||
return df.height
|
||||
|
||||
|
||||
def enrich_names_from_quotes(
|
||||
data_dir: Path,
|
||||
quotes_data: list[dict],
|
||||
) -> int:
|
||||
"""从 quotes 响应中提取 name,更新 instruments 维表(兜底补充)。
|
||||
|
||||
盘后 quotes.get(universes) 返回的数据中包含 ext.name,
|
||||
用来补充 instruments 中可能缺失的 name。
|
||||
"""
|
||||
if not quotes_data:
|
||||
return 0
|
||||
|
||||
# 构建 symbol → name 映射
|
||||
name_map: dict[str, str] = {}
|
||||
for q in quotes_data:
|
||||
symbol = q.get("symbol", "")
|
||||
ext = q.get("ext") or {}
|
||||
name = ext.get("name") or q.get("name", "")
|
||||
if symbol and name:
|
||||
name_map[symbol] = name
|
||||
|
||||
if not name_map:
|
||||
return 0
|
||||
|
||||
inst_path = data_dir / "instruments" / "instruments.parquet"
|
||||
if not inst_path.exists():
|
||||
return 0
|
||||
|
||||
df = pl.read_parquet(inst_path)
|
||||
|
||||
# 只更新空 name 的行
|
||||
updates = pl.DataFrame({
|
||||
"symbol": list(name_map.keys()),
|
||||
"_new_name": list(name_map.values()),
|
||||
})
|
||||
df = df.join(updates, on="symbol", how="left")
|
||||
df = df.with_columns(
|
||||
pl.when(pl.col("name").is_null() | (pl.col("name") == ""))
|
||||
.then(pl.col("_new_name"))
|
||||
.otherwise(pl.col("name"))
|
||||
.alias("name"),
|
||||
).drop("_new_name")
|
||||
|
||||
df.write_parquet(inst_path)
|
||||
logger.info("instruments name enriched from quotes: %d names", len(name_map))
|
||||
return len(name_map)
|
||||
@@ -0,0 +1,674 @@
|
||||
"""日 K 同步服务(§7.7 Step 1)。
|
||||
|
||||
调度器在 capability 允许下,把符号集合的日 K 批量同步到本地 Parquet。
|
||||
策略:
|
||||
- 日 K 仅使用 `kline.daily.batch`
|
||||
- 除权因子仅使用 `adj_factor`
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import polars as pl
|
||||
|
||||
from app.indicators.pipeline import filter_halt_days
|
||||
from app.tickflow.capabilities import Cap, CapabilitySet
|
||||
from app.tickflow.client import get_client
|
||||
from app.tickflow.repository import KlineRepository
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# 标准列(无论 SDK 返回什么形状,我们把它规范成这套)
|
||||
CANONICAL_DAILY_COLS = [
|
||||
"symbol", "date", "open", "high", "low", "close", "volume", "amount",
|
||||
]
|
||||
|
||||
|
||||
def _normalize_daily(df_in, default_symbol: str | None = None) -> pl.DataFrame:
|
||||
"""把 SDK 返回的 pandas/任意 DataFrame 规范成 canonical 列。"""
|
||||
if df_in is None or len(df_in) == 0:
|
||||
return pl.DataFrame()
|
||||
|
||||
if not isinstance(df_in, pl.DataFrame):
|
||||
df = pl.from_pandas(df_in.reset_index() if hasattr(df_in, "reset_index") else df_in)
|
||||
else:
|
||||
df = df_in
|
||||
|
||||
# 兼容字段名差异
|
||||
rename_map = {
|
||||
"ts_code": "symbol",
|
||||
"trade_date": "date",
|
||||
"vol": "volume",
|
||||
"amt": "amount",
|
||||
"datetime": "date",
|
||||
}
|
||||
df = df.rename({k: v for k, v in rename_map.items() if k in df.columns})
|
||||
|
||||
if "symbol" not in df.columns and default_symbol is not None:
|
||||
df = df.with_columns(pl.lit(default_symbol).alias("symbol"))
|
||||
|
||||
# 类型规范
|
||||
if "date" in df.columns and df.schema["date"] != pl.Date:
|
||||
df = df.with_columns(pl.col("date").cast(pl.Date, strict=False))
|
||||
|
||||
for col in ("open", "high", "low", "close"):
|
||||
if col in df.columns:
|
||||
df = df.with_columns(pl.col(col).cast(pl.Float64, strict=False))
|
||||
for col in ("volume", "amount"):
|
||||
if col in df.columns:
|
||||
df = df.with_columns(pl.col(col).cast(pl.Float64, strict=False))
|
||||
|
||||
# 过滤停牌日 (open/high 为 0; close 可能被填充为前收盘价, 不能用全零判断)
|
||||
df = filter_halt_days(df)
|
||||
|
||||
# 只保留 canonical 列
|
||||
keep = [c for c in CANONICAL_DAILY_COLS if c in df.columns]
|
||||
return df.select(keep)
|
||||
|
||||
|
||||
def sync_daily_batch(symbols: list[str],
|
||||
count: int | None = None,
|
||||
batch_size: int | None = None,
|
||||
rpm: int | None = None,
|
||||
start_time: datetime | None = None,
|
||||
end_time: datetime | None = None,
|
||||
on_chunk_done: Callable[[int, int], None] | None = None) -> pl.DataFrame:
|
||||
"""批量拉取多股日 K。
|
||||
|
||||
优先使用 start_time / end_time 区间 + count=10000,确保覆盖完整时间段。
|
||||
仅传 count 时按条数回溯。
|
||||
"""
|
||||
tf = get_client()
|
||||
out: list[pl.DataFrame] = []
|
||||
interval = (60.0 / rpm) if rpm else 0
|
||||
|
||||
if batch_size is None:
|
||||
chunks = [symbols]
|
||||
else:
|
||||
chunks = [symbols[i:i + batch_size] for i in range(0, len(symbols), batch_size)]
|
||||
|
||||
for i, chunk in enumerate(chunks):
|
||||
if i > 0 and interval > 0 and len(chunks) > rpm:
|
||||
time.sleep(interval)
|
||||
try:
|
||||
if start_time and end_time:
|
||||
raw = tf.klines.batch(
|
||||
chunk, period="1d", adjust="none",
|
||||
start_time=_datetime_to_ms(start_time),
|
||||
end_time=_datetime_to_ms(end_time),
|
||||
count=10000,
|
||||
as_dataframe=True, show_progress=False,
|
||||
)
|
||||
else:
|
||||
raw = tf.klines.batch(chunk, period="1d", count=count or 250, adjust="none",
|
||||
as_dataframe=True, show_progress=False)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("batch fetch failed for %d symbols: %s", len(chunk), e)
|
||||
continue
|
||||
|
||||
# 兼容两种形态:dict[sym → df] 和扁平 df
|
||||
if isinstance(raw, dict):
|
||||
for sym, sub in raw.items():
|
||||
if sub is None or len(sub) == 0:
|
||||
continue
|
||||
out.append(_normalize_daily(sub, default_symbol=sym))
|
||||
elif raw is not None and len(raw) > 0:
|
||||
out.append(_normalize_daily(raw))
|
||||
|
||||
if on_chunk_done:
|
||||
on_chunk_done(i + 1, len(chunks))
|
||||
|
||||
if not out:
|
||||
return pl.DataFrame()
|
||||
return pl.concat(out, how="diagonal_relaxed")
|
||||
|
||||
|
||||
def sync_and_persist_daily_batch(
|
||||
symbols: list[str],
|
||||
repo: KlineRepository,
|
||||
capset: CapabilitySet,
|
||||
count: int | None = None,
|
||||
start_date: datetime | None = None,
|
||||
end_date: datetime | None = None,
|
||||
on_chunk_done: Callable[[int, int], None] | None = None,
|
||||
) -> int:
|
||||
"""批量同步日 K 并落到 Parquet。返回写入的行数。
|
||||
|
||||
start_date/end_date: 外部传入的时间范围(由 pipeline 根据已有数据计算)。
|
||||
未传入时默认拉最近 1 年。
|
||||
"""
|
||||
if not symbols or not capset.has(Cap.KLINE_DAILY_BATCH):
|
||||
return 0
|
||||
|
||||
lim = capset.limits(Cap.KLINE_DAILY_BATCH)
|
||||
batch_size = lim.batch if lim and lim.batch else 100
|
||||
rpm = lim.rpm if lim else None
|
||||
|
||||
end_time = end_date or datetime.now()
|
||||
start_time = start_date or (end_time - timedelta(days=365))
|
||||
|
||||
df = sync_daily_batch(
|
||||
symbols, count=count, batch_size=batch_size, rpm=rpm,
|
||||
start_time=start_time, end_time=end_time,
|
||||
on_chunk_done=on_chunk_done,
|
||||
)
|
||||
|
||||
if df.is_empty():
|
||||
return 0
|
||||
|
||||
repo.append_daily(df)
|
||||
|
||||
try:
|
||||
d = repo.store.data_dir.as_posix()
|
||||
repo.db.execute(
|
||||
f"""CREATE OR REPLACE VIEW kline_daily AS
|
||||
SELECT * FROM read_parquet('{d}/kline_daily/**/*.parquet', union_by_name=true)"""
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("refresh view failed: %s", e)
|
||||
|
||||
return df.height
|
||||
|
||||
|
||||
def sync_daily_by_quotes(repo: KlineRepository) -> int:
|
||||
"""用实时行情接口拉全市场当日数据,覆写 kline_daily 今天分区。
|
||||
|
||||
一个请求覆盖 ~5500 只股票,比 batch K-line 快几个数量级。
|
||||
返回写入的行数。
|
||||
"""
|
||||
from datetime import date as _date
|
||||
|
||||
from app.tickflow.client import get_client
|
||||
|
||||
tf = get_client()
|
||||
try:
|
||||
resp = tf.quotes.get_by_universes(universes=["CN_Equity_A"])
|
||||
except Exception as e:
|
||||
logger.warning("get_by_universes failed: %s", e)
|
||||
return 0
|
||||
|
||||
if not resp:
|
||||
logger.warning("get_by_universes returned empty")
|
||||
return 0
|
||||
|
||||
records = []
|
||||
for q in resp:
|
||||
ext = q.get("ext") or {}
|
||||
records.append({
|
||||
"symbol": q.get("symbol"),
|
||||
"open": q.get("open"),
|
||||
"high": q.get("high"),
|
||||
"low": q.get("low"),
|
||||
"close": q.get("last_price"),
|
||||
"volume": q.get("volume"),
|
||||
"amount": q.get("amount"),
|
||||
})
|
||||
|
||||
df = pl.DataFrame(records)
|
||||
if df.is_empty():
|
||||
return 0
|
||||
|
||||
today = _date.today()
|
||||
daily_df = df.with_columns(pl.lit(today).cast(pl.Date).alias("date"))
|
||||
|
||||
# 过滤停牌 (open/high 为 0; close 可能被填充为前收盘价, 不能用全零判断)
|
||||
daily_df = filter_halt_days(daily_df)
|
||||
|
||||
repo.flush_live_daily(daily_df)
|
||||
logger.info("sync_daily_by_quotes: %d symbols flushed for %s", daily_df.height, today)
|
||||
return daily_df.height
|
||||
|
||||
|
||||
def _normalize_adj_factor(raw) -> pl.DataFrame:
|
||||
"""Normalize SDK ex_factors response to symbol/trade_date/ex_factor."""
|
||||
if raw is None or len(raw) == 0:
|
||||
return pl.DataFrame()
|
||||
if isinstance(raw, dict):
|
||||
rows: list[dict] = []
|
||||
for sym, values in raw.items():
|
||||
for item in values or []:
|
||||
row = dict(item or {})
|
||||
row.setdefault("symbol", sym)
|
||||
rows.append(row)
|
||||
df = pl.DataFrame(rows) if rows else pl.DataFrame()
|
||||
elif isinstance(raw, pl.DataFrame):
|
||||
df = raw
|
||||
else:
|
||||
df = pl.from_pandas(raw.reset_index() if hasattr(raw, "reset_index") else raw)
|
||||
if df.is_empty():
|
||||
return df
|
||||
# rename: timestamp/date → trade_date, adj_factor → ex_factor
|
||||
# 注意: 新版 SDK 可能同时返回 timestamp 和 trade_date (或 adj_factor 和 ex_factor),
|
||||
# 直接 rename 会产生重复列报错。仅当目标列不存在时才 rename。
|
||||
rename_map: dict[str, str] = {}
|
||||
for src, dst in (("timestamp", "trade_date"), ("date", "trade_date"), ("adj_factor", "ex_factor")):
|
||||
if src in df.columns and dst not in df.columns:
|
||||
rename_map[src] = dst
|
||||
df = df.rename(rename_map)
|
||||
if "trade_date" in df.columns:
|
||||
if df.schema["trade_date"] in {pl.Int64, pl.Int32, pl.UInt64, pl.UInt32, pl.Float64, pl.Float32}:
|
||||
df = df.with_columns(
|
||||
pl.from_epoch(pl.col("trade_date").cast(pl.Int64), time_unit="ms").dt.date().alias("trade_date")
|
||||
)
|
||||
else:
|
||||
df = df.with_columns(pl.col("trade_date").cast(pl.Date, strict=False))
|
||||
if "ex_factor" in df.columns:
|
||||
df = df.with_columns(pl.col("ex_factor").cast(pl.Float64, strict=False))
|
||||
cols = [c for c in ["symbol", "trade_date", "ex_factor"] if c in df.columns]
|
||||
if len(cols) < 3:
|
||||
return pl.DataFrame()
|
||||
return df.select(cols).drop_nulls()
|
||||
|
||||
|
||||
def sync_adj_factor(symbols: list[str], repo: KlineRepository,
|
||||
capset: CapabilitySet,
|
||||
start_time: datetime | None = None,
|
||||
end_time: datetime | None = None,
|
||||
on_chunk_done: Callable[[int, int], None] | None = None,
|
||||
asset_type: str = "stock") -> tuple[int, list[str]]:
|
||||
"""同步除权因子(Starter+)。SDK 接口:`tf.klines.ex_factors(symbols=...)`。
|
||||
|
||||
支持增量: 传 start_time/end_time 只拉取该时间范围内的新除权事件。
|
||||
返回 (写入行数, 受影响的 symbol 列表) — 供 enriched 局部重算使用。
|
||||
"""
|
||||
if not capset.has(Cap.ADJ_FACTOR) or not symbols:
|
||||
return 0, []
|
||||
|
||||
tf = get_client()
|
||||
lim = capset.limits(Cap.ADJ_FACTOR)
|
||||
batch_size = lim.batch if lim and lim.batch else 50
|
||||
rpm = lim.rpm if lim else 30
|
||||
interval = 60.0 / rpm if rpm else 0
|
||||
|
||||
# 构建 SDK 参数
|
||||
sdk_kwargs: dict = {"as_dataframe": True, "batch_size": batch_size, "show_progress": False}
|
||||
if start_time:
|
||||
sdk_kwargs["start_time"] = _datetime_to_ms(start_time)
|
||||
if end_time:
|
||||
sdk_kwargs["end_time"] = _datetime_to_ms(end_time)
|
||||
|
||||
chunks = [symbols[i:i + batch_size] for i in range(0, len(symbols), batch_size)]
|
||||
all_dfs: list[pl.DataFrame] = []
|
||||
|
||||
for i, chunk in enumerate(chunks):
|
||||
if i > 0 and interval > 0 and len(chunks) > rpm:
|
||||
time.sleep(interval)
|
||||
try:
|
||||
raw = tf.klines.ex_factors(chunk, **sdk_kwargs)
|
||||
normalized = _normalize_adj_factor(raw)
|
||||
if not normalized.is_empty():
|
||||
all_dfs.append(normalized)
|
||||
logger.debug("adj_factor chunk %d/%d: %d symbols", i + 1, len(chunks), len(chunk))
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("adj_factor chunk %d failed: %s", i + 1, e)
|
||||
|
||||
if on_chunk_done:
|
||||
on_chunk_done(i + 1, len(chunks))
|
||||
|
||||
if not all_dfs:
|
||||
return 0, []
|
||||
|
||||
new_data = pl.concat(all_dfs, how="diagonal_relaxed") if len(all_dfs) > 1 else all_dfs[0]
|
||||
|
||||
# 提取受影响的 symbol 列表(合并前)
|
||||
affected = new_data["symbol"].unique().to_list()
|
||||
|
||||
factor_dir = "adj_factor_etf" if asset_type == "etf" else "adj_factor"
|
||||
out = repo.store.data_dir / factor_dir / "all.parquet"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if out.exists():
|
||||
existing = pl.read_parquet(out)
|
||||
before = existing.height
|
||||
merged = pl.concat([existing, new_data]).unique(
|
||||
subset=["symbol", "trade_date"], keep="last",
|
||||
).sort(["symbol", "trade_date"])
|
||||
merged.write_parquet(out)
|
||||
added = merged.height - before
|
||||
logger.info("adj_factor merged: %d total (+%d new), %d/%d symbols",
|
||||
merged.height, added, new_data.height, len(symbols))
|
||||
return added, affected
|
||||
else:
|
||||
new_data.sort(["symbol", "trade_date"]).write_parquet(out)
|
||||
logger.info("adj_factor synced: %d rows (%d symbols)", new_data.height, len(symbols))
|
||||
return new_data.height, affected
|
||||
|
||||
|
||||
# ===== 分钟 K 同步 =====
|
||||
|
||||
CANONICAL_MINUTE_COLS = [
|
||||
"symbol", "datetime", "open", "high", "low", "close", "volume", "amount",
|
||||
]
|
||||
|
||||
|
||||
def _normalize_minute(df_in, default_symbol: str | None = None) -> pl.DataFrame:
|
||||
"""把 SDK 返回的分钟 K 数据规范成 canonical 列。"""
|
||||
if df_in is None or len(df_in) == 0:
|
||||
return pl.DataFrame()
|
||||
|
||||
if not isinstance(df_in, pl.DataFrame):
|
||||
df = pl.from_pandas(df_in.reset_index() if hasattr(df_in, "reset_index") else df_in)
|
||||
else:
|
||||
df = df_in
|
||||
|
||||
rename_map = {
|
||||
"ts_code": "symbol",
|
||||
"vol": "volume",
|
||||
"amt": "amount",
|
||||
}
|
||||
df = df.rename({k: v for k, v in rename_map.items() if k in df.columns})
|
||||
|
||||
# datetime 列:优先用 timestamp(毫秒精度),其次 trade_time
|
||||
if "timestamp" in df.columns:
|
||||
df = df.with_columns(
|
||||
pl.from_epoch("timestamp", time_unit="ms").alias("datetime"),
|
||||
).drop("timestamp")
|
||||
for drop_col in ("trade_time", "trade_date"):
|
||||
if drop_col in df.columns:
|
||||
df = df.drop(drop_col)
|
||||
elif "trade_time" in df.columns:
|
||||
df = df.rename({"trade_time": "datetime"})
|
||||
if "trade_date" in df.columns:
|
||||
df = df.drop("trade_date")
|
||||
elif "trade_date" in df.columns:
|
||||
df = df.rename({"trade_date": "datetime"})
|
||||
|
||||
if "symbol" not in df.columns and default_symbol is not None:
|
||||
df = df.with_columns(pl.lit(default_symbol).alias("symbol"))
|
||||
|
||||
# 类型规范:统一转 Datetime('us')
|
||||
if "datetime" in df.columns:
|
||||
dt_type = df.schema["datetime"]
|
||||
if not isinstance(dt_type, pl.Datetime) or dt_type.time_unit != "us":
|
||||
df = df.with_columns(pl.col("datetime").cast(pl.Datetime("us"), strict=False))
|
||||
|
||||
for col in ("open", "high", "low", "close"):
|
||||
if col in df.columns:
|
||||
df = df.with_columns(pl.col(col).cast(pl.Float64, strict=False))
|
||||
for col in ("volume", "amount"):
|
||||
if col in df.columns:
|
||||
df = df.with_columns(pl.col(col).cast(pl.Float64, strict=False))
|
||||
|
||||
keep = [c for c in CANONICAL_MINUTE_COLS if c in df.columns]
|
||||
return df.select(keep)
|
||||
|
||||
|
||||
def _datetime_to_ms(dt: datetime) -> int:
|
||||
"""datetime → 毫秒时间戳 (供 SDK start_time / end_time 使用)。"""
|
||||
return int(dt.timestamp() * 1000)
|
||||
|
||||
|
||||
def sync_minute_batch(
|
||||
symbols: list[str],
|
||||
start_time: datetime | None = None,
|
||||
end_time: datetime | None = None,
|
||||
count: int | None = None,
|
||||
batch_size: int | None = None,
|
||||
rpm: int | None = None,
|
||||
on_chunk_done: Callable[[int, int], None] | None = None,
|
||||
) -> pl.DataFrame:
|
||||
"""批量拉取多股分钟 K。
|
||||
|
||||
优先使用 start_time / end_time 区间, 确保所有标的覆盖同一时间段。
|
||||
count 仅作为 fallback 保留。
|
||||
on_chunk_done(current, total) 每个 chunk 完成后回调。
|
||||
"""
|
||||
tf = get_client()
|
||||
out: list[pl.DataFrame] = []
|
||||
interval = (60.0 / rpm) if rpm else 0
|
||||
|
||||
if batch_size is None:
|
||||
chunks = [symbols]
|
||||
else:
|
||||
chunks = [symbols[i:i + batch_size] for i in range(0, len(symbols), batch_size)]
|
||||
|
||||
for i, chunk in enumerate(chunks):
|
||||
if i > 0 and interval > 0 and len(chunks) > rpm:
|
||||
time.sleep(interval)
|
||||
try:
|
||||
if start_time and end_time:
|
||||
raw = tf.klines.batch(
|
||||
chunk, period="1m",
|
||||
start_time=_datetime_to_ms(start_time),
|
||||
end_time=_datetime_to_ms(end_time),
|
||||
count=10000,
|
||||
as_dataframe=True, show_progress=False,
|
||||
)
|
||||
else:
|
||||
raw = tf.klines.batch(chunk, period="1m", count=count or 1200,
|
||||
as_dataframe=True, show_progress=False)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("minute batch fetch failed for %d symbols: %s", len(chunk), e)
|
||||
continue
|
||||
|
||||
if isinstance(raw, dict):
|
||||
for sym, sub in raw.items():
|
||||
if sub is None or len(sub) == 0:
|
||||
continue
|
||||
out.append(_normalize_minute(sub, default_symbol=sym))
|
||||
elif raw is not None and len(raw) > 0:
|
||||
out.append(_normalize_minute(raw))
|
||||
|
||||
if on_chunk_done:
|
||||
on_chunk_done(i + 1, len(chunks))
|
||||
|
||||
if not out:
|
||||
return pl.DataFrame()
|
||||
return pl.concat(out, how="diagonal_relaxed")
|
||||
|
||||
|
||||
def fetch_minute_single(symbol: str, trade_date: date) -> pl.DataFrame:
|
||||
"""从 TickFlow 实时拉取单股单日分钟 K(不写入本地)。"""
|
||||
from datetime import datetime
|
||||
start_time = datetime(trade_date.year, trade_date.month, trade_date.day, 9, 25, 0)
|
||||
end_time = datetime(trade_date.year, trade_date.month, trade_date.day, 15, 5, 0)
|
||||
tf = get_client()
|
||||
try:
|
||||
raw = tf.klines.batch(
|
||||
[symbol], period="1m",
|
||||
start_time=_datetime_to_ms(start_time),
|
||||
end_time=_datetime_to_ms(end_time),
|
||||
count=10000,
|
||||
as_dataframe=True, show_progress=False,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("fetch_minute_single(%s, %s) failed: %s", symbol, trade_date, e)
|
||||
return pl.DataFrame()
|
||||
|
||||
if isinstance(raw, dict):
|
||||
sub = raw.get(symbol)
|
||||
return _normalize_minute(sub) if sub is not None and len(sub) > 0 else pl.DataFrame()
|
||||
if raw is not None and len(raw) > 0:
|
||||
return _normalize_minute(raw)
|
||||
return pl.DataFrame()
|
||||
|
||||
|
||||
def fetch_adj_factor_single(symbol: str) -> pl.DataFrame:
|
||||
"""从 TickFlow 实时拉取单股除权因子(不写入本地), 用于单股 K 线即时前复权。
|
||||
|
||||
返回结构: symbol, trade_date, ex_factor (空 DataFrame 表示无除权事件或拉取失败)。
|
||||
与 _apply_adj_factor / compute_enriched 的 factors 参数格式一致。
|
||||
"""
|
||||
tf = get_client()
|
||||
try:
|
||||
raw = tf.klines.ex_factors([symbol], as_dataframe=True, show_progress=False)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("fetch_adj_factor_single(%s) failed: %s", symbol, e)
|
||||
return pl.DataFrame()
|
||||
return _normalize_adj_factor(raw)
|
||||
|
||||
|
||||
def _latest_minute_datetime(repo: KlineRepository) -> datetime | None:
|
||||
"""本地分钟 K 数据的最新时间。"""
|
||||
try:
|
||||
res = repo.execute_one("SELECT max(datetime) FROM kline_minute")
|
||||
if res and res[0]:
|
||||
d = res[0]
|
||||
if isinstance(d, datetime):
|
||||
return d
|
||||
return datetime.fromisoformat(str(d))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _cleanup_null_datetime_minute(repo: KlineRepository) -> None:
|
||||
"""检测并清除 datetime 全为 null 的旧版分钟 K 数据(迁移用)。"""
|
||||
minute_dir = repo.store.data_dir / "kline_minute"
|
||||
if not minute_dir.exists():
|
||||
return
|
||||
try:
|
||||
row = repo.execute_one(
|
||||
"SELECT count(*) AS total, count(datetime) AS non_null FROM kline_minute"
|
||||
)
|
||||
if row and row[0] > 0 and (row[1] is None or row[1] == 0):
|
||||
# 全部 datetime 为 null — 清除所有分钟 K parquet
|
||||
n = 0
|
||||
for f in minute_dir.rglob("*.parquet"):
|
||||
f.unlink()
|
||||
n += 1
|
||||
logger.info("cleaned %d corrupted minute-K parquet files (null datetime)", n)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("minute cleanup check failed: %s", e)
|
||||
|
||||
|
||||
def _migrate_symbol_to_date_partition(repo: KlineRepository) -> None:
|
||||
"""将旧版 symbol= 分区迁移为 date= 分区。迁移完成后删除旧目录。"""
|
||||
minute_dir = repo.store.data_dir / "kline_minute"
|
||||
if not minute_dir.exists():
|
||||
return
|
||||
|
||||
old_dirs = [d for d in minute_dir.iterdir() if d.is_dir() and d.name.startswith("symbol=")]
|
||||
if not old_dirs:
|
||||
return
|
||||
|
||||
logger.info("migrating %d symbol-partitioned minute-K dirs to date partition…", len(old_dirs))
|
||||
|
||||
all_frames: list[pl.DataFrame] = []
|
||||
for sym_dir in old_dirs:
|
||||
for pq in sym_dir.glob("*.parquet"):
|
||||
try:
|
||||
df = pl.read_parquet(pq)
|
||||
if "datetime" in df.columns:
|
||||
df = df.filter(pl.col("datetime").is_not_null())
|
||||
if not df.is_empty():
|
||||
all_frames.append(df)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
if not all_frames:
|
||||
# 数据全部不可用,直接删旧目录
|
||||
for d in old_dirs:
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
for f in d.rglob("*"):
|
||||
if f.is_file():
|
||||
f.unlink()
|
||||
d.rmdir()
|
||||
return
|
||||
|
||||
combined = pl.concat(all_frames, how="diagonal_relaxed")
|
||||
combined = combined.unique(subset=["symbol", "datetime"], keep="last")
|
||||
|
||||
# 按日期写新分区
|
||||
combined = combined.with_columns(pl.col("datetime").dt.date().alias("_trade_date"))
|
||||
for day_df in combined.partition_by("_trade_date"):
|
||||
trade_date = day_df["_trade_date"][0]
|
||||
out = minute_dir / f"date={trade_date}" / "part.parquet"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
day_df = day_df.drop("_trade_date").sort("symbol", "datetime")
|
||||
day_df.write_parquet(out)
|
||||
|
||||
# 删旧目录
|
||||
for d in old_dirs:
|
||||
for f in d.rglob("*"):
|
||||
if f.is_file():
|
||||
f.unlink()
|
||||
# 移除空目录
|
||||
try:
|
||||
d.rmdir()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
logger.info("minute-K migration done: %d rows migrated", combined.height)
|
||||
|
||||
|
||||
def sync_and_persist_minute(
|
||||
symbols: list[str],
|
||||
repo: KlineRepository,
|
||||
capset: CapabilitySet,
|
||||
days: int = 5,
|
||||
on_chunk_done: Callable[[int, int], None] | None = None,
|
||||
) -> int:
|
||||
"""同步分钟 K 并存到 Parquet(仅 raw,不前复权)。返回写入行数。
|
||||
|
||||
使用 start_time / end_time 区间拉取, 确保所有标的覆盖同一时间段。
|
||||
on_chunk_done(current, total) 每个 chunk 完成后回调。
|
||||
"""
|
||||
if not symbols or not capset.has(Cap.KLINE_MINUTE_BATCH):
|
||||
return 0
|
||||
|
||||
# 迁移:旧版 _normalize_minute 未转换 timestamp→datetime,导致全部 datetime 为 null
|
||||
# 检测到后直接清除(这些数据无法使用)
|
||||
_cleanup_null_datetime_minute(repo)
|
||||
|
||||
# 迁移:旧版按 symbol= 分区转为 date= 分区
|
||||
_migrate_symbol_to_date_partition(repo)
|
||||
|
||||
now = datetime.now()
|
||||
|
||||
# 计算时间区间: 首次拉取回溯 N 天, 增量从最后数据时间开始
|
||||
last_dt = _latest_minute_datetime(repo)
|
||||
if last_dt:
|
||||
start_time = last_dt
|
||||
else:
|
||||
start_time = now - timedelta(days=days)
|
||||
end_time = now
|
||||
|
||||
lim = capset.limits(Cap.KLINE_MINUTE_BATCH)
|
||||
batch_size = lim.batch if lim and lim.batch else 100
|
||||
rpm = lim.rpm if lim else 30
|
||||
|
||||
df = sync_minute_batch(symbols, start_time=start_time, end_time=end_time,
|
||||
batch_size=batch_size, rpm=rpm,
|
||||
on_chunk_done=on_chunk_done)
|
||||
if df.is_empty():
|
||||
return 0
|
||||
|
||||
# 按日期分区写: data/kline_minute/date={YYYY-MM-DD}/part.parquet
|
||||
df = df.with_columns(
|
||||
pl.col("datetime").dt.date().alias("_trade_date")
|
||||
)
|
||||
written = 0
|
||||
for day_df in df.partition_by("_trade_date"):
|
||||
trade_date = day_df["_trade_date"][0]
|
||||
out = repo.store.data_dir / "kline_minute" / f"date={trade_date}" / "part.parquet"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
if out.exists():
|
||||
existing = pl.read_parquet(out)
|
||||
if "datetime" in existing.columns:
|
||||
existing = existing.filter(pl.col("datetime").is_not_null())
|
||||
day_df = pl.concat([existing, day_df.drop("_trade_date")]).unique(
|
||||
subset=["symbol", "datetime"], keep="last",
|
||||
)
|
||||
else:
|
||||
day_df = day_df.drop("_trade_date")
|
||||
day_df = day_df.sort("symbol", "datetime")
|
||||
day_df.write_parquet(out)
|
||||
written += day_df.height
|
||||
|
||||
# 刷新视图
|
||||
try:
|
||||
d = repo.store.data_dir.as_posix()
|
||||
repo.db.execute(
|
||||
f"""CREATE OR REPLACE VIEW kline_minute AS
|
||||
SELECT * FROM read_parquet('{d}/kline_minute/**/*.parquet', union_by_name=true)"""
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("refresh kline_minute view failed: %s", e)
|
||||
|
||||
logger.info("minute K synced: %d rows (%d symbols)", written, len(symbols))
|
||||
return written
|
||||
@@ -0,0 +1,576 @@
|
||||
"""市场总览数据装配(与 HTTP Request 解耦)。
|
||||
|
||||
本模块由 `app.api.overview._build_overview` 抽离而来,目的是让「大盘复盘」
|
||||
等无 Request 的调用方(定时任务、复盘服务)也能复用同一套聚合逻辑。
|
||||
|
||||
行为与原 `_build_overview` 完全一致,仅把对 `request.app.state.{repo,
|
||||
quote_service,depth_service}` 的依赖改为显式参数。
|
||||
|
||||
公共入口:
|
||||
build_market_overview(repo, quote_service, depth_service, as_of)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
import polars as pl
|
||||
|
||||
from app.services.ext_data import ExtConfig, ExtConfigStore
|
||||
from app.services.screener import ScreenerService
|
||||
|
||||
# ================================================================
|
||||
# 常量(与 overview.py 保持同步;复盘复盘仅 A 股核心指数)
|
||||
# ================================================================
|
||||
|
||||
CORE_INDEX_NAMES = {
|
||||
"000001.SH": "上证指数",
|
||||
"399001.SZ": "深证成指",
|
||||
"399006.SZ": "创业板指",
|
||||
"000680.SH": "科创综指",
|
||||
}
|
||||
CORE_INDEX_SYMBOLS = tuple(CORE_INDEX_NAMES.keys())
|
||||
|
||||
_DIMENSION_SEP = re.compile(r"[、,,;;|/\s]+")
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 通用工具
|
||||
# ================================================================
|
||||
|
||||
def _finite(v: Any) -> float | None:
|
||||
if v is None:
|
||||
return None
|
||||
try:
|
||||
f = float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return f if math.isfinite(f) else None
|
||||
|
||||
|
||||
def _json_safe(value: Any) -> Any:
|
||||
if isinstance(value, dict):
|
||||
return {k: _json_safe(v) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_json_safe(v) for v in value]
|
||||
if isinstance(value, float) and not math.isfinite(value):
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def _board(symbol: str) -> str:
|
||||
if symbol.endswith(".BJ"):
|
||||
return "北交所"
|
||||
if symbol.startswith(("300", "301")):
|
||||
return "创业板"
|
||||
if symbol.startswith(("688", "689")):
|
||||
return "科创板"
|
||||
if symbol.endswith(".SH"):
|
||||
return "沪主板"
|
||||
if symbol.endswith(".SZ"):
|
||||
return "深主板"
|
||||
return "其他"
|
||||
|
||||
|
||||
def _score(value: float, low: float, high: float) -> int:
|
||||
if high <= low:
|
||||
return 50
|
||||
return max(0, min(100, round((value - low) / (high - low) * 100)))
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 指数行情(实时 quote_service 优先,回退 kline_index_daily SQL)
|
||||
# ================================================================
|
||||
|
||||
def _quote_status(quote_service) -> dict:
|
||||
qs = quote_service
|
||||
if not qs:
|
||||
return {"enabled": False, "running": False, "quote_age_ms": None, "is_trading_hours": False}
|
||||
return qs.status()
|
||||
|
||||
|
||||
def _index_quotes(repo, quote_service, as_of: date | None = None) -> list[dict]:
|
||||
rows: list[dict] = []
|
||||
if quote_service and as_of is None:
|
||||
df = quote_service.get_index_quotes(list(CORE_INDEX_SYMBOLS))
|
||||
if not df.is_empty():
|
||||
rows = df.to_dicts()
|
||||
|
||||
if not rows and repo:
|
||||
placeholders = ", ".join("?" for _ in CORE_INDEX_SYMBOLS)
|
||||
try:
|
||||
db_rows = repo.execute_all(
|
||||
f"""
|
||||
WITH ranked AS (
|
||||
SELECT symbol, date, close,
|
||||
row_number() OVER (PARTITION BY symbol ORDER BY date DESC) AS rn
|
||||
FROM kline_index_daily
|
||||
WHERE symbol IN ({placeholders})
|
||||
AND (? IS NULL OR date <= ?)
|
||||
), latest AS (
|
||||
SELECT symbol,
|
||||
max(CASE WHEN rn = 1 THEN date END) AS date,
|
||||
max(CASE WHEN rn = 1 THEN close END) AS last_price,
|
||||
max(CASE WHEN rn = 2 THEN close END) AS prev_close
|
||||
FROM ranked
|
||||
WHERE rn <= 2
|
||||
GROUP BY symbol
|
||||
)
|
||||
SELECT symbol, date, last_price, prev_close
|
||||
FROM latest
|
||||
""",
|
||||
[*CORE_INDEX_SYMBOLS, as_of, as_of],
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
db_rows = []
|
||||
for symbol, dt, last_price, prev_close in db_rows:
|
||||
change_amount = None
|
||||
change_pct = None
|
||||
lp = _finite(last_price)
|
||||
pc = _finite(prev_close)
|
||||
if lp is not None and pc not in (None, 0):
|
||||
change_amount = lp - pc
|
||||
change_pct = change_amount / pc * 100
|
||||
rows.append({
|
||||
"symbol": symbol,
|
||||
"name": CORE_INDEX_NAMES.get(symbol),
|
||||
"date": str(dt) if dt else None,
|
||||
"last_price": lp,
|
||||
"close": lp,
|
||||
"prev_close": pc,
|
||||
"change_amount": change_amount,
|
||||
"change_pct": change_pct,
|
||||
})
|
||||
|
||||
by_symbol = {r.get("symbol"): r for r in rows}
|
||||
out = []
|
||||
for symbol in CORE_INDEX_SYMBOLS:
|
||||
r = by_symbol.get(symbol, {"symbol": symbol})
|
||||
out.append({
|
||||
"symbol": symbol,
|
||||
"name": r.get("name") or CORE_INDEX_NAMES[symbol],
|
||||
"last_price": _finite(r.get("last_price") if r.get("last_price") is not None else r.get("close")),
|
||||
"change_pct": _finite(r.get("change_pct")),
|
||||
"change_amount": _finite(r.get("change_amount")),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 扩展数据(行业 / 概念)维度聚合
|
||||
# ================================================================
|
||||
|
||||
def _dimension_field(config: ExtConfig, kind: str) -> str | None:
|
||||
candidates = ["概念", "concept", "theme"] if kind == "concept" else ["行业", "industry", "sector"]
|
||||
for candidate in candidates:
|
||||
needle = candidate.lower()
|
||||
for field in config.fields:
|
||||
haystack = f"{field.name} {field.label}".lower()
|
||||
if needle in haystack:
|
||||
return field.name
|
||||
return None
|
||||
|
||||
|
||||
def _ext_files(data_dir, config: ExtConfig) -> list[str]:
|
||||
base = data_dir / "ext_data" / config.id
|
||||
if config.mode == "timeseries":
|
||||
root = base / "timeseries"
|
||||
return [str(p) for p in sorted(root.rglob("*.parquet")) if p.is_file()]
|
||||
return [str(p) for p in sorted(base.glob("*.parquet")) if p.is_file()]
|
||||
|
||||
|
||||
def _read_ext_rows(data_dir, config: ExtConfig, dimension_field: str) -> list[dict]:
|
||||
files = _ext_files(data_dir, config)
|
||||
if not files:
|
||||
return []
|
||||
try:
|
||||
df = pl.read_parquet(files, hive_partitioning=True)
|
||||
except TypeError:
|
||||
try:
|
||||
df = pl.read_parquet(files)
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
if df.is_empty() or dimension_field not in df.columns:
|
||||
return []
|
||||
|
||||
if config.mode == "timeseries" and "date" in df.columns:
|
||||
latest = df.get_column("date").max()
|
||||
if latest is not None:
|
||||
df = df.filter(pl.col("date") == latest)
|
||||
|
||||
symbol_cols = ["symbol", "code", "股票代码", "代码"]
|
||||
for mapping in (config.symbol_map, config.code_map):
|
||||
if isinstance(mapping, dict) and mapping.get("type") == "mapped" and mapping.get("col"):
|
||||
symbol_cols.append(str(mapping["col"]))
|
||||
cols = []
|
||||
for col in [dimension_field, *symbol_cols]:
|
||||
if col in df.columns and col not in cols:
|
||||
cols.append(col)
|
||||
return df.select(cols).to_dicts()
|
||||
|
||||
|
||||
def _dimension_values(raw: Any) -> list[str]:
|
||||
if raw is None:
|
||||
return []
|
||||
values = [v.strip() for v in _DIMENSION_SEP.split(str(raw).strip()) if v.strip()]
|
||||
return values
|
||||
|
||||
|
||||
def _symbol_keys(row: dict, config: ExtConfig) -> list[str]:
|
||||
fields = ["symbol", "code", "股票代码", "代码"]
|
||||
for mapping in (config.symbol_map, config.code_map):
|
||||
if isinstance(mapping, dict) and mapping.get("type") == "mapped" and mapping.get("col"):
|
||||
fields.append(str(mapping["col"]))
|
||||
|
||||
keys: list[str] = []
|
||||
for field in fields:
|
||||
raw = row.get(field)
|
||||
if raw is None:
|
||||
continue
|
||||
text = str(raw).strip().upper()
|
||||
if not text:
|
||||
continue
|
||||
keys.append(text)
|
||||
if "." in text:
|
||||
keys.append(text.split(".", 1)[0])
|
||||
return keys
|
||||
|
||||
|
||||
def _dimension_rank(rows: list[dict], repo, kind: str, limit: int = 5, level: int | None = None) -> dict:
|
||||
if not rows:
|
||||
return {"leading": [], "lagging": []}
|
||||
|
||||
quote_map: dict[str, dict] = {}
|
||||
for row in rows:
|
||||
symbol = str(row.get("symbol") or "").strip().upper()
|
||||
if not symbol:
|
||||
continue
|
||||
quote_map[symbol] = row
|
||||
quote_map[symbol.split(".", 1)[0]] = row
|
||||
|
||||
store = ExtConfigStore(repo.store.data_dir)
|
||||
groups: dict[str, dict[str, dict]] = {}
|
||||
for config in store.load_all():
|
||||
field = _dimension_field(config, kind)
|
||||
if not field:
|
||||
continue
|
||||
for ext_row in _read_ext_rows(repo.store.data_dir, config, field):
|
||||
quote = None
|
||||
for key in _symbol_keys(ext_row, config):
|
||||
quote = quote_map.get(key)
|
||||
if quote:
|
||||
break
|
||||
if not quote:
|
||||
continue
|
||||
symbol = str(quote.get("symbol") or "")
|
||||
for value in _dimension_values(ext_row.get(field)):
|
||||
# 行业按 "-" 拆分级: "银行-银行-股份制银行" → level=2 取"银行"(二级)
|
||||
if level is not None and "-" in value:
|
||||
parts = value.split("-")
|
||||
value = parts[level - 1] if level <= len(parts) else parts[-1]
|
||||
groups.setdefault(value, {})[symbol] = quote
|
||||
|
||||
items = []
|
||||
for name, by_symbol in groups.items():
|
||||
stocks = list(by_symbol.values())
|
||||
changes = [_finite(s.get("change_pct")) for s in stocks]
|
||||
changes = [v for v in changes if v is not None]
|
||||
if not changes:
|
||||
continue
|
||||
leader = max(stocks, key=lambda s: _finite(s.get("change_pct")) or -999)
|
||||
items.append({
|
||||
"name": name,
|
||||
"count": len(stocks),
|
||||
"avg_pct": sum(changes) / len(changes),
|
||||
"up_count": sum(1 for v in changes if v > 0),
|
||||
"down_count": sum(1 for v in changes if v < 0),
|
||||
"amount": sum(_finite(s.get("amount")) or 0 for s in stocks),
|
||||
"leader": {
|
||||
"symbol": leader.get("symbol"),
|
||||
"name": leader.get("name"),
|
||||
"change_pct": _finite(leader.get("change_pct")),
|
||||
},
|
||||
})
|
||||
|
||||
leading = sorted(items, key=lambda x: x["avg_pct"], reverse=True)[:limit]
|
||||
lagging = sorted(items, key=lambda x: x["avg_pct"])[:limit]
|
||||
return {"leading": leading, "lagging": lagging}
|
||||
|
||||
|
||||
# ================================================================
|
||||
# Top 行 / 涨跌幅分桶
|
||||
# ================================================================
|
||||
|
||||
def _top_rows(rows: list[dict], key: str, descending: bool, limit: int = 8) -> list[dict]:
|
||||
filtered = [r for r in rows if _finite(r.get(key)) is not None]
|
||||
filtered.sort(key=lambda r: _finite(r.get(key)) or 0, reverse=descending)
|
||||
return [
|
||||
{
|
||||
"symbol": r.get("symbol"),
|
||||
"name": r.get("name"),
|
||||
"close": _finite(r.get("close")),
|
||||
"change_pct": _finite(r.get("change_pct")),
|
||||
"amount": _finite(r.get("amount")),
|
||||
"turnover_rate": _finite(r.get("turnover_rate")),
|
||||
"board": _board(str(r.get("symbol") or "")),
|
||||
}
|
||||
for r in filtered[:limit]
|
||||
]
|
||||
|
||||
|
||||
def _pct_band_rows(values: list[float]) -> list[dict]:
|
||||
bands = [
|
||||
("<-5%", None, -0.05),
|
||||
("-5~-3%", -0.05, -0.03),
|
||||
("-3~-1%", -0.03, -0.01),
|
||||
("-1~0%", -0.01, 0),
|
||||
("0~1%", 0, 0.01),
|
||||
("1~3%", 0.01, 0.03),
|
||||
("3~5%", 0.03, 0.05),
|
||||
(">5%", 0.05, None),
|
||||
]
|
||||
total = len(values) or 1
|
||||
out = []
|
||||
for label, low, high in bands:
|
||||
count = 0
|
||||
for v in values:
|
||||
if low is None and v < high:
|
||||
count += 1
|
||||
elif high is None and v >= low:
|
||||
count += 1
|
||||
elif low is not None and high is not None and low <= v < high:
|
||||
count += 1
|
||||
out.append({"label": label, "count": count, "pct": count / total * 100})
|
||||
return out
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 主装配入口
|
||||
# ================================================================
|
||||
|
||||
def build_market_overview(
|
||||
repo,
|
||||
quote_service=None,
|
||||
depth_service=None,
|
||||
as_of: date | None = None,
|
||||
) -> dict:
|
||||
"""装配市场总览(与原 overview._build_overview 行为一致)。
|
||||
|
||||
Args:
|
||||
repo: KlineRepository(必填)。
|
||||
quote_service: QuoteService(可选;实时指数行情来源)。
|
||||
depth_service: DepthService(可选;五档封板修正)。
|
||||
as_of: 指定日期,None 则取最新有数据日。
|
||||
"""
|
||||
svc = ScreenerService(repo)
|
||||
as_of = as_of or svc.latest_date()
|
||||
status = _quote_status(quote_service)
|
||||
indices = _index_quotes(repo, quote_service, as_of)
|
||||
|
||||
if not as_of:
|
||||
return {
|
||||
"as_of": None,
|
||||
"quote_status": status,
|
||||
"indices": indices,
|
||||
"breadth": {"total": 0, "up": 0, "down": 0, "flat": 0, "up_pct": 0, "down_pct": 0},
|
||||
"amount": {"total": 0, "avg": 0},
|
||||
"boards": [],
|
||||
"limit": {"limit_up": 0, "broken": 0, "failed": 0, "limit_down": 0, "max_boards": 0, "tiers": []},
|
||||
"distribution": [],
|
||||
"trend": {"above_ma5": 0, "above_ma20": 0, "above_ma60": 0, "above_ma5_pct": 0, "above_ma20_pct": 0, "above_ma60_pct": 0, "new_high": 0, "new_low": 0},
|
||||
"activity": {"avg_turnover": 0, "high_turnover": 0, "high_vol_ratio": 0, "vol_ratio": 1},
|
||||
"radar": [],
|
||||
"emotion": {"score": 50, "label": "暂无"},
|
||||
"top_gainers": [],
|
||||
"top_losers": [],
|
||||
"turnover_leaders": [],
|
||||
"active_leaders": [],
|
||||
"concept_rank": {"leading": [], "lagging": []},
|
||||
"industry_rank": {"leading": [], "lagging": []},
|
||||
}
|
||||
|
||||
df = svc._load_enriched_for_date(as_of)
|
||||
if df.is_empty():
|
||||
rows: list[dict] = []
|
||||
else:
|
||||
cols = [
|
||||
"symbol", "name", "close", "change_pct", "amount", "turnover_rate", "volume",
|
||||
"vol_ratio_5d", "consecutive_limit_ups", "signal_limit_up", "signal_broken_limit_up", "signal_limit_down",
|
||||
"ma5", "ma20", "ma60", "high_60d", "low_60d", "signal_n_day_high", "signal_n_day_low",
|
||||
]
|
||||
df = df.select([c for c in cols if c in df.columns])
|
||||
rows = df.to_dicts()
|
||||
|
||||
# 过滤真停牌(volume=0 且 change_pct=0),保留有涨跌幅的浮点误差股以对齐同花顺口径
|
||||
if rows and "volume" in rows[0]:
|
||||
rows = [r for r in rows
|
||||
if (_finite(r.get("volume")) or 0) > 0
|
||||
or (_finite(r.get("change_pct")) or 0) != 0]
|
||||
|
||||
total = len(rows)
|
||||
up = sum(1 for r in rows if (_finite(r.get("change_pct")) or 0) > 0)
|
||||
down = sum(1 for r in rows if (_finite(r.get("change_pct")) or 0) < 0)
|
||||
flat = max(0, total - up - down)
|
||||
up_pct = up / total * 100 if total else 0
|
||||
down_pct = down / total * 100 if total else 0
|
||||
|
||||
amounts = [_finite(r.get("amount")) or 0 for r in rows]
|
||||
total_amount = sum(amounts)
|
||||
avg_amount = total_amount / total if total else 0
|
||||
|
||||
pct_values = [_finite(r.get("change_pct")) for r in rows]
|
||||
pct_values = [v for v in pct_values if v is not None]
|
||||
avg_pct = sum(pct_values) / len(pct_values) if pct_values else 0
|
||||
median_pct = sorted(pct_values)[len(pct_values) // 2] if pct_values else 0
|
||||
strong_up = sum(1 for v in pct_values if v >= 0.03)
|
||||
strong_down = sum(1 for v in pct_values if v <= -0.03)
|
||||
|
||||
limit_up = sum(1 for r in rows if bool(r.get("signal_limit_up")) or (_finite(r.get("consecutive_limit_ups")) or 0) > 0)
|
||||
broken = sum(1 for r in rows if bool(r.get("signal_broken_limit_up")))
|
||||
limit_down = sum(1 for r in rows if bool(r.get("signal_limit_down")))
|
||||
max_boards = max([int(_finite(r.get("consecutive_limit_ups")) or 0) for r in rows], default=0)
|
||||
|
||||
# 五档 sealed 修正: 假涨停/假跌停不计入(需 Pro+ depth5.batch 能力)
|
||||
sealed_ready = False
|
||||
fake_up = 0
|
||||
fake_down = 0
|
||||
if depth_service:
|
||||
up_map = depth_service.get_sealed_map(as_of, is_down=False)
|
||||
down_map = depth_service.get_sealed_map(as_of, is_down=True)
|
||||
sealed_ready = bool(up_map or down_map) and depth_service.is_sealed_ready(as_of)
|
||||
if up_map:
|
||||
fake_up = sum(1 for v in up_map.values() if v.get("sealed") is False)
|
||||
if down_map:
|
||||
fake_down = sum(1 for v in down_map.values() if v.get("sealed") is False)
|
||||
if sealed_ready:
|
||||
limit_up = max(0, limit_up - fake_up)
|
||||
limit_down = max(0, limit_down - fake_down)
|
||||
|
||||
seal_rate = limit_up / (limit_up + broken) * 100 if (limit_up + broken) > 0 else 0
|
||||
|
||||
def above_ma_count(ma_key: str) -> int:
|
||||
return sum(1 for r in rows if (_finite(r.get("close")) is not None and _finite(r.get(ma_key)) is not None and (_finite(r.get("close")) or 0) >= (_finite(r.get(ma_key)) or 0)))
|
||||
|
||||
above_ma5 = above_ma_count("ma5")
|
||||
above_ma20 = above_ma_count("ma20")
|
||||
above_ma60 = above_ma_count("ma60")
|
||||
new_high = sum(1 for r in rows if bool(r.get("signal_n_day_high")) or (_finite(r.get("close")) is not None and _finite(r.get("high_60d")) is not None and (_finite(r.get("close")) or 0) >= (_finite(r.get("high_60d")) or 0)))
|
||||
new_low = sum(1 for r in rows if bool(r.get("signal_n_day_low")) or (_finite(r.get("close")) is not None and _finite(r.get("low_60d")) is not None and (_finite(r.get("close")) or 0) <= (_finite(r.get("low_60d")) or 0)))
|
||||
|
||||
turnovers = [_finite(r.get("turnover_rate")) for r in rows]
|
||||
turnovers = [v for v in turnovers if v is not None]
|
||||
avg_turnover = sum(turnovers) / len(turnovers) if turnovers else 0
|
||||
high_turnover = sum(1 for v in turnovers if v >= 5)
|
||||
|
||||
boards_map: dict[str, dict] = {}
|
||||
for r in rows:
|
||||
b = _board(str(r.get("symbol") or ""))
|
||||
item = boards_map.setdefault(b, {"board": b, "count": 0, "up": 0, "down": 0, "amount": 0.0})
|
||||
item["count"] += 1
|
||||
change = _finite(r.get("change_pct")) or 0
|
||||
if change > 0:
|
||||
item["up"] += 1
|
||||
elif change < 0:
|
||||
item["down"] += 1
|
||||
item["amount"] += _finite(r.get("amount")) or 0
|
||||
boards = sorted(boards_map.values(), key=lambda x: x["amount"], reverse=True)
|
||||
for b in boards:
|
||||
count = b["count"] or 1
|
||||
b["up_pct"] = b["up"] / count * 100
|
||||
|
||||
tiers_map: dict[int, int] = {}
|
||||
for r in rows:
|
||||
n = int(_finite(r.get("consecutive_limit_ups")) or 0)
|
||||
if n > 0:
|
||||
tiers_map[n] = tiers_map.get(n, 0) + 1
|
||||
tiers = [{"boards": k, "count": v} for k, v in sorted(tiers_map.items(), key=lambda item: -item[0])]
|
||||
|
||||
index_changes = [_finite(r.get("change_pct")) for r in indices]
|
||||
index_changes = [v for v in index_changes if v is not None]
|
||||
avg_index_pct = sum(index_changes) / len(index_changes) if index_changes else 0
|
||||
vol_ratios = [_finite(r.get("vol_ratio_5d")) for r in rows]
|
||||
vol_ratios = [v for v in vol_ratios if v is not None]
|
||||
avg_vol_ratio = sum(vol_ratios) / len(vol_ratios) if vol_ratios else 1
|
||||
high_vol_ratio = sum(1 for v in vol_ratios if v >= 1.5)
|
||||
|
||||
concept_rank = _dimension_rank(rows, repo, "concept")
|
||||
industry_rank = _dimension_rank(rows, repo, "industry", level=2)
|
||||
|
||||
strong_diff_pct = (strong_up - strong_down) / total * 100 if total else 0
|
||||
high_vol_pct = high_vol_ratio / total * 100 if total else 0
|
||||
strong_down_pct = strong_down / total * 100 if total else 0
|
||||
tier2_count = sum(t["count"] for t in tiers if t["boards"] >= 2)
|
||||
mainline_items = [*concept_rank["leading"][:3], *industry_rank["leading"][:3]]
|
||||
mainline_avg = max([_finite(item.get("avg_pct")) or 0 for item in mainline_items], default=0)
|
||||
mainline_cover_pct = max([(_finite(item.get("count")) or 0) / total * 100 for item in mainline_items], default=0) if total else 0
|
||||
mainline_score = round(_score(mainline_avg, -0.005, 0.03) * 0.65 + _score(mainline_cover_pct, 1, 12) * 0.35) if mainline_items else 50
|
||||
|
||||
radar = [
|
||||
{"key": "index", "label": "指数", "value": _score(avg_index_pct, -2.5, 2.5)},
|
||||
{"key": "profit", "label": "赚钱", "value": round(_score(up_pct, 20, 80) * 0.45 + _score(avg_pct, -0.02, 0.02) * 0.25 + _score(median_pct, -0.02, 0.02) * 0.20 + _score(strong_diff_pct, -8, 8) * 0.10)},
|
||||
{"key": "money", "label": "量能", "value": round(_score(avg_vol_ratio, 0.6, 1.8) * 0.70 + _score(high_vol_pct, 2, 12) * 0.30)},
|
||||
{"key": "speculation", "label": "投机", "value": round(_score(limit_up, 5, 90) * 0.25 + _score(seal_rate, 30, 85) * 0.35 + _score(max_boards, 1, 8) * 0.25 + _score(tier2_count, 0, 30) * 0.15)},
|
||||
{"key": "resilience", "label": "抗跌", "value": 100 - round(_score(down_pct, 20, 80) * 0.55 + _score(strong_down_pct, 1, 12) * 0.45)},
|
||||
{"key": "mainline", "label": "主线", "value": mainline_score},
|
||||
]
|
||||
emotion_score = round(sum(r["value"] for r in radar) / len(radar)) if radar else 50
|
||||
if emotion_score >= 70:
|
||||
emotion_label = "强势"
|
||||
elif emotion_score >= 55:
|
||||
emotion_label = "偏暖"
|
||||
elif emotion_score >= 45:
|
||||
emotion_label = "震荡"
|
||||
elif emotion_score >= 30:
|
||||
emotion_label = "偏冷"
|
||||
else:
|
||||
emotion_label = "冰点"
|
||||
|
||||
return _json_safe({
|
||||
"as_of": str(as_of),
|
||||
"quote_status": status,
|
||||
"indices": indices,
|
||||
"breadth": {
|
||||
"total": total,
|
||||
"up": up,
|
||||
"down": down,
|
||||
"flat": flat,
|
||||
"up_pct": up_pct,
|
||||
"down_pct": down_pct,
|
||||
"avg_pct": avg_pct,
|
||||
"median_pct": median_pct,
|
||||
"strong_up": strong_up,
|
||||
"strong_down": strong_down,
|
||||
},
|
||||
"amount": {"total": total_amount, "avg": avg_amount},
|
||||
"boards": boards,
|
||||
"limit": {"limit_up": limit_up, "broken": broken, "failed": 0, "limit_down": limit_down, "max_boards": max_boards, "seal_rate": seal_rate, "tiers": tiers, "sealed_ready": sealed_ready, "fake_up": fake_up, "fake_down": fake_down},
|
||||
"distribution": _pct_band_rows(pct_values),
|
||||
"trend": {
|
||||
"above_ma5": above_ma5,
|
||||
"above_ma20": above_ma20,
|
||||
"above_ma60": above_ma60,
|
||||
"above_ma5_pct": above_ma5 / total * 100 if total else 0,
|
||||
"above_ma20_pct": above_ma20 / total * 100 if total else 0,
|
||||
"above_ma60_pct": above_ma60 / total * 100 if total else 0,
|
||||
"new_high": new_high,
|
||||
"new_low": new_low,
|
||||
},
|
||||
"activity": {
|
||||
"avg_turnover": avg_turnover,
|
||||
"high_turnover": high_turnover,
|
||||
"high_vol_ratio": high_vol_pct,
|
||||
"vol_ratio": avg_vol_ratio,
|
||||
},
|
||||
"radar": radar,
|
||||
"emotion": {"score": emotion_score, "label": emotion_label},
|
||||
"top_gainers": _top_rows(rows, "change_pct", True),
|
||||
"top_losers": _top_rows(rows, "change_pct", False),
|
||||
"turnover_leaders": _top_rows(rows, "amount", True),
|
||||
"active_leaders": _top_rows(rows, "turnover_rate", True),
|
||||
"concept_rank": concept_rank,
|
||||
"industry_rank": industry_rank,
|
||||
})
|
||||
@@ -0,0 +1,343 @@
|
||||
"""AI 大盘复盘 —— 流式 LLM 复盘生成。
|
||||
|
||||
复刻 stock_analyzer.py 的 NDJSON 流式协议(meta/delta/error/done),
|
||||
将「市场总览」聚合数据交给 LLM 生成结构化复盘报告。
|
||||
|
||||
数据来源:services.market_overview_builder.build_market_overview
|
||||
(与 GET /api/overview/market 同源,保证复盘与看板数据口径一致)。
|
||||
|
||||
流式协议(与 stock_analyzer / financial_analyzer 一致,前端解析无差异):
|
||||
{"type":"meta", "as_of", "emotion_score", "emotion_label", "summary"}
|
||||
{"type":"delta","content":"..."} 逐 chunk 文本
|
||||
{"type":"error","message":"..."}
|
||||
{"type":"done"}
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import date
|
||||
from typing import AsyncIterator
|
||||
|
||||
from app.services.market_overview_builder import build_market_overview
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# 指数简称映射:摘要里用简称(上/深/创/科),全称太长列表放不下。与前端 INDEX_SHORT 对齐。
|
||||
_INDEX_SHORT = {
|
||||
"上证指数": "上",
|
||||
"深证成指": "深",
|
||||
"创业板指": "创",
|
||||
"科创综指": "科",
|
||||
"科创50": "科",
|
||||
}
|
||||
|
||||
# ================================================================
|
||||
# 系统提示词(市场策略师人格 + 固定七节模板)
|
||||
# ================================================================
|
||||
|
||||
_SYSTEM_PROMPT = """你是一位拥有 15 年 A 股一线实战经验的资深市场策略师,擅长从指数结构、涨跌家数、连板梯队、板块轮动与资金情绪中提炼交易主线,产出可直接指导次日仓位与节奏的盘后复盘报告。
|
||||
|
||||
## 输出规范
|
||||
|
||||
用 **Markdown** 格式输出,严格遵循以下结构。不要输出任何 JSON 或代码块,直接输出 Markdown 正文。
|
||||
|
||||
### 1. 🎯 一句话定调(1-2 句)
|
||||
用一句话概括今日市场的**核心矛盾与状态**(如"放量普涨、情绪修复,主线围绕科技扩散"/"指数虚高、个股杀跌,赚钱效应冰点")。结尾用【明日基调:进攻 / 均衡 / 防守】给出明确倾向。
|
||||
|
||||
### 2. 📊 盘面总览
|
||||
- 三大指数(上证/深证/创业板)表现:谁强谁弱、量能配合
|
||||
- 涨跌家数、涨停/跌停/炸板结构、两市成交额(放量/缩量判断)
|
||||
- 情绪温度(强势/偏暖/震荡/偏冷/冰点)及一句话依据
|
||||
|
||||
### 3. 📈 指数结构
|
||||
谁在护盘、谁在拖累;指数是否同步;关键支撑/压力位(基于当日点位推断);是否存在量价背离。
|
||||
|
||||
### 4. 🔥 板块主线
|
||||
- 领涨板块:背后的逻辑(消息/业绩/资金/技术)、持续性判断、是否形成可交易主线
|
||||
- 领跌板块:风险信号、是否扩散
|
||||
- 连板梯队与投机情绪:最高连板、封板率、炸板率反映的资金激进程度
|
||||
|
||||
### 5. 💰 资金与情绪
|
||||
成交额结构(增量/存量)、市场宽度(上涨占比、站上均线占比)、量能指标(量比)解读;风险偏好是修复还是转弱。
|
||||
|
||||
### 6. 📰 消息催化
|
||||
结合提供的近期新闻,提炼真正影响明日交易节奏的催化或扰动,明确区分"已兑现"与"待发酵"。**若无新闻数据,则直接从量价异动推断可能的催化逻辑并给出结论,不要标注"[推断]"之类的过程标签,更不要编造具体消息。**
|
||||
|
||||
### 7. 🎯 明日交易计划
|
||||
- 进攻 / 均衡 / 防守:基于今日盘面给出次日基调
|
||||
- 仓位区间建议(轻仓/半仓/重仓的粗略指引)
|
||||
- 关注方向(领涨延续 / 低吸 / 反包)与回避方向(高位滞涨 / 杀跌扩散)
|
||||
- 一个明确的触发失效条件(如"若上证跌破 X 点则转为防守")
|
||||
|
||||
### 8. ⚠️ 风险提示
|
||||
列出需要重点盯的风险点(如量能跟不上、外资流出、连板断层等)。末尾附一行:
|
||||
"> ⚠️ 本报告由 AI 基于公开行情数据生成,仅供参考,不构成任何投资建议。交易有风险,入市需谨慎。"
|
||||
|
||||
## 分析准则(务必遵守)
|
||||
|
||||
0. **只输出结论,不输出思考过程**:禁止复述你的分析步骤或方法论。不要写"我先按...做结构化复盘""接下来看...""基于上述数据我认为"这类元话语——直接给结论。读者要的是复盘结果,不是你怎么推导出来的。
|
||||
1. **数据说话**:每个判断引用具体数值,严禁空泛套话("情绪回暖"必须改成"涨停 68 家较前日 +22,封板率 75%")
|
||||
2. **诚实中立**:看多就写多,看空就写空,不要骑墙;数据不支持时直言无法判断
|
||||
3. **结构优先**:先看指数同步性与量能结构,再看板块与情绪,最后才是消息
|
||||
4. **不重复数字**:正文负责解读表格数据背后的含义,不要照抄罗列已提供的大段原始数字
|
||||
5. **风险前置**:任何进攻建议都要配触发失效条件
|
||||
6. **简明实战**:用交易员能扫读的密度输出,总字数 1200-2000 字,重在可执行
|
||||
|
||||
现在请基于下方数据进行复盘。"""
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 用户消息构建(精简切片,控制 token)
|
||||
# ================================================================
|
||||
|
||||
def _fmt_pct(v, suffix="%") -> str:
|
||||
if v is None:
|
||||
return "—"
|
||||
return f"{v:+.2f}{suffix}" if suffix else f"{v:.2f}"
|
||||
|
||||
|
||||
def _build_indices_block(overview: dict) -> str:
|
||||
"""指数行情精简块。"""
|
||||
indices = overview.get("indices") or []
|
||||
if not indices:
|
||||
return "(暂无指数)"
|
||||
lines = []
|
||||
for idx in indices:
|
||||
name = idx.get("name") or idx.get("symbol")
|
||||
price = idx.get("last_price")
|
||||
chg = idx.get("change_pct")
|
||||
price_s = f"{price:.2f}" if price is not None else "—"
|
||||
lines.append(f"- {name}: {price_s} {_fmt_pct(chg)}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _build_breadth_block(overview: dict) -> str:
|
||||
b = overview.get("breadth") or {}
|
||||
amt = overview.get("amount") or {}
|
||||
lim = overview.get("limit") or {}
|
||||
tr = overview.get("trend") or {}
|
||||
act = overview.get("activity") or {}
|
||||
|
||||
total_amount = amt.get("total") or 0
|
||||
# 成交额单位换算为亿元(原始为元)
|
||||
amount_yi = total_amount / 1e8 if total_amount else 0
|
||||
|
||||
lines = [
|
||||
f"- 上涨/下跌/平盘: {b.get('up',0)} / {b.get('down',0)} / {b.get('flat',0)}"
|
||||
f" (上涨占比 {b.get('up_pct',0):.1f}%)",
|
||||
f"- 涨停/炸板/跌停: {lim.get('limit_up',0)} / {lim.get('broken',0)} / {lim.get('limit_down',0)}"
|
||||
f" (封板率 {lim.get('seal_rate',0):.0f}%, 最高连板 {lim.get('max_boards',0)})",
|
||||
]
|
||||
if lim.get("tiers"):
|
||||
tiers_str = "、".join(f"{t['boards']}板×{t['count']}" for t in lim["tiers"][:5])
|
||||
lines.append(f"- 连板梯队: {tiers_str}")
|
||||
lines.append(f"- 两市成交额: {amount_yi:.0f} 亿元")
|
||||
lines.append(
|
||||
f"- 均线站位: MA5 {tr.get('above_ma5_pct',0):.0f}% / "
|
||||
f"MA20 {tr.get('above_ma20_pct',0):.0f}% / MA60 {tr.get('above_ma60_pct',0):.0f}%"
|
||||
)
|
||||
lines.append(
|
||||
f"- 量能: 平均换手 {act.get('avg_turnover',0):.2f}%, "
|
||||
f"量比5日均 {act.get('vol_ratio',1):.2f}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _build_sector_block(rank: dict, label: str) -> str:
|
||||
"""板块排名精简块(领涨/领跌 top5)。"""
|
||||
if not rank:
|
||||
return f"### {label}\n(暂无数据)"
|
||||
def _fmt(items):
|
||||
if not items:
|
||||
return "—"
|
||||
return "、".join(
|
||||
f"{it.get('name')}({(it.get('avg_pct') or 0)*100:+.2f}%,领涨:{it.get('leader',{}).get('name','—')})"
|
||||
for it in items[:5]
|
||||
)
|
||||
return (
|
||||
f"- 领涨{label}: {_fmt(rank.get('leading'))}\n"
|
||||
f"- 领跌{label}: {_fmt(rank.get('lagging'))}"
|
||||
)
|
||||
|
||||
|
||||
def _build_emotion_block(overview: dict) -> str:
|
||||
emo = overview.get("emotion") or {}
|
||||
radar = overview.get("radar") or []
|
||||
score = emo.get("score", 50)
|
||||
label = emo.get("label", "—")
|
||||
lines = [f"- 情绪温度: {score} ({label})"]
|
||||
if radar:
|
||||
dims = "、".join(f"{r.get('label')}{r.get('value',0)}" for r in radar)
|
||||
lines.append(f"- 六维雷达: {dims}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _build_user_prompt(overview: dict, news: list[dict], focus: str) -> str:
|
||||
"""构建用户消息:复盘日期 + 市场数据精简切片 + 新闻 + 关注点。"""
|
||||
as_of = overview.get("as_of") or "今日"
|
||||
|
||||
parts: list[str] = [
|
||||
f"复盘日期: {as_of}",
|
||||
"",
|
||||
"## 主要指数",
|
||||
_build_indices_block(overview),
|
||||
"",
|
||||
"## 盘面数据",
|
||||
_build_breadth_block(overview),
|
||||
"",
|
||||
"## 市场情绪",
|
||||
_build_emotion_block(overview),
|
||||
"",
|
||||
"## 概念板块排名",
|
||||
_build_sector_block(overview.get("concept_rank"), "概念"),
|
||||
"",
|
||||
"## 行业板块排名",
|
||||
_build_sector_block(overview.get("industry_rank"), "行业"),
|
||||
]
|
||||
|
||||
if news:
|
||||
news_lines = []
|
||||
for i, n in enumerate(news[:8], 1):
|
||||
title = (n.get("title") or "").strip()
|
||||
snippet = (n.get("snippet") or "").strip()
|
||||
source = (n.get("source") or "").strip()
|
||||
pub = (n.get("published_date") or "").strip()
|
||||
meta = " / ".join(p for p in (source, pub) if p)
|
||||
news_lines.append(f"{i}. {title} ({meta})\n {snippet}" if meta else f"{i}. {title}\n {snippet}")
|
||||
parts.extend(["", "## 近期市场新闻", "\n".join(news_lines)])
|
||||
else:
|
||||
parts.extend([
|
||||
"",
|
||||
"## 近期市场新闻",
|
||||
"(暂无新闻数据:本功能新闻检索能力将在后续版本接入。"
|
||||
"消息催化一节请直接从量价异动给出可能的催化逻辑结论,不要编造具体消息,也不要复述本说明。)",
|
||||
])
|
||||
|
||||
if focus.strip():
|
||||
parts.extend(["", f"本次复盘请特别关注: {focus.strip()}"])
|
||||
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 摘要生成(供 meta 事件 / 历史报告 summary)
|
||||
# ================================================================
|
||||
|
||||
def _recap_summary(overview: dict) -> str:
|
||||
"""一句话摘要(供 meta 事件与历史列表展示)。
|
||||
|
||||
指数用简称(上/深/创/科),与前端摘要条一致,避免列表里全称放不下。
|
||||
"""
|
||||
indices = overview.get("indices") or []
|
||||
emo = overview.get("emotion") or {}
|
||||
lim = overview.get("limit") or {}
|
||||
amt = overview.get("amount") or {}
|
||||
total_amount = (amt.get("total") or 0) / 1e8
|
||||
|
||||
idx_str = "、".join(
|
||||
f"{_INDEX_SHORT.get(i.get('name') or '', i.get('name') or '')}{(i.get('change_pct') or 0):+.2f}%"
|
||||
for i in indices[:4]
|
||||
) or "指数缺失"
|
||||
return (
|
||||
f"{idx_str} | 情绪{emo.get('score',50)}({emo.get('label','—')}) | "
|
||||
f"涨停{lim.get('limit_up',0)} | 成交{total_amount:.0f}亿"
|
||||
)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 流式主入口
|
||||
# ================================================================
|
||||
|
||||
async def recap_market_stream(
|
||||
repo,
|
||||
quote_service=None,
|
||||
depth_service=None,
|
||||
as_of: date | None = None,
|
||||
focus: str = "",
|
||||
news: list[dict] | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
"""流式大盘复盘:yield 出每个 NDJSON 事件。
|
||||
|
||||
Args:
|
||||
repo: KlineRepository(必填)。
|
||||
quote_service / depth_service: 可选,数据装配依赖。
|
||||
as_of: 复盘日期,None 取最新有数据日。
|
||||
focus: 用户追加的复盘关注点。
|
||||
news: 预检索的新闻列表(P1 不传,留 None 走降级说明;P3 由 news_search 注入)。
|
||||
"""
|
||||
# 1. 装配市场总览
|
||||
overview = build_market_overview(repo, quote_service, depth_service, as_of)
|
||||
as_of_str = overview.get("as_of")
|
||||
|
||||
if not as_of_str:
|
||||
yield json.dumps({
|
||||
"type": "error",
|
||||
"message": "暂无市场数据,请先在「数据」页同步日 K 与指数后再复盘",
|
||||
}, ensure_ascii=False)
|
||||
return
|
||||
|
||||
emo = overview.get("emotion") or {}
|
||||
|
||||
# 2. meta 事件(前端据此先渲染信号灯/看板)
|
||||
yield json.dumps({
|
||||
"type": "meta",
|
||||
"as_of": as_of_str,
|
||||
"emotion_score": emo.get("score", 50),
|
||||
"emotion_label": emo.get("label", "—"),
|
||||
"summary": _recap_summary(overview),
|
||||
}, ensure_ascii=False)
|
||||
|
||||
# 3+4. 构建 prompt + 流式调用 LLM(整体 try-except,任何异常 yield error,避免前端卡死)
|
||||
try:
|
||||
from app.services.ai_provider import stream_ai_text
|
||||
|
||||
user_prompt = _build_user_prompt(overview, news or [], focus)
|
||||
async for delta in stream_ai_text(
|
||||
[
|
||||
{"role": "system", "content": _SYSTEM_PROMPT},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
temperature=0.5,
|
||||
max_tokens=4500,
|
||||
):
|
||||
yield json.dumps({"type": "delta", "content": delta}, ensure_ascii=False)
|
||||
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception("AI market recap failed for %s: %s", as_of_str, e)
|
||||
yield json.dumps({"type": "error", "message": f"AI 复盘失败: {e}"}, ensure_ascii=False)
|
||||
return
|
||||
|
||||
yield json.dumps({"type": "done"}, ensure_ascii=False)
|
||||
|
||||
|
||||
async def recap_market_once(
|
||||
repo,
|
||||
quote_service=None,
|
||||
depth_service=None,
|
||||
as_of: date | None = None,
|
||||
focus: str = "",
|
||||
news: list[dict] | None = None,
|
||||
) -> tuple[str | None, dict]:
|
||||
"""非流式版本(供定时任务调用):累积全部 delta,返回 (content, meta)。
|
||||
|
||||
content 为完整 Markdown 文本;失败时为 None。
|
||||
meta 含 as_of / emotion_score / emotion_label / summary(即使失败也尽量回填)。
|
||||
"""
|
||||
content_parts: list[str] = []
|
||||
meta: dict = {"as_of": as_of.isoformat() if as_of else None}
|
||||
async for evt in recap_market_stream(repo, quote_service, depth_service, as_of, focus, news):
|
||||
try:
|
||||
obj = json.loads(evt)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
t = obj.get("type")
|
||||
if t == "meta":
|
||||
meta = obj
|
||||
elif t == "delta":
|
||||
content_parts.append(obj.get("content", ""))
|
||||
elif t == "error":
|
||||
logger.warning("market recap error event: %s", obj.get("message"))
|
||||
return None, meta
|
||||
return "".join(content_parts), meta
|
||||
@@ -0,0 +1,92 @@
|
||||
"""AI 大盘复盘报告持久化存储。
|
||||
|
||||
与 stock_reports.py(个股分析报告)/ ai_reports.py(财务分析报告)完全独立 ——
|
||||
单独的文件、字段、上限,互不影响。刻意不复用,避免引入 kind 判别字段与分支
|
||||
(解耦 > 抽象)。
|
||||
|
||||
存储位置: data/user_data/ai_market_recaps.json (数组,按 created_at 降序)
|
||||
保留最近 MAX_REPORTS 条;超出自动裁剪最旧的。
|
||||
|
||||
每条报告结构:
|
||||
{
|
||||
"id": "mkr_xxx", # 唯一 id(market-recap-report)
|
||||
"as_of": "2026-06-27", # 复盘日期
|
||||
"focus": "", # 用户追加的关心点(可为空)
|
||||
"content": "# ...markdown", # 报告正文
|
||||
"summary": "三大指数齐涨...", # 一句话摘要
|
||||
"emotion_score": 68, # 情绪分(0-100, 复盘生成时的市场情绪雷达均分)
|
||||
"emotion_label": "偏暖", # 情绪标签(强势/偏暖/震荡/偏冷/冰点)
|
||||
"created_at": "2026-06-27T15:35:00"
|
||||
}
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_REPORTS = 20
|
||||
|
||||
|
||||
def _path() -> Path:
|
||||
from app.config import settings
|
||||
p = settings.data_dir / "user_data" / "ai_market_recaps.json"
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
|
||||
|
||||
def list_reports() -> list[dict]:
|
||||
"""返回全部报告(按 created_at 降序)。"""
|
||||
p = _path()
|
||||
if not p.exists():
|
||||
return []
|
||||
try:
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
if isinstance(data, list):
|
||||
return sorted(data, key=lambda r: r.get("created_at", ""), reverse=True)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("ai_market_recaps.json malformed: %s", e)
|
||||
return []
|
||||
|
||||
|
||||
def _save_all(reports: list[dict]) -> None:
|
||||
"""全量写入(裁剪到 MAX_REPORTS)。"""
|
||||
reports.sort(key=lambda r: r.get("created_at", ""), reverse=True)
|
||||
if len(reports) > MAX_REPORTS:
|
||||
reports = reports[:MAX_REPORTS]
|
||||
_path().write_text(
|
||||
json.dumps(reports, indent=2, ensure_ascii=False), encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def save_report(report: dict) -> dict:
|
||||
"""新增一条报告并持久化。返回保存后的报告(含 id / created_at)。"""
|
||||
reports = list_reports()
|
||||
if not report.get("id"):
|
||||
report["id"] = f"mkr_{int(time.time() * 1000)}"
|
||||
if not report.get("created_at"):
|
||||
report["created_at"] = _now_iso()
|
||||
reports.append(report)
|
||||
_save_all(reports)
|
||||
logger.info("Market recap saved: %s (as_of=%s), total %d",
|
||||
report.get("id"), report.get("as_of"), len(reports))
|
||||
return report
|
||||
|
||||
|
||||
def delete_report(report_id: str) -> bool:
|
||||
"""删除指定报告。返回是否删除成功。"""
|
||||
reports = list_reports()
|
||||
before = len(reports)
|
||||
reports = [r for r in reports if r.get("id") != report_id]
|
||||
if len(reports) < before:
|
||||
_save_all(reports)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
from datetime import datetime
|
||||
return datetime.now().isoformat(timespec="seconds")
|
||||
@@ -0,0 +1,136 @@
|
||||
"""系统通知适配器 — 三平台原生通知中心。
|
||||
|
||||
职责: 把后端产生的告警事件推送到操作系统通知中心。
|
||||
窗口最小化 / 被遮挡 / 后台运行时都能弹通知 (不依赖前端 WebView)。
|
||||
|
||||
平台实现:
|
||||
- Windows: winotify (进现代操作中心, 支持图标)
|
||||
- macOS: osascript (系统已内置, 无需额外依赖)
|
||||
- Linux: notify-send (系统已内置) / plyer 兜底
|
||||
|
||||
设计: 失败静默降级, 绝不因通知失败阻断告警主流程 (落盘 / SSE 推送)。
|
||||
通知去重不在本层做, 复用 MonitorRuleEngine 的 cooldown 逻辑。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 单次通知最长字符 (避免某些平台截断报错)
|
||||
_MAX_LEN = 200
|
||||
|
||||
# 避免重复探测平台能力, 缓存一次
|
||||
_backend_cache: str | None = None
|
||||
|
||||
|
||||
def _detect_backend() -> str | None:
|
||||
"""探测当前平台可用的通知后端。"""
|
||||
global _backend_cache
|
||||
if _backend_cache is not None:
|
||||
return _backend_cache if _backend_cache != "none" else None
|
||||
|
||||
backend = None
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
import winotify # type: ignore[import-not-found] # noqa: F401
|
||||
|
||||
backend = "winotify"
|
||||
except ImportError:
|
||||
logger.debug("winotify 不可用, Windows 通知降级")
|
||||
backend = None
|
||||
elif sys.platform == "darwin":
|
||||
backend = "osascript"
|
||||
elif sys.platform.startswith("linux"):
|
||||
backend = "notify-send"
|
||||
|
||||
_backend_cache = backend or "none"
|
||||
return backend
|
||||
|
||||
|
||||
def _truncate(text: str) -> str:
|
||||
"""截断超长文本, 避免平台通知上限报错。"""
|
||||
text = (text or "").strip()
|
||||
return text[:_MAX_LEN] + ("…" if len(text) > _MAX_LEN else "")
|
||||
|
||||
|
||||
def notify(title: str, message: str, icon: Path | None = None) -> bool:
|
||||
"""推送一条系统通知。
|
||||
|
||||
Args:
|
||||
title: 通知标题
|
||||
message: 通知正文
|
||||
icon: 可选图标路径 (部分平台支持)
|
||||
|
||||
Returns:
|
||||
True=成功送达, False=失败或无可用后端。
|
||||
失败静默, 不抛异常 (通知是辅助通道, 不能阻断告警主流程)。
|
||||
"""
|
||||
title = _truncate(title)
|
||||
message = _truncate(message)
|
||||
if not title:
|
||||
return False
|
||||
|
||||
backend = _detect_backend()
|
||||
if backend is None:
|
||||
return False
|
||||
|
||||
try:
|
||||
if backend == "winotify":
|
||||
return _notify_winotify(title, message)
|
||||
if backend == "osascript":
|
||||
return _notify_osascript(title, message)
|
||||
if backend == "notify-send":
|
||||
return _notify_notify_send(title, message, icon)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("系统通知失败 (%s): %s", backend, e)
|
||||
return False
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _notify_winotify(title: str, message: str) -> bool:
|
||||
"""Windows 通知 (winotify) — 进现代操作中心。"""
|
||||
from winotify import Notifier # type: ignore[import-not-found]
|
||||
|
||||
Notifier().create_notification(
|
||||
title=title,
|
||||
msg=message,
|
||||
# winotify 要求 duration 为 "short" 或 "long"
|
||||
duration="short",
|
||||
# 无可点击动作 (桌面版不实现"点击回到窗口"的复杂交互)
|
||||
).show()
|
||||
return True
|
||||
|
||||
|
||||
def _notify_osascript(title: str, message: str) -> bool:
|
||||
"""macOS 通知 (osascript) — 调用系统 AppleScript。"""
|
||||
# 转义双引号, 避免 AppleScript 注入
|
||||
safe_title = title.replace('"', '\\"')
|
||||
safe_msg = message.replace('"', '\\"')
|
||||
script = (
|
||||
f'display notification "{safe_msg}" with title "{safe_title}"'
|
||||
)
|
||||
result = subprocess.run( # noqa: S603, S607
|
||||
["osascript", "-e", script],
|
||||
capture_output=True,
|
||||
timeout=5,
|
||||
)
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def _notify_notify_send(title: str, message: str, icon: Path | None) -> bool:
|
||||
"""Linux 通知 (notify-send) — freedesktop.org 标准。"""
|
||||
args = ["notify-send", title]
|
||||
if icon and Path(icon).exists():
|
||||
args.extend(["--icon", str(icon)])
|
||||
args.append(message)
|
||||
result = subprocess.run( # noqa: S603
|
||||
args,
|
||||
capture_output=True,
|
||||
timeout=5,
|
||||
)
|
||||
return result.returncode == 0
|
||||
@@ -0,0 +1,250 @@
|
||||
"""异步盘后管道任务注册表 — 每个 job 独立 JSON 文件。
|
||||
|
||||
设计:
|
||||
- job_store/ 文件夹,每个 job 一个 {id}.json,最多保留 max_jobs 个文件
|
||||
- running/pending 状态的 job 仅存内存(高频读写)
|
||||
- succeeded/failed 后写入独立文件并从内存释放
|
||||
- 列表查询 = 内存中的活跃 job + 磁盘文件扫描,按时间排序
|
||||
- 单个查询 = 内存优先,没有则读磁盘
|
||||
- 创建新 job 前检查文件数量,>= max_jobs 时删除最老的文件
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
JobStatus = Literal["pending", "running", "succeeded", "failed"]
|
||||
|
||||
|
||||
def _default_store_dir() -> Path:
|
||||
from app.config import settings
|
||||
return settings.data_dir / "job_store"
|
||||
|
||||
|
||||
_STORE_DIR = _default_store_dir()
|
||||
|
||||
|
||||
class JobStore:
|
||||
def __init__(self, max_jobs: int = 50, store_dir: Path = _STORE_DIR) -> None:
|
||||
self._max_jobs = max_jobs
|
||||
self._store_dir = store_dir
|
||||
self._active_jobs: dict[str, dict[str, Any]] = {} # running/pending
|
||||
self._active_id: str | None = None
|
||||
self._lock = threading.Lock()
|
||||
self._store_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# ===== persistence =====
|
||||
|
||||
def _write_file(self, job: dict[str, Any]) -> None:
|
||||
"""将终态 job 写入独立 JSON 文件。"""
|
||||
path = self._store_dir / f"{job['id']}.json"
|
||||
try:
|
||||
path.write_text(
|
||||
json.dumps(job, ensure_ascii=False, indent=None),
|
||||
encoding="utf-8",
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("failed to write job file %s", path)
|
||||
|
||||
def _read_file(self, job_id: str) -> dict[str, Any] | None:
|
||||
"""从磁盘读取单个 job 文件。"""
|
||||
path = self._store_dir / f"{job_id}.json"
|
||||
if not path.exists():
|
||||
return None
|
||||
try:
|
||||
return json.loads(path.read_text("utf-8"))
|
||||
except Exception:
|
||||
logger.warning("failed to read job file %s", path)
|
||||
return None
|
||||
|
||||
def _delete_oldest(self) -> None:
|
||||
"""删除最老的 job 文件,保持文件数量 < max_jobs。"""
|
||||
try:
|
||||
files = sorted(self._store_dir.glob("*.json"), key=lambda f: f.stat().st_mtime)
|
||||
except Exception:
|
||||
return
|
||||
while len(files) >= self._max_jobs:
|
||||
oldest = files.pop(0)
|
||||
try:
|
||||
oldest.unlink()
|
||||
except Exception:
|
||||
logger.warning("failed to delete old job file %s", oldest)
|
||||
|
||||
def _job_files_sorted(self) -> list[dict[str, Any]]:
|
||||
"""扫描磁盘上所有 job 文件,按 started_at 从新到旧排序。"""
|
||||
jobs: list[dict[str, Any]] = []
|
||||
for f in self._store_dir.glob("*.json"):
|
||||
try:
|
||||
jobs.append(json.loads(f.read_text("utf-8")))
|
||||
except Exception:
|
||||
continue
|
||||
jobs.sort(key=lambda j: j.get("started_at") or "", reverse=True)
|
||||
return jobs
|
||||
|
||||
# ===== lifecycle =====
|
||||
|
||||
def create(self) -> str:
|
||||
with self._lock:
|
||||
if self._active_id and self._active_jobs.get(self._active_id, {}).get("status") == "running":
|
||||
return self._active_id
|
||||
|
||||
job_id = uuid.uuid4().hex[:10]
|
||||
self._active_jobs[job_id] = {
|
||||
"id": job_id,
|
||||
"status": "pending",
|
||||
"stage": "init",
|
||||
"progress": 0,
|
||||
"stage_pct": 0,
|
||||
"log": [],
|
||||
"started_at": None,
|
||||
"finished_at": None,
|
||||
"duration_s": None,
|
||||
"result": None,
|
||||
"error": None,
|
||||
}
|
||||
self._active_id = job_id
|
||||
return job_id
|
||||
|
||||
def start(self, job_id: str) -> None:
|
||||
with self._lock:
|
||||
j = self._active_jobs.get(job_id)
|
||||
if not j:
|
||||
return
|
||||
j["status"] = "running"
|
||||
j["started_at"] = datetime.utcnow().isoformat(timespec="seconds") + "Z"
|
||||
|
||||
def succeed(self, job_id: str, result: Any) -> None:
|
||||
with self._lock:
|
||||
j = self._active_jobs.pop(job_id, None)
|
||||
if not j:
|
||||
return
|
||||
j["status"] = "succeeded"
|
||||
j["finished_at"] = datetime.utcnow().isoformat(timespec="seconds") + "Z"
|
||||
j["progress"] = 100
|
||||
j["result"] = result
|
||||
j["duration_s"] = _duration_s(j)
|
||||
if self._active_id == job_id:
|
||||
self._active_id = None
|
||||
self._delete_oldest()
|
||||
self._write_file(j)
|
||||
|
||||
def fail(self, job_id: str, error: str) -> None:
|
||||
with self._lock:
|
||||
j = self._active_jobs.pop(job_id, None)
|
||||
if not j:
|
||||
return
|
||||
j["status"] = "failed"
|
||||
j["finished_at"] = datetime.utcnow().isoformat(timespec="seconds") + "Z"
|
||||
j["error"] = error
|
||||
j["duration_s"] = _duration_s(j)
|
||||
if self._active_id == job_id:
|
||||
self._active_id = None
|
||||
self._delete_oldest()
|
||||
self._write_file(j)
|
||||
|
||||
# ===== progress =====
|
||||
|
||||
def progress(self, job_id: str, stage: str, pct: int, msg: str,
|
||||
stage_pct: int | None = None, skip_log: bool = False) -> None:
|
||||
with self._lock:
|
||||
j = self._active_jobs.get(job_id)
|
||||
if not j:
|
||||
return
|
||||
j["stage"] = stage
|
||||
j["progress"] = max(0, min(100, int(pct)))
|
||||
if stage_pct is not None:
|
||||
j["stage_pct"] = max(0, min(100, int(stage_pct)))
|
||||
elif j["stage"] != stage:
|
||||
j["stage_pct"] = 0
|
||||
entry = {
|
||||
"ts": datetime.utcnow().isoformat(timespec="seconds") + "Z",
|
||||
"stage": stage,
|
||||
"msg": msg,
|
||||
}
|
||||
if skip_log:
|
||||
entry["_skip"] = True
|
||||
if skip_log and j["log"] and j["log"][-1].get("stage") == stage and j["log"][-1].get("_skip"):
|
||||
j["log"][-1] = entry
|
||||
else:
|
||||
j["log"].append(entry)
|
||||
if len(j["log"]) > 200:
|
||||
j["log"] = j["log"][-200:]
|
||||
|
||||
# ===== query =====
|
||||
|
||||
def get(self, job_id: str) -> dict[str, Any] | None:
|
||||
# 内存中的活跃 job 优先
|
||||
j = self._active_jobs.get(job_id)
|
||||
if j:
|
||||
return j
|
||||
# 否则从磁盘读
|
||||
return self._read_file(job_id)
|
||||
|
||||
def list_recent(self, limit: int = 20) -> list[dict[str, Any]]:
|
||||
# 合并: 内存中的活跃 job + 磁盘文件
|
||||
all_jobs: list[dict[str, Any]] = list(self._active_jobs.values())
|
||||
all_jobs.extend(self._job_files_sorted())
|
||||
# 按 started_at 从新到旧排序,去重(理论上不会有重复)
|
||||
seen: set[str] = set()
|
||||
result: list[dict[str, Any]] = []
|
||||
for j in sorted(all_jobs, key=lambda x: x.get("started_at") or "", reverse=True):
|
||||
jid = j["id"]
|
||||
if jid in seen:
|
||||
continue
|
||||
seen.add(jid)
|
||||
result.append(_summary(j))
|
||||
if len(result) >= limit:
|
||||
break
|
||||
return result
|
||||
|
||||
def active_id(self) -> str | None:
|
||||
return self._active_id
|
||||
|
||||
def clear(self) -> None:
|
||||
"""清空所有任务(内存 + 磁盘文件)。"""
|
||||
with self._lock:
|
||||
self._active_jobs.clear()
|
||||
self._active_id = None
|
||||
for f in self._store_dir.glob("*.json"):
|
||||
try:
|
||||
f.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _summary(j: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": j["id"],
|
||||
"status": j["status"],
|
||||
"stage": j["stage"],
|
||||
"progress": j["progress"],
|
||||
"stage_pct": j.get("stage_pct", 0),
|
||||
"started_at": j["started_at"],
|
||||
"finished_at": j["finished_at"],
|
||||
"duration_s": j["duration_s"],
|
||||
"result": j["result"],
|
||||
"error": j["error"],
|
||||
}
|
||||
|
||||
|
||||
def _duration_s(j: dict[str, Any]) -> float | None:
|
||||
if not j.get("started_at") or not j.get("finished_at"):
|
||||
return None
|
||||
try:
|
||||
s = datetime.fromisoformat(j["started_at"])
|
||||
e = datetime.fromisoformat(j["finished_at"])
|
||||
return round((e - s).total_seconds(), 2)
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
# 进程内单例
|
||||
job_store = JobStore()
|
||||
@@ -0,0 +1,585 @@
|
||||
"""用户偏好设置持久化。
|
||||
|
||||
存储位置: data/user_data/preferences.json
|
||||
沿用 secrets_store 的 merge-write 模式,但不做 chmod 0600 (非敏感数据)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _path() -> Path:
|
||||
from app.config import settings
|
||||
p = settings.data_dir / "user_data" / "preferences.json"
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
|
||||
|
||||
def load() -> dict:
|
||||
p = _path()
|
||||
if p.exists():
|
||||
try:
|
||||
return json.loads(p.read_text(encoding="utf-8"))
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("preferences.json malformed: %s", e)
|
||||
return {}
|
||||
|
||||
|
||||
def save(updates: dict) -> dict:
|
||||
"""合并写入。返回新内容。"""
|
||||
current = load()
|
||||
current.update(updates)
|
||||
_path().write_text(
|
||||
json.dumps(current, indent=2, ensure_ascii=False), encoding="utf-8",
|
||||
)
|
||||
return current
|
||||
|
||||
|
||||
def get_realtime_quotes_enabled() -> bool:
|
||||
return load().get("realtime_quotes_enabled", False)
|
||||
|
||||
|
||||
def get_indices_nav_pinned() -> bool:
|
||||
"""侧栏指数报价卡片是否固定显示。默认 True(常驻)。
|
||||
关闭后,卡片跟随实时行情开关(仅实时开时显示)。"""
|
||||
return load().get("indices_nav_pinned", True)
|
||||
|
||||
|
||||
def get_realtime_quote_interval() -> float:
|
||||
return load().get("realtime_quote_interval", 10.0)
|
||||
|
||||
|
||||
def get_realtime_watchlist_symbols() -> list[str]:
|
||||
"""Free 档自选实时监控标的:直接取自选页前 5 个。"""
|
||||
try:
|
||||
from app.services import watchlist
|
||||
rows = watchlist.list_symbols()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("load watchlist for realtime failed: %s", e)
|
||||
return []
|
||||
out: list[str] = []
|
||||
for row in rows:
|
||||
symbol = str((row or {}).get("symbol") or "").strip().upper()
|
||||
if symbol and symbol not in out:
|
||||
out.append(symbol)
|
||||
if len(out) >= 5:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def set_realtime_watchlist_symbols(symbols: list[str]) -> list[str]: # noqa: ARG001
|
||||
"""兼容旧接口: Free 实时标的现在由自选页前 5 个决定。"""
|
||||
return get_realtime_watchlist_symbols()
|
||||
|
||||
|
||||
def set_realtime_quote_interval(interval: float) -> float:
|
||||
"""保存行情轮询间隔(不在此做 min/max 校验,由调用方按档位限制)。"""
|
||||
current = load()
|
||||
current["realtime_quote_interval"] = interval
|
||||
_path().write_text(
|
||||
json.dumps(current, indent=2, ensure_ascii=False), encoding="utf-8",
|
||||
)
|
||||
return interval
|
||||
|
||||
|
||||
def get_minute_sync_enabled() -> bool:
|
||||
return load().get("minute_sync_enabled", False)
|
||||
|
||||
|
||||
def get_minute_sync_days() -> int:
|
||||
return max(1, min(30, load().get("minute_sync_days", 5)))
|
||||
|
||||
|
||||
# ===== 数据源选择 (默认 TickFlow;第一阶段仅日K切换入口) =====
|
||||
|
||||
_ALLOWED_DATA_PROVIDERS = {"tickflow"}
|
||||
|
||||
|
||||
def get_daily_data_provider() -> str:
|
||||
provider = str(load().get("daily_data_provider", "tickflow") or "tickflow").lower()
|
||||
return provider if provider in _ALLOWED_DATA_PROVIDERS else "tickflow"
|
||||
|
||||
|
||||
def get_adj_factor_provider() -> str:
|
||||
provider = str(load().get("adj_factor_provider", "same_as_daily") or "same_as_daily").lower()
|
||||
if provider == "same_as_daily":
|
||||
return provider
|
||||
return provider if provider in _ALLOWED_DATA_PROVIDERS else "same_as_daily"
|
||||
|
||||
|
||||
def get_minute_data_provider() -> str:
|
||||
provider = str(load().get("minute_data_provider", "tickflow") or "tickflow").lower()
|
||||
return provider if provider in _ALLOWED_DATA_PROVIDERS else "tickflow"
|
||||
|
||||
|
||||
def get_realtime_data_provider() -> str:
|
||||
# 盘中实时现阶段仅支持 TickFlow。
|
||||
return "tickflow"
|
||||
|
||||
|
||||
# ===== 盘后管道拉取内容开关 (A股 / ETF / 指数 独立控制) =====
|
||||
|
||||
def get_pipeline_pull_a_share() -> bool:
|
||||
"""A 股日K固定拉取。"""
|
||||
return True
|
||||
|
||||
|
||||
def get_pipeline_pull_etf() -> bool:
|
||||
"""是否拉取 ETF 日K。默认 False(标的多,首次较慢)。"""
|
||||
return load().get("pipeline_pull_etf", False)
|
||||
|
||||
|
||||
def get_pipeline_pull_index() -> bool:
|
||||
"""是否拉取指数日K。默认 True。"""
|
||||
return load().get("pipeline_pull_index", True)
|
||||
|
||||
|
||||
_PIPELINE_PULL_KEYS = ("pipeline_pull_etf", "pipeline_pull_index")
|
||||
|
||||
|
||||
def get_pipeline_pull_types() -> dict:
|
||||
"""返回三个拉取开关的当前值。"""
|
||||
return {
|
||||
"pipeline_pull_a_share": get_pipeline_pull_a_share(),
|
||||
"pipeline_pull_etf": get_pipeline_pull_etf(),
|
||||
"pipeline_pull_index": get_pipeline_pull_index(),
|
||||
}
|
||||
|
||||
|
||||
def set_pipeline_pull_types(cfg: dict) -> dict:
|
||||
"""批量保存拉取开关。只接受白名单内的布尔字段。"""
|
||||
updates = {
|
||||
k: bool(v) for k, v in cfg.items()
|
||||
if k in _PIPELINE_PULL_KEYS and v is not None
|
||||
}
|
||||
save(updates)
|
||||
return get_pipeline_pull_types()
|
||||
|
||||
|
||||
def get_pipeline_index_symbols() -> str:
|
||||
"""指数自定义拉取代码(逗号/换行/空格分隔)。空串表示全量。"""
|
||||
return str(load().get("pipeline_index_symbols", "") or "").strip()
|
||||
|
||||
|
||||
def set_pipeline_index_symbols(symbols: str) -> str:
|
||||
"""保存指数自定义代码,返回规范化后的字符串。"""
|
||||
save({"pipeline_index_symbols": symbols})
|
||||
return get_pipeline_index_symbols()
|
||||
|
||||
|
||||
def get_pipeline_schedule() -> dict:
|
||||
"""返回盘后管道调度时间 {"hour": 15, "minute": 30}。"""
|
||||
d = load().get("pipeline_schedule", {"hour": 15, "minute": 30})
|
||||
return {"hour": d.get("hour", 15), "minute": d.get("minute", 30)}
|
||||
|
||||
|
||||
def set_pipeline_schedule(hour: int, minute: int) -> dict:
|
||||
h = max(0, min(23, hour))
|
||||
m = max(0, min(59, minute))
|
||||
# 盘后不早于 15:00
|
||||
if h * 60 + m < 15 * 60:
|
||||
h, m = 15, 0
|
||||
save({"pipeline_schedule": {"hour": h, "minute": m}})
|
||||
return {"hour": h, "minute": m}
|
||||
|
||||
|
||||
def get_instruments_schedule() -> dict:
|
||||
"""返回盘前标的维表调度时间 {"hour": 9, "minute": 10}。"""
|
||||
d = load().get("instruments_schedule", {"hour": 9, "minute": 10})
|
||||
return {"hour": d.get("hour", 9), "minute": d.get("minute", 10)}
|
||||
|
||||
|
||||
def set_instruments_schedule(hour: int, minute: int) -> dict:
|
||||
h = max(0, min(23, hour))
|
||||
m = max(0, min(59, minute))
|
||||
# 盘前不晚于 09:15
|
||||
if h * 60 + m > 9 * 60 + 15:
|
||||
h, m = 9, 15
|
||||
save({"instruments_schedule": {"hour": h, "minute": m}})
|
||||
return {"hour": h, "minute": m}
|
||||
|
||||
|
||||
def get_enriched_batch_size() -> int:
|
||||
"""返回 enriched 全量计算每批 symbol 数量。"""
|
||||
return max(1, min(10000, load().get("enriched_batch_size", 1000)))
|
||||
|
||||
|
||||
def set_enriched_batch_size(size: int) -> int:
|
||||
"""保存 enriched 全量计算批次大小。"""
|
||||
size = max(10, min(6000, size))
|
||||
save({"enriched_batch_size": size})
|
||||
return size
|
||||
|
||||
|
||||
def get_index_daily_batch_size() -> int:
|
||||
"""返回指数日 K 同步每批 symbol 数量。"""
|
||||
return max(1, min(10000, load().get("index_daily_batch_size", 100)))
|
||||
|
||||
|
||||
def set_index_daily_batch_size(size: int) -> int:
|
||||
"""保存指数日 K 同步批次大小。"""
|
||||
size = max(1, min(10000, size))
|
||||
save({"index_daily_batch_size": size})
|
||||
return size
|
||||
|
||||
|
||||
# ── 五档盘口 sealed(真假涨停) 配置 ──────────────────────
|
||||
|
||||
def get_limit_ladder_monitor_enabled() -> bool:
|
||||
"""连板梯队 5 档监控开关。关闭时 depth 不轮询(连板梯队降级显示)。"""
|
||||
return load().get("limit_ladder_monitor_enabled", False)
|
||||
|
||||
|
||||
def get_depth_polling_interval() -> float:
|
||||
"""depth 盘中轮询间隔(秒)。默认 20(Pro/Expert 都适用)。"""
|
||||
return float(load().get("depth_polling_interval", 20.0))
|
||||
|
||||
|
||||
def set_depth_polling_interval(interval: float) -> float:
|
||||
"""保存 depth 轮询间隔。套餐范围 clamp 由 depth_service 按档位做。"""
|
||||
interval = max(1.0, min(600.0, float(interval)))
|
||||
save({"depth_polling_interval": interval})
|
||||
return interval
|
||||
|
||||
|
||||
def get_depth_finalize_time() -> dict:
|
||||
"""盘后 sealed 定版时间 {"hour": 15, "minute": 2}。范围 15:01~18:00。"""
|
||||
d = load().get("depth_finalize_time", {"hour": 15, "minute": 2})
|
||||
return {"hour": d.get("hour", 15), "minute": d.get("minute", 2)}
|
||||
|
||||
|
||||
def set_depth_finalize_time(hour: int, minute: int) -> dict:
|
||||
"""保存盘后 sealed 定版时间,强制范围 15:01~18:00。"""
|
||||
h = max(0, min(23, hour))
|
||||
m = max(0, min(59, minute))
|
||||
# 下限 15:01, 上限 18:00
|
||||
if h * 60 + m < 15 * 60 + 1:
|
||||
h, m = 15, 1
|
||||
if h * 60 + m > 18 * 60:
|
||||
h, m = 18, 0
|
||||
save({"depth_finalize_time": {"hour": h, "minute": m}})
|
||||
return {"hour": h, "minute": m}
|
||||
|
||||
|
||||
# 复盘推送可选渠道白名单 (微信等暂未实现, 不在白名单内, 前端仅作占位)
|
||||
# 多选: 不推送 = 空数组, 而非 'none'
|
||||
REVIEW_PUSH_CHANNELS = {"feishu"}
|
||||
|
||||
|
||||
def get_review_schedule() -> dict:
|
||||
"""定时复盘调度 {"enabled": False, "hour": 15, "minute": 10}。默认关闭。
|
||||
|
||||
A股 15:00 收盘, 默认时间设为 15:10(收盘后即时复盘), 强制下限 15:00。
|
||||
"""
|
||||
d = load().get("review_schedule", {"enabled": False, "hour": 15, "minute": 10})
|
||||
return {
|
||||
"enabled": bool(d.get("enabled", False)),
|
||||
"hour": d.get("hour", 15),
|
||||
"minute": d.get("minute", 10),
|
||||
}
|
||||
|
||||
|
||||
def set_review_schedule(enabled: bool, hour: int, minute: int) -> dict:
|
||||
"""保存定时复盘调度。强制时间下限 15:00(A股收盘)。
|
||||
|
||||
enabled=False 时时间仍保存(下次开启可沿用), 但调度器不会注册 job。
|
||||
"""
|
||||
h = max(0, min(23, hour))
|
||||
m = max(0, min(59, minute))
|
||||
# 下限 15:00: A股 15:00 收盘, 收盘后才有当日完整数据复盘
|
||||
if h * 60 + m < 15 * 60:
|
||||
h, m = 15, 0
|
||||
save({"review_schedule": {"enabled": bool(enabled), "hour": h, "minute": m}})
|
||||
return {"enabled": bool(enabled), "hour": h, "minute": m}
|
||||
|
||||
|
||||
def get_review_push_channels() -> list[str]:
|
||||
"""复盘推送渠道(多选) — 选定的外部工具列表, 复盘归档后逐个推送。
|
||||
|
||||
与 review_schedule / 实时行情完全独立, 常驻可单独设置。
|
||||
空列表 = 不推送; ['feishu'] = 推送到飞书(复用监控中心全局 feishu_webhook_url/secret)。
|
||||
|
||||
向后兼容:
|
||||
- 老多版本单选 review_push_channel=='feishu' → ['feishu']
|
||||
- 更老布尔 review_push_enabled==True → ['feishu']
|
||||
"""
|
||||
d = load()
|
||||
raw = d.get("review_push_channels")
|
||||
if isinstance(raw, list):
|
||||
return [c for c in raw if c in REVIEW_PUSH_CHANNELS]
|
||||
# 兼容老单选字符串
|
||||
if d.get("review_push_channel") == "feishu":
|
||||
return ["feishu"]
|
||||
# 兼容更老布尔开关
|
||||
if d.get("review_push_enabled") is True:
|
||||
return ["feishu"]
|
||||
return []
|
||||
|
||||
|
||||
def set_review_push_channels(channels: list[str]) -> list[str]:
|
||||
"""保存复盘推送渠道(多选)。过滤白名单外的值、去重、保序。空列表 = 不推送。"""
|
||||
seen: set[str] = set()
|
||||
cleaned: list[str] = []
|
||||
for c in channels or []:
|
||||
if c in REVIEW_PUSH_CHANNELS and c not in seen:
|
||||
seen.add(c)
|
||||
cleaned.append(c)
|
||||
save({"review_push_channels": cleaned})
|
||||
return cleaned
|
||||
|
||||
|
||||
|
||||
# ===== 实时监控 =====
|
||||
|
||||
# 页面 SSE 刷新配置: { "watchlist": true, "monitor": true, ... }
|
||||
# 可刷新的页面列表及其默认值
|
||||
SSE_REFRESH_PAGES_DEFAULT = {
|
||||
"watchlist": True,
|
||||
"limit-ladder": False,
|
||||
}
|
||||
|
||||
SIDEBAR_INDEX_SYMBOLS_DEFAULT = ["000001.SH", "399001.SZ", "399006.SZ", "000680.SH"]
|
||||
|
||||
|
||||
# ===== 盘中实时行情范围 (独立于盘后管道范围) =====
|
||||
|
||||
|
||||
def get_realtime_pull_stock() -> bool:
|
||||
return load().get("realtime_pull_stock", True)
|
||||
|
||||
|
||||
def get_realtime_pull_etf() -> bool:
|
||||
# 老用户兼容: ETF 实时默认关闭,避免升级后请求量/写盘量突然增加。
|
||||
return load().get("realtime_pull_etf", False)
|
||||
|
||||
|
||||
def get_realtime_pull_index() -> bool:
|
||||
return load().get("realtime_pull_index", True)
|
||||
|
||||
|
||||
def get_realtime_index_mode() -> str:
|
||||
mode = str(load().get("realtime_index_mode", "core") or "core").lower()
|
||||
return mode if mode in {"core", "all"} else "core"
|
||||
|
||||
|
||||
def get_realtime_index_symbols() -> list[str]:
|
||||
stored = load().get("realtime_index_symbols", SIDEBAR_INDEX_SYMBOLS_DEFAULT)
|
||||
if isinstance(stored, str):
|
||||
import re
|
||||
stored = [s.strip() for s in re.split(r"[,\s]+", stored) if s.strip()]
|
||||
return [str(s) for s in stored if str(s).strip()]
|
||||
|
||||
|
||||
def set_realtime_quote_scope(cfg: dict) -> dict:
|
||||
updates = {}
|
||||
for key in ("realtime_pull_stock", "realtime_pull_etf", "realtime_pull_index"):
|
||||
if key in cfg and cfg[key] is not None:
|
||||
updates[key] = bool(cfg[key])
|
||||
if "realtime_index_mode" in cfg and cfg["realtime_index_mode"] in {"core", "all"}:
|
||||
updates["realtime_index_mode"] = cfg["realtime_index_mode"]
|
||||
if "realtime_index_symbols" in cfg and cfg["realtime_index_symbols"] is not None:
|
||||
updates["realtime_index_symbols"] = cfg["realtime_index_symbols"]
|
||||
if updates:
|
||||
save(updates)
|
||||
return get_realtime_quote_scope()
|
||||
|
||||
|
||||
def get_realtime_quote_scope() -> dict:
|
||||
return {
|
||||
"realtime_pull_stock": get_realtime_pull_stock(),
|
||||
"realtime_pull_etf": get_realtime_pull_etf(),
|
||||
"realtime_pull_index": get_realtime_pull_index(),
|
||||
"realtime_index_mode": get_realtime_index_mode(),
|
||||
"realtime_index_symbols": get_realtime_index_symbols(),
|
||||
}
|
||||
|
||||
|
||||
def get_sse_refresh_pages() -> dict[str, bool]:
|
||||
"""返回每个页面的 SSE 刷新开关。"""
|
||||
stored = load().get("sse_refresh_pages", {})
|
||||
# 合并默认值 (新增页面自动出现)
|
||||
result = dict(SSE_REFRESH_PAGES_DEFAULT)
|
||||
result.update(stored)
|
||||
return result
|
||||
|
||||
|
||||
def set_sse_refresh_pages(pages: dict[str, bool]) -> dict[str, bool]:
|
||||
"""保存页面 SSE 刷新配置。"""
|
||||
save({"sse_refresh_pages": pages})
|
||||
return get_sse_refresh_pages()
|
||||
|
||||
|
||||
def get_sidebar_index_symbols() -> list[str]:
|
||||
"""返回左侧菜单显示的指数代码。"""
|
||||
stored = load().get("sidebar_index_symbols", SIDEBAR_INDEX_SYMBOLS_DEFAULT)
|
||||
allowed = set(SIDEBAR_INDEX_SYMBOLS_DEFAULT)
|
||||
return [s for s in stored if s in allowed]
|
||||
|
||||
|
||||
def get_strategy_monitor_enabled() -> bool:
|
||||
"""策略告警评估总开关。"""
|
||||
return load().get("strategy_monitor_enabled", False)
|
||||
|
||||
|
||||
def get_system_notify_enabled() -> bool:
|
||||
"""系统通知开关 — 开启后监控告警同时推送到操作系统通知中心。"""
|
||||
return load().get("system_notify_enabled", False)
|
||||
|
||||
|
||||
def set_system_notify_enabled(enabled: bool) -> bool:
|
||||
"""保存系统通知开关。"""
|
||||
save({"system_notify_enabled": bool(enabled)})
|
||||
return bool(enabled)
|
||||
|
||||
|
||||
def get_feishu_webhook_url() -> str:
|
||||
"""飞书自定义机器人 Webhook 地址 — 全局共用一处, 所有启用推送的规则都推到这一个群。"""
|
||||
return load().get("feishu_webhook_url", "")
|
||||
|
||||
|
||||
def get_feishu_webhook_secret() -> str:
|
||||
"""飞书自定义机器人签名密钥 — 机器人启用「签名校验」时必填, 留空表示不验签。"""
|
||||
return load().get("feishu_webhook_secret", "")
|
||||
|
||||
|
||||
def set_feishu_webhook_url(url: str) -> str:
|
||||
"""保存飞书 Webhook 地址。传入空串表示清空配置。"""
|
||||
save({"feishu_webhook_url": str(url or "").strip()})
|
||||
return get_feishu_webhook_url()
|
||||
|
||||
|
||||
def set_feishu_webhook_secret(secret: str) -> str:
|
||||
"""保存飞书签名密钥。传入空串表示不验签。"""
|
||||
save({"feishu_webhook_secret": str(secret or "").strip()})
|
||||
return get_feishu_webhook_secret()
|
||||
|
||||
|
||||
def get_webhook_enabled_default() -> bool:
|
||||
"""新建监控规则时是否默认勾选「飞书推送」。
|
||||
|
||||
数据模型当前只有一个 webhook_enabled 布尔 (即飞书), QMT/ptrade 待定。
|
||||
此默认值供规则编辑器新建规则时预填, 单条规则仍可独立修改。
|
||||
"""
|
||||
return load().get("webhook_enabled_default", False)
|
||||
|
||||
|
||||
def set_webhook_enabled_default(enabled: bool) -> bool:
|
||||
"""保存飞书推送默认勾选态。"""
|
||||
save({"webhook_enabled_default": bool(enabled)})
|
||||
return get_webhook_enabled_default()
|
||||
|
||||
|
||||
def get_screener_auto_run() -> bool:
|
||||
"""选股页进入时是否自动运行所有策略 (获取命中数)。默认开。"""
|
||||
return load().get("screener_auto_run", True)
|
||||
|
||||
|
||||
def get_strategy_monitor_ids() -> list[str]:
|
||||
"""返回监控池中的策略 ID。"""
|
||||
return load().get("strategy_monitor_ids", [])
|
||||
|
||||
|
||||
def set_realtime_monitor_config(cfg: dict) -> dict:
|
||||
"""批量更新实时监控配置。"""
|
||||
updates = {}
|
||||
if "sse_refresh_pages" in cfg:
|
||||
updates["sse_refresh_pages"] = cfg["sse_refresh_pages"]
|
||||
if "strategy_monitor_enabled" in cfg:
|
||||
updates["strategy_monitor_enabled"] = cfg["strategy_monitor_enabled"]
|
||||
if "strategy_monitor_ids" in cfg:
|
||||
updates["strategy_monitor_ids"] = cfg["strategy_monitor_ids"]
|
||||
if "sidebar_index_symbols" in cfg:
|
||||
allowed = set(SIDEBAR_INDEX_SYMBOLS_DEFAULT)
|
||||
updates["sidebar_index_symbols"] = [s for s in cfg["sidebar_index_symbols"] if s in allowed]
|
||||
if "screener_auto_run" in cfg:
|
||||
updates["screener_auto_run"] = bool(cfg["screener_auto_run"])
|
||||
if updates:
|
||||
save(updates)
|
||||
return get_realtime_monitor_config()
|
||||
|
||||
|
||||
def get_realtime_monitor_config() -> dict:
|
||||
"""返回完整的实时监控配置。"""
|
||||
return {
|
||||
"sse_refresh_pages": get_sse_refresh_pages(),
|
||||
"strategy_monitor_enabled": get_strategy_monitor_enabled(),
|
||||
"strategy_monitor_ids": get_strategy_monitor_ids(),
|
||||
"sidebar_index_symbols": get_sidebar_index_symbols(),
|
||||
"screener_auto_run": get_screener_auto_run(),
|
||||
}
|
||||
|
||||
|
||||
def get_nav_order() -> list[str]:
|
||||
"""返回左侧菜单的自定义排序(内置页面 path + 扩展分析菜单 id)。"""
|
||||
return load().get("nav_order", [])
|
||||
|
||||
|
||||
def set_nav_order(order: list[str]) -> list[str]:
|
||||
"""保存左侧菜单排序。"""
|
||||
save({"nav_order": order})
|
||||
return get_nav_order()
|
||||
|
||||
|
||||
def get_nav_hidden() -> list[str]:
|
||||
"""返回左侧菜单中隐藏的项 id 列表。"""
|
||||
return load().get("nav_hidden", [])
|
||||
|
||||
|
||||
def set_nav_hidden(hidden: list[str]) -> list[str]:
|
||||
"""保存左侧菜单隐藏项。"""
|
||||
save({"nav_hidden": hidden})
|
||||
return get_nav_hidden()
|
||||
|
||||
|
||||
def get_watchlist_columns() -> list[dict] | None:
|
||||
"""返回自选列表列配置。"""
|
||||
return load().get("watchlist_columns")
|
||||
|
||||
|
||||
def set_watchlist_columns(columns: list[dict]) -> list[dict]:
|
||||
"""保存自选列表列配置。"""
|
||||
save({"watchlist_columns": columns})
|
||||
return columns
|
||||
|
||||
|
||||
def get_screener_result_columns() -> list[dict] | None:
|
||||
"""返回策略结果列表列配置。"""
|
||||
return load().get("screener_result_columns")
|
||||
|
||||
|
||||
def set_screener_result_columns(columns: list[dict]) -> list[dict]:
|
||||
"""保存策略结果列表列配置。"""
|
||||
save({"screener_result_columns": columns})
|
||||
return columns
|
||||
|
||||
|
||||
# ===== 首次使用引导 =====
|
||||
|
||||
def get_onboarding_completed() -> bool:
|
||||
"""是否已完成首次使用向导。默认 False(新用户)。"""
|
||||
return bool(load().get("onboarding_completed", False))
|
||||
|
||||
|
||||
def set_onboarding_completed(done: bool = True) -> bool:
|
||||
"""标记首次使用向导完成状态。"""
|
||||
save({"onboarding_completed": bool(done)})
|
||||
return bool(done)
|
||||
|
||||
|
||||
# ===== 财务数据同步时间(持久化,重启不丢失) =====
|
||||
# 结构: { "metrics": "2026-06-25T10:00:00+08:00", "income": ..., ... }
|
||||
|
||||
def get_financial_sync_times() -> dict[str, str]:
|
||||
"""返回各财务表的最后同步时间(ISO 字符串)。未同步过的表不在返回值中。"""
|
||||
return load().get("financial_sync_times", {}) or {}
|
||||
|
||||
|
||||
def set_financial_sync_time(table: str, iso_ts: str) -> None:
|
||||
"""更新单张财务表的最后同步时间(合并写入,不清除其他表)。"""
|
||||
times = get_financial_sync_times()
|
||||
times[table] = iso_ts
|
||||
save({"financial_sync_times": times})
|
||||
@@ -0,0 +1,971 @@
|
||||
"""全局实时行情服务。
|
||||
|
||||
集中管理全市场行情拉取 + enriched 缓存,供盘中选股、自选股等所有模块复用。
|
||||
|
||||
架构:
|
||||
- 后台线程轮询 TickFlow get_by_universes(["CN_Equity_A", "CN_Index"])
|
||||
- 拉取行情 → 写 kline_daily (不复权) + 增量计算 enriched → 写盘 + 更新缓存
|
||||
- _enriched_cache 是唯一的盘中数据源 (OHLCV + 全套技术指标)
|
||||
- _live_agg_cache 是递推状态 (只加载一次, 盘中不变)
|
||||
|
||||
数据流 (每轮 ~15s):
|
||||
1. API 拉取 → raw_records (临时变量)
|
||||
2. raw_records → 写 kline_daily (不复权原始价格)
|
||||
3. raw_records → 更新 _enriched_cache 的 OHLCV
|
||||
4. 增量计算 enriched 指标 (~50ms)
|
||||
5. 写 kline_daily_enriched + 替换 _enriched_cache
|
||||
6. 通知 SSE
|
||||
|
||||
生命周期:
|
||||
- 服务启动时读取 preferences,若 enabled 则自动启动线程
|
||||
- 运行中可通过 API 切换开关
|
||||
- 关闭时停止线程
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from datetime import date, datetime, time as dt_time
|
||||
|
||||
import polars as pl
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class QuoteService:
|
||||
"""全局实时行情服务 — 单例。"""
|
||||
|
||||
CORE_INDEX_SYMBOLS = ("000001.SH", "399001.SZ", "399006.SZ", "000680.SH")
|
||||
|
||||
# 档位 → 最小轮询间隔 (秒)
|
||||
TIER_MIN_INTERVAL = {
|
||||
"expert": 1.0,
|
||||
"pro": 2.0,
|
||||
"starter": 3.0,
|
||||
"free": 6.0,
|
||||
}
|
||||
DEFAULT_INTERVAL = 10.0
|
||||
MAX_INTERVAL = 60.0
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self._running = False
|
||||
self._enabled = False # 全局开关 (持久化到 preferences)
|
||||
self._interval = self.DEFAULT_INTERVAL
|
||||
self._thread: threading.Thread | None = None
|
||||
self._repo = None # 延迟注入, 避免循环导入
|
||||
self._update_event = threading.Event() # SSE 通知: 行情更新后 set
|
||||
self._alert_event = threading.Event() # SSE 通知: 有告警时 set
|
||||
self._depth_update_event = threading.Event() # SSE 通知: depth 五档修正后 set (刷新连板梯队)
|
||||
self._pending_alerts: list[dict] = [] # 待推送的告警
|
||||
self._max_pending_alerts: int = 1000 # 背压上限: 超出丢弃最旧
|
||||
# 复盘进度 SSE 通道: 定时复盘流式生成时, 把 meta/delta/done 事件推给开着页面的前端
|
||||
self._review_event = threading.Event() # SSE 通知: 有复盘进度事件时 set
|
||||
self._pending_review: list[str] = [] # 待推送的复盘事件(JSON 字符串)
|
||||
self._max_pending_review: int = 200 # 背压上限: 超出丢弃最旧
|
||||
self._strategy_monitor = None # 延迟注入
|
||||
self._app_state = None # 延迟注入 (FastAPI app.state)
|
||||
|
||||
# 拉取元信息 (给 SSE / status 用)
|
||||
self._fetch_time: float = 0.0 # perf_counter (用于计算 quote_age_ms)
|
||||
self._fetch_ms: float = 0.0 # 拉取耗时 (毫秒)
|
||||
self._fetched_at: float = 0.0 # 拉取完成的 Unix 时间戳 (毫秒)
|
||||
self._symbol_count: int = 0
|
||||
self._index_symbol_count: int = 0
|
||||
self._etf_symbol_count: int = 0
|
||||
self._index_quotes_cache: pl.DataFrame | None = None
|
||||
|
||||
# ================================================================
|
||||
# 生命周期
|
||||
# ================================================================
|
||||
|
||||
def start(self, interval: float = 0.0) -> None:
|
||||
"""启动后台行情轮询线程。"""
|
||||
if self._running:
|
||||
return
|
||||
if interval <= 0:
|
||||
from app.services import preferences
|
||||
interval = preferences.get_realtime_quote_interval()
|
||||
self._interval = self._clamp_interval(interval)
|
||||
self._running = True
|
||||
self._enabled = True
|
||||
self._thread = threading.Thread(target=self._poll_loop, daemon=True)
|
||||
self._thread.start()
|
||||
self._save_enabled(True)
|
||||
logger.info("行情服务已启动, 轮询间隔 %.1fs", self._interval)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""停止后台行情轮询线程。"""
|
||||
self._running = False
|
||||
self._enabled = False
|
||||
if self._thread:
|
||||
self._thread.join(timeout=10)
|
||||
self._thread = None
|
||||
self._save_enabled(False)
|
||||
logger.info("行情服务已停止")
|
||||
|
||||
def enable(self) -> bool:
|
||||
"""开启自动行情 (不立即启动线程,等下一个交易时段)。
|
||||
|
||||
none 档无实时行情权限,拒绝开启并返回 False;
|
||||
free 档开启自选股实时,starter+ 开启全市场实时。返回值表示是否真正开启。
|
||||
"""
|
||||
if not self.is_realtime_allowed():
|
||||
logger.warning("实时行情开启被拒:当前档位(none)无实时行情权限")
|
||||
return False
|
||||
self._enabled = True
|
||||
self._save_enabled(True)
|
||||
if not self._running:
|
||||
from app.services import preferences
|
||||
self._interval = self._clamp_interval(preferences.get_realtime_quote_interval())
|
||||
self._running = True
|
||||
self._thread = threading.Thread(target=self._poll_loop, daemon=True)
|
||||
self._thread.start()
|
||||
logger.info("行情服务已启用, 轮询间隔 %.1fs", self._interval)
|
||||
|
||||
def disable(self) -> None:
|
||||
"""关闭自动行情。"""
|
||||
self.stop()
|
||||
logger.info("行情服务已关闭")
|
||||
|
||||
def boot_check(self) -> None:
|
||||
"""启动时检查 preferences,若 enabled 则自动启动。
|
||||
|
||||
none 档无实时行情权限:即使 preferences 标记为 enabled,
|
||||
也不启动,并同步 preferences 为关闭(避免 UI 误显示已开启)。
|
||||
"""
|
||||
from app.services import preferences
|
||||
if not self.is_realtime_allowed():
|
||||
if preferences.get_realtime_quotes_enabled():
|
||||
self._save_enabled(False)
|
||||
logger.info("实时行情未启动:当前档位(none)无实时行情权限")
|
||||
return
|
||||
if preferences.get_realtime_quotes_enabled():
|
||||
self.start()
|
||||
|
||||
def set_repo(self, repo) -> None:
|
||||
"""注入 KlineRepository, 用于实时落盘。"""
|
||||
self._repo = repo
|
||||
|
||||
def set_app_state(self, app_state) -> None:
|
||||
"""注入 FastAPI app.state, 用于获取 strategy_monitor 等单例。"""
|
||||
self._app_state = app_state
|
||||
|
||||
def set_interval(self, interval: float) -> float:
|
||||
"""运行时更新轮询间隔(立即生效)。"""
|
||||
clamped = self._clamp_interval(interval)
|
||||
self._interval = clamped
|
||||
from app.services import preferences
|
||||
preferences.set_realtime_quote_interval(clamped)
|
||||
logger.info("轮询间隔已更新为 %.1fs", clamped)
|
||||
return clamped
|
||||
|
||||
def get_min_interval(self) -> float:
|
||||
"""返回当前档位允许的最小间隔。"""
|
||||
return self._tier_min_interval()
|
||||
|
||||
def wait_for_update(self, timeout: float = 30.0) -> bool:
|
||||
"""阻塞等待下一次行情更新 (供 SSE 线程使用)。"""
|
||||
self._update_event.clear()
|
||||
return self._update_event.wait(timeout=timeout)
|
||||
|
||||
def wait_for_alert(self, timeout: float = 30.0) -> bool:
|
||||
"""阻塞等待告警 (供 SSE 线程使用)。"""
|
||||
self._alert_event.clear()
|
||||
return self._alert_event.wait(timeout=timeout)
|
||||
|
||||
def notify_depth_updated(self) -> None:
|
||||
"""五档盘口修正完成后调用: 通知 SSE 推送 depth_updated, 触发连板梯队刷新。
|
||||
|
||||
与行情/告警通道独立 — 只刷新连板梯队, 不连带刷新 watchlist 等。
|
||||
"""
|
||||
self._depth_update_event.set()
|
||||
|
||||
def wait_for_depth_update(self, timeout: float = 30.0) -> bool:
|
||||
"""阻塞等待 depth 修正 (供 SSE 线程使用)。"""
|
||||
self._depth_update_event.clear()
|
||||
return self._depth_update_event.wait(timeout=timeout)
|
||||
|
||||
def pop_alerts(self) -> list[dict]:
|
||||
"""取走所有待推送的告警 (线程安全)。"""
|
||||
with self._lock:
|
||||
alerts = self._pending_alerts
|
||||
self._pending_alerts = []
|
||||
return alerts
|
||||
|
||||
# ================================================================
|
||||
# 复盘进度 SSE 通道 — 定时复盘流式生成时, 把事件实时推给前端
|
||||
# ================================================================
|
||||
def push_review_event(self, event_json: str) -> None:
|
||||
"""追加一条复盘进度事件(JSON 字符串), 并唤醒 SSE generator。
|
||||
|
||||
事件格式与 recap_market_stream 的产出一致(meta/delta/error/done),
|
||||
前端 reviewStore 直接消费。背压: 超过上限丢弃最旧(复盘流几百条 delta, 200 够用)。
|
||||
"""
|
||||
with self._lock:
|
||||
self._pending_review.append(event_json)
|
||||
if len(self._pending_review) > self._max_pending_review:
|
||||
overflow = len(self._pending_review) - self._max_pending_review
|
||||
self._pending_review = self._pending_review[overflow:]
|
||||
self._review_event.set()
|
||||
|
||||
def wait_for_review(self, timeout: float = 30.0) -> bool:
|
||||
"""阻塞等待复盘进度事件 (供 SSE 线程使用)。"""
|
||||
self._review_event.clear()
|
||||
return self._review_event.wait(timeout=timeout)
|
||||
|
||||
def pop_review_events(self) -> list[str]:
|
||||
"""取走所有待推送的复盘事件 (线程安全)。"""
|
||||
with self._lock:
|
||||
events = self._pending_review
|
||||
self._pending_review = []
|
||||
return events
|
||||
|
||||
# ================================================================
|
||||
# 档位感知间隔限制
|
||||
# ================================================================
|
||||
|
||||
@staticmethod
|
||||
def _current_tier() -> str:
|
||||
"""获取当前档位名(小写)。"""
|
||||
from app.tickflow.policy import tier_label
|
||||
return tier_label().split()[0].split("+")[0].strip().lower()
|
||||
|
||||
@classmethod
|
||||
def realtime_mode(cls) -> str:
|
||||
"""当前实时行情模式: none / watchlist / full_market。"""
|
||||
tier = cls._current_tier()
|
||||
if tier == "none":
|
||||
return "none"
|
||||
if tier == "free":
|
||||
return "watchlist"
|
||||
return "full_market"
|
||||
|
||||
@classmethod
|
||||
def is_realtime_allowed(cls) -> bool:
|
||||
"""当前档位是否允许使用实时行情。"""
|
||||
return cls.realtime_mode() != "none"
|
||||
|
||||
@classmethod
|
||||
def _tier_min_interval(cls) -> float:
|
||||
tier = cls._current_tier()
|
||||
return cls.TIER_MIN_INTERVAL.get(tier, cls.DEFAULT_INTERVAL)
|
||||
|
||||
def _clamp_interval(self, interval: float) -> float:
|
||||
return max(self._tier_min_interval(), min(self.MAX_INTERVAL, interval))
|
||||
|
||||
# ================================================================
|
||||
# 行情数据访问
|
||||
# ================================================================
|
||||
|
||||
def get_enriched_today(self) -> tuple[pl.DataFrame, date | None]:
|
||||
"""返回今天 enriched 数据 + 日期 (线程安全)。
|
||||
|
||||
所有页面统一通过此方法获取实时行情 + 技术指标。
|
||||
"""
|
||||
if not self._repo:
|
||||
return pl.DataFrame(), None
|
||||
return self._repo.get_enriched_latest()
|
||||
|
||||
def get_quotes_compat(self) -> pl.DataFrame:
|
||||
"""兼容接口: 返回行情 DataFrame (用于盘中选股等需要 last_price/prev_close 的场景)。
|
||||
|
||||
从 _enriched_cache 取 today 的数据, 只选行情基础列, 补上 last_price 别名。
|
||||
不返回指标列, 避免 JOIN live_agg 时列名冲突。
|
||||
"""
|
||||
df, _ = self.get_enriched_today()
|
||||
if df.is_empty():
|
||||
return df
|
||||
|
||||
# 只取盘中选股需要的行情基础列
|
||||
keep = [c for c in [
|
||||
"symbol", "close", "open", "high", "low", "volume", "amount",
|
||||
"prev_close", "change_pct", "change_amount", "amplitude", "turnover_rate",
|
||||
] if c in df.columns]
|
||||
df = df.select(keep)
|
||||
|
||||
# enriched 的 close 等价于 last_price
|
||||
if "close" in df.columns and "last_price" not in df.columns:
|
||||
df = df.with_columns(pl.col("close").alias("last_price"))
|
||||
return df
|
||||
|
||||
def get_index_quotes(self, symbols: list[str] | None = None) -> pl.DataFrame:
|
||||
"""返回实时指数行情缓存。不会触发 TickFlow 请求。"""
|
||||
with self._lock:
|
||||
df = self._index_quotes_cache.clone() if self._index_quotes_cache is not None else pl.DataFrame()
|
||||
if df.is_empty():
|
||||
return df
|
||||
if symbols:
|
||||
return df.filter(pl.col("symbol").is_in(symbols))
|
||||
return df
|
||||
|
||||
def status(self) -> dict:
|
||||
"""返回行情服务状态。"""
|
||||
from app.services import preferences
|
||||
age = (time.perf_counter() - self._fetch_time) * 1000 if self._fetch_time else -1
|
||||
mode = self.realtime_mode()
|
||||
return {
|
||||
"enabled": self._enabled,
|
||||
"running": self._running,
|
||||
"mode": mode,
|
||||
"realtime_allowed": mode != "none",
|
||||
"watchlist_symbol_count": len(preferences.get_realtime_watchlist_symbols()),
|
||||
"interval_s": self._interval,
|
||||
"symbol_count": self._symbol_count,
|
||||
"index_symbol_count": self._index_symbol_count,
|
||||
"etf_symbol_count": self._etf_symbol_count,
|
||||
"quote_age_ms": round(age, 0) if age >= 0 else None,
|
||||
"is_trading_hours": self._is_trading_hours(),
|
||||
"last_fetch_ms": round(self._fetched_at, 0) if self._fetched_at else None,
|
||||
}
|
||||
|
||||
def refresh(self) -> dict:
|
||||
"""手动触发一次行情拉取。"""
|
||||
self._fetch_quotes()
|
||||
return self.status()
|
||||
|
||||
# ================================================================
|
||||
# 后台轮询
|
||||
# ================================================================
|
||||
|
||||
def _poll_loop(self) -> None:
|
||||
while self._running and self._enabled:
|
||||
try:
|
||||
if self._is_trading_hours():
|
||||
self._fetch_quotes()
|
||||
else:
|
||||
logger.debug("非交易时段, 跳过行情轮询")
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("行情轮询异常: %s", e)
|
||||
|
||||
waited = 0.0
|
||||
while self._running and self._enabled and waited < self._interval:
|
||||
time.sleep(0.5)
|
||||
waited += 0.5
|
||||
|
||||
def _fetch_quotes(self) -> None:
|
||||
"""按当前档位拉取行情。"""
|
||||
if self.realtime_mode() == "watchlist":
|
||||
self._fetch_watchlist_quotes()
|
||||
return
|
||||
self._fetch_full_market_quotes()
|
||||
|
||||
def _fetch_full_market_quotes(self) -> None:
|
||||
"""拉取全市场行情 → 写 daily + 计算 enriched + 更新缓存。"""
|
||||
from app.tickflow.client import get_paid_realtime_client
|
||||
|
||||
tf = get_paid_realtime_client()
|
||||
if tf is None:
|
||||
logger.warning("实时行情拉取失败:未配置付费服务器 API Key")
|
||||
return
|
||||
t0 = time.perf_counter()
|
||||
now_ts = time.perf_counter()
|
||||
|
||||
try:
|
||||
from app.services import preferences
|
||||
all_index_symbols = set(self._repo.get_index_symbol_set()) if self._repo else set()
|
||||
core_index_symbols = set(preferences.get_realtime_index_symbols() or self.CORE_INDEX_SYMBOLS)
|
||||
all_index_symbols.update(core_index_symbols)
|
||||
all_etf_symbols = set()
|
||||
if self._repo:
|
||||
etf_inst = self._repo.get_etf_instruments()
|
||||
if not etf_inst.is_empty() and "symbol" in etf_inst.columns:
|
||||
all_etf_symbols = set(etf_inst["symbol"].cast(pl.Utf8).to_list())
|
||||
|
||||
universes: list[str] = []
|
||||
if preferences.get_realtime_pull_stock():
|
||||
universes.append("CN_Equity_A")
|
||||
if preferences.get_realtime_pull_etf() and all_etf_symbols:
|
||||
universes.append("CN_ETF")
|
||||
if preferences.get_realtime_pull_index() and preferences.get_realtime_index_mode() == "all":
|
||||
universes.append("CN_Index")
|
||||
|
||||
resp = []
|
||||
if universes:
|
||||
resp.extend(tf.quotes.get_by_universes(universes=universes) or [])
|
||||
if preferences.get_realtime_pull_index() and preferences.get_realtime_index_mode() == "core":
|
||||
resp.extend(tf.quotes.get(symbols=sorted(core_index_symbols)) or [])
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("行情拉取失败: %s", e)
|
||||
return
|
||||
|
||||
if not resp:
|
||||
logger.warning("行情数据为空")
|
||||
return
|
||||
|
||||
# ---- 解析 API 响应 (临时变量, 用完丢弃) ----
|
||||
records = []
|
||||
for q in resp:
|
||||
ext = q.get("ext") or {}
|
||||
last_price = q.get("last_price")
|
||||
prev_close = q.get("prev_close")
|
||||
change_amount = ext.get("change_amount")
|
||||
change_pct = ext.get("change_pct")
|
||||
if change_amount is None and last_price is not None and prev_close is not None:
|
||||
change_amount = float(last_price) - float(prev_close)
|
||||
if change_pct is None and change_amount is not None and prev_close not in (None, 0):
|
||||
change_pct = float(change_amount) / float(prev_close) * 100
|
||||
records.append({
|
||||
"symbol": q.get("symbol"),
|
||||
"name": q.get("name") or ext.get("name"),
|
||||
"last_price": last_price,
|
||||
"prev_close": prev_close,
|
||||
"open": q.get("open"),
|
||||
"high": q.get("high"),
|
||||
"low": q.get("low"),
|
||||
"volume": q.get("volume"),
|
||||
"amount": q.get("amount"),
|
||||
"change_pct": change_pct,
|
||||
"change_amount": change_amount,
|
||||
"amplitude": ext.get("amplitude"),
|
||||
"turnover_rate": ext.get("turnover_rate"),
|
||||
"timestamp": q.get("timestamp"),
|
||||
"session": q.get("session"),
|
||||
})
|
||||
|
||||
index_records = [r for r in records if r.get("symbol") in all_index_symbols]
|
||||
etf_records = [r for r in records if r.get("symbol") in all_etf_symbols]
|
||||
stock_records = [
|
||||
r for r in records
|
||||
if r.get("symbol") not in all_index_symbols and r.get("symbol") not in all_etf_symbols
|
||||
]
|
||||
|
||||
fetch_ms = (time.perf_counter() - t0) * 1000
|
||||
fetched_at = time.time() * 1000
|
||||
|
||||
# ---- 更新元信息 ----
|
||||
with self._lock:
|
||||
self._fetch_time = now_ts
|
||||
self._fetch_ms = fetch_ms
|
||||
self._fetched_at = fetched_at
|
||||
self._symbol_count = len(stock_records)
|
||||
self._index_symbol_count = len(index_records)
|
||||
self._etf_symbol_count = len(etf_records)
|
||||
self._index_quotes_cache = self._build_index_quotes(index_records)
|
||||
|
||||
logger.info("行情刷新: %d 只股票, %d 只ETF, %d 只指数, 耗时 %.0fms", len(stock_records), len(etf_records), len(index_records), fetch_ms)
|
||||
|
||||
# ---- 写 kline_daily (不复权原始价格, 只有 OHLCV) ----
|
||||
daily_df = self._build_daily(stock_records)
|
||||
if not daily_df.is_empty() and self._repo:
|
||||
try:
|
||||
self._repo.flush_live_daily(daily_df)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("日K写盘失败: %s", e)
|
||||
|
||||
etf_daily_df = self._build_daily(etf_records)
|
||||
if not etf_daily_df.is_empty() and self._repo:
|
||||
try:
|
||||
self._repo.flush_live_daily_asset("etf", etf_daily_df)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("ETF 日K写盘失败: %s", e)
|
||||
|
||||
# ---- 构建 API 直接值的补充表 (不写 daily, 只用于 enriched 计算) ----
|
||||
quote_extra = self._build_quote_extra(stock_records)
|
||||
etf_quote_extra = self._build_quote_extra(etf_records)
|
||||
|
||||
# ---- 增量计算 enriched + 写盘 + 更新缓存 ----
|
||||
if not daily_df.is_empty() and self._repo:
|
||||
self._flush_live_enriched(daily_df, quote_extra, asset_type="stock")
|
||||
if not etf_daily_df.is_empty() and self._repo:
|
||||
self._flush_live_enriched(etf_daily_df, etf_quote_extra, asset_type="etf")
|
||||
|
||||
# ---- 通知 SSE ----
|
||||
self._update_event.set()
|
||||
|
||||
# ---- 策略监控 + 告警评估 ----
|
||||
self._evaluate_monitors(daily_df, quote_extra)
|
||||
|
||||
def _fetch_watchlist_quotes(self) -> None:
|
||||
"""Free 档自选股实时: 只拉取最多 5 个 symbols。"""
|
||||
from app.services import preferences
|
||||
from app.tickflow.client import get_paid_realtime_client
|
||||
|
||||
symbols = preferences.get_realtime_watchlist_symbols()
|
||||
if not symbols:
|
||||
logger.info("自选实时未配置标的, 跳过行情拉取")
|
||||
return
|
||||
|
||||
tf = get_paid_realtime_client()
|
||||
if tf is None:
|
||||
logger.warning("自选实时拉取失败:未配置付费服务器 API Key")
|
||||
return
|
||||
|
||||
t0 = time.perf_counter()
|
||||
now_ts = time.perf_counter()
|
||||
try:
|
||||
resp = tf.quotes.get(symbols=symbols) or []
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("自选实时拉取失败: %s", e)
|
||||
return
|
||||
|
||||
if not resp:
|
||||
logger.warning("自选实时行情数据为空")
|
||||
return
|
||||
|
||||
records = []
|
||||
for q in resp:
|
||||
ext = q.get("ext") or {}
|
||||
last_price = q.get("last_price")
|
||||
prev_close = q.get("prev_close")
|
||||
change_amount = ext.get("change_amount")
|
||||
change_pct = ext.get("change_pct")
|
||||
if change_amount is None and last_price is not None and prev_close is not None:
|
||||
change_amount = float(last_price) - float(prev_close)
|
||||
if change_pct is None and change_amount is not None and prev_close not in (None, 0):
|
||||
change_pct = float(change_amount) / float(prev_close) * 100
|
||||
records.append({
|
||||
"symbol": q.get("symbol"),
|
||||
"name": q.get("name") or ext.get("name"),
|
||||
"last_price": last_price,
|
||||
"prev_close": prev_close,
|
||||
"open": q.get("open"),
|
||||
"high": q.get("high"),
|
||||
"low": q.get("low"),
|
||||
"volume": q.get("volume"),
|
||||
"amount": q.get("amount"),
|
||||
"change_pct": change_pct,
|
||||
"change_amount": change_amount,
|
||||
"amplitude": ext.get("amplitude"),
|
||||
"turnover_rate": ext.get("turnover_rate"),
|
||||
"timestamp": q.get("timestamp"),
|
||||
"session": q.get("session"),
|
||||
})
|
||||
|
||||
fetch_ms = (time.perf_counter() - t0) * 1000
|
||||
fetched_at = time.time() * 1000
|
||||
with self._lock:
|
||||
self._fetch_time = now_ts
|
||||
self._fetch_ms = fetch_ms
|
||||
self._fetched_at = fetched_at
|
||||
self._symbol_count = len(records)
|
||||
self._index_symbol_count = 0
|
||||
self._etf_symbol_count = 0
|
||||
self._index_quotes_cache = None
|
||||
|
||||
logger.info("自选实时刷新: %d 只股票, 耗时 %.0fms", len(records), fetch_ms)
|
||||
|
||||
daily_df = self._build_daily(records)
|
||||
quote_extra = self._build_quote_extra(records)
|
||||
if not daily_df.is_empty() and self._repo:
|
||||
try:
|
||||
self._repo.merge_live_daily_asset("stock", daily_df)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("自选实时日K写盘失败: %s", e)
|
||||
self._flush_live_enriched(daily_df, quote_extra, asset_type="stock", merge=True)
|
||||
|
||||
self._update_event.set()
|
||||
self._evaluate_monitors(daily_df, quote_extra)
|
||||
|
||||
# ================================================================
|
||||
# 工具
|
||||
# ================================================================
|
||||
|
||||
@staticmethod
|
||||
def _build_daily(records: list[dict]) -> pl.DataFrame:
|
||||
"""将 API records 转为日K格式 DataFrame (只有 OHLCV, 写 kline_daily 用)。"""
|
||||
if not records:
|
||||
return pl.DataFrame()
|
||||
df = pl.DataFrame(records)
|
||||
cols_map = {
|
||||
"symbol": "symbol",
|
||||
"last_price": "close",
|
||||
"open": "open",
|
||||
"high": "high",
|
||||
"low": "low",
|
||||
"volume": "volume",
|
||||
"amount": "amount",
|
||||
}
|
||||
select_exprs = []
|
||||
for src, dst in cols_map.items():
|
||||
if src in df.columns:
|
||||
select_exprs.append(pl.col(src).alias(dst))
|
||||
if not select_exprs:
|
||||
return pl.DataFrame()
|
||||
result = df.select(select_exprs).with_columns(
|
||||
pl.lit(date.today()).cast(pl.Date).alias("date"),
|
||||
)
|
||||
# 修复: API 在非交易时段可能返回 open/high/low=0 或 null,
|
||||
# 导致蜡烛从 0 开始。用 close 填充这些异常值。
|
||||
for col in ("open", "high", "low"):
|
||||
if col in result.columns:
|
||||
result = result.with_columns(
|
||||
pl.when((pl.col(col) == 0) | pl.col(col).is_null())
|
||||
.then(pl.col("close"))
|
||||
.otherwise(pl.col(col))
|
||||
.alias(col)
|
||||
)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _build_quote_extra(records: list[dict]) -> pl.DataFrame:
|
||||
"""构建 API 直接提供的补充字段 (不写 daily, 只传给 enriched 计算)。
|
||||
|
||||
包含: prev_close, change_pct, change_amount, amplitude, turnover_rate。
|
||||
"""
|
||||
if not records:
|
||||
return pl.DataFrame()
|
||||
df = pl.DataFrame(records)
|
||||
keep = [c for c in [
|
||||
"symbol", "prev_close", "change_pct", "change_amount",
|
||||
"amplitude", "turnover_rate",
|
||||
] if c in df.columns]
|
||||
if not keep or "symbol" not in keep:
|
||||
return pl.DataFrame()
|
||||
return df.select(keep)
|
||||
|
||||
@staticmethod
|
||||
def _build_index_quotes(records: list[dict]) -> pl.DataFrame:
|
||||
"""构建指数实时行情缓存,不落股票 parquet。
|
||||
|
||||
注意: API 返回的 change_pct/amplitude 是小数 (0.0366 = 3.66%),
|
||||
统一转成百分比输出, 与 _fallback_index_quotes_from_daily 口径一致
|
||||
(前端指数侧不×100, 直接 toFixed(2)% 展示)。
|
||||
"""
|
||||
if not records:
|
||||
return pl.DataFrame()
|
||||
df = pl.DataFrame(records)
|
||||
keep = [c for c in [
|
||||
"symbol", "name", "last_price", "prev_close", "open", "high", "low",
|
||||
"volume", "amount", "change_pct", "change_amount", "amplitude", "timestamp", "session",
|
||||
] if c in df.columns]
|
||||
if not keep or "symbol" not in keep:
|
||||
return pl.DataFrame()
|
||||
df = df.select(keep)
|
||||
# change_pct / amplitude: 小数 → 百分比 (统一指数展示口径)
|
||||
for col in ("change_pct", "amplitude"):
|
||||
if col in df.columns:
|
||||
df = df.with_columns((pl.col(col).cast(pl.Float64) * 100).alias(col))
|
||||
if "last_price" in df.columns and "close" not in df.columns:
|
||||
df = df.with_columns(pl.col("last_price").alias("close"))
|
||||
return df
|
||||
|
||||
@staticmethod
|
||||
def _is_trading_hours() -> bool:
|
||||
now = datetime.now()
|
||||
t = now.time()
|
||||
morning = dt_time(9, 15) <= t <= dt_time(11, 35)
|
||||
afternoon = dt_time(12, 55) <= t <= dt_time(15, 5)
|
||||
return now.weekday() < 5 and (morning or afternoon)
|
||||
|
||||
@staticmethod
|
||||
def _save_enabled(enabled: bool) -> None:
|
||||
from app.services import preferences
|
||||
preferences.save({"realtime_quotes_enabled": enabled})
|
||||
|
||||
# ================================================================
|
||||
# 策略监控
|
||||
# ================================================================
|
||||
|
||||
def _evaluate_monitors(self, daily_df: pl.DataFrame, quote_extra: pl.DataFrame | None) -> None:
|
||||
"""行情更新后评估统一监控规则引擎,并刷新策略结果缓存。"""
|
||||
try:
|
||||
# 获取 enriched 数据 (刚算好的)
|
||||
enriched_today, enriched_date = self.get_enriched_today()
|
||||
if enriched_today.is_empty():
|
||||
return
|
||||
|
||||
all_alerts: list[dict] = []
|
||||
rule_events: list[dict] = []
|
||||
engine = None
|
||||
|
||||
# 通用监控规则评估 (统一引擎: signal/price/market/strategy)
|
||||
if self._app_state:
|
||||
engine = getattr(self._app_state, "monitor_engine", None)
|
||||
if engine and engine.rule_count > 0:
|
||||
# 预构建 symbol → name 映射 (enriched 已 drop name 列, 引擎触发时回填用)
|
||||
try:
|
||||
inst_df = self._app_state.repo.get_instruments()
|
||||
if not inst_df.is_empty() and "symbol" in inst_df.columns and "name" in inst_df.columns:
|
||||
engine.set_name_map({
|
||||
row["symbol"]: row["name"]
|
||||
for row in inst_df.select(["symbol", "name"]).iter_rows(named=True)
|
||||
if row.get("name")
|
||||
})
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("name_map 构建失败 (不影响监控): %s", e)
|
||||
# 连板梯队封单监控: 有 ladder 规则时, 从 depth_service 注入封单量到 enriched
|
||||
eval_df = enriched_today
|
||||
if engine.has_rule_type("ladder"):
|
||||
eval_df = self._inject_sealed_vol(enriched_today, enriched_date)
|
||||
rule_events = engine.evaluate(eval_df)
|
||||
if rule_events:
|
||||
# 落盘到 alerts.jsonl
|
||||
try:
|
||||
from app.services import alert_store
|
||||
alert_store.append_many(
|
||||
self._app_state.repo.store.data_dir, rule_events,
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("告警落盘失败: %s", e)
|
||||
# 转为 SSE 推送格式 (兼容旧 alert schema)
|
||||
for ev in rule_events:
|
||||
all_alerts.append({
|
||||
"source": ev["source"],
|
||||
"type": ev["type"],
|
||||
"rule_id": ev.get("rule_id"),
|
||||
"strategy_id": ev.get("rule_id") if ev["source"] == "strategy" else None,
|
||||
"symbol": ev["symbol"],
|
||||
"name": ev["name"],
|
||||
"message": ev["message"],
|
||||
"price": ev["price"],
|
||||
"change_pct": ev["change_pct"],
|
||||
"signals": ev["signals"],
|
||||
"severity": ev.get("severity", "info"),
|
||||
"conditions": ev.get("conditions") or [],
|
||||
"logic": ev.get("logic") or "and",
|
||||
})
|
||||
|
||||
# 策略页实时回显: 不写文件 (实时行情每轮更新 enriched, 写文件会被 read_cache
|
||||
# 的 mtime 校验判过期, 反复读不到)。监控引擎本轮已算出的结果存在内存
|
||||
# (latest_strategy_results), 由 /api/screener/cached 端点直接叠加读取。
|
||||
|
||||
# 推入待推送队列 + 通知 SSE (含背压保护)
|
||||
if all_alerts:
|
||||
with self._lock:
|
||||
self._pending_alerts.extend(all_alerts)
|
||||
# 背压: 超出上限丢弃最旧
|
||||
if len(self._pending_alerts) > self._max_pending_alerts:
|
||||
overflow = len(self._pending_alerts) - self._max_pending_alerts
|
||||
self._pending_alerts = self._pending_alerts[overflow:]
|
||||
self._alert_event.set()
|
||||
logger.info("监控评估完成: %d 条通知", len(all_alerts))
|
||||
|
||||
# 系统通知 (可选通道, 由 preferences 开关控制)。
|
||||
# cooldown 去重已在 MonitorRuleEngine 做过, 这里只负责转发。
|
||||
self._maybe_send_system_notifications(all_alerts)
|
||||
|
||||
# Webhook 推送 (飞书等外部 IM, 由规则 webhook_enabled 开关控制)。
|
||||
# 紧随系统通知, 同样静默降级不阻断主流程。
|
||||
if rule_events:
|
||||
self._maybe_send_webhook(rule_events, engine)
|
||||
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("监控评估失败: %s", e)
|
||||
|
||||
def _inject_sealed_vol(self, enriched_today: pl.DataFrame, enriched_date) -> pl.DataFrame:
|
||||
"""从 depth_service 取封单量, 作为临时列 _sealed_vol 注入 enriched 副本。
|
||||
|
||||
涨停封单(买一量) + 跌停封单(卖一量)合并, 供 ladder 规则评估。
|
||||
depth 未就绪时返回原 df (不注入, ladder 规则安全降级不触发)。
|
||||
"""
|
||||
try:
|
||||
depth_svc = getattr(self._app_state, "depth_service", None)
|
||||
if not depth_svc:
|
||||
return enriched_today
|
||||
# enriched_date 可能是 date 或字符串, 统一为 date
|
||||
from datetime import date as date_cls
|
||||
target_date = enriched_date if isinstance(enriched_date, date_cls) else date_cls.fromisoformat(str(enriched_date))
|
||||
# 取涨停 + 跌停封单, 合并 {symbol: vol}
|
||||
up_map = depth_svc.get_sealed_map(target_date, is_down=False)
|
||||
down_map = depth_svc.get_sealed_map(target_date, is_down=True)
|
||||
sealed: dict[str, int] = {}
|
||||
for m in (up_map, down_map):
|
||||
for sym, info in m.items():
|
||||
vol = (info or {}).get("vol")
|
||||
if vol and vol > 0:
|
||||
sealed[sym] = vol # 后者覆盖前者 (同 symbol 不可能在涨跌停都封单)
|
||||
if not sealed:
|
||||
return enriched_today
|
||||
# 构造 (symbol, _sealed_vol) DataFrame, join 到 enriched 副本
|
||||
sealed_df = pl.DataFrame({
|
||||
"symbol": list(sealed.keys()),
|
||||
"_sealed_vol": list(sealed.values()),
|
||||
})
|
||||
# 若已有残留列先移除 (避免重复 join 报错)
|
||||
df = enriched_today.drop("_sealed_vol") if "_sealed_vol" in enriched_today.columns else enriched_today
|
||||
return df.join(sealed_df, on="symbol", how="left")
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("封单注入失败 (ladder 规则将不触发): %s", e)
|
||||
return enriched_today
|
||||
|
||||
def _maybe_send_webhook(self, rule_events: list[dict], engine) -> None:
|
||||
"""把告警通过 Webhook 推送到外部 IM (由规则 webhook_enabled 开关控制)。
|
||||
|
||||
- 全局飞书 URL 未配置: 直接返回
|
||||
- 仅推送 webhook_enabled=True 的规则触发的告警
|
||||
- 失败静默, 不阻断主流程
|
||||
- 去重: 复用 MonitorRuleEngine 的 cooldown, 此处不重复去重
|
||||
|
||||
注意: 用 rule_events (含 rule_id) 而非重建后的 all_alerts,
|
||||
以便反查引擎规则判断是否启用推送。
|
||||
"""
|
||||
try:
|
||||
from app.services import preferences
|
||||
from app.services import webhook_adapter
|
||||
|
||||
url = preferences.get_feishu_webhook_url()
|
||||
if not url:
|
||||
return
|
||||
secret = preferences.get_feishu_webhook_secret()
|
||||
|
||||
# 反查规则, 过滤出启用推送的事件
|
||||
source_labels = {
|
||||
"strategy": "策略", "signal": "信号",
|
||||
"price": "价格", "market": "异动",
|
||||
}
|
||||
rules = engine.rules if engine is not None else {}
|
||||
pushed = 0
|
||||
for ev in rule_events:
|
||||
rule = rules.get(ev.get("rule_id"))
|
||||
if not rule or not rule.get("webhook_enabled"):
|
||||
continue
|
||||
source = ev.get("source", "")
|
||||
source_label = source_labels.get(source, source or "通知")
|
||||
symbol = ev.get("symbol") or ""
|
||||
name = ev.get("name") or ""
|
||||
message = ev.get("message") or ""
|
||||
title = f"TickFlow · {source_label}"
|
||||
body = f"{symbol} {name} {message}".strip() if symbol else (message or name)
|
||||
if webhook_adapter.send_feishu(url, title, body, secret):
|
||||
pushed += 1
|
||||
if pushed:
|
||||
logger.info("飞书 Webhook 推送: %d 条", pushed)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("Webhook 推送异常 (不影响告警主流程): %s", e)
|
||||
|
||||
def _maybe_send_system_notifications(self, all_alerts: list[dict]) -> None:
|
||||
"""把告警转发到操作系统通知中心 (由 preferences 开关控制)。
|
||||
|
||||
- 开关关闭: 直接返回
|
||||
- 开关开启: 逐条发系统通知; 失败静默, 不阻断主流程
|
||||
- 去重: 复用 MonitorRuleEngine 的 cooldown, 此处不重复去重
|
||||
- 批量策略事件 (symbol="") 聚合为一条通知, 避免刷屏
|
||||
"""
|
||||
try:
|
||||
from app.services import preferences
|
||||
from app.services import notify_adapter
|
||||
|
||||
if not preferences.get_system_notify_enabled():
|
||||
return
|
||||
|
||||
for ev in all_alerts:
|
||||
# 通知标题: 用 source 分类 (策略/信号/价格/异动)
|
||||
source = ev.get("source", "")
|
||||
source_label = {
|
||||
"strategy": "策略", "signal": "信号",
|
||||
"price": "价格", "market": "异动",
|
||||
}.get(source, source or "通知")
|
||||
|
||||
name = ev.get("name") or ""
|
||||
symbol = ev.get("symbol") or ""
|
||||
message = ev.get("message") or ""
|
||||
|
||||
# 正文: 优先用现成 message, 拼上 symbol/name 让用户一眼定位
|
||||
if symbol:
|
||||
body = f"{symbol} {name} {message}".strip()
|
||||
else:
|
||||
body = message or name
|
||||
|
||||
title = f"TickFlow · {source_label}"
|
||||
notify_adapter.notify(title, body)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("系统通知发送异常 (不影响告警主流程): %s", e)
|
||||
|
||||
@staticmethod
|
||||
def _get_strategy_monitor():
|
||||
"""获取 StrategyMonitorService — 不再使用, 改用 _app_state 注入。"""
|
||||
return None
|
||||
|
||||
# ================================================================
|
||||
# enriched 增量计算
|
||||
# ================================================================
|
||||
|
||||
def _flush_live_enriched(self, daily_df: pl.DataFrame, quote_extra: pl.DataFrame = None, asset_type: str = "stock", merge: bool = False) -> None:
|
||||
"""增量计算今天的 enriched: 用昨天的递推状态 + 今天 OHLCV → 只算今天 5500 行。
|
||||
|
||||
quote_extra: API 直接提供的补充字段 (prev_close, change_pct 等),
|
||||
不写 daily, 直接传给 compute_enriched_today 避免重复计算。
|
||||
"""
|
||||
try:
|
||||
today = date.today()
|
||||
t0 = time.perf_counter()
|
||||
|
||||
# ---- 尝试增量路径 ----
|
||||
live_agg = self._repo.get_live_agg() if asset_type == "stock" else pl.DataFrame()
|
||||
prev_enriched, prev_date = (
|
||||
self._repo.get_enriched_latest()
|
||||
if asset_type == "stock"
|
||||
else self._repo.get_enriched_latest_asset(asset_type)
|
||||
)
|
||||
|
||||
use_incremental = (
|
||||
asset_type == "stock"
|
||||
and not live_agg.is_empty()
|
||||
and not prev_enriched.is_empty()
|
||||
and prev_date is not None
|
||||
)
|
||||
|
||||
if use_incremental:
|
||||
from app.indicators.pipeline import compute_enriched_today
|
||||
instruments = self._repo.get_instruments()
|
||||
# 将 API 直接提供的补充字段 JOIN 到 daily_df
|
||||
today_ohlcv = daily_df
|
||||
if quote_extra is not None and not quote_extra.is_empty():
|
||||
today_ohlcv = daily_df.join(quote_extra, on="symbol", how="left")
|
||||
enriched_today = compute_enriched_today(
|
||||
live_agg=live_agg,
|
||||
prev_enriched=prev_enriched,
|
||||
today_ohlcv=today_ohlcv,
|
||||
instruments=instruments,
|
||||
)
|
||||
if enriched_today.is_empty():
|
||||
logger.warning("增量计算结果为空, 回退到全量计算")
|
||||
use_incremental = False
|
||||
|
||||
# ---- 全量回退路径 ----
|
||||
if not use_incremental:
|
||||
from datetime import timedelta
|
||||
from app.indicators.pipeline import compute_enriched
|
||||
|
||||
logger.info("enriched 全量计算 (live_agg=%s, 上次日期=%s)",
|
||||
"ok" if not live_agg.is_empty() else "空", prev_date)
|
||||
|
||||
cutoff = today - timedelta(days=90)
|
||||
table = "kline_etf_daily" if asset_type == "etf" else "kline_daily"
|
||||
daily_glob = str(self._repo.store.data_dir / table / "**" / "*.parquet")
|
||||
ohlcv_cols = ["symbol", "date", "open", "high", "low", "close", "volume", "amount"]
|
||||
hist_df = (
|
||||
pl.scan_parquet(daily_glob)
|
||||
.filter(pl.col("date") >= cutoff)
|
||||
.sort(["symbol", "date"])
|
||||
.collect()
|
||||
)
|
||||
if hist_df.is_empty():
|
||||
return
|
||||
|
||||
hist_cols = [c for c in ohlcv_cols if c in hist_df.columns]
|
||||
hist_df = hist_df.select(hist_cols).filter(pl.col("date") != today)
|
||||
daily_ohlcv = daily_df.select([c for c in ohlcv_cols if c in daily_df.columns])
|
||||
full_df = pl.concat([hist_df, daily_ohlcv], how="diagonal_relaxed")
|
||||
full_df = full_df.sort(["symbol", "date"])
|
||||
|
||||
factor_dir = "adj_factor_etf" if asset_type == "etf" else "adj_factor"
|
||||
factor_path = self._repo.store.data_dir / factor_dir / "all.parquet"
|
||||
factors = pl.DataFrame()
|
||||
if factor_path.exists():
|
||||
try:
|
||||
factors = pl.read_parquet(factor_path)
|
||||
except Exception:
|
||||
pass
|
||||
instruments = self._repo.get_instruments() if asset_type == "stock" else None
|
||||
|
||||
enriched_full = compute_enriched(full_df, factors=factors, instruments=instruments)
|
||||
enriched_today = enriched_full.filter(pl.col("date") == today)
|
||||
|
||||
if enriched_today.is_empty():
|
||||
return
|
||||
|
||||
# ---- 写盘 + 更新缓存 ----
|
||||
if merge:
|
||||
self._repo.merge_live_enriched_asset(asset_type, enriched_today)
|
||||
else:
|
||||
self._repo.flush_live_enriched_asset(asset_type, enriched_today)
|
||||
|
||||
elapsed = time.perf_counter() - t0
|
||||
mode_label = "增量" if use_incremental else "全量"
|
||||
logger.info("enriched %s: %d 只, %s, 耗时 %.0fms",
|
||||
mode_label, len(enriched_today), today, elapsed * 1000)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("enriched 计算失败: %s", e)
|
||||
@@ -0,0 +1,214 @@
|
||||
"""概念涨幅轮动矩阵 service。
|
||||
|
||||
输出「每列(日期)各自把所有概念按当天涨幅从高到低排序」的矩阵,供前端
|
||||
「概念分析 → 涨幅RPS轮动」对话框渲染。
|
||||
|
||||
数据来源全部复用现有资产, 不引入新数据源:
|
||||
- 个股历史涨跌幅: repo.get_enriched_range(..., columns=["symbol","date","change_pct"])
|
||||
命中启动时构建的 _enriched_history_cache (0ms, 含 change_pct 小数列)
|
||||
- 概念成分股映射: 复用 market_overview_builder 的 _dimension_field / _read_ext_rows /
|
||||
_symbol_keys / _dimension_values, 与看板/复盘的概念聚合口径完全一致
|
||||
|
||||
性能: 387 概念 × 30 天的 group_by + sort 是 polars 内存操作, 实测 <50ms;
|
||||
另加进程级结果缓存 (_CACHE_TTL=120s), 重复请求 <1ms。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
|
||||
import polars as pl
|
||||
|
||||
from app.services.market_overview_builder import (
|
||||
_dimension_field,
|
||||
_dimension_values,
|
||||
_read_ext_rows,
|
||||
_symbol_keys,
|
||||
)
|
||||
from app.services.ext_data import ExtConfigStore
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 进程级结果缓存 (照搬 overview.py:18 的模式, TTL 拉长到 120s —— 轮动矩阵
|
||||
# 不像看板那样需要近实时, 盘后数据稳定, 缓存久一点无妨)
|
||||
_CACHE_TTL = 120.0
|
||||
_cache: dict[str, dict] = {}
|
||||
_cache_ts: dict[str, float] = {}
|
||||
|
||||
|
||||
def invalidate_cache() -> None:
|
||||
"""清空轮动矩阵结果缓存(数据管道完成后调用, 避免返回旧数据)。"""
|
||||
_cache.clear()
|
||||
_cache_ts.clear()
|
||||
|
||||
|
||||
def _latest_enriched_date(repo) -> date | None:
|
||||
"""取 enriched 缓存里的最新交易日(矩阵的右端=最新日期)。"""
|
||||
cache = repo._enriched_history_cache # noqa: SLF001 —— 缓存字段无公开 getter
|
||||
if cache is None or cache.is_empty() or "date" not in cache.columns:
|
||||
return None
|
||||
return cache["date"].max()
|
||||
|
||||
|
||||
def _load_concept_map_df(repo) -> tuple[pl.DataFrame, int]:
|
||||
"""构建并缓存 {symbol_upper → 概念} 的已展开 polars 映射表。
|
||||
|
||||
复用 market_overview_builder 的概念识别 + 成分股读取逻辑(_dimension_field /
|
||||
_read_ext_rows / _symbol_keys / _dimension_values), 但要的是「反向映射」
|
||||
(symbol → 概念), 且直接产出 polars DataFrame 供 join 使用。
|
||||
|
||||
返回 (map_df, concept_count):
|
||||
- map_df: 两列 (_sym_up: 大写 symbol, concept: 概念名), 已 explode, 一个
|
||||
symbol 属多概念时有多行。无概念数据时返回空 DataFrame。
|
||||
- concept_count: 去重概念总数。
|
||||
|
||||
缓存: 概念成分股是 snapshot, 进程内不变, 缓存 600s。
|
||||
直接缓存 DataFrame 而非 Python dict —— 后续 join 时省掉每次 ~1s 的 dict→DataFrame
|
||||
重建开销(这是结果缓存失效后重算的主要瓶颈)。
|
||||
"""
|
||||
global _concept_map_cache, _concept_map_count, _concept_map_ts
|
||||
now = time.time()
|
||||
if _concept_map_cache is not None and (now - _concept_map_ts) < 600:
|
||||
return _concept_map_cache, _concept_map_count
|
||||
|
||||
data_dir = repo.store.data_dir
|
||||
store = ExtConfigStore(data_dir)
|
||||
# 先收集成扁平的 (sym, concept) 行, 再一次性构造 DataFrame(比 list 列快得多)
|
||||
pairs: list[tuple[str, str]] = []
|
||||
concepts_seen: set[str] = set()
|
||||
|
||||
for config in store.load_all():
|
||||
field = _dimension_field(config, "concept")
|
||||
if not field:
|
||||
continue
|
||||
for ext_row in _read_ext_rows(data_dir, config, field):
|
||||
concepts = _dimension_values(ext_row.get(field))
|
||||
if not concepts:
|
||||
continue
|
||||
keys = _symbol_keys(ext_row, config)
|
||||
for key in keys:
|
||||
for c in concepts:
|
||||
pairs.append((key, c))
|
||||
concepts_seen.add(c)
|
||||
|
||||
if pairs:
|
||||
# 去重: 同一 (symbol, concept) 对会因多 key 形式(SZ/000001)和
|
||||
# 多 config 重复出现, 去重后从 ~48万 行降到 ~14万, join 快 3x+
|
||||
_concept_map_cache = pl.DataFrame(
|
||||
{"_sym_up": [p[0] for p in pairs], "concept": [p[1] for p in pairs]},
|
||||
schema={"_sym_up": pl.Utf8, "concept": pl.Utf8},
|
||||
).unique()
|
||||
_concept_map_count = len(concepts_seen)
|
||||
else:
|
||||
_concept_map_cache = pl.DataFrame(
|
||||
schema={"_sym_up": pl.Utf8, "concept": pl.Utf8}
|
||||
)
|
||||
_concept_map_count = 0
|
||||
_concept_map_ts = now
|
||||
return _concept_map_cache, _concept_map_count
|
||||
|
||||
|
||||
_concept_map_cache: pl.DataFrame | None = None
|
||||
_concept_map_count: int = 0
|
||||
_concept_map_ts: float = 0.0
|
||||
|
||||
|
||||
def build_rps_rotation(repo, days: int = 12) -> dict:
|
||||
"""构建概念涨幅轮动矩阵。
|
||||
|
||||
Args:
|
||||
repo: KlineRepository(含 _enriched_history_cache 内存历史)。
|
||||
days: 取最近 N 个交易日, 范围 [7, 30], 默认 12。
|
||||
|
||||
Returns:
|
||||
{
|
||||
"dates": ["2026-06-30", ...], # 最新在最前, 长度 ≤ days
|
||||
"columns": {"2026-06-30": [[概念, 涨幅], ...], ...}, # 每列各自排序(高→低)
|
||||
"concept_count": 387, # 去重概念总数(0 表示无概念数据)
|
||||
}
|
||||
涨幅是小数(0.0522 = +5.22%)。无数据时返回空 columns。
|
||||
"""
|
||||
days = max(7, min(30, days))
|
||||
|
||||
# 结果缓存: 同 days(→ 同 start/end)的请求在 TTL 内直接返回
|
||||
latest = _latest_enriched_date(repo)
|
||||
if latest is None:
|
||||
return {"dates": [], "columns": {}, "concept_count": 0}
|
||||
|
||||
cache_key = latest.isoformat()
|
||||
now = time.time()
|
||||
cached = _cache.get(cache_key)
|
||||
if cached and (now - _cache_ts.get(cache_key, 0)) < _CACHE_TTL:
|
||||
# 缓存的是所有日期, 按需要的 days 截取(避免不同 days 各存一份)
|
||||
return _slice_cached(cached, days)
|
||||
|
||||
# 1. 概念映射(symbol → 概念), 已缓存为 polars DataFrame
|
||||
map_df, concept_count = _load_concept_map_df(repo)
|
||||
if map_df.is_empty():
|
||||
logger.info("rps_rotation: no concept data (ext_gn_ths not fetched yet)")
|
||||
return {"dates": [], "columns": {}, "concept_count": 0}
|
||||
|
||||
# 2. 取最近 N 交易日的个股 change_pct(命中内存缓存)
|
||||
start = latest - timedelta(days=days * 2 + 10) # 日历天 ≈ 2/3 交易日, 多取余量
|
||||
df = repo.get_enriched_range(
|
||||
start, latest, columns=["symbol", "date", "change_pct"]
|
||||
)
|
||||
if df is None or df.is_empty():
|
||||
return {"dates": [], "columns": {}, "concept_count": 0}
|
||||
|
||||
# 3. 把个股 symbol 映射到概念, 一只股票拆成多行(每个概念一行)
|
||||
# symbol 大写匹配(map_df 的 _sym_up 已大写)
|
||||
df = df.with_columns(pl.col("symbol").str.to_uppercase().alias("_sym_up"))
|
||||
joined = df.join(map_df, on="_sym_up", how="inner").drop("_sym_up")
|
||||
|
||||
if joined.is_empty():
|
||||
return {"dates": [], "columns": {}, "concept_count": 0}
|
||||
|
||||
# 4. 按 (date, concept) 聚合 avg change_pct —— 与 _dimension_rank:288 的简单平均口径一致
|
||||
agg = joined.group_by(["date", "concept"]).agg(
|
||||
pl.col("change_pct").mean().alias("avg_pct")
|
||||
)
|
||||
# 去掉 NaN/Null(停牌等无行情的概念日)
|
||||
agg = agg.filter(pl.col("avg_pct").is_not_null() & pl.col("avg_pct").is_not_nan())
|
||||
|
||||
# 5. 每个日期内按 avg_pct 降序排, 再 group_by 把每组的 (concept, avg_pct)
|
||||
# 收集成并行 list —— 一次 polars 操作拿到全部列, 避免 partition_by 的 tuple key 歧义
|
||||
agg = agg.sort(["date", "avg_pct"], descending=[False, True])
|
||||
grouped = agg.group_by("date", maintain_order=True).agg(
|
||||
pl.col("concept"), pl.col("avg_pct")
|
||||
)
|
||||
# 最新日期排最前
|
||||
grouped = grouped.sort("date", descending=True)
|
||||
|
||||
columns: dict[str, list[list]] = {}
|
||||
all_dates_sorted: list[str] = []
|
||||
for row in grouped.iter_rows(named=True):
|
||||
d_str = str(row["date"])
|
||||
all_dates_sorted.append(d_str)
|
||||
columns[d_str] = list(zip(row["concept"], row["avg_pct"]))
|
||||
|
||||
full = {
|
||||
"dates": [str(d) for d in all_dates_sorted],
|
||||
"columns": columns,
|
||||
"concept_count": concept_count,
|
||||
}
|
||||
|
||||
# 写缓存(存全量, 按需 slice)
|
||||
_cache[cache_key] = full
|
||||
_cache_ts[cache_key] = now
|
||||
|
||||
return _slice_cached(full, days)
|
||||
|
||||
|
||||
def _slice_cached(full: dict, days: int) -> dict:
|
||||
"""从全量缓存截取最近 N 天(days)。"""
|
||||
dates_all = full["dates"]
|
||||
if len(dates_all) <= days:
|
||||
return full
|
||||
keep_dates = dates_all[:days]
|
||||
return {
|
||||
"dates": keep_dates,
|
||||
"columns": {d: full["columns"][d] for d in keep_dates},
|
||||
"concept_count": full["concept_count"],
|
||||
}
|
||||
@@ -0,0 +1,593 @@
|
||||
"""Screener 服务(§6.3)。
|
||||
|
||||
性能优化:
|
||||
- enriched parquet 仅存 14 列基础数据, 指标和信号即时计算
|
||||
- preset 策略: 从内存缓存或即时计算获取完整指标, ~10-50ms
|
||||
- custom SQL: DuckDB (用户传 SQL WHERE 字符串), ~10-50ms
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, timedelta
|
||||
|
||||
import polars as pl
|
||||
|
||||
from app.tickflow.repository import KlineRepository
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── 进程级历史数据缓存 (避免 run_all 每次重新扫描 parquet + 计算指标) ──
|
||||
_history_cache: dict[tuple[date, int], tuple[float, pl.DataFrame]] = {}
|
||||
_HISTORY_CACHE_TTL = 120.0 # 秒
|
||||
|
||||
|
||||
# 内置预设策略 — Polars 表达式方式
|
||||
PRESET_STRATEGIES: dict[str, dict] = {
|
||||
"trend_breakout": {
|
||||
"name": "趋势突破",
|
||||
"description": "MA60 上方 + 60 日新高 + 量能 ≥ 2 倍均量",
|
||||
"filter": (
|
||||
(pl.col("close") > pl.col("ma60"))
|
||||
& pl.col("signal_n_day_high").fill_null(False)
|
||||
& (pl.col("vol_ratio_5d") >= 2.0)
|
||||
),
|
||||
"order_by": "momentum_60d",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
},
|
||||
"ma_golden_cross": {
|
||||
"name": "MA 金叉",
|
||||
"description": "MA5 上穿 MA20 当日触发,量能配合",
|
||||
"filter": (
|
||||
pl.col("signal_ma_golden_5_20").fill_null(False)
|
||||
& (pl.col("vol_ratio_5d") >= 1.2)
|
||||
& (pl.col("close") > pl.col("ma60"))
|
||||
),
|
||||
"order_by": "momentum_20d",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
},
|
||||
"macd_golden": {
|
||||
"name": "MACD 金叉放量",
|
||||
"description": "MACD 金叉当日 + 量能放大",
|
||||
"filter": (
|
||||
pl.col("signal_macd_golden").fill_null(False)
|
||||
& (pl.col("vol_ratio_5d") >= 1.5)
|
||||
),
|
||||
"order_by": "momentum_60d",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
},
|
||||
"volume_price_surge": {
|
||||
"name": "量价齐升",
|
||||
"description": "突破 MA20 + 放量 + 收阳",
|
||||
"filter": (
|
||||
pl.col("signal_ma20_breakout").fill_null(False)
|
||||
& (pl.col("vol_ratio_5d") >= 2.0)
|
||||
& (pl.col("close") > pl.col("open"))
|
||||
),
|
||||
"order_by": "vol_ratio_5d",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
},
|
||||
"low_volatility_leader": {
|
||||
"name": "低波动龙头",
|
||||
"description": "20 日动量为正 + 年化波动 < 30% + MA20 上方",
|
||||
"filter": (
|
||||
(pl.col("momentum_20d") > 0)
|
||||
& (pl.col("annual_vol_20d") < 0.30)
|
||||
& (pl.col("close") > pl.col("ma20"))
|
||||
),
|
||||
"order_by": "momentum_60d",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
},
|
||||
"broken_board_recovery": {
|
||||
"name": "断板反包",
|
||||
"description": "连板 ≥2 后断板 1-2 天,出现放量反包信号",
|
||||
"filter": (
|
||||
pl.col("signal_limit_up").fill_null(False)
|
||||
& (pl.col("vol_ratio_5d") >= 1.5)
|
||||
& (pl.col("change_pct") > 0.03)
|
||||
),
|
||||
"order_by": "change_pct",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
},
|
||||
"oversold_bounce": {
|
||||
"name": "超跌反弹",
|
||||
"description": "RSI14 < 30 超卖区 + 当日收阳 + 放量,抄底信号",
|
||||
"filter": (
|
||||
(pl.col("rsi_14") < 30)
|
||||
& (pl.col("close") > pl.col("open"))
|
||||
& (pl.col("vol_ratio_5d") >= 1.2)
|
||||
),
|
||||
"order_by": "rsi_14",
|
||||
"descending": False,
|
||||
"limit": 100,
|
||||
},
|
||||
"boll_breakout": {
|
||||
"name": "布林突破",
|
||||
"description": "突破布林上轨 + 放量,强势加速信号",
|
||||
"filter": (
|
||||
pl.col("signal_boll_breakout_upper").fill_null(False)
|
||||
& (pl.col("vol_ratio_5d") >= 1.5)
|
||||
),
|
||||
"order_by": "vol_ratio_5d",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
},
|
||||
"bullish_alignment": {
|
||||
"name": "均线多头",
|
||||
"description": "MA5 > MA10 > MA20 > MA60 多头排列 + 短期动量为正",
|
||||
"filter": (
|
||||
(pl.col("ma5") > pl.col("ma10"))
|
||||
& (pl.col("ma10") > pl.col("ma20"))
|
||||
& (pl.col("ma20") > pl.col("ma60"))
|
||||
& (pl.col("momentum_20d") > 0)
|
||||
),
|
||||
"order_by": "momentum_60d",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
},
|
||||
"consecutive_limit_ups": {
|
||||
"name": "连板股",
|
||||
"description": "当日涨停且连续涨停 ≥ 2 天,强势追涨",
|
||||
"filter": (
|
||||
pl.col("signal_limit_up").fill_null(False)
|
||||
& (pl.col("consecutive_limit_ups") >= 2)
|
||||
),
|
||||
"order_by": "consecutive_limit_ups",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
},
|
||||
"pullback_to_support": {
|
||||
"name": "缩量回踩",
|
||||
"description": "回踩 MA20 附近 + 缩量 + 中期趋势向上",
|
||||
"filter": (
|
||||
(pl.col("close") > pl.col("ma20") * 0.98)
|
||||
& (pl.col("close") < pl.col("ma20") * 1.02)
|
||||
& (pl.col("vol_ratio_5d") < 0.8)
|
||||
& (pl.col("close") > pl.col("ma60"))
|
||||
& (pl.col("momentum_20d") > 0)
|
||||
),
|
||||
"order_by": "momentum_60d",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
},
|
||||
"n_day_low_reversal": {
|
||||
"name": "新低反转",
|
||||
"description": "触及 60 日新低后当日收阳放量,反转信号",
|
||||
"filter": (
|
||||
pl.col("signal_n_day_low").fill_null(False)
|
||||
& (pl.col("close") > pl.col("open"))
|
||||
& (pl.col("vol_ratio_5d") >= 1.5)
|
||||
),
|
||||
"order_by": "change_pct",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class ScreenerResult:
|
||||
as_of: date
|
||||
strategy: str | None
|
||||
rows: list[dict] = field(default_factory=list)
|
||||
total: int = 0
|
||||
elapsed_ms: float = 0.0
|
||||
|
||||
|
||||
class ScreenerService:
|
||||
def __init__(self, repo: KlineRepository) -> None:
|
||||
self.repo = repo
|
||||
|
||||
@staticmethod
|
||||
def clear_history_cache() -> None:
|
||||
"""清空进程级 _history_cache (TTL 缓存)。
|
||||
|
||||
清除数据后调用, 避免内存里的旧历史窗口残留导致策略/看板仍命中旧数据。
|
||||
"""
|
||||
_history_cache.clear()
|
||||
|
||||
def _load_enriched_for_date(self, target_date: date) -> pl.DataFrame:
|
||||
"""从 enriched parquet 读取指定日期的基础数据并即时计算完整指标+信号。
|
||||
|
||||
enriched parquet 仅存 14 列。读取后需要即时计算 ma/ema/macd/kdj/rsi/boll/momentum/signal 等列。
|
||||
对于最新日, 优先使用内存缓存 (已包含完整指标)。
|
||||
"""
|
||||
# 优先使用 repo 最新日缓存
|
||||
cache, cache_date = self.repo.get_enriched_latest()
|
||||
if cache is not None and not cache.is_empty() and cache_date == target_date:
|
||||
df = cache
|
||||
# JOIN instruments
|
||||
df_i = self.repo.get_instruments()
|
||||
if not df_i.is_empty():
|
||||
inst_cols = [c for c in ["symbol", "name", "total_shares", "float_shares"] if c in df_i.columns]
|
||||
if "name" not in df.columns:
|
||||
df = df.join(df_i.select(inst_cols), on="symbol", how="left")
|
||||
return df
|
||||
|
||||
# 尝试从 repo 级预计算历史缓存中提取目标日期
|
||||
cached_hist = self.repo.get_enriched_history(target_date, 1)
|
||||
if cached_hist is not None and not cached_hist.is_empty() and "date" in cached_hist.columns:
|
||||
df = cached_hist.filter(pl.col("date") == target_date)
|
||||
if not df.is_empty():
|
||||
logger.debug("_load_enriched_for_date: repo history cache for %s", target_date)
|
||||
# JOIN instruments
|
||||
df_i = self.repo.get_instruments()
|
||||
if not df_i.is_empty():
|
||||
inst_cols = [c for c in ["symbol", "name", "total_shares", "float_shares"] if c in df_i.columns]
|
||||
if "name" not in df.columns:
|
||||
df = df.join(df_i.select(inst_cols), on="symbol", how="left")
|
||||
return df
|
||||
|
||||
# 历史日期: 从 parquet 读取 14 列, 即时计算指标 (慢路径)
|
||||
enriched_dir = self.repo.store.data_dir / "kline_daily_enriched"
|
||||
ds = target_date.isoformat()
|
||||
target_parquet = enriched_dir / f"date={ds}" / "part.parquet"
|
||||
|
||||
if not target_parquet.exists():
|
||||
return pl.DataFrame()
|
||||
|
||||
try:
|
||||
df = pl.read_parquet(target_parquet)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("load_enriched_for_date failed: %s", e)
|
||||
return pl.DataFrame()
|
||||
|
||||
if df.is_empty():
|
||||
return df
|
||||
|
||||
# 即时计算指标: 需要加载历史窗口作 warmup
|
||||
df_full = self._compute_enriched_full(df, target_date)
|
||||
return df_full
|
||||
|
||||
def _compute_enriched_full(self, df_target: pl.DataFrame, target_date: date) -> pl.DataFrame:
|
||||
"""从 14 列基础数据即时计算完整 enriched (含全部指标和信号)。
|
||||
|
||||
读取历史数据作为指标计算的 warmup, 计算完成后只返回目标日期的行。
|
||||
"""
|
||||
from app.indicators.pipeline import compute_indicators, compute_signals, compute_limit_signals
|
||||
|
||||
# 加载 warmup 历史 (目标日期前 ~120 天)
|
||||
enriched_dir = self.repo.store.data_dir / "kline_daily_enriched"
|
||||
start = target_date - timedelta(days=150)
|
||||
read_cols = ["symbol", "date", "open", "high", "low", "close", "volume",
|
||||
"amount", "raw_close", "raw_high", "raw_low"]
|
||||
|
||||
try:
|
||||
lf = (
|
||||
pl.scan_parquet(str(enriched_dir / "**" / "*.parquet"))
|
||||
.filter(
|
||||
(pl.col("date") >= start)
|
||||
& (pl.col("date") <= target_date)
|
||||
)
|
||||
.sort(["symbol", "date"])
|
||||
)
|
||||
available = [c for c in read_cols if c in lf.schema]
|
||||
df_hist = lf.select(available).collect()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("warmup history load failed: %s", e)
|
||||
df_hist = df_target
|
||||
|
||||
if df_hist.is_empty():
|
||||
df_hist = df_target
|
||||
|
||||
# 计算指标
|
||||
df_full = compute_indicators(df_hist)
|
||||
df_full = compute_signals(df_full)
|
||||
|
||||
# 计算涨跌停信号 (需要 instruments)
|
||||
instruments = self.repo.get_instruments()
|
||||
if instruments is not None and not instruments.is_empty():
|
||||
df_full = compute_limit_signals(df_full, instruments)
|
||||
|
||||
# 只保留目标日期
|
||||
df_result = df_full.filter(pl.col("date") == target_date)
|
||||
|
||||
# JOIN instruments (name, total_shares, float_shares)
|
||||
if not instruments.is_empty():
|
||||
inst_cols = [c for c in ["symbol", "name", "total_shares", "float_shares"] if c in instruments.columns]
|
||||
if "name" not in df_result.columns:
|
||||
df_result = df_result.join(instruments.select(inst_cols), on="symbol", how="left")
|
||||
|
||||
return df_result
|
||||
|
||||
def _load_enriched_history(self, target_date: date, lookback_days: int) -> pl.DataFrame:
|
||||
"""读取目标日期之前的基础行情数据, 供历史窗口策略使用。
|
||||
|
||||
优先从 repo 内存缓存获取 (启动时已预计算), 命中时 0ms。
|
||||
缓存 miss 时走 scan_parquet + compute_indicators 慢路径。
|
||||
"""
|
||||
# 优先级 1: repo 级预计算缓存 (启动时 _refresh_enriched 已计算完整历史)
|
||||
t0 = time.perf_counter()
|
||||
cached = self.repo.get_enriched_history(target_date, lookback_days)
|
||||
if cached is not None and not cached.is_empty():
|
||||
# JOIN instruments (repo 缓存不含 name 等列)
|
||||
instruments = self.repo.get_instruments()
|
||||
if instruments is not None and not instruments.is_empty() and "name" not in cached.columns:
|
||||
inst_cols = [c for c in ["symbol", "name", "total_shares", "float_shares"]
|
||||
if c in instruments.columns]
|
||||
cached = cached.join(instruments.select(inst_cols), on="symbol", how="left")
|
||||
elapsed = (time.perf_counter() - t0) * 1000
|
||||
logger.info("_load_enriched_history(%s, %d): repo cache hit, %.1fms, %d rows",
|
||||
target_date, lookback_days, elapsed, len(cached))
|
||||
return cached
|
||||
|
||||
# 优先级 2: 进程级 history_cache (之前的 TTL 缓存)
|
||||
cache_key = (target_date, lookback_days)
|
||||
now = time.monotonic()
|
||||
ttl_cached = _history_cache.get(cache_key)
|
||||
if ttl_cached is not None:
|
||||
ts, cached_df = ttl_cached
|
||||
if now - ts < _HISTORY_CACHE_TTL:
|
||||
logger.debug("history TTL cache hit: %s lookback=%d", target_date, lookback_days)
|
||||
return cached_df
|
||||
del _history_cache[cache_key]
|
||||
|
||||
# 优先级 3: scan_parquet + compute_indicators (慢路径, ~5s)
|
||||
logger.warning("_load_enriched_history cache miss, computing indicators (%s, %d)...",
|
||||
target_date, lookback_days)
|
||||
from app.indicators.pipeline import compute_indicators, compute_signals, compute_limit_signals
|
||||
|
||||
warmup = 60
|
||||
start = target_date - timedelta(days=min((lookback_days + warmup) * 2, 180))
|
||||
|
||||
enriched_dir = self.repo.store.data_dir / "kline_daily_enriched"
|
||||
read_cols = ["symbol", "date", "open", "high", "low", "close", "volume",
|
||||
"amount", "raw_close", "raw_high", "raw_low"]
|
||||
|
||||
try:
|
||||
lf = (
|
||||
pl.scan_parquet(str(enriched_dir / "**" / "*.parquet"))
|
||||
.filter((pl.col("date") >= start) & (pl.col("date") <= target_date))
|
||||
.sort(["symbol", "date"])
|
||||
)
|
||||
available = [c for c in read_cols if c in lf.collect_schema().names()]
|
||||
df_hist = lf.select(available).collect()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("load_enriched_history failed: %s", e)
|
||||
return pl.DataFrame()
|
||||
|
||||
if df_hist.is_empty():
|
||||
return pl.DataFrame()
|
||||
|
||||
df_full = compute_indicators(df_hist)
|
||||
df_full = compute_signals(df_full)
|
||||
|
||||
instruments = self.repo.get_instruments()
|
||||
if instruments is not None and not instruments.is_empty():
|
||||
df_full = compute_limit_signals(df_full, instruments)
|
||||
|
||||
if instruments is not None and not instruments.is_empty():
|
||||
inst_cols = [c for c in ["symbol", "name", "total_shares", "float_shares"] if c in instruments.columns]
|
||||
if "name" not in df_full.columns:
|
||||
df_full = df_full.join(instruments.select(inst_cols), on="symbol", how="left")
|
||||
|
||||
# 裁剪掉 warmup 部分, 只保留 lookback 范围 (减少 group_by 开销)
|
||||
lookback_start = target_date - timedelta(days=lookback_days)
|
||||
if "date" in df_full.columns:
|
||||
df_full = df_full.filter(pl.col("date") >= lookback_start)
|
||||
|
||||
df_full = df_full.sort(["symbol", "date"])
|
||||
|
||||
elapsed = (time.perf_counter() - t0) * 1000
|
||||
logger.info("_load_enriched_history(%s, %d): computed in %.1fms, %d rows",
|
||||
target_date, lookback_days, elapsed, len(df_full))
|
||||
|
||||
_history_cache[cache_key] = (now, df_full)
|
||||
if len(_history_cache) > 10:
|
||||
expired = [k for k, (ts, _) in _history_cache.items() if now - ts > _HISTORY_CACHE_TTL]
|
||||
for k in expired:
|
||||
del _history_cache[k]
|
||||
|
||||
return df_full
|
||||
|
||||
def run(
|
||||
self,
|
||||
as_of: date,
|
||||
conditions: list[str],
|
||||
order_by: str | None = None,
|
||||
limit: int = 30,
|
||||
pool: list[str] | None = None,
|
||||
) -> ScreenerResult:
|
||||
"""自定义 SQL 条件选股。
|
||||
|
||||
先通过 Polars 即时计算完整指标, 再用 DuckDB 做 SQL WHERE 过滤。
|
||||
kline_enriched DuckDB 视图只有 14 列, 不能直接用于指标过滤。
|
||||
"""
|
||||
t0 = time.perf_counter()
|
||||
|
||||
if not conditions:
|
||||
return ScreenerResult(as_of=as_of, strategy=None)
|
||||
|
||||
# 从即时计算获取完整 enriched 数据
|
||||
df = self._load_enriched_for_date(as_of)
|
||||
if df.is_empty():
|
||||
return ScreenerResult(as_of=as_of, strategy=None)
|
||||
|
||||
# Pool 过滤
|
||||
if pool:
|
||||
df = df.filter(pl.col("symbol").is_in(pool))
|
||||
|
||||
# 用 DuckDB 做 SQL 过滤 (注册临时视图)
|
||||
try:
|
||||
import duckdb
|
||||
con = duckdb.connect(database=":memory:")
|
||||
con.register("enriched", df.to_arrow())
|
||||
where = " AND ".join(f"({c})" for c in conditions)
|
||||
sql = f"SELECT * FROM enriched WHERE {where}"
|
||||
if order_by:
|
||||
sql += f" ORDER BY {order_by}"
|
||||
if limit:
|
||||
sql += f" LIMIT {limit}"
|
||||
df_result = con.execute(sql).pl()
|
||||
con.close()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("screener SQL query failed: %s", e)
|
||||
df_result = pl.DataFrame()
|
||||
|
||||
rows = df_result.to_dicts() if not df_result.is_empty() else []
|
||||
elapsed = (time.perf_counter() - t0) * 1000
|
||||
|
||||
return ScreenerResult(
|
||||
as_of=as_of,
|
||||
strategy=None,
|
||||
rows=rows,
|
||||
total=len(rows),
|
||||
elapsed_ms=elapsed,
|
||||
)
|
||||
|
||||
def run_preset(
|
||||
self,
|
||||
strategy_id: str,
|
||||
as_of: date,
|
||||
pool: list[str] | None = None,
|
||||
precomputed: pl.DataFrame | None = None,
|
||||
basic_filter: dict | None = None,
|
||||
display_limit: int | None = None,
|
||||
) -> ScreenerResult:
|
||||
"""预设策略选股 — 从 enriched 读取预计算好的指标列后过滤。
|
||||
|
||||
- precomputed 不为空: 直接复用(run_all 场景)
|
||||
- precomputed 为空: 从 enriched 读目标日期
|
||||
- basic_filter: 用户保存的基础参数过滤(boards、价格等)
|
||||
"""
|
||||
t0 = time.perf_counter()
|
||||
|
||||
strat = PRESET_STRATEGIES.get(strategy_id)
|
||||
if not strat:
|
||||
raise ValueError(f"unknown strategy: {strategy_id}")
|
||||
|
||||
if precomputed is not None and not precomputed.is_empty():
|
||||
df = precomputed
|
||||
else:
|
||||
df = self._load_enriched_for_date(as_of)
|
||||
if df.is_empty():
|
||||
return ScreenerResult(as_of=as_of, strategy=strategy_id)
|
||||
|
||||
# 应用用户基础参数过滤(boards、价格区间等)
|
||||
if basic_filter and basic_filter.get("enabled", True):
|
||||
df = self._apply_basic_filter(df, basic_filter)
|
||||
|
||||
# 应用策略过滤
|
||||
df = df.filter(strat["filter"])
|
||||
|
||||
# 应用 pool
|
||||
if pool:
|
||||
df = df.filter(pl.col("symbol").is_in(pool))
|
||||
|
||||
# 排序 + 限制
|
||||
order_col = strat["order_by"]
|
||||
if order_col in df.columns:
|
||||
df = df.sort(order_col, descending=strat.get("descending", True))
|
||||
|
||||
# display_limit: None=不限制, 0=全部, N=前N个
|
||||
if display_limit == 0:
|
||||
limit = None # 不限制
|
||||
elif display_limit is not None:
|
||||
limit = display_limit
|
||||
else:
|
||||
limit = None # 未配置时默认不限制
|
||||
if limit is not None and limit > 0:
|
||||
df = df.head(limit)
|
||||
|
||||
# 基于排序列生成 0-100 评分 (与 StrategyEngine 统一)
|
||||
if order_col in df.columns and not df.is_empty():
|
||||
col_vals = df[order_col].cast(pl.Float64)
|
||||
col_min = col_vals.min()
|
||||
col_max = col_vals.max()
|
||||
col_range = col_max - col_min
|
||||
if col_range and col_range > 0:
|
||||
normalized = (col_vals - col_min) / col_range
|
||||
else:
|
||||
normalized = pl.Series("norm", [0.5] * len(df))
|
||||
if not strat.get("descending", True):
|
||||
normalized = 1.0 - normalized
|
||||
df = df.with_columns((normalized * 100).alias("score"))
|
||||
|
||||
rows = df.to_dicts()
|
||||
elapsed = (time.perf_counter() - t0) * 1000
|
||||
|
||||
# sanitize
|
||||
for r in rows:
|
||||
for k, v in list(r.items()):
|
||||
if isinstance(v, float) and (v != v or abs(v) == float("inf")):
|
||||
r[k] = None
|
||||
|
||||
return ScreenerResult(
|
||||
as_of=as_of,
|
||||
strategy=strategy_id,
|
||||
rows=rows,
|
||||
total=len(rows),
|
||||
elapsed_ms=elapsed,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _apply_basic_filter(df: pl.DataFrame, bf: dict) -> pl.DataFrame:
|
||||
"""应用用户基础参数过滤(boards、价格区间、市值等)"""
|
||||
exprs: list[pl.Expr] = []
|
||||
if bf.get("price_min") is not None:
|
||||
exprs.append(pl.col("close") >= bf["price_min"])
|
||||
if bf.get("price_max") is not None:
|
||||
exprs.append(pl.col("close") <= bf["price_max"])
|
||||
if bf.get("float_cap_min") is not None and "float_shares" in df.columns:
|
||||
exprs.append(pl.col("close") * pl.col("float_shares") >= bf["float_cap_min"])
|
||||
if bf.get("float_cap_max") is not None and "float_shares" in df.columns:
|
||||
exprs.append(pl.col("close") * pl.col("float_shares") <= bf["float_cap_max"])
|
||||
if bf.get("amount_min") is not None:
|
||||
exprs.append(pl.col("amount") >= bf["amount_min"])
|
||||
if bf.get("amount_max") is not None:
|
||||
exprs.append(pl.col("amount") <= bf["amount_max"])
|
||||
if bf.get("turnover_min") is not None and "turnover_rate" in df.columns:
|
||||
exprs.append(pl.col("turnover_rate") >= bf["turnover_min"])
|
||||
if bf.get("turnover_max") is not None and "turnover_rate" in df.columns:
|
||||
exprs.append(pl.col("turnover_rate") <= bf["turnover_max"])
|
||||
if bf.get("exclude_st") and "name" in df.columns:
|
||||
exprs.append(~pl.col("name").str.contains("(?i)ST|\\*ST|退"))
|
||||
# 板块过滤
|
||||
boards = bf.get("boards")
|
||||
if boards and isinstance(boards, list) and len(boards) > 0:
|
||||
board_exprs: list[pl.Expr] = []
|
||||
for b in boards:
|
||||
if b == "沪主板":
|
||||
board_exprs.append(pl.col("symbol").str.starts_with("60"))
|
||||
elif b == "深主板":
|
||||
board_exprs.append(
|
||||
pl.col("symbol").str.starts_with("00")
|
||||
| pl.col("symbol").str.starts_with("001")
|
||||
)
|
||||
elif b == "创业板":
|
||||
board_exprs.append(
|
||||
pl.col("symbol").str.starts_with("300")
|
||||
| pl.col("symbol").str.starts_with("301")
|
||||
)
|
||||
elif b == "科创板":
|
||||
board_exprs.append(pl.col("symbol").str.starts_with("688"))
|
||||
elif b == "北交所":
|
||||
board_exprs.append(pl.col("symbol").str.contains(r"\.BJ$"))
|
||||
if board_exprs:
|
||||
exprs.append(pl.any_horizontal(board_exprs))
|
||||
if exprs:
|
||||
return df.filter(pl.all_horizontal(exprs))
|
||||
return df
|
||||
|
||||
def latest_date(self) -> date | None:
|
||||
d = self.repo.enriched_latest_date()
|
||||
if d:
|
||||
return d
|
||||
# 回退 DuckDB
|
||||
try:
|
||||
res = self.repo.execute_one(
|
||||
"SELECT max(date) FROM kline_enriched",
|
||||
)
|
||||
if res and res[0]:
|
||||
d = res[0]
|
||||
return d if isinstance(d, date) else date.fromisoformat(str(d))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
return None
|
||||
@@ -0,0 +1,309 @@
|
||||
"""AI 个股分析服务 — 技术面 / 基本面 / 财务面 / 消息面 四维综合分析。
|
||||
|
||||
职责:
|
||||
组合一只股票的 K 线(含已算好的技术指标)+ 财务表 + 关键价位 →
|
||||
拼装"实战派交易员"级系统提示词 → 流式调用 LLM → 逐 chunk 吐给前端。
|
||||
|
||||
与 financial_analyzer.py 的区别(刻意区分,非复用):
|
||||
- 角色:A 股实战派交易员 / 技术分析师(非 CFA 财务分析师)
|
||||
- 数据源:K 线 + 技术指标为主,财务表为辅(财务分析以财务表为主)
|
||||
- 输出框架:技术面→基本面→财务面→消息面(四维),落点是买卖区间与操作建议
|
||||
(财务分析的落点是财务质量评级)
|
||||
|
||||
不知道: HTTP、前端、配置持久化。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import AsyncIterator
|
||||
|
||||
import polars as pl
|
||||
|
||||
from app.indicators.levels import compute_levels, summarize_levels
|
||||
from app.services.financial_sync import get_financial_df
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 注入最近多少根日 K(技术面分析样本)
|
||||
_KLINE_WINDOW = 90
|
||||
# 注入财务表的最近期数
|
||||
_MAX_PERIODS = 4
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 数据加载
|
||||
# ================================================================
|
||||
|
||||
def _load_kline(repo, symbol: str) -> pl.DataFrame:
|
||||
"""读取该标的最近 N 根日 K(已含技术指标 / 信号)。
|
||||
|
||||
repo: KlineRepository;走内存缓存,性能可控。
|
||||
"""
|
||||
from datetime import date, timedelta
|
||||
|
||||
end = date.today()
|
||||
start = end - timedelta(days=_KLINE_WINDOW * 2) # 多取一些保证交易日够
|
||||
df = repo.get_daily(symbol, start, end)
|
||||
if df.is_empty():
|
||||
return df
|
||||
return df.tail(_KLINE_WINDOW)
|
||||
|
||||
|
||||
def _clean_rows(df: pl.DataFrame, keep_cols: list[str]) -> list[dict]:
|
||||
"""把 DataFrame 转成 JSON 安全的 dict 列表(只保留关键列 + 清洗 NaN/Inf + date→字符串)。
|
||||
|
||||
polars 的 date 列会变成 Python datetime.date,json.dumps 无法直接序列化,
|
||||
必须转成 ISO 字符串,否则 json.dumps 抛 TypeError 让整个流静默失败。
|
||||
"""
|
||||
import datetime
|
||||
import math
|
||||
cols = [c for c in keep_cols if c in df.columns]
|
||||
sub = df.select(cols)
|
||||
rows = []
|
||||
for rec in sub.to_dicts():
|
||||
clean = {}
|
||||
for k, v in rec.items():
|
||||
if isinstance(v, float):
|
||||
clean[k] = None if not math.isfinite(v) else round(v, 4)
|
||||
elif isinstance(v, (datetime.date, datetime.datetime)):
|
||||
clean[k] = v.isoformat()
|
||||
else:
|
||||
clean[k] = v
|
||||
rows.append(clean)
|
||||
return rows
|
||||
|
||||
|
||||
def _load_financials(data_dir: Path, symbol: str) -> dict[str, list[dict]]:
|
||||
"""读取该标的核心财务指标 + 利润表(只取最有信息量的两张表)。
|
||||
|
||||
财务面只需要关键指标(ROE / 增速 / 毛利率 等),不需要把 4 张表全塞进上下文
|
||||
(那是 financial_analyzer 的职责)。这里取轻量,留给技术面更多 token。
|
||||
"""
|
||||
out: dict[str, list[dict]] = {}
|
||||
for table in ("metrics", "income"):
|
||||
df = get_financial_df(data_dir, table)
|
||||
if df.is_empty():
|
||||
out[table] = []
|
||||
continue
|
||||
df = df.filter(pl.col("symbol") == symbol)
|
||||
if df.is_empty():
|
||||
out[table] = []
|
||||
continue
|
||||
if "period_end" in df.columns:
|
||||
df = df.sort("period_end", descending=True).head(2) # 只取最近 2 期
|
||||
import math
|
||||
rows = []
|
||||
for rec in df.to_dicts():
|
||||
clean = {}
|
||||
for k, v in rec.items():
|
||||
if k == "symbol":
|
||||
continue
|
||||
if isinstance(v, float):
|
||||
clean[k] = None if not math.isfinite(v) else v
|
||||
else:
|
||||
clean[k] = v
|
||||
rows.append(clean)
|
||||
out[table] = rows
|
||||
return out
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 系统提示词 —— 实战派交易员四维框架(与财务分析明确区分)
|
||||
# ================================================================
|
||||
|
||||
_SYSTEM_PROMPT = """你是一位拥有 15 年 A 股一线实战经验的资深交易员兼技术分析师,擅长从 K 线、量价、关键价位与基本面交叉验证中把握买卖时机。你的任务是:基于提供的个股数据,产出一份**实战、可直接指导交易决策**的综合分析报告。
|
||||
|
||||
## 输出规范
|
||||
|
||||
用 **Markdown** 格式输出,严格遵循以下结构。不要输出任何 JSON 或代码块,直接输出 Markdown 正文。
|
||||
|
||||
### 1. 🎯 一句话定调(1-2 句)
|
||||
用一句话概括该股当前的**技术状态与交易属性**(如"高位放量滞涨,需警惕回调"/"底部筹码集中,放量突破在即")。结尾用【操作建议:观望 / 轻仓试探 / 逢低吸纳 / 持有 / 减仓 / 规避】给出明确倾向。
|
||||
|
||||
### 2. 📈 技术面分析(核心维度)
|
||||
这是你的主战场,务必深入:
|
||||
- **趋势判断**:均线多头/空头排列、20/60 日均线方向、价格在均线之上/下
|
||||
- **形态结构**:近期是否有突破/破位/双底/双顶/旗形等关键形态
|
||||
- **指标信号**:MACD 金叉/死叉/背离、KDJ 超买超卖、RSI 强弱、布林通道位置
|
||||
- **量价配合**:放量上涨/缩量回调/量价背离/换手率异动
|
||||
每条结论必须引用具体数值(如"MACD 在 6/12 出现金叉,DIF 0.32 上穿 DEA 0.18")。
|
||||
|
||||
### 3. 💰 关键价位(买卖区间)
|
||||
基于提供的关键价位数据,明确指出:
|
||||
- **上方压力位**(逐档列出,标注强度):第一压力、第二压力
|
||||
- **下方支撑位**(逐档列出,标注强度):第一支撑、第二支撑
|
||||
- 给出**建议买入区间**与**止损位**(基于支撑位)
|
||||
用数据说话,引用提供的压力/支撑(成交密集区)/枢轴点数值。
|
||||
|
||||
### 4. 🏭 基本面与财务面(辅助验证)
|
||||
简要点评(2-4 句,不展开长篇):
|
||||
- 盈利质量(ROE / 毛利率水平)、成长性(营收/利润增速)
|
||||
- 与技术面的**交叉验证**:好公司 + 技术面走坏 → 仍需谨慎;差公司 + 技术面强势 → 警惕炒作风险
|
||||
|
||||
**当用户消息中标注了"该标的暂无财务数据"时**,本节请输出:
|
||||
> 📌 财务面分析能力正在接入中。当前版本(Free)未同步该标的的财务报表,基本面维度暂无法评估。
|
||||
> 技术面分析不依赖财务数据,以下结论依然有效;升级套餐或等待财务数据同步后可补充本维度。
|
||||
|
||||
**绝对不要**在无数据时编造 ROE / 增速等数字。
|
||||
|
||||
### 5. 📰 消息面(价量异动推断)
|
||||
**注意:本期无直接新闻数据输入。** 请基于 K 线的**异动信号**进行推断(如:
|
||||
- 涨停/连板/炸板 → 可能有利好或资金炒作
|
||||
- 放量暴跌 → 可能有未公开利空
|
||||
- 突破放量 → 可能有催化剂
|
||||
明确标注"[推断]",告诉用户这是基于价量的推测,真实消息面数据待接入。若无明显异动,直说"近期价量平稳,无明显消息面信号"。
|
||||
|
||||
### 6. ⚖️ 综合研判与操作建议
|
||||
2-3 段:
|
||||
- 该股当前处于(底部启动 / 上升途中 / 高位震荡 / 下跌趋势 / 底部企稳)哪个阶段
|
||||
- 风险收益比评估(距支撑位的空间 vs 距压力位的空间)
|
||||
- **明确操作建议**:激进型 / 稳健型 / 保守型 分别怎么应对
|
||||
- **需要重点盯的信号**(如跌破 X 支撑止损、站上 Y 压力加仓)
|
||||
|
||||
## 分析准则(务必遵守)
|
||||
|
||||
1. **技术面优先**:作为交易员,技术面和量价是主要依据,基本面是验证手段,主次分明
|
||||
2. **数据说话**:每个判断引用具体数值,严禁空泛套话("走势良好"必须改成"连续 3 日站稳 20 日均线且放量")
|
||||
3. **诚实中立**:看多就写多,看空就写空,不要模棱两可骑墙;数据不支持时直言无法判断
|
||||
4. **价位精确**:买卖区间必须落到具体价格,基于提供的关键价位数据推演
|
||||
5. **风险前置**:任何买入建议都要配止损位;提示潜在风险不回避
|
||||
6. **简明实战**:用交易员能扫读的密度输出,总字数 1000-1800 字,重在可执行
|
||||
|
||||
## 重要免责
|
||||
报告末尾附一行:"> ⚠️ 本报告由 AI 基于公开行情与财务数据生成,仅供参考,不构成任何投资建议。交易有风险,入市需谨慎。"
|
||||
|
||||
现在请基于下方数据进行分析。"""
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 用户消息构建
|
||||
# ================================================================
|
||||
|
||||
def _build_user_prompt(
|
||||
kline_tail: list[dict],
|
||||
fins: dict[str, list[dict]],
|
||||
levels: dict[str, list[dict]],
|
||||
close: float | None,
|
||||
symbol: str,
|
||||
focus: str,
|
||||
) -> str:
|
||||
"""构建用户消息:标的 + 价位摘要 + 技术指标 JSON + 财务摘要 + 关注点。"""
|
||||
parts: list[str] = [
|
||||
f"标的标准代码: {symbol}",
|
||||
f"关键价位概览: {summarize_levels(levels, close)}",
|
||||
"",
|
||||
"以下是该标的最近日 K 数据(JSON,含 OHLCV 与已计算的技术指标。"
|
||||
f"最近 {_KLINE_WINDOW} 个交易日,升序):",
|
||||
"```json",
|
||||
json.dumps(kline_tail, ensure_ascii=False),
|
||||
"```",
|
||||
]
|
||||
|
||||
has_fin = any(fins.values())
|
||||
if has_fin:
|
||||
parts.extend([
|
||||
"",
|
||||
"以下是该标的最新财务数据(JSON,核心指标 + 利润表,金额单位为元):",
|
||||
"```json",
|
||||
json.dumps(fins, ensure_ascii=False),
|
||||
"```",
|
||||
])
|
||||
else:
|
||||
parts.extend([
|
||||
"",
|
||||
"(该标的暂无财务数据:当前为 Free 模式或尚未同步财务报表。"
|
||||
"请按系统提示词第 4 节的说明,在基本面/财务面维度给出\"接入中\"的友好提示,不要编造数据。)",
|
||||
])
|
||||
|
||||
if focus.strip():
|
||||
parts.extend(["", f"本次分析请特别关注: {focus.strip()}"])
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 关键列筛选(控制上下文体积)
|
||||
# ================================================================
|
||||
|
||||
_KLINE_KEEP_COLS = [
|
||||
"date", "open", "high", "low", "close", "volume", "change_pct",
|
||||
"ma5", "ma10", "ma20", "ma60",
|
||||
"macd_dif", "macd_dea", "macd_hist",
|
||||
"kdj_k", "kdj_d", "kdj_j",
|
||||
"rsi_6", "rsi_14", "rsi_24",
|
||||
"boll_upper", "boll_mid", "boll_lower",
|
||||
"atr_14", "vol_ratio_5d", "turnover_rate",
|
||||
"consecutive_limit_ups",
|
||||
# 信号类(布尔)——只挑对消息面推断有用的几个
|
||||
"signal_limit_up", "signal_broken_limit_up", "signal_macd_golden",
|
||||
"signal_macd_death", "signal_ma_golden_5_20", "signal_volume_surge",
|
||||
"signal_boll_breakout_upper", "signal_boll_breakout_lower",
|
||||
]
|
||||
|
||||
|
||||
# ================================================================
|
||||
# 流式分析入口
|
||||
# ================================================================
|
||||
|
||||
async def analyze_stock_stream(
|
||||
repo,
|
||||
data_dir: Path,
|
||||
symbol: str,
|
||||
focus: str = "",
|
||||
) -> AsyncIterator[str]:
|
||||
"""流式个股分析:yield 出每个 NDJSON 事件。
|
||||
|
||||
协议(与 financial_analyzer 一致,前端解析无差异):
|
||||
{"type":"meta","symbol","summary","levels"} 数据 + 价位摘要
|
||||
{"type":"delta","content":"..."} 逐 chunk 文本
|
||||
{"type":"error","message":"..."}
|
||||
{"type":"done"}
|
||||
"""
|
||||
# 1. 加载 K 线
|
||||
df = _load_kline(repo, symbol)
|
||||
if df.is_empty():
|
||||
yield json.dumps({
|
||||
"type": "error",
|
||||
"message": f"标的 {symbol} 暂无日 K 数据,请先同步",
|
||||
}, ensure_ascii=False)
|
||||
return
|
||||
|
||||
# 2. 价位计算(基于 K 线)
|
||||
levels = compute_levels(df)
|
||||
close = float(df.tail(1)["close"][0]) if "close" in df.columns else None
|
||||
|
||||
# 3. 财务(辅助)
|
||||
fins = _load_financials(data_dir, symbol)
|
||||
|
||||
# 4. meta
|
||||
yield json.dumps({
|
||||
"type": "meta",
|
||||
"symbol": symbol,
|
||||
"summary": summarize_levels(levels, close),
|
||||
"levels": levels,
|
||||
"close": close,
|
||||
}, ensure_ascii=False)
|
||||
|
||||
# 5+6. 构建提示词 + 流式调用 LLM(整体 try-except,任何异常都 yield error,避免前端卡死)
|
||||
try:
|
||||
from app.services.ai_provider import stream_ai_text
|
||||
|
||||
kline_tail = _clean_rows(df, _KLINE_KEEP_COLS)
|
||||
user_prompt = _build_user_prompt(kline_tail, fins, levels, close, symbol, focus)
|
||||
async for delta in stream_ai_text(
|
||||
[
|
||||
{"role": "system", "content": _SYSTEM_PROMPT},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
temperature=0.5,
|
||||
max_tokens=4500,
|
||||
):
|
||||
yield json.dumps({"type": "delta", "content": delta}, ensure_ascii=False)
|
||||
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception("AI stock analysis failed for %s: %s", symbol, e)
|
||||
yield json.dumps({"type": "error", "message": f"AI 分析失败: {e}"}, ensure_ascii=False)
|
||||
return
|
||||
|
||||
yield json.dumps({"type": "done"}, ensure_ascii=False)
|
||||
@@ -0,0 +1,91 @@
|
||||
"""AI 个股分析报告持久化存储。
|
||||
|
||||
与 ai_reports.py(财务分析报告)完全独立 —— 单独的文件、字段、上限,
|
||||
互不影响。刻意不复用,避免引入 kind 判别字段与分支(解耦 > 抽象)。
|
||||
|
||||
存储位置: data/user_data/ai_stock_reports.json (数组,按 created_at 降序)
|
||||
保留最近 MAX_REPORTS 条;超出自动裁剪最旧的。
|
||||
|
||||
每条报告结构:
|
||||
{
|
||||
"id": "sar_xxx", # 唯一 id(stock-analysis-report)
|
||||
"symbol": "600519.SH",
|
||||
"name": "贵州茅台",
|
||||
"focus": "", # 用户追加的关心点(可为空)
|
||||
"content": "# ...markdown", # 报告正文
|
||||
"summary": "当前价 12.3 · 压力位...", # 价位/数据摘要
|
||||
"levels": {...}, # 报告生成时的关键价位(供图表回放)
|
||||
"close": 12.3, # 报告生成时的收盘价
|
||||
"created_at": "2026-06-26T10:00:00"
|
||||
}
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_REPORTS = 50
|
||||
|
||||
|
||||
def _path() -> Path:
|
||||
from app.config import settings
|
||||
p = settings.data_dir / "user_data" / "ai_stock_reports.json"
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
|
||||
|
||||
def list_reports() -> list[dict]:
|
||||
"""返回全部报告(按 created_at 降序)。"""
|
||||
p = _path()
|
||||
if not p.exists():
|
||||
return []
|
||||
try:
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
if isinstance(data, list):
|
||||
return sorted(data, key=lambda r: r.get("created_at", ""), reverse=True)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("ai_stock_reports.json malformed: %s", e)
|
||||
return []
|
||||
|
||||
|
||||
def _save_all(reports: list[dict]) -> None:
|
||||
"""全量写入(裁剪到 MAX_REPORTS)。"""
|
||||
reports.sort(key=lambda r: r.get("created_at", ""), reverse=True)
|
||||
if len(reports) > MAX_REPORTS:
|
||||
reports = reports[:MAX_REPORTS]
|
||||
_path().write_text(
|
||||
json.dumps(reports, indent=2, ensure_ascii=False), encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def save_report(report: dict) -> dict:
|
||||
"""新增一条报告并持久化。返回保存后的报告(含 id / created_at)。"""
|
||||
reports = list_reports()
|
||||
if not report.get("id"):
|
||||
report["id"] = f"sar_{int(time.time() * 1000)}_{report.get('symbol', 'x')}"
|
||||
if not report.get("created_at"):
|
||||
report["created_at"] = _now_iso()
|
||||
reports.append(report)
|
||||
_save_all(reports)
|
||||
logger.info("Stock report saved: %s (%s), total %d", report.get("symbol"), report.get("id"), len(reports))
|
||||
return report
|
||||
|
||||
|
||||
def delete_report(report_id: str) -> bool:
|
||||
"""删除指定报告。返回是否删除成功。"""
|
||||
reports = list_reports()
|
||||
before = len(reports)
|
||||
reports = [r for r in reports if r.get("id") != report_id]
|
||||
if len(reports) < before:
|
||||
_save_all(reports)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
from datetime import datetime
|
||||
return datetime.now().isoformat(timespec="seconds")
|
||||
@@ -0,0 +1,149 @@
|
||||
"""策略结果缓存 — 写入本地文件,供策略页面秒加载。
|
||||
|
||||
缓存结构:
|
||||
{
|
||||
"as_of": "2024-01-15",
|
||||
"results": { strategy_id: { total, as_of, rows } },
|
||||
"today_ever_matched": { strategy_id: [symbol, ...] }, // 今日曾命中 symbol 并集
|
||||
"today_ever_rows": { strategy_id: { symbol: row_data } },// 今日曾命中的完整行数据
|
||||
"updated_at": 1705324800000 # Unix ms
|
||||
}
|
||||
|
||||
文件路径: data/user_data/strategy_cache.json
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _json_default(obj: Any) -> Any:
|
||||
"""处理 date/datetime 等 JSON 不认识的类型。"""
|
||||
if isinstance(obj, date):
|
||||
return obj.isoformat()
|
||||
if isinstance(obj, datetime):
|
||||
return obj.isoformat()
|
||||
raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_CACHE_FILENAME = "strategy_cache.json"
|
||||
|
||||
|
||||
def _cache_path(data_dir: Path) -> Path:
|
||||
return data_dir / "user_data" / _CACHE_FILENAME
|
||||
|
||||
|
||||
def _enriched_parquet_path(data_dir: Path, as_of: str) -> Path:
|
||||
"""返回 enriched parquet 文件路径。"""
|
||||
return data_dir / "kline_daily_enriched" / f"date={as_of}" / "part.parquet"
|
||||
|
||||
|
||||
def _get_enriched_mtime(data_dir: Path, as_of: str) -> float | None:
|
||||
"""返回 enriched parquet 文件的 mtime (秒)。文件不存在返回 None。"""
|
||||
p = _enriched_parquet_path(data_dir, as_of)
|
||||
try:
|
||||
return p.stat().st_mtime
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
|
||||
|
||||
def read_cache(data_dir: Path) -> dict | None:
|
||||
"""读取策略缓存文件。返回 None 表示无缓存或读取失败。
|
||||
|
||||
说明: 原先有 enriched mtime 过期校验 (数据文件变化 → 判过期返回 None),
|
||||
但在有实时行情的系统里, enriched parquet 每轮被刷新 → mtime 必然变化 →
|
||||
缓存被永久判死, 策略页读不到数据。且判过期后不触发重算, 只能让用户手动重跑,
|
||||
保护价值有限。故移除: 盘后缓存总能读出, 实时新鲜度由 /api/screener/cached
|
||||
端点叠加监控引擎的内存实时结果 (latest_strategy_results) 来保证。
|
||||
"""
|
||||
path = _cache_path(data_dir)
|
||||
if not path.exists():
|
||||
return None
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
if not text.strip():
|
||||
return None
|
||||
cached = json.loads(text)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("读取策略缓存失败: %s", e)
|
||||
return None
|
||||
|
||||
return cached
|
||||
|
||||
|
||||
def _rows_to_symbol_map(rows: list[dict]) -> dict[str, dict]:
|
||||
"""将 rows 列表转为 {symbol: row_data} 映射。"""
|
||||
result: dict[str, dict] = {}
|
||||
for row in rows:
|
||||
sym = row.get("symbol")
|
||||
if sym:
|
||||
result[sym] = row
|
||||
return result
|
||||
|
||||
|
||||
def write_cache(
|
||||
data_dir: Path,
|
||||
as_of: str,
|
||||
results: dict[str, Any],
|
||||
) -> None:
|
||||
"""将策略结果写入缓存文件,同时更新今日曾命中集合。
|
||||
|
||||
- 日期变更时重置 today_ever_matched 和 today_ever_rows
|
||||
- 同一天内合并 (并集) 之前曾命中的 symbol,并用最新行数据更新
|
||||
"""
|
||||
path = _cache_path(data_dir)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 读取旧缓存
|
||||
old = read_cache(data_dir)
|
||||
old_as_of = old.get("as_of") if old else None
|
||||
old_ever_rows: dict[str, dict[str, dict]] = old.get("today_ever_rows", {}) if old else {}
|
||||
|
||||
# 当前命中的行数据 → symbol 映射
|
||||
current_row_maps: dict[str, dict[str, dict]] = {}
|
||||
for sid, r in results.items():
|
||||
current_row_maps[sid] = _rows_to_symbol_map(r.get("rows", []))
|
||||
|
||||
if old_as_of and old_as_of == as_of and old_ever_rows:
|
||||
# 同一天: 合并 — 用当前行数据更新旧数据 (保持最新价格等)
|
||||
merged_rows: dict[str, dict[str, dict]] = {}
|
||||
all_keys = set(old_ever_rows.keys()) | set(current_row_maps.keys())
|
||||
for sid in all_keys:
|
||||
old_map = old_ever_rows.get(sid, {})
|
||||
cur_map = current_row_maps.get(sid, {})
|
||||
# 以旧数据为基础,用当前数据覆盖 (当前数据更新鲜)
|
||||
combined = {**old_map, **cur_map}
|
||||
merged_rows[sid] = combined
|
||||
today_ever_rows = merged_rows
|
||||
else:
|
||||
# 新的一天或首次写入
|
||||
today_ever_rows = current_row_maps
|
||||
|
||||
# 从 ever_rows 提取 symbol 列表 (用于快速计数)
|
||||
today_ever_matched = {sid: sorted(maps.keys()) for sid, maps in today_ever_rows.items()}
|
||||
|
||||
# enriched_mtime: 盘后缓存写入时记录 (向后兼容旧字段)。read_cache 已不再用它
|
||||
# 做过期校验, 实时新鲜度改由 /cached 端点叠加监控引擎内存结果保证。
|
||||
enriched_mtime = _get_enriched_mtime(data_dir, as_of)
|
||||
|
||||
payload = {
|
||||
"as_of": as_of,
|
||||
"results": results,
|
||||
"today_ever_matched": today_ever_matched,
|
||||
"today_ever_rows": today_ever_rows,
|
||||
"enriched_mtime": enriched_mtime,
|
||||
"updated_at": int(time.time() * 1000),
|
||||
}
|
||||
try:
|
||||
path.write_text(json.dumps(payload, ensure_ascii=False, default=_json_default), encoding="utf-8")
|
||||
total_rows = sum(len(r.get("rows", [])) for r in results.values())
|
||||
total_ever = sum(len(v) for v in today_ever_matched.values())
|
||||
logger.info("策略缓存已写入: %s, %d 策略, %d 命中, %d 曾命中", as_of, len(results), total_rows, total_ever)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("写入策略缓存失败: %s", e)
|
||||
@@ -0,0 +1,144 @@
|
||||
"""自选股服务(§6.1)。
|
||||
|
||||
存储:`data/user_data/watchlist.parquet`,字段 symbol + added_at + note。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import polars as pl
|
||||
|
||||
from app.config import settings
|
||||
from app.tickflow.capabilities import Cap, CapabilitySet
|
||||
from app.tickflow.client import get_client
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _path() -> Path:
|
||||
p = settings.data_dir / "user_data" / "watchlist.parquet"
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
|
||||
|
||||
def list_symbols() -> list[dict]:
|
||||
p = _path()
|
||||
if not p.exists():
|
||||
return []
|
||||
df = pl.read_parquet(p)
|
||||
if df.is_empty():
|
||||
return []
|
||||
return df.to_dicts()
|
||||
|
||||
|
||||
def add(symbol: str, note: str = "") -> list[dict]:
|
||||
p = _path()
|
||||
if p.exists():
|
||||
df = pl.read_parquet(p)
|
||||
# 已存在则先移除,后面重新插入到最前面
|
||||
if symbol in df["symbol"].to_list():
|
||||
df = df.filter(pl.col("symbol") != symbol)
|
||||
else:
|
||||
df = pl.DataFrame(schema={"symbol": pl.Utf8, "added_at": pl.Utf8, "note": pl.Utf8})
|
||||
|
||||
new_row = pl.DataFrame({
|
||||
"symbol": [symbol],
|
||||
"added_at": [datetime.utcnow().isoformat(timespec="seconds")],
|
||||
"note": [note],
|
||||
})
|
||||
out = pl.concat([new_row, df], how="diagonal_relaxed")
|
||||
out.write_parquet(p)
|
||||
return out.to_dicts()
|
||||
|
||||
|
||||
def remove(symbol: str) -> list[dict]:
|
||||
p = _path()
|
||||
if not p.exists():
|
||||
return []
|
||||
df = pl.read_parquet(p)
|
||||
df = df.filter(pl.col("symbol") != symbol)
|
||||
df.write_parquet(p)
|
||||
return df.to_dicts()
|
||||
|
||||
|
||||
def move_to_top(symbol: str) -> list[dict]:
|
||||
p = _path()
|
||||
if not p.exists():
|
||||
return []
|
||||
df = pl.read_parquet(p)
|
||||
if df.is_empty() or symbol not in df["symbol"].to_list():
|
||||
return df.to_dicts()
|
||||
target = df.filter(pl.col("symbol") == symbol)
|
||||
rest = df.filter(pl.col("symbol") != symbol)
|
||||
out = pl.concat([target, rest], how="diagonal_relaxed")
|
||||
out.write_parquet(p)
|
||||
return out.to_dicts()
|
||||
|
||||
|
||||
def clear() -> int:
|
||||
"""清空自选列表。返回移除的数量。"""
|
||||
p = _path()
|
||||
if not p.exists():
|
||||
return 0
|
||||
df = pl.read_parquet(p)
|
||||
count = df.height
|
||||
if count > 0:
|
||||
pl.DataFrame(schema={"symbol": pl.Utf8, "added_at": pl.Utf8, "note": pl.Utf8}).write_parquet(p)
|
||||
return count
|
||||
|
||||
|
||||
def fetch_quotes(symbols: list[str], capset: CapabilitySet, timeout_s: float = 8.0) -> list[dict]:
|
||||
"""拉取实时行情。
|
||||
|
||||
优先用 quote.batch;否则降级为 quote.by_symbol 单股请求。
|
||||
timeout_s: 单批次请求超时(秒),防止 API 卡死阻塞整个请求。
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeout
|
||||
|
||||
if not symbols:
|
||||
return []
|
||||
|
||||
tf = get_client()
|
||||
quotes: list[dict] = []
|
||||
|
||||
# 走 batch
|
||||
batch_size = 5
|
||||
if capset.has(Cap.QUOTE_BATCH):
|
||||
lim = capset.limits(Cap.QUOTE_BATCH)
|
||||
batch_size = lim.batch if lim and lim.batch else 50
|
||||
elif capset.has(Cap.QUOTE_BY_SYMBOL):
|
||||
lim = capset.limits(Cap.QUOTE_BY_SYMBOL)
|
||||
batch_size = lim.batch if lim and lim.batch else 5
|
||||
else:
|
||||
# 无任何实时行情能力(none/free 档走 free-api 服务器,不提供实时行情)
|
||||
# 提前返回空,避免发起注定失败的请求
|
||||
return []
|
||||
|
||||
chunks = [symbols[i:i + batch_size] for i in range(0, len(symbols), batch_size)]
|
||||
|
||||
# 用线程池为每个批次加超时保护
|
||||
pool = ThreadPoolExecutor(max_workers=1)
|
||||
for chunk in chunks:
|
||||
try:
|
||||
future = pool.submit(tf.quotes.get, symbols=chunk, as_dataframe=True)
|
||||
raw = future.result(timeout=timeout_s)
|
||||
if raw is None or len(raw) == 0:
|
||||
continue
|
||||
df = pl.from_pandas(raw)
|
||||
rename_map = {
|
||||
"last_price": "price",
|
||||
"ext.change_pct": "pct",
|
||||
"ext.name": "name",
|
||||
}
|
||||
df = df.rename({k: v for k, v in rename_map.items() if k in df.columns})
|
||||
quotes.extend(df.to_dicts())
|
||||
except FuturesTimeout:
|
||||
logger.warning("quote fetch timeout (%.1fs) for %d symbols", timeout_s, len(chunk))
|
||||
break # 超时后不再尝试后续批次
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("quote fetch failed for %d symbols: %s", len(chunk), e)
|
||||
pool.shutdown(wait=False)
|
||||
|
||||
return quotes
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Webhook 推送适配器 — 把告警事件推送到外部 IM / 量化软件。
|
||||
|
||||
职责: 把后端产生的告警事件, 通过用户配置的 Webhook 地址推送到外部。
|
||||
目前支持飞书群机器人; QMT / ptrade 等量化通道为待定。
|
||||
|
||||
飞书自定义机器人接入:
|
||||
1. 飞书群 → 群设置 → 群机器人 → 添加「自定义机器人」
|
||||
2. 复制生成的 Webhook 地址 (形如 https://open.feishu.cn/open-apis/bot/v2/hook/xxx)
|
||||
3. (可选) 安全设置 → 启用「签名校验」, 记录签名密钥(secret)
|
||||
4. 填入设置页「飞书 Webhook」配置
|
||||
|
||||
设计: 失败静默降级, 绝不因推送失败阻断告警主流程 (落盘 / SSE 推送)。
|
||||
去重不在本层做, 复用 MonitorRuleEngine 的 cooldown。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
import time
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 单次推送最长字符 (飞书单条文本消息上限 30KB, 这里保守截断避免刷屏)
|
||||
_MAX_LEN = 500
|
||||
|
||||
# 卡片消息正文最长字符 (飞书 interactive 卡片上限 30KB, 保守留余量给标题/结构)
|
||||
_CARD_MAX_LEN = 28000
|
||||
|
||||
# 飞书自定义机器人 Webhook 前缀 (用于 URL 合法性校验)
|
||||
FEISHU_HOOK_PREFIX = "https://open.feishu.cn/open-apis/bot/v2/hook/"
|
||||
|
||||
|
||||
def _truncate(text: str) -> str:
|
||||
"""截断超长文本。"""
|
||||
text = (text or "").strip()
|
||||
return text[:_MAX_LEN] + ("…" if len(text) > _MAX_LEN else "")
|
||||
|
||||
|
||||
def is_valid_feishu_url(url: str) -> bool:
|
||||
"""校验是否为合法的飞书自定义机器人 Webhook 地址。"""
|
||||
return bool(url) and url.startswith(FEISHU_HOOK_PREFIX)
|
||||
|
||||
|
||||
def _gen_sign(timestamp: str, secret: str) -> str:
|
||||
"""计算飞书自定义机器人签名。
|
||||
|
||||
算法 (官方): 把 `timestamp + "\\n" + secret` 作为签名字符串 (key),
|
||||
用 HmacSHA256 计算空字符串的签名结果, 再 Base64 编码。
|
||||
"""
|
||||
string_to_sign = f"{timestamp}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
string_to_sign.encode("utf-8"),
|
||||
digestmod=hashlib.sha256,
|
||||
).digest()
|
||||
return base64.b64encode(hmac_code).decode("utf-8")
|
||||
|
||||
|
||||
def _truncate_card(text: str) -> str:
|
||||
"""截断卡片正文 (留余量给标题与卡片结构)。"""
|
||||
text = (text or "").strip()
|
||||
return text[:_CARD_MAX_LEN] + ("…" if len(text) > _CARD_MAX_LEN else "")
|
||||
|
||||
|
||||
def _post_feishu(webhook_url: str, payload: dict, secret: str) -> bool:
|
||||
"""发送一次飞书 webhook 请求并判定成败 (供 text / card 共用)。
|
||||
|
||||
成功响应: HTTP 200 且业务 code=0 (或非 JSON 的 200)。失败静默返回 False。
|
||||
"""
|
||||
try:
|
||||
import httpx
|
||||
|
||||
# 启用签名校验时, 请求体须带 timestamp + sign (秒级时间戳)
|
||||
if secret:
|
||||
timestamp = str(int(time.time()))
|
||||
payload["timestamp"] = timestamp
|
||||
payload["sign"] = _gen_sign(timestamp, secret)
|
||||
|
||||
resp = httpx.post(webhook_url, json=payload, timeout=5.0)
|
||||
# 飞书成功响应: {"code":0,"msg":"success"} (或 StatusCode 200 + Extra)
|
||||
if resp.status_code == 200:
|
||||
try:
|
||||
data = resp.json()
|
||||
# code=0 表示飞书业务侧成功; 部分版本无 code 字段则按 msg 判断
|
||||
if isinstance(data, dict):
|
||||
code = data.get("code", data.get("StatusCode", 0))
|
||||
if code == 0:
|
||||
return True
|
||||
logger.debug("飞书推送业务失败: %s", data)
|
||||
return False
|
||||
except ValueError:
|
||||
# 非 JSON 响应但 HTTP 200, 视为成功
|
||||
return True
|
||||
logger.debug("飞书推送 HTTP %s: %s", resp.status_code, resp.text[:200])
|
||||
return False
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.debug("飞书 Webhook 推送失败: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def send_feishu(webhook_url: str, title: str, body: str, secret: str = "") -> bool:
|
||||
"""推送一条文本消息到飞书群机器人。
|
||||
|
||||
Args:
|
||||
webhook_url: 飞书自定义机器人 Webhook 地址
|
||||
title: 消息标题 (与正文拼接为一条文本)
|
||||
body: 消息正文
|
||||
secret: 签名密钥 (机器人启用了「签名校验」时必填; 留空则不带签名)
|
||||
|
||||
Returns:
|
||||
True=成功送达, False=失败或 URL 非法。
|
||||
失败静默, 不抛异常 (Webhook 是辅助通道, 不能阻断告警主流程)。
|
||||
"""
|
||||
if not is_valid_feishu_url(webhook_url):
|
||||
return False
|
||||
|
||||
text = _truncate(f"{title}\n{body}".strip())
|
||||
if not text:
|
||||
return False
|
||||
|
||||
payload: dict = {"msg_type": "text", "content": {"text": text}}
|
||||
return _post_feishu(webhook_url, payload, secret)
|
||||
|
||||
|
||||
def send_feishu_card(webhook_url: str, title: str, subtitle: str, body_md: str, secret: str = "") -> bool:
|
||||
"""推送一条 interactive 卡片消息到飞书群机器人 —— 用 lark_md 渲染完整 markdown 报告。
|
||||
|
||||
飞书「自定义机器人」webhook 不支持文件附件, 但 interactive 卡片的 lark_md 元素
|
||||
可渲染 markdown, 能承载完整复盘报告(通常 2-5KB, 远小于卡片 30KB 上限)。
|
||||
|
||||
Args:
|
||||
webhook_url: 飞书自定义机器人 Webhook 地址
|
||||
title: 卡片标题 (显示在蓝色 header)
|
||||
subtitle: 副标题 (加粗显示, 如日期/情绪标签; 留空则省略)
|
||||
body_md: 卡片正文 markdown (报告全文)
|
||||
secret: 签名密钥 (启用签名校验时必填)
|
||||
|
||||
Returns:
|
||||
True=成功送达, False=失败或 URL 非法。
|
||||
失败静默, 不抛异常 (与 send_feishu 一致, 不阻断告警主流程)。
|
||||
"""
|
||||
if not is_valid_feishu_url(webhook_url):
|
||||
return False
|
||||
|
||||
body = _truncate_card(body_md)
|
||||
elements: list[dict] = []
|
||||
if subtitle.strip():
|
||||
elements.append({
|
||||
"tag": "div",
|
||||
"text": {"tag": "lark_md", "content": f"**{subtitle.strip()}**"},
|
||||
})
|
||||
elements.append({"tag": "hr"})
|
||||
elements.append({
|
||||
"tag": "div",
|
||||
"text": {"tag": "lark_md", "content": body},
|
||||
})
|
||||
|
||||
payload: dict = {
|
||||
"msg_type": "interactive",
|
||||
"card": {
|
||||
"config": {"wide_screen_mode": True},
|
||||
"header": {
|
||||
"title": {"tag": "plain_text", "content": title},
|
||||
"template": "blue",
|
||||
},
|
||||
"elements": elements,
|
||||
},
|
||||
}
|
||||
return _post_feishu(webhook_url, payload, secret)
|
||||
@@ -0,0 +1,134 @@
|
||||
"""AI 策略生成器 — 读取策略开发文档 + 调用 LLM 生成策略代码。
|
||||
|
||||
职责: 接收用户自然语言描述 → 读取 docs/strategy-guide.md → 调用 LLM → 返回策略代码。
|
||||
不知道: 引擎内部、API、前端、配置持久化、回测。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import logging
|
||||
import re
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 策略开发文档路径
|
||||
GUIDE_PATH = Path(__file__).resolve().parent.parent.parent.parent / "docs" / "strategy-guide.md"
|
||||
|
||||
_SYSTEM_PREFIX = """你是A股量化策略设计专家。根据用户描述的需求,参考下方的《策略开发指南》生成一个完整的策略Python文件。
|
||||
|
||||
核心约束:
|
||||
- 只创建这一个 .py 文件,不要修改任何现有文件,不要跨文件引用
|
||||
- 只 import polars as pl,不 import 其他模块
|
||||
|
||||
要求:
|
||||
1. 用户可能调整的策略阈值通过 META["params"] 暴露;公式常数、固定窗口边界、布尔开关不必强行参数化
|
||||
2. 遵循指南中的文件结构,但优先贴合用户规则,不要为了套模板歪曲策略含义
|
||||
3. ENTRY_SIGNALS/EXIT_SIGNALS 根据策略逻辑自行选择匹配的信号列,不要照搬示例
|
||||
4. scoring 权重根据策略核心逻辑定制,总和 = 1.0
|
||||
5. 优先使用 Polars 表达式、窗口函数、聚合和 with_columns/filter 实现,避免逐行/逐股 Python 循环;只有表达式难以描述的复杂状态机才使用 partition_by/to_dicts
|
||||
6. 直接输出Python代码,不要输出其他内容
|
||||
|
||||
--- 策略开发指南 ---
|
||||
|
||||
"""
|
||||
|
||||
|
||||
class AIStrategyGenerator:
|
||||
"""AI 策略生成器"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._guide_cache: str | None = None
|
||||
|
||||
def _get_guide(self) -> str:
|
||||
if self._guide_cache is None:
|
||||
if GUIDE_PATH.exists():
|
||||
self._guide_cache = GUIDE_PATH.read_text(encoding="utf-8")
|
||||
else:
|
||||
logger.warning("strategy-guide.md not found at %s", GUIDE_PATH)
|
||||
self._guide_cache = ""
|
||||
return self._guide_cache
|
||||
|
||||
async def generate(self, user_prompt: str) -> dict:
|
||||
"""根据用户描述生成策略代码
|
||||
|
||||
Returns: {"code": str, "meta": dict, "valid": bool, "error": str | None}
|
||||
"""
|
||||
guide = self._get_guide()
|
||||
|
||||
# 调用 LLM
|
||||
code = await self._call_llm(user_prompt, guide)
|
||||
|
||||
# 验证
|
||||
try:
|
||||
self._validate_safety(code)
|
||||
except ValueError as e:
|
||||
return {"code": code, "meta": {}, "valid": False, "error": str(e)}
|
||||
|
||||
# 试加载获取 META
|
||||
try:
|
||||
meta = self._extract_meta(code)
|
||||
except Exception as e:
|
||||
return {"code": code, "meta": {}, "valid": False, "error": f"解析META失败: {e}"}
|
||||
|
||||
return {"code": code, "meta": meta, "valid": True, "error": None}
|
||||
|
||||
async def _call_llm(self, user_prompt: str, guide: str) -> str:
|
||||
"""Call the configured AI provider and return generated strategy code."""
|
||||
from app.services.ai_provider import generate_ai_text
|
||||
|
||||
content = await generate_ai_text(
|
||||
[
|
||||
{"role": "system", "content": _SYSTEM_PREFIX + guide},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
temperature=0.3,
|
||||
max_tokens=3000,
|
||||
)
|
||||
# Extract fenced code if the model wrapped the answer in Markdown.
|
||||
if "```python" in content:
|
||||
content = content.split("```python", 1)[1].split("```", 1)[0].strip()
|
||||
elif "```" in content:
|
||||
content = content.split("```", 1)[1].split("```", 1)[0].strip()
|
||||
return content
|
||||
|
||||
@staticmethod
|
||||
def _validate_safety(code: str) -> None:
|
||||
"""AST 级安全检查"""
|
||||
tree = ast.parse(code)
|
||||
|
||||
forbidden_modules = {"os", "sys", "subprocess", "socket", "shutil",
|
||||
"pathlib", "http", "urllib", "requests", "httpx"}
|
||||
forbidden_calls = {"open", "exec", "eval", "compile", "__import__",
|
||||
"globals", "locals", "vars", "dir", "getattr",
|
||||
"setattr", "delattr", "type", "input"}
|
||||
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
for alias in node.names:
|
||||
if alias.name.split(".")[0] not in ("polars",):
|
||||
if alias.name.split(".")[0] in forbidden_modules:
|
||||
raise ValueError(f"禁止 import {alias.name}")
|
||||
if isinstance(node, ast.ImportFrom):
|
||||
if node.module and node.module.split(".")[0] not in ("polars",):
|
||||
if node.module.split(".")[0] in forbidden_modules:
|
||||
raise ValueError(f"禁止 from {node.module} import")
|
||||
if isinstance(node, ast.Call):
|
||||
if isinstance(node.func, ast.Name) and node.func.id in forbidden_calls:
|
||||
raise ValueError(f"禁止调用 {node.func.id}()")
|
||||
|
||||
@staticmethod
|
||||
def _extract_meta(code: str) -> dict:
|
||||
"""从代码字符串中提取 META 字典(不执行代码)"""
|
||||
tree = ast.parse(code)
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Assign):
|
||||
for target in node.targets:
|
||||
if isinstance(target, ast.Name) and target.id == "META":
|
||||
# 找到 META 赋值,用 compile+eval 安全提取
|
||||
# 只允许字面量
|
||||
meta_node = node.value
|
||||
code_obj = compile(ast.Expression(meta_node), "<meta>", "eval")
|
||||
return eval(code_obj, {"__builtins__": {}}) # noqa: S307
|
||||
return {}
|
||||
@@ -0,0 +1,31 @@
|
||||
"""布林突破 — 突破布林上轨 + 放量"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "boll_breakout",
|
||||
"name": "布林突破",
|
||||
"description": "突破布林上轨 + 放量, 强势加速信号",
|
||||
"tags": ["布林", "突破"],
|
||||
"params": [
|
||||
{"id": "vol_ratio_min", "label": "最低量比", "type": "float",
|
||||
"default": 1.5, "min": 0.5, "max": 5.0, "step": 0.1},
|
||||
],
|
||||
"scoring": {"vol_ratio_5d": 0.4, "change_pct": 0.3, "momentum_20d": 0.3},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = ["signal_boll_breakout_upper"]
|
||||
EXIT_SIGNALS = ["signal_boll_breakdown_lower"]
|
||||
STOP_LOSS = -0.06
|
||||
MAX_HOLD_DAYS = 15
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
vol_min = params.get("vol_ratio_min", 1.5)
|
||||
return (
|
||||
pl.col("signal_boll_breakout_upper").fill_null(False)
|
||||
& (pl.col("vol_ratio_5d") >= vol_min)
|
||||
)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""断板反包 — 涨停 + 放量 + 涨幅 >3%"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "broken_board_recovery",
|
||||
"name": "断板反包",
|
||||
"description": "连板≥2后断板1-2天, 出现放量反包信号",
|
||||
"tags": ["涨停", "反包"],
|
||||
"params": [
|
||||
{"id": "vol_ratio_min", "label": "最低量比", "type": "float",
|
||||
"default": 1.5, "min": 0.5, "max": 5.0, "step": 0.1},
|
||||
{"id": "change_pct_min", "label": "最低涨幅", "type": "float",
|
||||
"default": 0.03, "min": 0.01, "max": 0.10, "step": 0.01},
|
||||
],
|
||||
"scoring": {"change_pct": 0.4, "vol_ratio_5d": 0.3, "momentum_5d": 0.3},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = ["signal_limit_up"]
|
||||
EXIT_SIGNALS = ["signal_ma20_breakdown"]
|
||||
STOP_LOSS = -0.06
|
||||
MAX_HOLD_DAYS = 10
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
vol_min = params.get("vol_ratio_min", 1.5)
|
||||
chg_min = params.get("change_pct_min", 0.03)
|
||||
return (
|
||||
pl.col("signal_limit_up").fill_null(False)
|
||||
& (pl.col("vol_ratio_5d") >= vol_min)
|
||||
& (pl.col("change_pct") > chg_min)
|
||||
)
|
||||
@@ -0,0 +1,29 @@
|
||||
"""均线多头 — MA5>MA10>MA20>MA60 + 短期动量为正"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "bullish_alignment",
|
||||
"name": "均线多头",
|
||||
"description": "MA5>MA10>MA20>MA60多头排列 + 短期动量为正",
|
||||
"tags": ["均线", "多头"],
|
||||
"params": [],
|
||||
"scoring": {"momentum_60d": 0.4, "momentum_20d": 0.3, "turnover_rate": 0.3},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = ["signal_ma_golden_5_20", "signal_ma_golden_20_60"]
|
||||
EXIT_SIGNALS = ["signal_ma_dead_5_20", "signal_ma20_breakdown"]
|
||||
STOP_LOSS = -0.06
|
||||
MAX_HOLD_DAYS = 20
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
return (
|
||||
(pl.col("ma5") > pl.col("ma10"))
|
||||
& (pl.col("ma10") > pl.col("ma20"))
|
||||
& (pl.col("ma20") > pl.col("ma60"))
|
||||
& (pl.col("momentum_20d") > 0)
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
"""连板股 — 涨停且连续涨停≥2天"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "consecutive_limit_ups",
|
||||
"name": "连板股",
|
||||
"description": "当日涨停且连续涨停≥2天, 强势追涨",
|
||||
"tags": ["涨停", "连板"],
|
||||
"params": [
|
||||
{"id": "min_boards", "label": "最少连板数", "type": "int",
|
||||
"default": 2, "min": 1, "max": 20, "step": 1},
|
||||
],
|
||||
"scoring": {"consecutive_limit_ups": 0.5, "change_pct": 0.3, "amount": 0.2},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = ["signal_limit_up"]
|
||||
EXIT_SIGNALS = []
|
||||
STOP_LOSS = -0.05
|
||||
MAX_HOLD_DAYS = 5
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
min_boards = params.get("min_boards", 2)
|
||||
return (
|
||||
pl.col("signal_limit_up").fill_null(False)
|
||||
& (pl.col("consecutive_limit_ups") >= min_boards)
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
"""高换手拉升 — 换手率 > 5% 且涨幅 > 3%, 资金活跃"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "high_turnover_surge",
|
||||
"name": "高换手拉升",
|
||||
"description": "换手率 > 5% 且涨幅 > 3%, 资金活跃",
|
||||
"tags": ["换手率", "放量", "资金"],
|
||||
"params": [
|
||||
{"id": "min_turnover", "label": "最低换手率%", "type": "float",
|
||||
"default": 5.0, "min": 1.0, "max": 20.0, "step": 0.5},
|
||||
{"id": "min_change", "label": "最低涨幅%", "type": "float",
|
||||
"default": 3.0, "min": 1.0, "max": 10.0, "step": 0.5},
|
||||
],
|
||||
"scoring": {"turnover_rate": 0.4, "change_pct": 0.3, "momentum_5d": 0.3},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 50,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = ["signal_volume_surge"]
|
||||
EXIT_SIGNALS = ["signal_ma20_breakdown"]
|
||||
STOP_LOSS = -0.05
|
||||
MAX_HOLD_DAYS = 10
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
min_to = params.get("min_turnover", 5.0) / 100.0
|
||||
min_chg = params.get("min_change", 3.0) / 100.0
|
||||
return (
|
||||
(pl.col("turnover_rate") > min_to)
|
||||
& (pl.col("change_pct") > min_chg)
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
"""连板接力 — 近2日涨停且今日涨幅 > 5%, 连板股追踪"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "limit_up_momentum",
|
||||
"name": "连板接力",
|
||||
"description": "连板股 + 今日涨幅 > 5%, 连板接力追踪",
|
||||
"tags": ["涨停", "连板", "接力"],
|
||||
"params": [
|
||||
{"id": "min_change", "label": "最低涨幅%", "type": "float",
|
||||
"default": 5.0, "min": 2.0, "max": 15.0, "step": 0.5},
|
||||
{"id": "min_boards", "label": "最少连板", "type": "int",
|
||||
"default": 1, "min": 1, "max": 10, "step": 1},
|
||||
],
|
||||
"scoring": {"consecutive_limit_ups": 0.4, "change_pct": 0.3, "amount": 0.3},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 50,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = ["signal_limit_up"]
|
||||
EXIT_SIGNALS = []
|
||||
STOP_LOSS = -0.05
|
||||
MAX_HOLD_DAYS = 5
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
min_chg = params.get("min_change", 5.0) / 100.0
|
||||
min_boards = params.get("min_boards", 1)
|
||||
return (
|
||||
(pl.col("change_pct") > min_chg)
|
||||
& (pl.col("consecutive_limit_ups") >= min_boards)
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
"""低波动龙头 — 正动量 + 低波动 + MA20上方"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "low_volatility_leader",
|
||||
"name": "低波动龙头",
|
||||
"description": "20日动量为正 + 年化波动 < 30% + MA20上方",
|
||||
"tags": ["低波动", "龙头"],
|
||||
"params": [
|
||||
{"id": "vol_max", "label": "最大年化波动", "type": "float",
|
||||
"default": 0.30, "min": 0.05, "max": 1.0, "step": 0.01},
|
||||
],
|
||||
"scoring": {"momentum_60d": 0.4, "momentum_20d": 0.3, "turnover_rate": 0.3},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = ["signal_ma20_breakout"]
|
||||
EXIT_SIGNALS = ["signal_ma20_breakdown"]
|
||||
STOP_LOSS = -0.05
|
||||
MAX_HOLD_DAYS = 30
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
vol_max = params.get("vol_max", 0.30)
|
||||
return (
|
||||
(pl.col("momentum_20d") > 0)
|
||||
& (pl.col("annual_vol_20d") < vol_max)
|
||||
& (pl.col("close") > pl.col("ma20"))
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
"""MA金叉 — MA5上穿MA20 + 量能配合 + MA60上方"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "ma_golden_cross",
|
||||
"name": "MA 金叉",
|
||||
"description": "MA5上穿MA20当日触发, 量能配合",
|
||||
"tags": ["均线", "金叉"],
|
||||
"params": [
|
||||
{"id": "vol_ratio_min", "label": "最低量比", "type": "float",
|
||||
"default": 1.2, "min": 0.5, "max": 5.0, "step": 0.1},
|
||||
],
|
||||
"scoring": {"momentum_20d": 0.5, "vol_ratio_5d": 0.3, "change_pct": 0.2},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = ["signal_ma_golden_5_20"]
|
||||
EXIT_SIGNALS = ["signal_ma_dead_5_20"]
|
||||
STOP_LOSS = -0.06
|
||||
MAX_HOLD_DAYS = 15
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
vol_min = params.get("vol_ratio_min", 1.2)
|
||||
return (
|
||||
pl.col("signal_ma_golden_5_20").fill_null(False)
|
||||
& (pl.col("vol_ratio_5d") >= vol_min)
|
||||
& (pl.col("close") > pl.col("ma60"))
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
"""MACD金叉放量 — MACD金叉当日 + 量能放大"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "macd_golden",
|
||||
"name": "MACD 金叉放量",
|
||||
"description": "MACD金叉当日 + 量能放大",
|
||||
"tags": ["MACD", "金叉", "放量"],
|
||||
"params": [
|
||||
{"id": "vol_ratio_min", "label": "最低量比", "type": "float",
|
||||
"default": 1.5, "min": 0.5, "max": 5.0, "step": 0.1},
|
||||
],
|
||||
"scoring": {"momentum_60d": 0.4, "vol_ratio_5d": 0.3, "change_pct": 0.3},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = ["signal_macd_golden"]
|
||||
EXIT_SIGNALS = ["signal_macd_dead"]
|
||||
STOP_LOSS = -0.07
|
||||
MAX_HOLD_DAYS = 20
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
vol_min = params.get("vol_ratio_min", 1.5)
|
||||
return (
|
||||
pl.col("signal_macd_golden").fill_null(False)
|
||||
& (pl.col("vol_ratio_5d") >= vol_min)
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
"""新低反转 — 60日新低后收阳放量"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "n_day_low_reversal",
|
||||
"name": "新低反转",
|
||||
"description": "触及60日新低后当日收阳放量, 反转信号",
|
||||
"tags": ["反转", "新低"],
|
||||
"params": [
|
||||
{"id": "vol_ratio_min", "label": "最低量比", "type": "float",
|
||||
"default": 1.5, "min": 0.5, "max": 5.0, "step": 0.1},
|
||||
],
|
||||
"scoring": {"change_pct": 0.4, "vol_ratio_5d": 0.3, "momentum_5d": 0.3},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = ["signal_n_day_low"]
|
||||
EXIT_SIGNALS = ["signal_ma20_breakdown"]
|
||||
STOP_LOSS = -0.06
|
||||
MAX_HOLD_DAYS = 15
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
vol_min = params.get("vol_ratio_min", 1.5)
|
||||
return (
|
||||
pl.col("signal_n_day_low").fill_null(False)
|
||||
& (pl.col("close") > pl.col("open"))
|
||||
& (pl.col("vol_ratio_5d") >= vol_min)
|
||||
)
|
||||
@@ -0,0 +1,55 @@
|
||||
"""逼近涨停 — 涨幅 > 7% 且距涨停 < 3%, 盘后选股"""
|
||||
import polars as pl
|
||||
|
||||
|
||||
def _limit_pct() -> pl.Expr:
|
||||
"""根据板块和 ST 动态计算涨跌幅限制 (小数)。
|
||||
创业板(300/301)/科创板(688): 20%
|
||||
北交所(.BJ): 30%
|
||||
ST: 5%
|
||||
主板: 10%
|
||||
"""
|
||||
is_st = pl.col("name").str.contains("(?i)ST").fill_null(False)
|
||||
is_cyb = pl.col("symbol").str.starts_with("300") | pl.col("symbol").str.starts_with("301")
|
||||
is_kcb = pl.col("symbol").str.starts_with("688")
|
||||
is_bj = pl.col("symbol").str.contains(r"\.BJ$")
|
||||
return (
|
||||
pl.when(is_st).then(0.05)
|
||||
.when(is_cyb | is_kcb).then(0.20)
|
||||
.when(is_bj).then(0.30)
|
||||
.otherwise(0.10)
|
||||
)
|
||||
|
||||
|
||||
META = {
|
||||
"id": "near_limit_up",
|
||||
"name": "逼近涨停",
|
||||
"description": "涨幅 > 7% 且距涨停 < 3%, 追涨信号",
|
||||
"tags": ["涨停", "追涨"],
|
||||
"params": [
|
||||
{"id": "min_change", "label": "最低涨幅%", "type": "float",
|
||||
"default": 7.0, "min": 3.0, "max": 15.0, "step": 1.0},
|
||||
{"id": "limit_gap", "label": "距涨停空间%", "type": "float",
|
||||
"default": 3.0, "min": 1.0, "max": 10.0, "step": 0.5},
|
||||
],
|
||||
"scoring": {"change_pct": 0.5, "amount": 0.3, "momentum_5d": 0.2},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 50,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = []
|
||||
EXIT_SIGNALS = ["signal_ma20_breakdown"]
|
||||
STOP_LOSS = -0.05
|
||||
MAX_HOLD_DAYS = 5
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
min_chg = params.get("min_change", 7.0) / 100.0
|
||||
gap = params.get("limit_gap", 3.0) / 100.0
|
||||
lp = _limit_pct()
|
||||
return (
|
||||
(pl.col("change_pct") > min_chg)
|
||||
& (pl.col("change_pct") < lp - gap)
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""超跌反弹 — RSI14 < 30 + 收阳 + 放量"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "oversold_bounce",
|
||||
"name": "超跌反弹",
|
||||
"description": "RSI14 < 30超卖区 + 当日收阳 + 放量, 抄底信号",
|
||||
"tags": ["超跌", "反弹", "RSI"],
|
||||
"params": [
|
||||
{"id": "rsi_max", "label": "RSI上限", "type": "float",
|
||||
"default": 30.0, "min": 10.0, "max": 50.0, "step": 1.0},
|
||||
{"id": "vol_ratio_min", "label": "最低量比", "type": "float",
|
||||
"default": 1.2, "min": 0.5, "max": 5.0, "step": 0.1},
|
||||
],
|
||||
"scoring": {"change_pct": 0.3, "vol_ratio_5d": 0.3, "momentum_5d": 0.2, "rsi_14": 0.2},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = []
|
||||
EXIT_SIGNALS = ["signal_ma20_breakdown"]
|
||||
STOP_LOSS = -0.05
|
||||
MAX_HOLD_DAYS = 15
|
||||
ALERTS = [
|
||||
{"field": "rsi_14", "op": "<", "value": 25, "message": "RSI极度超卖"},
|
||||
]
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
rsi_max = params.get("rsi_max", 30.0)
|
||||
vol_min = params.get("vol_ratio_min", 1.2)
|
||||
return (
|
||||
(pl.col("rsi_14") < rsi_max)
|
||||
& (pl.col("close") > pl.col("open"))
|
||||
& (pl.col("vol_ratio_5d") >= vol_min)
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""超跌反弹 — RSI14 < 30 + 涨幅 > 1% + 站上 MA5, 超卖反弹信号"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "oversold_reversal",
|
||||
"name": "超跌反转",
|
||||
"description": "RSI14 < 30超卖 + 涨幅 > 1% + 站上MA5, 超卖反转信号",
|
||||
"tags": ["超跌", "反弹", "RSI"],
|
||||
"params": [
|
||||
{"id": "rsi_max", "label": "RSI上限", "type": "float",
|
||||
"default": 30.0, "min": 10.0, "max": 50.0, "step": 1.0},
|
||||
{"id": "min_change", "label": "最低涨幅%", "type": "float",
|
||||
"default": 1.0, "min": 0.5, "max": 5.0, "step": 0.5},
|
||||
],
|
||||
"scoring": {"change_pct": 0.4, "rsi_14": 0.3, "vol_ratio_5d": 0.3},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 50,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = []
|
||||
EXIT_SIGNALS = ["signal_ma20_breakdown"]
|
||||
STOP_LOSS = -0.05
|
||||
MAX_HOLD_DAYS = 15
|
||||
ALERTS = [
|
||||
{"field": "rsi_14", "op": "<", "value": 25, "message": "RSI极度超卖"},
|
||||
]
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
rsi_max = params.get("rsi_max", 30.0)
|
||||
min_chg = params.get("min_change", 1.0) / 100.0
|
||||
return (
|
||||
(pl.col("rsi_14") < rsi_max)
|
||||
& (pl.col("change_pct") > min_chg)
|
||||
& (pl.col("close") > pl.col("ma5"))
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
"""均线回踩反弹 — 价格在 MA20 附近(±2%)且 MA 多头排列, 回踩买入"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "pullback_ma20_bounce",
|
||||
"name": "均线回踩反弹",
|
||||
"description": "价格在MA20附近(±2%)且MA5>MA20>MA60多头排列, 回踩买入",
|
||||
"tags": ["回踩", "均线", "反弹"],
|
||||
"params": [
|
||||
{"id": "ma_proximity", "label": "MA偏离度%", "type": "float",
|
||||
"default": 2.0, "min": 0.5, "max": 5.0, "step": 0.5},
|
||||
],
|
||||
"scoring": {"momentum_60d": 0.4, "change_pct": 0.3, "momentum_20d": 0.3},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 50,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = ["signal_ma_golden_5_20"]
|
||||
EXIT_SIGNALS = ["signal_ma20_breakdown", "signal_ma_dead_5_20"]
|
||||
STOP_LOSS = -0.05
|
||||
MAX_HOLD_DAYS = 15
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
proximity = params.get("ma_proximity", 2.0) / 100.0
|
||||
return (
|
||||
(pl.col("close") > pl.col("ma20") * (1 - proximity))
|
||||
& (pl.col("close") < pl.col("ma20") * (1 + proximity))
|
||||
& (pl.col("ma5") > pl.col("ma20"))
|
||||
& (pl.col("ma20") > pl.col("ma60"))
|
||||
& (pl.col("change_pct") > 0)
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""缩量回踩 — 回踩MA20附近 + 缩量 + 中期趋势向上"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "pullback_to_support",
|
||||
"name": "缩量回踩",
|
||||
"description": "回踩MA20附近 + 缩量 + 中期趋势向上",
|
||||
"tags": ["回踩", "支撑"],
|
||||
"params": [
|
||||
{"id": "ma_proximity", "label": "均线偏离度", "type": "float",
|
||||
"default": 0.02, "min": 0.01, "max": 0.05, "step": 0.005},
|
||||
{"id": "vol_ratio_max", "label": "最大量比", "type": "float",
|
||||
"default": 0.8, "min": 0.2, "max": 1.5, "step": 0.1},
|
||||
],
|
||||
"scoring": {"momentum_60d": 0.4, "momentum_20d": 0.3, "turnover_rate": 0.3},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = ["signal_ma_golden_5_20"]
|
||||
EXIT_SIGNALS = ["signal_ma20_breakdown"]
|
||||
STOP_LOSS = -0.05
|
||||
MAX_HOLD_DAYS = 20
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
proximity = params.get("ma_proximity", 0.02)
|
||||
vol_max = params.get("vol_ratio_max", 0.8)
|
||||
return (
|
||||
(pl.col("close") > pl.col("ma20") * (1 - proximity))
|
||||
& (pl.col("close") < pl.col("ma20") * (1 + proximity))
|
||||
& (pl.col("vol_ratio_5d") < vol_max)
|
||||
& (pl.col("close") > pl.col("ma60"))
|
||||
& (pl.col("momentum_20d") > 0)
|
||||
)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""强势高开 — 高开 > 3% 且保持上涨, 集合竞价强势"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "strong_open",
|
||||
"name": "强势高开",
|
||||
"description": "高开 > 3% 且收盘高于开盘价, 集合竞价强势",
|
||||
"tags": ["高开", "强势"],
|
||||
"params": [
|
||||
{"id": "min_open_gap", "label": "最低高开%", "type": "float",
|
||||
"default": 3.0, "min": 1.0, "max": 10.0, "step": 0.5},
|
||||
{"id": "min_change", "label": "最低涨幅%", "type": "float",
|
||||
"default": 3.0, "min": 1.0, "max": 10.0, "step": 0.5},
|
||||
],
|
||||
"scoring": {"change_pct": 0.4, "amplitude": 0.2, "amount": 0.4},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 50,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = []
|
||||
EXIT_SIGNALS = ["signal_ma20_breakdown"]
|
||||
STOP_LOSS = -0.05
|
||||
MAX_HOLD_DAYS = 10
|
||||
ALERTS = []
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
min_gap = params.get("min_open_gap", 3.0) / 100.0
|
||||
min_chg = params.get("min_change", 3.0) / 100.0
|
||||
return (
|
||||
(pl.col("open") > pl.col("prev_close") * (1 + min_gap))
|
||||
& (pl.col("close") > pl.col("open"))
|
||||
& (pl.col("change_pct") > min_chg)
|
||||
)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""趋势突破 — MA60上方 + 60日新高 + 放量"""
|
||||
import polars as pl
|
||||
|
||||
META = {
|
||||
"id": "trend_breakout",
|
||||
"name": "趋势突破",
|
||||
"description": "MA60上方 + 60日新高 + 量能 ≥ 2倍均量",
|
||||
"tags": ["趋势", "突破", "放量"],
|
||||
"basic_filter": {
|
||||
"price_min": 5,
|
||||
"price_max": 200,
|
||||
"market_cap_min": 20e8,
|
||||
"amount_min": 1e8,
|
||||
"exclude_st": True,
|
||||
"exclude_new_days": 60,
|
||||
},
|
||||
"params": [
|
||||
{"id": "vol_ratio_min", "label": "最低量比", "type": "float",
|
||||
"default": 2.0, "min": 0.5, "max": 10.0, "step": 0.1},
|
||||
],
|
||||
"scoring": {"momentum_60d": 0.4, "vol_ratio_5d": 0.3, "change_pct": 0.3},
|
||||
"order_by": "score",
|
||||
"descending": True,
|
||||
"limit": 100,
|
||||
}
|
||||
|
||||
ENTRY_SIGNALS = ["signal_n_day_high"]
|
||||
EXIT_SIGNALS = ["signal_ma20_breakdown"]
|
||||
STOP_LOSS = -0.08
|
||||
MAX_HOLD_DAYS = 20
|
||||
ALERTS = [
|
||||
{"field": "signal_volume_surge", "message": "放量异动"},
|
||||
]
|
||||
|
||||
|
||||
def filter(df: pl.DataFrame, params: dict) -> pl.Expr:
|
||||
vol_min = params.get("vol_ratio_min", 2.0)
|
||||
return (
|
||||
(pl.col("close") > pl.col("ma60"))
|
||||
& pl.col("signal_n_day_high").fill_null(False)
|
||||
& (pl.col("vol_ratio_5d") >= vol_min)
|
||||
)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user