diff --git a/README.md b/README.md index 5aa2d21..a6d0684 100644 --- a/README.md +++ b/README.md @@ -21,10 +21,10 @@ - **盘后复盘**:指数、涨跌家数、板块轮动、涨停池、龙虎榜和市场情绪温度。 - **价值投资数据**:估值分位、股息、股东结构、ETF 折溢价、财报日历、公告,以及美股 SEC 13F / Form 4。 - **持仓与风控**:组合集中度、压力测试、调仓计划和仓位计算;只计算你本次传入的数据,不保存账户。 -- **策略视角**:缠论、波浪理论、龙头战法、情绪周期等 18 套方法论,以 Skill 形式按需调用。 +- **策略视角**:缠论、波浪理论、龙头战法、情绪周期等 19 套方法论,以 Skill 形式按需调用。 - **dsh 仪表盘**:在 dsh Web / Desktop 侧栏看自选股和六个市场的行情,后台预热,打开即显示。 -一共 76 个工具、21 个 Skills,11 个数据源自动容灾。大部分功能不需要任何 API Key。 +一共 77 个工具、22 个 Skills,11 个数据源自动容灾。大部分功能不需要任何 API Key。 ## 快速开始 @@ -140,11 +140,12 @@ | 全市场选股 | `/skill:stock-screener` | L1 多因子硬筛(市场情绪调节,可选 `--l2` 量化增强)→ L2 LLM 智能排序 → 输出推荐列表 | | 策略回测 | `/skill:strategy-backtest` | YAML 策略定义 → 回测 → 诊断;按需进行最多 3 轮参数优化 | -### 策略、复盘与研究(18 个) +### 策略、复盘与研究(19 个) | Skill | 调用方式 | 方法论 | |-------|----------|--------| | 趋势追踪 | `/skill:bull-trend` | 均线排列 + MACD 方向 + 趋势阶段判断 | +| 分时承接与底仓 T0 | `/skill:intraday-support-t0` | A 股分钟级 VWAP、量价与可选逐笔,支持等量配对观察和回放 | | 缩量回调 | `/skill:shrink-pullback` | 上升趋势中的缩量洗盘识别 | | 均线金叉 | `/skill:ma-crossover` | MA5/10/20/60 交叉信号 + 金叉质量评估 | | 放量突破 | `/skill:volume-breakout` | 关键阻力位的放量突破确认 | @@ -165,12 +166,12 @@ ## 工具列表 -76 个工具按用途分组: +77 个工具按用途分组: | 类别 | 数量 | 主要内容 | |------|------|----------| | 数据获取 | 30 | K 线、报价、基金净值、资金流、财务、板块、涨停池、龙虎榜、两融、估值历史、股东、ETF、股息、公告、SEC、CDS 指数、宏观利率与汇率基准 | -| 分析计算 | 9 | 技术指标、K 线形态、量价、异动、信号胜率、趋势与行业轮动研究 | +| 分析计算 | 10 | 技术指标、K 线形态、量价、异动、信号胜率、趋势与行业轮动研究 | | 筛选与回测 | 8 | 多因子选股、风险筛查、策略回测(含多标的组合/再平衡/定投)、市场状态、日度复盘、自选股批量分析 | | 搜索与舆情 | 5 | 新闻搜索、综合情报、社交情绪、正文提取 | | 辅助 | 7 | 名称/拼音解析、交易日历、交易时段、数据源诊断、股票列表解析 | @@ -178,7 +179,7 @@ | 无状态研究与风险计算 | 9 | 同行比较、公告变更、组合风险、调仓计划、仓位计算、DCF 估值、事件研究、回测稳健性 |
-完整工具列表(76 个) +完整工具列表(77 个) #### 数据获取 @@ -190,7 +191,7 @@ | `get_valuation_history` | A/HK/US PE-TTM/PB 历史、正值分位与估值 Band,实际采样窗口(美股由 SEC 申报与周收盘派生) | | `get_index_valuation` | 中国指数 PE/PB 历史水位;中证官方多年滚动 PE;可选理杏仁补充 PB | | `get_cds_index` | 市场级 CDS 指数:中国在岸 CFETS-SHCH 指数期限曲线,或 DTCC 公开成交的 CDX/iTraxx 当前系列日中位数;窗口变化与分位,可按 index/tenor 只取单个指数和期限;非个股 CDS | -| `get_macro_anchors` | 宏观、利率、汇率与风险偏好基准(免 Key,缓存 1 小时):中美 10Y/美债 2Y 收益率及利差(bp)、DXY/USD-CNH/USD-HKD/推导 HKD-CNY、VIX/黄金/原油 | +| `get_macro_anchors` | 宏观、利率、汇率与风险偏好基准;`liquidity_a` 查国内资金与信用,`liquidity_hk` 查美债实际利率、HIBOR、汇率和南向成交 | | `get_earnings_calendar` | A 股报告期披露与业绩预告;HK 董事会排期;US/JP yfinance 预计日期(provider_only,非官方确认) | | `get_shareholder_structure` | A 股股东户数/十大流通股东变化/报告期北向名义持股;HK 南向持股 | | `get_etf_details` | A 股 ETF 净值折溢价、规模变动、披露持仓、可选基准成分与跟踪误差 | @@ -219,6 +220,7 @@ | 工具 | 说明 | |------|------| +| `analyze_intraday_t0` | 从调用方提供的 A 股分钟线和可选逐笔识别支撑回踩及 VWAP 收复;可回放底仓等量配对 | | `calculate_rotation_metrics` | 真实MC-dropout分布集中度与历史原始配权计算;不生成预测或买入信号 | | `backtest_rotation_allocation` | 股票/ETF代码自动取数,按市场与报价币种独立比较等权和历史配权;分项回测,非完整论文模型 | | `analyze_trend_strategy` | 月度右侧趋势策略:单市场股票池筛选、真实旧仓保持/退出与逆波动新仓预算;直接传股票代码、自动取行情,无持仓存储,仍为not_validated | @@ -462,7 +464,7 @@ sort_order: "desc" npm install # 同时构建仓库 .venv .venv/bin/python -m pytest -q # Python 单元测试(离线) npx tsc --noEmit # TypeScript 类型检查 -npx tsx tests/test_adapter_parity.ts # 四个宿主的 76 个工具和参数映射一致 +npx tsx tests/test_adapter_parity.ts # 四个宿主的 77 个工具和参数映射一致 npm run build:openclaw && npm run build:dsh # 构建 OpenClaw / dsh bundle ``` @@ -474,12 +476,12 @@ npm run build:openclaw && npm run build:dsh # 构建 OpenClaw / dsh bundle ``` stock-analysis/ ├── pi/ # Pi Agent Extension -│ └── index.ts # 注册 76 个工具 + 21 个 skill +│ └── index.ts # 注册 77 个工具 + 22 个 skill ├── hermes/ # Hermes Agent Plugin │ ├── plugin.yaml # 插件清单 │ ├── __init__.py # register(ctx) 入口 │ ├── schemas.py # 读取 tools/tool_schemas.json -│ └── tools.py # 76 个 handler → subprocess 调 CLI +│ └── tools.py # 77 个 handler → subprocess 调 CLI ├── openclaw/ # OpenClaw Plugin │ ├── openclaw.plugin.json # manifest(contracts.tools) │ ├── package.json # 含 openclaw 块(pluginApi/SDK 版本) @@ -494,7 +496,7 @@ stock-analysis/ │ ├── mcp_host/ # MCP stdio 服务器(复用 Hermes schema/handler) ├── tools/ # 共享 Python CLI 工具 -│ ├── tool_schemas.json # 76 个工具的名称/描述/参数(各宿主共用) +│ ├── tool_schemas.json # 77 个工具的名称/描述/参数(各宿主共用) │ ├── stock_data.py # 行情 / 资金流 / 新闻 / 财务 / 短线情绪 │ ├── signal_tracker.py # AI 买卖建议回测闭环(本地 JSONL 存储) │ ├── technical.py # 技术指标分析 @@ -511,7 +513,7 @@ stock-analysis/ │ ├── trading_calendar.py # 交易日历 │ └── requirements.txt │ -├── skills/ # 共享 SKILL.md(21 个) +├── skills/ # 共享 SKILL.md(22 个) │ ├── stock-analysis/ # 综合分析 workflow │ ├── stock-screener/ # 选股 workflow │ ├── strategy-backtest/ # 回测 + 进化 workflow diff --git a/docs/hermes-integration.en.md b/docs/hermes-integration.en.md index c530ab0..9473d36 100644 --- a/docs/hermes-integration.en.md +++ b/docs/hermes-integration.en.md @@ -128,8 +128,8 @@ stock-analysis-plugin (wheel) ├── hermes/ │ ├── __init__.py # register(ctx) entry point │ ├── plugin.yaml # plugin manifest -│ ├── schemas.py # loads tools/tool_schemas.json (JSON Schemas for 76 tools) -│ ├── tools.py # 76 handlers that run the CLIs as subprocesses +│ ├── schemas.py # loads tools/tool_schemas.json (JSON Schemas for 77 tools) +│ ├── tools.py # 77 handlers that run the CLIs as subprocesses │ └── _payload/ # tools/, skills/, schemas/, templates/ └── mcp_host/ # MCP stdio server (stock-analysis-mcp) ``` diff --git a/docs/hermes-integration.md b/docs/hermes-integration.md index ab053fa..58318b5 100644 --- a/docs/hermes-integration.md +++ b/docs/hermes-integration.md @@ -128,8 +128,8 @@ stock-analysis-plugin (wheel) ├── hermes/ │ ├── __init__.py # register(ctx) 入口 │ ├── plugin.yaml # 插件清单 -│ ├── schemas.py # 读取 tools/tool_schemas.json(76 个工具的 JSON Schema) -│ ├── tools.py # 76 个 handler,以子进程调用 CLI +│ ├── schemas.py # 读取 tools/tool_schemas.json(77 个工具的 JSON Schema) +│ ├── tools.py # 77 个 handler,以子进程调用 CLI │ └── _payload/ # tools/、skills/、schemas/、templates/ └── mcp_host/ # MCP stdio 服务器(stock-analysis-mcp) ``` diff --git a/docs/mcp.md b/docs/mcp.md index beaae8f..c3c2c0b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,6 +1,6 @@ # MCP 接入指南(WorkBuddy / Claude Desktop / Cursor) -`mcp_host/server.py` 是本插件的 MCP stdio 服务器:一行一条 JSON-RPC 2.0 消息,只用 Python 标准库。它复用所有宿主共用的 JSON Schema(`tools/tool_schemas.json`,经 `hermes/schemas.py` 读取)和参数映射(`hermes/tools.py`),所以 76 个工具的名称、参数和输出与其他宿主一致。同时自动将 21 个 `skills/*/SKILL.md` 暴露为 MCP Prompts、将 `SKILL.md`、`references/` 与 `schemas/*.json` 暴露为只读 MCP Resources。 +`mcp_host/server.py` 是本插件的 MCP stdio 服务器:一行一条 JSON-RPC 2.0 消息,只用 Python 标准库。它复用所有宿主共用的 JSON Schema(`tools/tool_schemas.json`,经 `hermes/schemas.py` 读取)和参数映射(`hermes/tools.py`),所以 77 个工具的名称、参数和输出与其他宿主一致。同时自动将 22 个 `skills/*/SKILL.md` 暴露为 MCP Prompts、将 `SKILL.md`、`references/` 与 `schemas/*.json` 暴露为只读 MCP Resources。 ## 前置条件 @@ -36,7 +36,7 @@ | Claude Desktop | `claude_desktop_config.json`(设置 → Developer → Edit Config) | | Cursor | `~/.cursor/mcp.json`(全局)或 `<项目目录>/.cursor/mcp.json` | -保存后,客户端里出现 76 个工具(如 `get_quote`、`get_technical_analysis`、`get_macro_anchors`)即接入成功。 +保存后,客户端里出现 77 个工具(如 `get_quote`、`get_technical_analysis`、`get_macro_anchors`)即接入成功。 ### 按需发现与精简模式(降低上下文占用) @@ -50,8 +50,9 @@ - **stdout 只有 JSON-RPC**:日志和误打印都会转到 stderr。 - **错误**:未知工具、参数不是对象、未知方法、无法解析的 JSON 作为 JSON-RPC 错误返回(`-32602` / `-32601` / `-32700` / `-32600`)。缺少必填参数、数据源失败、Python CLI 超时则作为工具结果返回:`isError: true`,正文为 `{"error": "..."}`。 - **并发与取消**:每次 `tools/call` 在独立线程里运行。收到 `notifications/cancelled` 后,服务器会结束对应的 Python 子进程,并且不再回复该请求。客户端关闭 stdin 时,服务器结束所有进行中的调用后退出。 +- **分时承接请求限额**。每条 `analyze_intraday_t0` JSON-RPC 请求最多 8 MiB。每个 MCP stdio 进程同时接受最多 2 个分时调用。超限会在启动工作线程和写临时文件前返回 `-32000`。并发超限可等现有调用结束再试,大批量回放可用独立 CLI。 - **超时**:沿用 `tools/cli_budgets.json` 的命令预算,与其他宿主一致。 -- **Skills 与 Schemas**:21 个 `skills/*/SKILL.md` 已自动暴露为 MCP Prompts(带可选 `request` 参数,并在 `prompts/get` 头部附带 MCP 工具与资源调用引导,适配无本地 shell 环境的客户端);`SKILL.md` 与 `references/` 暴露为只读 `stock-skill://...` Resources,`schemas/*.json`(如 `stock-schema://report_schema.json`)暴露为只读 `stock-schema://...` Resources。 +- **Skills 与 Schemas**:22 个 `skills/*/SKILL.md` 已自动暴露为 MCP Prompts(带可选 `request` 参数,并在 `prompts/get` 头部附带 MCP 工具与资源调用引导,适配无本地 shell 环境的客户端);`SKILL.md` 与 `references/` 暴露为只读 `stock-skill://...` Resources,`schemas/*.json`(如 `stock-schema://report_schema.json`)暴露为只读 `stock-schema://...` Resources。 ## 本地验证 diff --git a/docs/openclaw-integration.md b/docs/openclaw-integration.md index 6eadf44..4bd1c25 100644 --- a/docs/openclaw-integration.md +++ b/docs/openclaw-integration.md @@ -55,7 +55,7 @@ OpenClaw Gateway 启动时会扫描 `extensions/*` 工作区包并加载。 openclaw plugins inspect stock-analysis --runtime --json ``` -应该看到 76 个 tool 全部出现在 `tools` 列表里。也可以直接在 OpenClaw 对话中调用: +应该看到 77 个 tool 全部出现在 `tools` 列表里。也可以直接在 OpenClaw 对话中调用: ``` 帮我查一下贵州茅台的实时行情 diff --git a/docs/pi-integration.en.md b/docs/pi-integration.en.md index 5b33520..daaeb61 100644 --- a/docs/pi-integration.en.md +++ b/docs/pi-integration.en.md @@ -43,7 +43,7 @@ npm install ## Verify -Start Pi and type `/skills`. You should see 21 Skills, such as `stock-analysis`, `stock-screener` and `strategy-backtest`. Then ask: +Start Pi and type `/skills`. You should see 22 Skills, such as `stock-analysis`, `stock-screener` and `strategy-backtest`. Then ask: ``` Get the real-time quote for AAPL @@ -53,7 +53,7 @@ The agent should call `get_quote` and return market data. ## On-demand tool discovery -Pi 1.5.2 supports native tool discovery. At session startup, the plugin checks for the native `tool_search` exposure metadata and active-tool APIs. When available, it defers its stock tools and activates search while preserving other active tools. Older hosts and SDK sessions without the native search extension keep all 76 tools directly exposed. +Pi 1.5.2 supports native tool discovery. At session startup, the plugin checks for the native `tool_search` exposure metadata and active-tool APIs. When available, it defers its stock tools and activates search while preserving other active tools. Older hosts and SDK sessions without the native search extension keep all 77 tools directly exposed. If search is registered but inactive, the plugin enables it and confirms activation before deferring stock tools. Missing, restricted, or unavailable search keeps the tools directly exposed. Disabling search during a session restores the stock tools before the next model request and removes the discovery guidance. @@ -125,7 +125,7 @@ git pull && npm install ``` stock-analysis-plugin/ -├── pi/index.ts # Pi extension entry: 76 tools and 21 Skills +├── pi/index.ts # Pi extension entry: 77 tools and 22 Skills ├── tools/ # shared Python CLIs ├── skills/ # SKILL.md files ├── schemas/ templates/ strategies/ diff --git a/docs/pi-integration.md b/docs/pi-integration.md index 02fe8bf..c4807fe 100644 --- a/docs/pi-integration.md +++ b/docs/pi-integration.md @@ -43,7 +43,7 @@ npm install ## 验证 -启动 Pi 后输入 `/skills`,应能看到 21 个 Skill(如 `stock-analysis`、`stock-screener`、`strategy-backtest`)。再问一句: +启动 Pi 后输入 `/skills`,应能看到 22 个 Skill(如 `stock-analysis`、`stock-screener`、`strategy-backtest`)。再问一句: ``` 帮我查一下贵州茅台的实时行情 @@ -53,7 +53,7 @@ Agent 应调用 `get_quote` 并返回行情。 ## 按需工具发现 -最新稳定版 Pi 1.5.2 支持原生按需工具发现。插件在 `session_start` 检查 `tool_search` 的 exposure 元数据及活动工具 API:具备这些能力时,将股票工具设为 `deferred` 并启用原生搜索,保留其他插件的活动工具;旧宿主保持原来的 76 工具全量暴露,无需升级才能继续使用。 +最新稳定版 Pi 1.5.2 支持原生按需工具发现。插件在 `session_start` 检查 `tool_search` 的 exposure 元数据及活动工具 API:具备这些能力时,将股票工具设为 `deferred` 并启用原生搜索,保留其他插件的活动工具;旧宿主保持原来的 77 工具全量暴露,无需升级才能继续使用。 新版中搜索已注册但未激活时,插件会尝试启用并确认成功后再隐藏股票工具;未加载搜索扩展、被宿主限制或无法启用时保持全量暴露。会话中途关闭搜索时,下次模型请求前恢复全部股票工具,并停止发送搜索指引。 @@ -125,7 +125,7 @@ git pull && npm install ``` stock-analysis-plugin/ -├── pi/index.ts # Pi Extension 入口,注册 76 个工具和 21 个 Skill +├── pi/index.ts # Pi Extension 入口,注册 77 个工具和 22 个 Skill ├── tools/ # 共享 Python CLI ├── skills/ # SKILL.md ├── schemas/ templates/ strategies/ diff --git a/docs/tool-behavior.md b/docs/tool-behavior.md index 2741425..9281f5c 100644 --- a/docs/tool-behavior.md +++ b/docs/tool-behavior.md @@ -66,3 +66,8 @@ python tools/stateless_analysis.py position_size --input input.json L1 与 L2 综合分均在排序前按可用因子重新归一化;缺失或非有限因子不作零分处理,因子组内部也仅平均有效输入。factor_coverage.ratio 保留原始权重覆盖率,effective_weights 是实际归一化后的权重,高分仍需结合覆盖率判断。估值比较需同时读取 `pe_basis`;有限非正 PE/PB 的价值子分为 0,不能因数值更低而获得最高价值分。 L2 的 `vol20` 只使用恰好 20 个有效日收益,`factor_coverage.vol20_samples` 记录实际样本数,非正/非有限收盘价先剔除,空输入为 0;质量因子按 `report_date` 分组归一,避免年度累计与单季累计直接比较。资金流 5/10/20 日窗口不足返回 null,不按 0 或完整窗口处理。HK 快照统一带 `.HK`,US 快照移除东财交易所后缀并把类别股点号转为 Yahoo 连字符。主板 ST/*ST 按 5% 识别涨跌停,其他板块比例不变。 + +## 宏观流动性与分时承接 + +- `get_macro_anchors(group="liquidity_a"|"liquidity_hk")` 为可选分组。指标返回实际日期、来源、单位、窗口变化、滞后和缺失;现有默认分组维持原来的指标集合。方法及历史方向核验见[宏观流动性](../skills/stock-analysis/references/macro-liquidity.md)。 +- `analyze_intraday_t0` 接受单日已收盘 A 股分钟 K 线及可选逐笔,`mode="backtest"` 使用按日期排列的历史会话。分钟输入、降级、配对条件和回放口径见[分时承接与底仓 T0](../skills/intraday-support-t0/SKILL.md)。 diff --git a/dsh/README.md b/dsh/README.md index 41a161a..6a85def 100644 --- a/dsh/README.md +++ b/dsh/README.md @@ -1,6 +1,6 @@ # Stock Analysis — DeepSeek Harness (dsh) Plugin -A 股 / 港股 / 美股 / 日股 / 韩股 / 台股的行情、技术分析、选股与回测。作为 dsh bundle 安装到 profile 后,对话中可调用 76 个工具,并自动注册 21 个工作流和策略方法论 Skill;dsh Web / Desktop 侧栏还会多出一个「股票仪表盘」。 +A 股 / 港股 / 美股 / 日股 / 韩股 / 台股的行情、技术分析、选股与回测。作为 dsh bundle 安装到 profile 后,对话中可调用 77 个工具,并自动注册 22 个工作流和策略方法论 Skill;dsh Web / Desktop 侧栏还会多出一个「股票仪表盘」。 ![dsh 股票仪表盘:六市场自选股行情、指数带、A 股涨跌分布与行业涨跌榜(深色主题)](https://raw.githubusercontent.com/Weaxs/stock-analysis-plugin/main/docs/images/dsh-dashboard-dark.png) @@ -47,7 +47,7 @@ allowBuilds: 数据由插件后台常驻预热:Web 路由注册后即开始按固定任务表调用现有 CLI(`stock_data.py quotes/market_indices/klines/sector_rankings/market_stats` 与 `trading_calendar.py phase`),最多 4 个 Python 进程按优先级排队(报价 > 指数 > 走势 > 行业/统计);同一轮到期的自选股与 A 股指数报价合并为一个 `quotes` 进程,走势按市场合并为每个市场一个 `klines` 进程,单只失败只影响该行,结果留在内存缓存。刷新节奏随各市场交易阶段变化:交易时段有页面打开时报价与指数约 30 秒、行业 1 分钟、全 A 统计 2 分钟;无人查看时放宽到 5–10 分钟;收盘后 30–60 分钟一次。失败保留上次成功值并标注,重试间隔按 1、2、4… 分钟退避。页面只轮询内存快照 `/api/snapshot`(有后台任务时 1.5 秒,否则 15 秒,页面不可见时停止),并在浏览器本地缓存 24 小时,打开即显示上次数据;「刷新」会让所有数据立即重新获取。不调用包含财务、新闻、风险等完整采集的 `run_watchlist_analysis`。前端接口只接受固定的快照、刷新和自选股操作,不开放任意 Python 脚本或参数。 -前端由 `dsh/client.ts`、`dsh/dashboard.ts` 和 `dsh/web/`(`app.ts` + HTML/CSS)组成,均为 TypeScript,`npm run build:dsh` 将浏览器端编译为 IIFE 输出到 `dist/`;它不增加或改变四宿主共享的 76 个模型工具。源码或 manifest 改动后重新运行 `npm run build:dsh` 并重装/重启对应 profile。 +前端由 `dsh/client.ts`、`dsh/dashboard.ts` 和 `dsh/web/`(`app.ts` + HTML/CSS)组成,均为 TypeScript,`npm run build:dsh` 将浏览器端编译为 IIFE 输出到 `dist/`;它不增加或改变四宿主共享的 77 个模型工具。源码或 manifest 改动后重新运行 `npm run build:dsh` 并重装/重启对应 profile。 页脚显示当前插件版本。从 npm 安装时,打开看板会查询 `latest`,成功结果缓存 1 小时,失败后约 30 秒重试。点「刷新」会同时查行情和版本。默认先查 npm 官方源,失败后回退到 npmmirror。设置 `npm_config_registry` 可以指定使用的注册表。 @@ -55,7 +55,7 @@ allowBuilds: ## 按需工具发现 -dsh 0.2.2 及以上(工具注册支持按步骤的 `when` 条件)默认增加一个宿主控制入口 `stock_tool_search`;更早的 0.2.1 不提供该接口,插件会自动关闭按需发现并全量暴露工具,功能不受影响。按需发现只控制工具加载,不改变 76 个分析工具的名称、参数和输出。原生函数调用模式下,首次请求只暴露这个发现入口;其他插件的工具照常保留。搜索支持中文描述、英文关键词或确切工具名,例如 `财务`、`get_quote`、`run_backtest`;命中工具在下一次模型请求提供完整 schema,再按原名调用。默认最多加载 5 项,`limit` 可设 1 到 20;无匹配返回空列表。 +dsh 0.2.2 及以上(工具注册支持按步骤的 `when` 条件)默认增加一个宿主控制入口 `stock_tool_search`;更早的 0.2.1 不提供该接口,插件会自动关闭按需发现并全量暴露工具,功能不受影响。按需发现只控制工具加载,不改变 77 个分析工具的名称、参数和输出。原生函数调用模式下,首次请求只暴露这个发现入口;其他插件的工具照常保留。搜索支持中文描述、英文关键词或确切工具名,例如 `财务`、`get_quote`、`run_backtest`;命中工具在下一次模型请求提供完整 schema,再按原名调用。默认最多加载 5 项,`limit` 可设 1 到 20;无匹配返回空列表。 加载集合按 Agent 隔离,搜索和回退均保留宿主已有的工具权限限制。搜索入口被禁止或移除时,下一次请求保留原先已授权的完整股票工具目录。旧版缺少相关接口时保持全量暴露;PTC / both 模式沿用宿主生成的 SDK,不做发现过滤。加载集合在本次运行中保留,恢复会话或重载插件后需重新搜索。 @@ -71,7 +71,7 @@ dsh 0.2.2 及以上(工具注册支持按步骤的 `when` 条件)默认增 ## 工具与 Skills -76 个工具覆盖行情与基金净值、宏观利率与汇率基准、技术分析与 K 线形态、资金流与板块、估值/股东/ETF/股息、公告与 SEC、多因子选股、策略回测、市场复盘、新闻舆情、持仓风险与调仓计算。完整列表见[主仓库 README · 工具列表](https://github.com/Weaxs/stock-analysis-plugin#工具列表),Skills 见 [Skills 一览](https://github.com/Weaxs/stock-analysis-plugin#skills-一览)。 +77 个工具覆盖行情与基金净值、宏观利率与汇率基准、技术分析与 K 线形态、资金流与板块、估值/股东/ETF/股息、公告与 SEC、多因子选股、策略回测、市场复盘、新闻舆情、持仓风险与调仓计算。完整列表见[主仓库 README · 工具列表](https://github.com/Weaxs/stock-analysis-plugin#工具列表),Skills 见 [Skills 一览](https://github.com/Weaxs/stock-analysis-plugin#skills-一览)。 ## 其他宿主 diff --git a/hermes/plugin.yaml b/hermes/plugin.yaml index 8405f0f..34d03e7 100644 --- a/hermes/plugin.yaml +++ b/hermes/plugin.yaml @@ -11,6 +11,7 @@ provides_tools: - plan_portfolio_rebalance - calculate_position_size - calculate_dcf_valuation + - analyze_intraday_t0 - analyze_event_study - validate_backtest - compare_analysis_snapshots diff --git a/hermes/tools.py b/hermes/tools.py index 8a2ef5f..400d5be 100644 --- a/hermes/tools.py +++ b/hermes/tools.py @@ -522,6 +522,10 @@ def get_macro_anchors(args: dict, **kwargs) -> str: return _run("macro_data.py", ["anchors", "--group", args.get("group", "all"), "--days", days]) +def analyze_intraday_t0(args: dict, **kwargs) -> str: + return _run_analysis(args.get("mode", "analyze"), args, script="intraday_t0.py") + + def get_earnings_calendar(args: dict, **kwargs) -> str: return _run( "value_data.py", diff --git a/mcp_host/server.py b/mcp_host/server.py index 62c8a28..07eea1d 100644 --- a/mcp_host/server.py +++ b/mcp_host/server.py @@ -54,7 +54,7 @@ ) DISCOVERY_TOOL_DEF = { "name": "stock_tool_search", - "description": "按中文关键词、英文关键词或工具名搜索 76 个股票分析工具,返回匹配工具的完整名称与参数 schema,并在支持动态刷新的 MCP 客户端中将其加载到当前会话工具列表。", + "description": "按中文关键词、英文关键词或工具名搜索 77 个股票分析工具,返回匹配工具的完整名称与参数 schema,并在支持动态刷新的 MCP 客户端中将其加载到当前会话工具列表。", "inputSchema": { "type": "object", "properties": { @@ -68,6 +68,8 @@ _current = threading.local() # Each call is a Python process that loads pandas; parallel model calls must not fan out unbounded. _SLOTS = threading.BoundedSemaphore(4) +_INTRADAY_MAX_REQUEST_BYTES = 8 * 1024 * 1024 +_INTRADAY_MAX_CALLS = 2 _FRONTMATTER_RE = re.compile(r"^---\r?\n([\s\S]*?)\r?\n---\r?\n?") @@ -401,6 +403,7 @@ def serve(stdin, stdout, *, discovery: bool = False, profile: str = "full") -> N write_lock = threading.Lock() calls: dict = {} workers: list = [] + intraday_slots = threading.BoundedSemaphore(_INTRADAY_MAX_CALLS) session_state = {"discovery": discovery, "profile": profile, "loaded": set(), "lock": threading.Lock()} def send(message: dict) -> None: @@ -418,18 +421,22 @@ def reply(request_id, work, *args, **kwargs) -> dict: except RpcError as exc: return {"jsonrpc": "2.0", "id": request_id, "error": {"code": exc.code, "message": exc.message}} - def run_call(request_id, params, call): - _current.call = call - if discovery: - message = reply( - request_id, - call_tool, - params, - session_state=session_state, - on_tools_changed=notify_tools_changed, - ) - else: - message = reply(request_id, call_tool, params) + def run_call(request_id, params, call, intraday): + try: + _current.call = call + if discovery: + message = reply( + request_id, + call_tool, + params, + session_state=session_state, + on_tools_changed=notify_tools_changed, + ) + else: + message = reply(request_id, call_tool, params) + finally: + if intraday: + intraday_slots.release() with call.lock: if calls.get(request_id) is call: del calls[request_id] @@ -468,8 +475,20 @@ def run_call(request_id, params, call): continue # other notifications (initialized, ...) need no reply request_id = msg["id"] if method == "tools/call": + intraday = params.get("name") == "analyze_intraday_t0" + if intraday: + # Only admitted calls may start a worker and stage their input. + if len(line) > _INTRADAY_MAX_REQUEST_BYTES: + error = "Intraday MCP requests are limited to 8 MiB; use the standalone CLI for larger inputs" + elif not intraday_slots.acquire(blocking=False): + error = "Intraday tool is busy; retry after an active call finishes" + else: + error = None + if error is not None: + send({"jsonrpc": "2.0", "id": request_id, "error": {"code": -32000, "message": error}}) + continue call = calls[request_id] = _Call() - worker = threading.Thread(target=run_call, args=(request_id, params, call), daemon=True) + worker = threading.Thread(target=run_call, args=(request_id, params, call, intraday), daemon=True) worker.start() workers = [w for w in workers if w.is_alive()] + [worker] continue diff --git a/openclaw/openclaw.plugin.json b/openclaw/openclaw.plugin.json index 8381e25..586b41c 100644 --- a/openclaw/openclaw.plugin.json +++ b/openclaw/openclaw.plugin.json @@ -74,6 +74,7 @@ "plan_portfolio_rebalance", "calculate_position_size", "calculate_dcf_valuation", + "analyze_intraday_t0", "analyze_event_study", "validate_backtest", "compare_analysis_snapshots", diff --git a/package.json b/package.json index 250279a..ed84e08 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "./skills/sector-rotation/SKILL.md", "./skills/bull-trend/SKILL.md", "./skills/shrink-pullback/SKILL.md", + "./skills/intraday-support-t0/SKILL.md", "./skills/ma-crossover/SKILL.md", "./skills/volume-breakout/SKILL.md", "./skills/bottom-volume/SKILL.md", diff --git a/schemas/market_review_schema.json b/schemas/market_review_schema.json index 3067c5b..4f8c3ca 100644 --- a/schemas/market_review_schema.json +++ b/schemas/market_review_schema.json @@ -4,6 +4,68 @@ "description": "结构化大盘复盘报告格式", "type": "object", "properties": { + "macro_liquidity": { + "type": "object", + "description": "宏观流动性与估值敏感性,由 get_macro_anchors 的实际观察值及分析组成", + "properties": { + "anchors": { + "type": "object", + "description": "保留工具指标键、原始值和元数据", + "additionalProperties": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "latest": { + "type": [ + "number", + "null" + ] + }, + "unit": { + "type": "string" + }, + "as_of": { + "type": "string" + }, + "source": { + "type": "string" + }, + "source_url": { + "type": "string" + }, + "window_start": { + "type": "string" + }, + "window_change": { + "type": [ + "number", + "null" + ] + }, + "stale": { + "type": "boolean" + } + } + } + }, + "missing": { + "type": "array", + "items": { + "type": "string" + } + }, + "valuation": { + "type": "string", + "description": "折现率、融资环境或风险偏好的影响" + }, + "fundamentals": { + "type": "string", + "description": "增长、盈利及独立行业证据" + } + } + }, "market": { "type": "string", "enum": ["A", "HK", "US"], diff --git a/schemas/report_schema.json b/schemas/report_schema.json index 6cc7b21..0c3513b 100644 --- a/schemas/report_schema.json +++ b/schemas/report_schema.json @@ -4,6 +4,68 @@ "description": "结构化股票分析报告格式", "type": "object", "properties": { + "macro_liquidity": { + "type": "object", + "description": "宏观流动性与估值敏感性,由 get_macro_anchors 的实际观察值及分析组成", + "properties": { + "anchors": { + "type": "object", + "description": "保留工具指标键、原始值和元数据", + "additionalProperties": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "latest": { + "type": [ + "number", + "null" + ] + }, + "unit": { + "type": "string" + }, + "as_of": { + "type": "string" + }, + "source": { + "type": "string" + }, + "source_url": { + "type": "string" + }, + "window_start": { + "type": "string" + }, + "window_change": { + "type": [ + "number", + "null" + ] + }, + "stale": { + "type": "boolean" + } + } + } + }, + "missing": { + "type": "array", + "items": { + "type": "string" + } + }, + "valuation": { + "type": "string", + "description": "折现率、融资环境或风险偏好的影响" + }, + "fundamentals": { + "type": "string", + "description": "增长、盈利及独立行业证据" + } + } + }, "stock_name": { "type": "string" }, "stock_code": { "type": "string" }, "analysis_date": { "type": "string", "format": "date" }, diff --git a/scripts/tool-calls.mjs b/scripts/tool-calls.mjs index 26f6053..a395801 100644 --- a/scripts/tool-calls.mjs +++ b/scripts/tool-calls.mjs @@ -36,6 +36,11 @@ export const TOOL_CALLS = { script: "macro_data.py", argv: (p) => ["anchors", "--group", p.group ?? "all", "--days", String(p.days ?? 30)], }, + analyze_intraday_t0: { + script: "intraday_t0.py", + argv: (p, path) => [p.mode ?? "analyze", "--input", path], + input: (p) => p, + }, get_earnings_calendar: { script: "value_data.py", argv: (p) => ["earnings_calendar", "--report-date", p.report_date ?? "", "--symbol", p.symbol ?? "", "--top", String(p.top ?? 50)], diff --git a/skills/intraday-support-t0/SKILL.md b/skills/intraday-support-t0/SKILL.md new file mode 100644 index 0000000..29992c8 --- /dev/null +++ b/skills/intraday-support-t0/SKILL.md @@ -0,0 +1,14 @@ +--- +name: intraday-support-t0 +description: 用 A 股 1m/5m 数据观察分时回踩、VWAP 收复及底仓 T0 配对条件,支持逐笔主动买卖证据及分钟级回放。用于日内承接、做 T 和假收复复盘。 +--- + +# 分时承接与底仓 T0 + +1. 获取用户有权使用的分钟数据。调用 `analyze_intraday_t0`,提供同一交易日从开盘起连续的已完成 K 线,时间戳为收盘时点且带 UTC 偏移,按交易时间递增。成交量按股,成交额按元。累计成交量与成交额先做日内差分,对齐午休、首根与最后一根。大盘、行业使用同周期时间戳;来源、缺口和数据截止时间随报告说明。只有日线、盘口快照或未收盘分钟时,承接等级为不可用。 +2. 回踩前固定 `support.price/basis/as_of`。参考前期平台、当时已形成的日内低点、已计算的 VWAP 或均线。日线 MA5 用已完成日 K 单独输入,分钟均线随周期计算。均线位置只作为趋势过滤。缺逐笔时,输出量价代理等级;有逐笔时传入真实成交时刻、主动方向、股数及 `tick_side_basis`,保留未能分类的成交量。只有确认窗的主动方向量与分钟量完整对账后才能使用主动买卖比。 +3. 报告 `state`(Setup / Trigger / Acceptance / Failure)、`support_level`、原始指标、基线、VWAP 口径和阈值。先观察回踩与收复,再等后续两根有成交的 K 线收盘都高于各自当时的 VWAP。`recovery` 用当前 K 线最低价,`repair_recovery` 用已观察到的回踩低点判断修复。反弹量能与低点形态共同确认,提供逐笔时还需净主动买量达到候选线。支撑失效、确认失败或触发后五根未延续,报告失效原因。阈值是待验证的固定起点。 +4. 量化观察可同时输出条件性等量配对。当前分时模型观察收复后买入、随后卖出原有可卖底仓。只有首次强确认、同周期市场/板块数据、可卖底仓、现金、整手、往返成本、当日涨跌停价及预设目标齐全且净收益风险比至少为 1 时,才引用 `quantity`;买卖数量相同。结合实际成交能力与收盘可配对性解读。出现 `no_trade_conditions` 时直接说明等待条件。已有先卖后买计划可用承接证据观察回补时点,回补数量以实际已卖数量核对。 +5. 历史回放用 `mode="backtest"`,按交易日提供 `sessions`、统一 `order` 与 `out_of_sample_from`。每个交易日使用事先固定的支撑、目标与市场阶段,提供该日实际涨跌停价 `price_limits.lower/upper` 和同周期市场背景。目标超出涨停价或止损价或计入滑点的成交模型超出可交易价格范围时,跳过该笔。报告样本内外与各阶段的交易数、胜率、盈亏比、期望、最大回撤、连续亏损以及未成交/未配对。后段缺线时,回放截止到第一个缺口并保留此前的成交;已买未卖的数量单独列出。查看 `limitations`;样本不足标记未验证。 + +Pi 或 dsh 的按需工具发现中搜索 `analyze_intraday_t0` 后按原名调用。独立 CLI 用 `python3 tools/intraday_t0.py analyze --input session.json` 或 `backtest --input replay.json`。本流程由用户触发,分析输入随调用提供,无需账户或通知订阅。 diff --git a/skills/market-review/SKILL.md b/skills/market-review/SKILL.md index 240b7dc..09e58f2 100644 --- a/skills/market-review/SKILL.md +++ b/skills/market-review/SKILL.md @@ -45,6 +45,8 @@ gather 工具返回以下字段: - 涨停/跌停比作为情绪温度计 - 连板高度与赚钱效应 +- A 股和港股复盘分别调用 `get_macro_anchors(group="liquidity_a"|"liquidity_hk", days=30)`,与成交额、行业表现和消息数据并行获取。按[宏观流动性分析口径](../stock-analysis/references/macro-liquidity.md)填入报告的 `macro_liquidity`。历史日期复盘只采用分析时点已可获得的数据。 + ### 5. 消息催化 - 当日重要政策/新闻 - 对市场的影响路径 diff --git a/skills/stock-analysis/SKILL.md b/skills/stock-analysis/SKILL.md index 3bd8788..422f7f9 100644 --- a/skills/stock-analysis/SKILL.md +++ b/skills/stock-analysis/SKILL.md @@ -23,6 +23,8 @@ description: 综合股票分析:联合技术、基本面、资金、消息和 快速问答先判断意图,按下表走最短调用链;完整综合研判走下方执行流程(gather 采集管线),不受此表限制。单工具可答的问题按各工具描述中的适用场景选择,本表不再重复。 +用户要求分时承接、底仓做 T、VWAP 收复或逐笔主动方向时,转到 [intraday-support-t0](../intraday-support-t0/SKILL.md)。 + 用户要求短线、波段、交易计划或买卖时机时,读取[短线交易决策框架](references/short-term-trading.md);普通基本面或长期价值分析不加载该参考。 用户询问非对称风险、赔率、盈亏比、凸性或脆弱性时,读取[肥尾、非对称风险与趋势收益诊断](../bull-trend/references/fat-tails.md)的非对称风险公式模板。 @@ -61,6 +63,11 @@ python3 scripts/gather.py - 当前市场处于什么阶段(上涨/下跌/震荡/高波动) - 该阶段下哪些策略更适合,哪些应回避 +**宏观流动性与估值敏感性**: + +- 综合研判发现利率/外部融资敏感标的时,自动按市场调用 `get_macro_anchors(group="liquidity_a"|"liquidity_hk", days=30)`。恒生医疗、生物科技、创新药及以远期现金流为主的港股成长资产必须覆盖。对 A 股按利率敏感性、杠杆/再融资需求和信用环境决定是否纳入,举证依据是现金流及融资结构。 +- 按[宏观流动性分析口径](references/macro-liquidity.md)解读并填写报告的 `macro_liquidity`。利率与汇率记录实际日期、来源和窗口变化,估值传导和行业基本面各写一段。 + **技术面**: - 趋势判断:均线排列、MACD方向、布林带位置 - 买卖信号:金叉/死叉、超买/超卖、支撑/压力位 diff --git a/skills/stock-analysis/references/macro-liquidity.md b/skills/stock-analysis/references/macro-liquidity.md new file mode 100644 index 0000000..7ce906c --- /dev/null +++ b/skills/stock-analysis/references/macro-liquidity.md @@ -0,0 +1,27 @@ +# 宏观流动性与估值敏感性 + +| 市场 | 调用 | 分别核对 | +|---|---|---| +| A 股 | `get_macro_anchors(group="liquidity_a", days=30)` | 国债收益率、FR007/FDR007 和 LPR 反映不同融资环节,M1 同比与社融增量补充信用背景。可另用贴近标的和期限的 `get_cds_index` 核对信用条件。用消费、订单、利润与盈利预期检验增长端。 | +| 港股 | `get_macro_anchors(group="liquidity_hk", days=30)` | 美债名义和实际利率、DXY、USD/CNH、USD/HKD、HIBOR 和南向净成交。联系汇率机制传递美元利率环境,本地资金松紧用 HIBOR 核对。南向总额仅描述全市场,行业流向需同口径行业证据。 [香港金管局联系汇率机制](https://www.hkma.gov.hk/eng/key-functions/money/linked-exchange-rate-system/how-does-the-lers-work) | + +- 保留工具 `anchors` 中每项实际 `as_of/source/unit/window_start/window_change` 与 `missing`,形成报告的 `macro_liquidity`。说明 `meta.warnings`、滞后和单观察值窗口。日频 `days` 为观测数上限,月频用相近长度的月度窗口。货币与社融观测月是统计期间,披露日需另外取证。利率绝对变化按百分点解读,1 个百分点为 100 bp。 +- FR007/FDR007 是上午定盘价,作为 R007/DR007 所代表资金面的代理。M1 自 2025 年 1 月启用新统计口径。月度社融增量有季节性,结合同比和分项判断,滞后月份不能填作当期值。 [中国外汇交易中心定盘口径](https://www.chinamoney.com.cn/english/bmkfrr/) · [人民银行 M1 口径公告](https://www.pbc.gov.cn/chubanwu/fileDir/resource/cms/2025/06/2025062416082199683.pdf#page=9) +- `valuation` 写可由数据支持的折现率、融资成本和风险偏好传导。长久期创新药和生物科技更依赖远期现金流与融资条件。 `fundamentals` 独立报告政策、支付环境、临床进展、License-out、现金消耗、融资与盈利兑现。A 股国债利率下行时核对信用和盈利,用需求证据区分流动性宽松与增长预期走弱。每条因果解释保留待验证条件。宏观数据不生成独立买卖信号。 + +## 历史方向核验 + +先确定窗口,再取同一地区市场指数与利率的实际观察日。用时点可得的宏观数据,短窗对齐美股收盘与港股下一交易日。并列指数原始收益、同期大盘或行业基准和独立事件;估值分析需要同口径估值序列。可用 `analyze_event_study` 计算预先定义的公告事件前后超额收益。 + +以下以自然年末为检查窗口。利率为 FRED DFII10 每年最后一个有数据的观察,起点为 2021-12-31 的 −1.04%。指数收益为恒生指数公司公布的 HSBIO 年度价格表现。 [FRED DFII10 观测表](https://fred.stlouisfed.org/series/DFII10/tables) · [恒生生物科技指数年度表现,图 1](https://www.hsi.com.hk/content/dam/wpb/hsil/en_hk/index_flash/content/20260318T000000.pdf#page=1) + +| 区间 | 美债 10Y 实际利率期末观察 | 利率变化 | HSBIO | +|---|---|---:|---:| +| 2022 | 2022-12-30 · 1.58% | +262 bp | −18.7% | +| 2023 | 2023-12-29 · 1.72% | +14 bp | −24.0% | +| 2024 | 2024-12-31 · 2.24% | +52 bp | −15.7% | +| 2025 | 2025-12-31 · 1.93% | −31 bp | +64.5% | + +年度方向与折现率假设相容,幅度没有单调关系。2023 年仅有 14 bp 的期末利率变化,指数跌幅仍比 2022 年更大。2025 年需同时核对临床和对外授权驱动。四个年度窗口只能核对方向,未控制成分调整、政策、基准和估值口径,也不能推断利率的独立贡献。 + +月度反例为 2026 年 9 月。DFII10 从 8 月 31 日的 2.44% 升到 9 月 30 日的 2.93%,同期 HSBIO 上涨 7.3%。利率方向无法解释该月表现,应再查港股本地资金、板块基准和独立行业事件。 [FRED DFII10 观测表](https://fred.stlouisfed.org/series/DFII10/tables) · [恒生指数公司 2026 年 9 月回顾](https://www.hsi.com.hk/content/dam/wpb/hsil/zh_hk/monthly_roundup/content/20261005T000000.pdf#page=1) diff --git a/skills/stock-analysis/references/short-term-trading.md b/skills/stock-analysis/references/short-term-trading.md index 7cadf8c..2de777f 100644 --- a/skills/stock-analysis/references/short-term-trading.md +++ b/skills/stock-analysis/references/short-term-trading.md @@ -1,5 +1,7 @@ # 短线交易决策框架 +分钟级承接、VWAP 收复及底仓 T0 使用 [intraday-support-t0](../../intraday-support-t0/SKILL.md)。 + 本框架适用于日线级、持有数日至数周的交易分析。当前工具不提供分钟线、逐笔成交或盘口数据;缺少这些数据时,不判断竞价强弱、封单质量、开板次数或分时承接。 ## 1. 先做市场状态门控 diff --git a/templates/_macro_liquidity.md.j2 b/templates/_macro_liquidity.md.j2 new file mode 100644 index 0000000..bc028b9 --- /dev/null +++ b/templates/_macro_liquidity.md.j2 @@ -0,0 +1,22 @@ +{% if macro_liquidity %} +## 宏观流动性与估值敏感性 + +{% if macro_liquidity.anchors %} +| 指标 | 观测日期 | 最新值 | 窗口起始 | 窗口变化 | 来源 | +|---|---|---:|---|---:|---| +{% for key, a in macro_liquidity.anchors.items() %} +| {{ a.name or key }}{% if a.stale %}(滞后){% endif %} | {{ a.as_of or '—' }} | {{ a.latest if a.latest is defined and a.latest is not none else '—' }} {{ a.unit or '' }} | {{ a.window_start or '—' }} | {{ a.window_change if a.window_change is defined and a.window_change is not none else '—' }} | {% if a.source_url %}[{{ a.source }}]({{ a.source_url }}){% else %}{{ a.source or '—' }}{% endif %} | +{% endfor %} + +{% endif %} +{% if macro_liquidity.missing %} +- **缺失指标** {{ macro_liquidity.missing | join('、') }} +{% endif %} +{% if macro_liquidity.valuation %} +- **估值与融资** {{ macro_liquidity.valuation }} +{% endif %} +{% if macro_liquidity.fundamentals %} +- **行业与盈利** {{ macro_liquidity.fundamentals }} +{% endif %} + +{% endif %} diff --git a/templates/market_review/full.md.j2 b/templates/market_review/full.md.j2 index 870b03a..b79b7d0 100644 --- a/templates/market_review/full.md.j2 +++ b/templates/market_review/full.md.j2 @@ -86,6 +86,8 @@ {% endfor %} {%- endif %} +{% include "_macro_liquidity.md.j2" %} + {% if tomorrow_strategy -%} ## 6. 明日策略 diff --git a/templates/stock_analysis/brief.md.j2 b/templates/stock_analysis/brief.md.j2 index a46d8fe..dd87886 100644 --- a/templates/stock_analysis/brief.md.j2 +++ b/templates/stock_analysis/brief.md.j2 @@ -30,4 +30,6 @@ ⚠️ **风险:** {{ intel.risk_alerts | join(';') }} {% endif %} +{% include "_macro_liquidity.md.j2" %} + {% include "stock_analysis/_evidence.md.j2" %} diff --git a/templates/stock_analysis/full.md.j2 b/templates/stock_analysis/full.md.j2 index e03f6dc..b24cb2b 100644 --- a/templates/stock_analysis/full.md.j2 +++ b/templates/stock_analysis/full.md.j2 @@ -107,6 +107,8 @@ {% endfor %} {%- endif %} +{% include "_macro_liquidity.md.j2" %} + {% include "stock_analysis/_evidence.md.j2" %} --- diff --git a/tests/test_adapter_parity.ts b/tests/test_adapter_parity.ts index 25ef5c8..250ff6d 100644 --- a/tests/test_adapter_parity.ts +++ b/tests/test_adapter_parity.ts @@ -225,7 +225,7 @@ for (const host of ["openclaw", "dsh", "hermes"]) { } } const names = Object.keys(hosts.pi).sort(); -if (names.length !== 76) issues.push(`pi registered ${names.length} tools, expected 76`); +if (names.length !== 77) issues.push(`pi registered ${names.length} tools, expected 77`); for (const host of ["openclaw", "dsh", "hermes"]) { for (const extra of Object.keys(hosts[host]).filter(n => !hosts.pi[n])) issues.push(`${host}: extra tool ${extra}`); for (const name of names) { diff --git a/tests/test_dsh_discovery.ts b/tests/test_dsh_discovery.ts index 19281bf..3b459f9 100644 --- a/tests/test_dsh_discovery.ts +++ b/tests/test_dsh_discovery.ts @@ -99,8 +99,8 @@ await eager.plugin(NativeExecutor); await eager.plugin(SkillRegistry); await eager.plugin(stockPlugin, {toolDiscovery: false}); try { - assert.equal(eager.tools.schemas().length, 76); + assert.equal(eager.tools.schemas().length, 77); assert.equal(eager.tools.get("stock_tool_search"), undefined); - assert.equal((await eager.systemPrompt.assemble({scope: {}})).tools.length, 76); + assert.equal((await eager.systemPrompt.assemble({scope: {}})).tools.length, 77); } finally { await eager.fiber.dispose(); } console.log("dsh discovery: scoped loading, Chinese search, permissions, fallback, and real Python round-trip passed"); diff --git a/tests/test_dsh_integration.ts b/tests/test_dsh_integration.ts index adc6726..bb26ca4 100644 --- a/tests/test_dsh_integration.ts +++ b/tests/test_dsh_integration.ts @@ -178,6 +178,7 @@ const sampleArgs: Record> = { "analyze_portfolio_risk": {"positions": [{"symbol": "AAPL", "price": 100, "quantity": 10, "currency": "USD"}], "base_currency": "USD", "cash": 100}, "plan_portfolio_rebalance": {"base_currency": "USD", "cash": 100, "positions": [], "targets": [{"symbol": "AAPL", "weight": 1, "price": 100, "currency": "USD", "lot_size": 1}]}, "calculate_position_size": {"equity": 100000, "cash": 20000, "entry_price": 100, "stop_price": 95, "risk_fraction": 0.01, "lot_size": 100}, + analyze_intraday_t0: { bars: [] }, "analyze_event_study": {"prices": [{"date": "2026-01-02", "close": 100}, {"date": "2026-01-05", "close": 110}], "benchmark_prices": [{"date": "2026-01-02", "close": 100}, {"date": "2026-01-05", "close": 100}], "event_dates": ["2026-01-05"], "price_basis": "adjusted", "horizons": [0]}, "validate_backtest": {"datasets": [], "strategies": []}, "compare_analysis_snapshots": {"previous": {"价格": 10}, "current": {"价格": 12}}, diff --git a/tests/test_hermes_integration.py b/tests/test_hermes_integration.py index da49c22..ffdd338 100644 --- a/tests/test_hermes_integration.py +++ b/tests/test_hermes_integration.py @@ -113,6 +113,7 @@ def test_wheel_declares_all_shared_runtime_dependencies(): "plan_portfolio_rebalance", "calculate_position_size", "calculate_dcf_valuation", + "analyze_intraday_t0", "analyze_event_study", "validate_backtest", "compare_analysis_snapshots", @@ -200,6 +201,7 @@ def test_wheel_declares_all_shared_runtime_dependencies(): "one-yang-three-yin", "sector-rotation", "shrink-pullback", + "intraday-support-t0", "stock-analysis", "stock-screener", "strategy-backtest", diff --git a/tests/test_intraday_t0.py b/tests/test_intraday_t0.py new file mode 100644 index 0000000..3643821 --- /dev/null +++ b/tests/test_intraday_t0.py @@ -0,0 +1,494 @@ +import json +import subprocess +import sys +from datetime import datetime, timedelta +from pathlib import Path + +CLI = Path(__file__).resolve().parents[1] / "tools" / "intraday_t0.py" + + +def session(): + start = datetime.fromisoformat("2026-11-30T09:30:00+08:00") + bars = [] + + def add(o, h, low, c, volume): + end = start + timedelta(minutes=len(bars) + 1) + bars.append(dict(timestamp=end.isoformat(), open=o, high=h, low=low, close=c, volume=volume)) + + for _ in range(20): + add(10.02, 10.12, 10.00, 10.05, 1000) + add(10.05, 10.05, 9.99, 10.00, 800) + add(10.00, 10.16, 10.00, 10.14, 1500) + add(10.14, 10.20, 10.12, 10.18, 1500) + add(10.18, 10.23, 10.15, 10.20, 1500) + return { + "bars": bars, + "period": "1m", + "support": {"price": 10, "basis": "platform", "as_of": start.isoformat()}, + } + + +def test_cli_empty_and_invalid_inputs(): + for bars, expected in [([], 0), ([{}], 1)]: + proc = subprocess.run( + [sys.executable, str(CLI), "analyze"], + input=json.dumps({"bars": bars}), + capture_output=True, + text=True, + ) + assert proc.returncode == expected + result = json.loads(proc.stdout) + if expected: + assert result["error"] + else: + assert result["support_level"] == "unavailable" + + +def test_confirmation_uses_two_subsequent_closed_bars_and_no_tick_proxy(): + from tools import intraday_t0 + + data = session() + for count in (22, 23): + result = intraday_t0.analyze({**data, "bars": data["bars"][:count]}) + assert result["state"] == "Trigger" + assert result["metrics"]["hold_vwap"] is None + result = intraday_t0.analyze(data) + assert result["state"] == "Acceptance" + assert result["support_level"] == "strong" + assert result["metrics"]["hold_vwap"] is True + assert result["metrics"]["aggression_ratio"] is None + assert result["evidence_basis"] == "price_volume_proxy" + assert result["quantity"] is None + + +def ready_session(): + data = session() + context = [{"timestamp": bar["timestamp"], "close": 100} for bar in data["bars"]] + data.update( + benchmark_bars=context, + sector_bars=list(context), + target_price=10.75, + price_limits={"lower": 9, "upper": 11}, + order={ + "base_shares": 1000, + "sellable_shares": 350, + "cash": 4000, + "lot_size": 100, + "buy_fee_bps": 3, + "sell_fee_bps": 8, + "minimum_fee": 5, + "slippage_bps": 5, + }, + ) + return data + + +def extend(data, price, volume=1000): + end = datetime.fromisoformat(data["bars"][-1]["timestamp"]) + timedelta(minutes=1) + data["bars"].append(dict(timestamp=end.isoformat(), open=price, high=price, low=price, close=price, volume=volume)) + for key in ("benchmark_bars", "sector_bars"): + data[key].append(dict(timestamp=end.isoformat(), close=100)) + + +def test_backtest_fills_next_bar_and_pairs_only_sellable_base(): + from tools import intraday_t0 + + data = ready_session() + for close in (10.22, 10.75, 10.78): + extend(data, close) + result = intraday_t0.backtest( + { + "sessions": [ + { + **data, + "price_limits": {"lower": 9, "upper": 11}, + "regime": "sideways", + } + ], + "order": data["order"], + "out_of_sample_from": "2026-11-30", + } + ) + trade = result["trades"][0] + assert trade["entry"]["bar_end"] == data["bars"][24]["timestamp"] + assert trade["exit"]["bar_end"] == data["bars"][26]["timestamp"] + assert trade["buy_shares"] == trade["sell_shares"] == 300 + assert trade["net_pnl"] < (10.78 - 10.22) * 300 + assert result["samples"]["out_of_sample"]["metrics"]["total_trades"] == 1 + assert result["samples"]["out_of_sample"]["validation_status"] == "unverified" + + +def test_warmup_zero_denominators_and_missing_bar_are_unavailable(): + from tools import intraday_t0 + + data = session() + data["bars"] = [{**bar, "open": 10, "high": 10, "low": 10, "close": 10, "volume": 0} for bar in data["bars"]] + result = intraday_t0.analyze(data) + assert result["support_level"] == "unavailable" + assert result["metrics"]["close_position"] is None + assert result["metrics"]["recovery"] is None + assert result["metrics"]["vwap"] is None + assert result["metrics"]["sell_volume_ratio"] is None + data["bars"].pop(2) + result = intraday_t0.analyze(data) + assert result["data_complete_through_as_of"] is False + assert result["support_level"] == "unavailable" + + +def test_fake_reclaim_and_atr_break_invalidate_without_rearming(): + from tools import intraday_t0 + + data = ready_session() + data["bars"][-2].update(open=10.04, high=10.04, low=10.01, close=10.02) + result = intraday_t0.analyze(data) + assert result["state"] == "Failure" + assert result["metrics"]["hold_vwap"] is False + assert result["invalidation"]["reason"] == "vwap_lost_during_confirmation" + assert result["acceptance"] is None + + data = ready_session() + data["bars"][20]["low"] = 9.80 + result = intraday_t0.analyze(data) + assert result["state"] == "Failure" + assert result["invalidation"]["reason"] == "support_broken" + assert result["trigger"] is None + + +def test_tick_direction_requires_reconciled_execution_volume_and_gates_strength(): + from tools import intraday_t0 + + data = ready_session() + data["tick_side_basis"] = "exchange aggressor flag" + data["ticks"] = [ + {"timestamp": bar["timestamp"], "side": side, "volume": qty} + for bar in data["bars"][21:] + for side, qty in [("buy", 900), ("sell", 600)] + ] + result = intraday_t0.analyze(data) + assert result["support_level"] == "strong" + assert result["metrics"]["aggressive_buy_volume"] == 2700 + assert result["metrics"]["aggressive_sell_volume"] == 1800 + assert result["metrics"]["aggression_ratio"] == 0.2 + assert result["quantity"]["buy_shares"] == result["quantity"]["sell_shares"] == 300 + + for tick in data["ticks"]: + tick["side"] = "sell" if tick["side"] == "buy" else "buy" + result = intraday_t0.analyze(data) + assert result["support_level"] == "weak" + assert result["metrics"]["aggression_ratio"] == -0.2 + data["ticks"].pop() + result = intraday_t0.analyze(data) + assert result["support_level"] == "weak" + assert result["metrics"]["aggression_ratio"] is None + assert result["metrics"]["unclassified_volume"] == 600 + + +def test_confirmation_is_actionable_once_and_limit_down_leaves_unpaired(): + from tools import intraday_t0 + + data = ready_session() + assert intraday_t0.analyze(data)["quantity"] is not None + for close in (10.23, 10.75, 9.90, 9.90): + extend(data, close) + assert intraday_t0.analyze(data)["quantity"] is None + result = intraday_t0.backtest( + { + "sessions": [{**data, "price_limits": {"lower": 9.90, "upper": 11}}], + "order": data["order"], + "out_of_sample_from": "2026-11-30", + } + ) + assert result["sessions"][0]["status"] == "unpaired" + trade = result["trades"][0] + assert trade["unpaired_shares"] == trade["buy_shares"] == 300 + assert trade["sell_shares"] == 0 and trade["net_pnl"] is None + + +def test_zero_volume_bar_cannot_confirm_or_create_actionable_quantity(): + from tools import intraday_t0 + + data = ready_session() + data["bars"][-1].update(open=10.18, high=10.18, low=10.18, close=10.18, volume=0) + result = intraday_t0.analyze(data) + assert result["metrics"]["hold_vwap"] is False + assert result["quantity"] is None + + +def test_replay_later_missing_bar_preserves_earlier_entry(): + from tools import intraday_t0 + + data = ready_session() + for close in (10.22, 10.75, 10.78, 10.80): + extend(data, close) + data["bars"].pop(25) + result = intraday_t0.backtest( + { + "sessions": [{**data, "price_limits": {"lower": 9, "upper": 11}}], + "order": data["order"], + "out_of_sample_from": "2026-11-30", + } + ) + assert result["sessions"][0]["status"] == "unpaired" + assert result["sessions"][0]["data_gap_at"] == "2026-11-30T09:56:00+08:00" + assert result["trades"][0]["buy_shares"] == 300 + + +def test_recovery_uses_the_current_bar_low_even_after_repair(): + from tools import intraday_t0 + + result = intraday_t0.analyze(session()) + assert result["metrics"]["vwap"] < session()["bars"][-1]["low"] + assert result["metrics"]["recovery"] is None + assert result["state"] == "Acceptance" + + +def test_replay_time_stop_requires_lack_of_continuation(): + from tools import intraday_t0 + + data = ready_session() + for close in (10.22, 10.24, 10.25, 10.26, 10.27, 10.28, 10.29, 10.75, 10.78): + extend(data, close) + result = intraday_t0.backtest( + { + "sessions": [{**data, "price_limits": {"lower": 9, "upper": 11}}], + "order": data["order"], + "out_of_sample_from": "2026-11-30", + } + ) + assert result["trades"][0]["exit_reason"] == "target_close" + assert result["trades"][0]["exit"]["bar_end"] == data["bars"][-1]["timestamp"] + + +def test_replay_inherits_top_level_period(): + from tools import intraday_t0 + + data = ready_session() + start = datetime.fromisoformat("2026-11-30T09:30:00+08:00") + for i, bar in enumerate(data["bars"]): + bar["timestamp"] = (start + timedelta(minutes=5 * (i + 1))).isoformat() + del data["period"] + result = intraday_t0.backtest( + {"period": "5m", "sessions": [data], "order": data["order"], "out_of_sample_from": "2026-11-30"} + ) + assert result["sessions"][0]["signal_at"] == "2026-11-30T11:30:00+08:00" + + +def test_intraday_invalid_arguments_are_error_json(): + proc = subprocess.run([sys.executable, str(CLI), "wrong"], capture_output=True, text=True) + assert proc.returncode != 0 + assert json.loads(proc.stdout)["error"] + + +def test_replay_tries_next_executable_open_when_the_first_has_no_trades(): + from tools import intraday_t0 + + data = ready_session() + extend(data, 10.22, volume=0) + for close in (10.24, 10.75, 10.78): + extend(data, close) + result = intraday_t0.backtest( + { + "sessions": [{**data, "price_limits": {"lower": 9, "upper": 11}}], + "order": data["order"], + "out_of_sample_from": "2026-11-30", + } + ) + assert result["trades"][0]["entry"]["bar_end"] == data["bars"][25]["timestamp"] + assert result["trades"][0]["buy_shares"] == result["trades"][0]["sell_shares"] == 300 + + +def test_replay_skips_limit_up_open_before_evaluating_the_next_price(): + from tools import intraday_t0 + + data = ready_session() + for close in (11.00, 10.22, 10.75, 10.78): + extend(data, close) + result = intraday_t0.backtest({"sessions": [data], "order": data["order"], "out_of_sample_from": "2026-11-30"}) + assert result["sessions"][0]["status"] == "paired" + assert result["trades"][0]["entry"]["bar_end"] == data["bars"][25]["timestamp"] + + data["bars"][24].update(open=10.80, high=10.80, low=10.80, close=10.80) + result = intraday_t0.backtest({"sessions": [data], "order": data["order"], "out_of_sample_from": "2026-11-30"}) + assert result["sessions"][0]["status"] == "entry_outside_risk_budget" + assert result["trades"] == [] + + +def test_drawdown_uses_the_cash_that_actually_enters_the_sample(): + from tools import intraday_t0 + + data = ready_session() + for close in (10.22, 10.75, 10.78): + extend(data, close) + data["price_limits"] = {"lower": 9, "upper": 11} + second = { + **data, + "bars": [{**b, "timestamp": b["timestamp"].replace("11-30", "12-01")} for b in data["bars"]], + "support": {**data["support"], "as_of": data["support"]["as_of"].replace("11-30", "12-01")}, + } + for key in ("benchmark_bars", "sector_bars"): + second[key] = [{**b, "timestamp": b["timestamp"].replace("11-30", "12-01")} for b in data[key]] + result = intraday_t0.backtest( + {"sessions": [data, second], "order": data["order"], "out_of_sample_from": "2026-12-01"} + ) + trade = result["trades"][0] + initial = data["order"]["cash"] + drawdowns = result["samples"] + oos = drawdowns["out_of_sample"]["metrics"] + assert oos["starting_cash_cny"] == initial + trade["net_pnl"] + assert oos["max_drawdown"] < drawdowns["in_sample"]["metrics"]["max_drawdown"] + + +def test_replay_with_gap_before_support_time_marks_session_unavailable(): + from tools import intraday_t0 + + data = ready_session() + data["support"]["as_of"] = data["bars"][10]["timestamp"] + missing = data["bars"].pop(5)["timestamp"] + result = intraday_t0.backtest({"sessions": [data], "order": data["order"], "out_of_sample_from": "2026-11-30"}) + assert result["trades"] == [] + assert result["sessions"][0]["status"] == "unavailable" + assert result["sessions"][0]["data_gap_at"] == missing + + +def test_sample_screen_requires_price_limit_coverage_and_enough_trades_per_regime(): + from tools import intraday_t0 + + data = ready_session() + for close in (10.22, 10.75, 10.78): + extend(data, close) + sessions = [] + for n in range(31): + start = datetime.fromisoformat("2026-01-05T09:30:00+08:00") + timedelta(weeks=n) + timestamps = [(start + timedelta(minutes=minute)).isoformat() for minute in (*range(1, 121), *range(211, 331))] + flat = {"open": 10.78, "high": 10.79, "low": 10.77, "close": 10.78, "volume": 1000} + bars = [ + {**(data["bars"][i] if i < len(data["bars"]) else flat), "timestamp": timestamp} + for i, timestamp in enumerate(timestamps) + ] + context = [{"timestamp": timestamp, "close": 100} for timestamp in timestamps] + entry = { + "bars": bars, + "support": {**data["support"], "as_of": start.isoformat()}, + "benchmark_bars": context, + "sector_bars": context, + "target_price": 10.75, + "regime": "rally" if n == 1 else "sideways", + } + if n < 30: + entry["price_limits"] = {"lower": 9, "upper": 11} + sessions.append(entry) + control = intraday_t0.backtest( + {"sessions": sessions[:30], "order": data["order"], "out_of_sample_from": "2026-01-01"} + )["samples"]["out_of_sample"] + assert control["validation_status"] == "sample_screen_passed" + assert set(control["by_regime"]) == {"sideways", "rally"} + assert all(metrics["validation_status"] == "unverified" for metrics in control["by_regime"].values()) + + unlabeled = [{k: v for k, v in row.items() if k != "regime"} for row in sessions[:30]] + unknown = intraday_t0.backtest({"sessions": unlabeled, "order": data["order"], "out_of_sample_from": "2026-01-01"})[ + "samples" + ]["out_of_sample"] + assert unknown["validation_status"] == "sample_screen_passed" + assert unknown["by_regime"]["unknown"]["total_trades"] == 30 + assert unknown["by_regime"]["unknown"]["validation_status"] == "unverified" + + result = intraday_t0.backtest({"sessions": sessions, "order": data["order"], "out_of_sample_from": "2026-01-01"}) + sample = result["samples"]["out_of_sample"] + assert sample["metrics"]["total_trades"] == 30 + assert result["sessions"][-1]["status"] == "price_limits_missing" + assert sample["validation_status"] == "unverified" + assert sample["by_regime"]["rally"]["validation_status"] == "unverified" + + sessions[-1]["support"]["price"] = 9 + for key in ("benchmark_bars", "sector_bars", "target_price"): + del sessions[-1][key] + result = intraday_t0.backtest({"sessions": sessions, "order": data["order"], "out_of_sample_from": "2026-01-01"}) + assert result["sessions"][-1]["status"] == "no_signal" + assert result["samples"]["out_of_sample"]["validation_status"] == "unverified" + + +def test_hold_vwap_evidence_survives_independent_support_failure(): + from tools import intraday_t0 + + data = ready_session() + data["bars"][22]["low"] = 9.80 + result = intraday_t0.analyze(data) + assert result["invalidation"]["reason"] == "support_broken" + assert result["metrics"]["hold_vwap"] is True + assert result["acceptance"] is None + assert result["quantity"] is None + + +def test_replay_cannot_enter_against_an_unreachable_daily_target(): + from tools import intraday_t0 + + data = ready_session() + for close in (10.22, 10.28, 10.30): + extend(data, close) + result = intraday_t0.backtest( + { + "sessions": [{**data, "price_limits": {"lower": 9, "upper": 10.30}}], + "order": data["order"], + "out_of_sample_from": "2026-11-30", + } + ) + assert result["trades"] == [] + assert "price_limits_block_trade_plan" in result["sessions"][0]["reasons"] + + +def test_pairing_can_use_a_lot_when_cash_exactly_covers_price_and_min_fee(): + from tools import intraday_t0 + + data = ready_session() + for bar in data["bars"]: + for field in ("open", "high", "low", "close"): + bar[field] = round(bar[field] - 2.07, 2) + data["support"]["price"] = 7.93 + data["target_price"] = 8.68 + data["price_limits"] = {"lower": 7, "upper": 9} + data["order"].update(cash=2444, slippage_bps=0) + assert intraday_t0.analyze(data)["quantity"]["buy_shares"] == 300 + data["order"]["cash"] -= 0.01 + assert intraday_t0.analyze(data)["quantity"]["buy_shares"] == 200 + + +def test_observation_requires_reachable_prices_before_proposing_quantity(): + from tools import intraday_t0 + + data = ready_session() + data["target_price"] = 12 + data["price_limits"] = {"lower": 9, "upper": 11} + result = intraday_t0.analyze(data) + assert result["support_level"] == "strong" + assert result["quantity"] is None + assert "price_limits_block_trade_plan" in result["no_trade_conditions"] + + del data["price_limits"] + result = intraday_t0.analyze(data) + assert result["quantity"] is None + assert "price_limits_missing" in result["no_trade_conditions"] + + +def test_trade_plan_checks_stop_after_slippage_against_the_lower_limit(): + from tools import intraday_t0 + + data = ready_session() + data["price_limits"] = {"lower": 9.93, "upper": 12.13} + data["target_price"] = 11 + data["order"]["slippage_bps"] = 100 + + observed = intraday_t0.analyze(data) + assert observed["support_level"] == "strong" + assert observed["quantity"] is None + assert "price_limits_block_trade_plan" in observed["no_trade_conditions"] + + for close in (10.22, 9.94, 9.94, 9.94): + extend(data, close) + replay = intraday_t0.backtest({"sessions": [data], "order": data["order"], "out_of_sample_from": "2026-11-30"}) + assert replay["trades"] == [] + assert "price_limits_block_trade_plan" in replay["sessions"][0]["reasons"] + + data["price_limits"]["lower"] = 9.94 + data["order"]["slippage_bps"] = 0 + observed = intraday_t0.analyze({**data, "bars": data["bars"][:24]}) + assert "price_limits_block_trade_plan" in observed["no_trade_conditions"] diff --git a/tests/test_llm_hosts.ts b/tests/test_llm_hosts.ts index c433a8b..f23ee31 100644 --- a/tests/test_llm_hosts.ts +++ b/tests/test_llm_hosts.ts @@ -11,6 +11,7 @@ for (const host of ["pi", "openclaw", "dsh"]) { for (const [name, args] of [ ["get_market_capabilities", { market: "HK" }], ["parse_stock_list", { text: "NVDA AAPL" }], + ["analyze_intraday_t0", { bars: [] }], ] as const) { const tool = tools.find(t => t.name === name)!; assert.equal(tool.parameters.type, "object", `${host}: real JSON schema`); @@ -18,6 +19,9 @@ for (const host of ["pi", "openclaw", "dsh"]) { if (name === "get_market_capabilities") { assert.equal(result.market, "HK"); assert(result.unsupported.some((item: { tool: string }) => item.tool === "get_capital_flow")); + } else if (name === "analyze_intraday_t0") { + assert.equal(result.support_level, "unavailable"); + assert.deepEqual(result.no_trade_conditions, ["minute_bars_missing"]); } else { assert.deepEqual(result.items.map((item: { symbol: string }) => item.symbol).sort(), ["AAPL", "NVDA"]); } diff --git a/tests/test_macro_data.py b/tests/test_macro_data.py index b6c378b..c557154 100644 --- a/tests/test_macro_data.py +++ b/tests/test_macro_data.py @@ -100,3 +100,79 @@ def test_cli_whole_float_days_accepted_and_invalid_days_exits_nonzero(): assert "error" in payload assert macro_data._parse_int_days(30.0) == 30 assert macro_data._parse_int_days("30.0") == 30 + + +def test_hk_liquidity_group_keeps_partial_results_and_actual_window(monkeypatch): + def fetch(key, days, **kwargs): + if key == "us_real_10y": + return macro_data._summarize_series( + [("2026-11-20", 1.9), ("2026-11-24", 2.0)], + name="US 10Y real yield", + unit="percent", + source="fred", + ) + raise ValueError("provider unavailable") + + monkeypatch.setattr(macro_data, "_fetch_anchor_uncached", fetch) + monkeypatch.setattr(macro_data, "_fetch_cn_us_yields_akshare", lambda days: {}) + result = macro_data.get_macro_anchors("liquidity_hk", 30) + anchor = result["anchors"]["us_real_10y"] + assert anchor["as_of"] == "2026-11-24" + assert anchor["window_start"] == "2026-11-20" + assert anchor["window_change"] == 0.1 + assert {"hibor_1m", "southbound_net_buy", "usdcnh"} <= set(result["missing"]) + assert result["liquidity_context"]["market"] == "HK" + + +def test_hermes_cli_preserves_default_and_accepts_explicit_liquidity_group(tmp_path, monkeypatch): + from _cache import cached + + from hermes.tools import get_macro_anchors + + monkeypatch.setenv("STOCK_CACHE_DIR", str(tmp_path)) + + def fake(key): + return { + "name": key, + "latest": 1.5, + "observations": 2, + "as_of": "2026-11-30", + "window_start": "2026-11-27", + "window_change": 0.01, + "source": "fixture", + } + + cached("macro_bonds_30", 60, lambda: {"cn_10y": [["2026-11-30", 1.5]]}) + keys = ( + "us_10y", + "us_2y", + "cn_10y", + "dxy", + "usdcnh", + "usdhkd", + "vix", + "gold", + "crude_oil", + "fdr007", + "fr007", + "lpr_1y", + "lpr_5y", + "m1_yoy", + "tsf_increment", + ) + for key in keys: + cached(f"macro_{key}_30", 60, lambda key=key: fake(key)) + + default = json.loads(get_macro_anchors({})) + explicit = json.loads(get_macro_anchors({"group": "liquidity_a"})) + assert default["group"] == "all" and "fdr007" not in default["anchors"] + assert explicit["group"] == "liquidity_a" and explicit["missing"] == [] + assert explicit["anchors"]["fdr007"]["window_change"] == 0.01 + assert explicit["liquidity_context"]["proxies"] == {"dr007": "fdr007", "r007": "fr007"} + + +def test_macro_invalid_group_is_error_json(): + cli = Path(__file__).resolve().parents[1] / "tools" / "macro_data.py" + proc = subprocess.run([sys.executable, str(cli), "anchors", "--group", "wrong"], capture_output=True, text=True) + assert proc.returncode != 0 + assert json.loads(proc.stdout)["error"] diff --git a/tests/test_mcp_integration.py b/tests/test_mcp_integration.py index 4e50ca1..acb8d00 100644 --- a/tests/test_mcp_integration.py +++ b/tests/test_mcp_integration.py @@ -106,7 +106,8 @@ def test_prompts_and_resources_expose_bundled_skills(): }, ) prompts = got[2]["result"]["prompts"] - assert len(prompts) == 21 + assert len(prompts) == 22 + assert any(p["name"] == "intraday-support-t0" for p in prompts) assert any(p["name"] == "stock-analysis" for p in prompts) msg_text = got[3]["result"]["messages"][0]["content"]["text"] assert "[MCP 执行说明]" in msg_text @@ -482,3 +483,155 @@ def slot(call, script, argv): for worker in workers: worker.join(10) assert peak == 4 + + +def test_intraday_t0_mcp_dispatch_respects_mode_and_data_gaps(): + def call(id_, arguments): + return { + "jsonrpc": "2.0", + "id": id_, + "method": "tools/call", + "params": {"name": "analyze_intraday_t0", "arguments": arguments}, + } + + with_limits = { + "bars": [ + {"timestamp": "2026-11-30T09:31:00+08:00", "open": 10, "high": 10, "low": 10, "close": 10, "volume": 100} + ], + "support": {"price": 10, "basis": "platform", "as_of": "2026-11-30T09:30:00+08:00"}, + "price_limits": {"lower": 9, "upper": 11}, + } + without_limits = {key: value for key, value in with_limits.items() if key != "price_limits"} + got = _by_id( + INIT, + INITIALIZED, + call(101, {"bars": []}), + call(102, {"mode": "backtest", "sessions": []}), + ) + got.update(_by_id(INIT, INITIALIZED, call(103, with_limits), call(104, without_limits))) + observation = got[101]["result"] + backtest = got[102]["result"] + assert observation["isError"] is False + assert json.loads(observation["content"][0]["text"])["support_level"] == "unavailable" + assert backtest["isError"] is True + assert "backtest requires order" in json.loads(backtest["content"][0]["text"])["error"] + priced = got[103]["result"] + assert priced["isError"] is False + payload = json.loads(priced["content"][0]["text"]) + assert payload["price_limits"] == {"lower": 9, "upper": 11} + assert "price_limits_missing" not in payload["no_trade_conditions"] + unpriced = got[104]["result"] + assert unpriced["isError"] is False + payload = json.loads(unpriced["content"][0]["text"]) + assert payload["price_limits"] is None + assert "price_limits_missing" in payload["no_trade_conditions"] + + +def _intraday_request(request_id, **arguments): + return { + "jsonrpc": "2.0", + "id": request_id, + "method": "tools/call", + "params": {"name": "analyze_intraday_t0", "arguments": arguments}, + } + + +def test_mcp_rejects_oversized_intraday_call_and_keeps_connection_open(): + got = _by_id( + INIT, + _intraday_request(101, bars=[], tick_side_basis="x" * (8 * 1024 * 1024)), + {"jsonrpc": "2.0", "id": 102, "method": "ping"}, + ) + assert got[101]["error"]["code"] == -32000 + assert "8 MiB" in got[101]["error"]["message"] + assert got[102]["result"] == {} + + +def test_mcp_limits_pending_intraday_calls_before_worker_dispatch(monkeypatch): + from io import BytesIO + + from mcp_host import server + + entered = [] + release = threading.Event() + + def hold_call(params): + entered.append(params["arguments"]["probe"]) + release.wait(5) + return {"content": []} + + monkeypatch.setattr(server, "call_tool", hold_call) + + class Input: + def __iter__(self): + for request_id in range(1, 4): + yield (json.dumps(_intraday_request(request_id, probe=request_id)) + "\n").encode() + release.set() + yield b'{"jsonrpc":"2.0","id":4,"method":"ping"}\n' + + stdout = BytesIO() + server.serve(Input(), stdout) + got = {message["id"]: message for message in map(json.loads, stdout.getvalue().splitlines())} + assert got[3]["error"]["code"] == -32000 + assert "busy" in got[3]["error"]["message"] + assert got[4]["result"] == {} + assert sorted(entered) == [1, 2] + + +def test_completed_intraday_call_frees_slot_before_response(monkeypatch): + from io import BytesIO + from queue import Queue + + from mcp_host import server + + input_lines = Queue() + output_lines = Queue() + finish_second = threading.Event() + tried_replacement = threading.Event() + semaphore = threading.BoundedSemaphore(2) + attempts = 0 + + class TracedAdmission: + def acquire(self, *, blocking): + nonlocal attempts + admitted = semaphore.acquire(blocking=blocking) + attempts += 1 + if attempts == 3: + tried_replacement.set() + return admitted + + def release(self): + semaphore.release() + + def hold_call(params): + probe = params["arguments"]["probe"] + if probe == 2: + assert finish_second.wait(5) + return {"content": []} + + def submit(request_id): + input_lines.put((json.dumps(_intraday_request(request_id, probe=request_id)) + "\n").encode()) + + class Output(BytesIO): + def write(self, data): + message = json.loads(data) + output_lines.put(message) + if message["id"] == 1: + submit(3) + assert tried_replacement.wait(5) + return super().write(data) + + monkeypatch.setattr(server.threading, "BoundedSemaphore", lambda _: TracedAdmission()) + monkeypatch.setattr(server, "call_tool", hold_call) + submit(1) + submit(2) + t = threading.Thread(target=server.serve, args=(iter(input_lines.get, None), Output()), daemon=True) + t.start() + try: + results = {line["id"]: line for line in (output_lines.get(timeout=5), output_lines.get(timeout=5))} + assert results[3]["result"] == {"content": []} + finally: + finish_second.set() + input_lines.put(None) + t.join(5) + assert not t.is_alive() diff --git a/tests/test_openclaw_integration.ts b/tests/test_openclaw_integration.ts index 32f99b2..ed5f89b 100644 --- a/tests/test_openclaw_integration.ts +++ b/tests/test_openclaw_integration.ts @@ -208,6 +208,7 @@ const sampleArgs: Record> = { "analyze_portfolio_risk": {"positions": [{"symbol": "AAPL", "price": 100, "quantity": 10, "currency": "USD"}], "base_currency": "USD", "cash": 100}, "plan_portfolio_rebalance": {"base_currency": "USD", "cash": 100, "positions": [], "targets": [{"symbol": "AAPL", "weight": 1, "price": 100, "currency": "USD", "lot_size": 1}]}, "calculate_position_size": {"equity": 100000, "cash": 20000, "entry_price": 100, "stop_price": 95, "risk_fraction": 0.01, "lot_size": 100}, + analyze_intraday_t0: { bars: [] }, "analyze_event_study": {"prices": [{"date": "2026-01-02", "close": 100}, {"date": "2026-01-05", "close": 110}], "benchmark_prices": [{"date": "2026-01-02", "close": 100}, {"date": "2026-01-05", "close": 100}], "event_dates": ["2026-01-05"], "price_basis": "adjusted", "horizons": [0]}, "validate_backtest": {"datasets": [], "strategies": []}, "compare_analysis_snapshots": {"previous": {"价格": 10}, "current": {"价格": 12}}, diff --git a/tests/test_pi_integration.ts b/tests/test_pi_integration.ts index 5f12e5e..3279062 100644 --- a/tests/test_pi_integration.ts +++ b/tests/test_pi_integration.ts @@ -12,6 +12,7 @@ const EXPECTED_TOOLS = [ "plan_portfolio_rebalance", "calculate_position_size", "calculate_dcf_valuation", + "analyze_intraday_t0", "analyze_event_study", "validate_backtest", "compare_analysis_snapshots", diff --git a/tests/test_report_renderer.py b/tests/test_report_renderer.py index e86f275..55b9f8e 100644 --- a/tests/test_report_renderer.py +++ b/tests/test_report_renderer.py @@ -258,3 +258,35 @@ def test_unknown_market_temperature_renders_honest_limitations(): assert "error" not in result assert "市场行情采集失败,无法确定温度" in result["content"] assert "均衡" not in result["content"] + + +@pytest.mark.parametrize(("kind", "template"), [("stock", "full"), ("stock", "brief"), ("market", "full")]) +def test_macro_liquidity_survives_report_rendering(kind, template): + stock_schema = json.loads((PROJECT_ROOT / "schemas" / "report_schema.json").read_text()) + market_schema = json.loads(MARKET_SCHEMA.read_text()) + assert stock_schema["properties"]["macro_liquidity"] == market_schema["properties"]["macro_liquidity"] + report = { + "market": "HK", + "macro_liquidity": { + "anchors": { + "us_real_10y": { + "name": "US 10Y TIPS", + "latest": 1.72, + "window_change": 0.0, + "unit": "percent", + "as_of": "2023-12-29", + "window_start": "2023-12-01", + "source": "fred", + } + }, + "missing": ["hibor_1m"], + "valuation": "实际利率在观察窗内持平", + "fundamentals": "授权进展单独核对", + }, + } + result = report_renderer.render(kind, template, report) + text = result["content"] + assert "US 10Y TIPS | 2023-12-29 | 1.72 percent | 2023-12-01 | 0.0 | fred" in text + assert "hibor_1m" in text + assert "实际利率在观察窗内持平" in text + assert "授权进展单独核对" in text diff --git a/tools/_subproc.py b/tools/_subproc.py index c3342ad..d374d1c 100644 --- a/tools/_subproc.py +++ b/tools/_subproc.py @@ -6,6 +6,7 @@ pytest imports it as tools.*. """ +import argparse import contextlib import json import math @@ -24,6 +25,12 @@ COMMAND_BUDGETS = json.loads((Path(TOOLS_DIR) / "cli_budgets.json").read_text(encoding="utf-8")) +class JsonArgumentParser(argparse.ArgumentParser): + def error(self, message): + print(json.dumps({"error": "Invalid command arguments; see --help"})) + raise SystemExit(2) + + def command_timeout(script: str, args: list) -> int: key = f"{Path(script).name}:{args[0] if args else ''}" budget = COMMAND_BUDGETS.get(key, COMMAND_BUDGETS["default"]) diff --git a/tools/capabilities.py b/tools/capabilities.py index 52a5d76..d7d2012 100644 --- a/tools/capabilities.py +++ b/tools/capabilities.py @@ -31,6 +31,7 @@ "plan_portfolio_rebalance": {"markets": ALL_MARKETS, "reason": None}, "calculate_position_size": {"markets": ALL_MARKETS, "reason": None}, "calculate_dcf_valuation": {"markets": ALL_MARKETS, "reason": None}, + "analyze_intraday_t0": {"markets": ["A"], "reason": "A-share session and sellable base position rules"}, "analyze_event_study": {"markets": ALL_MARKETS, "reason": None}, "validate_backtest": {"markets": ALL_MARKETS, "reason": None}, "compare_analysis_snapshots": {"markets": ALL_MARKETS, "reason": None}, diff --git a/tools/intraday_t0.py b/tools/intraday_t0.py new file mode 100644 index 0000000..21cfe14 --- /dev/null +++ b/tools/intraday_t0.py @@ -0,0 +1,823 @@ +#!/usr/bin/env python3 +"""Causal minute-bar support observation for an existing A-share position.""" + +import json +import math +import sys +from collections import defaultdict +from dataclasses import dataclass +from datetime import date, datetime, timedelta, timezone +from pathlib import Path +from statistics import mean, median + +from _subproc import JsonArgumentParser, json_safe, utf8_stdio + +CST = timezone(timedelta(hours=8)) +MISSING_ORDER_INPUTS = { + "benchmark_or_sector_minute_coverage_missing", + "position_costs_or_target_missing", + "price_limits_missing", +} +THRESHOLDS = { + "atr_bars": 14, + "volume_baseline_bars": 20, + "new_low_bars": 5, + "break_atr_multiple": 0.5, + "break_volume_ratio": 1.5, + "bounce_volume_ratio": 1.2, + "hold_bars": 2, + "min_aggression_ratio": 0.10, + "time_stop_bars": 5, +} + + +@dataclass(frozen=True) +class Bar: + end: datetime + open: float + high: float + low: float + close: float + volume: int + amount: float | None + + +def number(value, label, *, minimum=0, maximum=None, integer=False): + if ( + type(value) not in (int, float) + or not math.isfinite(value) + or value < minimum + or (maximum is not None and value > maximum) + or (integer and int(value) != value) + ): + raise ValueError(f"invalid {label}") + return int(value) if integer else float(value) + + +def price(value, label): + return number(value, label, minimum=0.000001) + + +def time(value): + if not isinstance(value, str): + raise ValueError("timestamps must be ISO 8601 with UTC offset") + ts = datetime.fromisoformat(value[:-1] + "+00:00" if value.endswith("Z") else value) + if ts.tzinfo is None: + raise ValueError("timestamps must include a UTC offset") + return ts.astimezone(CST) + + +def array(value, label): + if not isinstance(value, list) or any(not isinstance(item, dict) for item in value): + raise ValueError(f"{label} must be an array of objects") + return value + + +def session_grid(day, minutes): + return [ + datetime.combine(day, datetime.min.time(), CST) + timedelta(minutes=end) + for start, finish in ((570, 690), (780, 900)) + for end in range(start + minutes, finish + 1, minutes) + ] + + +def parse_bars(rows): + bars = [] + for row in rows: + volume = number(row.get("volume"), "volume (shares)", integer=True) + amount = None if row.get("amount") is None else number(row["amount"], "amount (CNY)") + bar = Bar( + time(row.get("timestamp")), + price(row.get("open"), "open"), + price(row.get("high"), "high"), + price(row.get("low"), "low"), + price(row.get("close"), "close"), + volume, + amount, + ) + if bar.low > min(bar.open, bar.close) or bar.high < max(bar.open, bar.close): + raise ValueError("OHLC prices fall outside the bar range") + if amount is not None: + if not volume and amount: + raise ValueError("positive amount with zero volume") + if volume and not bar.low - 0.005 <= amount / volume <= bar.high + 0.005: + raise ValueError("amount/volume falls outside the bar range; check CNY and shares units") + bars.append(bar) + if any(a.end >= b.end for a, b in zip(bars, bars[1:])): + raise ValueError("bars must be unique and in ascending timestamp order") + return bars + + +def tick_volumes(data, bars, step): + ticks = data.get("ticks") + if ticks is None: + return None + if not isinstance(data.get("tick_side_basis"), str) or not data["tick_side_basis"].strip(): + raise ValueError("tick_side_basis must describe the supplied trade-side classification") + sides = {} + for row in array(ticks, "ticks"): + ts = time(row.get("timestamp")) + side = row.get("side") + if side not in ("buy", "sell", "unknown"): + raise ValueError("tick side must be buy, sell or unknown") + volume = number(row.get("volume"), "tick volume (shares)", minimum=1, integer=True) + if not bars[0].end - step < ts <= bars[-1].end: + raise ValueError("tick timestamp lies outside supplied bars") + volumes = sides.setdefault(ts, {"buy": 0, "sell": 0, "unknown": 0}) + volumes[side] += volume + result = [] + times = iter(sorted(sides)) + ts = next(times, None) + for bar in bars: + totals = {"buy": 0, "sell": 0, "unknown": 0} + while ts is not None and ts <= bar.end: + if ts <= bar.end - step: + raise ValueError("tick timestamp lies outside supplied bars") + for side, volume in sides[ts].items(): + totals[side] += volume + ts = next(times, None) + if sum(totals.values()) > bar.volume: + raise ValueError("tick volume exceeds bar volume; check coverage and units") + result.append(totals) + return result + + +def benchmark(data, field, bars): + if data.get(field) is None: + return None + prices = {} + for row in array(data[field], field): + ts = time(row.get("timestamp")) + if ts in prices: + raise ValueError(f"duplicate timestamps in {field}") + prices[ts] = price(row.get("close"), field) + expected = [b.end for b in bars] + matched = [ts for ts in expected if ts in prices] + return { + "matched_bars": len(matched), + "complete": len(matched) == len(expected), + "window_return": ( + prices[expected[-1]] / prices[expected[0]] - 1 + if len(expected) >= 2 and len(matched) == len(expected) + else None + ), + } + + +def divide(num, den): + return num / den if den > 0 else None + + +def order_terms(order): + if order is None: + return None + if not isinstance(order, dict): + raise ValueError("order must be an object") + values = { + key: number(order.get(key), key, minimum=minimum, maximum=maximum, integer=integer) + for key, minimum, maximum, integer in ( + ("base_shares", 1, None, True), + ("sellable_shares", 0, None, True), + ("lot_size", 1, None, True), + ("cash", 0, None, False), + ("buy_fee_bps", 0, 1000, False), + ("sell_fee_bps", 0, 1000, False), + ("minimum_fee", 0, None, False), + ("slippage_bps", 0, 1000, False), + ) + } + if values["sellable_shares"] > values["base_shares"]: + raise ValueError("sellable_shares cannot exceed base_shares") + return values + + +def fill_price(px, terms, side): + sign = 1 if side == "buy" else -1 + return px * (1 + sign * terms["slippage_bps"] / 10000) + + +def fill_cash(px, qty, terms, side): + fill = fill_price(px, terms, side) + gross = fill * qty + fee = max(terms["minimum_fee"], gross * terms[f"{side}_fee_bps"] / 10000) + return fill, gross + fee if side == "buy" else gross - fee + + +def paired_quantity(entry, stop, target, terms): + lot = terms["lot_size"] + cash = terms["cash"] + # Allow rounding from price multiplication and fee addition at the exact cash boundary. + cash_limit = cash + 2 * math.ulp(cash) + low, high = 0, terms["sellable_shares"] // lot + while low < high: + lots = (low + high + 1) // 2 + _, cost = fill_cash(entry, lots * lot, terms, "buy") + if cost <= cash_limit: + low = lots + else: + high = lots - 1 + qty = low * lot + if qty <= 0: + return None + _, cost = fill_cash(entry, qty, terms, "buy") + _, profit_proceeds = fill_cash(target, qty, terms, "sell") + _, stop_proceeds = fill_cash(stop, qty, terms, "sell") + reward, risk = profit_proceeds - cost, cost - stop_proceeds + if reward <= 0 or risk <= 0 or reward < risk: + return None + return {"buy_shares": qty, "sell_shares": qty, "net_reward": reward, "net_risk": risk, "reward_risk": reward / risk} + + +def down_volume(bars, index): + volumes = [] + for j in range(index, 0, -1): + if bars[j].close >= bars[j - 1].close: + break + volumes.append(bars[j].volume) + return mean(volumes) if volumes else None + + +def candidate_states(bars, step, support, ticks): + """Evaluate only closed bars. Each fixed support produces at most one attempt per session.""" + price_amount = volume = 0 + used_proxy = False + ranges = [] + atr_bars = THRESHOLDS["atr_bars"] + baseline_bars = THRESHOLDS["volume_baseline_bars"] + low_bars = THRESHOLDS["new_low_bars"] + attempt = None + for i, bar in enumerate(bars): + prev = bars[i - 1].close if i else bar.open + tr = max(bar.high - bar.low, abs(bar.high - prev), abs(bar.low - prev)) + atr = mean(ranges[-atr_bars:]) if len(ranges) >= atr_bars else None + ranges.append(tr) + baseline = median(b.volume for b in bars[i - baseline_bars : i]) if i >= baseline_bars else None + sell_ratio = divide(bar.volume, baseline) if baseline and bar.close < prev else None + used_proxy |= bar.volume > 0 and bar.amount is None + amount = bar.amount if bar.amount is not None else (bar.high + bar.low + bar.close) / 3 * bar.volume + price_amount += amount + volume += bar.volume + vwap = divide(price_amount, volume) + distance = (bar.low - support["price"]) / support["price"] + levels = { + "atr_14": atr, + "sell_volume_baseline": baseline, + "sell_volume_ratio": sell_ratio, + "vwap": vwap, + "cumulative_volume": volume, + "cumulative_vwap_numerator": price_amount, + "close_position": divide(bar.close - bar.low, bar.high - bar.low), + "distance_to_support": distance, + "new_low_count": sum( + bars[j].low < min(b.low for b in bars[max(0, j - low_bars) : j]) + for j in range(max(1, i - low_bars + 1), i + 1) + ), + "reclaim_vwap": bar.close > vwap if vwap is not None else None, + } + state, level = "Setup", "none" + if not atr or not baseline or vwap is None: + level = "unavailable" + if ( + attempt is None + and level != "unavailable" + and bar.volume > 0 + and bar.end - step >= support["as_of"] + and bar.low <= support["price"] + ): + attempt = { + "index": i, + "low": bar.low, + "stop": support["price"] - THRESHOLDS["break_atr_multiple"] * atr, + "down_average": down_volume(bars, i), + "trigger": None, + "accepted": None, + "failed": None, + "hold": None, + "continued": False, + "bounce_sum": 0, + "bounce_count": 0, + } + + levels.update( + recovery=divide(bar.close - bar.low, vwap - bar.low) if vwap is not None else None, + repair_recovery=None, + bounce_volume_ratio=None, + hold_vwap=None, + aggression_ratio=None, + aggressive_buy_volume=None, + aggressive_sell_volume=None, + unclassified_volume=None, + ) + assumption = "price_volume_proxy" + if attempt is not None: + trigger = attempt["trigger"] + if bar.volume and ( + bar.low < attempt["stop"] or (distance < 0 and (sell_ratio or 0) >= THRESHOLDS["break_volume_ratio"]) + ): + attempt["failed"] = attempt["failed"] or "support_broken" + if bar.volume and i > attempt["index"] and bar.low < attempt["low"]: + if trigger is not None: + attempt["failed"] = attempt["failed"] or "new_low_after_trigger" + if trigger is None: + attempt.update(low=bar.low, down_average=down_volume(bars, i), bounce_sum=0, bounce_count=0) + if bar.volume and i > attempt["index"] and bar.low >= attempt["low"] and bar.close > prev: + attempt["bounce_sum"] += bar.volume + attempt["bounce_count"] += 1 + if vwap is not None: + levels["repair_recovery"] = divide(bar.close - attempt["low"], vwap - attempt["low"]) + + if ( + trigger is None + and not attempt["failed"] + and bar.volume > 0 + and levels["reclaim_vwap"] + and levels["repair_recovery"] is not None + ): + trigger = attempt["trigger"] = i + + if trigger is not None and i > trigger: + if (not bar.volume or not levels["reclaim_vwap"]) and i <= trigger + THRESHOLDS["hold_bars"]: + attempt["hold"] = False + attempt["failed"] = attempt["failed"] or ( + "no_trades_during_confirmation" if not bar.volume else "vwap_lost_during_confirmation" + ) + if i == trigger + THRESHOLDS["hold_bars"] and attempt["hold"] is None: + attempt["hold"] = True + if not attempt["failed"]: + attempt["accepted"] = i + if bar.volume and not levels["reclaim_vwap"] and attempt["accepted"] is not None: + attempt["failed"] = attempt["failed"] or "vwap_lost_after_confirmation" + attempt["continued"] |= bar.volume > 0 and bar.close > bars[trigger].high + if i >= trigger + THRESHOLDS["time_stop_bars"] and not attempt["continued"]: + attempt["failed"] = attempt["failed"] or "time_stop" + + # Freeze the volume and tick evidence at the confirmation bar. + if attempt["accepted"] is None or i == attempt["accepted"]: + bounce_mean = divide(attempt["bounce_sum"], attempt["bounce_count"]) + attempt["bounce_ratio"] = ( + divide(bounce_mean, attempt["down_average"]) if bounce_mean and attempt["down_average"] else None + ) + levels["bounce_volume_ratio"] = attempt["bounce_ratio"] + levels["down_phase_mean_volume"] = attempt["down_average"] + levels["hold_vwap"] = attempt["hold"] + if ticks is not None and trigger is not None: + end = attempt["accepted"] if attempt["accepted"] is not None else i + buy = sum(t["buy"] for t in ticks[trigger : end + 1]) + sell = sum(t["sell"] for t in ticks[trigger : end + 1]) + total = sum(b.volume for b in bars[trigger : end + 1]) + ratio = divide(buy - sell, buy + sell) if buy + sell == total else None + levels.update( + aggressive_buy_volume=buy, + aggressive_sell_volume=sell, + unclassified_volume=total - buy - sell, + aggression_ratio=ratio, + ) + assumption = "classified_trades" if ratio is not None else "incomplete_trade_sides" + + if attempt["failed"]: + state, level = "Failure", "none" + elif attempt["accepted"] is not None: + state, level = "Acceptance", "weak" + if (attempt["bounce_ratio"] or 0) >= THRESHOLDS["bounce_volume_ratio"] and ( + ticks is None or (levels["aggression_ratio"] or 0) >= THRESHOLDS["min_aggression_ratio"] + ): + level = "strong" + elif trigger is not None: + state, level = "Trigger", "weak" + else: + level = "watch" + yield { + "state": state, + "support_level": level, + "as_of": bar.end.isoformat(), + "metrics": levels, + "evidence_basis": assumption, + "vwap_basis": "ohlcv_typical_price_proxy" if used_proxy else "turnover_divided_by_volume", + "setup": {"touch_at": bars[attempt["index"]].end.isoformat()} if attempt else None, + "trigger": {"at": bars[trigger].end.isoformat()} if attempt and trigger is not None else None, + "acceptance": ( + {"at": bars[attempt["accepted"]].end.isoformat()} + if attempt and attempt["accepted"] is not None + else None + ), + "invalidation": ( + {"stop_price": attempt["stop"], "reason": attempt["failed"]} if attempt is not None else None + ), + "time_stop": { + "bars_after_trigger": THRESHOLDS["time_stop_bars"], + "requires_close_above_trigger_high": True, + }, + } + + +def validated_price_limits(value, bars): + if value is None: + return None + if not isinstance(value, dict): + raise ValueError("price_limits must be an object") + lower, upper = price(value.get("lower"), "lower price limit"), price(value.get("upper"), "upper price limit") + if lower >= upper or any(bar.low < lower or bar.high > upper for bar in bars): + raise ValueError("bar prices inconsistent with stated price limits") + return {"lower": lower, "upper": upper} + + +def session_period(data): + if not isinstance(data, dict) or data.get("market", "A") != "A": + raise ValueError("only A-share minute sessions are supported") + period = data.get("period", "1m") + if period not in ("1m", "5m"): + raise ValueError("period must be 1m or 5m") + return period + + +def analyze(data, *, snapshots=None): + period = session_period(data) + minutes = int(period[0]) + step = timedelta(minutes=minutes) + bars = parse_bars(array(data.get("bars", []), "bars")) + result = { + "market": "A", + "period": period, + "timezone": "Asia/Shanghai", + "trade_date": bars[0].end.date().isoformat() if bars else None, + "as_of": bars[-1].end.isoformat() if bars else None, + "state": "Setup", + "support_level": "unavailable", + "data_complete_through_as_of": False, + "session_complete": False, + "quantity": None, + "setup": None, + "trigger": None, + "acceptance": None, + "invalidation": None, + "thresholds": THRESHOLDS, + "metrics": {"aggression_ratio": None}, + "no_trade_conditions": [], + } + if not bars: + result["no_trade_conditions"] = ["minute_bars_missing"] + return result + if bars[0].end.date() != bars[-1].end.date(): + raise ValueError("analyze accepts one trading session") + grid = session_grid(bars[0].end.date(), minutes) + if [b.end for b in bars] != grid[: len(bars)]: + result["no_trade_conditions"] = ["missing_or_unaligned_session_bars"] + return result + result.update(data_complete_through_as_of=True, session_complete=len(bars) == len(grid)) + support = data.get("support") + if support is None: + result["no_trade_conditions"] = ["predeclared_support_missing"] + return result + if not isinstance(support, dict) or support.get("basis") not in ( + "platform", + "intraday_low", + "daily_ma5", + "daily_ma10", + "minute_ma5", + "minute_ma10", + "vwap", + ): + raise ValueError("support.basis must identify a platform, prior intraday low, daily/minute MA5/MA10 or VWAP") + support = { + "basis": support["basis"], + "price": price(support.get("price"), "support price"), + "as_of": time(support.get("as_of")), + } + if support["as_of"] > bars[-1].end: + raise ValueError("support timestamp is after the data cutoff") + ticks = tick_volumes(data, bars, step) + for snapshot in candidate_states(bars, step, support, ticks): + result.update(snapshot) + if snapshots is not None: + snapshots.append(snapshot) + result["support"] = {**support, "as_of": support["as_of"].isoformat()} + if ticks is not None: + result["tick_side_basis"] = data["tick_side_basis"] + result["market_context"] = { + "benchmark": benchmark(data, "benchmark_bars", bars), + "sector": benchmark(data, "sector_bars", bars), + } + if "daily_ma5" in data: + result["daily_ma5"] = price(data["daily_ma5"], "daily_ma5") + result["above_daily_ma5"] = bars[-1].close > result["daily_ma5"] + if result["support_level"] == "unavailable": + result["no_trade_conditions"].append("atr_volume_or_vwap_warmup_insufficient") + result["minute_ma5"] = mean(b.close for b in bars[-5:]) if len(bars) >= 5 else None + result["minute_ma10"] = mean(b.close for b in bars[-10:]) if len(bars) >= 10 else None + terms = order_terms(data.get("order")) + limits = validated_price_limits(data.get("price_limits"), bars) + result["price_limits"] = limits + conditions = result["no_trade_conditions"] + accepted = result.get("acceptance") + if result["support_level"] != "strong": + conditions.append("strong_acceptance_missing") + elif accepted["at"] != result["as_of"]: + conditions.append("acceptance_already_observed") + if len(bars) >= len(grid) - 1: + conditions.append("insufficient_time_to_pair_before_close") + if any(context is None or not context["complete"] for context in result["market_context"].values()): + conditions.append("benchmark_or_sector_minute_coverage_missing") + if result.get("above_daily_ma5") is False: + conditions.append("below_daily_ma5") + if terms is None or data.get("target_price") is None: + conditions.append("position_costs_or_target_missing") + if limits is None: + conditions.append("price_limits_missing") + target = price(data["target_price"], "target_price") if data.get("target_price") is not None else None + if not conditions: + stop = result["invalidation"]["stop_price"] + lower, upper = limits["lower"], limits["upper"] + close = bars[-1].close + if ( + stop <= math.nextafter(lower, math.inf) + or not stop < target <= upper + or fill_price(stop, terms, "sell") < lower + or fill_price(close, terms, "buy") > upper + ): + conditions.append("price_limits_block_trade_plan") + else: + if stop < close < target: + result["quantity"] = paired_quantity(close, stop, target, terms) + if result["quantity"] is None: + conditions.append("insufficient_lot_cash_or_net_reward_to_risk") + return result + + +def executable_open(bar, terms, side, lower, upper): + blocked_at_limit = bar.open >= upper if side == "buy" else bar.open <= lower + return bar.volume > 0 and not blocked_at_limit and lower <= fill_price(bar.open, terms, side) <= upper + + +def simulated_fill(bar, qty, terms, side, lower, upper): + if bar.volume < qty or not executable_open(bar, terms, side, lower, upper): + return None + fill, cash = fill_cash(bar.open, qty, terms, side) + return {"bar_end": bar.end.isoformat(), "price": fill, "cash": cash} + + +def replay_session(data, terms): + period = int(session_period(data)[0]) + rows = data["bars"] + bars = parse_bars(rows) + if bars[0].end.date() != bars[-1].end.date(): + raise ValueError("replay accepts one trading session per entry") + grid = session_grid(bars[0].end.date(), period) + report = { + "date": bars[0].end.date().isoformat(), + "regime": data.get("regime", "unknown"), + "status": "no_signal", + "session_complete": False, + } + for i, bar in enumerate(bars): + if i == len(grid) or bar.end != grid[i]: + report["data_gap_at"] = (grid[i] if i < len(grid) else bar.end).isoformat() + bars = bars[:i] + if not bars: + report["status"] = "unavailable" + return report, None + support = data.get("support") + if isinstance(support, dict) and time(support.get("as_of")) > bars[-1].end: + report.update(status="unavailable", reasons=["support_not_known_before_data_gap"]) + return report, None + data = {**data, "bars": rows[:i]} + if data.get("ticks") is not None: + data["ticks"] = [ + tick for tick in array(data["ticks"], "ticks") if time(tick.get("timestamp")) <= bars[-1].end + ] + break + snapshots = [] + observation = analyze(data, snapshots=snapshots) + report["session_complete"] = observation["session_complete"] and "data_gap_at" not in report + missing_inputs = MISSING_ORDER_INPUTS.intersection(observation["no_trade_conditions"]) + if missing_inputs: + report["missing_inputs"] = sorted(missing_inputs) + hit = next((i for i, s in enumerate(snapshots) if s["support_level"] == "strong"), None) + if hit is None: + if observation["support_level"] == "unavailable" or not observation["data_complete_through_as_of"]: + report["status"] = "unavailable" + return report, None + prefix = {**data, "bars": data["bars"][: hit + 1], "order": terms} + if data.get("ticks") is not None: + prefix["ticks"] = [tick for tick in data["ticks"] if time(tick["timestamp"]) <= bars[hit].end] + signal = analyze(prefix) + report["signal_at"] = signal["as_of"] + if signal["quantity"] is None: + reasons = signal["no_trade_conditions"] + status = "price_limits_missing" if "price_limits_missing" in reasons else "no_trade" + report.update(status=status, reasons=reasons) + return report, None + if hit + 1 >= len(bars): + report["status"] = "entry_bar_missing" + return report, None + + lower, upper = signal["price_limits"]["lower"], signal["price_limits"]["upper"] + stop, target = signal["invalidation"]["stop_price"], data["target_price"] + entry = None + report["status"] = "entry_unfilled" + last_entry = min(len(bars), len(grid) - 1) + for entry_index in range(hit + 1, last_entry): + if snapshots[entry_index - 1]["state"] == "Failure": + break + entry_bar = bars[entry_index] + if not executable_open(entry_bar, terms, "buy", lower, upper): + continue + paired = paired_quantity(entry_bar.open, stop, target, terms) if stop < entry_bar.open < target else None + if paired is None: + report["status"] = "entry_outside_risk_budget" + return report, None + qty = min(signal["quantity"]["buy_shares"], paired["buy_shares"]) + entry = simulated_fill(entry_bar, qty, terms, "buy", lower, upper) + if entry is not None: + break + if entry is None: + return report, None + + trade = {"date": report["date"], "regime": report["regime"], "entry": entry, "buy_shares": qty} + exit_reason = None + trade_curve = [] + last_session_bar = grid[-1] + for i in range(entry_index, len(bars)): + bar = bars[i] + if bar.end == last_session_bar: + exit_reason = exit_reason or "session_close" + if exit_reason: + exit_fill = simulated_fill(bar, qty, terms, "sell", lower, upper) + if exit_fill: + pnl = exit_fill["cash"] - entry["cash"] + trade_curve.append(pnl) + trade.update(exit=exit_fill, sell_shares=qty, net_pnl=pnl, exit_reason=exit_reason, curve=trade_curve) + report["status"] = "paired" + return report, trade + trade_curve.append(bar.close * qty - entry["cash"]) + if exit_reason is None: + if snapshots[i]["state"] == "Failure" or (bar.volume and bar.close <= stop): + exit_reason = snapshots[i]["invalidation"]["reason"] or "support_stop" + elif bar.volume and bar.close >= target: + exit_reason = "target_close" + + trade.update( + exit=None, + sell_shares=0, + net_pnl=None, + unpaired_shares=qty, + mark_to_market=trade_curve[-1], + exit_reason=exit_reason, + curve=trade_curve, + ) + report["status"] = "unpaired" + return report, trade + + +def trade_metrics(trades, cash): + pnl = [t["net_pnl"] for t in trades if t["net_pnl"] is not None] + wins = [p for p in pnl if p > 0] + losses = [-p for p in pnl if p < 0] + streak = longest = 0 + for value in pnl: + streak = streak + 1 if value < 0 else 0 + longest = max(longest, streak) + equity = peak = cash if cash is not None else 0.0 + drawdown = 0.0 + for trade in trades: + for value in trade["curve"]: + marked = equity + value + peak = max(peak, marked) + if peak > 0: + drawdown = max(drawdown, (peak - marked) / peak) + equity += trade["net_pnl"] if trade["net_pnl"] is not None else trade["mark_to_market"] + return { + "starting_cash_cny": cash, + "total_trades": len(pnl), + "unpaired_trades": len(trades) - len(pnl), + "win_rate": len(wins) / len(pnl) if pnl else None, + "profit_loss_ratio": mean(wins) / mean(losses) if wins and losses else None, + "expectancy_cny": mean(pnl) if pnl else None, + "net_realized_pnl_cny": sum(pnl), + "max_drawdown": drawdown if trades and cash else None, + "max_consecutive_losses": longest, + } + + +def validation_status(metrics, reports): + incomplete = { + "unavailable", + "price_limits_missing", + "entry_bar_missing", + "unpaired", + "skipped_after_unpaired_trade", + } + if metrics["total_trades"] < 30 or any( + not row.get("session_complete") or row["status"] in incomplete or row.get("missing_inputs") for row in reports + ): + return "unverified" + return "sample_screen_passed" + + +def backtest(data): + period = session_period(data) + terms = order_terms(data.get("order")) + if terms is None: + raise ValueError("backtest requires order and costs") + split = data.get("out_of_sample_from") + if not isinstance(split, str): + raise ValueError("backtest requires out_of_sample_from (YYYY-MM-DD)") + split = date.fromisoformat(split).isoformat() + sessions = array(data.get("sessions"), "sessions") + reports, trades = [], [] + starting_cash = {} + previous = "" + halted = False + cash = float(terms["cash"]) + for session in sessions: + first = array(session.get("bars"), "session bars") + if not first: + raise ValueError("each replay session needs a dated minute bar") + day = time(first[0].get("timestamp")).date().isoformat() + if day <= previous: + raise ValueError("backtest sessions must be unique and in ascending date order") + previous = day + regime = session.get("regime", "unknown") + if not isinstance(regime, str) or not regime: + raise ValueError("regime must be a nonempty label known before entry") + sample = "in_sample" if day < split else "out_of_sample" + starting_cash.setdefault(sample, None if halted else cash) + if halted: + reports.append({"date": day, "regime": regime, "status": "skipped_after_unpaired_trade"}) + continue + report, trade = replay_session({"period": period, **session, "order": terms}, {**terms, "cash": cash}) + reports.append(report) + if trade: + trades.append(trade) + if trade["net_pnl"] is None: + halted = True + else: + cash += trade["net_pnl"] + + samples = {} + for name, predicate in (("in_sample", lambda day: day < split), ("out_of_sample", lambda day: day >= split)): + selected = [t for t in trades if predicate(t["date"])] + rows = [r for r in reports if predicate(r["date"])] + sample_cash = starting_cash.get(name) + metrics = trade_metrics(selected, sample_cash) + reports_by_regime = defaultdict(list) + trades_by_regime = defaultdict(list) + for row in rows: + reports_by_regime[row["regime"]].append(row) + for trade in selected: + trades_by_regime[trade["regime"]].append(trade) + by_regime = {} + for regime, regime_reports in sorted(reports_by_regime.items()): + regime_metrics = trade_metrics(trades_by_regime.get(regime, []), sample_cash) + by_regime[regime] = { + **regime_metrics, + "validation_status": "unverified" + if regime == "unknown" + else validation_status(regime_metrics, regime_reports), + } + samples[name] = { + "sessions": len(rows), + "metrics": metrics, + "validation_status": validation_status(metrics, rows), + "by_regime": by_regime, + } + for trade in trades: + del trade["curve"] + return { + "market": "A", + "out_of_sample_from": split, + "thresholds": THRESHOLDS, + "samples": samples, + "sessions": reports, + "trades": trades, + "limitations": [ + "Buy first, then sell the same quantity from the previously sellable base position.", + "Entry retries on later bar opens while support holds and risk permits; exits also use later bar opens. " + "Volume checks are a capacity proxy. Queue, latency, " + "partial fills, intrabar ordering and market impact are not modeled.", + "Drawdown uses each sample's starting cash and minute closes, excluding base-position price P&L. " + "Regime slices include only trades in the selected regime, with the same sample starting cash.", + "Thresholds are fixed research candidates. The split does not establish that inputs were chosen ex ante.", + ], + } + + +def main(): + utf8_stdio() + parser = JsonArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + commands = {"analyze": analyze, "backtest": backtest} + for command in commands: + p = sub.add_parser(command) + p.add_argument("--input", type=Path, help="JSON file; defaults to stdin") + args = parser.parse_args() + try: + data = json.loads(args.input.read_text(encoding="utf-8") if args.input else sys.stdin.read()) + result = commands[args.command](data) + except (ValueError, OSError, OverflowError) as exc: + result = {"error": str(exc) if isinstance(exc, ValueError) else "unable to read or process intraday input"} + print(json.dumps(json_safe(result), ensure_ascii=False, allow_nan=False)) + return int("error" in result) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/macro_data.py b/tools/macro_data.py index 581657e..d74bb0e 100644 --- a/tools/macro_data.py +++ b/tools/macro_data.py @@ -6,21 +6,20 @@ cross-currency portfolio risk, and market review. """ -import argparse import csv import io import json import math import sys from concurrent.futures import ThreadPoolExecutor -from datetime import datetime, timezone +from datetime import date, datetime, timedelta, timezone from pathlib import Path import requests sys.path.insert(0, str(Path(__file__).resolve().parent)) from _cache import cached # noqa: E402 -from _subproc import error_message, json_safe, utf8_stdio # noqa: E402 +from _subproc import JsonArgumentParser, error_message, json_safe, socket_timeout, utf8_stdio # noqa: E402 MACRO_TTL = 3600 # 1 hour cache for daily macro anchors @@ -28,6 +27,8 @@ "rates": ("us_10y", "us_2y", "cn_10y"), "fx": ("dxy", "usdcnh", "usdhkd", "hkdcny"), "risk": ("vix", "gold", "crude_oil"), + "liquidity_a": ("cn_10y", "fdr007", "fr007", "lpr_1y", "lpr_5y", "m1_yoy", "tsf_increment"), + "liquidity_hk": ("us_10y", "us_2y", "us_real_10y", "dxy", "usdcnh", "usdhkd", "hibor_1m", "southbound_net_buy"), } ALL_KEYS = GROUPS["rates"] + GROUPS["fx"] + GROUPS["risk"] @@ -44,6 +45,7 @@ FRED_SPECS = { "us_10y": ("DGS10", "US 10Y Treasury Yield", "percent"), "us_2y": ("DGS2", "US 2Y Treasury Yield", "percent"), + "us_real_10y": ("DFII10", "US 10Y TIPS Real Yield", "percent"), } @@ -114,8 +116,14 @@ def _fetch_yf_series(ticker: str, days: int, scale: float = 1.0) -> list[tuple[s def _fetch_fred_series(series_id: str, days: int) -> list[tuple[str, float]]: - url = f"https://fred.stlouisfed.org/graph/fredgraph.csv?id={series_id}" - resp = requests.get(url, timeout=15, headers={"User-Agent": "stock-analysis-plugin"}) + url = "https://fred.stlouisfed.org/graph/fredgraph.csv" + end = datetime.now(timezone.utc).date() + start = end - timedelta(days=days * 2 + 14) + resp = requests.get( + url, + params={"id": series_id, "cosd": start.isoformat(), "coed": end.isoformat()}, + timeout=12, + ) resp.raise_for_status() reader = csv.DictReader(io.StringIO(resp.text)) points = [] @@ -155,6 +163,152 @@ def _fetch_cn_us_yields_akshare(days: int) -> dict[str, list[tuple[str, float]]] return out +LIQUIDITY_CONTEXT = { + "liquidity_a": { + "market": "A", + "discount_rate": ["cn_10y"], + "proxies": {"dr007": "fdr007", "r007": "fr007"}, + "funding_and_credit": ["fdr007", "fr007", "lpr_1y", "lpr_5y", "m1_yoy", "tsf_increment"], + "interpretation": [ + "Read government yields alongside repo fixings and credit conditions.", + "Separate the discount-rate effect from growth, demand and earnings revisions.", + "A lower government yield can coexist with weaker expected earnings.", + "FR007/FDR007 are morning fixings, not full-day weighted R007/DR007.", + "M1 methodology changed starting January 2025; compare like-for-like vintages.", + "Social financing increments are seasonal; prefer year-on-year context to adjacent months.", + ], + }, + "liquidity_hk": { + "market": "HK", + "discount_rate": ["us_10y", "us_2y", "us_real_10y", "hibor_1m"], + "fx_and_flows": ["dxy", "usdcnh", "usdhkd", "southbound_net_buy"], + "interpretation": [ + "The Linked Exchange Rate System transmits USD rate conditions; use HIBOR to check local funding.", + "For long-duration biotechnology, assess discount rates and financing separately from " + "policy, reimbursement, clinical milestones, licensing and earnings.", + "Southbound net buying is market-wide evidence; it is not sector-specific buying.", + ], + }, +} + +HKMA_URL = ( + "https://api.hkma.gov.hk/public/market-data-and-statistics/" + "daily-monetary-statistics/daily-figures-interbank-liquidity" +) +REPO_CSV_URL = "https://www.chinamoney.com.cn/r/cms/www/chinamoney/data/currency/" +EASTMONEY_URL = "https://datacenter-web.eastmoney.com/api/data/v1/get" +TSF_URL = "https://data.mofcom.gov.cn/datamofcom/front/gnmy/shrzgmQuery" + + +def _points(rows, date_key, value_key): + points = {} + for row in rows: + value = _finite(row.get(value_key)) + if value is None: + continue + try: + observed = date.fromisoformat(str(row[date_key])[:10]).isoformat() + except (ValueError, KeyError): + continue + points[observed] = value + return sorted(points.items()) + + +def _get(url, **params): + response = requests.get(url, params=params, timeout=12) + response.raise_for_status() + return response + + +def _eastmoney(report, date_key, columns, days, **params): + result = ( + _get( + EASTMONEY_URL, + reportName=report, + columns=",".join((date_key, *columns)), + sortColumns=date_key, + sortTypes="-1", + pageSize=days, + **params, + ) + .json() + .get("result") + ) + if not result or not isinstance(result.get("data"), list): + raise ValueError(f"{report} returned no data") + return result["data"] + + +def _fetch_liquidity_anchor(key, days): + monthly = key in ("lpr_1y", "lpr_5y", "m1_yoy", "tsf_increment") + count = max(2, math.ceil(days / 30) + 1) if monthly else days + unit = "percent" + if key == "us_real_10y": + symbol, name, unit = FRED_SPECS[key] + points = _fetch_fred_series(symbol, count) + source = "fred" + url = f"https://fred.stlouisfed.org/series/{symbol}" + elif key == "hibor_1m": + name, source, url = "HKAB 1-Month HIBOR Fixing", "hkma", HKMA_URL + rows = _get(url, pagesize=count, sortby="end_of_date", sortorder="desc").json()["result"]["records"] + points = _points(rows, "end_of_date", "hibor_fixing_1m") + elif key in ("fr007", "fdr007"): + name, source = f"{key.upper()} 7-Day Morning Repo Fixing", "cfets" + url = REPO_CSV_URL + ("fdr-chrt.csv" if key == "fdr007" else "frr-chrt.csv") + rows = [ + {"date": row[0], "rate": [cell for cell in row[1:] if cell.strip()][1]} + for row in csv.reader(io.StringIO(_get(url).text)) + if row and len([cell for cell in row[1:] if cell.strip()]) == 3 + ] + points = _points(rows, "date", "rate") + elif key == "tsf_increment": + name, source, url, unit = "China Monthly Aggregate Financing Increment", "mofcom", TSF_URL, "cny_100m" + response = requests.post(url, timeout=12) + response.raise_for_status() + rows = [ + {"period": f"{str(row.get('date'))[:4]}-{str(row.get('date'))[4:6]}-01", "value": row.get("tiosfs")} + for row in response.json() + ] + points = _points(rows, "period", "value") + elif key.startswith("lpr_"): + name, source = f"China {key[-2:].upper()} Loan Prime Rate", "eastmoney" + url = "https://data.eastmoney.com/cjsj/globalRateLPR.html" + column = {"lpr_1y": "LPR1Y", "lpr_5y": "LPR5Y"}[key] + rows = cached( + f"macro_lpr_rows_{count}", + MACRO_TTL, + lambda: _eastmoney("RPTA_WEB_RATE", "TRADE_DATE", ("LPR1Y", "LPR5Y"), count, filter="(LPR1Y>0)"), + ) + points = _points(rows, "TRADE_DATE", column) + elif key == "m1_yoy": + name, source = "China M1 Year-on-Year Growth", "eastmoney" + url = "https://data.eastmoney.com/cjsj/hbgyl.html" + rows = _eastmoney("RPT_ECONOMY_CURRENCY_SUPPLY", "REPORT_DATE", ("CURRENCY_SAME",), count) + points = _points(rows, "REPORT_DATE", "CURRENCY_SAME") + elif key == "southbound_net_buy": + name, source, unit = "Southbound Stock Connect Net Buy Turnover", "eastmoney", "hkd_million" + url = "https://data.eastmoney.com/hsgt/index.html" + rows = _eastmoney( + "RPT_MUTUAL_DEAL_HISTORY", "TRADE_DATE", ("NET_DEAL_AMT",), count, filter='(MUTUAL_TYPE="006")' + ) + points = _points(rows, "TRADE_DATE", "NET_DEAL_AMT") + else: + raise ValueError(f"unknown liquidity anchor: {key}") + period_label = key in ("m1_yoy", "tsf_increment") + if period_label: + points = [(observed[:7], value) for observed, value in points] + summary = _summarize_series(points[-count:], name=name, unit=unit, source=source) + summary.update(source_url=url, frequency="monthly" if monthly else "daily") + if period_label: + summary.update(as_of_basis="observation_period", release_date=None) + summary["change_previous_observation"] = summary["change_1d"] + if monthly: + summary.update(change_1d=None, change_1d_pct=None) + if key == "southbound_net_buy": + summary["window_net_buy"] = round(sum(value for _, value in points[-count:]), 4) + return summary + + def _fetch_anchor_uncached(key: str, days: int, bond_cache: dict | None = None) -> dict: if key == "cn_10y": bonds = bond_cache if bond_cache is not None else _fetch_cn_us_yields_akshare(days) @@ -207,7 +361,11 @@ def _fetch_anchor_uncached(key: str, days: int, bond_cache: dict | None = None) try: pts = _fetch_yf_series(ticker, days) return _summarize_series( - pts, name="USD/CNH Exchange Rate", unit="rate", source="yfinance", symbol=ticker + pts, + name="USD/CNH Exchange Rate" if ticker == "CNH=X" else "USD/CNY Onshore Proxy", + unit="rate", + source="yfinance", + symbol=ticker, ) except Exception as exc: errors.append(f"{ticker}: {error_message(exc, 100)}") @@ -218,7 +376,7 @@ def _fetch_anchor_uncached(key: str, days: int, bond_cache: dict | None = None) pts = _fetch_yf_series(ticker, days, scale=scale) return _summarize_series(pts, name=name, unit=unit, source="yfinance", symbol=ticker) - raise ValueError(f"unknown macro anchor: {key}") + return _fetch_liquidity_anchor(key, days) def _parse_int_days(value) -> int: @@ -244,7 +402,7 @@ def _parse_int_days(value) -> int: def get_macro_anchors(group: str = "all", days: int = 30) -> dict: group = (group or "all").lower() if group != "all" and group not in GROUPS: - return {"error": f"Unknown macro group: {group}. Expected one of all, rates, fx, risk"} + return {"error": f"Unknown macro group: {group}. Expected one of all, {', '.join(GROUPS)}"} try: days = _parse_int_days(days) except ValueError as exc: @@ -259,7 +417,8 @@ def get_macro_anchors(group: str = "all", days: int = 30) -> dict: bond_cache = None if any(k in fetch_keys for k in ("cn_10y", "us_10y", "us_2y")): try: - bond_cache = cached(f"macro_bonds_{days}", MACRO_TTL, lambda: _fetch_cn_us_yields_akshare(days)) + with socket_timeout(12): + bond_cache = cached(f"macro_bonds_{days}", MACRO_TTL, lambda: _fetch_cn_us_yields_akshare(days)) except Exception: bond_cache = {} @@ -274,7 +433,7 @@ def load_one(key: str): lambda: _fetch_anchor_uncached(key, days, bond_cache=bond_cache), ) - with ThreadPoolExecutor(max_workers=min(len(fetch_keys), 6) or 1) as pool: + with socket_timeout(12), ThreadPoolExecutor(max_workers=min(len(fetch_keys), 6) or 1) as pool: futures = {key: pool.submit(load_one, key) for key in fetch_keys} for key, future in futures.items(): try: @@ -299,8 +458,34 @@ def load_one(key: str): missing.append("hkdcny") warnings.append("hkdcny unavailable: requires both usdcnh and usdhkd") + context = LIQUIDITY_CONTEXT.get(group) + if context and (anchors.get("usdcnh") or {}).get("symbol") == "CNY=X": + anchors["usdcny_proxy"] = {**anchors.pop("usdcnh"), "name": "USD/CNY Onshore Proxy"} + missing.append("usdcnh") + warnings.append("usdcnh unavailable: onshore USD/CNY is available as a separate proxy") + + if context: + today = datetime.now(timezone.utc).date() + for key, anchor in anchors.items(): + as_of = anchor.get("as_of") + try: + observed = date.fromisoformat(as_of if len(as_of) == 10 else as_of + "-01") + except (ValueError, TypeError): + continue + monthly = anchor.get("frequency") == "monthly" + lag = (today - observed).days + anchor["stale"] = lag > (65 if monthly else 10) + if anchor["stale"]: + warnings.append(f"{key}: latest source observation {as_of} is stale") + if anchor.get("observations", 0) < 2: + anchor["window_change"] = None + warnings.append(f"{key}: fewer than two observations; window change unavailable") if not anchors: - return {"error": f"All requested macro anchors unavailable ({', '.join(missing)})", "warnings": warnings} + return { + "error": f"All requested macro anchors unavailable ({', '.join(missing)})", + "warnings": warnings, + "missing": missing, + } derived: dict[str, float | None] = {} us10 = (anchors.get("us_10y") or {}).get("latest") @@ -323,6 +508,7 @@ def load_one(key: str): }, "group": group, "days": days, + **({"liquidity_context": context} if context else {}), "anchors": anchors, "derived": derived, "missing": missing, @@ -334,15 +520,12 @@ def load_one(key: str): def main(): - parser = argparse.ArgumentParser(description="Macro, rates, FX, and volatility anchors") - sub = parser.add_subparsers(dest="command") + parser = JsonArgumentParser(description="Macro, rates, FX, and volatility anchors") + sub = parser.add_subparsers(dest="command", required=True) p = sub.add_parser("anchors") - p.add_argument("--group", default="all", choices=["all", "rates", "fx", "risk"]) + p.add_argument("--group", default="all", choices=["all", *GROUPS]) p.add_argument("--days", default="30") args = parser.parse_args() - if not args.command: - parser.print_help() - sys.exit(1) result = get_macro_anchors(group=args.group, days=args.days) print(json.dumps(json_safe(result), ensure_ascii=False, indent=2, allow_nan=False)) if isinstance(result, dict) and "error" in result: diff --git a/tools/stateless_analysis.py b/tools/stateless_analysis.py index f4c0add..55d3d3e 100644 --- a/tools/stateless_analysis.py +++ b/tools/stateless_analysis.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 """Explicit-input research calculations. No account, watchlist or history storage.""" -import argparse import json import math import sys @@ -13,7 +12,7 @@ from fractions import Fraction from pathlib import Path -from _subproc import utf8_stdio +from _subproc import JsonArgumentParser, utf8_stdio class RawNumber(float): @@ -1259,12 +1258,6 @@ def evaluate(frame, name, symbol=symbol): } -class JsonArgumentParser(argparse.ArgumentParser): - def error(self, message): - print(json.dumps({"error": "Invalid command arguments; see --help"})) - raise SystemExit(2) - - def main(): utf8_stdio() parser = JsonArgumentParser(description=__doc__) diff --git a/tools/tool_schemas.json b/tools/tool_schemas.json index 12b7569..845b5f5 100644 --- a/tools/tool_schemas.json +++ b/tools/tool_schemas.json @@ -414,9 +414,11 @@ "all", "rates", "fx", - "risk" + "risk", + "liquidity_a", + "liquidity_hk" ], - "description": "基准分组:all=全部(默认),rates=中美无风险利率,fx=汇率与美元指数,risk=VIX/黄金/原油" + "description": "基准分组:all=原有 rates、fx、risk 指标(默认),rates=中美无风险利率,fx=汇率与美元指数,risk=VIX/黄金/原油;liquidity_a=A股利率、回购定盘、LPR、M1和社融;liquidity_hk=港股美元名义/实际利率、汇率、HIBOR和南向资金" }, "days": { "type": "integer", @@ -426,6 +428,258 @@ "required": [] } }, + { + "name": "analyze_intraday_t0", + "description": "A 股分钟级分时承接与底仓 T0 观察、无状态回放。基于调用方已有的 1m/5m OHLCV、可选逐笔和底仓,输出 VWAP、支撑回踩、两根确认、数据缺失与等量配对条件。无自动下单。", + "parameters": { + "type": "object", + "properties": { + "mode": { + "type": "string", + "description": "analyze=单日观察(默认);backtest=固定阈值复盘", + "enum": [ + "analyze", + "backtest" + ] + }, + "market": { + "type": "string", + "description": "A 股", + "enum": [ + "A" + ] + }, + "period": { + "type": "string", + "description": "已收盘 K 线的周期,默认 1m", + "enum": [ + "1m", + "5m" + ] + }, + "bars": { + "type": "array", + "description": "当日从开盘起连续的已收盘分钟 OHLCV;时间戳为收盘时点,成交量为股,逐根成交额为元", + "items": { + "type": "object", + "properties": { + "timestamp": { + "type": "string", + "description": "带 UTC 偏移的 ISO 8601 时间" + }, + "open": { + "type": "number" + }, + "high": { + "type": "number" + }, + "low": { + "type": "number" + }, + "close": { + "type": "number" + }, + "volume": { + "type": "integer" + }, + "amount": { + "type": "number" + } + }, + "required": [ + "timestamp", + "open", + "high", + "low", + "close", + "volume" + ], + "additionalProperties": false + } + }, + "support": { + "type": "object", + "description": "回踩前已知且固定的支撑价及时间", + "properties": { + "price": { + "type": "number" + }, + "basis": { + "type": "string", + "enum": [ + "platform", + "intraday_low", + "daily_ma5", + "daily_ma10", + "minute_ma5", + "minute_ma10", + "vwap" + ] + }, + "as_of": { + "type": "string", + "description": "带 UTC 偏移的 ISO 8601 时间" + } + }, + "required": [ + "price", + "basis", + "as_of" + ], + "additionalProperties": false + }, + "ticks": { + "type": "array", + "description": "可选真实逐笔,volume 为股", + "items": { + "type": "object", + "properties": { + "timestamp": { + "type": "string", + "description": "带 UTC 偏移的 ISO 8601 时间" + }, + "side": { + "type": "string", + "enum": [ + "buy", + "sell", + "unknown" + ] + }, + "volume": { + "type": "integer" + } + }, + "required": [ + "timestamp", + "side", + "volume" + ], + "additionalProperties": false + } + }, + "tick_side_basis": { + "type": "string", + "description": "逐笔主动买卖方向的来源和判定口径" + }, + "benchmark_bars": { + "type": "array", + "description": "大盘分钟收盘价,时间与个股一致", + "items": { + "type": "object", + "properties": { + "timestamp": { + "type": "string", + "description": "带 UTC 偏移的 ISO 8601 时间" + }, + "close": { + "type": "number" + } + }, + "required": [ + "timestamp", + "close" + ], + "additionalProperties": false + } + }, + "sector_bars": { + "type": "array", + "description": "行业分钟收盘价,时间与个股一致", + "items": { + "type": "object", + "properties": { + "timestamp": { + "type": "string", + "description": "带 UTC 偏移的 ISO 8601 时间" + }, + "close": { + "type": "number" + } + }, + "required": [ + "timestamp", + "close" + ], + "additionalProperties": false + } + }, + "daily_ma5": { + "type": "number", + "description": "用已完成日 K 算出的 MA5,仅作趋势过滤" + }, + "price_limits": { + "type": "object", + "description": "分析模式使用当日实际涨跌停价;缺失时仍可观察承接,配对数量留空。回放在每个 session 提供。", + "properties": { + "lower": { "type": "number" }, + "upper": { "type": "number" } + }, + "required": ["lower", "upper"], + "additionalProperties": false + }, + "target_price": { + "type": "number", + "description": "预先设定的配对退出参考价" + }, + "order": { + "type": "object", + "description": "底仓股数、可卖股数、最小单位、可用现金和往返成本;回放必填", + "properties": { + "base_shares": { + "type": "integer" + }, + "sellable_shares": { + "type": "integer" + }, + "lot_size": { + "type": "integer" + }, + "cash": { + "type": "number" + }, + "buy_fee_bps": { + "type": "number" + }, + "sell_fee_bps": { + "type": "number" + }, + "minimum_fee": { + "type": "number" + }, + "slippage_bps": { + "type": "number" + } + }, + "required": [ + "base_shares", + "sellable_shares", + "lot_size", + "cash", + "buy_fee_bps", + "sell_fee_bps", + "minimum_fee", + "slippage_bps" + ], + "additionalProperties": false + }, + "sessions": { + "type": "array", + "description": "回放专用,按日递增。每项使用上述观察字段,另含 price_limits.lower/upper 与事先确定的 regime;底仓及成本用顶层 order", + "items": { + "type": "object", + "additionalProperties": true + } + }, + "out_of_sample_from": { + "type": "string", + "description": "回放专用,样本外起始交易日 YYYY-MM-DD(含该日)" + } + }, + "required": [], + "additionalProperties": false + } + }, { "name": "get_earnings_calendar", "description": "查询财报日历:A股report_date必填季度期末,返回预约/修订/实际披露与业绩预告;HK需symbol,优先HKEX已公告业绩审批董事会排期(不是实际披露日);US/JP需symbol并返回yfinance供应商预计日期(provider_only,非官方确认)。HK可按已知财政期末过滤,未知期次与US/JP请求report_date时另列unverified_schedules;KR/TW不可用。",