diff --git a/README.md b/README.md index cf1848f..5aa2d21 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ - **策略视角**:缠论、波浪理论、龙头战法、情绪周期等 18 套方法论,以 Skill 形式按需调用。 - **dsh 仪表盘**:在 dsh Web / Desktop 侧栏看自选股和六个市场的行情,后台预热,打开即显示。 -一共 75 个工具、21 个 Skills,11 个数据源自动容灾。大部分功能不需要任何 API Key。 +一共 76 个工具、21 个 Skills,11 个数据源自动容灾。大部分功能不需要任何 API Key。 ## 快速开始 @@ -165,20 +165,20 @@ ## 工具列表 -75 个工具按用途分组: +76 个工具按用途分组: | 类别 | 数量 | 主要内容 | |------|------|----------| -| 数据获取 | 29 | K 线、报价、基金净值、资金流、财务、板块、涨停池、龙虎榜、两融、估值历史、股东、ETF、股息、公告、SEC、CDS 指数 | +| 数据获取 | 30 | K 线、报价、基金净值、资金流、财务、板块、涨停池、龙虎榜、两融、估值历史、股东、ETF、股息、公告、SEC、CDS 指数、宏观利率与汇率基准 | | 分析计算 | 9 | 技术指标、K 线形态、量价、异动、信号胜率、趋势与行业轮动研究 | -| 筛选与回测 | 8 | 多因子选股、风险筛查、策略回测、市场状态、日度复盘、自选股批量分析 | +| 筛选与回测 | 8 | 多因子选股、风险筛查、策略回测(含多标的组合/再平衡/定投)、市场状态、日度复盘、自选股批量分析 | | 搜索与舆情 | 5 | 新闻搜索、综合情报、社交情绪、正文提取 | | 辅助 | 7 | 名称/拼音解析、交易日历、交易时段、数据源诊断、股票列表解析 | | 上下文与报告 | 8 | 自选股上下文、持仓分析、告警规则、信号记录与评估、研报渲染 | | 无状态研究与风险计算 | 9 | 同行比较、公告变更、组合风险、调仓计划、仓位计算、DCF 估值、事件研究、回测稳健性 |
-完整工具列表(75 个) +完整工具列表(76 个) #### 数据获取 @@ -190,6 +190,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_earnings_calendar` | A 股报告期披露与业绩预告;HK 董事会排期;US/JP yfinance 预计日期(provider_only,非官方确认) | | `get_shareholder_structure` | A 股股东户数/十大流通股东变化/报告期北向名义持股;HK 南向持股 | | `get_etf_details` | A 股 ETF 净值折溢价、规模变动、披露持仓、可选基准成分与跟踪误差 | @@ -203,7 +204,7 @@ | `get_stock_info` | 股票基本信息 | | `get_chip_distribution` | 筹码分布 | | `get_market_indices` | 主要指数行情 | -| `get_sector_rankings` | 板块涨跌排行(A 股行业/概念;美股 SPDR 行业 ETF 代理) | +| `get_sector_rankings` | 板块涨跌排行(A 股行业/概念;港股 TradingView 聚合/ETF 代理;美股 SPDR 行业 ETF 代理) | | `get_sector_constituents` | 板块成分股查询(仅 A 股,板块名模糊匹配) | | `resolve_stock_sectors` | 个股所属板块查询(A 股行业+概念 / 港股 GICS) | | `get_market_stats` | 市场统计(A/HK/US 涨跌家数;成交额、涨停仅 A 股) | @@ -235,8 +236,8 @@ | 工具 | 说明 | |------|------| | `screen_stocks` | 全市场多因子筛选,流动性使用成交额 turnover。港股支持 PE、PB、股息率和港股通买入资格。可选 L2,factor_coverage 展示因子覆盖与实际权重。 | -| `screen_risk` | 风险因子筛查 | -| `run_backtest` | YAML 策略回测,默认收盘信号于次日开盘成交,execution 返回模型与限制 | +| `screen_risk` | 风险因子筛查(A 股、港股、美股) | +| `run_backtest` | YAML 策略回测(单标的择时与多标的组合/定期再平衡/定投 DCA),默认收盘信号于次日开盘成交,execution 返回模型与限制 | | `detect_market_regime` | A/HK/US/JP/KR/TW 市场状态检测(返回实际 as_of 和警告;板块热点仅 A 股) | | `get_market_review` | 市场日度复盘数据 | | `get_review_history` | 复盘归档历史(最近 N 条,最新在前,用于纵向对比) | @@ -461,7 +462,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 # 四个宿主的 75 个工具和参数映射一致 +npx tsx tests/test_adapter_parity.ts # 四个宿主的 76 个工具和参数映射一致 npm run build:openclaw && npm run build:dsh # 构建 OpenClaw / dsh bundle ``` @@ -473,12 +474,12 @@ npm run build:openclaw && npm run build:dsh # 构建 OpenClaw / dsh bundle ``` stock-analysis/ ├── pi/ # Pi Agent Extension -│ └── index.ts # 注册 75 个工具 + 21 个 skill +│ └── index.ts # 注册 76 个工具 + 21 个 skill ├── hermes/ # Hermes Agent Plugin │ ├── plugin.yaml # 插件清单 │ ├── __init__.py # register(ctx) 入口 │ ├── schemas.py # 读取 tools/tool_schemas.json -│ └── tools.py # 75 个 handler → subprocess 调 CLI +│ └── tools.py # 76 个 handler → subprocess 调 CLI ├── openclaw/ # OpenClaw Plugin │ ├── openclaw.plugin.json # manifest(contracts.tools) │ ├── package.json # 含 openclaw 块(pluginApi/SDK 版本) @@ -493,7 +494,7 @@ stock-analysis/ │ ├── mcp_host/ # MCP stdio 服务器(复用 Hermes schema/handler) ├── tools/ # 共享 Python CLI 工具 -│ ├── tool_schemas.json # 75 个工具的名称/描述/参数(各宿主共用) +│ ├── tool_schemas.json # 76 个工具的名称/描述/参数(各宿主共用) │ ├── stock_data.py # 行情 / 资金流 / 新闻 / 财务 / 短线情绪 │ ├── signal_tracker.py # AI 买卖建议回测闭环(本地 JSONL 存储) │ ├── technical.py # 技术指标分析 diff --git a/docs/backtest-dsl.md b/docs/backtest-dsl.md index 37a6eca..b7d263f 100644 --- a/docs/backtest-dsl.md +++ b/docs/backtest-dsl.md @@ -4,7 +4,9 @@ ## 风控、基准与成交 -- `exit.trailing_stop`:移动止损,价格自持仓期间最高收盘价回撤达到该比例即卖出(如 `0.08` = 峰值回撤 8% 触发);与 `stop_loss` 同时设置时先判固定止损。`stop_loss` 必须为负数、`take_profit` 必须为正数、`trailing_stop` 须在 (0, 1) 内;`position.max_positions` 当前仅支持 1,其他配置明确报错。 +- `exit.trailing_stop`:移动止损,价格自持仓期间最高收盘价回撤达到该比例即卖出(如 `0.08` = 峰值回撤 8% 触发);与 `stop_loss` 同时设置时先判固定止损。`stop_loss` 必须为负数、`take_profit` 必须为正数、`trailing_stop` 须在 (0, 1) 内;单标的信号引擎要求 `position.max_positions: 1`,多标的组合(逗号分隔同市场代码,如 `510300,510500,518880`)支持多仓位、定期再平衡与定投。 +- `portfolio`(顶层,可选):多标的同市场组合配置。`rebalance` 支持 `none`/`weekly`/`monthly`/`quarterly`(仅适用于目标权重组合模式,不可与 `entry.conditions` 信号入场混用);`weighting` 支持 `equal`(默认)或 `custom`(配合 `weights: {symbol: weight}`);`drift_threshold` 为 (0, 1) 偏离阈值;`max_positions` 控制多标的信号模式同时持仓上限。重复标的别名(如 `600519` 与 `sh600519`)以及混合不同市场/报价币种代码(含港股双柜台不同币种代码)会明确报错。 +- `dca`(顶层,可选):定期定投配置,单标的或多标的均可使用。`frequency` 支持 `weekly`/`biweekly`/`monthly`/`quarterly`,`amount` 为每期新增投入金额(正有限数)。启用后结果返回 `total_contributed`、`contributions`、`final_holdings` 及时间加权收益率 `metrics.time_weighted_return`,且 `max_drawdown`、`sharpe_ratio`、`annual_return` 均基于剔除外部现金流影响的时间加权净值序列计算,避免定投现金流入扭曲策略表现。示例见 `strategies/examples/portfolio_rebalance.yaml` 与 `strategies/examples/dca_monthly.yaml`。 - `benchmark`(顶层):基准对比标的代码(如 `"sh000300"` 沪深300;指数代码必须带 sh/sz 交易所前缀,裸 6 位数字会被当作个股),设置后回测结果附带 `benchmark` 块(基准买入持有收益与 `excess_return` 超额收益)。基准与策略采用同一首日执行口径(next_open 用 open、same_close 用 close),无预热时以策略首条权益日期为起点;实际覆盖不符或首末价格非法时返回 error,不输出超额。 - `simulation.execution`:默认 `next_open`,前日收盘信号、次日开盘加滑点成交;显式 `same_close` 复现旧收盘成交假设。交易同时返回 signal_date/date。延迟的入场信号在新收盘失效时撤单,风险退出 pending 保留至成交。`start` 前可得历史仅用于指标预热,取数长度随策略最大 lookback 增加,交易与权益仍按请求区间统计;`warnings` 出现 `Entry indicator is unavailable` 时必须披露指标不可用及数据质量,不能声称完成预热。零成交量阻止成交;一字板限制只在输入提供同口径历史 limit_up/limit_down 时执行。`execution` 列出阻止成交次数、未成交订单及限制;止损是收盘信号,未模拟盘口排队、部分成交、结算和市场冲击。回测仅接受单一 `qfq`/`total_return`/`none` 复权口径,unknown 或混合口径明确报错。 - `simulation`(顶层):交易成本。`slippage`(滑点,买卖双边,默认 0.001)、`commission`(佣金,买卖双边,默认 0.0015)、`stamp_tax`(印花税,仅卖出收取,默认 0;A股为 0.0005,各市场税率不同且会调整,按当下实际费率填写)。费率均须在 [0, 1) 区间,越界报错。回测结果附带 `costs` 块(实际生效费率与实付费用合计 `commission_paid`/`stamp_tax_paid`)。 diff --git a/docs/data-sources.md b/docs/data-sources.md index af9ea7e..351b0c7 100644 --- a/docs/data-sources.md +++ b/docs/data-sources.md @@ -41,13 +41,13 @@ CDS 指数(`get_cds_index`)只提供市场级信用风险偏好,不是个 SEC 配置 `SEC_USER_AGENT`,包含应用名称与真实联系邮箱,仅通过环境变量提供。单进程最多每秒 2 次请求(多个并行进程需控制账户/IP 总量不超过 SEC 的每秒 10 次),并缓存 ticker/CIK、申报元数据和 XML 解析结果。13F 返回机构最近季度的原始申报,不是实时完整组合;通常在季度后 45 天内披露(节假日顺延),实际数据年龄以季度末为准,2023-01-03 起金额单位为美元,更早申报为千美元。修订文件另列原文链接,避免错误合并补充与重述;发行人 CIK 反查现已通过 `mode=issuer` 支持:从结构化 Schedule 13D/G 校验发行人 CIK、提取 CUSIP,再扫描官方最新已发布 13F 批量窗口。`auto` 默认有当前或已检索历史 13F 时查机构,否则查发行人;Berkshire 等兼具两种身份时显式选择 `issuer`。修订按 `RESTATEMENT` 替换与 `NEW HOLDINGS` 补充重建;无法判断的修订或缺少基础版时总量为 null,并给出 `unresolved_manager_count`。 -Form 4 的 `days` 是申报日期窗口,`top=1..20` 限制文件数,返回全部已解析交易。保留多人联报、衍生品、交易代码、脚注、直接/间接持有和修订信息;仅 P/S 标为买/卖,其余行为不推断方向,价格未披露为 null。读取 `truncated/warnings`,原件与修订不要重复计数。风险组合工具 `screen_risk` 仍为 A 股专用。 +Form 4 的 `days` 是申报日期窗口,`top=1..20` 限制文件数,返回全部已解析交易。保留多人联报、衍生品、交易代码、脚注、直接/间接持有和修订信息;仅 P/S 标为买/卖,其余行为不推断方向,价格未披露为 null。读取 `truncated/warnings`,原件与修订不要重复计数。风险组合工具 `screen_risk` 现已覆盖 A 股、港股和美股(A 股查限售解禁与中文风险线索,港股查 HKEXnews 风险公告与双语线索,美股查英文风险线索及已配置 `SEC_USER_AGENT` 时的 Form 4 内部人卖出)。 A/港/美股 DCF 输入(`get_financials include_dcf_inputs=true`):美股以 SEC companyfacts 为主源,A 股和港股配置 `LIXINGER_TOKEN` 时以理杏仁年报为主源(理杏仁港股无营业利润、资本开支、折旧摊销字段;A 股 `total_debt` 含“一年内到期的非流动负债”,其中可能有一年内到期的租赁负债),未配置时用 Yahoo(A 股为 `.SS/.SZ`,北交所无 Yahoo 财报),主源缺失字段仅在同一财年末(±10 天)且币种一致时用 Yahoo 补齐,`field_sources` 标明每个字段来源,`missing_fields` 列出仍缺字段。`total_debt` 三个来源都不含租赁(Yahoo 用 Current Debt + Long Term Debt,不用含租赁的 Total Debt),租赁负债在 `lease_liabilities` 单列。 美股估值历史(`get_valuation_history`)由 SEC companyfacts 派生:TTM `NetIncomeLoss`(10-Q 单季加由 10-K 推出的第四季)、`StockholdersEquity` 和封面股本,均按 SEC 申报日起生效,取每个期间最早申报值,避免用后来的重述回填;Yahoo 周收盘按拆股调整后的价格乘以同口径股本得到市值。多类股公司按所有类别股本合计、单一类别价格计算;无封面股本时退回加权稀释股本(`share_basis`)。 -港美股市场宽度(`get_market_stats market=HK|US`)用东方财富涨跌排行二分计数涨跌家数,总成交额与涨跌停字段为 null。港股在东财失败时改用 TradingView 排行,按有涨跌幅报价的股票计数,来源为 `tradingview_rank`。美股行业表现(`get_sector_rankings market=US`)用 11 只 SPDR Select Sector ETF 最近两个收盘作为代理,标注 `proxy`。港股行业排行暂无可靠的公开行业指数源。 +港美股市场宽度(`get_market_stats market=HK|US`)用东方财富涨跌排行二分计数涨跌家数,总成交额与涨跌停字段为 null。港股在东财失败时改用 TradingView 排行,按有涨跌幅报价的股票计数,来源为 `tradingview_rank`。美股行业表现(`get_sector_rankings market=US`)用 11 只 SPDR Select Sector ETF 最近两个收盘作为代理,标注 `proxy`。港股行业表现(`get_sector_rankings market=HK`)优先按 TradingView 港股前 500 市值股票聚合行业涨跌幅(市值加权),失败时回退至港股行业/主题 ETF 代理(`proxy="HK Sector ETF"`)。宏观与利率/汇率基准(`get_macro_anchors`)聚合中美 10Y/美债 2Y 收益率(yfinance / FRED CSV / akshare 债券表容灾)、DXY/USD-CNH/USD-HKD/推导 HKD-CNY 与 VIX/黄金/原油,缓存 1 小时。 接口依据:[巨潮公告查询](https://www.cninfo.com.cn/new/commonUrl/pageOfSearch?url=disclosure/list/search)、[理杏仁港股财报](https://www.lixinger.com/api/open-api/html-doc/hk/company/fs/non_financial)、[理杏仁港股估值](https://www.lixinger.com/api/open-api/html-doc/hk/company/fundamental/non_financial)、[SEC API](https://www.sec.gov/search-filings/edgar-application-programming-interfaces)。 diff --git a/docs/hermes-integration.en.md b/docs/hermes-integration.en.md index b696cc9..c530ab0 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 75 tools) -│ ├── tools.py # 75 handlers that run the CLIs as subprocesses +│ ├── schemas.py # loads tools/tool_schemas.json (JSON Schemas for 76 tools) +│ ├── tools.py # 76 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 8b6a917..ab053fa 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(75 个工具的 JSON Schema) -│ ├── tools.py # 75 个 handler,以子进程调用 CLI +│ ├── schemas.py # 读取 tools/tool_schemas.json(76 个工具的 JSON Schema) +│ ├── tools.py # 76 个 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 94f81fe..beaae8f 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`),所以 75 个工具的名称、参数和输出与其他宿主一致。 +`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。 ## 前置条件 @@ -36,16 +36,22 @@ | Claude Desktop | `claude_desktop_config.json`(设置 → Developer → Edit Config) | | Cursor | `~/.cursor/mcp.json`(全局)或 `<项目目录>/.cursor/mcp.json` | -保存后,客户端里出现 75 个工具(如 `get_quote`、`get_technical_analysis`)即接入成功。 +保存后,客户端里出现 76 个工具(如 `get_quote`、`get_technical_analysis`、`get_macro_anchors`)即接入成功。 + +### 按需发现与精简模式(降低上下文占用) + +- **按需发现模式**:在 `args` 追加 `"--discovery"`(或设置 `STOCK_MCP_DISCOVERY=1`),初始只暴露 `stock_tool_search`,按中英文关键词搜索命中后返回完整 schema 并在支持动态刷新的客户端中触发 `notifications/tools/list_changed`。 +- **核心子集模式**:在 `args` 追加 `"--profile", "core"`(或设置 `STOCK_MCP_PROFILE=core`),静态暴露 19 个高频核心工具(含 `render_stock_report`)。 +- **边界说明**:`--discovery` 与 `--profile core` 仅用于收敛 `tools/list` 的上下文体积,不作为安全授权边界;工具调用权限仍由宿主客户端控制。 ## 行为说明 -- **协议**:支持 `initialize`、`ping`、`tools/list`、`tools/call`,以及 `notifications/initialized` 和 `notifications/cancelled`。协商版本为 `2025-11-25`、`2025-06-18`、`2025-03-26`、`2024-11-05`;客户端请求其他版本时,回复 `2025-11-25`。 +- **协议**:支持 `initialize`、`ping`、`tools/list`、`tools/call`、`prompts/list`、`prompts/get`、`resources/list`、`resources/read`,以及 `notifications/initialized` 和 `notifications/cancelled`。协商版本为 `2025-11-25`、`2025-06-18`、`2025-03-26`、`2024-11-05`;客户端请求其他版本时,回复 `2025-11-25`。 - **stdout 只有 JSON-RPC**:日志和误打印都会转到 stderr。 - **错误**:未知工具、参数不是对象、未知方法、无法解析的 JSON 作为 JSON-RPC 错误返回(`-32602` / `-32601` / `-32700` / `-32600`)。缺少必填参数、数据源失败、Python CLI 超时则作为工具结果返回:`isError: true`,正文为 `{"error": "..."}`。 - **并发与取消**:每次 `tools/call` 在独立线程里运行。收到 `notifications/cancelled` 后,服务器会结束对应的 Python 子进程,并且不再回复该请求。客户端关闭 stdin 时,服务器结束所有进行中的调用后退出。 - **超时**:沿用 `tools/cli_budgets.json` 的命令预算,与其他宿主一致。 -- **Skills**:MCP 只提供工具。`skills/*/SKILL.md` 里的 21 个工作流需要客户端自己的 Skills 功能单独导入。 +- **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。 ## 本地验证 diff --git a/docs/openclaw-integration.md b/docs/openclaw-integration.md index 36de4c1..6eadf44 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 ``` -应该看到 75 个 tool 全部出现在 `tools` 列表里。也可以直接在 OpenClaw 对话中调用: +应该看到 76 个 tool 全部出现在 `tools` 列表里。也可以直接在 OpenClaw 对话中调用: ``` 帮我查一下贵州茅台的实时行情 diff --git a/docs/pi-integration.en.md b/docs/pi-integration.en.md index 0de333c..5b33520 100644 --- a/docs/pi-integration.en.md +++ b/docs/pi-integration.en.md @@ -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 75 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 76 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: 75 tools and 21 Skills +├── pi/index.ts # Pi extension entry: 76 tools and 21 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 1ba9e90..02fe8bf 100644 --- a/docs/pi-integration.md +++ b/docs/pi-integration.md @@ -53,7 +53,7 @@ Agent 应调用 `get_quote` 并返回行情。 ## 按需工具发现 -最新稳定版 Pi 1.5.2 支持原生按需工具发现。插件在 `session_start` 检查 `tool_search` 的 exposure 元数据及活动工具 API:具备这些能力时,将股票工具设为 `deferred` 并启用原生搜索,保留其他插件的活动工具;旧宿主保持原来的 75 工具全量暴露,无需升级才能继续使用。 +最新稳定版 Pi 1.5.2 支持原生按需工具发现。插件在 `session_start` 检查 `tool_search` 的 exposure 元数据及活动工具 API:具备这些能力时,将股票工具设为 `deferred` 并启用原生搜索,保留其他插件的活动工具;旧宿主保持原来的 76 工具全量暴露,无需升级才能继续使用。 新版中搜索已注册但未激活时,插件会尝试启用并确认成功后再隐藏股票工具;未加载搜索扩展、被宿主限制或无法启用时保持全量暴露。会话中途关闭搜索时,下次模型请求前恢复全部股票工具,并停止发送搜索指引。 @@ -125,7 +125,7 @@ git pull && npm install ``` stock-analysis-plugin/ -├── pi/index.ts # Pi Extension 入口,注册 75 个工具和 21 个 Skill +├── pi/index.ts # Pi Extension 入口,注册 76 个工具和 21 个 Skill ├── tools/ # 共享 Python CLI ├── skills/ # SKILL.md ├── schemas/ templates/ strategies/ diff --git a/docs/tool-behavior.md b/docs/tool-behavior.md index 7d38330..2741425 100644 --- a/docs/tool-behavior.md +++ b/docs/tool-behavior.md @@ -59,7 +59,7 @@ python tools/stateless_analysis.py position_size --input input.json 信号建议可沿用 source 标识策略版本,按来源复盘胜率、平均收益和样本量;未扣成本、未匹配基准的观察记录不能当作策略回测。 -信号结算仅在价格口径可核实时进行:原始价格可直接比较;自动记录的默认 `record_date` 与 `price_date` 均按标的市场时区确定(显式 `date` 不变),并保存原始 `price_as_of`;`price_date` 晚于 `record_date` 时拒绝记录与结算;多头 target 必须高于 entry、stop 必须低于 entry,空头相反,否则拒绝记录。开盘先触 stop 按 open 结算,先触 target 按 target 保守结算,日内顺序未知的双触发仍 stop 优先;无止损的旧 HLC 记录可继续用 high/low/close 判定目标和到期,但若提供 open 也必须是正有限数值,有止损但缺 open 则拒绝结算。重复日期返回 skipped_no_data,复权乘除使用 Decimal。复权日线需该报价日的 adjustment_factor(复权价/原始价),当前日线 Tushare、Alpha Vantage 可提供。缺失系数或口径未知时返回 skipped_price_basis,保持未结算,不猜测除权比例;记录日无 K 线时仅在前后因子一致(或已有明确报价日)时使用最近锚点,旧信号缺少报价时点且记录日因子变化时也保持未结算。换算后的 exit_price 是记录时价格单位的等价值,实际市场价可不同,evaluation_price_basis 保留依据。evaluate_signals 的 CLI 预算为 300 秒,内部提前结束采集并保存已完成结果,complete/deferred/warnings 指示需要重试的记录;预算耗尽后调整未结算记录的处理顺序,下轮优先处理尚未尝试的记录,避免慢请求长期阻塞后续信号。 +信号结算仅在价格口径可核实时进行:原始价格可直接比较;自动记录的默认 `record_date` 与 `price_date` 均按标的市场时区确定(显式 `date` 不变),并保存原始 `price_as_of`;`price_date` 晚于 `record_date` 时拒绝记录与结算;多头 target 必须高于 entry、stop 必须低于 entry,空头相反,否则拒绝记录。开盘先触 stop 按 open 结算,先触 target 按 target 保守结算,日内顺序未知的双触发仍 stop 优先;无止损的旧 HLC 记录可继续用 high/low/close 判定目标和到期,但若提供 open 也必须是正有限数值,有止损但缺 open 则拒绝结算。重复日期返回 skipped_no_data,复权乘除使用 Decimal。复权日线需该报价日的 adjustment_factor(复权价/原始价),当前日线 Tushare、Alpha Vantage 可提供。无 `adjustment_factor` 时,仅当全部 K 线同属 `qfq`/`total_return`、记录价严格落在锚点 K 线 `[low, high]` 区间内、且 `get_dividends` 绕过 24 小时缓存实时核验(`--no-cache`,`cache_bypassed=true`、`corporate_actions_complete=true`、`splits_checked=true`、`capital_gains_checked=true` 且行情源真实覆盖区间 `history_covered_from..history_current_through` 完整覆盖锚点日至评估末日)、无历史缺失/截断告警,且确认区间内无已实施或已公告的分红/拆合股/资本利得分配事件时,允许按 `factor=1.0` 结算并在 `evaluation_price_basis` 标注 `verification=no_corporate_action_verified`;A 股东方财富分红明细(`RPT_SHAREBONUS_DET`)不覆盖配股且不提供行情覆盖截止日,缺 `adjustment_factor` 时保持未验证;发生除权除息/拆股/资本利得分配、历史缺失告警、区间未完整覆盖、查询失败或口径未知时仍返回 `skipped_price_basis`,保持未结算,不猜测除权比例;记录日无 K 线时仅在前后因子一致(或已有明确报价日)时使用最近锚点,旧信号缺少报价时点且记录日因子变化时也保持未结算。换算后的 exit_price 是记录时价格单位的等价值,实际市场价可不同,evaluation_price_basis 保留依据。evaluate_signals 的 CLI 预算为 300 秒,内部提前结束采集并保存已完成结果,complete/deferred/warnings 指示需要重试的记录;预算耗尽后调整未结算记录的处理顺序,下轮优先处理尚未尝试的记录,避免慢请求长期阻塞后续信号。 市场复盘数据不足时温度/姿态为 null,信号 unknown,data_quality.limitations 说明限制。自选股异动采集失败时 anomaly_status=unavailable、anomaly_count=null,保留警告并计入 summary.partial,不能当成无异常。 diff --git a/dsh/README.md b/dsh/README.md index 528666b..41a161a 100644 --- a/dsh/README.md +++ b/dsh/README.md @@ -1,6 +1,6 @@ # Stock Analysis — DeepSeek Harness (dsh) Plugin -A 股 / 港股 / 美股 / 日股 / 韩股 / 台股的行情、技术分析、选股与回测。作为 dsh bundle 安装到 profile 后,对话中可调用 75 个工具,并自动注册 21 个工作流和策略方法论 Skill;dsh Web / Desktop 侧栏还会多出一个「股票仪表盘」。 +A 股 / 港股 / 美股 / 日股 / 韩股 / 台股的行情、技术分析、选股与回测。作为 dsh bundle 安装到 profile 后,对话中可调用 76 个工具,并自动注册 21 个工作流和策略方法论 Skill;dsh Web / Desktop 侧栏还会多出一个「股票仪表盘」。 ![dsh 股票仪表盘:六市场自选股行情、指数带、A 股涨跌分布与行业涨跌榜(深色主题)](https://raw.githubusercontent.com/Weaxs/stock-analysis-plugin/main/docs/images/dsh-dashboard-dark.png) @@ -39,7 +39,7 @@ allowBuilds: 支持 dsh 前端的宿主会在侧栏显示「股票仪表盘」。首屏是自选股行情表:最新价、涨跌幅、涨跌额、今日区间(振幅与昨收位置)、成交额和 30 日走势(悬停可看每日收盘与较首日涨跌),可按列排序、按市场筛选;上方是六市场指数带和 A 股涨跌分布,下方可切换 A / HK / US / JP / KR / TW 查看各市场指数与交易阶段,A 股另有涨跌统计和行业领涨/领跌榜。其他市场没有用少数指数推算全市场宽度。 -自选股按代码添加,支持逗号批量导入和删除,最多 30 只,覆盖六个市场。列表保存在 `$STOCK_WATCHLIST_FILE`,未配置时保存到 `$DSH_HOME/stock-analysis/watchlist.json`(`DSH_HOME` 默认为 `~/.dsh`)。文件损坏时拒绝静默覆盖。 +自选股支持按中文名/拼音模糊搜索(`/api/search`)或按代码逗号批量导入和删除,最多 30 只,覆盖六个市场;行内支持一键复制 Agent 分析提示词、自定义分组标签筛选与本地价格阈值高亮提醒(保存在浏览器本地偏好)。列表保存在 `$STOCK_WATCHLIST_FILE`,未配置时保存到 `$DSH_HOME/stock-analysis/watchlist.json`(`DSH_HOME` 默认为 `~/.dsh`)。文件损坏时拒绝静默覆盖。 场外公募基金可用六位基金代码添加。交易所行情源均返回无报价时,自选会查询基金已披露的单位净值、净值日期和净值走势。添加股票或指数时可用交易所前缀指定市场。自选会合并裸码与其默认交易所前缀写法,更换写法时先删除原条目。`TIAA` 投顾组合显示组合名称和可获取的投顾机构信息,价格一栏标注「无统一净值」。 @@ -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/`;它不增加或改变四宿主共享的 75 个模型工具。源码或 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/`;它不增加或改变四宿主共享的 76 个模型工具。源码或 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 不提供该接口,插件会自动关闭按需发现并全量暴露工具,功能不受影响。按需发现只控制工具加载,不改变 75 个分析工具的名称、参数和输出。原生函数调用模式下,首次请求只暴露这个发现入口;其他插件的工具照常保留。搜索支持中文描述、英文关键词或确切工具名,例如 `财务`、`get_quote`、`run_backtest`;命中工具在下一次模型请求提供完整 schema,再按原名调用。默认最多加载 5 项,`limit` 可设 1 到 20;无匹配返回空列表。 +dsh 0.2.2 及以上(工具注册支持按步骤的 `when` 条件)默认增加一个宿主控制入口 `stock_tool_search`;更早的 0.2.1 不提供该接口,插件会自动关闭按需发现并全量暴露工具,功能不受影响。按需发现只控制工具加载,不改变 76 个分析工具的名称、参数和输出。原生函数调用模式下,首次请求只暴露这个发现入口;其他插件的工具照常保留。搜索支持中文描述、英文关键词或确切工具名,例如 `财务`、`get_quote`、`run_backtest`;命中工具在下一次模型请求提供完整 schema,再按原名调用。默认最多加载 5 项,`limit` 可设 1 到 20;无匹配返回空列表。 加载集合按 Agent 隔离,搜索和回退均保留宿主已有的工具权限限制。搜索入口被禁止或移除时,下一次请求保留原先已授权的完整股票工具目录。旧版缺少相关接口时保持全量暴露;PTC / both 模式沿用宿主生成的 SDK,不做发现过滤。加载集合在本次运行中保留,恢复会话或重载插件后需重新搜索。 @@ -71,7 +71,7 @@ dsh 0.2.2 及以上(工具注册支持按步骤的 `when` 条件)默认增 ## 工具与 Skills -75 个工具覆盖行情与基金净值、技术分析与 K 线形态、资金流与板块、估值/股东/ETF/股息、公告与 SEC、多因子选股、策略回测、市场复盘、新闻舆情、持仓风险与调仓计算。完整列表见[主仓库 README · 工具列表](https://github.com/Weaxs/stock-analysis-plugin#工具列表),Skills 见 [Skills 一览](https://github.com/Weaxs/stock-analysis-plugin#skills-一览)。 +76 个工具覆盖行情与基金净值、宏观利率与汇率基准、技术分析与 K 线形态、资金流与板块、估值/股东/ETF/股息、公告与 SEC、多因子选股、策略回测、市场复盘、新闻舆情、持仓风险与调仓计算。完整列表见[主仓库 README · 工具列表](https://github.com/Weaxs/stock-analysis-plugin#工具列表),Skills 见 [Skills 一览](https://github.com/Weaxs/stock-analysis-plugin#skills-一览)。 ## 其他宿主 diff --git a/dsh/dashboard.ts b/dsh/dashboard.ts index b847ab9..b935889 100644 --- a/dsh/dashboard.ts +++ b/dsh/dashboard.ts @@ -626,6 +626,27 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand } return sendJson(res, 405, { error: "Method not allowed" }); } + if (rest === "/api/search") { + if (req.method !== "GET") return sendJson(res, 405, { error: "Method not allowed" }); + const q = (url.searchParams.get("q") ?? "").trim(); + if (!q) return sendJson(res, 200, { query: "", results: [] }); + if (q.length > 64) throw new HttpError(400, "搜索关键词过长"); + const raw = await limiter.run(0, () => runPy("name_resolver.py", ["resolve", q, "--top", "8"], 15_000, abort.signal)); + const parsed = parseJson(raw); + if (!Array.isArray(parsed)) { + const err = (parsed as { error?: unknown } | null)?.error; + throw new HttpError(502, typeof err === "string" ? err : "搜索服务暂时不可用"); + } + const results = parsed + .filter((item): item is { code: string; name?: string; score?: number } => typeof item?.code === "string" && item.code.length > 0) + .map(item => ({ + symbol: item.code, + name: typeof item.name === "string" ? item.name : item.code, + region: symbolRegion(item.code), + score: typeof item.score === "number" ? item.score : null, + })); + return sendJson(res, 200, { query: q, results }); + } if (rest.startsWith("/api/")) return sendJson(res, 404, { error: "Not found" }); if (req.method !== "GET" && req.method !== "HEAD") return sendJson(res, 404, { error: "Not found" }); diff --git a/dsh/research-role.ts b/dsh/research-role.ts index 18799a0..765886f 100644 --- a/dsh/research-role.ts +++ b/dsh/research-role.ts @@ -7,10 +7,10 @@ export const inject = ["tools"]; const common = ["get_market_capabilities", "resolve_stock_name", "get_stock_info", "check_trading_day", "get_trading_phase"]; const roles = { fundamentals: [...common, "get_quote", "get_financials", "get_fundamental_context", "get_valuation_history", - "get_index_valuation", "get_shareholder_structure", "get_us_holdings", "get_insider_trades", "get_dividends", "compare_stocks"], + "get_index_valuation", "get_macro_anchors", "get_shareholder_structure", "get_us_holdings", "get_insider_trades", "get_dividends", "compare_stocks"], technical: [...common, "get_quote", "get_kline", "get_technical_analysis", "analyze_pattern", "get_volume_analysis", "detect_market_regime", "run_backtest", "validate_backtest", "analyze_trend_strategy", "backtest_rotation_allocation"], - events: [...common, "get_news", "get_announcements", "get_earnings_calendar", "get_dividends", "search_stock_news", + events: [...common, "get_news", "get_announcements", "get_earnings_calendar", "get_dividends", "get_macro_anchors", "search_stock_news", "search_comprehensive_intel", "extract_article", "analyze_disclosure_changes", "analyze_event_study"], }; diff --git a/dsh/web/app.ts b/dsh/web/app.ts index b8ff426..7ac27c3 100644 --- a/dsh/web/app.ts +++ b/dsh/web/app.ts @@ -113,20 +113,39 @@ const INDEX_NAMES: Record = { }; const SVG_NS = "http://www.w3.org/2000/svg"; const SORT_KEYS = new Set(["order", "price", "change_pct", "change", "turnover", "trend"]); +const EXACT_CODE_RE = /^(?:(?:sh|sz|bj)?\d{6}|\d{4,5}\.HK|\d{4}\.(?:T|TW|TWO)|\d{6}\.(?:KS|KQ)|TIAA\d{6})$/i; + +interface SearchHit { + symbol: string; + name: string; + region: WatchRegion; + score?: number | null; +} + +interface PriceAlert { + above?: number; + below?: number; +} const isRegion = (value: unknown): value is Region => typeof value === "string" && value in REGION_NAMES; const isWatchRegion = (value: unknown): value is WatchRegion => value === "fund" || value === "advisor" || isRegion(value); +const isGroupFilter = (value: unknown): value is string => typeof value === "string" && value.startsWith("group:") && value.length > 6; const state = { snap: null as Snapshot | null, region: "cn" as Region, sort: { key: "order" as SortKey, dir: -1 }, - filter: "all" as WatchRegion | "all", + filter: "all" as WatchRegion | "all" | string, + groups: {} as Record, + alerts: {} as Record, prices: new Map(), marketCache: new Map(), sectionSigs: { ribbon: "", pulse: "", filters: "", rows: "", market: "" }, pollTimer: undefined as ReturnType | undefined, undoTimer: undefined as ReturnType | undefined, + toastTimer: undefined as ReturnType | undefined, + searchTimer: undefined as ReturnType | undefined, + searchSeq: 0, inflight: false, // A poll requested while one is in flight (e.g. right after a watchlist edit) runs once that one ends. dirty: false, @@ -368,7 +387,13 @@ function writeJson(key: string, value: unknown) { } function savePrefs() { - writeJson(PREF_KEY, { region: state.region, sort: state.sort, filter: state.filter }); + writeJson(PREF_KEY, { + region: state.region, + sort: state.sort, + filter: state.filter, + groups: state.groups, + alerts: state.alerts, + }); } // ---------- API ---------- @@ -564,29 +589,52 @@ function renderPulse() { } } +function alertHit(symbol: string, price: number | null): string | null { + if (price === null) return null; + const rule = state.alerts[symbol]; + if (!rule) return null; + if (typeof rule.above === "number" && Number.isFinite(rule.above) && price >= rule.above) return `触达 ≥ ${rule.above}`; + if (typeof rule.below === "number" && Number.isFinite(rule.below) && price <= rule.below) return `触达 ≤ ${rule.below}`; + return null; +} + function renderFilters() { const node = $("filters"); const items = state.snap?.watchlist || []; const counts = new Map(); - for (const item of items) counts.set(item.region, (counts.get(item.region) || 0) + 1); - if (counts.size < 2) { + const groupCounts = new Map(); + for (const item of items) { + counts.set(item.region, (counts.get(item.region) || 0) + 1); + const grp = state.groups[item.symbol]; + if (grp) groupCounts.set(grp, (groupCounts.get(grp) || 0) + 1); + } + if (counts.size < 2 && groupCounts.size === 0) { node.hidden = true; state.filter = "all"; state.sectionSigs.filters = "hidden"; return; } - if (state.filter !== "all" && !counts.has(state.filter)) state.filter = "all"; - const sig = `${state.filter}:${items.length}:${[...counts.entries()].map(([k, v]) => `${k}=${v}`).join(",")}`; + if (state.filter !== "all") { + if (isGroupFilter(state.filter)) { + if (!groupCounts.has(state.filter.slice(6))) state.filter = "all"; + } else if (!isWatchRegion(state.filter) || !counts.has(state.filter)) { + state.filter = "all"; + } + } + const sig = `${state.filter}:${items.length}:${[...counts.entries()].map(([k, v]) => `${k}=${v}`).join(",")}:${[...groupCounts.entries()].map(([k, v]) => `${k}=${v}`).join(",")}`; if (sig === state.sectionSigs.filters) return; state.sectionSigs.filters = sig; node.hidden = false; node.replaceChildren(); - const chips: Array<[WatchRegion | "all", string, number]> = [ + const chips: Array<[string, string, number]> = [ ["all", "全部", items.length], ]; for (const [region, label] of Object.entries(WATCH_REGION_NAMES)) { if (isWatchRegion(region) && counts.has(region)) chips.push([region, label, counts.get(region)!]); } + for (const [grp, count] of groupCounts.entries()) { + chips.push([`group:${grp}`, `#${grp}`, count]); + } for (const [key, label, count] of chips) { const chip = el("button", "chip", `${label} ${count}`); chip.type = "button"; @@ -607,7 +655,11 @@ function sortValue(item: WatchItem, key: Exclude): number | nu } function visibleItems(): WatchItem[] { - const items = (state.snap?.watchlist || []).filter(item => state.filter === "all" || item.region === state.filter); + const items = (state.snap?.watchlist || []).filter(item => { + if (state.filter === "all") return true; + if (isGroupFilter(state.filter)) return state.groups[item.symbol] === state.filter.slice(6); + return item.region === state.filter; + }); const { key, dir: direction } = state.sort; if (key === "order") return items; return items @@ -670,6 +722,8 @@ function renderRows(flash: Map) { empty: !state.snap?.watchlist.length, sort: state.sort, filter: state.filter, + groups: state.groups, + alerts: state.alerts, items, }); if (flash.size === 0 && sig === state.sectionSigs.rows) return; @@ -699,11 +753,16 @@ function renderRows(flash: Map) { const change = dir(quote?.change_pct); const row = el("tr"); row.dataset.symbol = item.symbol; + const hitAlert = alertHit(item.symbol, price); + if (hitAlert) row.classList.add("is-alert"); const nameCell = el("td", "c-name"); nameCell.append(el("span", "name", quote?.name || item.symbol)); const meta = el("div", "meta"); meta.append(el("span", "code", item.symbol), el("span", "tag", WATCH_REGION_NAMES[item.region])); + const grp = state.groups[item.symbol]; + if (grp) meta.append(el("span", "tag group-tag", `#${grp}`)); + if (hitAlert) meta.append(el("span", "tag alert-badge", hitAlert)); if (item.region === "fund" && quote?.nav_date) meta.append(el("span", "", `净值日 ${quote.nav_date}`)); if (item.region === "advisor" && quote?.advisor_org) meta.append(el("span", "", quote.advisor_org)); if (item.region !== "fund" && quote?.stale) meta.append(el("span", "stale", "报价可能不是最新")); @@ -735,6 +794,32 @@ function renderRows(flash: Map) { } else { trendCell.append(skeleton(108)); } + const actions = el("div", "row-actions"); + const analyze = el("button", "row-btn"); + analyze.type = "button"; + analyze.dataset.analyze = item.symbol; + analyze.dataset.label = quote?.name || item.symbol; + analyze.title = "复制 Agent 分析提示词"; + analyze.setAttribute("aria-label", `复制 ${quote?.name || item.symbol} 分析提示词`); + analyze.append(icon(["M4 15l4-4 3 3 5-7", "M13 7h3v3"], 13)); + + const hasAlert = Boolean(state.alerts[item.symbol]?.above || state.alerts[item.symbol]?.below); + const alertBtn = el("button", `row-btn${hasAlert ? " is-set" : ""}`); + alertBtn.type = "button"; + alertBtn.dataset.alert = item.symbol; + alertBtn.dataset.label = quote?.name || item.symbol; + alertBtn.title = hasAlert ? "修改或清除价格提醒" : "设置价格阈值提醒"; + alertBtn.setAttribute("aria-label", `设置 ${quote?.name || item.symbol} 价格提醒`); + alertBtn.append(icon(["M10 3a4.5 4.5 0 0 1 4.5 4.5V12l1.5 2H4l1.5-2V7.5A4.5 4.5 0 0 1 10 3z", "M8.5 16a1.5 1.5 0 0 0 3 0"], 13)); + + const groupBtn = el("button", `row-btn${grp ? " is-set" : ""}`); + groupBtn.type = "button"; + groupBtn.dataset.group = item.symbol; + groupBtn.dataset.label = quote?.name || item.symbol; + groupBtn.title = grp ? `分组:#${grp}(点击修改)` : "设置自选分组标签"; + groupBtn.setAttribute("aria-label", `设置 ${quote?.name || item.symbol} 分组`); + groupBtn.append(icon(["M4 6h12", "M4 10h8", "M4 14h6"], 13)); + const remove = el("button", "remove"); remove.type = "button"; remove.dataset.remove = item.symbol; @@ -742,6 +827,7 @@ function renderRows(flash: Map) { remove.setAttribute("aria-label", `从自选中删除 ${quote?.name || item.symbol}`); remove.title = "删除"; remove.append(icon(["M5.5 5.5l9 9", "M14.5 5.5l-9 9"])); + actions.append(analyze, alertBtn, groupBtn, remove); row.append( nameCell, @@ -751,7 +837,7 @@ function renderRows(flash: Map) { cell("c-range", loadingQuote ? skeleton(96) : rangeCell(quote, digits)), cell("c-num c-amount", loadingQuote ? skeleton(52) : el("span", "amount", fmtAmount(quote?.turnover))), cell("c-trend", trendCell), - cell("c-act", remove), + cell("c-act", actions), ); body.append(row); } @@ -1022,9 +1108,63 @@ function post(path: string, body?: unknown): Promise { // ---------- interactions ---------- +function hideSearchResults() { + state.searchSeq++; + clearTimeout(state.searchTimer); + const box = document.getElementById("search-results"); + if (box) { + box.hidden = true; + box.replaceChildren(); + } +} + +function showToast(text: string) { + clearTimeout(state.toastTimer); + const bar = $("watch-toast"); + bar.replaceChildren(el("span", "", text)); + bar.hidden = false; + state.toastTimer = setTimeout(() => { + bar.hidden = true; + }, 4500); +} + +async function runNameSearch(raw: string) { + const q = raw.trim(); + const box = document.getElementById("search-results"); + if (!box) return; + if (!q || /[\s,,、;;]/.test(q) || EXACT_CODE_RE.test(q)) { + hideSearchResults(); + return; + } + const seq = ++state.searchSeq; + try { + const res = await api<{ query: string; results: SearchHit[] }>(`./api/search?q=${encodeURIComponent(q)}`); + if (seq !== state.searchSeq) return; + if (!res.results.length) { + hideSearchResults(); + return; + } + box.replaceChildren(); + for (const hit of res.results) { + const btn = el("button", "search-item"); + btn.type = "button"; + btn.setAttribute("role", "option"); + btn.dataset.pick = hit.symbol; + const left = el("span", "sname", hit.name); + const right = el("span", "scode", `${hit.symbol} · ${WATCH_REGION_NAMES[hit.region] || hit.region}`); + btn.append(left, right); + box.append(btn); + } + box.hidden = false; + } catch { + if (seq === state.searchSeq) hideSearchResults(); + } +} + function setAddForm(open: boolean) { $("add-form").hidden = !open; $("add-toggle").setAttribute("aria-expanded", String(open)); + if (!open) hideSearchResults(); if (open) $("symbol-input").focus(); } @@ -1110,6 +1250,21 @@ $("add-form").addEventListener("submit", event => { const symbols = $("symbol-input").value.split(/[\s,,、;;]+/).map(value => value.trim()).filter(Boolean); if (symbols.length) void changeWatchlist("add", symbols); }); +$("symbol-input").addEventListener("input", () => { + hideSearchResults(); + const value = $("symbol-input").value; + const q = value.trim(); + if (!q || /[\s,,、;;]/.test(q) || EXACT_CODE_RE.test(q)) { + return; + } + state.searchTimer = setTimeout(() => { void runNameSearch(value); }, 250); +}); +document.getElementById("search-results")?.addEventListener("click", event => { + const btn = closest(event, "button[data-pick]"); + if (!btn?.dataset.pick) return; + hideSearchResults(); + void changeWatchlist("add", [btn.dataset.pick]); +}); $("symbol-input").addEventListener("keydown", event => { if (event.key === "Escape") setAddForm(false); }); @@ -1133,6 +1288,81 @@ $("refresh").addEventListener("click", async () => { } }); $("rows").addEventListener("click", event => { + const analyze = closest(event, "button[data-analyze]"); + if (analyze?.dataset.analyze) { + const sym = analyze.dataset.analyze; + const item = state.snap?.watchlist.find(w => w.symbol === sym); + const label = analyze.dataset.label || sym; + const px = item ? watchPrice(item) : null; + const pct = item?.quote?.change_pct; + const pricePart = px !== null ? `,当前参考价 ${px}${num(pct) !== null ? `(${fmtPct(pct)})` : ""}` : ""; + const prompt = `请用 stock-analysis 全面分析 ${label}(${sym})${pricePart}。`; + if (typeof navigator !== "undefined" && typeof navigator.clipboard?.writeText === "function") { + void navigator.clipboard.writeText(prompt).then( + () => showToast(`已复制 ${label} 分析提示词`), + () => showToast(`剪贴板不可用,请手动复制:${prompt}`), + ); + } else { + showToast(`剪贴板不可用,请手动复制:${prompt}`); + } + return; + } + const alertBtn = closest(event, "button[data-alert]"); + if (alertBtn?.dataset.alert && typeof window.prompt === "function") { + const sym = alertBtn.dataset.alert; + const cur = state.alerts[sym] || {}; + const curStr = [cur.above !== undefined ? `>=${cur.above}` : "", cur.below !== undefined ? `<=${cur.below}` : ""].filter(Boolean).join(", "); + const input = window.prompt(`设置 ${alertBtn.dataset.label || sym} 价格提醒(格式:>=1800 或 <=1500,可逗号同填,留空清除)`, curStr); + if (input !== null) { + const trimmed = input.trim(); + if (!trimmed) { + delete state.alerts[sym]; + savePrefs(); + renderRows(new Map()); + } else { + const next: PriceAlert = {}; + let invalid = false; + const parts = trimmed.split(/[,,;;]+/).map(s => s.trim()).filter(Boolean); + for (const part of parts) { + const up = /^>=?\s*(\d+(?:\.\d+)?)$/.exec(part); + const dn = /^<=?\s*(\d+(?:\.\d+)?)$/.exec(part); + if (up) { + const val = Number(up[1]); + if (!Number.isFinite(val) || val <= 0) invalid = true; + else next.above = val; + } else if (dn) { + const val = Number(dn[1]); + if (!Number.isFinite(val) || val <= 0) invalid = true; + else next.below = val; + } else { + invalid = true; + } + } + if (invalid || (next.above === undefined && next.below === undefined)) { + showToast("提醒格式无效,示例:>= 1800, <= 1500(已保留原设置)"); + } else { + state.alerts[sym] = next; + savePrefs(); + renderRows(new Map()); + } + } + } + return; + } + const groupBtn = closest(event, "button[data-group]"); + if (groupBtn?.dataset.group && typeof window.prompt === "function") { + const sym = groupBtn.dataset.group; + const input = window.prompt(`设置 ${groupBtn.dataset.label || sym} 自选分组(如 持仓 / 观察 / 核心,留空清除)`, state.groups[sym] || ""); + if (input !== null) { + const trimmed = input.trim().slice(0, 16); + if (trimmed) state.groups[sym] = trimmed; + else delete state.groups[sym]; + savePrefs(); + renderFilters(); + renderRows(new Map()); + } + return; + } const remove = closest(event, "button[data-remove]"); if (remove?.dataset.remove) { void changeWatchlist("remove", [remove.dataset.remove], remove.dataset.label); @@ -1149,7 +1379,7 @@ $("watch-undo").addEventListener("click", event => { $("filters").addEventListener("click", event => { const chip = closest(event, "button[data-filter]"); const filter = chip?.dataset.filter; - if (!filter || (filter !== "all" && !isWatchRegion(filter))) return; + if (!filter || (filter !== "all" && !isWatchRegion(filter) && !isGroupFilter(filter))) return; state.filter = filter; savePrefs(); renderFilters(); @@ -1217,11 +1447,13 @@ document.addEventListener("visibilitychange", () => { else clearTimeout(state.pollTimer); }); -const prefs = readJson<{ region?: unknown; sort?: { key?: unknown; dir?: unknown }; filter?: unknown }>(PREF_KEY); +const prefs = readJson<{ region?: unknown; sort?: { key?: unknown; dir?: unknown }; filter?: unknown; groups?: Record; alerts?: Record }>(PREF_KEY); if (prefs) { if (isRegion(prefs.region)) state.region = prefs.region; if (SORT_KEYS.has(prefs.sort?.key as SortKey) && (prefs.sort?.dir === 1 || prefs.sort?.dir === -1)) state.sort = { key: prefs.sort.key as SortKey, dir: prefs.sort.dir }; - if (prefs.filter === "all" || isWatchRegion(prefs.filter)) state.filter = prefs.filter; + if (prefs.filter === "all" || isWatchRegion(prefs.filter) || isGroupFilter(prefs.filter)) state.filter = prefs.filter; + if (prefs.groups && typeof prefs.groups === "object") state.groups = prefs.groups; + if (prefs.alerts && typeof prefs.alerts === "object") state.alerts = prefs.alerts; } const cached = readJson<{ savedAt: number; snap: Snapshot }>(CACHE_KEY); if (cached?.snap && Date.now() - cached.savedAt < CACHE_TTL && cached.snap.market?.region === state.region) applySnapshot(cached.snap, true); diff --git a/dsh/web/index.html b/dsh/web/index.html index 9babe10..de2d752 100644 --- a/dsh/web/index.html +++ b/dsh/web/index.html @@ -33,13 +33,16 @@

行情

@@ -66,6 +69,7 @@

自选

+
diff --git a/dsh/web/style.css b/dsh/web/style.css index 4643639..3a9187c 100644 --- a/dsh/web/style.css +++ b/dsh/web/style.css @@ -108,7 +108,21 @@ h1 { font-size: 19px; font-weight: 650; letter-spacing: -.02em; line-height: 1.2 } .add { display: grid; grid-template-columns: minmax(0, 420px) auto 1fr; align-items: center; gap: 8px; margin-top: 12px; padding: 12px; border: 1px solid var(--border); border-radius: 12px; background: var(--surface); } +.add-input-wrap { position: relative; min-width: 0; } +.add-input-wrap input { width: 100%; } .add input { height: 32px; min-width: 0; padding: 0 10px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface-subtle); caret-color: var(--accent); transition: border-color .16s ease, box-shadow .16s ease; } +.search-results { position: absolute; z-index: 20; left: 0; right: 0; top: calc(100% + 4px); max-height: 240px; overflow-y: auto; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); box-shadow: var(--shadow); padding: 4px; } +.search-item { width: 100%; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 6px 8px; border: 0; border-radius: 7px; background: transparent; text-align: left; font-size: 12.5px; } +.search-item:hover, .search-item:focus-visible { background: var(--surface-subtle); } +.search-item .sname { font-weight: 600; } +.search-item .scode { color: var(--muted); font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; font-size: 11px; } +.row-actions { display: inline-flex; align-items: center; gap: 2px; } +.row-btn { width: 24px; height: 24px; display: inline-flex; align-items: center; justify-content: center; border: 0; border-radius: 6px; background: transparent; color: var(--muted); opacity: .7; transition: background-color .14s ease, color .14s ease, opacity .14s ease; } +.row-btn:hover { background: var(--surface-subtle); color: var(--text); opacity: 1; } +.row-btn.is-set { color: var(--accent); opacity: 1; } +.tag.group-tag { background: color-mix(in srgb, var(--accent) 14%, transparent); color: var(--accent); border-color: color-mix(in srgb, var(--accent) 28%, transparent); } +.tag.alert-badge { background: color-mix(in srgb, var(--warn) 18%, transparent); color: var(--warn); border-color: color-mix(in srgb, var(--warn) 40%, transparent); font-weight: 600; } +tr.is-alert { background: color-mix(in srgb, var(--warn) 8%, transparent); } .add input::placeholder { color: var(--muted); opacity: 1; } .add input:focus { border-color: var(--accent); outline: none; box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 20%, transparent); } .add-actions { display: flex; align-items: center; gap: 8px; } diff --git a/hermes/plugin.yaml b/hermes/plugin.yaml index 3d0a798..8405f0f 100644 --- a/hermes/plugin.yaml +++ b/hermes/plugin.yaml @@ -20,6 +20,7 @@ provides_tools: - get_valuation_history - get_index_valuation - get_cds_index + - get_macro_anchors - get_earnings_calendar - get_shareholder_structure - get_etf_details diff --git a/hermes/tools.py b/hermes/tools.py index cb0a9cd..8a2ef5f 100644 --- a/hermes/tools.py +++ b/hermes/tools.py @@ -385,7 +385,10 @@ def detect_anomaly(args: dict, **kwargs) -> str: def diagnose_data_sources(args: dict, **kwargs) -> str: market = args.get("market", "all") - return _run("diagnostics.py", ["check", "--market", market]) + argv = ["check", "--market", market] + if args.get("probe"): + argv.append("--probe") + return _run("diagnostics.py", argv) def get_market_capabilities(args: dict, **kwargs) -> str: @@ -512,6 +515,13 @@ def get_cds_index(args: dict, **kwargs) -> str: ) +def get_macro_anchors(args: dict, **kwargs) -> str: + days = args.get("days", 30) + if isinstance(days, float) and days.is_integer(): + days = int(days) + return _run("macro_data.py", ["anchors", "--group", args.get("group", "all"), "--days", days]) + + 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 c9cc23a..62c8a28 100644 --- a/mcp_host/server.py +++ b/mcp_host/server.py @@ -2,12 +2,16 @@ """MCP stdio server for the stock-analysis tools: newline-delimited JSON-RPC 2.0, stdlib only. Reuses the Hermes adapter (tools/tool_schemas.json via hermes/schemas.py + hermes/tools.py argv mapping), so the -tools stay identical to the other hosts. stdout carries only JSON-RPC messages; anything else -goes to stderr. +tools stay identical to the other hosts. Also exposes bundled skills/*/SKILL.md as MCP Prompts and +references as MCP Resources, plus optional --discovery / --profile=core modes to reduce context footprint. +stdout carries only JSON-RPC messages; anything else goes to stderr. """ +import argparse import contextlib import json +import os +import re import subprocess import sys import threading @@ -25,9 +29,183 @@ TOOL_LIST = [ {"name": s["name"], "description": s["description"], "inputSchema": s["parameters"]} for s in schemas.TOOL_SCHEMAS ] +CORE_TOOL_NAMES = frozenset( + { + "get_quote", + "get_kline", + "get_technical_analysis", + "get_financials", + "get_fundamental_context", + "get_valuation_history", + "get_macro_anchors", + "screen_stocks", + "screen_risk", + "run_backtest", + "get_market_review", + "detect_market_regime", + "search_stock_news", + "resolve_stock_name", + "get_watchlist", + "build_watchlist_context", + "diagnose_data_sources", + "get_market_capabilities", + "render_stock_report", + } +) +DISCOVERY_TOOL_DEF = { + "name": "stock_tool_search", + "description": "按中文关键词、英文关键词或工具名搜索 76 个股票分析工具,返回匹配工具的完整名称与参数 schema,并在支持动态刷新的 MCP 客户端中将其加载到当前会话工具列表。", + "inputSchema": { + "type": "object", + "properties": { + "query": {"type": "string", "description": "搜索关键词或工具名,例如 财务、get_quote、DCF、回测"}, + "limit": {"type": "number", "description": "最多返回的工具数量(1..20,默认 5)"}, + }, + "required": ["query"], + }, +} + _current = threading.local() # Each call is a Python process that loads pandas; parallel model calls must not fan out unbounded. _SLOTS = threading.BoundedSemaphore(4) +_FRONTMATTER_RE = re.compile(r"^---\r?\n([\s\S]*?)\r?\n---\r?\n?") + + +def _mcp_skill_preamble(*, discovery: bool, profile: str) -> str: + if discovery: + tool_guidance = ( + "1. 当前会话开启了 `--discovery` 按需发现模式:请先调用 `stock_tool_search` 按关键词搜索并加载所需 MCP 工具" + "(如 `get_quote`、`get_kline`、`get_technical_analysis`、`get_financials`、`screen_risk`、`render_stock_report` 等),再直接调用已加载工具完成分析。\n" + ) + elif profile == "core": + tool_guidance = ( + "1. 当前会话运行在 `--profile core` 核心子集模式(暴露 19 个核心工具,含行情/K线/技术面/财务/估值/宏观/风控/新闻与 `render_stock_report`):" + "请仅调用 `tools/list` 中已暴露的 MCP 工具完成采集与报告渲染;若正文中引用了未在当前列表中的扩展工具,请跳过该扩展环节并在结论中说明。\n" + ) + else: + tool_guidance = ( + "1. 请直接调用已注册的 MCP 工具完成数据采集与分析(如 `get_quote`、`get_kline`、`get_technical_analysis`、`get_financials`、" + "`get_fundamental_context`、`get_valuation_history`、`get_macro_anchors`、`screen_risk`、`detect_market_regime`、" + "`search_stock_news`、`render_stock_report` 等)。\n" + ) + return ( + "[MCP 执行说明]\n" + "你当前通过 MCP 协议接入 stock-analysis 工具集,无需也不要依赖本地 shell 脚本(如 `python3 scripts/gather.py`)或本地文件路径:\n" + f"{tool_guidance}" + "2. 若正文引用了 `references/...` 或 `schemas/...` 文件,请通过 MCP `resources/read` 读取对应的 " + "`stock-skill:///references/` 或 `stock-schema://` 资源(例如 `stock-schema://report_schema.json`)。\n\n" + ) + + +def _skills_dir() -> Path: + return tools.TOOLS_DIR.parent / "skills" + + +def _schemas_dir() -> Path: + return tools.TOOLS_DIR.parent / "schemas" + + +def _parse_frontmatter(raw: str) -> tuple[dict[str, str], str]: + m = _FRONTMATTER_RE.match(raw) + if not m: + return {}, raw + meta = {} + for line in m.group(1).splitlines(): + if ":" in line: + k, v = line.split(":", 1) + meta[k.strip()] = v.strip().strip('"').strip("'") + return meta, raw[m.end() :].lstrip() + + +def _discover_skills() -> tuple[dict[str, dict], dict[str, dict]]: + """Return (prompts_by_name, resources_by_uri) from skills/*/SKILL.md, references/, and schemas/.""" + sdir = _skills_dir() + prompts: dict[str, dict] = {} + resources: dict[str, dict] = {} + if sdir.is_dir(): + for child in sorted(sdir.iterdir(), key=lambda p: p.name): + if not child.is_dir(): + continue + skill_md = child / "SKILL.md" + if not skill_md.is_file(): + continue + raw = skill_md.read_text(encoding="utf-8") + meta, body = _parse_frontmatter(raw) + desc = meta.get("description") or child.name + prompts[child.name] = { + "name": child.name, + "description": desc, + "body": body, + "arguments": [ + { + "name": "request", + "description": "可选:股票代码、市场或具体分析问题", + "required": False, + } + ], + } + uri = f"stock-skill://{child.name}/SKILL.md" + resources[uri] = { + "uri": uri, + "name": f"{child.name}/SKILL.md", + "description": desc, + "mimeType": "text/markdown", + "path": skill_md, + } + refs_dir = child / "references" + if refs_dir.is_dir(): + for ref in sorted(refs_dir.iterdir(), key=lambda p: p.name): + if ref.is_file() and ref.suffix.lower() in (".md", ".txt", ".yaml", ".yml", ".json"): + ref_uri = f"stock-skill://{child.name}/references/{ref.name}" + suffix = ref.suffix.lower() + mime = ( + "text/markdown" + if suffix == ".md" + else ("application/json" if suffix == ".json" else "text/plain") + ) + resources[ref_uri] = { + "uri": ref_uri, + "name": f"{child.name}/references/{ref.name}", + "description": f"Reference material for {child.name}", + "mimeType": mime, + "path": ref, + } + schemas_dir = _schemas_dir() + if schemas_dir.is_dir(): + for schema_file in sorted(schemas_dir.iterdir(), key=lambda p: p.name): + if schema_file.is_file() and schema_file.suffix.lower() == ".json": + schema_uri = f"stock-schema://{schema_file.name}" + resources[schema_uri] = { + "uri": schema_uri, + "name": f"schemas/{schema_file.name}", + "description": f"Shared JSON schema: {schema_file.name}", + "mimeType": "application/json", + "path": schema_file, + } + return prompts, resources + + +def _search_tools(query: str, limit: int = 5) -> list[dict]: + limit = max(1, min(int(limit) if isinstance(limit, (int, float)) else 5, 20)) + terms = [t for t in re.split(r"[\s,/,、]+", str(query or "").strip().casefold()) if t] + if not terms: + return [] + scored = [] + for entry in TOOL_LIST: + name_low = entry["name"].casefold() + desc_low = entry["description"].casefold() + score = 0 + for term in terms: + if name_low == term: + score += 100 + elif term in name_low: + score += 30 + if term in desc_low: + score += 10 + if score > 0: + scored.append((score, entry["name"], entry)) + scored.sort(key=lambda item: (-item[0], item[1])) + return [entry for _, _, entry in scored[:limit]] def _version() -> str: @@ -97,14 +275,34 @@ def __init__(self, code: int, message: str): self.message = message -def call_tool(params: dict) -> dict: +def call_tool(params: dict, *, session_state: dict | None = None, on_tools_changed=None) -> dict: name = params.get("name") - schema = SCHEMAS.get(name) if isinstance(name, str) else None - if schema is None: - raise RpcError(-32602, f"Unknown tool: {name}") args = params.get("arguments", {}) if not isinstance(args, dict): raise RpcError(-32602, "Tool arguments must be an object") + + if name == "stock_tool_search" and session_state and session_state.get("discovery"): + query = args.get("query") + if not isinstance(query, str) or not query.strip(): + return { + "content": [{"type": "text", "text": json.dumps({"error": "missing required argument: query"})}], + "isError": True, + } + matches = _search_tools(query, args.get("limit", 5)) + added = False + with session_state["lock"]: + for entry in matches: + if entry["name"] not in session_state["loaded"]: + session_state["loaded"].add(entry["name"]) + added = True + if added and on_tools_changed is not None: + on_tools_changed() + payload = {"query": query, "matched": len(matches), "tools": matches} + return {"content": [{"type": "text", "text": json.dumps(payload, ensure_ascii=False)}], "isError": False} + + schema = SCHEMAS.get(name) if isinstance(name, str) else None + if schema is None: + raise RpcError(-32602, f"Unknown tool: {name}") missing = [key for key in schema["parameters"].get("required", []) if args.get(key) is None] if missing: text = json.dumps({"error": f"missing required argument: {', '.join(missing)}"}) @@ -125,25 +323,85 @@ def call_tool(params: dict) -> dict: return {"content": [{"type": "text", "text": text}], "isError": is_error} -def handle(method: str, params: dict) -> dict: +def handle(method: str, params: dict, *, session_state: dict | None = None) -> dict: + discovery = bool(session_state and session_state.get("discovery")) + profile = (session_state or {}).get("profile", "full") if method == "initialize": requested = params.get("protocolVersion") return { "protocolVersion": requested if requested in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0], - "capabilities": {"tools": {"listChanged": False}}, + "capabilities": { + "tools": {"listChanged": discovery}, + "prompts": {"listChanged": False}, + "resources": {"subscribe": False, "listChanged": False}, + }, "serverInfo": {"name": "stock-analysis", "version": _version()}, } if method == "ping": return {} if method == "tools/list": + if discovery: + with session_state["lock"]: + loaded = set(session_state["loaded"]) + exposed = [DISCOVERY_TOOL_DEF] + [t for t in TOOL_LIST if t["name"] in loaded] + return {"tools": exposed} + if profile == "core": + return {"tools": [t for t in TOOL_LIST if t["name"] in CORE_TOOL_NAMES]} return {"tools": TOOL_LIST} + if method == "prompts/list": + prompts, _ = _discover_skills() + return { + "prompts": [ + {"name": p["name"], "description": p["description"], "arguments": p["arguments"]} + for p in prompts.values() + ] + } + if method == "prompts/get": + name = params.get("name") + prompts, _ = _discover_skills() + prompt = prompts.get(name) if isinstance(name, str) else None + if prompt is None: + raise RpcError(-32602, f"Unknown prompt: {name}") + arguments = params.get("arguments") or {} + if not isinstance(arguments, dict): + raise RpcError(-32602, "Prompt arguments must be an object") + req = arguments.get("request") + text = f"{_mcp_skill_preamble(discovery=discovery, profile=profile)}{prompt['body']}" + if isinstance(req, str) and req.strip(): + text = f"{text}\n\n---\n用户请求:{req.strip()}" + return { + "description": prompt["description"], + "messages": [{"role": "user", "content": {"type": "text", "text": text}}], + } + if method == "resources/list": + _, resources = _discover_skills() + return { + "resources": [ + { + "uri": r["uri"], + "name": r["name"], + "description": r["description"], + "mimeType": r["mimeType"], + } + for r in resources.values() + ] + } + if method == "resources/read": + uri = params.get("uri") + _, resources = _discover_skills() + res = resources.get(uri) if isinstance(uri, str) else None + if res is None: + raise RpcError(-32602, f"Unknown resource: {uri}") + content = res["path"].read_text(encoding="utf-8") + return {"contents": [{"uri": res["uri"], "mimeType": res["mimeType"], "text": content}]} raise RpcError(-32601, f"Method not found: {method}") -def serve(stdin, stdout) -> None: +def serve(stdin, stdout, *, discovery: bool = False, profile: str = "full") -> None: write_lock = threading.Lock() calls: dict = {} workers: list = [] + session_state = {"discovery": discovery, "profile": profile, "loaded": set(), "lock": threading.Lock()} def send(message: dict) -> None: data = (json.dumps(message, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8") @@ -151,15 +409,27 @@ def send(message: dict) -> None: stdout.write(data) stdout.flush() - def reply(request_id, work, *args) -> dict: + def notify_tools_changed() -> None: + send({"jsonrpc": "2.0", "method": "notifications/tools/list_changed"}) + + def reply(request_id, work, *args, **kwargs) -> dict: try: - return {"jsonrpc": "2.0", "id": request_id, "result": work(*args)} + return {"jsonrpc": "2.0", "id": request_id, "result": work(*args, **kwargs)} 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 - message = reply(request_id, call_tool, params) + 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) with call.lock: if calls.get(request_id) is call: del calls[request_id] @@ -203,7 +473,7 @@ def run_call(request_id, params, call): worker.start() workers = [w for w in workers if w.is_alive()] + [worker] continue - send(reply(request_id, handle, method, params)) + send(reply(request_id, handle, method, params, session_state=session_state)) for call in list(calls.values()): # client closed stdin: stop outstanding work call.cancel() @@ -211,11 +481,25 @@ def run_call(request_id, params, call): worker.join() -def main() -> None: +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description="Stock Analysis MCP stdio server") + parser.add_argument( + "--discovery", + action="store_true", + default=os.environ.get("STOCK_MCP_DISCOVERY", "").lower() in ("1", "true", "yes"), + help="Start with stock_tool_search only and load matched tools on demand", + ) + parser.add_argument( + "--profile", + choices=("full", "core"), + default=os.environ.get("STOCK_MCP_PROFILE", "full").lower() or "full", + help="Static tool set profile when --discovery is off (full=all tools, core=19 core tools)", + ) + args = parser.parse_args(argv) stdout = sys.stdout.buffer sys.stdout = sys.stderr # stray prints must never corrupt the JSON-RPC stream with contextlib.suppress(KeyboardInterrupt): - serve(sys.stdin.buffer, stdout) + serve(sys.stdin.buffer, stdout, discovery=args.discovery, profile=args.profile) if __name__ == "__main__": diff --git a/openclaw/index.ts b/openclaw/index.ts index 68ed264..20f6593 100644 --- a/openclaw/index.ts +++ b/openclaw/index.ts @@ -62,6 +62,8 @@ function typeboxSchema({ type, properties, required = [], items, anyOf, enum: va return Type.Array(items ? typeboxSchema(items) : Type.Unknown(), options); case "number": return Type.Number(options); + case "integer": + return Type.Integer(options); case "boolean": return Type.Boolean(options); case "null": diff --git a/openclaw/openclaw.plugin.json b/openclaw/openclaw.plugin.json index d00feca..8381e25 100644 --- a/openclaw/openclaw.plugin.json +++ b/openclaw/openclaw.plugin.json @@ -60,6 +60,7 @@ "get_valuation_history", "get_index_valuation", "get_cds_index", + "get_macro_anchors", "get_earnings_calendar", "get_shareholder_structure", "get_etf_details", diff --git a/scripts/tool-calls.mjs b/scripts/tool-calls.mjs index 69a32b6..26f6053 100644 --- a/scripts/tool-calls.mjs +++ b/scripts/tool-calls.mjs @@ -32,6 +32,10 @@ export const TOOL_CALLS = { script: "credit_data.py", argv: (p) => ["cds_index", "--source", p.source ?? "cn", "--days", String(p.days ?? 30), "--index", p.index ?? "", "--tenor", p.tenor ?? ""], }, + get_macro_anchors: { + script: "macro_data.py", + argv: (p) => ["anchors", "--group", p.group ?? "all", "--days", String(p.days ?? 30)], + }, get_earnings_calendar: { script: "value_data.py", argv: (p) => ["earnings_calendar", "--report-date", p.report_date ?? "", "--symbol", p.symbol ?? "", "--top", String(p.top ?? 50)], @@ -341,7 +345,11 @@ export const TOOL_CALLS = { }, diagnose_data_sources: { script: "diagnostics.py", - argv: (p) => ["check", "--market", p.market ?? "all"], + argv: (p) => { + const args = ["check", "--market", p.market ?? "all"]; + if (p.probe) args.push("--probe"); + return args; + }, }, get_market_capabilities: { script: "capabilities.py", diff --git a/skills/stock-analysis/SKILL.md b/skills/stock-analysis/SKILL.md index c2153c9..3bd8788 100644 --- a/skills/stock-analysis/SKILL.md +++ b/skills/stock-analysis/SKILL.md @@ -13,7 +13,7 @@ description: 综合股票分析:联合技术、基本面、资金、消息和 美股机构研究调用 `get_us_holdings(cik, mode=auto)`:有当前或已检索历史 13F 时返回机构组合,否则按发行人 CIK 反查机构;也可显式选 `manager/issuer`,如 Berkshire `0001067983` 查组合、Apple `0000320193` 用 `issuer` 查机构。发行人映射仅使用核对 CIK 的官方 13D/G CUSIP,不做名称猜测;无映射直接报缺失。首次下载约 100 MB,后续缓存,共享 CLI 查询预算 300 秒(宿主另留退出余量)。读取 `report_date/filing_window_end/cusip_evidence`,区分持仓日期与披露窗口;修订重述替换、新增补充,缺基础版或未知修订时总量 null,并计入 `unresolved_manager_count`。`mapping_complete=false` 表示不能保证涵盖所有类别或变更,`complete_for_mapped_cusips` 只表示已映射证券在公开数据窗口的申报链完整性,不能称实时全部股东。期权/本金在 `positions` 单列,不能把跨机构持股简单合计成去重比例。机构组合查询仍返回最新已知报告期的原始 13F 与修订链接,缺少对应原始版时明确报错;`history_truncated=true` 时不能将旧记录当作已完整检索。存在修订先读原文,不能自动推断变化。 -美股内部人研究调用 `get_insider_trades(symbol, days=90, top=10)`,需设置含真实联系邮箱的 `SEC_USER_AGENT`。`days` 按申报日期过滤,`top` 限制文件数;只将代码 P/S 视作买卖信号,授予、行权、赠与等保留原始代码和脚注,衍生品单列。Form 4/A 与原申报勿重复计算,检查截断和失败提示;`screen_risk` 仍仅支持 A 股。 +美股内部人研究调用 `get_insider_trades(symbol, days=90, top=10)`,需设置含真实联系邮箱的 `SEC_USER_AGENT`。`days` 按申报日期过滤,`top` 限制文件数;只将代码 P/S 视作买卖信号,授予、行权、赠与等保留原始代码和脚注,衍生品单列。Form 4/A 与原申报勿重复计算,检查截断和失败提示。`screen_risk` 已覆盖 A 股、港股和美股(A 股查限售解禁与中文线索,港股查 HKEXnews 风险公告与双语线索,美股查英文线索及 `SEC_USER_AGENT` 就绪时的 Form 4 内部人卖出);日/韩/台不支持。 ## 无状态分析扩展 @@ -29,7 +29,7 @@ description: 综合股票分析:联合技术、基本面、资金、消息和 | 意图 | 调用序列 | |------|---------| -| 个股买卖时机 | `get_technical_analysis` → `get_market_capabilities` → 当前市场支持的资金/风险工具 → `detect_market_regime`。A股可加 `get_capital_flow`(summary) 和 `screen_risk`;其他市场不得用缺失的资金或风险数据。veto_buy=true 则不入场;大盘下跌时个股看多信号降级为轻仓试错或等待;HOLD/WAIT 给出可观察触发条件 | +| 个股买卖时机 | `get_technical_analysis` → `get_market_capabilities` → 当前市场支持的资金/风险工具 → `detect_market_regime`。A股可加 `get_capital_flow`(summary) 和 `screen_risk`;港股和美股也可调用 `screen_risk`(需披露 `data_complete`/warnings 与 `SEC_USER_AGENT` 覆盖边界),其他市场不得用缺失的资金或风险数据。veto_buy=true 则不入场;大盘下跌时个股看多信号降级为轻仓试错或等待;HOLD/WAIT 给出可观察触发条件 | | 个股状态速览 | `get_quote` + `get_technical_analysis` | | 场外公募基金净值 | `get_fund_quote`(6 位基金代码,如 018147) | | 异动归因 | `detect_anomaly` + `get_news` | diff --git a/strategies/examples/dca_monthly.yaml b/strategies/examples/dca_monthly.yaml new file mode 100644 index 0000000..46a62d0 --- /dev/null +++ b/strategies/examples/dca_monthly.yaml @@ -0,0 +1,17 @@ +name: "Monthly DCA Allocation" +version: "1.0" +description: "按月定投策略(支持单标的或逗号分隔多标的等权/自定义权重定投)" + +portfolio: + rebalance: "quarterly" + weighting: "equal" + +dca: + frequency: "monthly" + amount: 10000 + +simulation: + execution: "next_open" + slippage: 0.001 + commission: 0.0005 + stamp_tax: 0.0 diff --git a/strategies/examples/portfolio_rebalance.yaml b/strategies/examples/portfolio_rebalance.yaml new file mode 100644 index 0000000..8a43751 --- /dev/null +++ b/strategies/examples/portfolio_rebalance.yaml @@ -0,0 +1,14 @@ +name: "Equal-Weight Monthly Rebalance" +version: "1.0" +description: "多标的等权月度再平衡组合策略(配合逗号分隔同市场标的运行,如 510300,510500,518880)" + +portfolio: + rebalance: "monthly" + weighting: "equal" + drift_threshold: 0.05 + +simulation: + execution: "next_open" + slippage: 0.001 + commission: 0.0005 + stamp_tax: 0.0 diff --git a/tests/e2e/test_openclaw_e2e.ts b/tests/e2e/test_openclaw_e2e.ts index 503fe0c..07b3e08 100644 --- a/tests/e2e/test_openclaw_e2e.ts +++ b/tests/e2e/test_openclaw_e2e.ts @@ -33,6 +33,7 @@ const fakeTypebox = { Object: (props: unknown) => ({ __t: "object", props }), String: () => ({ __t: "string" }), Number: () => ({ __t: "number" }), + Integer: () => ({ __t: "integer" }), Null: () => ({ __t: "null" }), Boolean: () => ({ __t: "boolean" }), Optional: (s: unknown) => ({ __t: "optional", s }), diff --git a/tests/test_adapter_parity.ts b/tests/test_adapter_parity.ts index 5ea978b..25ef5c8 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 !== 75) issues.push(`pi registered ${names.length} tools, expected 75`); +if (names.length !== 76) issues.push(`pi registered ${names.length} tools, expected 76`); 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_backtest_portfolio.py b/tests/test_backtest_portfolio.py new file mode 100644 index 0000000..fe5eefc --- /dev/null +++ b/tests/test_backtest_portfolio.py @@ -0,0 +1,354 @@ +"""Tests for multi-asset portfolio, DCA, and periodic rebalance backtesting.""" + +import numpy as np +import pandas as pd +import pytest + +from tools import backtest + + +def _make_df(dates, prices, volume=1_000_000, opens=None, limit_up=None, limit_down=None, currency=None): + data = { + "date": pd.to_datetime(dates), + "open": opens if opens is not None else prices, + "high": [p * 1.02 for p in prices] if limit_up is None and limit_down is None else prices, + "low": [p * 0.98 for p in prices] if limit_up is None and limit_down is None else prices, + "close": prices, + "volume": volume if isinstance(volume, list) else [volume] * len(dates), + "adjusted": ["qfq"] * len(dates), + } + if limit_up is not None: + data["limit_up"] = limit_up + if limit_down is not None: + data["limit_down"] = limit_down + if currency is not None: + data["currency"] = [currency] * len(dates) + return pd.DataFrame(data) + + +def test_monthly_rebalance_sells_winner_and_buys_laggard(): + dates = pd.bdate_range("2025-01-02", periods=65) + a_prices = np.linspace(10.0, 20.0, 65) + b_prices = np.full(65, 10.0) + datasets = {"510300": _make_df(dates, a_prices), "510500": _make_df(dates, b_prices)} + strategy = { + "name": "Equal Rebalance", + "portfolio": {"rebalance": "monthly", "weighting": "equal"}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + } + res = backtest.simulate_portfolio(datasets, strategy, capital=100_000, start="2025-01-03") + assert res["mode"] == "portfolio_allocation" + assert res["final_equity"] > 100_000 + sells = [t for t in res["trades"] if t["type"] == "sell"] + assert any(t["symbol"] == "510300" and "再平衡" in t["reason"] for t in sells) + assert len(res["final_holdings"]) == 2 + weights = {h["symbol"]: h["weight"] for h in res["final_holdings"]} + assert 0.4 <= weights["510300"] <= 0.6 + + +def test_flat_price_dca_has_zero_drawdown_zero_sharpe_and_zero_twr(tmp_path, monkeypatch): + dates = pd.bdate_range("2025-01-02", periods=65) + df = _make_df(dates, np.full(65, 10.0)) + monkeypatch.setattr(backtest, "fetch_kline", lambda sym, *a, **kw: df) + strat = tmp_path / "flat_dca.yaml" + strat.write_text( + "name: FlatDCA\ndca:\n frequency: monthly\n amount: 10000\nsimulation:\n execution: next_open\n slippage: 0\n commission: 0\n stamp_tax: 0\n", + encoding="utf-8", + ) + res = backtest.run_backtest(str(strat), "AAPL", "2025-01-02", "2025-04-02", 10_000) + assert res["contributions"]["count"] >= 2 + assert res["metrics"]["time_weighted_return"] == 0.0 + assert res["metrics"]["max_drawdown"] == 0.0 + assert res["metrics"]["sharpe_ratio"] == 0.0 + assert res["metrics"]["annual_return"] == 0.0 + + +def test_twr_links_overnight_jump_before_open_contribution(): + # Close day0=128, day1 opens at 256 (100% overnight gain), $128 DCA deposited at open -> TWR must be 100%, not 50% + dates = pd.to_datetime(["2025-01-31", "2025-02-03", "2025-02-04"]) + df = pd.DataFrame( + { + "date": dates, + "open": [128.0, 256.0, 256.0], + "high": [128.0, 256.0, 256.0], + "low": [128.0, 256.0, 256.0], + "close": [128.0, 256.0, 256.0], + "volume": [1000, 1000, 1000], + "adjusted": ["qfq"] * 3, + } + ) + strategy = { + "dca": {"frequency": "monthly", "amount": 128}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + } + res = backtest.simulate_portfolio({"AAPL": df}, strategy, capital=128, start="2025-01-31") + assert res["time_weighted_return"] == 1.0 + + +def test_biweekly_schedule_is_continuous_across_year_boundary(): + b1 = backtest._schedule_bucket(pd.Timestamp("2025-12-22"), "biweekly") + b2 = backtest._schedule_bucket(pd.Timestamp("2025-12-29"), "biweekly") + b3 = backtest._schedule_bucket(pd.Timestamp("2026-01-05"), "biweekly") + assert b1 == b2 + assert b3 == b2 + 1 + + +def test_dca_deploys_when_drift_threshold_skips_rebalance(): + dates = pd.bdate_range("2025-01-02", periods=65) + df = _make_df(dates, np.full(65, 10.0)) + strategy = { + "portfolio": {"rebalance": "monthly", "weighting": "equal", "drift_threshold": 0.2}, + "dca": {"frequency": "monthly", "amount": 100}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + } + res = backtest.simulate_portfolio({"AAPL": df}, strategy, capital=1_000, start="2025-01-03") + assert res["contributions"]["count"] >= 2 + assert res["final_cash"] == 0.0 + assert any("定期定投" in t["reason"] for t in res["trades"]) + + +def test_stop_loss_does_not_reenter_on_same_bar_and_persists_when_blocked(): + # Stop triggers on day 1 close (10 -> 7), day 2 has 0 volume (blocked), day 2 close recovers to 10, day 3 trades -> must still sell and not reenter same bar + dates = pd.to_datetime(["2025-01-02", "2025-01-03", "2025-01-06", "2025-01-07", "2025-01-08"]) + df = pd.DataFrame( + { + "date": dates, + "open": [10.0, 10.0, 7.0, 10.0, 10.0], + "high": [10.0, 10.0, 10.0, 10.0, 10.0], + "low": [10.0, 7.0, 7.0, 10.0, 10.0], + "close": [10.0, 7.0, 10.0, 10.0, 10.0], + "volume": [1000, 1000, 0, 1000, 1000], + "adjusted": ["qfq"] * 5, + } + ) + strategy = { + "entry": {"conditions": [{"indicator": "close", "operator": ">", "value": 5}], "logic": "all"}, + "exit": {"conditions": [], "stop_loss": -0.05, "take_profit": 0.5}, + "position": {"max_positions": 1, "size": 0.5}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + } + res = backtest.simulate_portfolio({"AAPL": df}, strategy, capital=10_000, start="2025-01-03") + # Day 1 buys using 50% size (5000 = 500 shares), day 2 stop blocked, day 3 sells and does NOT re-buy on day 3! + buys_d3 = [t for t in res["trades"] if t["type"] == "buy" and t["date"] == "2025-01-07"] + sells_d3 = [t for t in res["trades"] if t["type"] == "sell" and t["date"] == "2025-01-07"] + assert len(sells_d3) == 1 + assert buys_d3 == [] + assert res["trades"][0]["shares"] == 500 # position.size=0.5 applied + assert res["execution"]["blocked_orders"] == 1 + assert res["execution"]["unfilled_order"] is False + + +def test_staggered_start_date_retries_initial_allocation(): + d_a = pd.bdate_range("2025-01-02", periods=10) + d_b = pd.bdate_range("2025-01-06", periods=8) + datasets = {"AAPL": _make_df(d_a, np.full(10, 10.0)), "MSFT": _make_df(d_b, np.full(8, 10.0))} + strategy = { + "portfolio": {"rebalance": "none", "weighting": "equal"}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + } + res = backtest.simulate_portfolio(datasets, strategy, capital=10_000, start="2025-01-03") + held = {h["symbol"]: h["shares"] for h in res["final_holdings"]} + assert held == {"AAPL": 500, "MSFT": 500} + assert res["final_cash"] == 0.0 + + +def test_numeric_yaml_weight_keys_and_signal_rebalance_conflict_and_defaults(): + dates = pd.bdate_range("2025-01-02", periods=10) + datasets = {"510300": _make_df(dates, np.full(10, 10.0)), "510500": _make_df(dates, np.full(10, 10.0))} + # Numeric int key 510300 resolved cleanly + strategy = { + "portfolio": {"rebalance": "none", "weighting": "custom", "weights": {510300: 0.6, "510500": 0.4}}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + } + res = backtest.simulate_portfolio(datasets, strategy, capital=100_000, start="2025-01-03") + weights = {h["symbol"]: h["weight"] for h in res["final_holdings"]} + assert weights["510300"] == 0.6 and weights["510500"] == 0.4 + + # Rebalance + entry.conditions conflict rejected + with pytest.raises(ValueError, match="rebalance"): + backtest.simulate_portfolio( + datasets, + { + "entry": {"conditions": [{"indicator": "close", "operator": ">", "value": 1}]}, + "portfolio": {"rebalance": "monthly"}, + }, + capital=100_000, + ) + + # Single-symbol signal + DCA preserves default -10% stop_loss + drop_df = _make_df(dates, [10, 10, 8, 8, 8, 8, 8, 8, 8, 8]) + sig_dca = { + "entry": {"conditions": [{"indicator": "close", "operator": ">", "value": 9}]}, + "dca": {"frequency": "monthly", "amount": 1000}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + } + res_stop = backtest.simulate_portfolio({"AAPL": drop_df}, sig_dca, capital=10_000, start="2025-01-03") + assert any(t["type"] == "sell" and "止损" in t["reason"] for t in res_stop["trades"]) + + +def test_price_limit_up_blocks_portfolio_buy(): + dates = pd.bdate_range("2025-01-02", periods=5) + df = _make_df(dates, [10.0, 11.0, 11.0, 11.0, 11.0], limit_up=[11.0, 11.0, 12.1, 12.1, 12.1]) + strategy = { + "portfolio": {"rebalance": "none", "weighting": "equal"}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + } + res = backtest.simulate_portfolio({"600519": df}, strategy, capital=100_000, start="2025-01-03") + assert res["execution"]["blocked_orders"] == 1 + assert res["trades"][0]["date"] == "2025-01-06" + + +def test_duplicate_canonical_symbols_and_mixed_hk_counters_rejected(): + dates = pd.bdate_range("2025-01-02", periods=40) + with pytest.raises(ValueError, match="Duplicate instrument"): + backtest.simulate_portfolio( + {"600519": _make_df(dates, np.full(40, 100.0)), "sh600519": _make_df(dates, np.full(40, 100.0))}, + {"portfolio": {"rebalance": "monthly"}}, + capital=100_000, + ) + with pytest.raises(ValueError, match="quote currency"): + backtest.simulate_portfolio( + {"2807.HK": _make_df(dates, np.full(40, 10.0)), "9807.HK": _make_df(dates, np.full(40, 10.0))}, + {"portfolio": {"rebalance": "monthly"}}, + capital=100_000, + ) + with pytest.raises(ValueError, match="single market"): + backtest.simulate_portfolio( + {"600519": _make_df(dates, np.full(40, 100.0)), "AAPL": _make_df(dates, np.full(40, 100.0))}, + {"portfolio": {"rebalance": "monthly"}}, + capital=100_000, + ) + # 9988.HK (Alibaba) and 9618.HK (JD) are HKD main-board equities, not USD ETF counters + ok_hk = backtest.simulate_portfolio( + {"00700.HK": _make_df(dates, np.full(40, 300.0)), "9988.HK": _make_df(dates, np.full(40, 80.0))}, + {"portfolio": {"rebalance": "monthly"}}, + capital=100_000, + ) + assert ok_hk["currency"] == "HKD" + + +def test_allocation_mode_enforces_explicit_exits_without_reentry(): + dates = pd.bdate_range("2025-01-02", periods=50) + # Symbol A drops -20% on day 4; Symbol B stays flat + prices_a = [10.0, 10.0, 10.0, 8.0] + [8.0] * 46 + prices_b = [10.0] * 50 + datasets = {"AAA": _make_df(dates, prices_a), "BBB": _make_df(dates, prices_b)} + strategy = { + "portfolio": {"rebalance": "monthly", "weighting": "equal"}, + "dca": {"frequency": "monthly", "amount": 2_000}, + "exit": {"stop_loss": -0.10}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + } + res = backtest.simulate_portfolio(datasets, strategy, capital=10_000, start="2025-01-03") + a_trades = [t for t in res["trades"] if t["symbol"] == "AAA"] + assert len(a_trades) == 2 + assert a_trades[0]["type"] == "buy" + assert a_trades[1]["type"] == "sell" and "止损" in a_trades[1]["reason"] + assert all(h["symbol"] != "AAA" for h in res["final_holdings"]) + + +def test_blocked_dca_contribution_retries_on_next_tradable_bar(): + dates = pd.bdate_range("2025-01-02", periods=30) + # 2025-02-03 is the first business day of February (index 22) -> block trading via volume=0 on that bar only + feb_idx = next(i for i, d in enumerate(dates) if d.month == 2) + df = _make_df(dates, np.full(len(dates), 10.0)) + df.loc[feb_idx, "volume"] = 0 + strategy = { + "portfolio": {"rebalance": "none", "weighting": "equal"}, + "dca": {"frequency": "monthly", "amount": 5_000}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + } + res = backtest.simulate_portfolio({"AAPL": df}, strategy, capital=10_000, start="2025-01-03") + assert res["execution"]["blocked_orders"] == 1 + assert res["execution"]["unfilled_order"] is False + # Initial 1000 shares + retried 500 shares deployed on next tradable bar (and never doubled) + assert res["final_holdings"][0]["shares"] == 1500 + assert res["final_cash"] == 0.0 + dca_buys = [t for t in res["trades"] if t["type"] == "buy" and "定期定投" in t["reason"]] + assert len(dca_buys) == 1 and dca_buys[0]["date"] == str(dates[feb_idx + 1].date()) + + +def test_rebalance_plus_dca_retains_blocked_symbol_budget_until_tradable(): + dates = pd.bdate_range("2025-01-02", periods=30) + feb_idx = next(i for i, d in enumerate(dates) if d.month == 2) + df = _make_df(dates, np.full(len(dates), 10.0)) + df.loc[feb_idx, "volume"] = 0 + strategy = { + "portfolio": {"rebalance": "monthly", "weighting": "equal"}, + "dca": {"frequency": "monthly", "amount": 100}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + } + res = backtest.simulate_portfolio({"AAPL": df}, strategy, capital=1_000, start="2025-01-03") + assert res["execution"]["blocked_orders"] == 1 + assert res["execution"]["unfilled_order"] is False + # Jan 100 shares + Feb 10 shares deployed on next tradable bar after rebalance bar was suspended + assert res["final_holdings"][0]["shares"] == 110 + assert res["final_cash"] == 0.0 + + # If the suspended bar is the final bar, unfilled_order stays True + df_end = df.iloc[: feb_idx + 1].copy() + res_end = backtest.simulate_portfolio({"AAPL": df_end}, strategy, capital=1_000, start="2025-01-03") + assert res_end["execution"]["unfilled_order"] is True + assert res_end["final_cash"] == 100.0 + + +def test_rebalance_clears_overweight_missing_bar_dca_and_reserves_cash_for_suspended_underweight(): + dates = pd.bdate_range("2025-01-02", periods=30) + feb_idx = next(i for i, d in enumerate(dates) if d.month == 2) + + # Case 1: Overweight symbol (rises to 30 before rebalance) with missing bar on rebalance date must NOT keep DCA budget + aapl_prices = [10.0] * (feb_idx - 1) + [30.0] * (len(dates) - feb_idx + 1) + msft_prices = [10.0] * len(dates) + df_aapl_missing = _make_df(dates, aapl_prices).drop(index=feb_idx).reset_index(drop=True) + df_msft = _make_df(dates, msft_prices) + res_ow = backtest.simulate_portfolio( + {"AAPL": df_aapl_missing, "MSFT": df_msft}, + { + "portfolio": {"rebalance": "monthly", "weighting": "custom", "weights": {"AAPL": 0.25, "MSFT": 0.25}}, + "dca": {"frequency": "monthly", "amount": 200}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + }, + capital=1_000, + start="2025-01-03", + ) + aapl_buys = [t for t in res_ow["trades"] if t["symbol"] == "AAPL" and t["type"] == "buy"] + assert len(aapl_buys) == 1, "overweight missing-bar symbol must not DCA-buy on next bar" + + # Case 2: 3 equal-weight symbols (AAPL, MSFT, NVDA), monthly rebalance + monthly DCA 99. + # NVDA surges (overweight) and is suspended alongside underweight MSFT on rebalance day. + # AAPL must leave MSFT's $33 DCA cash reserved so MSFT executes on resume (and unfilled_order becomes False). + df_aapl = _make_df(dates, [10.0] * len(dates)) + df_msft2 = _make_df(dates, [10.0] * len(dates)) + df_nvda = _make_df(dates, [10.0] * feb_idx + [20.0] * (len(dates) - feb_idx)) + df_msft2.loc[feb_idx, "volume"] = 0 + df_nvda.loc[feb_idx, "volume"] = 0 + res_3 = backtest.simulate_portfolio( + {"AAPL": df_aapl, "MSFT": df_msft2, "NVDA": df_nvda}, + { + "portfolio": {"rebalance": "monthly", "weighting": "equal"}, + "dca": {"frequency": "monthly", "amount": 99}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + }, + capital=300, + start="2025-01-03", + ) + msft_feb_buys = [ + t for t in res_3["trades"] if t["symbol"] == "MSFT" and t["date"] == str(dates[feb_idx + 1].date()) + ] + assert len(msft_feb_buys) == 1 and msft_feb_buys[0]["shares"] >= 3 + assert res_3["execution"]["unfilled_order"] is False + + # Case 3: MSFT is underweight & suspended on feb_idx (price=10), then resumes at price=100 (> $33 budget) -> unfilled_order stays True + df_msft_expensive = _make_df(dates, [10.0] * (feb_idx + 1) + [100.0] * (len(dates) - feb_idx - 1)) + df_msft_expensive.loc[feb_idx, "volume"] = 0 + res_unfilled = backtest.simulate_portfolio( + {"AAPL": df_aapl, "MSFT": df_msft_expensive, "NVDA": df_nvda}, + { + "portfolio": {"rebalance": "monthly", "weighting": "equal"}, + "dca": {"frequency": "monthly", "amount": 99}, + "simulation": {"execution": "next_open", "slippage": 0.0, "commission": 0.0, "stamp_tax": 0.0}, + }, + capital=300, + start="2025-01-03", + ) + assert res_unfilled["execution"]["unfilled_order"] is True diff --git a/tests/test_capabilities.py b/tests/test_capabilities.py index 754b53d..98c6b44 100644 --- a/tests/test_capabilities.py +++ b/tests/test_capabilities.py @@ -13,7 +13,8 @@ def test_hk_rejects_a_share_only_tools(self): unsupported_tools = {u["tool"] for u in result["unsupported"]} assert "get_chip_distribution" in unsupported_tools assert "get_capital_flow" in unsupported_tools - assert "screen_risk" in unsupported_tools + assert "screen_risk" in result["supported"] + assert "get_sector_rankings" in result["supported"] # kline is universal assert "get_kline" in result["supported"] assert "get_social_sentiment" in result["supported"] diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py index b54ce4d..acf06d0 100644 --- a/tests/test_diagnostics.py +++ b/tests/test_diagnostics.py @@ -144,6 +144,93 @@ def test_baostock_is_listed_in_a_share_diagnostics(self): providers = {p["name"] for p in diagnostics.diagnose("A")["markets"][0]["providers"]} assert "baostock" in providers + def test_services_and_summary_cover_search_sec_sentiment_and_tradingview(self, monkeypatch): + for env_key in ("TAVILY_API_KEY", "BRAVE_API_KEY", "SERPAPI_KEY", "BOCHA_API_KEY", "SEARXNG_BASE_URLS"): + monkeypatch.delenv(env_key, raising=False) + monkeypatch.setenv("TAVILY_API_KEY", "fake-key") + monkeypatch.setenv("SEC_USER_AGENT", "app user@example.com") + monkeypatch.delenv("SENTIMENT_API_KEY", raising=False) + res = diagnostics.diagnose("HK") + hk_providers = {p["name"] for p in res["markets"][0]["providers"]} + assert "tradingview" in hk_providers + svc = {s["name"]: s for s in res["services"]} + assert svc["tavily"]["available"] is True + assert svc["sec_edgar"]["available"] is True + assert svc["adanos_sentiment"]["available"] is False + assert svc["cninfo"]["available"] is True + assert svc["hkexnews"]["available"] is True + assert res["summary"]["search_engines_ready"] == ["tavily"] + assert res["summary"]["sec_edgar_ready"] is True + assert res["summary"]["sentiment_api_ready"] is False + assert res["meta"]["probed"] is False + + def test_sec_user_agent_without_email_is_reported_invalid(self, monkeypatch): + monkeypatch.setenv("SEC_USER_AGENT", "stock-analysis-plugin") + res = diagnostics.diagnose("US") + sec = next(s for s in res["services"] if s["name"] == "sec_edgar") + assert sec["available"] is False + assert "invalid SEC_USER_AGENT" in (sec["reason"] or "") + assert res["summary"]["sec_edgar_ready"] is False + assert any("invalid SEC_USER_AGENT" in w for w in res["meta"]["warnings"]) + assert not any("SEC_USER_AGENT not set" in w for w in res["meta"]["warnings"]) + + def test_probe_flag_populates_reachability_without_hitting_live_network(self, monkeypatch): + probed = [] + + def fake_probe(name, timeout=4.0): + probed.append(name) + return (True, 12, None) if name != "sina" else (False, None, "connection refused") + + monkeypatch.setattr(diagnostics, "_probe_url", fake_probe) + res = diagnostics.diagnose("A", probe=True) + assert res["meta"]["probed"] is True + assert "tencent" in probed and "sina" in probed + providers = {p["name"]: p for p in res["markets"][0]["providers"]} + assert providers["tencent"]["reachable"] is True + assert providers["tencent"]["latency_ms"] == 12 + assert providers["sina"]["reachable"] is False + assert providers["sina"]["probe_error"] == "connection refused" + + def test_cli_returns_structured_json_when_requests_is_unavailable(self): + import json + import subprocess + import sys + from pathlib import Path + + script = Path(__file__).resolve().parents[1] / "tools" / "diagnostics.py" + # python -S disables site-packages (including requests), verifying diagnostics never crashes on import + proc = subprocess.run( + [sys.executable, "-S", str(script), "check", "--market", "US"], + capture_output=True, + text=True, + timeout=15, + ) + assert proc.returncode == 0, proc.stderr + payload = json.loads(proc.stdout) + sec = next(s for s in payload["services"] if s["name"] == "sec_edgar") + assert sec["available"] is False + assert "requests" in (sec["reason"] or "") + + def test_sec_lazy_import_failure_returns_unavailable_without_traceback(self, monkeypatch): + import builtins + import sys + + monkeypatch.setenv("SEC_USER_AGENT", "app user@example.com") + monkeypatch.delitem(sys.modules, "sec_edgar", raising=False) + real_import = builtins.__import__ + + def fail_sec_import(name, *args, **kwargs): + if name == "sec_edgar": + raise ImportError("missing transitive dependency urllib3") + return real_import(name, *args, **kwargs) + + monkeypatch.setattr(builtins, "__import__", fail_sec_import) + res = diagnostics.diagnose("US") + sec = next(s for s in res["services"] if s["name"] == "sec_edgar") + assert sec["available"] is False + assert "sec_edgar import failed" in (sec["reason"] or "") + assert any("sec_edgar import failed" in w for w in res["meta"]["warnings"]) + if __name__ == "__main__": import subprocess diff --git a/tests/test_dsh_dashboard.ts b/tests/test_dsh_dashboard.ts index 109d42e..9607aca 100644 --- a/tests/test_dsh_dashboard.ts +++ b/tests/test_dsh_dashboard.ts @@ -568,6 +568,37 @@ try { } await handler.settle(); + // ---------- name/pinyin fuzzy search endpoint ---------- + { + const searchFile = join(temp, "search", "watchlist.json"); + writeWatchlist(searchFile, []); + const searchHandler = createDashboardHandler({ + runPy: async (script, args) => { + if (script === "name_resolver.py" && args[0] == "resolve") { + return JSON.stringify([ + { code: "600519", name: "贵州茅台", score: 1.0 }, + { code: "00700.HK", name: "腾讯控股", score: 0.9 }, + ]); + } + return "{}"; + }, + watchlistFile: searchFile, + webDir, + }); + const emptyRes = await call(searchHandler, get("/stock-analysis/api/search?q=")); + assert.equal(emptyRes.status(), 200); + assert.deepEqual(emptyRes.json().results, []); + const hitRes = await call(searchHandler, get("/stock-analysis/api/search?q=%E8%8C%85%E5%8F%B0")); + assert.equal(hitRes.status(), 200); + assert.deepEqual(hitRes.json().results, [ + { symbol: "600519", name: "贵州茅台", region: "cn", score: 1 }, + { symbol: "00700.HK", name: "腾讯控股", region: "hk", score: 0.9 }, + ]); + const tooLong = await call(searchHandler, get(`/stock-analysis/api/search?q=${"a".repeat(65)}`)); + assert.equal(tooLong.status(), 400); + searchHandler.dispose(); + } + // ---------- resident warmer lifecycle ---------- { const warmFile = join(temp, "warm", "watchlist.json"); diff --git a/tests/test_dsh_discovery.ts b/tests/test_dsh_discovery.ts index cf32eb1..19281bf 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, 75); + assert.equal(eager.tools.schemas().length, 76); assert.equal(eager.tools.get("stock_tool_search"), undefined); - assert.equal((await eager.systemPrompt.assemble({scope: {}})).tools.length, 75); + assert.equal((await eager.systemPrompt.assemble({scope: {}})).tools.length, 76); } 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 1c40668..adc6726 100644 --- a/tests/test_dsh_integration.ts +++ b/tests/test_dsh_integration.ts @@ -188,6 +188,7 @@ const sampleArgs: Record> = { get_valuation_history: { symbol: "600519" }, get_index_valuation: { symbol: "000300" }, get_cds_index: { source: "cn", days: 60, index: "民企", tenor: "1Y" }, + get_macro_anchors: { group: "rates", days: 60 }, get_earnings_calendar: { report_date: "2026-09-30", symbol: "600519" }, get_shareholder_structure: { symbol: "600519", report_date: "2026-06-30" }, get_etf_details: { symbol: "510300", benchmark: "sh000300" }, diff --git a/tests/test_dsh_web_poll.ts b/tests/test_dsh_web_poll.ts index fe317f4..5d9cc78 100644 --- a/tests/test_dsh_web_poll.ts +++ b/tests/test_dsh_web_poll.ts @@ -30,7 +30,7 @@ function element() { }, append(...nodes: unknown[]) { this.children.push(...nodes); }, appendChild(node: unknown) { this.children.push(node); }, - replaceChildren() { this.children.length = 0; }, + replaceChildren(...nodes: unknown[]) { this.children.length = 0; this.children.push(...nodes); }, remove() {}, setAttribute() {}, focus() {}, scrollBy() {}, scrollIntoView() {}, querySelector() { return element(); }, @@ -58,9 +58,12 @@ const document = { addEventListener() {}, }; const windowListeners = new Map void>>(); +const postedMessages: unknown[] = []; const window = { innerWidth: 1024, parent: null as unknown, + prompt: undefined as ((msg?: string, def?: string) => string | null) | undefined, + postMessage(msg: unknown) { postedMessages.push(msg); }, addEventListener(type: string, fn: (event: unknown) => void) { windowListeners.set(type, [...(windowListeners.get(type) ?? []), fn]); }, @@ -71,6 +74,19 @@ let resolveFirst!: (value: unknown) => void; const firstSnapshot = new Promise(resolve => { resolveFirst = resolve; }); const snapshotCalls: string[] = []; const writeCalls: unknown[] = []; +const searchCalls: string[] = []; +const pendingSearch: { resolve?: (value: unknown) => void } = {}; +let holdNextSearch = false; +const copiedTexts: string[] = []; +let clipboardShouldReject = false; +const navigatorMock = { + clipboard: { + writeText: async (text: string) => { + if (clipboardShouldReject) throw new Error("clipboard denied"); + copiedTexts.push(text); + }, + }, +}; const fundAndAdvisor = [ { symbol: "018147", region: "fund", @@ -102,6 +118,21 @@ async function fetch(path: string, options: { method?: string; body?: string } = writeCalls.push(JSON.parse(options.body ?? "{}")); return { ok: true, status: 200, json: async () => ({ symbols: ["AAPL"] }) }; } + if (path.startsWith("./api/search")) { + searchCalls.push(path); + const body = { query: path, results: [{ symbol: "600519", name: "贵州茅台", region: "cn", score: 1 }] }; + if (holdNextSearch) { + holdNextSearch = false; + const deferred = new Promise(resolve => { pendingSearch.resolve = resolve; }); + const value = await deferred; + return { ok: true, status: 200, json: async () => value }; + } + return { + ok: true, + status: 200, + json: async () => body, + }; + } throw new Error("unexpected fetch: " + path); } @@ -110,6 +141,7 @@ let nextTimer = 1; const sandbox = { document, window, + navigator: navigatorMock, location: { search: "", origin: "http://dashboard.local" }, localStorage: { getItem: (key: string) => storage.get(key) ?? null, @@ -180,4 +212,103 @@ for (const listener of windowListeners.get("message") ?? []) { } assert.equal(document.documentElement.style.props.has("--bg"), false, "omitted theme token is removed"); -console.log("dsh web: watchlist polling, fund NAV, advisor rows, undo and theme cleanup passed"); +// Quick analyze copies prompt to clipboard into #watch-toast WITHOUT clobbering an active #watch-undo bar. +for (const listener of byId("rows").listeners.get("click") ?? []) { + listener({ target: { closest: (sel: string) => (sel === "button[data-remove]" ? removeBtn : null) } }); +} +await new Promise(resolve => setTimeout(resolve, 10)); +assert.equal(byId("watch-undo").hidden, false, "undo bar visible before toast"); + +const analyzeBtn = { dataset: { analyze: "018147", label: "建信新兴市场混合(QDII)C" } }; +for (const listener of byId("rows").listeners.get("click") ?? []) { + listener({ target: { closest: (sel: string) => (sel === "button[data-analyze]" ? analyzeBtn : null) } }); +} +await new Promise(resolve => setTimeout(resolve, 10)); +assert.equal(postedMessages.some(m => (m as { type?: string }).type === "stock-analysis:ask-agent"), false); +assert.equal(copiedTexts.length, 1); +assert(copiedTexts[0].includes("018147")); +assert.equal(byId("watch-toast").hidden, false, "toast renders in dedicated #watch-toast"); +assert(JSON.stringify(byId("watch-toast").children).includes("已复制")); +assert.equal(byId("watch-undo").hidden, false, "toast must not hide active undo bar"); +assert(JSON.stringify(byId("watch-undo").children).includes("撤销"), "undo button preserved while toast is shown"); + +clipboardShouldReject = true; +for (const listener of byId("rows").listeners.get("click") ?? []) { + listener({ target: { closest: (sel: string) => (sel === "button[data-analyze]" ? analyzeBtn : null) } }); +} +await new Promise(resolve => setTimeout(resolve, 10)); +assert(JSON.stringify(byId("watch-toast").children).includes("剪贴板不可用")); +clipboardShouldReject = false; + +// Group & price alert thresholds: whitespace like '>= 1.5' parses cleanly, invalid non-empty input preserves existing alert. +window.prompt = () => "核心"; +const groupBtn = { dataset: { group: "018147", label: "建信新兴市场混合(QDII)C" } }; +for (const listener of byId("rows").listeners.get("click") ?? []) { + listener({ target: { closest: (sel: string) => (sel === "button[data-group]" ? groupBtn : null) } }); +} +window.prompt = () => ">= 1.5"; +const alertBtn = { dataset: { alert: "018147", label: "建信新兴市场混合(QDII)C" } }; +for (const listener of byId("rows").listeners.get("click") ?? []) { + listener({ target: { closest: (sel: string) => (sel === "button[data-alert]" ? alertBtn : null) } }); +} +const updatedRows = JSON.stringify(byId("rows").children); +assert(updatedRows.includes("#核心"), "custom group badge rendered"); +assert(updatedRows.includes("触达 ≥ 1.5"), "triggered price alert badge rendered with whitespace in input"); + +window.prompt = () => "not-a-valid-alert"; +for (const listener of byId("rows").listeners.get("click") ?? []) { + listener({ target: { closest: (sel: string) => (sel === "button[data-alert]" ? alertBtn : null) } }); +} +assert(JSON.stringify(byId("watch-toast").children).includes("提醒格式无效"), "invalid alert format notifies user in toast"); +assert(JSON.stringify(byId("watch-undo").children).includes("撤销"), "invalid alert toast preserves undo bar"); +assert(JSON.stringify(byId("rows").children).includes("触达 ≥ 1.5"), "existing alert preserved after invalid input"); + +// Full pinyin search reaches /api/search, switching to another valid query clears stale suggestions immediately. +byId("symbol-input").value = "guizhoumaotai"; +for (const listener of byId("symbol-input").listeners.get("input") ?? []) { + listener({}); +} +const pinyinTimer = [...timers.values()].at(-1) as (() => void) | undefined; +if (typeof pinyinTimer === "function") pinyinTimer(); +await new Promise(resolve => setTimeout(resolve, 10)); +assert(searchCalls.some(p => p.includes("guizhoumaotai")), "full pinyin reaches /api/search"); +assert(JSON.stringify(byId("search-results").children).includes("贵州茅台")); + +// Switching query to "腾讯" clears the previous "贵州茅台" suggestions during the 250ms debounce window. +byId("symbol-input").value = "腾讯"; +for (const listener of byId("symbol-input").listeners.get("input") ?? []) { + listener({}); +} +assert.equal(byId("search-results").hidden, true, "switching valid query immediately hides stale suggestions"); +assert.equal(byId("search-results").children.length, 0, "switching valid query clears stale suggestion buttons"); + +const beforeCodeCount = searchCalls.length; +byId("symbol-input").value = "600519"; +for (const listener of byId("symbol-input").listeners.get("input") ?? []) { + listener({}); +} +assert.equal(byId("search-results").hidden, true, "exact code hides search results immediately"); +assert.equal(searchCalls.length, beforeCodeCount, "exact code does not trigger /api/search"); + +const beforeDelayedCount = searchCalls.length; +holdNextSearch = true; +byId("symbol-input").value = "茅台"; +for (const listener of byId("symbol-input").listeners.get("input") ?? []) { + listener({}); +} +const delayedTimer = [...timers.values()].at(-1) as (() => void) | undefined; +if (typeof delayedTimer === "function") delayedTimer(); +await new Promise(resolve => setTimeout(resolve, 5)); +assert.equal(searchCalls.length, beforeDelayedCount + 1, "delayed search request must start before clearing input"); +assert.equal(typeof pendingSearch.resolve, "function", "delayed search promise resolver must be registered"); +// Clear input before the in-flight search finishes. +byId("symbol-input").value = ""; +for (const listener of byId("symbol-input").listeners.get("input") ?? []) { + listener({}); +} +assert.equal(byId("search-results").hidden, true); +pendingSearch.resolve!({ query: "茅台", results: [{ symbol: "600519", name: "贵州茅台", region: "cn", score: 1 }] }); +await new Promise(resolve => setTimeout(resolve, 10)); +assert.equal(byId("search-results").hidden, true, "stale search response must not reopen cleared dropdown"); + +console.log("dsh web: watchlist polling, fund NAV, advisor rows, search, groups, alerts, analyze, undo and theme cleanup passed"); diff --git a/tests/test_gather.py b/tests/test_gather.py index f861e65..29fba00 100644 --- a/tests/test_gather.py +++ b/tests/test_gather.py @@ -100,12 +100,10 @@ def test_correct_args_for_social_sentiment(self, mock_run): @patch("tools.gather._run") def test_error_json_from_new_legs_passes_through(self, mock_run): - """chip_distribution is A-share-only and sentiment degrades without API keys — - their {"error": ...}/note payloads are normal data, relayed untouched.""" + """chip_distribution and capital_flow are A-share-only so non-A skips spawning them; + sentiment degrades without API keys and its payload is relayed untouched.""" def side_effect(script, args, **kwargs): - if "chip_distribution" in args: - return '{"error": "chip_distribution only available for A-shares"}' if "sentiment" in args: return '{"symbol": "AAPL", "sources": {}, "note": "No sentiment data available."}' return None @@ -113,7 +111,20 @@ def side_effect(script, args, **kwargs): mock_run.side_effect = side_effect result = gather_analysis("AAPL") assert result["chip_distribution"] == {"error": "chip_distribution only available for A-shares"} + assert result["capital_flow"] == {"error": "capital_flow only available for A-shares"} assert result["social_sentiment"]["sources"] == {} + spawned = [c.args[1][0] for c in mock_run.call_args_list if c.args[0] == "stock_data.py"] + assert "chip_distribution" not in spawned + assert "capital_flow" not in spawned + + @patch("tools.gather._run") + def test_jp_skips_a_share_and_risk_subprocesses(self, mock_run): + mock_run.return_value = None + result = gather_analysis("7203.T") + assert "error" in result["capital_flow"] + assert "error" in result["chip_distribution"] + assert "error" in result["risk"] + assert not any(c.args[0] == "risk_screening.py" for c in mock_run.call_args_list) @patch("tools.gather._run") def test_correct_args_for_quote(self, mock_run): @@ -312,7 +323,7 @@ def test_no_command_exits(self): class TestGatherFundamental: - @pytest.mark.parametrize("symbol", ["AAPL", "00700.HK", "7203.T"]) + @pytest.mark.parametrize("symbol", ["7203.T", "005930.KS", "2330.TW"]) @patch("tools.gather._run") def test_non_a_market_does_not_receive_chinese_sectors(self, mock_run, symbol): mock_run.return_value = None @@ -320,6 +331,16 @@ def test_non_a_market_does_not_receive_chinese_sectors(self, mock_run, symbol): assert "error" in result["sector_rankings"] assert not any(c.args[1][0] == "sector_rankings" for c in mock_run.call_args_list) + @pytest.mark.parametrize("symbol,market", [("AAPL", "US"), ("00700.HK", "HK")]) + @patch("tools.gather._run") + def test_hk_us_fundamental_requests_own_market_sectors(self, mock_run, symbol, market): + mock_run.return_value = '{"top": [], "bottom": []}' + gather_fundamental(symbol) + sector_calls = [c.args for c in mock_run.call_args_list if c.args[1][0] == "sector_rankings"] + assert sector_calls == [ + ("stock_data.py", ["sector_rankings", "--market", market, "--top", "5", "--direction", "both"]) + ] + @patch("tools.gather._run") def test_returns_all_keys(self, mock_run): mock_run.return_value = '{"data": "value"}' diff --git a/tests/test_hermes_integration.py b/tests/test_hermes_integration.py index 2debfc8..da49c22 100644 --- a/tests/test_hermes_integration.py +++ b/tests/test_hermes_integration.py @@ -122,6 +122,7 @@ def test_wheel_declares_all_shared_runtime_dependencies(): "get_valuation_history", "get_index_valuation", "get_cds_index", + "get_macro_anchors", "get_earnings_calendar", "get_shareholder_structure", "get_etf_details", diff --git a/tests/test_macro_data.py b/tests/test_macro_data.py new file mode 100644 index 0000000..b6c378b --- /dev/null +++ b/tests/test_macro_data.py @@ -0,0 +1,102 @@ +"""Offline tests for tools/macro_data.py (rates, FX, risk-appetite anchors).""" + +import json +import subprocess +import sys +from pathlib import Path + +import pandas as pd +import pytest + +from tools import macro_data + + +@pytest.fixture(autouse=True) +def isolated_cache(tmp_path, monkeypatch): + import _cache + + monkeypatch.setattr(_cache, "CACHE_DIR", tmp_path) + + +def test_macro_anchors_all_groups_and_derived_spreads(monkeypatch): + idx = pd.to_datetime(["2026-11-20", "2026-11-21", "2026-11-24"]) + series_map = { + "^TNX": [4.20, 4.25, 4.30], # Yahoo ^TNX already returns percent-scale yields (e.g. 4.30 -> 4.30%) + "DX-Y.NYB": [104.0, 104.5, 105.0], + "CNH=X": [7.20, 7.22, 7.25], + "HKD=X": [7.78, 7.78, 7.80], + "^VIX": [16.0, 17.5, 18.0], + "GC=F": [2650.0, 2680.0, 2700.0], + "CL=F": [70.0, 71.0, 72.0], + } + + def fake_yf_download(ticker, **kwargs): + return pd.DataFrame({"Close": series_map[ticker]}, index=idx) + + import yfinance as yf + + monkeypatch.setattr(yf, "download", fake_yf_download) + monkeypatch.setattr( + macro_data, + "_fetch_fred_series", + lambda sid, days: [("2026-11-20", 3.90), ("2026-11-24", 4.00)] if sid == "DGS2" else [], + ) + monkeypatch.setattr( + macro_data, + "_fetch_cn_us_yields_akshare", + lambda days: {"cn_10y": [("2026-11-20", 2.10), ("2026-11-24", 2.15)]}, + ) + + res = macro_data.get_macro_anchors("all", days=30) + assert res["missing"] == [] + assert res["anchors"]["us_10y"]["latest"] == 4.3 + assert res["anchors"]["us_10y"]["unit"] == "percent" + assert res["anchors"]["cn_10y"]["latest"] == 2.15 + assert res["anchors"]["us_2y"]["latest"] == 4.0 + assert res["derived"]["us_cn_10y_spread_bp"] == 215.0 + assert res["derived"]["us_10y_2y_spread_bp"] == 30.0 + assert res["anchors"]["hkdcny"]["latest"] == round(7.25 / 7.80, 4) + assert res["anchors"]["vix"]["latest"] == 18.0 + + +def test_us10y_falls_back_to_fred_when_yfinance_fails(monkeypatch): + import yfinance as yf + + monkeypatch.setattr(yf, "download", lambda *a, **kw: (_ for _ in ()).throw(RuntimeError("yf down"))) + monkeypatch.setattr( + macro_data, + "_fetch_fred_series", + lambda sid, days: [("2026-11-20", 4.10), ("2026-11-24", 4.20)] if sid == "DGS10" else [("2026-11-24", 3.9)], + ) + monkeypatch.setattr( + macro_data, + "_fetch_cn_us_yields_akshare", + lambda days: {"cn_10y": [("2026-11-20", 2.0), ("2026-11-24", 2.05)]}, + ) + + res = macro_data.get_macro_anchors("rates", days=15) + assert res["anchors"]["us_10y"]["source"] == "fred" + assert res["anchors"]["us_10y"]["latest"] == 4.2 + assert res["meta"]["fallback_used"] is True + + +def test_all_failed_returns_error_and_invalid_inputs_rejected(monkeypatch): + import yfinance as yf + + monkeypatch.setattr(yf, "download", lambda *a, **kw: (_ for _ in ()).throw(RuntimeError("down"))) + res = macro_data.get_macro_anchors("risk", days=10) + assert "error" in res + + assert "error" in macro_data.get_macro_anchors("invalid_group") + assert "error" in macro_data.get_macro_anchors("all", days=1) + assert "error" in macro_data.get_macro_anchors("all", days=30.5) + + +def test_cli_whole_float_days_accepted_and_invalid_days_exits_nonzero(): + script = Path(__file__).resolve().parents[1] / "tools" / "macro_data.py" + proc = subprocess.run([sys.executable, str(script), "anchors", "--days", "1"], capture_output=True, text=True) + assert proc.returncode == 1 + payload = json.loads(proc.stdout) + assert "error" in payload + assert macro_data._parse_int_days(30.0) == 30 + assert macro_data._parse_int_days("30.0") == 30 diff --git a/tests/test_mcp_integration.py b/tests/test_mcp_integration.py index fccc903..4e50ca1 100644 --- a/tests/test_mcp_integration.py +++ b/tests/test_mcp_integration.py @@ -23,17 +23,28 @@ INITIALIZED = {"jsonrpc": "2.0", "method": "notifications/initialized"} -def _session(*messages, raw=""): +def _session(*messages, raw="", extra_args=()): # Keep stdin open until every request is answered: closing it is the MCP shutdown signal. body = raw + "".join(json.dumps(m, ensure_ascii=False) + "\n" for m in messages) expected = raw.count("\n") + sum("id" in m for m in messages) with subprocess.Popen( - [sys.executable, str(SERVER)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, encoding="utf-8" + [sys.executable, str(SERVER), *extra_args], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + encoding="utf-8", ) as proc: try: proc.stdin.write(body) proc.stdin.flush() - responses = [json.loads(proc.stdout.readline()) for _ in range(expected)] # stdout lines are JSON-RPC only + responses = [] + while len(responses) < expected: + line = proc.stdout.readline() + if not line: + break + msg = json.loads(line) + if "id" in msg: + responses.append(msg) proc.stdin.close() assert proc.stdout.read() == "" assert proc.wait(30) == 0 @@ -43,15 +54,19 @@ def _session(*messages, raw=""): return responses -def _by_id(*messages): - return {r["id"]: r for r in _session(*messages)} +def _by_id(*messages, extra_args=()): + return {r["id"]: r for r in _session(*messages, extra_args=extra_args)} def test_initialize_and_tools_list_match_hermes_schemas(): got = _by_id(INIT, INITIALIZED, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}) init = got[1]["result"] assert init["protocolVersion"] == "2025-06-18" - assert init["capabilities"] == {"tools": {"listChanged": False}} + assert init["capabilities"] == { + "tools": {"listChanged": False}, + "prompts": {"listChanged": False}, + "resources": {"subscribe": False, "listChanged": False}, + } assert init["serverInfo"]["name"] == "stock-analysis" listed = got[2]["result"]["tools"] assert len(listed) == len(TOOL_SCHEMAS) @@ -64,6 +79,129 @@ def test_initialize_and_tools_list_match_hermes_schemas(): } +def test_prompts_and_resources_expose_bundled_skills(): + got = _by_id( + INIT, + INITIALIZED, + {"jsonrpc": "2.0", "id": 2, "method": "prompts/list"}, + { + "jsonrpc": "2.0", + "id": 3, + "method": "prompts/get", + "params": {"name": "stock-analysis", "arguments": {"request": "600519"}}, + }, + {"jsonrpc": "2.0", "id": 4, "method": "resources/list"}, + { + "jsonrpc": "2.0", + "id": 5, + "method": "resources/read", + "params": {"uri": "stock-skill://stock-analysis/SKILL.md"}, + }, + {"jsonrpc": "2.0", "id": 6, "method": "resources/read", "params": {"uri": "stock-skill://../../etc/passwd"}}, + { + "jsonrpc": "2.0", + "id": 7, + "method": "resources/read", + "params": {"uri": "stock-schema://report_schema.json"}, + }, + ) + prompts = got[2]["result"]["prompts"] + assert len(prompts) == 21 + assert any(p["name"] == "stock-analysis" for p in prompts) + msg_text = got[3]["result"]["messages"][0]["content"]["text"] + assert "[MCP 执行说明]" in msg_text + assert "stock-schema://report_schema.json" in msg_text + assert "用户请求:600519" in msg_text + assert not msg_text.startswith("---") + resources = got[4]["result"]["resources"] + assert any(r["uri"] == "stock-skill://stock-analysis/SKILL.md" for r in resources) + assert any(r["uri"] == "stock-schema://report_schema.json" for r in resources) + assert "SKILL" in got[5]["result"]["contents"][0]["uri"] + assert got[6]["error"]["code"] == -32602 + schema_content = got[7]["result"]["contents"][0] + assert schema_content["mimeType"] == "application/json" + assert isinstance(json.loads(schema_content["text"]), dict) + + +def test_discovery_and_core_profile_modes(): + with subprocess.Popen( + [sys.executable, str(SERVER), "--discovery"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + encoding="utf-8", + ) as proc: + try: + + def send(msg): + proc.stdin.write(json.dumps(msg, ensure_ascii=False) + "\n") + proc.stdin.flush() + + def read_until(target_id): + notifications = [] + while True: + line = proc.stdout.readline() + assert line, f"EOF waiting for response id={target_id}" + msg = json.loads(line) + if msg.get("id") == target_id: + return msg, notifications + notifications.append(msg) + + send(INIT) + init_resp, _ = read_until(1) + assert init_resp["result"]["capabilities"]["tools"]["listChanged"] is True + + send(INITIALIZED) + send({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}) + list1, _ = read_until(2) + assert [t["name"] for t in list1["result"]["tools"]] == ["stock_tool_search"] + + send( + { + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": {"name": "stock_tool_search", "arguments": {"query": "DCF 宏观", "limit": 5}}, + } + ) + search_resp, notes = read_until(3) + search_payload = json.loads(search_resp["result"]["content"][0]["text"]) + assert search_payload["matched"] >= 1 + assert any(n.get("method") == "notifications/tools/list_changed" for n in notes) + + # Request tools/list strictly after stock_tool_search has finished and replied. + send({"jsonrpc": "2.0", "id": 4, "method": "tools/list"}) + list2, _ = read_until(4) + expanded = [t["name"] for t in list2["result"]["tools"]] + assert "stock_tool_search" in expanded and len(expanded) > 1 + + proc.stdin.close() + assert proc.stdout.read() == "" + assert proc.wait(30) == 0 + finally: + proc.kill() + + core = _by_id( + INIT, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, + { + "jsonrpc": "2.0", + "id": 3, + "method": "prompts/get", + "params": {"name": "stock-analysis", "arguments": {"request": "600519"}}, + }, + extra_args=("--profile", "core"), + ) + core_names = {t["name"] for t in core[2]["result"]["tools"]} + assert len(core_names) == 19 + assert {"get_quote", "get_macro_anchors", "run_backtest", "render_stock_report"} <= core_names + core_prompt = core[3]["result"]["messages"][0]["content"]["text"] + core_preamble = core_prompt.split("\n\n", 1)[0] + assert "--profile core" in core_preamble + assert "render_stock_report" in core_preamble + assert "stock_tool_search" not in core_preamble + + def test_unsupported_protocol_version_gets_server_latest(): init = dict(INIT, params=dict(INIT["params"], protocolVersion="1999-01-01")) assert _by_id(init)[1]["result"]["protocolVersion"] == "2025-11-25" diff --git a/tests/test_openclaw_integration.ts b/tests/test_openclaw_integration.ts index 5bcc609..32f99b2 100644 --- a/tests/test_openclaw_integration.ts +++ b/tests/test_openclaw_integration.ts @@ -58,6 +58,7 @@ const fakeTypebox = { }), String: (opts?: unknown) => ({ __typebox: "string", opts }), Number: (opts?: unknown) => ({ __typebox: "number", opts }), + Integer: (opts?: unknown) => ({ __typebox: "integer", opts }), Null: () => ({ __typebox: "null" }), Boolean: (opts?: unknown) => ({ __typebox: "boolean", opts }), Optional: (schema: unknown) => ({ __typebox: "optional", schema }), @@ -217,6 +218,7 @@ const sampleArgs: Record> = { get_valuation_history: { symbol: "600519" }, get_index_valuation: { symbol: "000300" }, get_cds_index: { source: "cn", days: 60, index: "民企", tenor: "1Y" }, + get_macro_anchors: { group: "rates", days: 60 }, get_earnings_calendar: { report_date: "2026-09-30", symbol: "600519" }, get_shareholder_structure: { symbol: "600519", report_date: "2026-06-30" }, get_etf_details: { symbol: "510300", benchmark: "sh000300" }, diff --git a/tests/test_pi_integration.ts b/tests/test_pi_integration.ts index a137947..5f12e5e 100644 --- a/tests/test_pi_integration.ts +++ b/tests/test_pi_integration.ts @@ -21,6 +21,7 @@ const EXPECTED_TOOLS = [ "get_valuation_history", "get_index_valuation", "get_cds_index", + "get_macro_anchors", "get_earnings_calendar", "get_shareholder_structure", "get_etf_details", diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 0f2844e..d9f2ea2 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -1,5 +1,7 @@ from unittest.mock import patch +import pytest + from tools import risk_screening from tools.risk_screening import _safe_float, check_news_risks, compute_risk @@ -220,3 +222,4027 @@ def collect(script, args, **kwargs): assert result["checks"]["valuation"]["available"] is False assert result["checks"]["technical"]["available"] is False assert result["checks"]["lockup"]["available"] is True + + +def test_hk_risk_screening_uses_disclosures_and_skips_lockup(): + calls = [] + + def fake_run(script, args, **kwargs): + calls.append((script, args)) + if script == "value_data.py" and args[0] == "announcements": + return {"announcements": [{"date": "2026-10-01", "title": "Profit Warning and Trading Halt"}]} + return [] + + result = risk_screening.screen_risk( + "00700.HK", + "Tencent", + inputs={ + "quote": {"pe": 18, "pb": 3}, + "technical": {"signal_score": 65, "buy_signal": "BUY", "trend": {"overall": "bullish"}}, + }, + run=fake_run, + ) + assert result["market"] == "HK" + assert result["data_complete"] is True + assert result["checks"]["lockup"]["applicable"] is False + assert result["checks"]["disclosures"]["available"] is True + assert any(f["category"] == "disclosure" and f["severity"] == "high" for f in result["flags"]) + assert result["veto_buy"] is True + assert not any(args[0] == "lockup" for _, args in calls) + search_queries = [args[1] for script, args in calls if script == "search_intel.py"] + assert any("profit warning" in q for q in search_queries) + + +def test_us_risk_screening_uses_sec_form4_when_configured(monkeypatch): + monkeypatch.setenv("SEC_USER_AGENT", "test-app test@example.com") + calls = [] + + def fake_run(script, args, **kwargs): + calls.append((script, args)) + if script == "sec_edgar.py" and args[0] == "insider_trades": + return { + "since_filing_date": "2026-08-01", + "transactions": [{"code": "S", "transaction_date": f"2026-10-0{i}"} for i in (1, 2, 3)], + } + return [] + + result = risk_screening.screen_risk( + "AAPL", + "Apple", + inputs={ + "quote": {"pe": 28, "pb": 12}, + "technical": {"signal_score": 70, "buy_signal": "BUY", "trend": {"overall": "bullish"}}, + }, + run=fake_run, + ) + assert result["market"] == "US" + assert result["data_complete"] is True + assert result["checks"]["insider_trades"]["sales_90d"] == 3 + assert any(f["category"] == "insider" and f["source"] == "data" for f in result["flags"]) + assert not any(args[0] == "lockup" for _, args in calls) + + +def test_us_risk_screening_without_sec_env_stays_complete(monkeypatch): + monkeypatch.delenv("SEC_USER_AGENT", raising=False) + result = risk_screening.screen_risk( + "AAPL", + "Apple", + inputs={ + "quote": {"pe": 25, "pb": 5}, + "technical": {"signal_score": 60, "buy_signal": "HOLD", "trend": {"overall": "neutral"}}, + }, + run=lambda *a, **kw: [], + ) + assert result["data_complete"] is True + assert result["checks"]["insider_trades"]["configured"] is False + assert any("SEC_USER_AGENT" in w for w in result["warnings"]) + + +def test_us_risk_screening_deduplicates_form4a_amendments_before_veto(monkeypatch): + monkeypatch.setenv("SEC_USER_AGENT", "test-app test@example.com") + orig = [ + { + "form": "4", + "accession": "0001-26-000001", + "transaction_date": f"2026-10-0{i}", + "owners": [{"cik": "123", "name": "Exec A"}], + "security": "Common Stock", + "derivative": False, + "transaction_code": "S", + "shares": 1000, + "price": 150.0, + } + for i in (1, 2, 3) + ] + amended_copies = [dict(row, form="4/A", accession="0001-26-000002") for row in orig] + + def fake_run(script, args, **kwargs): + if script == "sec_edgar.py" and args[0] == "insider_trades": + return { + "since_filing_date": "2026-08-01", + "transactions": orig + amended_copies, + "truncated": False, + "warnings": ["Includes Form 4 amendments; do not double-count original and amended transactions"], + } + return [] + + res = risk_screening.screen_risk( + "AAPL", + "Apple", + inputs={ + "quote": {"pe": 25, "pb": 5}, + "technical": {"signal_score": 60, "buy_signal": "HOLD", "trend": {"overall": "neutral"}}, + }, + run=fake_run, + ) + assert res["checks"]["insider_trades"]["sales_90d"] == 3 + assert res["veto_buy"] is not True + insider_flags = [f for f in res["flags"] if f["category"] == "insider"] + assert len(insider_flags) == 1 and insider_flags[0]["severity"] == "medium" + + # Even when 4/A rows revise shares/price (cannot match 1-to-1), do not trigger buy veto from amended duplicates + revised = [dict(row, form="4/A", accession="0001-26-000003", price=151.0) for row in orig] + res_rev = risk_screening.screen_risk( + "AAPL", + "Apple", + inputs={ + "quote": {"pe": 25, "pb": 5}, + "technical": {"signal_score": 60, "buy_signal": "HOLD", "trend": {"overall": "neutral"}}, + }, + run=lambda script, args, **kw: ( + { + "since_filing_date": "2026-08-01", + "transactions": orig + revised, + "truncated": False, + "warnings": ["Includes Form 4 amendments; do not double-count original and amended transactions"], + } + if script == "sec_edgar.py" + else [] + ), + ) + assert res_rev["veto_buy"] is not True + assert all(f["severity"] != "high" for f in res_rev["flags"]) + + # 6 original S rows where Form 4/A confirms 5 as S and reclassifies the 6th to Gift (G) -> 5 sales, no buy veto + six_orig = [ + { + "form": "4", + "accession": "0001-26-000010", + "transaction_date": f"2026-10-0{i}", + "owners": [{"cik": "123", "name": "Exec A"}], + "security": "Common Stock", + "derivative": False, + "transaction_code": "S", + "shares": 1000, + "price": 150.0, + } + for i in range(1, 7) + ] + amend_reclass = [dict(row, form="4/A", accession="0001-26-000011") for row in six_orig[:5]] + [ + dict(six_orig[5], form="4/A", accession="0001-26-000011", transaction_code="G", direction="other") + ] + res_reclass = risk_screening.screen_risk( + "AAPL", + "Apple", + inputs={ + "quote": {"pe": 25, "pb": 5}, + "technical": {"signal_score": 60, "buy_signal": "HOLD", "trend": {"overall": "neutral"}}, + }, + run=lambda script, args, **kw: ( + { + "since_filing_date": "2026-08-01", + "transactions": six_orig + amend_reclass, + "truncated": False, + "warnings": ["Includes Form 4 amendments; do not double-count original and amended transactions"], + } + if script == "sec_edgar.py" + else [] + ), + ) + assert res_reclass["checks"]["insider_trades"]["sales_90d"] == 5 + assert res_reclass["veto_buy"] is not True + assert all(f["severity"] != "high" for f in res_reclass["flags"]) + + # Successive 4/A accessions reclassifying the same 4th same-day sale to G must be idempotent (3 sales, medium flag) + four_same_day = [ + { + "form": "4", + "accession": "0001-26-000020", + "transaction_date": "2026-10-05", + "owners": [{"cik": "123", "name": "Exec A"}], + "security": "Common Stock", + "derivative": False, + "transaction_code": "S", + "shares": shares, + "price": 150.0, + } + for shares in (100, 200, 300, 400) + ] + amend_g_1 = dict(four_same_day[3], form="4/A", accession="0001-26-000021", transaction_code="G", direction="other") + amend_g_2 = dict(four_same_day[3], form="4/A", accession="0001-26-000022", transaction_code="G", direction="other") + res_idem = risk_screening.screen_risk( + "AAPL", + "Apple", + inputs={ + "quote": {"pe": 25, "pb": 5}, + "technical": {"signal_score": 60, "buy_signal": "HOLD", "trend": {"overall": "neutral"}}, + }, + run=lambda script, args, **kw: ( + { + "since_filing_date": "2026-08-01", + "transactions": four_same_day + [amend_g_1, amend_g_2], + "truncated": False, + "warnings": ["Includes Form 4 amendments; do not double-count original and amended transactions"], + } + if script == "sec_edgar.py" + else [] + ), + ) + assert res_idem["checks"]["insider_trades"]["sales_90d"] == 3 + assert any(f["category"] == "insider" and f["severity"] == "medium" for f in res_idem["flags"]) + + # Unrelated same-day gift (different shares) must NOT remove a confirmed sale or suppress buy veto for 6 sales + unrelated_gift = dict( + six_orig[0], form="4/A", accession="0001-26-000030", transaction_code="G", direction="other", shares=250 + ) + res_gift = risk_screening.screen_risk( + "AAPL", + "Apple", + inputs={ + "quote": {"pe": 25, "pb": 5}, + "technical": {"signal_score": 60, "buy_signal": "HOLD", "trend": {"overall": "neutral"}}, + }, + run=lambda script, args, **kw: ( + { + "since_filing_date": "2026-08-01", + "transactions": six_orig + [unrelated_gift], + "truncated": False, + "warnings": ["Includes Form 4 amendments; do not double-count original and amended transactions"], + } + if script == "sec_edgar.py" + else [] + ), + ) + assert res_gift["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_gift["veto_buy"] is True + + # 2 original sales + 1 Form 4/A restating one sale at a different price -> still 2 sales, NO medium flag + two_orig = six_orig[:2] + restated = dict(two_orig[0], form="4/A", accession="0001-26-000040", price=152.0) + res_restate = risk_screening.screen_risk( + "AAPL", + "Apple", + inputs={ + "quote": {"pe": 25, "pb": 5}, + "technical": {"signal_score": 60, "buy_signal": "HOLD", "trend": {"overall": "neutral"}}, + }, + run=lambda script, args, **kw: ( + { + "since_filing_date": "2026-08-01", + "transactions": two_orig + [restated], + "truncated": False, + "warnings": ["Includes Form 4 amendments; do not double-count original and amended transactions"], + } + if script == "sec_edgar.py" + else [] + ), + ) + assert res_restate["checks"]["insider_trades"]["sales_90d"] == 2 + assert not any(f["category"] == "insider" for f in res_restate["flags"]) + + def _run_us(tx_list): + return risk_screening.screen_risk( + "AAPL", + "Apple", + inputs={ + "quote": {"pe": 25, "pb": 5}, + "technical": {"signal_score": 60, "buy_signal": "HOLD", "trend": {"overall": "neutral"}}, + }, + run=lambda script, args, **kw: ( + { + "since_filing_date": "2026-08-01", + "transactions": tx_list, + "truncated": False, + "warnings": ["Includes Form 4 amendments; do not double-count original and amended transactions"], + } + if script == "sec_edgar.py" + else [] + ), + ) + + # Branch A (Weaxs): 6 orig S + 1 orig Form 4 G (same shares as one S) + 4/A G adding footnote -> keep all 6 S & veto + orig_gift = dict( + six_orig[0], + accession="0001-26-000050", + transaction_code="G", + direction="other", + price=None, + ) + amend_gift_fn = dict( + orig_gift, + form="4/A", + accession="0001-26-000051", + footnotes={ + "F1": "Filing amended solely to add gift recipient footnote.", + "F99": "Unrelated filing footnote that must not affect this row.", + }, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + res_orig_gift = _run_us(six_orig + [orig_gift, amend_gift_fn]) + assert res_orig_gift["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_orig_gift["checks"]["insider_trades"]["available"] is True + assert res_orig_gift["veto_buy"] is True + + # Branch B (Weaxs): 6 orig S (6 shares) + 4/A explicitly correcting 6-share S to 7-share G -> 5 sales, no veto + six_small = [dict(r, shares=6) for r in six_orig] + corr_7g = dict( + six_small[5], + form="4/A", + accession="0001-26-000052", + transaction_code="G", + direction="other", + shares=7, + price=None, + footnotes={ + "F1": "Corrects previously misreported 6-share sale to a 7-share gift.", + "F99": "Inadvertently omitted unrelated transaction on another row.", + }, + footnote_refs={"transactionAmounts/transactionShares/value": ["F1"]}, + ) + res_corr_7g = _run_us(six_small + [corr_7g]) + assert res_corr_7g["checks"]["insider_trades"]["sales_90d"] == 5 + assert res_corr_7g["veto_buy"] is False + + # Branch C (Weaxs): 2 orig same-day S + 4/A explicitly adding omitted 3rd S -> 3 sales, medium flag + two_same = [ + dict(six_orig[0], transaction_date="2026-10-08", shares=100, price=150.0), + dict(six_orig[0], transaction_date="2026-10-08", shares=100, price=150.0), + ] + added_third = dict( + six_orig[0], + form="4/A", + accession="0001-26-000053", + transaction_date="2026-10-08", + shares=100, + price=150.0, + footnotes={ + "F1": "Amends original Form 4 to report an inadvertently omitted third sale.", + "F2": "Corrects an unrelated prior gift row.", + }, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + res_added_third = _run_us(two_same + [added_third]) + assert res_added_third["checks"]["insider_trades"]["sales_90d"] == 3 + assert any(f["category"] == "insider" and f["severity"] == "medium" for f in res_added_third["flags"]) + + # Branch D (CodeRabbit Major): 7 orig S incl. two same-day 100-sh ($10, $20); 4/A #1 G @ $20 + 4/A #2 G @ price=None + # Must remove only the $20 sale (6 remaining, veto preserved), NOT also remove the $10 sale. + seven_orig = [ + dict(six_orig[0], transaction_date="2026-10-09", shares=100, price=10.0), + dict(six_orig[0], transaction_date="2026-10-09", shares=100, price=20.0), + ] + [dict(six_orig[i], transaction_date=f"2026-10-1{i}") for i in range(5)] + g_with_px = dict(seven_orig[1], form="4/A", accession="0001-26-000060", transaction_code="G", direction="other") + g_blank_px = dict( + seven_orig[1], form="4/A", accession="0001-26-000061", transaction_code="G", direction="other", price=None + ) + res_blank_followup = _run_us(seven_orig + [g_with_px, g_blank_px]) + assert res_blank_followup["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_blank_followup["veto_buy"] is True + + # Same-accession blank-price gift BEFORE priced gift removes both $10 and $20 regardless of row order + g_same_blank = dict(g_blank_px, accession="0001-26-000062") + g_same_priced = dict(g_with_px, accession="0001-26-000062") + assert _run_us(seven_orig + [g_same_blank, g_same_priced])["checks"]["insider_trades"]["sales_90d"] == 5 + assert _run_us(seven_orig + [g_same_priced, g_same_blank])["checks"]["insider_trades"]["sales_90d"] == 5 + + # If ONLY the blank-price 4/A exists across two distinct-price candidates ($10 & $20), retain both & flag uncertainty + res_ambig_blank = _run_us(seven_orig + [g_blank_px]) + assert res_ambig_blank["checks"]["insider_trades"]["sales_90d"] == 7 + assert res_ambig_blank["checks"]["insider_trades"]["count_uncertain"] is True + + # Branch E (CodeRabbit Minor 477): 1 orig S + two 4/A accessions each adding a different same-day S -> 3 sales, medium + one_orig = [dict(six_orig[0], transaction_date="2026-10-15", shares=100, price=10.0)] + add_s1 = dict( + one_orig[0], + form="4/A", + accession="0001-26-000070", + shares=200, + price=11.0, + footnotes={"F1": "Reports an inadvertently omitted sale."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + add_s2 = dict( + one_orig[0], + form="4/A", + accession="0001-26-000071", + shares=300, + price=12.0, + footnotes={"F1": "Reports an inadvertently omitted sale."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + res_two_adds = _run_us(one_orig + [add_s1, add_s2]) + assert res_two_adds["checks"]["insider_trades"]["sales_90d"] == 3 + assert any(f["category"] == "insider" and f["severity"] == "medium" for f in res_two_adds["flags"]) + + # Branch F (CodeRabbit Minor 452): 3 orig S + 4/A restating 1st S (new price) + 4/A reclassifying 1st S to G -> 2 sales, no flag + three_orig = six_orig[:3] + restate_first = dict(three_orig[0], form="4/A", accession="0001-26-000080", price=155.0) + reclass_first = dict(three_orig[0], form="4/A", accession="0001-26-000081", transaction_code="G", direction="other") + res_restate_and_gift = _run_us(three_orig + [restate_first, reclass_first]) + assert res_restate_and_gift["checks"]["insider_trades"]["sales_90d"] == 2 + assert not any(f["category"] == "insider" for f in res_restate_and_gift["flags"]) + + # Branch G (CodeRabbit Major 590): 6 confirmed original S + explicitly added 7th S keeps veto_buy=True + seventh_add = dict( + six_orig[0], + form="4/A", + accession="0001-26-000090", + transaction_date="2026-10-20", + footnotes={"F1": "Reports previously omitted sale."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + res_seventh = _run_us(six_orig + [seventh_add]) + assert res_seventh["checks"]["insider_trades"]["sales_90d"] == 7 + assert res_seventh["veto_buy"] is True + + # Branch H: the additional row is unconfirmed in either order after the exact row matches. + orig_single = [dict(six_orig[0], transaction_date="2026-10-21", shares=100, price=150.0)] + amend_155 = dict(orig_single[0], form="4/A", accession="0001-26-000091", price=155.0) + amend_150 = dict(orig_single[0], form="4/A", accession="0001-26-000091", price=150.0) + for ordered in ([amend_155, amend_150], [amend_150, amend_155]): + single_check = _run_us(orig_single + ordered)["checks"]["insider_trades"] + assert single_check["sales_90d"] == 1 + assert single_check["count_uncertain"] is True + # With a 2nd unmatched original on the same day, unannotated amend_155 is uncertain in both row orders (no false 3rd) + orig_pair = orig_single + [dict(six_orig[0], transaction_date="2026-10-21", shares=50, price=160.0)] + for ordered in ([amend_155, amend_150], [amend_150, amend_155]): + res_pair = _run_us(orig_pair + ordered) + assert res_pair["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_pair["checks"]["insider_trades"]["count_uncertain"] is True + + # Branch I (CodeRabbit Minor 608): later 4/A explicitly correcting an earlier 4/A added sale -> 3 sales, not 4 + two_other = six_orig[:2] + add_oct22 = dict( + six_orig[0], + form="4/A", + filing_date="2026-10-23", + accession="0001-26-000092", + transaction_date="2026-10-22", + shares=100, + price=10.0, + footnotes={"F1": "Reports inadvertently omitted sale."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + corr_oct22 = dict( + add_oct22, + filing_date="2026-10-24", + accession="0001-26-000093", + price=11.0, + footnotes={"F1": "Corrects price of previously reported sale to $11."}, + footnote_refs={"transactionAmounts/transactionPricePerShare/value": ["F1"]}, + ) + res_corr_added = _run_us(two_other + [add_oct22, corr_oct22]) + assert res_corr_added["checks"]["insider_trades"]["sales_90d"] == 3 + + +def test_real_sec_form4_xml_boundary_with_risk_screening(monkeypatch): + import sec_edgar + + monkeypatch.setenv("SEC_USER_AGENT", "test-app test@example.com") + orig_xml = """ + 0000320193 + + 0001111111Exec XML + 1CFO + + + + Common Stock + 2026-10-01 + S + + 100 + 150 + D + + + + Common Stock + 2026-10-01 + S + + 50 + 160 + D + + + + """ + amend_xml = """ + 0000320193 + + 0001111111Exec XML + 1CFO + + + + Common Stock + 2026-10-01 + S + + 100 + 150 + D + + + + Common Stock + 2026-10-02 + G + + 25 + D + + + + + Reports an inadvertently omitted sale on 2026-10-01. + Corrects an unrelated separate gift filing. + + Amendment filed to report omitted sale F1 and update F2. + """ + xml_map = {"orig.xml": orig_xml, "amend.xml": amend_xml} + monkeypatch.setattr(sec_edgar, "sec_get", lambda url, as_json=True: xml_map[url.rsplit("/", 1)[-1]]) + orig_rows = sec_edgar.form4( + "0000320193", + { + "accessionNumber": "0000320193-26-000100", + "filingDate": "2026-10-02", + "form": "4", + "primaryDocument": "orig.xml", + }, + ) + amend_rows = sec_edgar.form4( + "0000320193", + { + "accessionNumber": "0000320193-26-000101", + "filingDate": "2026-10-03", + "form": "4/A", + "primaryDocument": "amend.xml", + }, + ) + assert amend_rows[0]["remarks"] == "Amendment filed to report omitted sale F1 and update F2." + assert isinstance(amend_rows[0]["footnote_refs"], dict) + res = risk_screening.screen_risk( + "AAPL", + "Apple", + inputs={ + "quote": {"pe": 25, "pb": 5}, + "technical": {"signal_score": 60, "buy_signal": "HOLD", "trend": {"overall": "neutral"}}, + }, + run=lambda script, args, **kw: ( + { + "since_filing_date": "2026-08-01", + "transactions": orig_rows + amend_rows, + "truncated": False, + "warnings": ["Includes Form 4 amendments; do not double-count original and amended transactions"], + } + if script == "sec_edgar.py" + else [] + ), + ) + assert res["checks"]["insider_trades"]["sales_90d"] == 3 + assert any(f["category"] == "insider" and f["severity"] == "medium" for f in res["flags"]) + + +def test_form4_amendment_remarks_scoping_and_chronological_ledger_chain(monkeypatch): + import sec_edgar + + monkeypatch.setenv("SEC_USER_AGENT", "test-app test@example.com") + base_inputs = { + "quote": {"pe": 25, "pb": 5}, + "technical": {"signal_score": 60, "buy_signal": "HOLD", "trend": {"overall": "neutral"}}, + } + + def _screen(txs, *, since_filing_date="2026-08-01"): + return risk_screening.screen_risk( + "AAPL", + "Apple", + inputs=base_inputs, + run=lambda script, args, **kw: ( + { + "since_filing_date": since_filing_date, + "transactions": txs, + "truncated": False, + "warnings": ["Includes Form 4 amendments; do not double-count original and amended transactions"], + } + if script == "sec_edgar.py" + else [] + ), + ) + + orig_xml = """ + 0000320193 + + 0001111111Exec Chain + + + + Common Stock + 2026-10-01 + S + + 100 + 150 + D + + + + Common Stock + 2026-10-01 + S + + 50 + 160 + D + + + + """ + + # 1. Scoped remarks: Row 1 claims F1 ("omitted sale"), Row 2 has NO footnote and restates orig 50-sh sale, + # filing says "Amending to report one omitted sale". Row 2 must NOT inherit addition intent! + scoped_rem_xml = """ + 0000320193 + + 0001111111Exec Chain + + + + Common Stock + 2026-10-01 + S + + 100 + 150 + D + + + + Common Stock + 2026-10-01 + S + + 50 + 160 + D + + + + + Reports an inadvertently omitted sale on 2026-10-01. + + Amending to report one omitted sale. + """ + + # 2. Mixed remarks without row footnotes: Row 0 restates 100 @ $150 -> $155, Row 1 adds distinct 200 @ $170. + # Must count 3 sales (NOT drop Row 1 as a correction of 50 @ $160) AND mark count_uncertain=True. + mixed_rem_xml = """ + 0000320193 + + 0001111111Exec Chain + + + + Common Stock + 2026-10-01 + S + + 100 + 155 + D + + + + Common Stock + 2026-10-01 + S + + 200 + 170 + D + + + + Corrects one line and adds another omitted transaction. + """ + + # 3. Chronological chain: 2 orig sales -> 4/A #1 adds omitted 101-sh sale -> 4/A #2 corrects that 101-sh sale to G. + add_101_xml = """ + 0000320193 + + 0001111111Exec Chain + + + + Common Stock + 2026-10-03 + S + + 101 + 155 + D + + + + Reports an inadvertently omitted sale. + """ + + reclass_101_xml = """ + 0000320193 + + 0001111111Exec Chain + + + + Common Stock + 2026-10-03 + G + + 101 + D + + + + Corrects previously misreported 101-share sale to a bona fide gift. + """ + + xml_map = { + "orig.xml": orig_xml, + "scoped.xml": scoped_rem_xml, + "mixed.xml": mixed_rem_xml, + "add101.xml": add_101_xml, + "reclass101.xml": reclass_101_xml, + } + monkeypatch.setattr(sec_edgar, "sec_get", lambda url, as_json=True: xml_map[url.rsplit("/", 1)[-1]]) + + def _parse(accn, fdate, form, doc): + return sec_edgar.form4( + "0000320193", + {"accessionNumber": accn, "filingDate": fdate, "form": form, "primaryDocument": doc}, + ) + + orig_rows = _parse("0000320193-26-000300", "2026-10-02", "4", "orig.xml") + scoped_rows = _parse("0000320193-26-000301", "2026-10-03", "4/A", "scoped.xml") + mixed_rows = _parse("0000320193-26-000302", "2026-10-03", "4/A", "mixed.xml") + add101_rows = _parse("0000320193-26-000303", "2026-10-04", "4/A", "add101.xml") + reclass101_rows = _parse("0000320193-26-000304", "2026-10-05", "4/A", "reclass101.xml") + + res_scoped = _screen(orig_rows + scoped_rows) + assert res_scoped["checks"]["insider_trades"]["sales_90d"] == 3 + assert res_scoped["checks"]["insider_trades"]["count_uncertain"] is False + + res_mixed = _screen(orig_rows + mixed_rows) + # Without row-level footnotes or pigeonhole proof, mixed filing-level remarks stay conservative (no speculative +1). + assert res_mixed["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_mixed["checks"]["insider_trades"]["count_uncertain"] is True + assert not any(f["category"] == "insider" for f in res_mixed["flags"]) + + res_chain = _screen(orig_rows + add101_rows + reclass101_rows) + assert res_chain["checks"]["insider_trades"]["sales_90d"] == 2 + assert not any(f["category"] == "insider" for f in res_chain["flags"]) + + # Also test share-changed explicit gift correction against the earlier 4/A added sale (101 -> 102 shares G) + reclass_102_rows = [dict(reclass101_rows[0], shares=102)] + res_chain_share_change = _screen(orig_rows + add101_rows + reclass_102_rows) + assert res_chain_share_change["checks"]["insider_trades"]["sales_90d"] == 2 + assert not any(f["category"] == "insider" for f in res_chain_share_change["flags"]) + + # 4. Restore sale when a later linked 4/A explicitly corrects a previously reclassified gift back to S + three_orig_rows = orig_rows + [dict(orig_rows[0], transaction_date="2026-10-02", shares=75, price=152.0)] + gift_first = dict( + three_orig_rows[0], + form="4/A", + accession="0000320193-26-000305", + filing_date="2026-10-03", + transaction_code="G", + direction="other", + footnotes={"F1": "Corrects previously misreported sale to a gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + restore_first = dict( + three_orig_rows[0], + form="4/A", + accession="0000320193-26-000306", + filing_date="2026-10-04", + footnotes={"F1": "Corrects prior Form 4/A: transaction was a sale, not a gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + res_restore = _screen(three_orig_rows + [gift_first, restore_first]) + assert res_restore["checks"]["insider_trades"]["sales_90d"] == 3 + assert res_restore["checks"]["insider_trades"]["count_uncertain"] is False + assert any(f["category"] == "insider" and f["severity"] == "medium" for f in res_restore["flags"]) + + # Unannotated bare restatement of old S row after reclassification keeps gift state & surfaces uncertainty + bare_restate = dict(three_orig_rows[0], form="4/A", accession="0000320193-26-000307", filing_date="2026-10-04") + res_bare = _screen(three_orig_rows + [gift_first, bare_restate]) + assert res_bare["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_bare["checks"]["insider_trades"]["count_uncertain"] is True + + # 5. Unlinked same-day 4/A row (changed shares AND price, NO footnote/remarks) must NOT inflate count + unlinked_amend = dict( + orig_rows[0], + form="4/A", + accession="0000320193-26-000308", + filing_date="2026-10-03", + shares=75, + price=155.0, + footnotes={}, + footnote_refs={}, + remarks=None, + ) + res_unlinked = _screen(orig_rows + [unlinked_amend]) + assert res_unlinked["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_unlinked["checks"]["insider_trades"]["count_uncertain"] is True + assert not any(f["category"] == "insider" for f in res_unlinked["flags"]) + + # 6. A filing total cannot promote an exact restatement or an unlinked row in a mixed filing. + two_omit_r1 = dict( + orig_rows[0], + form="4/A", + accession="0000320193-26-000309", + filing_date="2026-10-03", + footnotes={"F1": "Reports an omitted sale."}, + footnote_refs={"transactionDate/value": ["F1"]}, + remarks="Amending to report two omitted sales.", + ) + two_omit_r2 = dict( + orig_rows[1], + form="4/A", + accession="0000320193-26-000309", + filing_date="2026-10-03", + footnotes={"F1": "Reports an omitted sale."}, + footnote_refs={}, + remarks="Amending to report two omitted sales.", + ) + assert _screen(orig_rows + [two_omit_r1, two_omit_r2])["checks"]["insider_trades"]["sales_90d"] == 3 + two_omit_r3 = dict(two_omit_r2, shares=275, price=175.0) + res_two_omit_ambig = _screen(orig_rows + [two_omit_r1, two_omit_r2, two_omit_r3]) + assert res_two_omit_ambig["checks"]["insider_trades"]["sales_90d"] == 3 + assert res_two_omit_ambig["checks"]["insider_trades"]["count_uncertain"] is True + + # Single-row 4/A with pure non-sell remarks ("omitted gift") must NOT promote a sell row into a new sale + gift_only_remark_sell = dict( + orig_rows[0], + form="4/A", + accession="0000320193-26-000319", + filing_date="2026-10-03", + shares=275, + price=175.0, + footnotes={}, + footnote_refs={}, + remarks="Amending to report an omitted gift.", + ) + res_gift_remark = _screen(orig_rows + [gift_only_remark_sell]) + assert res_gift_remark["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_gift_remark["checks"]["insider_trades"]["count_uncertain"] is True + assert not any(f["category"] == "insider" for f in res_gift_remark["flags"]) + + # 7. Unrelated same-day original gift must NOT hide a linked correction of a sale to a gift + six_sales = [dict(orig_rows[0], transaction_date=f"2026-10-0{i}") for i in range(1, 7)] + same_day_gift = dict( + six_sales[0], accession="0000320193-26-000310", transaction_code="G", direction="other", price=None + ) + # 7a: priced correction matches sale ($150) rather than orig gift (None) + corr_sale_priced = dict( + six_sales[0], + form="4/A", + accession="0000320193-26-000311", + filing_date="2026-10-08", + transaction_code="G", + direction="other", + price=150.0, + ) + res_corr_priced = _screen(six_sales + [same_day_gift, corr_sale_priced]) + assert res_corr_priced["checks"]["insider_trades"]["sales_90d"] == 5 + assert res_corr_priced["veto_buy"] is False + # 7b: blank-price explicit correction of sale to gift + corr_sale_text = dict( + corr_sale_priced, + price=None, + footnotes={"F1": "Corrects previously misreported sale to a bona fide gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + res_corr_text = _screen(six_sales + [same_day_gift, corr_sale_text]) + assert res_corr_text["checks"]["insider_trades"]["sales_90d"] == 5 + assert res_corr_text["veto_buy"] is False + + # 8. Order-independent sell share-match with multiple distinct-price candidates ($10 and $20) + s_10 = dict(orig_rows[0], transaction_date="2026-10-12", shares=100, price=10.0) + s_20 = dict(orig_rows[0], transaction_date="2026-10-12", shares=100, price=20.0) + a_s11 = dict(s_10, form="4/A", accession="0000320193-26-000312", filing_date="2026-10-13", price=11.0) + a_g10 = dict( + s_10, form="4/A", accession="0000320193-26-000313", filing_date="2026-10-14", transaction_code="G", price=10.0 + ) + a_g11 = dict( + s_10, form="4/A", accession="0000320193-26-000314", filing_date="2026-10-15", transaction_code="G", price=11.0 + ) + res_order_a = _screen([s_10, s_20, a_s11, a_g10, a_g11]) + res_order_b = _screen([s_20, s_10, a_s11, a_g10, a_g11]) + assert res_order_a["checks"]["insider_trades"]["sales_90d"] == res_order_b["checks"]["insider_trades"]["sales_90d"] + assert res_order_a["checks"]["insider_trades"]["count_uncertain"] is True + + # 9. Apply 90-day window to transaction_date (stale late-filed sales must not count or trigger veto) + stale_six = [dict(orig_rows[0], transaction_date=f"2026-05-0{i}", filing_date="2026-10-20") for i in range(1, 7)] + res_stale = _screen(stale_six, since_filing_date="2026-08-01") + assert res_stale["checks"]["insider_trades"]["sales_90d"] == 0 + assert res_stale["veto_buy"] is False + assert not any(f["category"] == "insider" for f in res_stale["flags"]) + + # 10. dateOfOriginalSubmission binds correction to the original filing date rather than another filing's exact match + orig_f1 = dict(orig_rows[0], accession="0000320193-26-000320", filing_date="2026-10-02", shares=100, price=10.0) + orig_f2 = dict(orig_rows[0], accession="0000320193-26-000321", filing_date="2026-10-03", shares=100, price=20.0) + corr_f1_to_20 = dict( + orig_f1, + form="4/A", + accession="0000320193-26-000322", + filing_date="2026-10-04", + original_filing_date="2026-10-02", + price=20.0, + footnotes={"F1": "Corrects sale price to $20."}, + footnote_refs={"transactionAmounts/transactionPricePerShare/value": ["F1"]}, + ) + # Reclassifying the corrected $20 sale from filing 1 via gift on 2026-10-02 leaves filing 2 active (1 sale) + gift_f1 = dict( + corr_f1_to_20, + accession="0000320193-26-000323", + filing_date="2026-10-05", + transaction_code="G", + direction="other", + ) + res_orig_date = _screen([orig_f1, orig_f2, corr_f1_to_20, gift_f1]) + assert res_orig_date["checks"]["insider_trades"]["sales_90d"] == 1 + # When two distinct original filings share the SAME filing_date, date alone cannot separate them -> uncertain + orig_f2_same_day = dict(orig_f2, filing_date="2026-10-02") + res_same_fdate = _screen([orig_f1, orig_f2_same_day, corr_f1_to_20]) + assert res_same_fdate["checks"]["insider_trades"]["count_uncertain"] is True + + # 11. Gift recipient correction that merely mentions a sale must NOT reclassify the same-day sale or drop veto + gift_recip_note = dict( + corr_sale_priced, + price=None, + footnotes={"F1": "Corrects the gift recipient. The gift was reported alongside a sale."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + res_gift_recip = _screen(six_sales + [same_day_gift, gift_recip_note]) + assert res_gift_recip["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_gift_recip["veto_buy"] is True + assert res_gift_recip["checks"]["insider_trades"]["count_uncertain"] is False + + # 12. Price correction on active $20 sale to $10 must NOT restore a previously reclassified $10 gift + pair_10_20_plus_4 = [ + dict(orig_rows[0], transaction_date="2026-10-12", shares=100, price=10.0), + dict(orig_rows[0], transaction_date="2026-10-12", shares=100, price=20.0), + ] + [dict(orig_rows[0], transaction_date=f"2026-10-1{i}", shares=100, price=150.0) for i in range(3, 7)] + reclass_10_g = dict( + pair_10_20_plus_4[0], + form="4/A", + accession="0000320193-26-000330", + filing_date="2026-10-18", + transaction_code="G", + direction="other", + ) + corr_20_to_10 = dict( + pair_10_20_plus_4[1], + form="4/A", + accession="0000320193-26-000331", + filing_date="2026-10-19", + price=10.0, + footnotes={"F1": "Corrects sale price from $20 to $10."}, + footnote_refs={"transactionAmounts/transactionPricePerShare/value": ["F1"]}, + ) + res_no_false_restore = _screen(pair_10_20_plus_4 + [reclass_10_g, corr_20_to_10]) + assert res_no_false_restore["checks"]["insider_trades"]["sales_90d"] == 5 + assert res_no_false_restore["veto_buy"] is False + + # 12b. With a 7th sale on another date (6 confirmed sales remain after $10 becomes a gift), uniquely identified + # price correction ("from $20 to $10") must preserve confirmed buy veto & count_uncertain=False. + pair_10_20_plus_5 = pair_10_20_plus_4 + [dict(orig_rows[0], transaction_date="2026-10-17", shares=100, price=150.0)] + res_preserve_veto = _screen(pair_10_20_plus_5 + [reclass_10_g, corr_20_to_10]) + assert res_preserve_veto["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_preserve_veto["checks"]["insider_trades"]["count_uncertain"] is False + assert res_preserve_veto["veto_buy"] is True + + # 13. Linked transaction-date correction from Aug 3 to Jul 31 (before Aug 1 cutoff) excludes corrected sale + aug_sales = [ + dict(orig_rows[0], accession="0000320193-26-000340", filing_date="2026-08-06", transaction_date="2026-08-05"), + dict(orig_rows[0], accession="0000320193-26-000340", filing_date="2026-08-06", transaction_date="2026-08-04"), + dict(orig_rows[0], accession="0000320193-26-000341", filing_date="2026-08-05", transaction_date="2026-08-03"), + ] + corr_date_to_jul31 = dict( + aug_sales[2], + form="4/A", + accession="0000320193-26-000342", + filing_date="2026-08-07", + original_filing_date="2026-08-05", + transaction_date="2026-07-31", + footnotes={"F1": "Corrects transaction date from 2026-08-03 to 2026-07-31."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + res_date_corr = _screen(aug_sales + [corr_date_to_jul31], since_filing_date="2026-08-01") + assert res_date_corr["checks"]["insider_trades"]["sales_90d"] == 2 + assert not any(f["category"] == "insider" for f in res_date_corr["flags"]) + + # 14. Two original filings on the SAME filing_date (Aug 6) with distinct transaction dates (Aug 3 vs Aug 4): + # stated prior date Aug 3 disambiguates the filing and excludes the corrected Jul 31 sale (2 sales, no flag). + same_fdate_sales = [ + dict(orig_rows[0], accession="0000320193-26-000350", filing_date="2026-08-06", transaction_date="2026-08-03"), + dict(orig_rows[0], accession="0000320193-26-000351", filing_date="2026-08-06", transaction_date="2026-08-04"), + dict(orig_rows[0], accession="0000320193-26-000352", filing_date="2026-08-07", transaction_date="2026-08-05"), + ] + corr_same_fdate = dict( + same_fdate_sales[0], + form="4/A", + accession="0000320193-26-000353", + filing_date="2026-08-08", + original_filing_date="2026-08-06", + transaction_date="2026-07-31", + footnotes={"F1": "Corrects transaction date from 2026-08-03 to 2026-07-31."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + res_same_fdate_disambig = _screen(same_fdate_sales + [corr_same_fdate], since_filing_date="2026-08-01") + assert res_same_fdate_disambig["checks"]["insider_trades"]["sales_90d"] == 2 + assert not any(f["category"] == "insider" for f in res_same_fdate_disambig["flags"]) + + # 15. Unmatched stated prior date (Aug 3 already reclassified to G) must NOT substitute Aug 4 sale! + aug3_aug4_plus_5 = [ + dict(orig_rows[0], filing_date="2026-08-10", transaction_date="2026-08-03", shares=100, price=10.0), + dict(orig_rows[0], filing_date="2026-08-10", transaction_date="2026-08-04", shares=100, price=10.0), + ] + [ + dict(orig_rows[0], filing_date="2026-08-10", transaction_date=f"2026-08-0{i}", shares=100, price=10.0) + for i in range(5, 10) + ] + aug3_to_gift = dict( + aug3_aug4_plus_5[0], + form="4/A", + accession="0000320193-26-000360", + filing_date="2026-08-11", + transaction_code="G", + direction="other", + ) + aug3_date_corr_no_restore = dict( + aug3_aug4_plus_5[0], + form="4/A", + accession="0000320193-26-000361", + filing_date="2026-08-12", + transaction_date="2026-07-31", + footnotes={"F1": "Corrects transaction date from 2026-08-03 to 2026-07-31."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + res_no_sub = _screen(aug3_aug4_plus_5 + [aug3_to_gift, aug3_date_corr_no_restore], since_filing_date="2026-08-01") + assert res_no_sub["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_no_sub["checks"]["insider_trades"]["count_uncertain"] is True + + # 16. Order-independent batch date corrections within one accession (both row orders give identical result) + batch_orig = [ + dict( + orig_rows[0], + accession="0000320193-26-000370", + filing_date="2026-08-05", + transaction_date="2026-08-03", + shares=100, + price=10.0, + ), + dict( + orig_rows[0], + accession="0000320193-26-000370", + filing_date="2026-08-05", + transaction_date="2026-08-03", + shares=200, + price=20.0, + ), + dict( + orig_rows[0], + accession="0000320193-26-000371", + filing_date="2026-08-06", + transaction_date="2026-08-05", + shares=50, + price=15.0, + ), + ] + batch_row1 = dict( + batch_orig[0], + form="4/A", + accession="0000320193-26-000372", + filing_date="2026-08-07", + original_filing_date="2026-08-05", + transaction_date="2026-08-04", + shares=100, + price=10.0, + footnotes={"F1": "Corrects transaction date from 2026-08-03 to 2026-08-04."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + batch_row2 = dict( + batch_orig[1], + form="4/A", + accession="0000320193-26-000372", + filing_date="2026-08-07", + original_filing_date="2026-08-05", + transaction_date="2026-07-31", + shares=300, + price=30.0, + footnotes={"F2": "Corrects 200 shares at $20 on 2026-08-03 to 2026-07-31 (300 shares at $30)."}, + footnote_refs={"transactionDate/value": ["F2"]}, + ) + res_batch_12 = _screen(batch_orig + [batch_row1, batch_row2], since_filing_date="2026-08-01") + res_batch_21 = _screen(batch_orig + [batch_row2, batch_row1], since_filing_date="2026-08-01") + assert res_batch_12["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_batch_21["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_batch_12["checks"]["insider_trades"]["count_uncertain"] is False + assert res_batch_21["checks"]["insider_trades"]["count_uncertain"] is False + # Even when row 2 omits old shares/price, both row orders still produce identical counts and uncertainty flags + batch_row2_bare = dict( + batch_row2, + footnotes={"F2": "Corrects transaction date from 2026-08-03 to 2026-07-31."}, + ) + res_bare_12 = _screen(batch_orig + [batch_row1, batch_row2_bare], since_filing_date="2026-08-01") + res_bare_21 = _screen(batch_orig + [batch_row2_bare, batch_row1], since_filing_date="2026-08-01") + assert res_bare_12["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_bare_21["checks"]["insider_trades"]["sales_90d"] == 2 + assert ( + res_bare_12["checks"]["insider_trades"]["count_uncertain"] + == res_bare_21["checks"]["insider_trades"]["count_uncertain"] + is True + ) + + # 17. Thousands-separated prior price ("from $1,250 to $1,200") preserves confirmed 6-sale buy veto + six_high_px = [dict(orig_rows[0], transaction_date=f"2026-10-0{i}", shares=100, price=1250.0) for i in range(1, 7)] + corr_grouped_px = dict( + six_high_px[0], + form="4/A", + accession="0000320193-26-000380", + filing_date="2026-10-10", + price=1200.0, + footnotes={"F1": "Corrects sale price from $1,250 to $1,200."}, + footnote_refs={"transactionAmounts/transactionPricePerShare/value": ["F1"]}, + ) + res_grouped_px = _screen(six_high_px + [corr_grouped_px]) + assert res_grouped_px["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_grouped_px["checks"]["insider_trades"]["count_uncertain"] is False + assert res_grouped_px["veto_buy"] is True + + # 18. Same-day multi-accession filings on Aug 6 (both Aug 3 sales: 100@$10 vs 200@$20) disambiguated by old shares/price + same_day_two_acc = [ + dict( + orig_rows[0], + accession="0000320193-26-000381", + filing_date="2026-08-06", + transaction_date="2026-08-03", + shares=100, + price=10.0, + ), + dict( + orig_rows[0], + accession="0000320193-26-000382", + filing_date="2026-08-06", + transaction_date="2026-08-03", + shares=200, + price=20.0, + ), + dict( + orig_rows[0], + accession="0000320193-26-000383", + filing_date="2026-08-07", + transaction_date="2026-08-05", + shares=50, + price=15.0, + ), + ] + move_200_jul31 = dict( + same_day_two_acc[1], + form="4/A", + accession="0000320193-26-000384", + filing_date="2026-08-08", + original_filing_date="2026-08-06", + transaction_date="2026-07-31", + shares=300, + price=30.0, + footnotes={"F1": "Corrects 200 shares at $20 on 2026-08-03 to 2026-07-31 (300 shares at $30)."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + res_two_acc_disambig = _screen(same_day_two_acc + [move_200_jul31], since_filing_date="2026-08-01") + assert res_two_acc_disambig["checks"]["insider_trades"]["sales_90d"] == 2 + assert not any(f["category"] == "insider" for f in res_two_acc_disambig["flags"]) + + # 19. Explicit share+price change (200@$20 -> 100@$30) alongside same-day 100@$10 + 4 others preserves buy veto + six_share_change = [ + dict(orig_rows[0], transaction_date="2026-10-12", shares=100, price=10.0), + dict(orig_rows[0], transaction_date="2026-10-12", shares=200, price=20.0), + ] + [dict(orig_rows[0], transaction_date=f"2026-10-1{i}", shares=100, price=150.0) for i in range(3, 7)] + corr_200_to_100 = dict( + six_share_change[1], + form="4/A", + accession="0000320193-26-000385", + filing_date="2026-10-18", + shares=100, + price=30.0, + footnotes={"F1": "Corrects previously reported 200 shares at $20 to 100 shares at $30."}, + footnote_refs={"transactionAmounts/transactionShares/value": ["F1"]}, + ) + res_share_change_veto = _screen(six_share_change + [corr_200_to_100]) + assert res_share_change_veto["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_share_change_veto["checks"]["insider_trades"]["count_uncertain"] is False + assert res_share_change_veto["veto_buy"] is True + + # 20. Indistinguishable original $10 sales across two filings with $11/$12 amendments stay uncertain & order-independent + sym_orig = [ + dict( + orig_rows[0], + accession="0000320193-26-000390", + filing_date="2026-08-05", + transaction_date="2026-08-03", + shares=100, + price=10.0, + ), + dict( + orig_rows[0], + accession="0000320193-26-000391", + filing_date="2026-08-06", + transaction_date="2026-08-03", + shares=100, + price=10.0, + ), + ] + sym_a11 = dict(sym_orig[0], form="4/A", accession="0000320193-26-000392", filing_date="2026-08-07", price=11.0) + sym_a12 = dict(sym_orig[0], form="4/A", accession="0000320193-26-000392", filing_date="2026-08-07", price=12.0) + sym_move_f1 = dict( + sym_orig[0], + form="4/A", + accession="0000320193-26-000393", + filing_date="2026-08-08", + original_filing_date="2026-08-05", + transaction_date="2026-07-31", + price=13.0, + footnotes={"F1": "Corrects transaction date from 2026-08-03 (previously at $11) to 2026-07-31 at $13."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + res_sym_ab = _screen(sym_orig + [sym_a11, sym_a12, sym_move_f1], since_filing_date="2026-08-01") + res_sym_ba = _screen(sym_orig + [sym_a12, sym_a11, sym_move_f1], since_filing_date="2026-08-01") + assert res_sym_ab["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_sym_ba["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_sym_ab["checks"]["insider_trades"]["count_uncertain"] is True + assert res_sym_ba["checks"]["insider_trades"]["count_uncertain"] is True + + # 21. Separate unchanged sale price mentioned in footnote ("executed at $1,250 is unchanged") must NOT confuse prior price + six_sep_px = [ + dict(orig_rows[0], transaction_date="2026-10-12", shares=100, price=20.0), + dict(orig_rows[0], transaction_date="2026-10-12", shares=100, price=1250.0), + ] + [dict(orig_rows[0], transaction_date=f"2026-10-1{i}", shares=100, price=150.0) for i in range(3, 7)] + corr_sep_px = dict( + six_sep_px[0], + form="4/A", + accession="0000320193-26-000394", + filing_date="2026-10-18", + price=21.0, + footnotes={"F1": "Corrects sale price from $20 to $21. A separate sale executed at $1,250 is unchanged."}, + footnote_refs={"transactionAmounts/transactionPricePerShare/value": ["F1"]}, + ) + res_sep_px = _screen(six_sep_px + [corr_sep_px]) + assert res_sep_px["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_sep_px["checks"]["insider_trades"]["count_uncertain"] is False + assert res_sep_px["veto_buy"] is True + + # 22. Competing exact matches with historical alias ($10 -> $11, then accession restating both $10 and $11 in either order) + six_alias = [ + dict( + orig_rows[0], + accession="0000320193-26-000400", + filing_date="2026-10-02", + transaction_date="2026-10-01", + shares=100, + price=10.0, + ), + dict( + orig_rows[0], + accession="0000320193-26-000401", + filing_date="2026-10-03", + transaction_date="2026-10-01", + shares=100, + price=10.0, + ), + ] + [ + dict( + orig_rows[0], + accession="0000320193-26-000402", + filing_date="2026-10-04", + transaction_date=f"2026-10-0{i}", + shares=100, + price=150.0, + ) + for i in range(2, 6) + ] + corr_alias_11 = dict( + six_alias[0], + form="4/A", + accession="0000320193-26-000403", + filing_date="2026-10-06", + original_filing_date="2026-10-02", + price=11.0, + footnotes={"F1": "Corrects sale price from $10 to $11."}, + footnote_refs={"transactionAmounts/transactionPricePerShare/value": ["F1"]}, + ) + restate_10 = dict(six_alias[1], form="4/A", accession="0000320193-26-000404", filing_date="2026-10-07", price=10.0) + restate_11 = dict(six_alias[0], form="4/A", accession="0000320193-26-000404", filing_date="2026-10-07", price=11.0) + for ordered in ([restate_10, restate_11], [restate_11, restate_10]): + res_alias = _screen(six_alias + [corr_alias_11] + ordered) + assert res_alias["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_alias["checks"]["insider_trades"]["count_uncertain"] is False + assert res_alias["veto_buy"] is True + + # 23. Explicit date correction takes priority over unannotated share restatement in both row orders + prio_orig = [ + dict( + orig_rows[0], + accession="0000320193-26-000410", + filing_date="2026-08-05", + transaction_date="2026-08-03", + shares=100, + price=10.0, + ), + dict( + orig_rows[0], + accession="0000320193-26-000410", + filing_date="2026-08-05", + transaction_date="2026-08-03", + shares=200, + price=20.0, + ), + dict( + orig_rows[0], + accession="0000320193-26-000411", + filing_date="2026-08-06", + transaction_date="2026-08-05", + shares=50, + price=15.0, + ), + ] + prio_unannot = dict( + prio_orig[0], form="4/A", accession="0000320193-26-000412", filing_date="2026-08-07", price=15.0 + ) + prio_date_corr = dict( + prio_orig[0], + form="4/A", + accession="0000320193-26-000412", + filing_date="2026-08-07", + transaction_date="2026-07-31", + footnotes={"F1": "Corrects transaction date from 2026-08-03 to 2026-07-31."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + prio_reclass_200 = dict( + prio_orig[1], + form="4/A", + accession="0000320193-26-000413", + filing_date="2026-08-08", + transaction_code="G", + direction="other", + ) + for ordered in ([prio_unannot, prio_date_corr], [prio_date_corr, prio_unannot]): + res_prio = _screen(prio_orig + ordered, since_filing_date="2026-08-01") + assert res_prio["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_prio["checks"]["insider_trades"]["count_uncertain"] is True + # Follow-up reclassification of the 200-share sale to G drops count to 1, proving the 100-share sale moved. + res_prio_after_g = _screen(prio_orig + ordered + [prio_reclass_200], since_filing_date="2026-08-01") + assert res_prio_after_g["checks"]["insider_trades"]["sales_90d"] == 1 + + # 24. Match stated prior shares and price against the SAME transaction revision (never mix rev 1 shares + rev 2 price) + six_rev = [ + dict( + orig_rows[0], + accession="0000320193-26-000420", + filing_date="2026-10-02", + transaction_date="2026-10-01", + shares=200, + price=20.0, + ), + dict( + orig_rows[0], + accession="0000320193-26-000421", + filing_date="2026-10-03", + transaction_date="2026-10-01", + shares=200, + price=30.0, + ), + ] + [ + dict( + orig_rows[0], + accession="0000320193-26-000422", + filing_date="2026-10-04", + transaction_date=f"2026-10-0{i}", + shares=100, + price=150.0, + ) + for i in range(2, 6) + ] + rev_first = dict( + six_rev[0], + form="4/A", + accession="0000320193-26-000423", + filing_date="2026-10-06", + original_filing_date="2026-10-02", + shares=100, + price=30.0, + footnotes={"F1": "Corrects previously reported 200 shares at $20 to 100 shares at $30."}, + footnote_refs={"transactionAmounts/transactionShares/value": ["F1"]}, + ) + rev_second = dict( + six_rev[1], + form="4/A", + accession="0000320193-26-000424", + filing_date="2026-10-07", + shares=300, + price=40.0, + footnotes={"F1": "Corrects previously reported 200 shares at $30 to 300 shares at $40."}, + footnote_refs={"transactionAmounts/transactionShares/value": ["F1"]}, + ) + res_same_rev = _screen(six_rev + [rev_first, rev_second]) + assert res_same_rev["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_same_rev["checks"]["insider_trades"]["count_uncertain"] is False + assert res_same_rev["veto_buy"] is True + + # 25. Fractional prior prices ("from $20.50 to $21.75") must NOT be split at decimal points + six_frac_px = [ + dict(orig_rows[0], transaction_date="2026-10-12", shares=100, price=20.50), + dict(orig_rows[0], transaction_date="2026-10-12", shares=100, price=1250.50), + ] + [dict(orig_rows[0], transaction_date=f"2026-10-1{i}", shares=100, price=150.0) for i in range(3, 7)] + corr_frac_px = dict( + six_frac_px[0], + form="4/A", + accession="0000320193-26-000430", + filing_date="2026-10-18", + price=21.75, + footnotes={ + "F1": "Corrects sale price from $20.50 to $21.75. A separate sale executed at $1,250.50 is unchanged." + }, + footnote_refs={"transactionAmounts/transactionPricePerShare/value": ["F1"]}, + ) + res_frac_px = _screen(six_frac_px + [corr_frac_px]) + assert res_frac_px["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_frac_px["checks"]["insider_trades"]["count_uncertain"] is False + assert res_frac_px["veto_buy"] is True + + # 26. Unannotated historical restatement of Aug 3 after linked date correction to Jul 31 must NOT revert to Aug 3 + hist_restate_aug3 = dict( + aug_sales[2], + form="4/A", + accession="0000320193-26-000431", + filing_date="2026-08-09", + ) + res_hist_no_revert = _screen(aug_sales + [corr_date_to_jul31, hist_restate_aug3], since_filing_date="2026-08-01") + assert res_hist_no_revert["checks"]["insider_trades"]["sales_90d"] == 2 + assert not any(f["category"] == "insider" for f in res_hist_no_revert["flags"]) + + # 27. Overlapping symmetric exact-match groups (A, B in filing 1 + C in filing 2; 2 scoped + 1 unscoped in any order) + overlap_orig = [ + dict(orig_rows[0], accession="0000320193-26-000440", filing_date="2026-10-02", shares=100, price=10.0), + dict(orig_rows[0], accession="0000320193-26-000440", filing_date="2026-10-02", shares=100, price=10.0), + dict(orig_rows[0], accession="0000320193-26-000441", filing_date="2026-10-03", shares=100, price=10.0), + ] + scoped_r1 = dict( + overlap_orig[0], + form="4/A", + accession="0000320193-26-000442", + filing_date="2026-10-05", + original_filing_date="2026-10-02", + ) + scoped_r2 = dict(scoped_r1) + unscoped_r3 = dict( + overlap_orig[2], + form="4/A", + accession="0000320193-26-000442", + filing_date="2026-10-05", + original_filing_date=None, + ) + for ordered in ([unscoped_r3, scoped_r1, scoped_r2], [scoped_r1, scoped_r2, unscoped_r3]): + res_overlap = _screen(overlap_orig + ordered) + assert res_overlap["checks"]["insider_trades"]["sales_90d"] == 3 + assert res_overlap["checks"]["insider_trades"]["count_uncertain"] is False + + # 28. Symmetric exact restatements and historical restatements preserve filing_date provenance for later amendments + prov_orig = [ + dict( + orig_rows[0], + accession="0000320193-26-000450", + filing_date="2026-08-05", + transaction_date="2026-08-04", + shares=100, + price=10.0, + ), + dict( + orig_rows[0], + accession="0000320193-26-000450", + filing_date="2026-08-05", + transaction_date="2026-08-04", + shares=100, + price=10.0, + ), + dict( + orig_rows[0], + accession="0000320193-26-000451", + filing_date="2026-08-06", + transaction_date="2026-08-05", + shares=50, + price=15.0, + ), + ] + prov_restate_1 = dict(prov_orig[0], form="4/A", accession="0000320193-26-000452", filing_date="2026-08-07") + prov_restate_2 = dict(prov_restate_1) + prov_gift_link = dict( + prov_orig[0], + form="4/A", + accession="0000320193-26-000453", + filing_date="2026-08-08", + original_filing_date="2026-08-07", + transaction_code="G", + direction="other", + footnotes={"F1": "Corrects previously misreported sale to a gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + res_prov = _screen(prov_orig + [prov_restate_1, prov_restate_2, prov_gift_link], since_filing_date="2026-08-01") + assert res_prov["checks"]["insider_trades"]["sales_90d"] == 2 + assert not any(f["category"] == "insider" for f in res_prov["flags"]) + + # Historical restatement on Aug 9 preserves Aug 9 provenance so an Aug 10 correction linked to Aug 9 still resolves + hist_link_followup = dict( + corr_date_to_jul31, + accession="0000320193-26-000432", + filing_date="2026-08-10", + original_filing_date="2026-08-09", + transaction_date="2026-08-04", + footnotes={"F1": "Corrects transaction date from 2026-07-31 to 2026-08-04."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + res_hist_prov = _screen( + aug_sales + [corr_date_to_jul31, hist_restate_aug3, hist_link_followup], since_filing_date="2026-08-01" + ) + assert res_hist_prov["checks"]["insider_trades"]["sales_90d"] == 3 + assert res_hist_prov["checks"]["insider_trades"]["count_uncertain"] is False + + # 29. Single unscoped restatement matching two identical sales across different filings must NOT attach provenance + # to an arbitrary single slot: both slot orderings [A, B] and [B, A] produce identical count and uncertainty. + ambig_a = dict( + orig_rows[0], + accession="0000320193-26-000460", + filing_date="2026-08-04", + transaction_date="2026-08-03", + shares=100, + price=10.0, + ) + ambig_b = dict( + orig_rows[0], + accession="0000320193-26-000461", + filing_date="2026-08-05", + transaction_date="2026-08-03", + shares=100, + price=10.0, + ) + ambig_others = [ + dict( + orig_rows[0], + accession="0000320193-26-000462", + filing_date="2026-08-06", + transaction_date=f"2026-08-0{i}", + shares=50, + price=15.0, + ) + for i in range(4, 9) + ] + ambig_unscoped_restate = dict( + ambig_a, + form="4/A", + accession="0000320193-26-000463", + filing_date="2026-08-09", + original_filing_date=None, + ) + ambig_gift_a = dict( + ambig_a, + form="4/A", + accession="0000320193-26-000464", + filing_date="2026-08-10", + original_filing_date="2026-08-04", + transaction_code="G", + direction="other", + ) + ambig_gift_restate = dict( + ambig_a, + form="4/A", + accession="0000320193-26-000465", + filing_date="2026-08-11", + original_filing_date="2026-08-09", + transaction_code="G", + direction="other", + ) + res_ambig_ab = _screen( + [ambig_a, ambig_b] + ambig_others + [ambig_unscoped_restate, ambig_gift_a, ambig_gift_restate], + since_filing_date="2026-08-01", + ) + res_ambig_ba = _screen( + [ambig_b, ambig_a] + ambig_others + [ambig_unscoped_restate, ambig_gift_a, ambig_gift_restate], + since_filing_date="2026-08-01", + ) + assert res_ambig_ab["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_ambig_ba["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_ambig_ab["checks"]["insider_trades"]["count_uncertain"] is True + assert res_ambig_ba["checks"]["insider_trades"]["count_uncertain"] is True + assert res_ambig_ab["veto_buy"] is False + assert res_ambig_ba["veto_buy"] is False + + # 30. Unattributable filing-level remarks (plural nouns, prior-filing counts, omitted-gift remarks, or + # cross-cutoff candidates) must NEVER fabricate speculative sale additions or trigger medium-risk flags. + cap_orig = { + "form": "4", + "accession": "0001-26-000501", + "filing_date": "2026-10-05", + "transaction_date": "2026-10-04", + "transaction_code": "S", + "owner": "Cap Owner", + "owners": [{"cik": "0000000030", "name": "Cap Owner"}], + "security": "Common Stock", + "derivative": False, + "shares": 100.0, + "price": 100.0, + } + for rem_text in ( + "Amending to correct one transaction and add an omitted transaction.", + "Amending to correct one transaction and add one of the omitted sales.", + "Amending to correct one transaction and report one omitted sale. The original filing reported six transactions.", + ): + cap_in = { + "form": "4/A", + "accession": "0001-26-000502", + "filing_date": "2026-10-06", + "original_filing_date": "2026-10-05", + "transaction_date": "2026-10-04", + "transaction_code": "S", + "owner": "Cap Owner", + "owners": [{"cik": "0000000030", "name": "Cap Owner"}], + "security": "Common Stock", + "derivative": False, + "shares": 120.0, + "price": 105.0, + "remarks": rem_text, + } + cap_out = { + "form": "4/A", + "accession": "0001-26-000502", + "filing_date": "2026-10-06", + "original_filing_date": "2026-10-05", + "transaction_date": "2026-09-20", + "transaction_code": "S", + "owner": "Cap Owner", + "owners": [{"cik": "0000000030", "name": "Cap Owner"}], + "security": "Common Stock", + "derivative": False, + "shares": 250.0, + "price": None, + "remarks": rem_text, + } + res_cap_12 = _screen([cap_orig, cap_in, cap_out], since_filing_date="2026-10-01") + res_cap_21 = _screen([cap_orig, cap_out, cap_in], since_filing_date="2026-10-01") + assert res_cap_12["checks"]["insider_trades"]["sales_90d"] == 1 + assert res_cap_21["checks"]["insider_trades"]["sales_90d"] == 1 + assert res_cap_12["checks"]["insider_trades"]["count_uncertain"] is True + assert res_cap_21["checks"]["insider_trades"]["count_uncertain"] is True + assert not any(f["category"] == "insider" for f in res_cap_12["flags"]) + assert not any(f["category"] == "insider" for f in res_cap_21["flags"]) + + # 30b. Omitted gift + corrected sale remarks must NOT inflate 2 original sales into 3 + two_cap_orig = [ + cap_orig, + dict(cap_orig, transaction_date="2026-10-05", shares=150.0, price=110.0), + ] + corr_unlinked_sale = dict( + cap_orig, + form="4/A", + accession="0001-26-000503", + filing_date="2026-10-06", + original_filing_date="2026-10-05", + shares=125.0, + price=108.0, + remarks="Corrects one sale and reports one omitted gift.", + ) + omitted_gift_row = dict( + cap_orig, + form="4/A", + accession="0001-26-000503", + filing_date="2026-10-06", + original_filing_date="2026-10-05", + transaction_date="2026-10-06", + transaction_code="G", + direction="other", + shares=50.0, + price=0.0, + remarks="Corrects one sale and reports one omitted gift.", + ) + res_omit_gift = _screen(two_cap_orig + [corr_unlinked_sale, omitted_gift_row], since_filing_date="2026-10-01") + assert res_omit_gift["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_omit_gift["checks"]["insider_trades"]["count_uncertain"] is True + assert not any(f["category"] == "insider" for f in res_omit_gift["flags"]) + + # 30c. Cross-cutoff unlinked candidates (one outside 2026-08-28 cutoff, one inside) must NOT bias toward in-window + cut_orig = [ + dict(cap_orig, filing_date="2026-11-21", transaction_date="2026-11-18", shares=100.0, price=100.0), + dict(cap_orig, filing_date="2026-11-21", transaction_date="2026-11-20", shares=200.0, price=110.0), + ] + cut_rem = "Amending to report an omitted 2026-08-10 sale and correct the 2026-11-20 sale." + cut_out_row = dict( + cut_orig[0], + form="4/A", + accession="0001-26-000504", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + transaction_date="2026-08-10", + shares=90.0, + price=95.0, + remarks=cut_rem, + ) + cut_in_row = dict( + cut_orig[1], + form="4/A", + accession="0001-26-000504", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + transaction_date="2026-11-20", + shares=220.0, + price=115.0, + remarks=cut_rem, + ) + for ordered in ([cut_out_row, cut_in_row], [cut_in_row, cut_out_row]): + res_cut = _screen(cut_orig + ordered, since_filing_date="2026-08-28") + assert res_cut["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_cut["checks"]["insider_trades"]["count_uncertain"] is True + assert not any(f["category"] == "insider" for f in res_cut["flags"]) + + # 31. Consecutive date corrections where the second 4/A references the original transaction date (10-06 -> 09-29) + # after an intermediate 4/A moved it to 10-07 must still match the prior revision and exclude the sale. + seq_orig = { + "form": "4", + "accession": "0001-26-000511", + "filing_date": "2026-10-06", + "transaction_date": "2026-10-06", + "transaction_code": "S", + "owner": "Seq Date Owner", + "owners": [{"cik": "0000000031", "name": "Seq Date Owner"}], + "security": "Common Stock", + "derivative": False, + "shares": 100.0, + "price": 50.0, + } + seq_amend_1 = { + "form": "4/A", + "accession": "0001-26-000512", + "filing_date": "2026-10-07", + "original_filing_date": "2026-10-06", + "transaction_date": "2026-10-07", + "transaction_code": "S", + "owner": "Seq Date Owner", + "owners": [{"cik": "0000000031", "name": "Seq Date Owner"}], + "security": "Common Stock", + "derivative": False, + "shares": 100.0, + "price": 50.0, + "footnotes": {"F1": "Corrects transaction date from 2026-10-06 to 2026-10-07."}, + "footnote_refs": {"transactionDate": ["F1"]}, + } + seq_amend_2 = { + "form": "4/A", + "accession": "0001-26-000513", + "filing_date": "2026-10-08", + "original_filing_date": "2026-10-06", + "transaction_date": "2026-09-29", + "transaction_code": "S", + "owner": "Seq Date Owner", + "owners": [{"cik": "0000000031", "name": "Seq Date Owner"}], + "security": "Common Stock", + "derivative": False, + "shares": 100.0, + "price": 50.0, + "footnotes": {"F1": "Corrects transaction date originally reported as 2026-10-06 to 2026-09-29."}, + "footnote_refs": {"transactionDate": ["F1"]}, + } + res_seq_only2 = _screen([seq_orig, seq_amend_2], since_filing_date="2026-10-01") + res_seq_both = _screen([seq_orig, seq_amend_1, seq_amend_2], since_filing_date="2026-10-01") + assert res_seq_only2["checks"]["insider_trades"]["sales_90d"] == 0 + assert res_seq_both["checks"]["insider_trades"]["sales_90d"] == 0 + assert res_seq_both["checks"]["insider_trades"]["count_uncertain"] is False + assert not any(f["category"] == "insider" for f in res_seq_both["flags"]) + + # 32. Same-day amendments from different submitting agents must execute in EDGAR acceptanceDateTime order + # (14:00Z prefix 999 addition before 16:00Z prefix 111 gift reclassification), and flag uncertainty when + # acceptance_datetime is missing so cross-submitter order cannot be determined. + same_day_orig = [ + { + "form": "4", + "accession": "0000555555-26-000001", + "filing_date": "2026-10-03", + "transaction_date": f"2026-10-0{i}", + "transaction_code": "S", + "owner": "Same Day Owner", + "owners": [{"cik": "0000000032", "name": "Same Day Owner"}], + "security": "Common Stock", + "derivative": False, + "shares": 100.0 + i, + "price": 50.0, + } + for i in (1, 2) + ] + same_day_add = { + "form": "4/A", + "accession": "0000999999-26-000001", + "filing_date": "2026-10-05", + "acceptance_datetime": "2026-10-05T14:00:00.000Z", + "original_filing_date": "2026-10-03", + "transaction_date": "2026-10-03", + "transaction_code": "S", + "owner": "Same Day Owner", + "owners": [{"cik": "0000000032", "name": "Same Day Owner"}], + "security": "Common Stock", + "derivative": False, + "shares": 101.0, + "price": 51.0, + "footnotes": {"F1": "Reports an inadvertently omitted sale."}, + "footnote_refs": {"transactionCode": ["F1"]}, + } + same_day_gift = { + "form": "4/A", + "accession": "0000111111-26-000002", + "filing_date": "2026-10-05", + "acceptance_datetime": "2026-10-05T16:00:00.000Z", + "original_filing_date": "2026-10-03", + "transaction_date": "2026-10-03", + "transaction_code": "G", + "owner": "Same Day Owner", + "owners": [{"cik": "0000000032", "name": "Same Day Owner"}], + "security": "Common Stock", + "derivative": False, + "shares": 101.0, + "price": 0.0, + "footnotes": {"F1": "Corrects previously reported sale as a bona fide gift."}, + "footnote_refs": {"transactionCode": ["F1"]}, + } + res_same_day_ts = _screen(same_day_orig + [same_day_gift, same_day_add], since_filing_date="2026-10-01") + assert res_same_day_ts["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_same_day_ts["checks"]["insider_trades"]["count_uncertain"] is False + assert not any(f["category"] == "insider" for f in res_same_day_ts["flags"]) + + same_day_add_no_ts = {k: v for k, v in same_day_add.items() if k != "acceptance_datetime"} + same_day_gift_no_ts = {k: v for k, v in same_day_gift.items() if k != "acceptance_datetime"} + res_same_day_no_ts = _screen( + same_day_orig + [same_day_add_no_ts, same_day_gift_no_ts], since_filing_date="2026-10-01" + ) + assert res_same_day_no_ts["checks"]["insider_trades"]["count_uncertain"] is True + + # 33. Apply row-level evidence (shares/price) BEFORE checking multi-accession ambiguity: + # 33a (Weaxs): 2 orig same-day sales (100sh, 150sh) + 4/A #1 adds same-day 200sh + 4/A #2 reclassifies 200sh + # to Gift G sharing original_filing_date -> 2 sales, no insider flag, count_uncertain=False. + chain_orig_2 = [ + { + "form": "4", + "accession": "0000555555-26-000101", + "filing_date": "2026-10-03", + "transaction_date": "2026-10-03", + "transaction_code": "S", + "owner": "Chain Owner", + "owners": [{"cik": "0000000033", "name": "Chain Owner"}], + "security": "Common Stock", + "derivative": False, + "shares": shares, + "price": 50.0, + } + for shares in (100.0, 150.0) + ] + chain_add_200 = { + "form": "4/A", + "accession": "0000555555-26-000102", + "filing_date": "2026-10-04", + "original_filing_date": "2026-10-03", + "transaction_date": "2026-10-03", + "transaction_code": "S", + "owner": "Chain Owner", + "owners": [{"cik": "0000000033", "name": "Chain Owner"}], + "security": "Common Stock", + "derivative": False, + "shares": 200.0, + "price": 60.0, + "footnotes": {"F1": "Reports an inadvertently omitted sale."}, + "footnote_refs": {"transactionCode": ["F1"]}, + } + chain_gift_200 = { + "form": "4/A", + "accession": "0000555555-26-000103", + "filing_date": "2026-10-05", + "original_filing_date": "2026-10-03", + "transaction_date": "2026-10-03", + "transaction_code": "G", + "direction": "other", + "owner": "Chain Owner", + "owners": [{"cik": "0000000033", "name": "Chain Owner"}], + "security": "Common Stock", + "derivative": False, + "shares": 200.0, + "price": 60.0, + "footnotes": {"F1": "Corrects previously misreported 200-share sale to a bona fide gift."}, + "footnote_refs": {"transactionCode": ["F1"]}, + } + res_chain_200_before = _screen(chain_orig_2 + [chain_add_200], since_filing_date="2026-10-01") + assert res_chain_200_before["checks"]["insider_trades"]["sales_90d"] == 3 + res_chain_200 = _screen(chain_orig_2 + [chain_add_200, chain_gift_200], since_filing_date="2026-10-01") + assert res_chain_200["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_chain_200["checks"]["insider_trades"]["count_uncertain"] is False + assert not any(f["category"] == "insider" for f in res_chain_200["flags"]) + + # 33b (CodeRabbit Major): 6 orig sales (incl. same-day 100@$50) + 4/A #1 adds 7th same-day 200@$60 + + # 4/A #2 reclassifies 200@$60 to Gift G -> 6 confirmed orig sales remain, buy veto preserved! + chain_orig_6 = [chain_orig_2[0]] + [ + dict(chain_orig_2[0], transaction_date=f"2026-10-0{i}", shares=110.0 + i) for i in range(4, 9) + ] + res_chain_veto_before = _screen(chain_orig_6 + [chain_add_200], since_filing_date="2026-10-01") + assert res_chain_veto_before["checks"]["insider_trades"]["sales_90d"] == 7 + res_chain_veto = _screen(chain_orig_6 + [chain_add_200, chain_gift_200], since_filing_date="2026-10-01") + assert res_chain_veto["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_chain_veto["checks"]["insider_trades"]["count_uncertain"] is False + assert res_chain_veto["veto_buy"] is True + + # 33c: Multi-accession ambiguity IS still enforced when 2 distinct filings both match exact shares & price + dup_acc_orig = [ + dict(chain_orig_2[0], accession="0000555555-26-000201", shares=200.0, price=60.0), + dict(chain_orig_2[0], accession="0000555555-26-000202", shares=200.0, price=60.0), + ] + res_dup_acc = _screen(dup_acc_orig + [chain_gift_200], since_filing_date="2026-10-01") + assert res_dup_acc["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_dup_acc["checks"]["insider_trades"]["count_uncertain"] is True + + # 34. Sentence-ending period after numbers ("at $30. A separate sale was 500 shares") must split cleanly so + # unrelated share counts in the next sentence do not make a confirmed six-sale correction ambiguous. + sent_orig = [ + dict(chain_orig_2[0], transaction_date="2026-10-03", shares=200.0, price=20.0), + dict(chain_orig_2[0], transaction_date="2026-10-03", shares=500.0, price=20.0), + ] + [dict(chain_orig_2[0], transaction_date=f"2026-10-0{i}", shares=110.0 + i) for i in range(4, 8)] + sent_corr = dict( + sent_orig[0], + form="4/A", + accession="0000555555-26-000210", + filing_date="2026-10-09", + original_filing_date="2026-10-03", + shares=300.0, + price=30.0, + footnotes={"F1": "Corrects 200 shares at $20 to 300 shares at $30. A separate sale was 500 shares."}, + footnote_refs={"transactionAmounts/transactionShares/value": ["F1"]}, + ) + res_sent = _screen(sent_orig + [sent_corr], since_filing_date="2026-10-01") + assert res_sent["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_sent["checks"]["insider_trades"]["count_uncertain"] is False + assert res_sent["veto_buy"] is True + + # 35. Restoring a sale after a share-changing gift (200-sh S -> 120-sh G -> linked restore citing 120 shares) + # must match the stored gift revision and preserve the 6-sale buy veto. + gift_rev_orig = [ + dict(chain_orig_2[0], transaction_date="2026-10-03", shares=200.0, price=20.0), + ] + [dict(chain_orig_2[0], transaction_date=f"2026-10-0{i}", shares=110.0 + i) for i in range(4, 9)] + gift_rev_120 = dict( + gift_rev_orig[0], + form="4/A", + accession="0000555555-26-000220", + filing_date="2026-10-09", + original_filing_date="2026-10-03", + transaction_code="G", + direction="other", + shares=120.0, + price=0.0, + footnotes={"F1": "Corrects previously misreported 200-share sale to a 120-share gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + restore_from_120 = dict( + gift_rev_orig[0], + form="4/A", + accession="0000555555-26-000221", + filing_date="2026-10-10", + original_filing_date="2026-10-09", + shares=200.0, + price=20.0, + footnotes={"F1": "Restores sale: previously reported as 120 shares gift, should have been a 200-share sale."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + res_gift_rev = _screen(gift_rev_orig + [gift_rev_120, restore_from_120], since_filing_date="2026-10-01") + assert res_gift_rev["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_gift_rev["checks"]["insider_trades"]["count_uncertain"] is False + assert res_gift_rev["veto_buy"] is True + + # 36. An unscoped amendment filed on Oct 5 must NOT match an identical original filed LATER on Oct 8. + chron_oct4 = dict( + chain_orig_2[0], accession="0000555555-26-000230", filing_date="2026-10-04", shares=100.0, price=50.0 + ) + chron_oct8 = dict( + chain_orig_2[0], accession="0000555555-26-000231", filing_date="2026-10-08", shares=100.0, price=50.0 + ) + chron_others = [dict(chain_orig_2[0], transaction_date=f"2026-10-0{i}", shares=110.0 + i) for i in range(4, 9)] + chron_g_oct5 = dict( + chron_oct4, + form="4/A", + accession="0000555555-26-000232", + filing_date="2026-10-05", + original_filing_date=None, + transaction_code="G", + direction="other", + ) + chron_g_oct9 = dict( + chron_oct8, + form="4/A", + accession="0000555555-26-000233", + filing_date="2026-10-09", + original_filing_date="2026-10-08", + transaction_code="G", + direction="other", + ) + res_chron = _screen( + [chron_oct8, chron_oct4] + chron_others + [chron_g_oct5, chron_g_oct9], since_filing_date="2026-10-01" + ) + assert res_chron["checks"]["insider_trades"]["sales_90d"] == 5 + assert res_chron["veto_buy"] is False + + # 37. Gift correction stating prior shares (200-sh -> 100-sh G) must NOT hijack an unrelated same-day 100-sh sale. + prior_g_orig = [ + dict(chain_orig_2[0], transaction_date="2026-10-03", shares=200.0, price=20.0), + dict(chain_orig_2[0], transaction_date="2026-10-03", shares=100.0, price=10.0), + ] + [dict(chain_orig_2[0], transaction_date=f"2026-10-0{i}", shares=110.0 + i) for i in range(4, 9)] + prior_g_200_to_100 = dict( + prior_g_orig[0], + form="4/A", + accession="0000555555-26-000240", + filing_date="2026-10-09", + original_filing_date="2026-10-03", + transaction_code="G", + direction="other", + shares=100.0, + price=0.0, + footnotes={"F1": "Corrects previously misreported 200-share sale to a 100-share gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + prior_g_100 = dict( + prior_g_orig[1], + form="4/A", + accession="0000555555-26-000241", + filing_date="2026-10-10", + original_filing_date="2026-10-03", + transaction_code="G", + direction="other", + ) + res_prior_g = _screen(prior_g_orig + [prior_g_200_to_100, prior_g_100], since_filing_date="2026-10-01") + assert res_prior_g["checks"]["insider_trades"]["sales_90d"] == 5 + assert res_prior_g["veto_buy"] is False + + # 38. Active sale with missing/invalid transaction_date must mark count_uncertain=True consistently. + undated_orig = [ + dict(chain_orig_2[0], transaction_date="2026-10-03"), + dict(chain_orig_2[0], transaction_date="2026-10-04"), + dict(chain_orig_2[0], transaction_date=None), + ] + res_undated = _screen(undated_orig, since_filing_date="2026-10-01") + assert res_undated["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_undated["checks"]["insider_trades"]["count_uncertain"] is True + assert not any(f["category"] == "insider" for f in res_undated["flags"]) + + # 39. "previously reported alongside a gift" must NOT trigger gift-restoration mode on an active sale restatement. + alongside_orig = [ + dict(chain_orig_2[0], transaction_date=f"2026-10-0{i}", shares=100.0 + i, price=50.0) for i in range(3, 9) + ] + alongside_restate = dict( + alongside_orig[0], + form="4/A", + accession="0000555555-26-000250", + filing_date="2026-10-09", + original_filing_date="2026-10-03", + footnotes={"F1": "Corrects the post-transaction balance. This sale was previously reported alongside a gift."}, + footnote_refs={"postTransactionAmounts": ["F1"]}, + ) + res_alongside = _screen(alongside_orig + [alongside_restate], since_filing_date="2026-10-01") + assert res_alongside["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_alongside["checks"]["insider_trades"]["count_uncertain"] is False + assert res_alongside["veto_buy"] is True + + # 40. Same-accession swap (Sale A -> 120-sh gift AND restore prior 120-sh Gift B -> sale) must match against + # pre-accession revisions so A's new gift revision never collides with B's restoration. + swap_orig = [ + dict(chain_orig_2[0], transaction_date="2026-10-03", shares=200.0, price=20.0), + dict(chain_orig_2[0], transaction_date="2026-10-03", shares=300.0, price=30.0), + ] + [dict(chain_orig_2[0], transaction_date=f"2026-10-0{i}", shares=110.0 + i) for i in range(4, 9)] + swap_b_to_gift = dict( + swap_orig[1], + form="4/A", + accession="0000555555-26-000260", + filing_date="2026-10-09", + original_filing_date="2026-10-03", + transaction_code="G", + direction="other", + shares=120.0, + price=0.0, + footnotes={"F1": "Corrects previously misreported 300-share sale to a 120-share gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + swap_a_to_gift = dict( + swap_orig[0], + form="4/A", + accession="0000555555-26-000261", + filing_date="2026-10-10", + original_filing_date="2026-10-03", + transaction_code="G", + direction="other", + shares=120.0, + price=0.0, + footnotes={"F1": "Corrects previously misreported 200-share sale to a 120-share gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + swap_restore_b = dict( + swap_orig[1], + form="4/A", + accession="0000555555-26-000261", + filing_date="2026-10-10", + original_filing_date="2026-10-09", + shares=300.0, + price=30.0, + footnotes={"F1": "Restores sale: previously reported as 120 shares gift, should have been a 300-share sale."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + res_swap = _screen(swap_orig + [swap_b_to_gift, swap_a_to_gift, swap_restore_b], since_filing_date="2026-10-01") + assert res_swap["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_swap["checks"]["insider_trades"]["count_uncertain"] is False + assert res_swap["veto_buy"] is True + + # 41. Pass A0 order-independence: specific price claim ($20) resolves before broader 200-share claim in both orders. + a0_orig = [ + dict(chain_orig_2[0], transaction_date="2026-10-03", shares=200.0, price=20.0), + dict(chain_orig_2[0], transaction_date="2026-10-03", shares=200.0, price=30.0), + ] + [dict(chain_orig_2[0], transaction_date=f"2026-10-0{i}", shares=110.0 + i) for i in range(4, 10)] + a0_broad = dict( + a0_orig[1], + form="4/A", + accession="0000555555-26-000270", + filing_date="2026-10-10", + original_filing_date="2026-10-03", + transaction_code="G", + direction="other", + shares=150.0, + price=0.0, + footnotes={"F1": "Corrects previously misreported 200-share sale to a 150-share gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + a0_specific = dict( + a0_orig[0], + form="4/A", + accession="0000555555-26-000270", + filing_date="2026-10-10", + original_filing_date="2026-10-03", + transaction_code="G", + direction="other", + shares=140.0, + price=0.0, + footnotes={"F1": "Corrects previously reported sale at $20 to a 140-share gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + for ordered in ([a0_broad, a0_specific], [a0_specific, a0_broad]): + res_a0 = _screen(a0_orig + ordered, since_filing_date="2026-10-01") + assert res_a0["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_a0["checks"]["insider_trades"]["count_uncertain"] is False + assert res_a0["veto_buy"] is True + + # 42. Linked restoration matches gift revision reported on the linked filing date (Oct 9 vs Oct 8). + prov_g_orig = [ + dict(chain_orig_2[0], transaction_date="2026-10-03", shares=200.0, price=20.0), + dict(chain_orig_2[0], transaction_date="2026-10-03", shares=300.0, price=30.0), + ] + [dict(chain_orig_2[0], transaction_date=f"2026-10-0{i}", shares=110.0 + i) for i in range(4, 9)] + prov_g_a_oct8 = dict( + prov_g_orig[0], + form="4/A", + accession="0000555555-26-000280", + filing_date="2026-10-08", + original_filing_date="2026-10-03", + transaction_code="G", + direction="other", + shares=120.0, + price=0.0, + footnotes={"F1": "Corrects previously misreported 200-share sale to a 120-share gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + prov_g_a_oct9 = dict( + prov_g_orig[0], + form="4/A", + accession="0000555555-26-000281", + filing_date="2026-10-09", + original_filing_date="2026-10-08", + transaction_code="G", + direction="other", + shares=150.0, + price=0.0, + footnotes={"F1": "Corrects previously reported as 120 shares gift to a 150-share gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + prov_g_b_oct9 = dict( + prov_g_orig[1], + form="4/A", + accession="0000555555-26-000281", + filing_date="2026-10-09", + original_filing_date="2026-10-03", + transaction_code="G", + direction="other", + shares=120.0, + price=0.0, + footnotes={"F1": "Corrects previously misreported 300-share sale to a 120-share gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + prov_restore_oct9 = dict( + prov_g_orig[1], + form="4/A", + accession="0000555555-26-000282", + filing_date="2026-10-10", + original_filing_date="2026-10-09", + shares=300.0, + price=30.0, + footnotes={"F1": "Restores sale: previously reported as 120 shares gift, should have been a 300-share sale."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + res_prov_g9 = _screen( + prov_g_orig + [prov_g_a_oct8, prov_g_a_oct9, prov_g_b_oct9, prov_restore_oct9], since_filing_date="2026-10-01" + ) + assert res_prov_g9["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_prov_g9["checks"]["insider_trades"]["count_uncertain"] is False + assert res_prov_g9["veto_buy"] is True + + prov_restore_oct8 = dict( + prov_g_orig[0], + form="4/A", + accession="0000555555-26-000283", + filing_date="2026-10-10", + original_filing_date="2026-10-08", + shares=200.0, + price=20.0, + footnotes={"F1": "Restores sale: previously reported as 120 shares gift, should have been a 200-share sale."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + res_prov_g8 = _screen( + prov_g_orig + [prov_g_a_oct8, prov_g_a_oct9, prov_g_b_oct9, prov_restore_oct8], since_filing_date="2026-10-01" + ) + assert res_prov_g8["checks"]["insider_trades"]["sales_90d"] == 6 + assert res_prov_g8["checks"]["insider_trades"]["count_uncertain"] is False + assert res_prov_g8["veto_buy"] is True + + +def _screen_form4(monkeypatch, rows): + monkeypatch.setenv("SEC_USER_AGENT", "test-app test@example.com") + return risk_screening.screen_risk( + "AAPL", + inputs={ + "quote": {"pe": 25, "pb": 5}, + "technical": {"signal_score": 60, "buy_signal": "HOLD", "trend": {"overall": "neutral"}}, + }, + run=lambda script, args, **kwargs: ( + {"transactions": rows, "since_filing_date": "2026-08-28"} if script == "sec_edgar.py" else [] + ), + ) + + +def _form4_sale(shares=100, **fields): + return { + "form": "4", + "accession": "0000000123-26-000001", + "filing_date": "2026-11-21", + "transaction_date": "2026-11-20", + "transaction_code": "S", + "owners": [{"cik": "123"}], + "security": "Common Stock", + "shares": shares, + "price": 20, + **fields, + } + + +def test_form4_accession_explicitly_adds_all_its_sale_rows(monkeypatch): + original = _form4_sale() + amendments = [ + _form4_sale( + shares, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + transaction_date=day, + remarks="This amendment reports two previously omitted sales.", + ) + for shares, day in [(200, "2026-11-18"), (300, "2026-11-19")] + ] + for remarks in ( + "This amendment adds two sales.", + "This amendment reports two previously omitted sales.", + "This amendment reports two additional sales. The original Form 4 was filed on November 21, 2026.", + "This amendment is being filed to report two sales that were inadvertently omitted from the original Form 4.", + "This amendment reports two previously unreported sales by the reporting person.", + ): + rows = [dict(tx, remarks=remarks) for tx in amendments] + result = _screen_form4(monkeypatch, [original, *rows]) + assert result["checks"]["insider_trades"]["sales_90d"] == 3 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + assert any(flag["severity"] == "medium" for flag in result["flags"]) + + later_original = _form4_sale( + 200, accession="0000000123-26-000003", filing_date="2026-11-23", transaction_date="2026-11-18" + ) + result = _screen_form4(monkeypatch, [original, later_original, *amendments]) + assert result["checks"]["insider_trades"]["sales_90d"] == 4 + + revised = dict( + original, + **{key: amendments[0][key] for key in ("form", "accession", "filing_date", "original_filing_date", "remarks")}, + price=25, + footnotes={"F1": "The sale price for this row was revised from $20 to $25."}, + footnote_refs={"transactionAmounts/transactionPricePerShare/value": ["F1"]}, + ) + for note in ( + "The sale price for this row was revised from $20 to $25.", + "The previously reported sale price has been updated to $25.", + "The price on the previously reported sale is now $25.", + "The previously reported sale omitted brokerage fees from the sale price.", + ): + row = dict(revised, footnotes={"F1": note}) + result = _screen_form4(monkeypatch, [original, row, amendments[1]]) + assert result["checks"]["insider_trades"]["sales_90d"] == 1 + assert result["checks"]["insider_trades"]["count_uncertain"] is True + + +def _screen_form4_cli(monkeypatch, rows): + import json + import subprocess + import sys + from pathlib import Path + + script = Path(risk_screening.__file__) + monkeypatch.setenv("SEC_USER_AGENT", "test-app test@example.com") + monkeypatch.setenv("PYTHONPATH", str(script.parent)) + launch = """ +import json, runpy, sys +import _subproc +fixture = json.load(sys.stdin) +_subproc.run_tool = lambda name, *_args, **_kwargs: fixture[name] +sys.argv.pop(0) +runpy.run_path(sys.argv[0], run_name='__main__') +""" + fixture = { + "stock_data.py": {"pe": 25, "pb": 5}, + "technical.py": {"signal_score": 60, "buy_signal": "HOLD"}, + "sec_edgar.py": {"transactions": rows, "since_filing_date": "2026-08-28"}, + "search_intel.py": [], + } + cli = subprocess.run( + [sys.executable, "-c", launch, str(script), "screen", "AAPL"], + input=json.dumps(fixture), + capture_output=True, + encoding="utf-8", + timeout=10, + ) + assert cli.returncode == 0, cli.stderr + assert not cli.stderr + return json.loads(cli.stdout) + + +def test_form4_screen_cli_requires_affirmative_matching_addition_count(monkeypatch): + remarks_cases = ( + ( + 2, + "The previous amendment reported two previously omitted sales. This amendment updates the reported prices.", + ), + (2, "This amendment does not report two previously omitted sales."), + (6, "This amendment reports sıx previously omitted sales."), + (1, "This amendment reports two previously omitted sales."), + (1, "This amendment does not report one previously omitted sale."), + (1, "The previous amendment reported one previously omitted sale."), + (1, "This amendment reports two additional sales. The original Form 4 was filed on November 21, 2026."), + (2, "This amendment reports two additional sales. It also updates the price of the previously reported sale."), + (2, "This amendment reports two additional sales. The previously reported sale prices were also adjusted."), + (2, "This amendment reports two additional sales. *The director's prior sales were also adjusted."), + ( + 2, + "This amendment reports two additional sales. *President, the previously reported sale price was adjusted.", + ), + ) + for n, remarks, expected in [ + *((n, remarks, n) for n, remarks in remarks_cases), + (2, "This amendment reports two additional sales.", 4), + ]: + originals = [_form4_sale(shares) for shares in range(100, 100 + n)] + amendments = [ + dict( + row, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + price=25, + remarks=remarks, + ) + for row in originals + ] + result = _screen_form4_cli(monkeypatch, [*originals, *amendments]) + assert result["checks"]["insider_trades"]["sales_90d"] == expected + + +def test_form4_single_omitted_sale_requires_a_distinct_row(monkeypatch): + original = _form4_sale() + amendment = dict( + original, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + remarks="This amendment reports the previously omitted sale.", + ) + exact = _screen_form4(monkeypatch, [original, amendment])["checks"]["insider_trades"] + assert exact["sales_90d"] == 1 + assert exact["count_uncertain"] is True + distinct = _screen_form4(monkeypatch, [original, dict(amendment, transaction_date="2026-11-19")]) + assert distinct["checks"]["insider_trades"]["sales_90d"] == 2 + assert distinct["checks"]["insider_trades"]["count_uncertain"] is False + for remarks in ( + "This amendment is being filed to report a sale transaction that was inadvertently omitted from the original Form 4.", + "This Form 4 Amendment is filed to include an additional sale of common shares that was omitted from the Form 4 filed on November 21, 2026.\n\n*President, North America Insurance", + ): + result = _screen_form4(monkeypatch, [original, dict(amendment, transaction_date="2026-11-19", remarks=remarks)]) + assert result["checks"]["insider_trades"]["sales_90d"] == 2 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + + for note in ( + "This sale was previously omitted. The reporting person's title changed from Vice President to President.", + "This sale was inadvertently omitted from the previously filed Form 4.", + "This report adds the sale omitted from the original Form 4 that was not previously reported.", + ): + annotated = dict( + amendment, + transaction_date="2026-11-19", + remarks=None, + footnotes={"F1": note}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + result = _screen_form4(monkeypatch, [original, annotated]) + assert result["checks"]["insider_trades"]["sales_90d"] == 2 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + + +def test_form4_unlinked_date_correction_does_not_create_a_sale(monkeypatch): + originals = [_form4_sale(), _form4_sale(200, transaction_date="2026-11-19")] + context = { + "form": "4/A", + "accession": "0000000123-26-000002", + "filing_date": "2026-11-22", + "original_filing_date": "2026-11-21", + "remarks": "Corrects the 200-share sale date from November 19, 2026 to November 20, 2026.", + } + result = _screen_form4(monkeypatch, originals + [_form4_sale(**context), _form4_sale(200, **context)]) + assert result["checks"]["insider_trades"]["sales_90d"] == 2 + assert result["checks"]["insider_trades"]["count_uncertain"] is True + assert not result["flags"] + + +def test_form4_linked_footnote_requires_affirmative_sale_addition(monkeypatch): + original = _form4_sale() + originals = [original, _form4_sale(200)] + amendment = dict( + original, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + footnote_refs={"transactionDate/value": ["F1"]}, + ) + for note in ( + "This sale was not omitted.", + "The sale price omitted commissions.", + "This sale was omitted from the calculation of 10b5-1 shares.", + "This sale was omitted in this amendment.", + "Reports an omitted gift.", + ): + result = _screen_form4(monkeypatch, [*originals, dict(amendment, footnotes={"F1": note})]) + assert result["checks"]["insider_trades"]["sales_90d"] == 2, note + assert not result["flags"] + + contradictory = dict( + amendment, + shares=300, + footnotes={"F1": "This sale was not omitted."}, + remarks="This amendment reports one omitted sale.", + ) + result = _screen_form4(monkeypatch, [*originals, contradictory]) + assert result["checks"]["insider_trades"]["sales_90d"] == 2 + assert result["checks"]["insider_trades"]["count_uncertain"] is True + + for note in ( + "This sale was omitted from the original Form 4.", + "This sale was omitted from the original Form 4 filed on November 21, 2026.", + "This sale was omitted from the Form 4 originally filed on November 21, 2026.", + "The sale reported on this line was inadvertently omitted from the original Form 4.", + "This sale is newly reported.", + "This Form 4 Amendment is filed to include an additional sale of common shares that was omitted from the Form 4 filed on November 21, 2026.", + "This transaction line was added to this Form 4 to report a previously omitted private sale of the company's common stock.", + "This transaction line has been added to this Form 4 to disclose a private sale of securities omitted from the original report.", + ): + result = _screen_form4(monkeypatch, [*originals, dict(amendment, footnotes={"F1": note})]) + assert result["checks"]["insider_trades"]["sales_90d"] == 3, note + assert result["checks"]["insider_trades"]["count_uncertain"] is False + assert any(flag["severity"] == "medium" for flag in result["flags"]) + + for first_note, expected in ( + ("Weighted-average price", 3), + ("This sale was not omitted.", 2), + ("This sale was not omitted from the original Form 4 and remains on the same line.", 2), + ("The sale reported on this line was not omitted from the original Form 4.", 2), + ("This amendment does not disclose a new sale.", 2), + ("This amendment does not disclose a new sale and leaves the quantity unchanged.", 2), + ("This amendment does not disclose a new sale and only provides this line for context.", 2), + ("This amendment does not disclose a new sale and merely leaves the prior filing unchanged.", 2), + ("This amendment does not report any sales and leaves the quantity unchanged.", 2), + ("This amendment does not report sales but provides this line for context.", 2), + ("This amendment does not report a private sale.", 2), + ("This amendment does not report one omitted sale.", 2), + ("This amendment does not report any additional sales of common stock.", 2), + ("This sale was not newly reported in this amendment.", 2), + ("This amendment does not disclose the amount of fees.", 3), + ("This amendment does not disclose the sale price.", 3), + ("This amendment does not disclose the sale and purchase prices.", 3), + ("This amendment does not disclose the new sale and purchase prices.", 3), + ("This amendment does not disclose the transaction fees.", 3), + ): + linked = dict( + amendment, + footnotes={"F1": first_note, "F2": "This sale was omitted from the original Form 4"}, + footnote_refs={"transactionDate/value": ["F1", "F2"]}, + ) + result = _screen_form4_cli(monkeypatch, [*originals, linked]) + assert result["checks"]["insider_trades"]["sales_90d"] == expected + assert bool(result["flags"]) is (expected == 3) + + +def test_form4_shared_footnote_does_not_attribute_a_counted_addition_to_every_row(monkeypatch): + original = _form4_sale(ownership="D") + amendment = dict( + original, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + footnotes={"F1": "This amendment reports one omitted sale."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + restatement = dict(amendment, ownership="I") + addition = dict(amendment, shares=200) + for note in ( + "This amendment reports one omitted sale.", + "This sale was omitted from the original Form 4.", + ): + shared_rows = [dict(row, footnotes={"F1": note}) for row in (restatement, addition)] + result = _screen_form4_cli(monkeypatch, [original, *shared_rows]) + assert result["checks"]["insider_trades"]["sales_90d"] == 1 + assert result["checks"]["insider_trades"]["count_uncertain"] is True + assert not result["flags"] + + scoped_addition = dict( + addition, + footnotes={**addition["footnotes"], "F2": "This sale was omitted from the original Form 4."}, + footnote_refs={"transactionDate/value": ["F1"], "transactionAmounts/transactionShares/value": ["F2"]}, + ) + result = _screen_form4(monkeypatch, [original, restatement, scoped_addition]) + assert result["checks"]["insider_trades"]["sales_90d"] == 2 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + + single_reference = dict( + amendment, footnote_refs={"transactionDate/value": ["F1"], "transactionAmounts/transactionShares/value": ["F1"]} + ) + result = _screen_form4(monkeypatch, [original, single_reference]) + assert result["checks"]["insider_trades"]["sales_90d"] == 2 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + + for note in ("This amendment reports two omitted sales.", "This amendment adds two sales."): + both_new = [ + dict( + amendment, + shares=shares, + remarks="This amendment reports two omitted sales.", + footnotes={"F1": note}, + ) + for shares in (200, 300) + ] + result = _screen_form4(monkeypatch, [original, *both_new]) + assert result["checks"]["insider_trades"]["sales_90d"] == 3 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + + +def test_form4_shared_omitted_gifts_do_not_change_sale_certainty(monkeypatch): + sales = [_form4_sale(shares) for shares in range(200, 206)] + gifts = [ + _form4_sale( + shares, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + transaction_code="G", + price=None, + footnotes={"F1": "This amendment reports two omitted transactions."}, + footnote_refs={"transactionDate/value": ["F1"]}, + ) + for shares in (120, 130) + ] + result = _screen_form4(monkeypatch, [*sales, *gifts]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + assert result["veto_buy"] is True + + +def test_form4_shared_conversion_note_is_scoped_to_the_gift(monkeypatch): + from itertools import permutations + + other_sales = [_form4_sale(n, transaction_date="2026-11-19") for n in range(401, 406)] + for shares, note, restated_fields, competing_price in ( + (200, "Corrects the sale of 200 shares at $20 to a gift.", {}, None), + (200, "Corrects the sale of 200 shares at $20 per share to a gift.", {}, None), + (200, "Corrects the sale of 200 shares of Common Stock at $20 to a gift.", {}, None), + (200, "Corrects the sale of 200 shares to a gift.", {}, None), + (0.5, "Corrects the .5-share sale to a gift.", {}, None), + (200, "The 200-share sale should be reclassified to a gift.", {}, None), + (200, "This amendment is filed to correct the sale of 200 shares at $20 to a gift.", {}, None), + (200, "The sale of 200 shares at $20 should have been reported as a gift.", {}, None), + ( + 200, + "The sale of 200 shares at $20 was incorrectly reported and should have been reported as a gift.", + {}, + None, + ), + (200, "Corrects the sale of 200 shares at 20 to a gift.", {"shares": 200}, 25), + ( + 200, + "Corrects the sale of 200 shares at $20 to a 200-share gift.", + {"transaction_date": "2026-11-18"}, + None, + ), + ): + converted = _form4_sale(shares, transaction_date="2026-11-18") + restated = _form4_sale(price=30, **restated_fields) + sales = [converted, restated, *other_sales] + if competing_price is not None: + sales.append(dict(converted, price=competing_price)) + amendment = { + "form": "4/A", + "accession": "0000000123-26-000002", + "filing_date": "2026-11-22", + "original_filing_date": "2026-11-21", + "footnotes": {"F1": note}, + "footnote_refs": {"transactionCoding": ["F1"]}, + } + gift = dict(converted, **amendment, transaction_code="G", price=None) + sell = dict(restated, **amendment) + native_gift = dict(restated, transaction_code="G", price=None) + for originals, amendments in ( + (sales, (gift, sell)), + ([*sales, native_gift], (gift, sell, dict(native_gift, **amendment))), + ): + for ordered in permutations(amendments): + result = _screen_form4_cli(monkeypatch, [*originals, *ordered]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == len(sales) - 1, note + assert check["count_uncertain"] is False, note + assert result["veto_buy"] is True, note + if competing_price is not None: + followup = dict( + gift, + accession="0000000123-26-000003", + filing_date="2026-11-23", + footnotes={"F1": f"Corrects the sale of {shares} shares at ${competing_price} to a gift."}, + ) + result = _screen_form4_cli(monkeypatch, [*originals, *ordered, followup]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == len(sales) - 2, note + assert check["count_uncertain"] is False, note + assert result["veto_buy"] is True, note + + +def test_form4_shared_conversion_preserves_independently_corrected_gift(monkeypatch): + from itertools import permutations + + converted = _form4_sale(200) + restated = _form4_sale(100, price=30) + other_sales = [_form4_sale(n, transaction_date="2026-11-19") for n in range(401, 406)] + native = dict(restated, shares=90, transaction_code="G", price=None) + amendment = { + "form": "4/A", + "accession": "0000000123-26-000002", + "filing_date": "2026-11-22", + "original_filing_date": "2026-11-21", + "footnote_refs": {"transactionCoding": ["F1"]}, + "footnotes": { + "F1": "Corrects the sale of 200 shares at $20 to a gift.", + "F2": "Corrects this gift from 90 shares to 100 shares.", + }, + } + gift = dict(converted, **amendment, transaction_code="G", price=None) + sell = dict(restated, **amendment) + for prior_gifts, has_gift_correction, certain in ( + ([native], True, True), + ([native], False, False), + ([], True, False), + ): + revised = dict(native, **amendment, shares=100) + if has_gift_correction: + revised["footnote_refs"] = {"transactionCoding": ["F1"], "transactionAmounts": ["F2"]} + for ordered in permutations((gift, sell, revised)): + result = _screen_form4_cli(monkeypatch, [converted, restated, *other_sales, *prior_gifts, *ordered]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == (6 if certain else 7) + assert check["count_uncertain"] is not certain + assert result["veto_buy"] is certain + + native_restatement = dict(native, shares=100) + unrelated_gift = dict(native_restatement, **amendment) + unrelated_gift["footnote_refs"] = {} + duplicate_remark = amendment["footnotes"]["F1"] + result = _screen_form4_cli( + monkeypatch, + [ + converted, + restated, + *other_sales, + native_restatement, + *(dict(row, remarks=duplicate_remark) for row in (gift, sell, unrelated_gift)), + ], + ) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + assert result["veto_buy"] is True + + +@pytest.mark.parametrize( + "gift_note, shared_note, conversion_date, denial_source, expected_sales", + [ + ("This gift was previously unreported.", False, "2026-11-20", None, 6), + ("This gift was unreported.", False, "2026-11-20", None, 6), + ("This amendment reports one omitted gift.", False, "2026-11-20", None, 6), + ("This amendment reports one unreported gift.", False, "2026-11-20", None, 6), + ("This gift was previously unreported.", True, "2026-11-20", None, 7), + ("This gift was previously unreported. This gift was not omitted.", False, "2026-11-20", None, 7), + ("This gift was previously unreported.", False, "2026-11-20", "remarks", 7), + ("This gift was previously unreported.", False, "2026-11-20", "remarks_prior_gift", 7), + ("This gift was previously unreported.", False, "2026-11-20", "remarks_other_gift", 6), + ("This gift was previously unreported.", False, "2026-11-20", "shared_ref", 7), + ("This gift was previously unreported.", False, "2026-11-20", "note", 7), + ("This gift was previously unreported.", False, "2026-11-20", "amendment_reason", 7), + ("This gift was previously unreported.", False, "2026-11-17", None, 7), + ("This gift was previously unreported.", False, "2026-11-17", "remarks", 7), + ], +) +def test_form4_shared_conversion_preserves_independently_added_gift( + monkeypatch, gift_note, shared_note, conversion_date, denial_source, expected_sales +): + sale = _form4_sale(200) + originals = [sale, _form4_sale(100), *(_form4_sale(n, transaction_date="2026-11-19") for n in range(401, 406))] + denial = "This amendment does not add any gifts." + amendment = { + "form": "4/A", + "accession": "0000000123-26-000002", + "filing_date": "2026-11-22", + "original_filing_date": "2026-11-21", + "footnotes": {"F1": "Corrects the sale of 200 shares at $20 to a gift.", "F2": gift_note, "F3": denial}, + } + remarks_by_source = { + "remarks": denial, + "remarks_prior_gift": "The 100-share gift was already reported.", + "remarks_other_gift": "The 200-share gift was already reported.", + } + if denial_source in remarks_by_source: + amendment["remarks"] = remarks_by_source[denial_source] + references = ["F1", "F3"] if denial_source == "shared_ref" else ["F1"] + converted = _form4_sale( + 200, + **amendment, + transaction_date=conversion_date, + transaction_code="G", + price=None, + footnote_refs={"transactionCoding": [*references, "F2"] if shared_note else references}, + ) + added = _form4_sale( + 100, **amendment, transaction_code="G", price=None, footnote_refs={"transactionCoding": [*references, "F2"]} + ) + if denial_source in ("note", "amendment_reason"): + added[denial_source] = denial + for amended_rows in ((converted, added), (added, converted)): + result = _screen_form4_cli(monkeypatch, [*originals, *amended_rows]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == expected_sales + assert check["count_uncertain"] is (expected_sales == 7) + assert result["veto_buy"] is (expected_sales == 6) + + +@pytest.mark.parametrize( + "remark, expected_sales", + [ + ("The 100-share gift was already reported in the original Form 4.", 7), + ("The 100-share gift was already reported on the original Form 4.", 7), + ("The 200-share gift was already reported in the original Form 4.", 6), + ("The 100-share gift was previously disclosed in the prior Form 4/A filed on November 21, 2026.", 7), + ("The 100-share gift was not already reported in the original Form 4.", 6), + ("The 100-share gift was already reported in the original Form 4 holdings totals only.", 6), + ], +) +def test_form4_prior_gift_disclosure_with_filing_reference(monkeypatch, remark, expected_sales): + sale = _form4_sale(200) + originals = [sale, _form4_sale(100), *(_form4_sale(n, transaction_date="2026-11-19") for n in range(401, 406))] + amendment = { + "form": "4/A", + "accession": "0000000123-26-000002", + "filing_date": "2026-11-22", + "original_filing_date": "2026-11-21", + "transaction_code": "G", + "price": None, + "remarks": remark, + "footnotes": {"F1": "Corrects the sale of 200 shares at $20 to a gift.", "F2": "This gift was unreported."}, + } + converted = _form4_sale(200, **amendment, footnote_refs={"transactionCoding": ["F1"]}) + added = _form4_sale(100, **amendment, footnote_refs={"transactionCoding": ["F1", "F2"]}) + for amended_rows in ((converted, added), (added, converted)): + result = _screen_form4_cli(monkeypatch, [*originals, *amended_rows]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == expected_sales + assert check["count_uncertain"] is (expected_sales == 7) + assert result["veto_buy"] is (expected_sales == 6) + + +def _assert_form4_gift_addition_correctable(monkeypatch, rows, added): + correction = dict( + added, + accession="0000000123-26-000003", + filing_date="2026-11-23", + original_filing_date=added["filing_date"], + shares=120, + remarks=None, + footnotes={"F1": "Corrects this gift from 100 shares to 120 shares."}, + footnote_refs={"transactionCoding": ["F1"]}, + ) + result = _screen_form4_cli(monkeypatch, [*rows, correction]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == 6 + assert check["count_uncertain"] is False + assert result["veto_buy"] is True + + +@pytest.mark.parametrize( + "prior_transaction_date, restate_prior_gift, expected_sales, count_uncertain", + [ + ("2026-11-18", False, 6, False), + ("2026-11-18", True, 6, False), + ("2026-11-20", False, 7, True), + ], + ids=["different-date", "restated-different-date", "same-date-conflict"], +) +def test_form4_dated_disclosure_identifies_the_reported_gift( + monkeypatch, prior_transaction_date, restate_prior_gift, expected_sales, count_uncertain +): + from itertools import permutations + + sale = _form4_sale(200) + originals = [sale, *(_form4_sale(n, transaction_date="2026-11-19") for n in range(401, 407))] + prior = _form4_sale( + 100, + accession="0000000123-26-000004", + filing_date="2026-11-20", + transaction_date=prior_transaction_date, + transaction_code="G", + price=None, + ) + amendment = { + "form": "4/A", + "accession": "0000000123-26-000002", + "filing_date": "2026-11-22", + "original_filing_date": "2026-11-21", + "remarks": "The 100-share gift was previously disclosed in the prior Form 4 filed on November 20, 2026.", + "footnotes": {"F1": "Corrects the sale of 200 shares at $20 to a gift.", "F2": "This gift was unreported."}, + } + converted = dict(sale, **amendment, transaction_code="G", price=None, footnote_refs={"transactionCoding": ["F1"]}) + added = dict(converted, shares=100, footnote_refs={"transactionCoding": ["F1", "F2"]}) + rows = [converted, added] + if restate_prior_gift: + rows.append(dict(prior, **amendment)) + for ordered in permutations(rows): + result = _screen_form4_cli(monkeypatch, [*originals, prior, *ordered]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == expected_sales + assert check["count_uncertain"] is count_uncertain + assert result["veto_buy"] is (not count_uncertain) + if not count_uncertain: + _assert_form4_gift_addition_correctable(monkeypatch, [*originals, prior, *rows], added) + + +@pytest.mark.parametrize("cited_day, prior_code, expected_sales", [(19, "G", 6), (18, "G", 7), (19, "F", 7)]) +def test_form4_dated_disclosure_identifies_a_reclassified_gift(monkeypatch, cited_day, prior_code, expected_sales): + sale = _form4_sale(200) + other_sales = [_form4_sale(n, transaction_date="2026-11-19") for n in range(401, 407)] + prior_sale = _form4_sale( + 90 if prior_code == "G" else 100, + accession="0000000123-26-000010", + filing_date="2026-11-18", + transaction_date="2026-11-18", + ) + prior_footnote = ( + "Corrects the sale of 90 shares at $20 to a 100-share gift." + if prior_code == "G" + else "Corrects the transaction code from S to F." + ) + prior_reclassification = dict( + prior_sale, + form="4/A", + accession="0000000123-26-000011", + filing_date="2026-11-19", + original_filing_date="2026-11-18", + transaction_code=prior_code, + shares=100, + price=None, + footnotes={"F1": prior_footnote}, + footnote_refs={"transactionCoding": ["F1"]}, + ) + converted = dict( + sale, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + transaction_code="G", + price=None, + remarks=f"The 100-share gift was previously disclosed in the report filed on November {cited_day}, 2026.", + footnotes={"F1": "Corrects the sale of 200 shares at $20 to a gift.", "F2": "This gift was unreported."}, + footnote_refs={"transactionCoding": ["F1"]}, + ) + added = dict(converted, shares=100, footnote_refs={"transactionCoding": ["F1", "F2"]}) + for amended_rows in ((converted, added), (added, converted)): + result = _screen_form4_cli(monkeypatch, [sale, *other_sales, prior_reclassification, prior_sale, *amended_rows]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == expected_sales + assert check["count_uncertain"] is (expected_sales == 7) + assert result["veto_buy"] is (expected_sales == 6) + if expected_sales == 6: + _assert_form4_gift_addition_correctable( + monkeypatch, [sale, *other_sales, prior_reclassification, prior_sale, converted, added], added + ) + + +@pytest.mark.parametrize("conversion_date, expected_sales", [("2026-11-20", 6), ("2026-11-17", 7)]) +def test_form4_shared_conversion_respects_independent_gift_addition_and_correction( + monkeypatch, conversion_date, expected_sales +): + from itertools import permutations + + sale = _form4_sale(200) + originals = [sale, *(_form4_sale(n, transaction_date="2026-11-19") for n in range(401, 407))] + native = _form4_sale(90, transaction_code="G", price=None) + amendment = { + "form": "4/A", + "accession": "0000000123-26-000002", + "filing_date": "2026-11-22", + "original_filing_date": "2026-11-21", + "transaction_code": "G", + "price": None, + "footnotes": { + "F1": "Corrects the sale of 200 shares at $20 to a gift.", + "F2": "This gift was previously unreported.", + "F3": "Corrects this gift from 90 shares to 100 shares.", + }, + } + converted = _form4_sale( + 200, **amendment, transaction_date=conversion_date, footnote_refs={"transactionCoding": ["F1"]} + ) + added = _form4_sale(110, **amendment, footnote_refs={"transactionCoding": ["F1", "F2"]}) + corrected = _form4_sale(100, **amendment, footnote_refs={"transactionCoding": ["F1", "F3"]}) + for amended_rows in permutations((converted, added, corrected)): + result = _screen_form4_cli(monkeypatch, [*originals, native, *amended_rows]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == expected_sales + assert check["count_uncertain"] is (expected_sales == 7) + assert result["veto_buy"] is (expected_sales == 6) + if expected_sales == 6: + for gift in (added, corrected): + shares = gift["shares"] + follow_up = dict( + gift, + accession="0000000123-26-000003", + filing_date="2026-11-23", + original_filing_date=gift["filing_date"], + shares=shares + 5, + footnotes={"F1": f"Corrects this gift from {shares} shares to {shares + 5} shares."}, + footnote_refs={"transactionCoding": ["F1"]}, + ) + result = _screen_form4_cli(monkeypatch, [*originals, native, converted, added, corrected, follow_up]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == 6 + assert check["count_uncertain"] is False, shares + assert result["veto_buy"] is True + + +def test_form4_conflicting_gift_addition_does_not_remove_a_matching_sale(monkeypatch): + sale = _form4_sale() + amendment = dict( + sale, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + transaction_code="G", + price=None, + footnotes={"F1": "This gift was previously unreported. This gift was not omitted."}, + footnote_refs={"transactionCoding": ["F1"]}, + ) + check = _screen_form4_cli(monkeypatch, [sale, amendment])["checks"]["insider_trades"] + assert check["sales_90d"] == 1 + assert check["count_uncertain"] is True + + +@pytest.mark.parametrize( + "note, expected_sales", + [ + ("Corrects the sale of 200 shares at $20 to a 300-share gift.", 1), + ("Corrects the transaction code from S to F.", 1), + ("Corrects the sale of 200 shares at $20 to a 200-share gift.", 0), + ], +) +@pytest.mark.parametrize("source", ["footnote", "remarks", "both"]) +def test_form4_conversion_note_must_match_the_amended_non_sell(monkeypatch, note, expected_sales, source): + sale = _form4_sale(200) + amendment = dict( + sale, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + transaction_code="G", + price=None, + footnotes={"F1": note} if source != "remarks" else {}, + footnote_refs={"transactionCoding": ["F1"]}, + remarks=note if source != "footnote" else "", + ) + check = _screen_form4_cli(monkeypatch, [sale, amendment])["checks"]["insider_trades"] + assert check["sales_90d"] == expected_sales + assert check["count_uncertain"] is bool(expected_sales) + + +def test_form4_addition_declarations_keep_transaction_quantity(monkeypatch): + original = _form4_sale(200) + amendment = { + "form": "4/A", + "accession": "0000000123-26-000002", + "filing_date": "2026-11-22", + "original_filing_date": "2026-11-21", + "remarks": "This amendment reports one omitted sale of 100 shares.", + } + for shared_subject, separate_evidence, expected, uncertain in ( + ("sale of 100 shares", False, 2, False), + ("sale of 200 shares", False, 2, True), + ("sale of 200 shares", True, 3, False), + ("sale of 200 shares at $20", False, 2, True), + ("200-share sale", False, 2, True), + ("second sale", False, 2, True), + ): + footnotes = { + "F1": ( + "This amendment reports the omitted second sale." + if shared_subject == "second sale" + else f"This amendment adds one omitted {shared_subject}." + ), + "F2": "This sale was omitted from the original Form 4.", + "F3": "This sale was omitted from the original Form 4.", + } + rows = [ + _form4_sale(100, **amendment, footnotes=footnotes, footnote_refs={"transactionDate/value": ["F1", "F2"]}), + dict( + original, + **amendment, + footnotes=footnotes, + footnote_refs={"transactionDate/value": ["F1", "F3"] if separate_evidence else ["F1"]}, + ), + ] + result = _screen_form4_cli(monkeypatch, [original, *rows]) + assert result["checks"]["insider_trades"]["sales_90d"] == expected + assert result["checks"]["insider_trades"]["count_uncertain"] is uncertain, shared_subject + + +def test_form4_addition_declarations_respect_filing_evidence(monkeypatch): + original = _form4_sale(200, security="Class B Common Stock") + amendment = { + "form": "4/A", + "accession": "0000000123-26-000002", + "filing_date": "2026-11-22", + "original_filing_date": "2026-11-21", + } + shared_refs = {"transactionDate/value": ["F1"]} + row_refs = {"transactionDate/value": ["F1", "F2"]} + for footnote_detail, remarks_detail, other_security, expected_uncertain in ( + ("100 Class A shares", "100 Class B shares", "Class A Common Stock", True), + ("100 Class A shares", "100 Class B shares", "Class B Common Stock", False), + ("100 Class A shares", "100 shares", None, False), + ("100 shares", "100 shares at $30", None, True), + ("100 shares", "100 shares at $30 per share", None, True), + ("100 shares", "100 shares at $20 per share", None, False), + ( + "100 shares omitted from the form 4 filed on November 21, 2026", + "100 shares omitted from the form 4 filed on Nov 21 2026", + None, + False, + ), + ( + "100 shares omitted from the form 4 filed on November 21, 2026", + "100 shares omitted from the form 4 filed on November 20, 2026", + "Class A Common Stock", + True, + ), + ): + footnotes = { + "F1": f"This amendment adds one omitted sale of {footnote_detail}.", + "F2": "This sale was omitted from the original Form 4.", + "F3": "This sale was omitted from the original Form 4.", + } + remarks = f"This amendment reports one omitted sale of {remarks_detail}." + rows = [ + _form4_sale(100, **amendment, security="Class A Common Stock", footnotes=footnotes, footnote_refs=row_refs), + dict(original, **amendment, footnotes=footnotes, footnote_refs=shared_refs), + ] + if other_security: + rows.append( + _form4_sale( + 100, + **amendment, + transaction_date="2026-11-19", + security=other_security, + footnotes=footnotes, + footnote_refs={"transactionDate/value": ["F1", "F3"]}, + ) + ) + result = _screen_form4_cli(monkeypatch, [original, *(dict(row, remarks=remarks) for row in rows)]) + assert result["checks"]["insider_trades"]["sales_90d"] == 2 + bool(other_security) + assert result["checks"]["insider_trades"]["count_uncertain"] is expected_uncertain, remarks + + scoped_notes = { + "F1": "This amendment reports one omitted sale of 100 shares.", + "F2": "This sale was omitted from the original Form 4.", + } + linked = {**amendment, "footnotes": scoped_notes, "footnote_refs": shared_refs} + scoped_rows = [ + dict(original, **linked), + _form4_sale(100, **linked), + _form4_sale(100, **amendment, footnotes=scoped_notes, footnote_refs={"transactionDate/value": ["F2"]}), + ] + result = _screen_form4_cli(monkeypatch, [original, *scoped_rows]) + assert result["checks"]["insider_trades"]["sales_90d"] == 2 + assert result["checks"]["insider_trades"]["count_uncertain"] is True + + for shares, declaration, expected_uncertain in ( + (0.5, "one omitted sale of .5 shares", False), + (100, "one omitted sale of 100 Class B shares", True), + ): + row = _form4_sale( + shares, **amendment, security="Class A Common Stock", remarks=f"This amendment reports {declaration}." + ) + result = _screen_form4_cli(monkeypatch, [original, row]) + assert result["checks"]["insider_trades"]["sales_90d"] == (1 if expected_uncertain else 2) + assert result["checks"]["insider_trades"]["count_uncertain"] is expected_uncertain + + mixed_originals = [original, _form4_sale(120, transaction_code="G", price=None)] + mixed_rows = [ + dict( + tx, + **amendment, + footnote_refs=shared_refs, + footnotes={"F1": "This amendment reports one omitted transaction."}, + ) + for tx in mixed_originals + ] + result = _screen_form4_cli(monkeypatch, [*mixed_originals, *mixed_rows]) + assert result["checks"]["insider_trades"]["sales_90d"] == 1 + assert result["checks"]["insider_trades"]["count_uncertain"] is True + + +@pytest.mark.parametrize( + "declared_class, security, class_matches", + [ + ("Class A", "Class A Common Stock", True), + ("Class A", "Class A-1 Common Stock", False), + ("Class A", "Class A‑1 Common Stock", False), + ("Class A-1", "Class A‑1 Common Stock", True), + ("Class A-1", "Class A Common Stock", False), + ], +) +def test_form4_addition_matches_complete_share_class(monkeypatch, declared_class, security, class_matches): + originals = [_form4_sale(shares, security="Class B Common Stock") for shares in (200, 250)] + amendment = _form4_sale( + 100, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + security=security, + footnotes={"F1": f"This amendment reports one omitted sale of 100 {declared_class} shares."}, + footnote_refs={"transactionCoding": ["F1"]}, + ) + result = _screen_form4_cli(monkeypatch, [*originals, amendment]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == (3 if class_matches else 2) + assert check["count_uncertain"] is (not class_matches) + has_medium_flag = any(flag["category"] == "insider" and flag["severity"] == "medium" for flag in result["flags"]) + assert has_medium_flag is class_matches + + +def test_form4_additions_match_compatible_statements_and_independent_row_details(monkeypatch): + original = _form4_sale(200, price=30) + amendment = { + "form": "4/A", + "accession": "0000000123-26-000002", + "filing_date": "2026-11-22", + "original_filing_date": "2026-11-21", + } + for shared, remarks, row_note, outside_shares, count, uncertain in ( + ("one omitted sale at $20", "one omitted sale of 100 shares", "the omitted first sale", None, 2, False), + ("one omitted sale", "one omitted sale of 200 shares", "the omitted first sale", 200, 3, False), + ("the omitted second sale", "", "the omitted first sale", None, 2, True), + ("the omitted second sale", "", "the omitted second sale", None, 2, False), + ("the omitted second sale", "one omitted sale of 100 shares", "the omitted second sale", None, 2, False), + ("the omitted second sale", "one omitted transaction of 100 shares", "the omitted second sale", None, 2, False), + ("one omitted sale of 100 shares", "the omitted second sale", "the omitted second sale", None, 2, False), + ("the omitted second sale", "one omitted sale of 200 shares", "the omitted second sale", 200, 3, False), + ("the omitted second sale", "one omitted sale of 100 shares", "the omitted first sale", None, 2, True), + ( + "the omitted second sale", + "one omitted sale of 100 shares", + "the omitted second sale. This amendment reports the omitted first sale", + None, + 2, + True, + ), + ( + "the omitted second sale", + "one omitted sale of 100 shares", + "the omitted second sale. This amendment reports an omitted private sale", + None, + 2, + False, + ), + ("", "the omitted second sale", "the omitted first sale", None, 2, True), + ("the omitted private sale", "", "the omitted open-market sale", None, 2, True), + ( + "one omitted sale of 100 shares", + "", + "the sale omitted from the original Form 4 filed on November 20, 2026", + None, + 1, + True, + ), + ("one omitted sale", "", "one omitted 200-share sale of 100 shares", None, 1, True), + ): + footnotes = { + "F1": f"This amendment reports {shared}." if shared else "", + "F2": f"This amendment reports {row_note}.", + "F3": "This sale was omitted from the original Form 4.", + } + rows = [ + dict(original, **amendment, footnotes=footnotes, footnote_refs={"transactionDate/value": ["F1"]}), + _form4_sale(100, **amendment, footnotes=footnotes, footnote_refs={"transactionDate/value": ["F1", "F2"]}), + ] + if outside_shares is not None: + rows.append( + _form4_sale( + outside_shares, **amendment, footnotes=footnotes, footnote_refs={"transactionDate/value": ["F3"]} + ) + ) + result = _screen_form4_cli( + monkeypatch, + [original, *(dict(row, remarks=f"This amendment reports {remarks}." if remarks else "") for row in rows)], + ) + assert result["checks"]["insider_trades"]["sales_90d"] == count, row_note + assert result["checks"]["insider_trades"]["count_uncertain"] is uncertain, (shared, remarks, row_note) + + +def test_form4_gift_quantity_correction_preserves_unrelated_sale_and_veto(monkeypatch): + original = _form4_sale() + active_sales = [_form4_sale(150), *(_form4_sale(shares) for shares in range(201, 206))] + gift = dict( + original, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + transaction_code="G", + shares=120, + price=None, + footnotes={"F1": "Corrects previously misreported 100-share sale to a 120-share gift."}, + footnote_refs={"transactionAmounts/transactionShares/value": ["F1"]}, + ) + correction = dict( + gift, + accession="0000000123-26-000003", + filing_date="2026-11-23", + shares=150, + footnotes={"F1": "Corrects the number of gift shares to 150."}, + ) + for price in (None, 20): + result = _screen_form4(monkeypatch, [original, *active_sales, gift, dict(correction, price=price)]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + assert result["veto_buy"] is True + + linked = dict( + correction, + price=20, + footnotes={"F1": "Shares are held directly", "F2": "Corrects the number of gift shares to 150."}, + footnote_refs={"transactionAmounts/transactionShares/value": ["F1", "F2"]}, + ) + result = _screen_form4(monkeypatch, [original, *active_sales, gift, linked]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["veto_buy"] is True + + for row in ( + dict(correction, footnotes={"F1": "Shares are held directly."}, remarks=correction["footnotes"]["F1"]), + dict( + linked, + footnotes={"F1": "The sale had 20 shares at $20.", "F2": "Updates the number of gift shares to 150."}, + ), + dict( + correction, + footnotes={ + "F1": "This amendment is filed solely to correct the number of shares gifted. The line does not reflect a new transaction." + }, + ), + ): + result = _screen_form4(monkeypatch, [original, *active_sales, gift, row]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + assert result["veto_buy"] is True + + native_gift = _form4_sale(150, transaction_code="G", price=None) + stated = dict(correction, footnotes={"F1": "Corrects this gift from 120 shares to 150 shares."}) + result = _screen_form4(monkeypatch, [original, *active_sales, native_gift, gift, stated]) + assert result["checks"]["insider_trades"]["count_uncertain"] is False + assert result["veto_buy"] is True + + for transition in ("S to G", '"S" to "G"', "S (sale) to G (gift)"): + first_conversion = dict( + gift, shares=100, footnotes={"F1": f"Corrects the gift transaction code from {transition}."} + ) + result = _screen_form4(monkeypatch, [original, *active_sales, first_conversion]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["veto_buy"] is True + converted = dict( + gift, + footnotes={**gift["footnotes"], "F2": "Corrects the number of gift shares to 120."}, + footnote_refs={"transactionAmounts/transactionShares/value": ["F1", "F2"]}, + ) + result = _screen_form4(monkeypatch, [original, *active_sales, converted]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["veto_buy"] is True + + result = _screen_form4(monkeypatch, [*active_sales, correction]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["checks"]["insider_trades"]["count_uncertain"] is True + + second_gift = dict( + gift, shares=150, footnotes={"F1": "Corrects previously misreported 250-share sale to a 150-share gift."} + ) + history = [original, _form4_sale(250), *active_sales, gift, second_gift] + for note, uncertain in ( + ("Corrects the number of gift shares to 150.", True), + ("Corrects this gift from 100 shares to 150 shares.", True), + ("Corrects this gift from 120 shares to 150 shares.", False), + ("The gift shares were corrected from 120 shares to 150 shares.", False), + ): + result = _screen_form4(monkeypatch, [*history, dict(correction, footnotes={"F1": note})]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["checks"]["insider_trades"]["count_uncertain"] is uncertain + assert result["veto_buy"] is (not uncertain) + + original_gifts = [native_gift, dict(native_gift, shares=120)] + broad = dict(correction, shares=180, footnotes={"F1": "Corrects the number of gift shares to 180."}) + specific = dict(correction, shares=190, footnotes={"F1": "Corrects this gift from 120 shares to 190 shares."}) + for ordered in ([broad, specific], [specific, broad]): + result = _screen_form4(monkeypatch, [*active_sales, *original_gifts, *ordered]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["checks"]["insider_trades"]["count_uncertain"] is True + identified = dict(broad, footnotes={"F1": "Corrects this gift from 150 shares to 180 shares."}) + for ordered in ([identified, specific], [specific, identified]): + result = _screen_form4(monkeypatch, [*active_sales, *original_gifts, *ordered]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + assert result["veto_buy"] is True + + +def test_form4_native_gift_revision_ignores_later_same_day_filings(monkeypatch): + sales = [_form4_sale(shares) for shares in range(200, 206)] + original = _form4_sale( + 120, + accession="0000000123-26-000002", + transaction_code="G", + price=None, + acceptance_datetime="2026-11-21T14:00:00Z", + ) + later_gift = dict(original, accession="0000000456-26-000001", acceptance_datetime="2026-11-21T16:00:00Z") + correction = dict( + original, + form="4/A", + accession="0000000789-26-000001", + original_filing_date="2026-11-21", + acceptance_datetime="2026-11-21T15:00:00Z", + shares=150, + footnotes={"F1": "Corrects this gift from 120 shares to 150 shares."}, + footnote_refs={"transactionAmounts/transactionShares/value": ["F1"]}, + ) + result = _screen_form4_cli(monkeypatch, [*sales, later_gift, correction, original]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + assert result["veto_buy"] is True + + +def test_form4_non_sell_fallback_uses_acceptance_time(monkeypatch): + target = _form4_sale(100, acceptance_datetime="2026-11-21T10:00:00Z") + sales = [target, *(_form4_sale(n) for n in range(401, 406))] + amendment = dict( + target, + form="4/A", + accession="0000000123-26-000002", + original_filing_date="2026-11-21", + acceptance_datetime="2026-11-21T12:00:00Z", + transaction_code="G", + price=None, + ) + early = dict( + target, + accession="0000000456-26-000001", + transaction_code="G", + price=None, + acceptance_datetime="2026-11-21T11:00:00Z", + ) + late = dict(early, accession="0000000456-26-000002", acceptance_datetime="2026-11-21T15:00:00Z") + same_time = dict(early, acceptance_datetime="2026-11-21T07:00:00-05:00") + for gifts, expected in (([early], 6), ([late], 5), ([late, early], 6), ([same_time], 6)): + result = _screen_form4_cli(monkeypatch, [*sales, amendment, *gifts]) + assert result["checks"]["insider_trades"]["sales_90d"] == expected + assert result["checks"]["insider_trades"]["count_uncertain"] is False + assert result["veto_buy"] is (expected == 6) + + unlinked = dict(amendment, original_filing_date=None) + later = dict(late, filing_date="2026-11-22", acceptance_datetime="2026-11-22T15:00:00Z") + with_next_day = _screen_form4_cli(monkeypatch, [later, *sales, unlinked]) + assert with_next_day["checks"]["insider_trades"]["sales_90d"] == 5 + assert with_next_day["checks"]["insider_trades"]["count_uncertain"] is False + assert with_next_day["veto_buy"] is False + + +def test_form4_native_gift_corrections_preserve_revision_history(monkeypatch): + sales = [_form4_sale(150), *(_form4_sale(shares) for shares in range(201, 206))] + original = _form4_sale(120, transaction_code="G", price=None) + first = dict( + original, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + shares=150, + footnotes={"F1": "Corrects this gift from 120 shares to 150 shares."}, + footnote_refs={"transactionAmounts/transactionShares/value": ["F1"]}, + ) + for previous_shares, referenced_filing in ((150, "2026-11-22"), (150, "2026-11-21"), (120, "2026-11-21")): + second = dict( + first, + accession="0000000123-26-000003", + filing_date="2026-11-23", + original_filing_date=referenced_filing, + shares=180, + footnotes={"F1": f"Corrects this gift from {previous_shares} shares to 180 shares."}, + ) + result = _screen_form4(monkeypatch, [*sales, original, second, first]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + assert result["veto_buy"] is True + + repeated = dict( + first, + accession="0000000123-26-000003", + filing_date="2026-11-23", + original_filing_date="2026-11-22", + footnotes={}, + footnote_refs={}, + ) + result = _screen_form4(monkeypatch, [*sales, original, repeated, first]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + assert result["veto_buy"] is True + + follow_up = dict( + first, + accession="0000000123-26-000004", + filing_date="2026-11-24", + original_filing_date="2026-11-23", + shares=180, + footnotes={"F1": "Corrects this gift from 150 shares to 180 shares."}, + ) + new_gift = dict( + repeated, + original_filing_date="2026-11-21", + footnotes={"F1": "This amendment reports one omitted gift."}, + footnote_refs=first["footnote_refs"], + ) + for gift in (repeated, new_gift): + result = _screen_form4_cli(monkeypatch, [*sales, original, follow_up, gift, first]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["checks"]["insider_trades"]["count_uncertain"] is False + assert result["veto_buy"] is True + + +def test_form4_explicit_gift_addition_preserves_identical_original(monkeypatch): + sales = [_form4_sale(shares) for shares in range(401, 407)] + original = _form4_sale(100, transaction_code="G", price=None) + added = dict( + original, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + footnotes={"F1": "This gift was unreported."}, + footnote_refs={"transactionAmounts/transactionShares/value": ["F1"]}, + ) + correction = dict( + added, + accession="0000000123-26-000003", + filing_date="2026-11-23", + shares=120, + footnotes={"F1": "Corrects this gift from 100 shares to 120 shares."}, + ) + correction_again = dict( + correction, + accession="0000000123-26-000004", + filing_date="2026-11-24", + original_filing_date=original["filing_date"], + shares=130, + footnotes={"F1": "Corrects this gift from 120 shares to 130 shares."}, + ) + for linked_filing in (added["filing_date"], original["filing_date"], None): + rows = [*sales, original, dict(correction, original_filing_date=linked_filing), added] + result = _screen_form4_cli(monkeypatch, rows) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == 6 + assert check["count_uncertain"] is (linked_filing is None), linked_filing + assert result["veto_buy"] is (linked_filing is not None), linked_filing + if linked_filing is None: + continue + result = _screen_form4_cli(monkeypatch, [*rows, correction_again]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == 6 + assert check["count_uncertain"] is (linked_filing == added["filing_date"]), linked_filing + assert result["veto_buy"] is (linked_filing == original["filing_date"]), linked_filing + + +@pytest.mark.parametrize( + "repeat_filing, repeated_date_text", + [ + ("2026-11-22", "November 21, 2026"), + ("2026-11-23", "November 21, 2026"), + ("2026-11-23", "November 21 2026"), + ], +) +def test_form4_repeated_dated_gift_omission_preserves_one_history(monkeypatch, repeat_filing, repeated_date_text): + sales = [_form4_sale(shares) for shares in range(401, 407)] + added = _form4_sale( + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + acceptance_datetime="2026-11-22T13:00:00Z", + original_filing_date="2026-11-21", + transaction_code="G", + price=None, + footnotes={"F1": "This gift was omitted from the original Form 4 filed on November 21, 2026."}, + footnote_refs={"transactionCoding": ["F1"]}, + ) + repeated = dict( + added, + accession="0000000123-26-000003", + filing_date=repeat_filing, + acceptance_datetime=f"{repeat_filing}T15:00:00Z", + original_filing_date=added["filing_date"], + footnotes={"F1": f"This gift was omitted from the original Form 4 filed on {repeated_date_text}."}, + ) + corrected = dict( + added, + accession="0000000123-26-000004", + filing_date="2026-11-24", + acceptance_datetime="2026-11-24T13:00:00Z", + original_filing_date=repeat_filing, + shares=120, + footnotes={"F1": "Corrects this gift from 100 shares to 120 shares."}, + ) + corrected_again = dict( + corrected, + accession="0000000123-26-000005", + filing_date="2026-11-25", + acceptance_datetime="2026-11-25T13:00:00Z", + original_filing_date=added["filing_date"], + shares=130, + footnotes={"F1": "Corrects this gift from 120 shares to 130 shares."}, + ) + corrected_last = dict( + corrected_again, + accession="0000000123-26-000006", + filing_date="2026-11-26", + acceptance_datetime="2026-11-26T13:00:00Z", + original_filing_date=corrected_again["filing_date"], + shares=140, + footnotes={"F1": "Corrects this gift from 130 shares to 140 shares."}, + ) + result = _screen_form4_cli(monkeypatch, [*sales, corrected_last, corrected_again, corrected, repeated, added]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == 6 + assert check["count_uncertain"] is False + assert result["veto_buy"] is True + + +def test_form4_same_day_omissions_of_identical_gifts_remain_uncertain(monkeypatch): + sales = [_form4_sale(shares, acceptance_datetime="2026-11-21T09:00:00Z") for shares in range(401, 407)] + first = _form4_sale( + form="4/A", + accession="0000000123-26-000002", + original_filing_date="2026-11-21", + acceptance_datetime="2026-11-21T12:00:00Z", + transaction_code="G", + price=None, + footnotes={"F1": "This gift was omitted from the original Form 4 filed on November 21, 2026."}, + footnote_refs={"transactionCoding": ["F1"]}, + ) + second = dict(first, accession="0000000123-26-000003", acceptance_datetime="2026-11-21T15:00:00Z") + before_correction = _screen_form4_cli(monkeypatch, [*sales, second, first]) + check = before_correction["checks"]["insider_trades"] + assert check["sales_90d"] == 6 + assert check["count_uncertain"] is False + assert before_correction["veto_buy"] is True + + correction = dict( + first, + accession="0000000123-26-000004", + filing_date="2026-11-22", + acceptance_datetime="2026-11-22T09:00:00Z", + original_filing_date=None, + shares=120, + footnotes={"F1": "Corrects this gift from 100 shares to 120 shares."}, + ) + for gift_rows, uncertain in (((first,), False), ((second, first), True)): + result = _screen_form4_cli(monkeypatch, [*sales, *gift_rows, correction]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == 6 + assert check["count_uncertain"] is uncertain + assert result["veto_buy"] is (not uncertain) + + +def test_form4_dated_gift_addition_does_not_merge_with_a_plain_restatement(monkeypatch): + sales = [_form4_sale(shares) for shares in range(401, 407)] + original = _form4_sale(transaction_code="G", price=None) + restatement = dict( + original, + form="4/A", + accession="0000000123-26-000002", + filing_date="2026-11-22", + original_filing_date="2026-11-21", + ) + added = dict( + restatement, + accession="0000000123-26-000003", + filing_date="2026-11-23", + original_filing_date="2026-11-22", + footnotes={"F1": "This gift was omitted from the original Form 4 filed on November 21, 2026."}, + footnote_refs={"transactionCoding": ["F1"]}, + ) + correction = dict( + added, + accession="0000000123-26-000004", + filing_date="2026-11-24", + shares=120, + footnotes={"F1": "Corrects this gift from 100 shares to 120 shares."}, + ) + correction_again = dict( + correction, + accession="0000000123-26-000005", + filing_date="2026-11-25", + original_filing_date=original["filing_date"], + shares=130, + footnotes={"F1": "Corrects this gift from 120 shares to 130 shares."}, + ) + for linked_filing in (None, original["filing_date"], restatement["filing_date"], added["filing_date"]): + rows = [*sales, original, restatement, added, dict(correction, original_filing_date=linked_filing)] + result = _screen_form4_cli(monkeypatch, rows) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == 6 + assert check["count_uncertain"] is (linked_filing is None), linked_filing + assert result["veto_buy"] is (linked_filing is not None), linked_filing + if linked_filing is None: + continue + result = _screen_form4_cli(monkeypatch, [*rows, correction_again]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == 6 + assert check["count_uncertain"] is (linked_filing == added["filing_date"]), linked_filing + assert result["veto_buy"] is (linked_filing != added["filing_date"]), linked_filing + + +def test_form4_undated_sale_does_not_change_dated_sales_veto(monkeypatch): + originals = [_form4_sale(shares) for shares in range(100, 106)] + undated = _form4_sale(300, accession="0000000123-26-000002", transaction_date=None) + result = _screen_form4(monkeypatch, [*originals, undated]) + assert result["checks"]["insider_trades"]["sales_90d"] == 6 + assert result["checks"]["insider_trades"]["count_uncertain"] is True + assert result["veto_buy"] is True + assert any("date" in warning for warning in result["warnings"]) + assert not any("revision" in warning for warning in result["warnings"]) + + +def test_form4_reclassification_reservation_does_not_create_a_sale(monkeypatch): + originals = [ + _form4_sale(), + _form4_sale(200, transaction_date="2026-11-19"), + _form4_sale(300, transaction_date="2026-11-18"), + ] + context = { + "form": "4/A", + "accession": "0000000123-26-000002", + "filing_date": "2026-11-22", + "original_filing_date": "2026-11-21", + } + gift = _form4_sale( + transaction_code="G", + footnotes={"F1": "Corrects the sale of 100 shares to a gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + **context, + ) + result = _screen_form4(monkeypatch, originals + [gift, _form4_sale(**context)]) + assert result["checks"]["insider_trades"]["sales_90d"] == 2 + assert not result["flags"] + + +def test_form4_conflicting_gift_revisions_do_not_create_a_restorable_state(monkeypatch): + def file_revision(row, day, **fields): + return dict( + row, + form="4/A", + accession=f"0000000123-26-{day - 20:06d}", + filing_date=f"2026-11-{day}", + original_filing_date=f"2026-11-{day - 1}", + **fields, + ) + + original = _form4_sale() + gift = file_revision( + original, + 22, + shares=120, + transaction_code="G", + footnotes={"F1": "Corrects previously reported 100-share sale to a 120-share gift."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + restore = file_revision( + original, + 24, + footnotes={"F1": "Corrects the gift previously reported as 150 shares. It should have been a 100-share sale."}, + footnote_refs={"transactionCoding/transactionCode": ["F1"]}, + ) + stated_prior = "Corrects this gift from 120 shares to {} shares." + no_prior = "Corrects the number of gift shares to {}." + for templates in ((stated_prior, stated_prior), (no_prior, no_prior), (stated_prior, no_prior)): + claims = [ + file_revision( + gift, + 23, + shares=shares, + footnotes={"F1": template.format(shares)}, + ) + for shares, template in zip((150, 160), templates) + ] + for ordered in (claims, claims[::-1]): + result = _screen_form4(monkeypatch, [original, gift, *ordered, restore]) + assert result["checks"]["insider_trades"]["sales_90d"] == 0 + assert result["checks"]["insider_trades"]["count_uncertain"] is True + + prior_sale_price = dict( + gift, + transaction_code="S", + shares=100, + price=24, + footnotes={"F1": "Corrects the sale price from $20 to $24."}, + ) + # The historical/current signatures use exact matching, the new prices use share matching. + for last_filed, history, prices in ( + (22, [gift], (25, 30)), + (23, [prior_sale_price, file_revision(gift, 23, price=24)], (20, 24)), + ): + price_claims = [ + file_revision( + gift, + last_filed + 1, + shares=100, + price=price, + footnotes={"F1": f"Corrects the gift price to ${price}."}, + ) + for price in prices + ] + restore_price = file_revision( + restore, + last_filed + 2, + price=25 if prices[0] == 20 else 20, + footnotes={ + "F1": f"Corrects the gift previously reported at ${prices[0]}. It should have been a 100-share sale." + }, + ) + for ordered in (price_claims, price_claims[::-1]): + check = _screen_form4(monkeypatch, [original, *history, *ordered, restore_price])["checks"][ + "insider_trades" + ] + assert check["sales_90d"] == 0 + assert check["count_uncertain"] is True + check = _screen_form4(monkeypatch, [original, *history, price_claims[0], restore_price])["checks"][ + "insider_trades" + ] + assert check["sales_90d"] == 1 + assert check["count_uncertain"] is False + + # A first-time reclassification and a revision to an existing gift can coexist. + other_sale = dict(original, price=24) + gift = dict( + gift, + price=None, + footnotes={"F1": "Corrects the previously reported sale of 100 shares at $20 to a 120-share gift."}, + ) + revise_gift = file_revision( + gift, 23, shares=150, footnotes={"F1": "Corrects this gift from 120 shares to 150 shares."} + ) + new_gift = file_revision(gift, 23, shares=100, footnotes={"F1": "Corrects the 100-share sale to a gift."}) + revise_gift["original_filing_date"] = new_gift["original_filing_date"] = original["filing_date"] + share_correction = dict( + new_gift, shares=130, footnotes={"F1": "Corrects the previously reported 100-share sale to a 130-share gift."} + ) + prefixed = dict( + share_correction, + footnotes={"F1": "This amendment corrects the previously reported 100-share sale to a 130-share gift."}, + ) + passive = dict( + share_correction, + footnotes={ + "F1": "The 100-share sale was previously reported in error and is reclassified to a 130-share gift." + }, + ) + code_corrections = [ + dict(new_gift, footnotes={"F1": f"{verb} the transaction code from S to G."}) + for verb in ("Corrects", "Changes", "Reclassifies") + ] + for sale_to_gift in (new_gift, share_correction, prefixed, passive, *code_corrections): + for ordered in ([revise_gift, sale_to_gift], [sale_to_gift, revise_gift]): + check = _screen_form4(monkeypatch, [original, other_sale, gift, *ordered])["checks"]["insider_trades"] + assert check["sales_90d"] == 0 + assert check["count_uncertain"] is False + + for code, note in ( + ("D", "Corrects the transaction code of the gift from G to D."), + ("G", "Restates the gift after the previous amendment reclassified a sale to a gift."), + ("G", "Corrects the sale previously reclassified to a gift to update the reported share amount."), + ): + restated_gift = dict(new_gift, transaction_code=code, footnotes={"F1": note}) + check = _screen_form4(monkeypatch, [original, other_sale, gift, restated_gift])["checks"]["insider_trades"] + assert check["sales_90d"] == 1 + assert check["count_uncertain"] is False + + same_size_gift = dict( + gift, + shares=100, + footnotes={"F1": "Corrects the previously reported sale of 100 shares at $20 to a 100-share gift."}, + ) + repeated_gift = dict(new_gift, footnotes={"F1": "This amendment corrects the 100-share sale to a gift."}) + check = _screen_form4(monkeypatch, [original, other_sale, same_size_gift, repeated_gift])["checks"][ + "insider_trades" + ] + assert check["sales_90d"] == 1 + + +def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): + base_inputs = { + "quote": {"pe": 18, "pb": 3}, + "technical": {"signal_score": 65, "buy_signal": "BUY", "trend": {"overall": "bullish"}}, + } + # 1. Resumption / lifting of suspension must NOT trigger high-severity buy veto even if categorized as Trading Halt + res_resume = risk_screening.screen_risk( + "00700.HK", + "Tencent", + inputs=base_inputs, + run=lambda script, args, **kw: ( + { + "announcements": [ + { + "date": "2026-10-01", + "title": "LIFTING OF SUSPENSION AND RESUMPTION OF TRADING", + "type": "Trading Halt", + } + ], + "truncated": False, + } + if script == "value_data.py" + else [] + ), + ) + assert res_resume["veto_buy"] is False + assert res_resume["checks"]["disclosures"]["available"] is True + assert not any(f["category"] == "disclosure" for f in res_resume["flags"]) + + # 2. HKEX "HALT IN TRADING" wording and "Trading Halt" announcement type trigger high-severity buy veto + for ann in ( + {"date": "2026-10-01", "title": "INSIDE INFORMATION - FURTHER UPDATE AND CONTINUED HALT IN TRADING"}, + {"date": "2026-10-01", "title": "INSIDE INFORMATION - FURTHER UPDATE", "type": "Trading Halt"}, + ): + res_halt = risk_screening.screen_risk( + "00700.HK", + "Tencent", + inputs=base_inputs, + run=lambda script, args, ann=ann, **kw: ( + {"announcements": [ann], "truncated": False} if script == "value_data.py" else [] + ), + ) + assert res_halt["veto_buy"] is True + assert any(f["category"] == "disclosure" and f["severity"] == "high" for f in res_halt["flags"]) + + # 3. Provider-incomplete HKEX response (truncated=True with < 15 rows) marks unavailable & data_complete=False + res_trunc = risk_screening.screen_risk( + "00700.HK", + "Tencent", + inputs=base_inputs, + run=lambda script, args, **kw: ( + {"announcements": [{"date": "2026-10-01", "title": "Profit Warning"}], "truncated": True} + if script == "value_data.py" + else [] + ), + ) + assert res_trunc["checks"]["disclosures"]["available"] is False + assert res_trunc["data_complete"] is False + assert any(f["category"] == "disclosure" and f["severity"] == "medium" for f in res_trunc["flags"]) + assert any("incomplete/truncated" in w for w in res_trunc["warnings"]) + + +def test_us_risk_screening_truncated_sec_marks_incomplete_and_keeps_flags(monkeypatch): + monkeypatch.setenv("SEC_USER_AGENT", "test-app test@example.com") + + def fake_run(script, args, **kwargs): + if script == "sec_edgar.py" and args[0] == "insider_trades": + return { + "since_filing_date": "2026-08-01", + "transactions": [{"code": "S", "transaction_date": f"2026-10-0{i}"} for i in (1, 2, 3)], + "truncated": True, + "warnings": ["1 filing failed"], + } + return [] + + result = risk_screening.screen_risk( + "AAPL", + "Apple", + inputs={ + "quote": {"pe": 25, "pb": 5}, + "technical": {"signal_score": 60, "buy_signal": "HOLD", "trend": {"overall": "neutral"}}, + }, + run=fake_run, + ) + assert result["data_complete"] is False + assert result["checks"]["insider_trades"]["available"] is False + assert result["checks"]["insider_trades"]["truncated"] is True + assert any(f["category"] == "insider" and f["source"] == "data" for f in result["flags"]) + assert any("truncated" in w for w in result["warnings"]) + + +def test_unsupported_market_returns_error(): + result = risk_screening.screen_risk("7203.T") + assert "error" in result + assert result["market"] == "JP" + + +def test_hk_sector_rankings_tradingview_and_etf_fallback(monkeypatch): + import argparse + + import pandas as pd + + from tools import stock_data + + def fake_tv(region, body): + assert region == "hongkong" + return { + "data": [ + {"d": ["00700", "Tencent", "Technology Services", 3.0, 4_000_000_000_000, 10_000_000_000]}, + {"d": ["09988", "Alibaba", "Technology Services", 1.0, 2_000_000_000_000, 8_000_000_000]}, + {"d": ["00005", "HSBC", "Finance", -1.0, 1_500_000_000_000, 5_000_000_000]}, + ] + } + + monkeypatch.setattr(stock_data, "_tradingview_scan", fake_tv) + args = argparse.Namespace(top=5, direction="both", board_type="industry", market="HK") + res = stock_data.cmd_sector_rankings(args) + assert res["top"][0]["name"] == "Technology Services" + assert res["top"][0]["change_pct"] == 2.3333 + assert res["top"][0]["leading_stock"] == "Tencent" + assert res["bottom"][0]["name"] == "Finance" + assert res["top"][0]["market"] == "HK" + + # Concept board rejected cleanly + bad = stock_data.cmd_sector_rankings(argparse.Namespace(top=5, direction="top", board_type="concept", market="HK")) + assert "error" in bad + + # Fallback to HK ETF proxies when TradingView fails + monkeypatch.setattr(stock_data, "_tradingview_scan", lambda *a, **kw: (_ for _ in ()).throw(RuntimeError("down"))) + idx = pd.to_datetime(["2026-10-01", "2026-10-02"]) + closes = pd.DataFrame({"3033.HK": [4.0, 4.2], "2800.HK": [20.0, 19.8]}, index=idx) + import yfinance as yf + + monkeypatch.setattr(yf, "download", lambda *a, **kw: {"Close": closes}) + fb = stock_data.cmd_sector_rankings(argparse.Namespace(top=5, direction="top", board_type="industry", market="HK")) + assert fb[0]["etf"] == "3033.HK" + assert fb[0]["proxy"] == "HK Sector ETF" + assert fb[0]["change_pct"] == 5.0 diff --git a/tests/test_sec_edgar.py b/tests/test_sec_edgar.py index 2a43059..838b5af 100644 --- a/tests/test_sec_edgar.py +++ b/tests/test_sec_edgar.py @@ -565,3 +565,66 @@ def flow(start, end, value, filed, form="10-Q"): assert facts["ttm_net_income"] == [{"filed": "2026-02-01", "end": "2025-12-31", "val": 100}] assert facts["shares"] == [{"filed": "2026-02-01", "end": "2026-01-20", "val": 10}] assert facts["share_basis"] == "cover_shares_outstanding" + + +def test_form4_cache_key_version_re_parses_remarks_over_legacy_cache(monkeypatch, tmp_path): + from datetime import date, timedelta + + import _cache as cache_mod + + monkeypatch.setattr(cache_mod, "CACHE_DIR", tmp_path) + accn = "0000320193-26-000201" + recent_filing = (date.today() - timedelta(days=7)).isoformat() + orig_filing = (date.today() - timedelta(days=9)).isoformat() + tx_date = (date.today() - timedelta(days=10)).isoformat() + # Pre-seed legacy cache entries missing `remarks` / `original_filing_date` / `acceptance_datetime`. + for prefix in ("sec-form4", "sec-form4-v2", "sec-form4-v3"): + sec_edgar.cached( + f"{prefix}:0000320193:{accn}", + sec_edgar.WEEK, + lambda: [{"form": "4/A", "transaction_code": "S", "shares": 10}], + ) + + accept_ts_early = f"{recent_filing}T14:00:00.000Z" + accept_ts_late = f"{recent_filing}T16:00:00.000Z" + accn_late_small_prefix = "0000111111-26-000202" + + def get(url, **kwargs): + if url.endswith("company_tickers.json"): + return response({"0": {"ticker": "AAPL", "cik_str": 320193}}) + if "submissions" in url: + return response( + { + "filings": { + "recent": { + "form": ["4/A", "4/A"], + "accessionNumber": [accn, accn_late_small_prefix], + "filingDate": [recent_filing, recent_filing], + "acceptanceDateTime": [accept_ts_early, accept_ts_late], + "reportDate": [tx_date, tx_date], + "primaryDocument": ["form4a.xml", "form4a2.xml"], + }, + "files": [], + } + } + ) + return response( + f"""{orig_filing}0000320193{tx_date}S10150DAmending to report an inadvertently omitted sale.""" + ) + + monkeypatch.setattr("requests.get", get) + result = sec_edgar.insider_trades(Namespace(symbol="AAPL", days=90, top=10)) + # Same-day cross-submitter filings are sorted by acceptanceDateTime descending (16:00Z before 14:00Z). + assert [tx["accession"] for tx in result["transactions"]] == [accn_late_small_prefix, accn] + assert result["transactions"][0]["acceptance_datetime"] == accept_ts_late + assert result["transactions"][1]["acceptance_datetime"] == accept_ts_early + assert result["transactions"][1]["remarks"] == "Amending to report an inadvertently omitted sale." + assert result["transactions"][1]["original_filing_date"] == orig_filing + v4_rows = sec_edgar.cached( + f"sec-form4-v4:0000320193:{accn}", + sec_edgar.WEEK, + lambda: pytest.fail("expected v4 Form 4 cache entry to be populated"), + ) + assert v4_rows[0]["remarks"] == "Amending to report an inadvertently omitted sale." + assert v4_rows[0]["original_filing_date"] == orig_filing + assert v4_rows[0]["acceptance_datetime"] == accept_ts_early diff --git a/tests/test_signal_tracker.py b/tests/test_signal_tracker.py index 5769c27..97d2c91 100644 --- a/tests/test_signal_tracker.py +++ b/tests/test_signal_tracker.py @@ -131,17 +131,22 @@ def test_quote_failure_is_error(self, store, mock_run_tool): assert not store.exists() -class TestEvaluate: - @pytest.fixture(autouse=True) - def _freeze_now(self, monkeypatch): - """Pin datetime.now so _kline_count's elapsed-days computation is deterministic.""" +@pytest.fixture +def freeze_now(monkeypatch): + """Pin datetime.now so elapsed-days and dividend lookback computations are deterministic.""" + + class _FrozenDateTime(datetime): + @classmethod + def now(cls, tz=None): + return cls(2026, 9, 18) - class _FrozenDateTime(datetime): - @classmethod - def now(cls, tz=None): - return cls(2026, 9, 18) + monkeypatch.setattr(st, "datetime", _FrozenDateTime) - monkeypatch.setattr(st, "datetime", _FrozenDateTime) + +class TestEvaluate: + @pytest.fixture(autouse=True) + def _freeze_now(self, freeze_now): + pass def _record(self, store, mock_run_tool, **over): return st.cmd_record(_rec_args(store, **over)) @@ -589,6 +594,303 @@ def test_unverified_price_basis_never_closes_original_price_signal(store, mock_r ) +def test_keyless_qfq_settles_when_no_corporate_action_and_price_consistent(store, mock_run_tool, freeze_now): + st.cmd_record(_rec_args(store, date="2026-09-01", entry_price=100, stop_price=90, target_price=120, horizon_days=2)) + bars = [ + {"date": "2026-09-01", "open": 99, "high": 102, "low": 98, "close": 100, "adjusted": "qfq"}, + {"date": "2026-09-02", "open": 101, "high": 122, "low": 100, "close": 121, "adjusted": "qfq"}, + ] + div_calls = [] + + def fake_run(script, args, **kwargs): + if script == "stock_data.py": + return bars + if script == "value_data.py" and args[0] == "dividends": + div_calls.append(args) + return { + "source": "eastmoney", + "as_of": "2026-09-18", + "cache_bypassed": True, + "history_current_through": "2026-09-18", + "history_years_requested": 2, + "splits_checked": True, + "splits": [], + "capital_gains_checked": True, + "capital_gains": [], + "corporate_actions_complete": True, + "history": [{"ex_date": "2026-06-15", "cash_per_share": 1.2, "status": "实施分配"}], + "calendar": [], + "warnings": [], + } + return None + + mock_run_tool.side_effect = fake_run + result = st.cmd_evaluate(Namespace(symbol=None, store=str(store))) + assert result["closed"] == 1 + assert result["results"][0]["outcome"] == "target_hit" + assert result["results"][0]["return_pct"] == 20.0 + assert "--market" not in div_calls[0] + assert "--no-cache" in div_calls[0] + saved = st._load_records(store)[0] + assert saved["evaluation_price_basis"] == { + "adjusted": "qfq", + "factor": 1.0, + "verification": "no_corporate_action_verified", + } + + +def test_keyless_qfq_skips_when_ex_dividend_or_split_or_empty_history_or_price_outside_anchor( + store, mock_run_tool, freeze_now +): + # Case 1: ex-dividend inside window, empty history, split, unchecked splits, short window, or cached/stale history + st.cmd_record(_rec_args(store, date="2026-09-01", entry_price=100, stop_price=90, target_price=120, horizon_days=2)) + bars = [ + {"date": "2026-09-01", "open": 99, "high": 102, "low": 98, "close": 100, "adjusted": "qfq"}, + {"date": "2026-09-02", "open": 101, "high": 122, "low": 100, "close": 121, "adjusted": "qfq"}, + ] + base_div = { + "source": "eastmoney", + "as_of": "2026-09-18", + "cache_bypassed": True, + "history_current_through": "2026-09-18", + "history_years_requested": 2, + "splits_checked": True, + "splits": [], + "capital_gains_checked": True, + "capital_gains": [], + "corporate_actions_complete": True, + "history": [{"ex_date": "2026-06-15", "cash_per_share": 1.2, "status": "实施分配"}], + "calendar": [], + "warnings": [], + } + cases = [ + {**base_div, "history": [{"ex_date": "2026-09-02", "cash_per_share": 2.0, "status": "实施分配"}]}, + {**base_div, "history": [], "warnings": ["no dividend history returned; absence is not interpreted as zero"]}, + {**base_div, "splits": [{"ex_date": "2026-09-02", "ratio": 2.0}]}, + {**base_div, "splits_checked": False}, + {**base_div, "capital_gains": [{"ex_date": "2026-09-02", "amount": 1.5}]}, + {**base_div, "capital_gains_checked": False}, + {**base_div, "corporate_actions_complete": False}, + {**base_div, "history_years_requested": 1}, + {**base_div, "cache_bypassed": False}, + {**base_div, "history_current_through": None}, + {**base_div, "history_current_through": "2026-09-01"}, + ] + for payload in cases: + mock_run_tool.side_effect = lambda script, args, p=payload, **kw: bars if script == "stock_data.py" else p + res = st.cmd_evaluate(Namespace(symbol=None, store=str(store))) + assert res["closed"] == 0 + assert res["results"][0]["outcome"] == "skipped_price_basis" + + # Case 2: entry price outside anchor bar [low, high] (e.g. entry=105 vs high=100) must skip + store2 = store.with_name("signals2.jsonl") + st.cmd_record( + _rec_args(store2, date="2026-09-01", entry_price=105, stop_price=90, target_price=120, horizon_days=2) + ) + tight_bars = [ + {"date": "2026-09-01", "open": 99, "high": 100, "low": 98, "close": 100, "adjusted": "qfq"}, + {"date": "2026-09-02", "open": 101, "high": 122, "low": 100, "close": 121, "adjusted": "qfq"}, + ] + mock_run_tool.side_effect = lambda script, args, **kw: tight_bars if script == "stock_data.py" else base_div + res2 = st.cmd_evaluate(Namespace(symbol=None, store=str(store2))) + assert res2["closed"] == 0 + assert res2["results"][0]["outcome"] == "skipped_price_basis" + + +def test_keyless_us_total_return_uses_cli_without_market_flag(store, mock_run_tool, freeze_now): + st.cmd_record( + _rec_args( + store, symbol="AAPL", date="2026-09-01", entry_price=200, stop_price=180, target_price=220, horizon_days=2 + ) + ) + bars = [ + {"date": "2026-09-01", "open": 199, "high": 202, "low": 198, "close": 200, "adjusted": "total_return"}, + {"date": "2026-09-02", "open": 201, "high": 225, "low": 200, "close": 222, "adjusted": "total_return"}, + ] + seen_div_args = [] + + def fake_run(script, args, **kwargs): + if script == "stock_data.py": + return bars + if script == "value_data.py" and args[0] == "dividends": + seen_div_args.append(args) + return { + "source": "yfinance", + "as_of": "2026-09-18", + "cache_bypassed": True, + "history_current_through": "2026-09-18", + "history_years_requested": 2, + "splits_checked": True, + "splits": [], + "capital_gains_checked": True, + "capital_gains": [], + "corporate_actions_complete": True, + "history": [{"ex_date": "2026-08-10", "cash_per_share": 0.25, "status": "paid"}], + "calendar": [], + "warnings": [], + } + return None + + mock_run_tool.side_effect = fake_run + res = st.cmd_evaluate(Namespace(symbol=None, store=str(store))) + assert res["closed"] == 1 + assert seen_div_args == [["dividends", "--symbol", "AAPL", "--mode", "history", "--years", "2", "--no-cache"]] + + +def test_keyless_us_dividends_provider_coverage_stops_before_last_bar_stays_unverified( + store, mock_run_tool, monkeypatch +): + import pandas as pd + + from tools import value_data + + class _NovNow(datetime): + @classmethod + def now(cls, tz=None): + return cls(2026, 11, 26) + + monkeypatch.setattr(st, "datetime", _NovNow) + monkeypatch.setattr(value_data, "market_now", lambda market: datetime(2026, 11, 26)) + st.cmd_record( + _rec_args( + store, symbol="AAPL", date="2026-11-23", entry_price=200, stop_price=180, target_price=220, horizon_days=2 + ) + ) + bars = [ + {"date": "2026-11-23", "open": 199, "high": 202, "low": 198, "close": 200, "adjusted": "total_return"}, + {"date": "2026-11-24", "open": 201, "high": 225, "low": 200, "close": 222, "adjusted": "total_return"}, + ] + + # Yahoo action-bearing daily history ends on 2026-09-12 -> must NOT verify 2026-11-23..11-24 + stale_ticker = Namespace( + history=lambda **kw: pd.DataFrame( + {"Close": [190.0, 195.0], "Dividends": [0.25, 0.0], "Stock Splits": [0.0, 0.0]}, + index=pd.DatetimeIndex(["2026-08-10", "2026-09-12"], tz="America/New_York", name="Date"), + ), + info={"currentPrice": 200.0, "currency": "USD"}, + calendar={}, + ) + monkeypatch.setattr("yfinance.Ticker", lambda s: stale_ticker) + + def bridge(script, args, **kwargs): + if script == "stock_data.py": + return bars + if script == "value_data.py" and args[0] == "dividends": + years = int(args[args.index("--years") + 1]) + return value_data.dividends( + Namespace( + symbol=args[args.index("--symbol") + 1], + mode="history", + report_date="", + top=20, + years=years, + no_cache="--no-cache" in args, + ) + ) + return None + + mock_run_tool.side_effect = bridge + res = st.cmd_evaluate(Namespace(symbol=None, store=str(store))) + assert res["closed"] == 0 + assert res["results"][0]["outcome"] == "skipped_price_basis" + + # Intervening ETF Capital Gains distribution must also reject factor-one verification + capgain_ticker = Namespace( + history=lambda **kw: pd.DataFrame( + { + "Close": [190.0, 222.0], + "Dividends": [0.25, 0.0], + "Stock Splits": [0.0, 0.0], + "Capital Gains": [0.0, 1.5], + }, + index=pd.DatetimeIndex(["2026-08-10", "2026-11-24"], tz="America/New_York", name="Date"), + ), + info={"currentPrice": 222.0, "currency": "USD"}, + calendar={}, + ) + monkeypatch.setattr("yfinance.Ticker", lambda s: capgain_ticker) + res_cg = st.cmd_evaluate(Namespace(symbol=None, store=str(store))) + assert res_cg["closed"] == 0 + assert res_cg["results"][0]["outcome"] == "skipped_price_basis" + + # Once Yahoo's action-bearing history actually covers through 2026-11-24 with no intervening events, verification succeeds + fresh_ticker = Namespace( + history=lambda **kw: pd.DataFrame( + {"Close": [190.0, 222.0], "Dividends": [0.25, 0.0], "Stock Splits": [0.0, 0.0]}, + index=pd.DatetimeIndex(["2026-08-10", "2026-11-24"], tz="America/New_York", name="Date"), + ), + info={"currentPrice": 222.0, "currency": "USD"}, + calendar={}, + ) + monkeypatch.setattr("yfinance.Ticker", lambda s: fresh_ticker) + res_ok = st.cmd_evaluate(Namespace(symbol=None, store=str(store))) + assert res_ok["closed"] == 1 + assert res_ok["results"][0]["outcome"] == "target_hit" + + +def test_keyless_a_share_eastmoney_dividends_stays_unverified_without_allotment_coverage( + store, mock_run_tool, monkeypatch +): + import akshare as ak + import pandas as pd + + from tools import value_data + + class _NovNow(datetime): + @classmethod + def now(cls, tz=None): + return cls(2026, 11, 26) + + monkeypatch.setattr(st, "datetime", _NovNow) + monkeypatch.setattr(value_data, "market_now", lambda market: datetime(2026, 11, 26)) + monkeypatch.setattr( + ak, + "stock_fhps_detail_em", + lambda **kw: pd.DataFrame( + { + "报告期": ["2026-06-30"], + "除权除息日": ["2026-08-28"], + "现金分红-现金分红比例": [10.0], + "送转股份-送转总比例": [0.0], + "方案进度": ["实施分配"], + } + ), + ) + monkeypatch.setattr("_subproc.run_tool", lambda *a, **kw: {"price": 100.0, "as_of": "2026-11-26"}) + + st.cmd_record( + _rec_args( + store, symbol="600519", date="2026-11-23", entry_price=100, stop_price=90, target_price=120, horizon_days=2 + ) + ) + bars = [ + {"date": "2026-11-23", "open": 99, "high": 102, "low": 98, "close": 100, "adjusted": "qfq"}, + {"date": "2026-11-24", "open": 101, "high": 122, "low": 100, "close": 121, "adjusted": "qfq"}, + ] + + def bridge(script, args, **kwargs): + if script == "stock_data.py": + return bars + if script == "value_data.py" and args[0] == "dividends": + years = int(args[args.index("--years") + 1]) + return value_data.dividends( + Namespace( + symbol=args[args.index("--symbol") + 1], + mode="history", + report_date="", + top=20, + years=years, + no_cache="--no-cache" in args, + ) + ) + return None + + mock_run_tool.side_effect = bridge + res = st.cmd_evaluate(Namespace(symbol=None, store=str(store))) + assert res["closed"] == 0 + assert res["results"][0]["outcome"] == "skipped_price_basis" + + def test_verified_adjustment_factor_keeps_split_return_correct(store, mock_run_tool): st.cmd_record(_rec_args(store, entry_price=100, stop_price=90, target_price=120, horizon_days=1)) bars = [_bar("2026-09-01", 50, 50, 50), _bar("2026-09-02", 51, 50, 51)] diff --git a/tests/test_value_data.py b/tests/test_value_data.py index c227c1c..513ed56 100644 --- a/tests/test_value_data.py +++ b/tests/test_value_data.py @@ -1380,3 +1380,63 @@ def test_us_valuation_history_uses_filed_facts_and_split_adjusted_shares(monkeyp assert result["source"] == "sec_companyfacts+yfinance" assert result["history"] == [{"date": "2026-03-06", "pe_ttm": 10.0, "pb": 2.0}] assert result["share_basis"] == "cover_shares_outstanding" + + +def test_us_dividends_splits_checked_requires_verified_history_and_no_cache(monkeypatch): + from tools import value_data + + # 1. Single action-bearing history derives cash, splits, and provider coverage (NOT today's date) + hist_calls = [] + + def ok_history(**kwargs): + hist_calls.append(kwargs) + return pd.DataFrame( + {"Close": [100.0, 102.0], "Dividends": [0.25, 0.0], "Stock Splits": [0.0, 0.0]}, + index=pd.DatetimeIndex(["2026-08-01", "2026-09-12"], tz="America/New_York", name="Date"), + ) + + ticker_ok = Namespace( + history=ok_history, + info={"currentPrice": 100.0, "currency": "USD"}, + calendar={}, + ) + monkeypatch.setattr("yfinance.Ticker", lambda s: ticker_ok) + monkeypatch.setattr(value_data, "cached", _fail) # --no-cache must bypass cache completely + res = value_data.dividends(Namespace(symbol="AAPL", mode="history", report_date="", top=20, years=2, no_cache=True)) + assert res["splits_checked"] is True + assert res["splits"] == [] + assert len(res["history"]) == 1 and res["history"][0]["ex_date"] == "2026-08-01" + assert res["cache_bypassed"] is True + assert res["history_covered_from"] == "2026-08-01" + # Provider history ended on 2026-09-12 — must NOT fabricate request-day as_of + assert res["history_current_through"] == "2026-09-12" + assert hist_calls == [{"period": "max", "actions": True, "raise_errors": True}] + + # 2. Empty DataFrame returned by failed history request must NOT set splits_checked=True or history_current_through + ticker_empty = Namespace( + history=lambda **kw: pd.DataFrame(), + info=ticker_ok.info, + calendar={"Ex-Dividend Date": date(2026, 12, 1)}, + ) + monkeypatch.setattr("yfinance.Ticker", lambda s: ticker_empty) + res_empty = value_data.dividends( + Namespace(symbol="AAPL", mode="history", report_date="", top=20, years=2, no_cache=True) + ) + assert res_empty["splits_checked"] is False + assert res_empty["history_current_through"] is None + + # 3. Exception raised by history must NOT set splits_checked=True or history_current_through + def boom(**kw): + raise RuntimeError("network error") + + ticker_err = Namespace( + history=boom, + info=ticker_ok.info, + calendar={"Ex-Dividend Date": date(2026, 12, 1)}, + ) + monkeypatch.setattr("yfinance.Ticker", lambda s: ticker_err) + res_err = value_data.dividends( + Namespace(symbol="AAPL", mode="history", report_date="", top=20, years=2, no_cache=True) + ) + assert res_err["splits_checked"] is False + assert res_err["history_current_through"] is None diff --git a/tests/test_workflow_performance.py b/tests/test_workflow_performance.py index 5c5a7a2..1ff8b8a 100644 --- a/tests/test_workflow_performance.py +++ b/tests/test_workflow_performance.py @@ -129,7 +129,7 @@ def collect(script, args, **kwargs): return "{}" monkeypatch.setattr(gather, "_run", collect) - gather.gather_analysis("AAPL") + gather.gather_analysis("600519") assert observed == [True] diff --git a/tools/_etf_data.py b/tools/_etf_data.py new file mode 100644 index 0000000..8a6226d --- /dev/null +++ b/tools/_etf_data.py @@ -0,0 +1,298 @@ +"""ETF tracking error, AUM scale, SSE/SZSE PCF basket, and disclosed equity helpers (extracted from value_data.py).""" + +import json +import math +import re +from datetime import date, datetime, timedelta +from io import StringIO +from xml.etree import ElementTree +from zoneinfo import ZoneInfo + +import numpy as np +import pandas as pd +from _cache import DAY, cached +from _fund_data import fund_pingzhong_js + + +def _cn_now() -> datetime: + return datetime.now(ZoneInfo("Asia/Shanghai")) + + +def _number(value): + try: + out = float(value) + except (TypeError, ValueError): + return None + return out if math.isfinite(out) else None + + +def _iso(value): + if value is None or (isinstance(value, float) and math.isnan(value)): + return None + text = str(value).strip() + if not text or text.lower() in ("nan", "nat", "none"): + return None + if re.fullmatch(r"\d{8}", text): + return f"{text[:4]}-{text[4:6]}-{text[6:]}" + return text[:10] if re.match(r"\d{4}-\d{2}-\d{2}", text) else text + + +def tracking_error(nav, benchmark): + if not nav or not benchmark: + return { + "annualized_tracking_error_pct": None, + "observations": 0, + "note": "fund NAV or benchmark history unavailable", + } + fund = pd.DataFrame(nav).drop_duplicates("date").set_index("date").sort_index() + index = pd.DataFrame(benchmark).drop_duplicates("date").set_index("date").sort_index() + fund_returns = pd.to_numeric(fund["daily_return_pct"], errors="coerce") / 100 + close = pd.to_numeric(index["close"], errors="coerce") + index_returns = close.pct_change(fill_method=None) + try: + import exchange_calendars as xcals + + calendar = xcals.get_calendar("XSHG") + previous = { + stamp: calendar.previous_session(stamp).date().isoformat() + for stamp in fund.index.union(index.index) + if calendar.is_session(stamp) + } + except Exception: + return {"annualized_tracking_error_pct": None, "observations": 0, "note": "ETF trading calendar unavailable"} + matched = ( + pd.concat( + [ + fund_returns.rename("fund"), + index_returns.rename("benchmark"), + fund.index.to_series().shift().rename("fund_previous"), + index.index.to_series().shift().rename("benchmark_previous"), + pd.Series(previous).rename("session_previous"), + ], + axis=1, + ) + .replace([np.inf, -np.inf], np.nan) + .dropna() + ) + matched = matched[ + (matched["fund_previous"] == matched["session_previous"]) + & (matched["benchmark_previous"] == matched["session_previous"]) + ] + active = matched["fund"] - matched["benchmark"] + return { + "annualized_tracking_error_pct": round(float(active.std(ddof=1) * np.sqrt(252) * 100), 4) + if len(active) >= 2 + else None, + "observations": len(active), + "window_start": matched.index[0] if len(active) else None, + "window_end": matched.index[-1] if len(active) else None, + "basis": "daily published NAV growth minus benchmark close return; sample std, 252 trading days; only matching consecutive ETF trading-session intervals, no missing-date fill", + } + + +def fund_size_history(symbol, *, fetch_js=None, cache_fn=None): + def fetch(): + match = re.search(r"\bData_fluctuationScale\s*=\s*(.*?);", (fetch_js or fund_pingzhong_js)(symbol), re.S) + if not match: + raise ValueError("fund scale history unavailable") + data = json.loads(match.group(1)) + if len(data["categories"]) != len(data["series"]): + raise ValueError("fund scale dates and observations do not match") + return [ + {"date": _iso(stamp), "aum_cny": _number(row.get("y")) * 1e8} + for stamp, row in zip(data["categories"], data["series"], strict=True) + if _iso(stamp) and _number(row.get("y")) is not None + ] + + return (cache_fn or cached)(f"etf-size:{symbol}", DAY, fetch) + + +def etf_basket(symbol, *, cache_fn=None, now_fn=None): + import requests + + clock = now_fn or _cn_now + + def fetch(): + if symbol.startswith("5"): + response = requests.get( + "https://query.sse.com.cn/etfDownload/downloadETF2Bulletin.do", + params={"fundCode": symbol}, + headers={"Referer": "https://www.sse.com.cn/"}, + timeout=20, + ) + source = "SSE PCF" + else: + response = requests.get( + "https://www.szse.cn/api/report/ShowReport/data", + params={ + "SHOWTYPE": "JSON", + "CATALOGID": "sgshqd", + "txtJCorDH": symbol, + "txtStart": (clock().date() - timedelta(days=30)).isoformat(), + "txtEnd": clock().date().isoformat(), + }, + headers={"Referer": "https://www.szse.cn/"}, + timeout=20, + ) + response.raise_for_status() + dates = re.findall(rf"pcf_{re.escape(symbol)}_(\d{{8}})", json.dumps(response.json())) + dates = [d for d in dates if _iso(d) and _iso(d) <= clock().date().isoformat()] + if not dates: + raise ValueError("no published SZSE PCF found") + response = requests.get( + f"https://reportdocs.static.szse.cn/files/text/ETFDown/pcf_{symbol}_{max(dates)}.xml", timeout=20 + ) + source = "SZSE PCF" + response.raise_for_status() + if b" clock().date().isoformat() + or not unit + or unit <= 0 + or count != len(components) + or not components + ): + raise ValueError("incomplete or mismatched PCF document") + rows = [] + for node in components: + code = node.findtext("InstrumentID") or node.findtext("UnderlyingSecurityID") + quantity = _number(node.findtext("Quantity") or node.findtext("ComponentShare")) + if not code or quantity is None or quantity < 0: + raise ValueError("invalid PCF component") + rows.append( + { + "code": code, + "name": node.findtext("InstrumentName") or node.findtext("UnderlyingSymbol"), + "quantity_per_unit": quantity, + "exchange_code": node.findtext("UnderlyingSecurityID") + if root.tag == "SSEPortfolioCompositionFile" + else node.findtext("UnderlyingSecurityIDSource"), + "cash_substitution_flag": node.findtext("SubstitutionFlag") or node.findtext("SubstituteFlag"), + "creation_premium_rate": _number( + node.findtext("CreationPremiumRate") or node.findtext("PremiumRatio") + ), + "redemption_discount_rate": _number( + node.findtext("RedemptionDiscountRate") or node.findtext("DiscountRatio") + ), + "substitution_cash_amount": _number(node.findtext("SubstitutionCashAmount")), + "creation_cash_substitute": _number(node.findtext("CreationCashSubstitute")), + "redemption_cash_substitute": _number(node.findtext("RedemptionCashSubstitute")), + } + ) + return { + "source": source, + "as_of": stamp, + "previous_trading_day": _iso(root.findtext("PreTradingDay")), + "creation_redemption_unit": unit, + "previous_nav": { + "as_of": _iso(root.findtext("PreTradingDay")), + "nav_per_unit": _number(root.findtext("NAV")), + "nav_per_creation_unit": _number(root.findtext("NAVperCU")), + }, + "previous_cash_component": _number(root.findtext("PreCashComponent") or root.findtext("CashComponent")), + "estimated_cash_component": _number( + root.findtext("EstimatedCashComponent") or root.findtext("EstimateCashComponent") + ), + "cash_unit": "CNY per creation/redemption unit", + "max_cash_substitution_ratio": _number(root.findtext("MaxCashRatio")), + "creation_redemption_switch": root.findtext("CreationRedemptionSwitch"), + "creation_flag": root.findtext("Creation"), + "redemption_flag": root.findtext("Redemption"), + "record_count": len(rows), + "complete": True, + "components": rows, + "basis": "complete published creation/redemption basket, not actual fund holdings; quantities per creation unit, rates are fractions", + } + + return (cache_fn or cached)(f"etf-basket:{symbol}", DAY, fetch) + + +def fund_disclosed_equities(symbol, *, cache_fn=None, now_fn=None): + import requests + + clock = now_fn or _cn_now + + try: + from akshare.utils.jsonish import loads as decode + except ImportError: + from akshare.utils.demjson import decode + from bs4 import BeautifulSoup + + limit = 10000 + + def fetch(stamp): + response = requests.get( + "https://fundf10.eastmoney.com/FundArchivesDatas.aspx", + params={"type": "jjcc", "code": symbol, "topline": limit, "year": stamp[:4], "month": str(int(stamp[5:7]))}, + headers={"Referer": f"https://fundf10.eastmoney.com/ccmx_{symbol}.html"}, + timeout=20, + ) + response.raise_for_status() + text = response.text + payload = decode(text[text.index("{") : text.rindex("}") + 1]) + soup = BeautifulSoup(payload["content"], "lxml") + for block in soup.select("div.boxitem"): + heading = block.find("h4") + link = heading.find("a", href=True) if heading else None + if not heading or not link or not link["href"].endswith(f"/{symbol}.html"): + continue + match = re.search(r"\d{4}-\d{2}-\d{2}", heading.get_text()) + if not match or match.group() != stamp: + continue + table = block.find("table") + if table is None: + raise ValueError("disclosed equity table unavailable") + frame = pd.read_html(StringIO(str(table)), converters={"股票代码": str})[0] + frame.columns = [re.sub(r"\s+", "", str(c)) for c in frame.columns] + value_column = next((c for c in frame.columns if c in ("持仓市值(万元)", "持仓市值(万元人民币)")), None) + if not {"股票代码", "股票名称", "占净值比例", "持股数(万股)"}.issubset(frame.columns) or not value_column: + raise ValueError("unknown disclosed equity units/schema") + if frame.empty or len(frame) >= limit: + raise ValueError("empty or potentially truncated disclosed equity table") + positions = [] + for row in frame.to_dict("records"): + quantity = _number(str(row["持股数(万股)"]).replace(",", "")) + value = _number(str(row[value_column]).replace(",", "")) + positions.append( + { + "code": str(row["股票代码"]), + "name": str(row["股票名称"]) if pd.notna(row["股票名称"]) else None, + "weight_pct": _number(str(row["占净值比例"]).replace("%", "")), + "quantity_shares": quantity * 10000 if quantity is not None else None, + "market_value_cny": value * 10000 if value is not None else None, + } + ) + return { + "source": "eastmoney periodic equity report", + "as_of": stamp, + "is_realtime": False, + "position_count": len(positions), + "equity_positions": positions, + "coverage": "all received source-table equity rows, not total fund assets; source completeness is not independently verified", + "source_url": f"https://fundf10.eastmoney.com/ccmx_{symbol}.html", + } + raise ValueError("requested semiannual/annual equity report not available") + + end = date(clock().date().year, ((clock().date().month - 1) // 6) * 6 + 1, 1) - timedelta(days=1) + requested = end.isoformat() + for _ in range(2): + stamp = end.isoformat() + try: + result = (cache_fn or cached)(f"fund-equity-report:{symbol}:{stamp}", DAY, lambda stamp=stamp: fetch(stamp)) + return {**result, "requested_report_date": requested} + except Exception: + end = date(end.year, end.month - 5, 1) - timedelta(days=1) + raise ValueError("latest disclosed semiannual/annual equity report unavailable") diff --git a/tools/_fund_data.py b/tools/_fund_data.py new file mode 100644 index 0000000..c74aad9 --- /dev/null +++ b/tools/_fund_data.py @@ -0,0 +1,235 @@ +"""Open-end fund NAV and TIAA investment-advisory portfolio helpers (extracted from stock_data.py).""" + +import json +import math +import re +from datetime import datetime, timezone +from zoneinfo import ZoneInfo + +from _subproc import error_message + +_YOUZHIYOUXING_TIAA = { + "TIAA001001": "长钱账户", + "TIAA001002": "海外长钱", + "TIAA001004": "稳钱账户", +} + + +def _parse_float(value): + try: + v = float(value) + return v if math.isfinite(v) else None + except (TypeError, ValueError): + return None + + +def _unix_quote_time(value) -> str | None: + try: + ts = float(value) + if not math.isfinite(ts) or ts <= 0: + return None + if ts > 1e12: + ts /= 1000.0 + return datetime.fromtimestamp(ts, timezone.utc).isoformat() + except (TypeError, ValueError, OverflowError, OSError): + return None + + +def _cn_now() -> datetime: + return datetime.now(ZoneInfo("Asia/Shanghai")) + + +def _clean_row(d: dict) -> dict: + return {k: (None if isinstance(v, float) and (math.isnan(v) or math.isinf(v)) else v) for k, v in d.items()} + + +def _quote_tiaa(symbol: str, *, include_disclosures: bool = True) -> dict: + import requests + + disclosure_name = _YOUZHIYOUXING_TIAA.get(symbol) + result = { + "symbol": symbol, + "name": disclosure_name, + "asset_type": "investment_advisory_portfolio", + "type_description": "雪球投顾组合,无统一单位净值", + "manager": None, + "advisor_code": f"A{symbol[4:7]}", + "advisor_org": None, + "advisor_mapping_basis": "tiaa_prefix_best_effort", + "advisor_source_url": None, + "advisor_retrieved_at": None, + "nav": None, + "example_account_performance": None, + "quote_type": None, + "exchange": None, + "source": None, + "source_url": f"https://xueqiu.com/S/{symbol}", + "data_as_of": None, + "fetched_at": datetime.now(timezone.utc).isoformat(), + "official_disclosures": [], + "public_search_results": [], + "disclosure_provider": "youzhiyouxing" if disclosure_name else None, + "disclosure_status": "unavailable" if disclosure_name else "unsupported_provider", + "disclosures_partial": True, + "disclosures_as_of": None, + "note": ( + "投顾组合无统一净值;主理人及完整业绩/持仓需在对应投顾平台登录后查询;" + "官方公开披露仅为部分历史信息,持有人收益随买入时点和调仓跟进不同" + ), + } + try: + from tiaa_disclosures import advisor_metadata + + result.update(advisor_metadata(symbol)) + except Exception: + result.setdefault("warnings", []).append("advisor organization metadata unavailable") + if not include_disclosures and disclosure_name: + return result + + try: + with requests.Session() as session: + session.get( + "https://xueqiu.com/", + headers={"User-Agent": "Mozilla/5.0"}, + timeout=10, + allow_redirects=True, + ).raise_for_status() + response = session.get( + "https://stock.xueqiu.com/v5/stock/quote.json", + params={"symbol": symbol, "extend": "detail"}, + headers={"User-Agent": "Mozilla/5.0", "Referer": "https://xueqiu.com/"}, + timeout=10, + ) + response.raise_for_status() + payload = response.json() + if payload.get("error_code") not in (None, 0): + raise ValueError("xueqiu portfolio metadata unavailable") + quote = (payload.get("data") or {}).get("quote") or {} + if quote.get("symbol") != symbol: + raise ValueError("xueqiu returned different portfolio metadata") + result.update( + name=quote.get("name") or disclosure_name, + quote_type=quote.get("type"), + exchange=quote.get("exchange"), + source="xueqiu", + data_as_of=_unix_quote_time(quote.get("timestamp")), + ) + except Exception: + result.setdefault("warnings", []).append( + "xueqiu portfolio metadata unavailable; type guidance remains available" + ) + if not include_disclosures: + return result + + if disclosure_name and result["name"] in (None, disclosure_name): + try: + from tiaa_disclosures import public_disclosures + + disclosure = public_disclosures(symbol, disclosure_name) + result["official_disclosures"] = disclosure["items"] + result["disclosures_as_of"] = disclosure["as_of"] + if disclosure["items"]: + result["disclosure_status"] = "partial_public" + except Exception: + result.setdefault("warnings", []).append( + "official public disclosures unavailable; type guidance remains available" + ) + elif disclosure_name and result["name"]: + result["disclosure_status"] = "unsupported_provider" + result.setdefault("warnings", []).append("portfolio name does not match the registered disclosure source") + else: + from tiaa_disclosures import search_public + + result["public_search_results"] = search_public(symbol, result["name"]) + if result["public_search_results"]: + result["disclosure_provider"] = "web_search" + result["disclosure_status"] = "search_partial" + return result + + +def _fund_js_value(text: str, name: str): + match = re.search(rf"\b{re.escape(name)}\s*=\s*", text) + if not match: + raise ValueError(f"eastmoney fund data missing {name}") + try: + return json.JSONDecoder().raw_decode(text[match.end() :])[0] + except json.JSONDecodeError as exc: + raise ValueError(f"eastmoney fund data has invalid {name}") from exc + + +def _fund_nav_date(stamp) -> str: + return datetime.fromtimestamp(stamp / 1000, timezone.utc).astimezone(ZoneInfo("Asia/Shanghai")).date().isoformat() + + +def fund_pingzhong_js(symbol: str) -> str: + """Eastmoney's per-fund JS bundle (NAV, scale, holdings series).""" + import requests + + response = requests.get(f"https://fund.eastmoney.com/pingzhongdata/{symbol}.js", timeout=15) + response.raise_for_status() + return response.text + + +def cmd_fund_quote(args, *, trend_count: int = 0, fetch_js=None): + symbol = args.symbol + if not re.fullmatch(r"\d{6}", symbol): + return {"error": "open-end fund symbol must be exactly 6 digits"} + try: + text = (fetch_js or fund_pingzhong_js)(symbol) + if _fund_js_value(text, "fS_code") != symbol: + raise ValueError(f"eastmoney returned a different fund for {symbol}") + name = _fund_js_value(text, "fS_name") + nav_rows = _fund_js_value(text, "Data_netWorthTrend") + accumulated_rows = [] if trend_count else _fund_js_value(text, "Data_ACWorthTrend") + points = [] + for row in reversed(nav_rows): + if not isinstance(row, dict): + continue + nav = _parse_float(row.get("y")) + if nav is None or not math.isfinite(nav) or nav <= 0: + continue + try: + day = _fund_nav_date(row.get("x")) + except (TypeError, ValueError, OverflowError, OSError): + continue + points.append((row, day, nav)) + if len(points) >= max(1, trend_count): + break + if not points: + raise ValueError(f"eastmoney returned no NAV for {symbol}") + latest, nav_date, nav = points[0] + accumulated_by_date = {_fund_nav_date(row[0]): row[1] for row in accumulated_rows} + today = _cn_now().date().isoformat() + result = _clean_row( + { + "symbol": symbol, + "name": name, + "asset_type": "open_end_fund", + "nav": nav, + "accumulated_nav": accumulated_by_date.get(nav_date), + "change_pct": latest.get("equityReturn"), + "nav_date": nav_date, + "data_as_of": nav_date, + "as_of": nav_date, + "as_of_basis": "provider", + "stale": nav_date < today, + "source": "eastmoney", + "source_url": f"https://fund.eastmoney.com/{symbol}.html", + "fetched_at": datetime.now(timezone.utc).isoformat(), + "note": ( + "nav is published end-of-day NAV, not a real-time price; QDII disclosure may lag " + "1-2 trading days; no intraday estimated NAV is provided" + ), + # Eastmoney retired its per-fund intraday estimate (fundgz); its remaining estimate + # page lists every fund at once, so the estimate keys stay but are always unavailable. + "estimated_nav": None, + "estimated_change_pct": None, + "estimated_at": None, + "estimate_status": "unavailable", + } + ) + if trend_count: + result["trend"] = [{"date": day, "close": nav} for _, day, nav in reversed(points)] + return result + except Exception as e: + return {"error": error_message(e)} diff --git a/tools/backtest.py b/tools/backtest.py index 9938c36..f0cd426 100644 --- a/tools/backtest.py +++ b/tools/backtest.py @@ -2,12 +2,13 @@ """AlphaEvo — strategy backtesting engine with YAML DSL.""" import argparse +import contextlib import json import math import os import re import sys -from datetime import datetime, timedelta +from datetime import date, datetime, timedelta import numpy as np import pandas as pd @@ -658,10 +659,747 @@ def simulate_monthly_market( } +_BIWEEKLY_ANCHOR = date(1970, 1, 5) # Monday epoch for continuous 14-day buckets across year boundaries + + +def _schedule_bucket(ts: pd.Timestamp, frequency: str): + if frequency == "weekly": + iso = ts.isocalendar() + return (int(iso.year), int(iso.week)) + if frequency == "biweekly": + return (ts.date() - _BIWEEKLY_ANCHOR).days // 14 + if frequency == "monthly": + return (ts.year, ts.month) + if frequency == "quarterly": + return (ts.year, (ts.month - 1) // 3) + raise ValueError(f"Unsupported schedule frequency: {frequency}") + + +def _canonical_symbol(symbol: str) -> str: + raw = str(symbol).strip() + upper = raw.upper() + # A-share explicit indices keep lowercase prefix (sh000xxx / sz399xxx) + if re.fullmatch(r"(?:SH000|SZ399)\d{3}", upper): + return upper.lower() + # A-share stocks / ETFs: sh600519 and 600519 refer to the same instrument + m_cn = re.fullmatch(r"(?:SH|SZ|BJ)(\d{6})", upper) + if m_cn: + return m_cn.group(1) + # HK stocks / ETFs: 700.HK / 0700.HK / 00700.HK refer to the same instrument + m_hk = re.fullmatch(r"0*(\d{1,5})\.HK", upper) + if m_hk: + return f"{int(m_hk.group(1)):05d}.HK" + return upper + + +def _infer_currency(symbol: str, market: str, df: pd.DataFrame) -> str | None: + if "currency" in df.columns: + vals = {str(v).strip().upper() for v in df["currency"].dropna().tolist() if str(v).strip()} + if len(vals) > 1: + raise ValueError(f"Mixed currencies within dataset for {symbol}: {sorted(vals)}") + if len(vals) == 1: + return next(iter(vals)) + if market == "A": + return "CNY" + if market == "US": + return "USD" + if market == "JP": + return "JPY" + if market == "KR": + return "KRW" + if market == "TW": + return "TWD" + if market == "HK": + # HKEX Stock Code Allocation Plan: + # 80000-89999 = RMB counters; USD ETF / L&I counters = 9000-9599, 9700-9849, 41500-41599. + # Main-board equities in 9600-9699 (e.g. 9618.HK) and 9850-9999 (e.g. 9988.HK) trade in HKD. + m = re.fullmatch(r"0*(\d{1,5})\.HK", _canonical_symbol(symbol)) + if m: + code = int(m.group(1)) + if 80000 <= code <= 89999: + return "CNY" + if (9000 <= code <= 9599) or (9700 <= code <= 9849) or (41500 <= code <= 41599): + return "USD" + return "HKD" + return None + + +def _parse_portfolio_config(strategy: dict, symbols: list[str], *, signal_mode: bool = False) -> dict: + portfolio_cfg = strategy.get("portfolio") or {} + pos_cfg = strategy.get("position") or {} + dca_cfg = strategy.get("dca") or {} + + rebalance = str(portfolio_cfg.get("rebalance", "none")).lower() + if rebalance not in ("none", "weekly", "monthly", "quarterly"): + raise ValueError("portfolio.rebalance must be one of none, weekly, monthly, quarterly") + if signal_mode and rebalance != "none": + raise ValueError( + "portfolio.rebalance is only supported in allocation mode (omit entry.conditions or set rebalance: none)" + ) + + weighting = str(portfolio_cfg.get("weighting", "equal")).lower() + if weighting not in ("equal", "custom"): + raise ValueError("portfolio.weighting must be equal or custom") + + if weighting == "custom": + raw_weights = portfolio_cfg.get("weights") + if not isinstance(raw_weights, dict) or not raw_weights: + raise ValueError("portfolio.weights must be a non-empty mapping when weighting=custom") + norm_weights: dict[str, float] = {} + for raw_k, raw_v in raw_weights.items(): + key = _canonical_symbol(str(raw_k)) + if key in norm_weights: + raise ValueError(f"Duplicate weight entry after symbol normalization: {raw_k!r}") + w = float(raw_v) + if not math.isfinite(w) or w < 0: + raise ValueError(f"portfolio.weights[{raw_k}] must be a non-negative finite number") + norm_weights[key] = w + weights = {sym: norm_weights.get(_canonical_symbol(sym), 0.0) for sym in symbols} + total_w = sum(weights.values()) + if not (0 < total_w <= 1.0001): + raise ValueError(f"portfolio.weights sum must be in (0, 1], got {round(total_w, 4)}") + else: + w = 1.0 / len(symbols) + weights = {sym: w for sym in symbols} + + drift = portfolio_cfg.get("drift_threshold") + if drift is not None: + drift = float(drift) + if not math.isfinite(drift) or not 0 < drift < 1: + raise ValueError("portfolio.drift_threshold must be in (0, 1)") + + size_frac = float(pos_cfg.get("size", 1.0)) + if not math.isfinite(size_frac) or not 0 <= size_frac <= 1: + raise ValueError("position.size must be a fraction in [0, 1]") + + max_positions = portfolio_cfg.get("max_positions", pos_cfg.get("max_positions", len(symbols))) + if isinstance(max_positions, bool) or not isinstance(max_positions, int) or max_positions <= 0: + raise ValueError("max_positions must be a positive integer") + + dca = None + if dca_cfg: + freq = str(dca_cfg.get("frequency", "monthly")).lower() + if freq not in ("weekly", "biweekly", "monthly", "quarterly"): + raise ValueError("dca.frequency must be weekly, biweekly, monthly, or quarterly") + amt = float(dca_cfg.get("amount", 0)) + if not math.isfinite(amt) or amt <= 0: + raise ValueError("dca.amount must be a finite positive number") + dca = {"frequency": freq, "amount": amt} + + return { + "rebalance": rebalance, + "weighting": weighting, + "weights": weights, + "drift_threshold": drift, + "size": size_frac, + "max_positions": max_positions, + "dca": dca, + } + + +def simulate_portfolio( + datasets: dict[str, pd.DataFrame], + strategy: dict, + capital: float, + *, + start: str | None = None, +) -> dict: + """Multi-asset portfolio simulation with optional periodic rebalancing, DCA, and multi-position signals.""" + if not datasets: + raise ValueError("datasets must contain at least one symbol") + if not math.isfinite(capital) or capital <= 0: + raise ValueError("capital must be finite and positive") + + symbols = list(datasets.keys()) + seen_canon: dict[str, str] = {} + for sym in symbols: + canon = _canonical_symbol(sym) + if canon in seen_canon: + raise ValueError(f"Duplicate instrument in portfolio: {seen_canon[canon]!r} and {sym!r}") + seen_canon[canon] = sym + + markets = {detect_market(sym) for sym in symbols} + if len(markets) > 1: + raise ValueError(f"Portfolio symbols must belong to a single market/currency, got {sorted(markets)}") + market = next(iter(markets)) + currencies = {_infer_currency(sym, market, datasets[sym]) for sym in symbols} + if len(currencies) > 1 or None in currencies: + raise ValueError( + f"Portfolio symbols must share a single verified quote currency, got {sorted(map(str, currencies))}" + ) + currency = next(iter(currencies)) + lot_size = 100 if market == "A" else 1 + + sim_cfg = strategy.get("simulation") or {} + execution = sim_cfg.get("execution", "next_open") + if execution not in ("next_open", "same_close"): + raise ValueError("simulation.execution must be next_open or same_close") + slippage = float(sim_cfg.get("slippage", 0.001)) + commission = float(sim_cfg.get("commission", 0.0015)) + tax_raw = sim_cfg.get("stamp_tax") + stamp_tax = float(0.0 if tax_raw is None else tax_raw) + for name, rate in (("slippage", slippage), ("commission", commission), ("stamp_tax", stamp_tax)): + if not 0 <= rate < 1: + raise ValueError(f"simulation.{name} must be a rate in [0, 1), got {rate}") + if commission + stamp_tax >= 1: + raise ValueError(f"simulation commission + stamp_tax must be < 1, got {commission + stamp_tax}") + + entry_cfg = strategy.get("entry") or {} + exit_cfg = strategy.get("exit") or {} + entry_conditions = entry_cfg.get("conditions") or [] + entry_logic = entry_cfg.get("logic", "all") + exit_conditions = exit_cfg.get("conditions") or [] + exit_logic = exit_cfg.get("logic", "any") + for side, logic in (("entry", entry_logic), ("exit", exit_logic)): + if logic not in ("all", "any"): + raise ValueError(f"{side}.logic must be all or any") + + signal_mode = bool(entry_conditions) + cfg = _parse_portfolio_config(strategy, symbols, signal_mode=signal_mode) + + # Preserve single-symbol signal defaults (-0.10 / +0.50) in signal mode; disabled in pure allocation mode unless explicit + if signal_mode: + stop_loss = float(exit_cfg.get("stop_loss", -0.10)) + take_profit = float(exit_cfg.get("take_profit", 0.50)) + else: + stop_loss = ( + float(exit_cfg["stop_loss"]) if "stop_loss" in exit_cfg and exit_cfg["stop_loss"] is not None else None + ) + take_profit = ( + float(exit_cfg["take_profit"]) + if "take_profit" in exit_cfg and exit_cfg["take_profit"] is not None + else None + ) + ts_val = exit_cfg.get("trailing_stop") + trailing_stop = float(ts_val) if ts_val is not None else None + if stop_loss is not None and (not math.isfinite(stop_loss) or stop_loss >= 0): + raise ValueError("exit.stop_loss must be a finite negative fraction") + if take_profit is not None and (not math.isfinite(take_profit) or take_profit <= 0): + raise ValueError("exit.take_profit must be a finite positive fraction") + if trailing_stop is not None and (not math.isfinite(trailing_stop) or not 0 < trailing_stop < 1): + raise ValueError("exit.trailing_stop must be a finite fraction in (0, 1)") + + # Validate each dataset and build date maps + indicator caches + per_sym: dict[str, dict] = {} + all_dates: set[pd.Timestamp] = set() + for sym, raw_df in datasets.items(): + df = raw_df.copy().reset_index(drop=True) + _validate_adjustment_basis(df) + if not np.isfinite(df["close"]).all() or (df["close"] <= 0).any(): + raise ValueError(f"backtest prices for {sym} must be finite and positive") + if execution == "next_open" and ( + "open" not in df or not np.isfinite(df["open"]).all() or (df["open"] <= 0).any() + ): + raise ValueError(f"next_open requires finite positive open prices for {sym}") + dates = pd.to_datetime(df["date"], errors="coerce") + if dates.isna().any() or dates.duplicated().any() or not dates.is_monotonic_increasing: + raise ValueError(f"backtest dates for {sym} must be valid, unique and increasing") + cache: dict = {} + for cond in entry_conditions + exit_conditions: + _condition_series(df, cond, cache) + _condition_value(cond) + date_to_idx = {ts: idx for idx, ts in enumerate(dates)} + per_sym[sym] = {"df": df, "dates": dates, "bars": df.to_dict("records"), "idx": date_to_idx, "cache": cache} + all_dates.update(dates.tolist()) + + timeline = sorted(all_dates) + if start is not None: + start_ts = pd.Timestamp(start) + eval_dates = [d for d in timeline if d >= start_ts] + else: + eval_dates = timeline[1:] if len(timeline) > 1 else timeline + if not eval_dates: + raise ValueError("start must be a valid date within the backtest data") + + cash = capital + total_contributed = capital + contributions = [] + holdings: dict[str, dict] = {} # sym -> {shares, cost, buy_date, buy_price, peak_close} + last_close: dict[str, float] = {} + pending_exits: dict[str, tuple[str, str]] = {} # sym -> (reason, signal_date) + trades = [] + equity_curve = [] + twr_curve = [] + commission_paid = 0.0 + stamp_tax_paid = 0.0 + blocked_orders = 0 + trade_id = 0 + + last_dca_bucket = None + last_rebal_bucket = None + target_symbols = [sym for sym in symbols if cfg["weights"].get(sym, 0.0) > 0] + initially_allocated: set[str] = set() + has_explicit_exits = bool( + stop_loss is not None or take_profit is not None or trailing_stop is not None or exit_conditions + ) + exited_alloc: set[str] = set() + pending_dca: dict[str, float] = {} + + # Time-weighted return (TWR) tracks pure investment return strictly excluding external cash inflows + twr_factor = 1.0 + prev_equity = capital + + def is_tradable(row: dict, side: str) -> bool: + if "volume" in row and (not pd.notna(row["volume"]) or row["volume"] <= 0): + return False + limit = row.get("limit_up" if side == "buy" else "limit_down") + return not ( + limit is not None + and pd.notna(limit) + and row.get("high") == row.get("low") + and abs(float(row["high"]) - float(limit)) < 0.005 + ) + + def fill_px(row: dict) -> float: + return float(row["close"] if execution == "same_close" else row["open"]) + + def sell_shares(sym: str, shares_to_sell: int, row: dict, date_str: str, reason: str): + nonlocal cash, commission_paid, stamp_tax_paid, trade_id + h = holdings.get(sym) + if not h or shares_to_sell <= 0: + return + qty = min(shares_to_sell, h["shares"]) + if qty <= 0: + return + sell_price = fill_px(row) * (1 - slippage) + gross = qty * sell_price + proceeds = gross * (1 - commission - stamp_tax) + commission_paid += gross * commission + stamp_tax_paid += gross * stamp_tax + cash += proceeds + cost_portion = h["cost"] * (qty / h["shares"]) + pnl = proceeds - cost_portion + days = 0 + with contextlib.suppress(ValueError): + days = (datetime.strptime(date_str, "%Y-%m-%d") - datetime.strptime(h["buy_date"], "%Y-%m-%d")).days + trade_id += 1 + trades.append( + { + "id": trade_id, + "symbol": sym, + "type": "sell", + "date": date_str, + "price": round(sell_price, 2), + "shares": qty, + "amount": round(proceeds, 2), + "reason": reason, + "pnl": round(pnl, 2), + "pnl_pct": round(pnl / cost_portion, 4) if cost_portion > 0 else 0.0, + "holding_days": days, + } + ) + h["shares"] -= qty + h["cost"] -= cost_portion + if h["shares"] <= 0: + del holdings[sym] + + def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str) -> bool: + nonlocal cash, commission_paid, trade_id + if budget <= 0 or cash <= 0: + return False + spend = min(budget, cash) + buy_price = fill_px(row) * (1 + slippage) + shares = int(spend / (buy_price * (1 + commission)) / lot_size) * lot_size + if shares <= 0: + return False + cost = shares * buy_price * (1 + commission) + commission_paid += shares * buy_price * commission + cash -= cost + trade_id += 1 + if sym in holdings: + h = holdings[sym] + new_shares = h["shares"] + shares + h["cost"] += cost + h["shares"] = new_shares + h["buy_price"] = round(h["cost"] / new_shares, 4) + h["peak_close"] = max(h["peak_close"], float(row["close"])) + else: + holdings[sym] = { + "shares": shares, + "cost": cost, + "buy_date": date_str, + "buy_price": round(buy_price, 4), + "peak_close": float(row["close"]), + } + trades.append( + { + "id": trade_id, + "symbol": sym, + "type": "buy", + "date": date_str, + "price": round(buy_price, 2), + "shares": shares, + "amount": round(cost, 2), + "reason": reason, + } + ) + return True + + def process_exits(ts, date_str: str) -> set[str]: + nonlocal blocked_orders + sold: set[str] = set() + for sym in list(holdings.keys()): + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is None: + continue + sig_idx = idx if execution == "same_close" else idx - 1 + if sig_idx < 0: + continue + row = info["bars"][idx] + sig_price = float(info["bars"][sig_idx]["close"]) + sig_date = str(info["dates"].iloc[sig_idx].date()) + h = holdings[sym] + h["peak_close"] = max(h["peak_close"], sig_price) + pnl_pct = (sig_price - h["buy_price"]) / h["buy_price"] + sell, reason = False, "" + if stop_loss is not None and pnl_pct <= stop_loss: + sell, reason = True, f"止损触发 ({round(pnl_pct * 100, 1)}% <= {round(stop_loss * 100, 1)}%)" + elif trailing_stop is not None and sig_price <= h["peak_close"] * (1 - trailing_stop): + dd = (h["peak_close"] - sig_price) / h["peak_close"] + sell, reason = ( + True, + f"移动止损触发 (较高点回撤 {round(dd * 100, 1)}% >= {round(trailing_stop * 100, 1)}%)", + ) + elif take_profit is not None and pnl_pct >= take_profit: + sell, reason = True, f"止盈触发 ({round(pnl_pct * 100, 1)}% >= {round(take_profit * 100, 1)}%)" + elif exit_conditions: + sell, reason = evaluate_conditions(info["df"], exit_conditions, exit_logic, sig_idx, info["cache"]) + + if sym in pending_exits: + sell, reason, sig_date = True, pending_exits[sym][0], pending_exits[sym][1] + + if sell: + if not is_tradable(row, "sell"): + pending_exits[sym] = (reason, sig_date) + blocked_orders += 1 + else: + pending_exits.pop(sym, None) + sell_shares(sym, h["shares"], row, date_str, reason) + sold.add(sym) + return sold + + for ts in eval_dates: + date_str = str(ts.date()) + # Refresh last known closes for symbols that have a bar prior to ts + for sym in symbols: + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is not None and idx > 0 and sym not in last_close: + last_close[sym] = float(info["bars"][idx - 1]["close"]) + + # Determine valuation prices at contribution/execution time for exact TWR sub-period linking + exec_prices: dict[str, float] = {} + for sym in symbols: + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is not None: + exec_prices[sym] = fill_px(info["bars"][idx]) + elif sym in last_close: + exec_prices[sym] = last_close[sym] + + # Step 1: Scheduled DCA contribution (links pre-deposit return before adding fresh cash) + dca_added = 0.0 + if cfg["dca"] is not None: + bucket = _schedule_bucket(ts, cfg["dca"]["frequency"]) + if last_dca_bucket is None: + last_dca_bucket = bucket + elif bucket != last_dca_bucket: + last_dca_bucket = bucket + dca_added = cfg["dca"]["amount"] + + pre_deposit_equity = None + if dca_added > 0: + pre_deposit_equity = cash + sum( + h["shares"] * exec_prices.get(s, h["buy_price"]) for s, h in holdings.items() + ) + if prev_equity > 0: + twr_factor *= pre_deposit_equity / prev_equity + cash += dca_added + total_contributed += dca_added + contributions.append({"date": date_str, "amount": round(dca_added, 2)}) + + # Step 2: Execute either signal-driven multi-position mode or target-allocation/rebalance mode + if signal_mode: + sold_today = process_exits(ts, date_str) + + # Entries for non-held symbols (excluding symbols sold on this same bar) up to max_positions + open_slots = cfg["max_positions"] - len(holdings) + if open_slots > 0 and cash > 0: + candidates = [] + for sym in symbols: + if sym in holdings or sym in sold_today: + continue + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is None: + continue + sig_idx = idx if execution == "same_close" else idx - 1 + if sig_idx < 0: + continue + hit, reason = evaluate_conditions(info["df"], entry_conditions, entry_logic, sig_idx, info["cache"]) + if hit: + candidates.append((sym, info["bars"][idx], reason)) + for sym, row, reason in candidates[:open_slots]: + if not is_tradable(row, "buy"): + blocked_orders += 1 + continue + remaining_slots = max(1, cfg["max_positions"] - len(holdings)) + buy_amount(sym, cash * cfg["size"] / remaining_slots, row, date_str, reason) + else: + # Allocation / Rebalance / DCA mode + if has_explicit_exits or pending_exits: + sold_today = process_exits(ts, date_str) + for sym in sold_today | set(pending_exits.keys()): + exited_alloc.add(sym) + initially_allocated.add(sym) + pending_dca.pop(sym, None) + + rebal_due = False + if cfg["rebalance"] != "none": + bucket = _schedule_bucket(ts, cfg["rebalance"]) + if last_rebal_bucket is None: + last_rebal_bucket = bucket + elif bucket != last_rebal_bucket: + last_rebal_bucket = bucket + rebal_due = True + + port_value = cash + sum(h["shares"] * exec_prices.get(s, h["buy_price"]) for s, h in holdings.items()) + rebalanced_today = False + + # First: complete initial allocation for any target-weight symbol not yet deployed (handles staggered start dates) + pending_initial = [ + sym for sym in target_symbols if sym not in initially_allocated and sym not in exited_alloc + ] + if pending_initial and not rebal_due: + unalloc_weight = sum(cfg["weights"][s] for s in pending_initial) + reserved_dca = sum(pending_dca.values()) + (dca_added if dca_added > 0 else 0.0) + avail_cash_for_init = max(0.0, cash - reserved_dca) + for sym in pending_initial: + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is None: + continue + row = info["bars"][idx] + if not is_tradable(row, "buy"): + blocked_orders += 1 + continue + share_of_unalloc = cfg["weights"][sym] / unalloc_weight if unalloc_weight > 0 else 0.0 + budget = min(avail_cash_for_init * share_of_unalloc, port_value * cfg["weights"][sym]) + if buy_amount(sym, budget, row, date_str, "初始建仓"): + initially_allocated.add(sym) + avail_cash_for_init = max(0.0, avail_cash_for_init - budget) + unalloc_weight = max(0.0, unalloc_weight - cfg["weights"][sym]) + # Recompute port_value after initial buys + port_value = cash + sum(h["shares"] * exec_prices.get(s, h["buy_price"]) for s, h in holdings.items()) + + # Credit scheduled DCA budgets per active symbol before rebalance/deployment so suspended bars retain them + if dca_added > 0: + for sym in target_symbols: + if sym in exited_alloc or sym in pending_exits: + continue + pending_dca[sym] = pending_dca.get(sym, 0.0) + dca_added * cfg["weights"][sym] + + if rebal_due and port_value > 0: + if cfg["drift_threshold"] is None: + do_rebalance = True + else: + max_drift = ( + max( + abs( + (holdings.get(s, {}).get("shares", 0) * exec_prices.get(s, 0.0) / port_value) + - cfg["weights"][s] + ) + for s in symbols + if s not in exited_alloc + ) + if any(s not in exited_alloc for s in symbols) + else 0.0 + ) + do_rebalance = max_drift >= cfg["drift_threshold"] + + if do_rebalance: + reason = f"定期再平衡 ({cfg['rebalance']})" + # Clear pending DCA for any symbol already at/above target using carried valuation, + # even when its bar is missing on the rebalance date. + blocked_underweight_syms: set[str] = set() + for sym in symbols: + if sym in exited_alloc or sym in pending_exits: + continue + px = exec_prices.get(sym, holdings.get(sym, {}).get("buy_price", 0.0)) + target_val = port_value * cfg["weights"][sym] + cur_val = holdings.get(sym, {}).get("shares", 0) * px + if cur_val >= target_val: + pending_dca.pop(sym, None) + else: + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is None or not is_tradable(info["bars"][idx], "buy"): + blocked_underweight_syms.add(sym) + + # Sell overweight positions first + for sym in symbols: + if sym in exited_alloc or sym in pending_exits: + continue + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is None or sym not in holdings: + continue + row = info["bars"][idx] + px = exec_prices[sym] + target_val = port_value * cfg["weights"][sym] + cur_val = holdings[sym]["shares"] * px + if cur_val > target_val: + excess_shares = int((cur_val - target_val) / px / lot_size) * lot_size + if excess_shares > 0: + if not is_tradable(row, "sell"): + blocked_orders += 1 + else: + sell_shares(sym, excess_shares, row, date_str, reason) + + # Reserve cash for blocked underweight symbols' pending DCA so tradable buys don't exhaust it + reserved_blocked_dca = sum(pending_dca.get(s, 0.0) for s in blocked_underweight_syms) + + # Buy underweight positions; only clear pending DCA when actually filled + for sym in symbols: + if sym in exited_alloc or sym in pending_exits: + continue + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is None: + continue + row = info["bars"][idx] + px = exec_prices[sym] + target_val = port_value * cfg["weights"][sym] + cur_val = holdings.get(sym, {}).get("shares", 0) * px + deficit = target_val - cur_val + if deficit > 0: + if not is_tradable(row, "buy"): + blocked_orders += 1 + else: + avail_cash = max(0.0, cash - reserved_blocked_dca) + buy_budget = min(deficit, avail_cash) + if buy_amount(sym, buy_budget, row, date_str, reason): + initially_allocated.add(sym) + pending_dca.pop(sym, None) + rebalanced_today = True + + # Deploy fresh & retained blocked DCA budgets whenever rebalance did not run on this bar + if not rebalanced_today: + for sym in list(pending_dca.keys()): + if sym in exited_alloc or sym in pending_exits: + pending_dca.pop(sym, None) + continue + budget = pending_dca[sym] + if budget <= 0: + pending_dca.pop(sym, None) + continue + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is None: + continue + row = info["bars"][idx] + if not is_tradable(row, "buy"): + blocked_orders += 1 + continue + if buy_amount(sym, budget, row, date_str, f"定期定投 ({cfg['dca']['frequency']})"): + pending_dca.pop(sym, None) + + # Step 3: Mark-to-market at close & link TWR sub-period + for sym in symbols: + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is not None: + last_close[sym] = float(info["bars"][idx]["close"]) + equity = cash + sum(h["shares"] * last_close.get(s, h["buy_price"]) for s, h in holdings.items()) + if dca_added > 0 and pre_deposit_equity is not None: + post_deposit_base = pre_deposit_equity + dca_added + if post_deposit_base > 0: + twr_factor *= equity / post_deposit_base + elif prev_equity > 0: + twr_factor *= equity / prev_equity + prev_equity = equity + equity_curve.append({"date": date_str, "equity": round(equity, 2)}) + twr_curve.append({"date": date_str, "equity": round(capital * twr_factor, 2)}) + + final_equity = equity_curve[-1]["equity"] if equity_curve else capital + final_holdings = [] + for sym, h in holdings.items(): + px = last_close.get(sym, h["buy_price"]) + mv = round(h["shares"] * px, 2) + final_holdings.append( + { + "symbol": sym, + "shares": h["shares"], + "close": round(px, 4), + "market_value": mv, + "weight": round(mv / final_equity, 4) if final_equity > 0 else 0.0, + } + ) + + out = { + "mode": "portfolio_signal" if signal_mode else "portfolio_allocation", + "symbols": symbols, + "market": market, + "currency": currency, + "trades": trades, + "equity_curve": equity_curve, + "twr_curve": twr_curve, + "final_equity": final_equity, + "final_cash": round(cash, 2), + "final_holdings": final_holdings, + "total_contributed": round(total_contributed, 2), + "time_weighted_return": round(twr_factor - 1.0, 4), + "contributions": { + "count": len(contributions), + "total_added": round(total_contributed - capital, 2), + "schedule": contributions, + } + if cfg["dca"] is not None + else None, + "portfolio": { + "rebalance": cfg["rebalance"], + "weighting": cfg["weighting"], + "weights": {k: round(v, 4) for k, v in cfg["weights"].items()}, + "max_positions": cfg["max_positions"], + }, + "execution": { + "model": execution, + "blocked_orders": blocked_orders, + "unfilled_order": bool(pending_exits or pending_dca), + "limitations": [ + "Stops are close signals, not intraday guaranteed stop prices", + "Historical price limits are enforced only when limit_up/limit_down are supplied", + "Queue priority, partial fills, market impact and settlement are not simulated", + "Adjusted OHLC are synthetic prices; corporate actions and cash dividends are not simulated separately", + ], + }, + "costs": { + "slippage": slippage, + "commission": commission, + "stamp_tax": stamp_tax, + "commission_paid": round(commission_paid, 2), + "stamp_tax_paid": round(stamp_tax_paid, 2), + }, + } + return out + + # --------------- Metrics --------------- -def compute_metrics(trades: list, equity_curve: list, initial: float, final: float, start: str, end: str) -> dict: +def compute_metrics( + trades: list, + equity_curve: list, + initial: float, + final: float, + start: str, + end: str, + *, + risk_curve: list | None = None, + risk_initial: float | None = None, + annual_return_basis: float | None = None, +) -> dict: sell_trades = [t for t in trades if t["type"] == "sell"] total_trades = len(sell_trades) winning = [t for t in sell_trades if t.get("pnl", 0) > 0] @@ -674,9 +1412,12 @@ def compute_metrics(trades: list, equity_curve: list, initial: float, final: flo years = (d1 - d0).days / 365.25 except (ValueError, TypeError): years = 1 - annual_return = (1 + total_return) ** (1 / max(years, 0.01)) - 1 if total_return > -1 else total_return + ann_source = annual_return_basis if annual_return_basis is not None else total_return + annual_return = (1 + ann_source) ** (1 / max(years, 0.01)) - 1 if ann_source > -1 else ann_source - equities = pd.Series([initial, *[e["equity"] for e in equity_curve]], dtype=float) + curve_for_risk = risk_curve if risk_curve is not None else equity_curve + base_for_risk = risk_initial if risk_initial is not None else initial + equities = pd.Series([base_for_risk, *[e["equity"] for e in curve_for_risk]], dtype=float) peak = equities.cummax() dd = (equities - peak) / peak max_drawdown = float(dd.min()) if len(dd) > 0 else 0 @@ -926,6 +1667,102 @@ def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str | if not start: start = (datetime.now() - timedelta(days=365)).strftime("%Y-%m-%d") + symbols = [s.strip() for s in str(symbol).split(",") if s.strip()] + if not symbols: + return {"error": "At least one stock symbol is required"} + use_portfolio = ( + len(symbols) > 1 + or bool(strategy.get("portfolio")) + or bool(strategy.get("dca")) + or (strategy.get("position") or {}).get("max_positions", 1) != 1 + ) + if use_portfolio and len(symbols) == 1 and not strategy.get("portfolio") and not strategy.get("dca"): + # Keep single-symbol max_positions != 1 validation error in single-position simulate() + use_portfolio = False + + if use_portfolio: + from concurrent.futures import ThreadPoolExecutor + + # Validate canonical symbol uniqueness before issuing any fetches + seen_canon: dict[str, str] = {} + for sym in symbols: + canon = _canonical_symbol(sym) + if canon in seen_canon: + return {"error": f"Duplicate instrument in portfolio: {seen_canon[canon]!r} and {sym!r}"} + seen_canon[canon] = sym + + warmup = _strategy_warmup_bars(strategy) + datasets: dict[str, pd.DataFrame] = {} + actual_starts, actual_ends = [], [] + with ThreadPoolExecutor(max_workers=min(len(symbols), 4)) as pool: + fetched = {sym: pool.submit(fetch_kline, sym, start, end, True, warmup) for sym in symbols} + for sym in symbols: + df = fetched[sym].result() + ev = df[(df["date"] >= start) & (df["date"] <= end)] + if len(ev) < 30: + return {"error": f"Insufficient data for {sym}: {len(ev)} rows (need at least 30)"} + datasets[sym] = df + actual_starts.append(ev["date"].iloc[0].strftime("%Y-%m-%d")) + actual_ends.append(ev["date"].iloc[-1].strftime("%Y-%m-%d")) + requested_period = f"{start} to {end}" + actual_start = min(actual_starts) + actual_end = max(actual_ends) + warnings = [] + if actual_start != start or actual_end != end: + warnings.append(f"Actual data covers {actual_start} to {actual_end}; requested {requested_period}") + execution = (strategy.get("simulation") or {}).get("execution", "next_open") + sim = simulate_portfolio(datasets, strategy, capital, start=actual_start) + final = sim["final_equity"] + total_in = sim["total_contributed"] + has_dca = bool(sim.get("contributions")) + risk_curve = sim["twr_curve"] if has_dca else sim["equity_curve"] + metrics = compute_metrics( + sim["trades"], + sim["equity_curve"], + total_in, + final, + actual_start, + actual_end, + risk_curve=risk_curve, + risk_initial=capital, + annual_return_basis=sim["time_weighted_return"] if has_dca else None, + ) + if has_dca: + metrics["time_weighted_return"] = sim["time_weighted_return"] + result = { + "strategy": strategy.get("name", "unnamed"), + "symbol": symbol, + "symbols": symbols, + "mode": sim["mode"], + "currency": sim["currency"], + "period": f"{actual_start} to {actual_end}", + "requested_period": requested_period, + "warnings": warnings, + "initial_capital": capital, + "total_contributed": total_in, + "final_capital": final, + "final_cash": sim["final_cash"], + "final_holdings": sim["final_holdings"], + "portfolio": sim["portfolio"], + "costs": sim["costs"], + "execution": sim["execution"], + "metrics": metrics, + "trades": sim["trades"], + "equity_curve": sample_curve(sim["equity_curve"]), + "diagnosis": diagnose(metrics), + "diagnostics": diagnose_advanced(metrics, sim["trades"], risk_curve, strategy), + } + if sim.get("contributions"): + result["contributions"] = sim["contributions"] + benchmark_symbol = strategy.get("benchmark") + if benchmark_symbol: + benchmark_start = sim["equity_curve"][0]["date"] if sim["equity_curve"] else actual_start + comp_ret = sim["time_weighted_return"] if sim.get("contributions") else metrics["total_return"] + result["benchmark"] = _benchmark_comparison( + str(benchmark_symbol), benchmark_start, actual_end, comp_ret, execution + ) + return result + df = fetch_kline(symbol, start, end, True, _strategy_warmup_bars(strategy)) evaluation = df[(df["date"] >= start) & (df["date"] <= end)] if len(evaluation) < 30: diff --git a/tools/capabilities.py b/tools/capabilities.py index a039268..52a5d76 100644 --- a/tools/capabilities.py +++ b/tools/capabilities.py @@ -43,6 +43,7 @@ "get_valuation_history": {"markets": ["A", "HK", "US"], "reason": "A/HK providers; US derived from SEC filings"}, "get_index_valuation": {"markets": ["A"], "reason": "Chinese index valuation only"}, "get_cds_index": {"markets": ["A", "US"], "reason": "Market-level CN onshore CDS indices / CDX-iTraxx only"}, + "get_macro_anchors": {"markets": ALL_MARKETS, "reason": None}, "get_earnings_calendar": { "markets": ["A", "HK", "US", "JP"], "reason": "A-share disclosed calendar / HK/US/JP single-symbol provider schedule", @@ -67,7 +68,10 @@ # A-share only "get_capital_flow": {"markets": ["A"], "reason": "A-share only (akshare data)"}, "get_chip_distribution": {"markets": ["A"], "reason": "A-share only"}, - "get_sector_rankings": {"markets": ["A", "US"], "reason": "A-share boards; US sector ETF proxies"}, + "get_sector_rankings": { + "markets": ["A", "HK", "US"], + "reason": "A-share boards; HK TradingView/ETF proxies; US sector ETF proxies", + }, "get_sector_constituents": {"markets": ["A"], "reason": "A-share only"}, "get_market_stats": {"markets": ["A", "HK", "US"], "reason": "full-market snapshot breadth; limits A-share only"}, "get_fundamental_context": {"markets": ["A"], "reason": "A-share only"}, @@ -89,7 +93,7 @@ "search_stock_news": {"markets": ALL_MARKETS, "reason": None}, "search_comprehensive_intel": {"markets": ALL_MARKETS, "reason": None}, "extract_article": {"markets": ALL_MARKETS, "reason": None}, - "screen_risk": {"markets": ["A"], "reason": "A-share only"}, + "screen_risk": {"markets": ["A", "HK", "US"], "reason": "A-share, HK, and US risk checks only"}, # trading phase (session tables) + signal tracking (local JSONL store) "get_trading_phase": {"markets": ALL_MARKETS, "reason": None}, "record_signal": {"markets": ALL_MARKETS, "reason": None}, diff --git a/tools/diagnostics.py b/tools/diagnostics.py index 01fcf98..88b4009 100644 --- a/tools/diagnostics.py +++ b/tools/diagnostics.py @@ -1,10 +1,9 @@ #!/usr/bin/env python3 -"""Data source diagnostics — report which providers are usable per market. +"""Data source diagnostics — report which providers and services are usable per market. Checks: (1) python package importable, (2) required env vars present. -Does NOT hit the network — this is a cheap capability probe, not a health check. -`available` therefore means "package + credentials ready"; actual reachability -is reported as `reachable: null` (unknown) rather than guessed (issue #25). +By default does NOT hit the network — `reachable: null` (unknown) rather than guessed +(issue #25). Pass `--probe` to opt into lightweight bounded HTTP reachability probes. """ import argparse @@ -13,11 +12,13 @@ import json import os import sys +import time +from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timezone from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) -from _subproc import utf8_stdio # noqa: E402 +from _subproc import error_message, json_safe, utf8_stdio # noqa: E402 from capabilities import ALL_MARKETS # noqa: E402 # provider -> (import_name, required_env_vars, markets, note) @@ -44,6 +45,7 @@ "xueqiu": ("akshare", ["XUEQIU_TOKEN"], ["A"], "industry board fallback via akshare"), "baostock": ("baostock", [], ["A"], None), "yfinance": ("yfinance", [], ["HK", "US", "JP", "KR", "TW"], "quote may be delayed 15-20min"), + "tradingview": ("requests", [], ["HK", "US"], "scanner.tradingview.com HK/US snapshots & HK sectors, no auth"), "finnhub": ("finnhub", ["FINNHUB_API_KEY"], ["HK", "US"], None), "longbridge": ( "longport.openapi", @@ -54,10 +56,71 @@ "alphavantage": ("requests", ["ALPHAVANTAGE_API_KEY"], ["US"], None), } +# Non-quote auxiliary services: search engines, filings, sentiment, credit/macro +# service -> (category, import_name, required_env_vars, note) +SERVICES = { + "tavily": ("search", "requests", ["TAVILY_API_KEY"], "Tavily web search"), + "brave": ("search", "requests", ["BRAVE_API_KEY"], "Brave web search"), + "serpapi": ("search", "requests", ["SERPAPI_KEY"], "SerpAPI Google search"), + "bocha": ("search", "requests", ["BOCHA_API_KEY"], "Bocha AI search"), + "searxng": ("search", "requests", ["SEARXNG_BASE_URLS"], "Self-hosted SearXNG fallback (comma-separated URLs)"), + "sec_edgar": ("filings", "requests", ["SEC_USER_AGENT"], "SEC EDGAR 13F / Form 4 / US DCF & valuation"), + "cninfo": ("filings", "requests", [], "CNINFO A-share official announcements, no auth"), + "hkexnews": ("filings", "requests", [], "HKEXnews HK announcements & board meetings, no auth"), + "adanos_sentiment": ( + "sentiment", + "requests", + ["SENTIMENT_API_KEY"], + "HK/US social sentiment (Reddit/X/Polymarket); URL via SENTIMENT_API_URL", + ), + "chinamoney_cds": ("credit", "requests", [], "CFETS-SHCH onshore CN CDS indices, no auth"), + "dtcc_cds": ("credit", "requests", [], "DTCC public CDX/iTraxx daily files, no auth"), + "fred_macro": ("macro", "requests", [], "FRED public CSV fallback for US Treasury yields, no auth"), +} + +# Lightweight public probe endpoints (never send credentials or secrets in probe requests) +_PROBE_URLS = { + "tencent": "https://qt.gtimg.cn/q=sh000001", + "sina": "https://hq.sinajs.cn/list=sh000001", + "tradingview": "https://scanner.tradingview.com/hongkong/scan", + "yfinance": "https://query1.finance.yahoo.com/v1/test/getcrumb", + "cninfo": "https://www.cninfo.com.cn/new/data/szse_stock.json", + "hkexnews": "https://www1.hkexnews.hk", + "sec_edgar": "https://data.sec.gov/submissions/", + "chinamoney_cds": "https://www.chinamoney.com.cn/r/cms/www/chinamoney/data/bond/CDSIndex.json", + "dtcc_cds": "https://kgc0418-tdw-data-0.s3.amazonaws.com/dashboard/Cumulative.json", + "fred_macro": "https://fred.stlouisfed.org/graph/fredgraph.csv?id=DGS10", +} -def _check_provider(name: str) -> dict: - import_name, env_vars, markets, note = PROVIDERS[name] +def _probe_url(name: str, timeout: float = 4.0) -> tuple[bool | None, int | None, str | None]: + url = _PROBE_URLS.get(name) + if not url: + return None, None, None + import requests + + headers = { + "User-Agent": os.environ.get("SEC_USER_AGENT", "stock-analysis-plugin") + if name == "sec_edgar" + else "Mozilla/5.0" + } + if name == "sina": + headers["Referer"] = "https://finance.sina.com.cn" + t0 = time.monotonic() + try: + resp = requests.head(url, headers=headers, timeout=timeout, allow_redirects=True) + # Some endpoints reject HEAD with 405/403 while accepting GET/POST — treat HTTP response < 500 as reachable. + if resp.status_code == 405: + resp = requests.get(url, headers=headers, timeout=timeout, stream=True) + resp.close() + latency = round((time.monotonic() - t0) * 1000) + ok = resp.status_code < 500 + return ok, latency, (None if ok else f"HTTP {resp.status_code}") + except Exception as exc: + return False, None, error_message(exc, 120) + + +def _check_entry(name: str, import_name: str, env_vars: list[str], extra: dict, note: str | None) -> dict: # find_spec avoids executing the package's top-level code — cheaper and # side-effect-free vs import_module. This is a capability probe, not a call. try: @@ -80,8 +143,8 @@ def _check_provider(name: str) -> dict: entry = { "name": name, "available": available, - "reachable": None, # not probed — available only means package + env ready - "markets": markets, + "reachable": None, # not probed unless --probe is explicitly passed + **extra, "reason": "; ".join(reasons) if reasons else None, } if note: @@ -89,21 +152,79 @@ def _check_provider(name: str) -> dict: return entry -def diagnose(market: str = "all") -> dict: +def _check_provider(name: str) -> dict: + import_name, env_vars, markets, note = PROVIDERS[name] + return _check_entry(name, import_name, env_vars, {"markets": markets}, note) + + +def _check_service(name: str) -> dict: + category, import_name, env_vars, note = SERVICES[name] + entry = _check_entry(name, import_name, env_vars, {"category": category}, note) + if name == "sec_edgar" and entry["available"]: + try: + from sec_edgar import identity as _sec_identity + + _sec_identity() + except ValueError as exc: + entry["available"] = False + entry["reason"] = f"invalid SEC_USER_AGENT: {exc}" + except Exception as exc: + entry["available"] = False + entry["reason"] = f"sec_edgar import failed: {error_message(exc, 120)}" + return entry + + +def _apply_probes(entries: list[dict]) -> None: + targets = [e for e in entries if e["available"] and e["name"] in _PROBE_URLS] + if not targets: + return + with ThreadPoolExecutor(max_workers=min(len(targets), 6)) as pool: + futures = {pool.submit(_probe_url, e["name"]): e for e in targets} + for future, entry in futures.items(): + reachable, latency_ms, err = future.result() + entry["reachable"] = reachable + if latency_ms is not None: + entry["latency_ms"] = latency_ms + if err: + entry["probe_error"] = err + + +def diagnose(market: str = "all", probe: bool = False) -> dict: market = (market or "all").upper() all_providers = [_check_provider(p) for p in PROVIDERS] + all_services = [_check_service(s) for s in SERVICES] + if probe: + _apply_probes(all_providers + all_services) markets_to_report = ALL_MARKETS if market == "ALL" else [market] + search_ready = [s["name"] for s in all_services if s["category"] == "search" and s["available"]] + top_warnings = [] + if not search_ready: + top_warnings.append( + "No search engine configured (TAVILY/BRAVE/SERPAPI/BOCHA/SEARXNG); news search tools unavailable" + ) + sec_entry = next((s for s in all_services if s["name"] == "sec_edgar"), None) + if sec_entry and not sec_entry["available"]: + sec_reason = sec_entry.get("reason") or "SEC_USER_AGENT not set" + top_warnings.append(f"SEC EDGAR unavailable ({sec_reason}) — US 13F / Form 4 / SEC filings unavailable") + result = { "meta": { "provider": "diagnostics", "fetched_at": datetime.now(timezone.utc).isoformat(), - "freshness": "instant", + "freshness": "probed" if probe else "instant", + "probed": bool(probe), "fallback_used": False, - "warnings": [], + "warnings": top_warnings, }, "markets": [], + "services": all_services, + "summary": { + "search_engines_ready": search_ready, + "sec_edgar_ready": any(s["name"] == "sec_edgar" and s["available"] for s in all_services), + "sentiment_api_ready": any(s["name"] == "adanos_sentiment" and s["available"] for s in all_services), + }, } for m in markets_to_report: @@ -148,13 +269,18 @@ def main(): choices=ALL_MARKETS + ["ALL"], help="Market to diagnose (default: ALL)", ) + p.add_argument( + "--probe", + action="store_true", + help="Opt into lightweight HTTP reachability probes for public endpoints", + ) args = parser.parse_args() if not args.command: parser.print_help() sys.exit(1) - result = diagnose(args.market) - json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str) + result = diagnose(args.market, probe=args.probe) + json.dump(json_safe(result), sys.stdout, ensure_ascii=False, indent=2, default=str, allow_nan=False) print() diff --git a/tools/gather.py b/tools/gather.py index d5877d8..01090d1 100755 --- a/tools/gather.py +++ b/tools/gather.py @@ -101,13 +101,21 @@ def gather_analysis(symbol: str, *, session=None) -> dict: "quote": ("stock_data.py", ["quote", symbol]), "kline": ("stock_data.py", ["kline", symbol, "--period", "daily", "--count", "120"]), "financials": ("stock_data.py", ["financials", symbol]), - "capital_flow": ("stock_data.py", ["capital_flow", symbol]), - "chip_distribution": ("stock_data.py", ["chip_distribution", symbol]), "news": ("search_intel.py", ["search", _news_query(symbol)]), "social_sentiment": ("search_intel.py", ["sentiment", symbol]), } + if market == "A": + tasks["capital_flow"] = ("stock_data.py", ["capital_flow", symbol]) + tasks["chip_distribution"] = ("stock_data.py", ["chip_distribution", symbol]) tasks["regime"] = ("market_regime.py", ["detect", market]) - return _run_all(tasks, symbol, session=session, with_risk=True) + supports_risk = market in ("A", "HK", "US") + result = _run_all(tasks, symbol, session=session, with_risk=supports_risk) + if market != "A": + result["capital_flow"] = {"error": "capital_flow only available for A-shares"} + result["chip_distribution"] = {"error": "chip_distribution only available for A-shares"} + if not supports_risk: + result["risk"] = {"error": f"screen_risk only supports A, HK, and US markets (got {market})"} + return result def gather_technical(symbol: str, kline_count: int = 120, with_quote: bool = False) -> dict: @@ -138,8 +146,13 @@ def gather_fundamental(symbol: str) -> dict: } if market == "A": tasks["sector_rankings"] = ("stock_data.py", ["sector_rankings", "--top", "5", "--direction", "both"]) + elif market in ("HK", "US"): + tasks["sector_rankings"] = ( + "stock_data.py", + ["sector_rankings", "--market", market, "--top", "5", "--direction", "both"], + ) result = _run_all(tasks, symbol) - if market != "A": + if market not in ("A", "HK", "US"): result["sector_rankings"] = {"error": f"Sector rankings unavailable for {market}"} return result diff --git a/tools/macro_data.py b/tools/macro_data.py new file mode 100644 index 0000000..581657e --- /dev/null +++ b/tools/macro_data.py @@ -0,0 +1,354 @@ +#!/usr/bin/env python3 +"""Macro, interest-rate, FX, and market risk-appetite anchors (keyless by default). + +Provides risk-free yield anchors (US/CN 10Y, US 2Y), FX rates (DXY, USD/CNH, USD/HKD, +HKD/CNY), and risk-appetite proxies (VIX, Gold, WTI Crude) for DCF valuation, +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 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 + +MACRO_TTL = 3600 # 1 hour cache for daily macro anchors + +GROUPS = { + "rates": ("us_10y", "us_2y", "cn_10y"), + "fx": ("dxy", "usdcnh", "usdhkd", "hkdcny"), + "risk": ("vix", "gold", "crude_oil"), +} +ALL_KEYS = GROUPS["rates"] + GROUPS["fx"] + GROUPS["risk"] + +YF_SPECS = { + "us_10y": ("^TNX", "US 10Y Treasury Yield", "percent", 1.0), + "dxy": ("DX-Y.NYB", "US Dollar Index (DXY)", "index", 1.0), + "usdcnh": ("CNH=X", "USD/CNH Exchange Rate", "rate", 1.0), + "usdhkd": ("HKD=X", "USD/HKD Exchange Rate", "rate", 1.0), + "vix": ("^VIX", "CBOE Volatility Index (VIX)", "index", 1.0), + "gold": ("GC=F", "COMEX Gold Futures", "usd_per_oz", 1.0), + "crude_oil": ("CL=F", "WTI Crude Oil Futures", "usd_per_bbl", 1.0), +} + +FRED_SPECS = { + "us_10y": ("DGS10", "US 10Y Treasury Yield", "percent"), + "us_2y": ("DGS2", "US 2Y Treasury Yield", "percent"), +} + + +def _finite(val) -> float | None: + try: + v = float(val) + except (TypeError, ValueError): + return None + return v if math.isfinite(v) else None + + +def _summarize_series( + points: list[tuple[str, float]], + *, + name: str, + unit: str, + source: str, + symbol: str | None = None, +) -> dict: + clean = [(d, v) for d, v in points if d and _finite(v) is not None] + clean.sort(key=lambda item: item[0]) + if not clean: + raise ValueError(f"empty series for {name}") + values = [v for _, v in clean] + latest = values[-1] + start_val = values[0] + prev_val = values[-2] if len(values) >= 2 else None + change = round(latest - prev_val, 4) if prev_val is not None else None + change_pct = round((latest - prev_val) / prev_val * 100, 4) if prev_val not in (None, 0) else None + window_change = round(latest - start_val, 4) + out = { + "name": name, + "unit": unit, + "source": source, + "latest": round(latest, 4), + "as_of": clean[-1][0], + "change_1d": change, + "change_1d_pct": change_pct if unit != "percent" else None, + "window_start": clean[0][0], + "window_change": window_change, + "min": round(min(values), 4), + "max": round(max(values), 4), + "observations": len(values), + } + if symbol: + out["symbol"] = symbol + return out + + +def _fetch_yf_series(ticker: str, days: int, scale: float = 1.0) -> list[tuple[str, float]]: + import yfinance as yf + + period = "1mo" if days <= 25 else "3mo" if days <= 75 else "6mo" if days <= 160 else "1y" + df = yf.download(ticker, period=period, auto_adjust=False, progress=False) + if df is None or df.empty: + raise ValueError(f"yfinance returned empty history for {ticker}") + close = df["Close"] + if hasattr(close, "columns"): + close = close.iloc[:, 0] + points = [] + for idx, val in close.dropna().items(): + v = _finite(val) + if v is not None and v > 0: + points.append((str(idx)[:10], v * scale)) + if not points: + raise ValueError(f"yfinance returned no valid closes for {ticker}") + return points[-max(days, 2) :] + + +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"}) + resp.raise_for_status() + reader = csv.DictReader(io.StringIO(resp.text)) + points = [] + for row in reader: + date_str = row.get("observation_date") or row.get("DATE") + val = _finite(row.get(series_id)) + if date_str and val is not None: + points.append((date_str[:10], val)) + if not points: + raise ValueError(f"FRED returned no observations for {series_id}") + return points[-max(days, 2) :] + + +def _fetch_cn_us_yields_akshare(days: int) -> dict[str, list[tuple[str, float]]]: + import akshare as ak + + df = ak.bond_zh_us_rate() + if df is None or df.empty: + raise ValueError("akshare bond_zh_us_rate returned empty data") + date_col = next((c for c in df.columns if "日期" in str(c)), df.columns[0]) + cn10_col = next((c for c in df.columns if "中国国债收益率10年" in str(c)), None) + us10_col = next((c for c in df.columns if "美国国债收益率10年" in str(c)), None) + us2_col = next((c for c in df.columns if "美国国债收益率2年" in str(c)), None) + out: dict[str, list[tuple[str, float]]] = {} + for key, col in (("cn_10y", cn10_col), ("us_10y", us10_col), ("us_2y", us2_col)): + if not col: + continue + pts = [] + for _, row in df[[date_col, col]].dropna().tail(max(days, 5)).iterrows(): + v = _finite(row[col]) + if v is not None: + pts.append((str(row[date_col])[:10], v)) + if pts: + out[key] = pts[-max(days, 2) :] + if not out: + raise ValueError("akshare bond_zh_us_rate had no usable yield columns") + return out + + +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) + pts = bonds.get("cn_10y") + if not pts: + raise ValueError("CN 10Y yield unavailable") + return _summarize_series(pts, name="China 10Y Government Bond Yield", unit="percent", source="akshare_bond") + + if key == "us_2y": + errors = [] + try: + pts = _fetch_fred_series("DGS2", days) + return _summarize_series(pts, name="US 2Y Treasury Yield", unit="percent", source="fred", symbol="DGS2") + except Exception as exc: + errors.append(f"fred: {error_message(exc, 100)}") + try: + bonds = bond_cache if bond_cache is not None else _fetch_cn_us_yields_akshare(days) + pts = bonds.get("us_2y") + if pts: + return _summarize_series(pts, name="US 2Y Treasury Yield", unit="percent", source="akshare_bond") + except Exception as exc: + errors.append(f"akshare: {error_message(exc, 100)}") + raise ValueError("; ".join(errors) or "US 2Y yield unavailable") + + if key == "us_10y": + errors = [] + ticker, name, unit, scale = YF_SPECS["us_10y"] + try: + pts = _fetch_yf_series(ticker, days, scale=scale) + return _summarize_series(pts, name=name, unit=unit, source="yfinance", symbol=ticker) + except Exception as exc: + errors.append(f"yfinance: {error_message(exc, 100)}") + try: + pts = _fetch_fred_series("DGS10", days) + return _summarize_series(pts, name=name, unit=unit, source="fred", symbol="DGS10") + except Exception as exc: + errors.append(f"fred: {error_message(exc, 100)}") + try: + bonds = bond_cache if bond_cache is not None else _fetch_cn_us_yields_akshare(days) + pts = bonds.get("us_10y") + if pts: + return _summarize_series(pts, name=name, unit=unit, source="akshare_bond") + except Exception as exc: + errors.append(f"akshare: {error_message(exc, 100)}") + raise ValueError("; ".join(errors)) + + if key == "usdcnh": + errors = [] + for ticker in ("CNH=X", "CNY=X"): + try: + pts = _fetch_yf_series(ticker, days) + return _summarize_series( + pts, name="USD/CNH Exchange Rate", unit="rate", source="yfinance", symbol=ticker + ) + except Exception as exc: + errors.append(f"{ticker}: {error_message(exc, 100)}") + raise ValueError("; ".join(errors)) + + if key in YF_SPECS: + ticker, name, unit, scale = YF_SPECS[key] + 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}") + + +def _parse_int_days(value) -> int: + if isinstance(value, bool): + raise ValueError("days must be an integer between 2 and 365") + if isinstance(value, int): + return value + if isinstance(value, float): + if math.isfinite(value) and value.is_integer(): + return int(value) + raise ValueError("days must be an integer between 2 and 365") + if isinstance(value, str): + text = value.strip() + try: + f = float(text) + except ValueError as exc: + raise ValueError("days must be an integer between 2 and 365") from exc + if math.isfinite(f) and f.is_integer(): + return int(f) + raise ValueError("days must be an integer between 2 and 365") + + +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"} + try: + days = _parse_int_days(days) + except ValueError as exc: + return {"error": str(exc)} + if days < 2 or days > 365: + return {"error": "days must be an integer between 2 and 365"} + + keys = list(ALL_KEYS if group == "all" else GROUPS[group]) + fetch_keys = [k for k in keys if k != "hkdcny"] + + # Fetch akshare CN/US bond table once if needed by rates group + 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)) + except Exception: + bond_cache = {} + + anchors: dict[str, dict] = {} + missing: list[str] = [] + warnings: list[str] = [] + + def load_one(key: str): + return cached( + f"macro_{key}_{days}", + MACRO_TTL, + lambda: _fetch_anchor_uncached(key, days, bond_cache=bond_cache), + ) + + with 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: + anchors[key] = future.result() + except Exception as exc: + missing.append(key) + warnings.append(f"{key} unavailable: {error_message(exc, 150)}") + + # Derive HKD/CNY from USD/CNH and USD/HKD if requested + if "hkdcny" in keys: + cnh = (anchors.get("usdcnh") or {}).get("latest") + hkd = (anchors.get("usdhkd") or {}).get("latest") + if _finite(cnh) and _finite(hkd) and hkd > 0: + anchors["hkdcny"] = { + "name": "HKD/CNY Implied Cross Rate", + "unit": "rate", + "source": "derived(usdcnh/usdhkd)", + "latest": round(cnh / hkd, 4), + "as_of": anchors["usdcnh"].get("as_of") or anchors["usdhkd"].get("as_of"), + } + else: + missing.append("hkdcny") + warnings.append("hkdcny unavailable: requires both usdcnh and usdhkd") + + if not anchors: + return {"error": f"All requested macro anchors unavailable ({', '.join(missing)})", "warnings": warnings} + + derived: dict[str, float | None] = {} + us10 = (anchors.get("us_10y") or {}).get("latest") + cn10 = (anchors.get("cn_10y") or {}).get("latest") + us2 = (anchors.get("us_2y") or {}).get("latest") + if _finite(us10) is not None and _finite(cn10) is not None: + derived["us_cn_10y_spread_bp"] = round((us10 - cn10) * 100, 1) + if _finite(us10) is not None and _finite(us2) is not None: + derived["us_10y_2y_spread_bp"] = round((us10 - us2) * 100, 1) + + return { + "meta": { + "provider": "macro_data", + "fetched_at": datetime.now(timezone.utc).isoformat(), + "freshness": "delayed_or_daily", + "fallback_used": any( + a.get("source") in ("fred", "akshare_bond") for k, a in anchors.items() if k == "us_10y" + ), + "warnings": warnings, + }, + "group": group, + "days": days, + "anchors": anchors, + "derived": derived, + "missing": missing, + "notes": [ + "Yields are expressed in percent (e.g. 4.25 means 4.25%); spreads are in basis points (bp).", + "Suitable as risk-free rate, FX, and risk-appetite references for DCF valuation, portfolio risk, and market review.", + ], + } + + +def main(): + parser = argparse.ArgumentParser(description="Macro, rates, FX, and volatility anchors") + sub = parser.add_subparsers(dest="command") + p = sub.add_parser("anchors") + p.add_argument("--group", default="all", choices=["all", "rates", "fx", "risk"]) + 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: + sys.exit(1) + + +if __name__ == "__main__": + utf8_stdio() + main() diff --git a/tools/risk_screening.py b/tools/risk_screening.py index ecea101..a13fdad 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -5,14 +5,18 @@ import json import math import os +import re import sys from concurrent.futures import Future, ThreadPoolExecutor -from datetime import timedelta +from datetime import date, datetime, timedelta, timezone +from itertools import chain +from typing import NamedTuple sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from _subproc import run_tool as _run_tool from _subproc import utf8_stdio +from stock_data import detect_market from trading_calendar import market_now @@ -216,14 +220,33 @@ def _fetch_lockup(symbol: str) -> dict: # --------------- Check 4-7: News-based risks --------------- -def check_news_risks(symbol: str, name: str = "", *, run=None) -> dict: - search_name = name if name else symbol - categories = { - "insider": f"{search_name} 减持 股东减持", - "earnings": f"{search_name} 业绩预告 亏损 下降", - "regulatory": f"{search_name} 处罚 违规 监管 立案", - "industry": f"{search_name} 行业政策 监管 限制", +def _news_risk_queries(search_name: str, market: str) -> dict[str, str]: + if market == "A": + return { + "insider": f"{search_name} 减持 股东减持", + "earnings": f"{search_name} 业绩预告 亏损 下降", + "regulatory": f"{search_name} 处罚 违规 监管 立案", + "industry": f"{search_name} 行业政策 监管 限制", + } + if market == "HK": + return { + "insider": f"{search_name} insider selling stake reduction 减持", + "earnings": f"{search_name} profit warning earnings miss 盈警", + "regulatory": f"{search_name} SFC regulatory investigation penalty 监管", + "industry": f"{search_name} industry regulation policy headwind", + } + return { + "insider": f"{search_name} insider selling Form 4 sale", + "earnings": f"{search_name} earnings miss guidance cut loss", + "regulatory": f"{search_name} SEC investigation lawsuit antitrust fine", + "industry": f"{search_name} industry regulation tariff headwind", } + + +def check_news_risks(symbol: str, name: str = "", *, run=None, market: str | None = None) -> dict: + search_name = name if name else symbol + resolved_market = market or detect_market(symbol) + categories = _news_risk_queries(search_name, resolved_market) result = {"flags": [], "available": True} # four independent search_intel subprocesses — fan out concurrently (same # ThreadPoolExecutor pattern as gather._run_all); iterating `futures` in @@ -256,6 +279,2163 @@ def check_news_risks(symbol: str, name: str = "", *, run=None) -> dict: return result +_HK_DISCLOSURE_HIGH_ALWAYS = ("清盘", "winding up", "监管调查", "investigation") +_HK_DISCLOSURE_SUSPENSION = ("停牌", "trading halt", "halt in trading", "suspension") +_HK_RESUMPTION_RE = re.compile( + r"(resumption\s+of\s+trading|lifting\s+of\s+(?:trading\s+)?suspension|恢复买卖|复牌)", + re.IGNORECASE, +) +_HK_LIFTING_PHRASE_RE = re.compile(r"lifting\s+of\s+(?:trading\s+)?suspension", re.IGNORECASE) +_HK_DISCLOSURE_MEDIUM = ( + "盈警", + "盈利警告", + "profit warning", + "配售", + "placing", + "供股", + "rights issue", + "减持", + "disposal", +) +_HK_SCREEN_TOP = 15 + + +def check_hk_disclosures(symbol: str, *, run=None) -> dict: + data = (run or _run_tool)( + "value_data.py", ["announcements", symbol, "--category", "all", "--top", str(_HK_SCREEN_TOP)], timeout=25 + ) + result = {"matches": [], "flags": [], "available": False, "truncated": False, "warnings": []} + if not isinstance(data, dict) or "error" in data or not isinstance(data.get("announcements"), list): + return result + announcements = data["announcements"] + truncated = bool(data.get("truncated")) + # Distinguish the intentional 15-row screening cap from an incomplete provider response (< 15 rows while truncated). + provider_incomplete = truncated and len(announcements) < _HK_SCREEN_TOP + result["truncated"] = truncated + result["available"] = not provider_incomplete + if provider_incomplete: + result["warnings"].append("HKEX disclosure response was incomplete/truncated; coverage may miss risk filings") + for item in announcements: + title = str(item.get("title") or "") + ann_type = str(item.get("type") or "") + low = title.lower() + type_low = ann_type.lower() + sev = None + is_resumption_only = ( + bool(_HK_RESUMPTION_RE.search(title)) + and not any( + k in _HK_LIFTING_PHRASE_RE.sub("", low) for k in ("trading halt", "halt in trading", "suspension") + ) + and "停牌" not in title.replace("复牌", "") + ) + has_suspension = any( + k in low or k in title or k in type_low or k in ann_type for k in _HK_DISCLOSURE_SUSPENSION + ) + if any(k in low or k in title for k in _HK_DISCLOSURE_HIGH_ALWAYS) or ( + not is_resumption_only and has_suspension + ): + sev = "high" + elif any(k in low or k in title for k in _HK_DISCLOSURE_MEDIUM): + sev = "medium" + if sev: + result["matches"].append({"date": item.get("date"), "title": title, "severity": sev}) + if any(m["severity"] == "high" for m in result["matches"]): + count = sum(1 for m in result["matches"] if m["severity"] == "high") + result["flags"].append( + { + "category": "disclosure", + "severity": "high", + "description": f"港交所近期发现{count}条高风险公告(停牌/清盘/调查类)", + "source": "data", + } + ) + elif result["matches"]: + result["flags"].append( + { + "category": "disclosure", + "severity": "medium", + "description": f"港交所近期发现{len(result['matches'])}条风险相关公告(盈警/配售/减持类)", + "source": "data", + } + ) + return result + + +_F4_ADDITION_RE = re.compile( + r"(omit(?:ted|ting)?|inadvertently\s+omitted|previously\s+unreported|" + r"add(?:ed|ing|itional)\s+(?:a\s+)?(?:previously\s+omitted\s+)?transactions?|" + r"late[- ]?report(?:ed|ing)|补报|漏报|遗漏)", + re.IGNORECASE, +) +_F4_CORRECTION_RE = re.compile( + r"(correct(?:ed|ing|ion|s)?|reclassif(?:ied|y|ying)|instead\s+of|" + r"erroneously\s+reported|incorrectly\s+reported|misreported|should\s+have\s+been|" + r"replaces?|supersedes?|restat(?:ed|es|ing|ement)|" + r"(?:revis(?:ed|es|ing)|chang(?:ed|es|ing))\s+from\s+\$?\s*\d|更正|修正|重分类|误报)", + re.IGNORECASE, +) +_F4_COUNT_WORDS = ("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten") +_F4_SALE_COUNT = rf"(?:[1-9]\d{{0,3}}|an?|the|{'|'.join(_F4_COUNT_WORDS[1:])})" +_F4_OMITTED = r"(?:(?:previously|inadvertently)\s+)?(?:omitted|unreported)" +_F4_REMARKS_DATE = r"[a-z]+ \d{1,2},? \d{4}" +_F4_DECLARED_NUMBER = r"(?:\d+(?:,\d{3})*(?:\.\d+)?|\.\d+)" +_F4_PER_SHARE = r"(?:\s+per\s+share)?" +_F4_CLASS_DASH = r"[-\u2010-\u2013]" +_F4_CLASS_IDENTIFIER = rf"class\s+[a-z0-9]+(?:{_F4_CLASS_DASH}[a-z0-9]+)*" +_F4_SECURITY_CLASS_RE = re.compile(rf"\b{_F4_CLASS_IDENTIFIER}\b", re.IGNORECASE | re.ASCII) +_F4_COUNTED_SALE_ADDITION_RE = re.compile( + r"(?:(?:this )?(?:form 4(?:/a)?(?: amendment)?|amendment)\s+" + r"(?:(?:is (?:being )?filed|was filed|filed)\s+to\s+)?|amending to\s+)?" + r"(?Padd(?:s|ed|ing)?|report(?:s|ed|ing)?|includ(?:e[sd]?|ing))\s+" + rf"(?P{_F4_SALE_COUNT})\s+" + rf"(?:(?P{_F4_OMITTED}|additional)\s+)?(?:(?P{_F4_DECLARED_NUMBER})-share\s+)?" + r"(?Psale(?: transactions?|s)?|transactions?)" + rf"(?:\s+of (?(share_prefix)|(?:(?P{_F4_DECLARED_NUMBER})\s+)?)" + rf"(?:(?Pcommon|ordinary|{_F4_CLASS_IDENTIFIER})\s+)?shares?)?" + rf"(?:\s+at\s+\$?\s*(?P{_F4_DECLARED_NUMBER}){_F4_PER_SHARE})?" + rf"(?:\s+(?P(?:(?:that\s+)?(?:was|were)\s+)?{_F4_OMITTED})" + rf"(?:\s+from the (?:original )?(?:form 4|filing)(?: filed on (?P{_F4_REMARKS_DATE}))?)?)?" + r"(?:\s+by the reporting (?:person|owner))?", + re.IGNORECASE | re.ASCII, +) +_F4_ROW_SALE = r"(?:sale(?: transaction)?|transaction(?: line)?|trade)" +_F4_ROW_SALE_SUBJECT = rf"(?:(?:this|the)\s+)?{_F4_ROW_SALE}(?:\s+reported on this line)?" +_F4_ROW_REPORT_VERB = r"(?:report|include|disclose)" +_F4_SALE_ORDINALS = ("first", "second", "third", "fourth", "fifth") +_F4_SALE_VENUES = ("private", "open-market") +_F4_SALE_QUALIFIER = rf"(?:{'|'.join((*_F4_SALE_ORDINALS, *_F4_SALE_VENUES))})" +_F4_ROW_SALE_DESCRIPTION = rf"(?:{_F4_SALE_QUALIFIER}\s+)?{_F4_ROW_SALE}" +_F4_ROW_ADDITION_QUALIFIER_RE = re.compile(rf"\b({_F4_SALE_QUALIFIER})\s+{_F4_ROW_SALE}\b", re.IGNORECASE) +_F4_ROW_ADDITION_FILING_DATE_RE = re.compile(rf"\bfiled on ({_F4_REMARKS_DATE})", re.IGNORECASE) +_F4_ROW_SECURITY = r"(?:\s+of\s+(?:the (?:company|issuer)'s\s+)?(?:common (?:stock|shares)|securities))?" +_F4_ROW_SALE_OBJECT = rf"{_F4_ROW_SALE_DESCRIPTION}{_F4_ROW_SECURITY}" +_F4_ROW_FILING_REFERENCE = ( + r"(?:the\s+)?(?:report(?:ing)? person's\s+)?" + r"(?:(?:original|prior|(?:previously|originally) filed)\s+)?(?:form 4(?:/a)?(?: filing)?|filing|report)" + rf"(?: (?:originally )?filed on {_F4_REMARKS_DATE})?" +) +_F4_ROW_REPORT_CONTEXT = ( + rf"(?:\s+from\s+{_F4_ROW_FILING_REFERENCE})?" + r"(?:\s+that was not previously reported)?(?:\s+on\s+\d{4}-\d{2}-\d{2})?" +) +_F4_ROW_SALE_ADDITION_RE = re.compile( + rf"(?:{_F4_ROW_SALE_SUBJECT}\s+(?:was|is)\s+(?:{_F4_OMITTED}|newly reported)|" + r"(?:this (?:amendment|report)\s+|(?:amends (?:the )?original form 4|amending)\s+to\s+|" + r"(?:this|the) transaction line (?:was|has been) added to (?:this|the) form 4 to\s+)?" + rf"(?:{_F4_ROW_REPORT_VERB}s?\s+(?:(?:an?|the)\s+)?" + rf"(?:(?:{_F4_OMITTED}|additional)\s+{_F4_ROW_SALE_OBJECT}|" + rf"{_F4_ROW_SALE_OBJECT}\s+(?:(?:that|which) was\s+)?{_F4_OMITTED})|" + rf"adds?\s+(?:(?:an?|the)\s+)?(?:{_F4_OMITTED}\s+)?{_F4_ROW_SALE_OBJECT}(?:\s+{_F4_OMITTED})?)|" + rf"{_F4_OMITTED}\s+{_F4_ROW_SALE_OBJECT}){_F4_ROW_REPORT_CONTEXT}", + re.IGNORECASE, +) +_F4_ROW_SALE_DENIAL_CONTEXT = rf"{_F4_ROW_REPORT_CONTEXT}(?:\s+in\s+(?:this|the)\s+(?:amendment|form 4(?:/a)?|report))?" +_F4_CLAUSE_ADVERBS = r"(?:(?:[a-z]+ly|also|still|just|then|instead)\s+)*" +_F4_ROW_SALE_DENIAL_RE = re.compile( + rf"{_F4_ROW_SALE_SUBJECT}\s+(?:was|is)\s+(?:not|never)\s+(?:{_F4_OMITTED}|newly reported)" + rf"{_F4_ROW_SALE_DENIAL_CONTEXT}(?=$|(?:\s*,\s*|\s+)(?:and|but)\s+)|" + rf"(?:this (?:amendment|report)\s+)?(?:does|did)\s+not\s+(?:add|{_F4_ROW_REPORT_VERB})\s+" + rf"(?:(?:{_F4_SALE_COUNT}|any)\s+)?(?:(?:new|additional|{_F4_OMITTED})\s+)?" + rf"{_F4_ROW_SALE_DESCRIPTION}s?{_F4_ROW_SECURITY}{_F4_ROW_SALE_DENIAL_CONTEXT}" + # An unpunctuated conjunction must start a predicate, not a second object such as "purchase prices". + rf"(?=$|\s*,\s*(?:and|but)\s+|\s+(?:and|but)\s+{_F4_CLAUSE_ADVERBS}" + rf"(?:(?:it|they|(?:this|the)\s+(?:amendment|report|sale|transaction|filing|row))\s+{_F4_CLAUSE_ADVERBS})?" + rf"(?:is|are|was|were|does|do|did|has|have|had|will|would|can|could|may|" + rf"(?:{_F4_ROW_REPORT_VERB}|add|correct|provide|leave|remain)s?)\b)", + re.IGNORECASE, +) +_F4_SENTENCE_BOUNDARY_RE = re.compile(r"(?:\.(?=\s|$)|[!?;。!?;])+") +_F4_REMARKS_METADATA_RE = re.compile( + rf"(?:the )?original (?:form 4|filing) was filed on {_F4_REMARKS_DATE}|" + r"\*\s*(?:[a-z0-9 &,-]+ and )?(?:(?:executive|senior|vice|chief|acting)\s+)*" + r"(?:president|director|officer|chair|secretary|treasurer)" + r"(?:,\s*(?-i:[A-Z][A-Za-z0-9&-]*(?:\s+[A-Z][A-Za-z0-9&-]*)*))?", + re.IGNORECASE | re.ASCII, +) +_F4_OTHER_CHANGE_RE = re.compile( + r"\b(?:(?:amend|adjust|fix)(?:ed|s|ing)|(?:updat|chang|revis)(?:e[ds]?|ing)|modif(?:ied|ies|ying))\b", + re.IGNORECASE, +) +_F4_PRIOR_DISCLOSURE_RE = re.compile( + r"\b(?:(?Pnot|never)\s+)?(?:previously|originally|already)\s+(?:reported|disclosed)\b" + r"(?!\s+(?:form|filing|statement)\b)|" + r"\b(?:prior|original|existing|old)\s+(?:sale|transaction|trade|price|shares?)\b", + re.IGNORECASE, +) +_F4_SALE_TO_NONSELL_RE = re.compile( + r"(\breclassif(?:ied|y|ying)|\btransaction\s+code|\bcode\s+s\s+to\b|" + r"\b(?:from|misreported|(?:erroneously|incorrectly)\s+reported)\s+(?:as\s+)?(?:a\s+)?(?:[\w-]+\s+){0,3}(?:sale|sell|sold)\b|" + r"\b(?:sale|sell|sold)\s+(?:should\s+have\s+been|was\s+actually|to\s+(?:a\s+)?(?:bona\s+fide\s+)?(?:gift|non-sale|transfer|disposition))|" + r"\b(?:instead\s+of|not)\s+(?:a\s+)?(?:[\w-]+\s+){0,2}(?:sale|sell|sold)\b|" + r"\bto\s+(?:a\s+)?(?:bona\s+fide\s+)?gift\b|" + r"重分类|改为赠与|误报为卖出|并非卖出)", + re.IGNORECASE, +) +_F4_SALE_REFERENCE = ( + r"(?:(?:the|a)\s+)?(?:(?:previously (?:misreported|reported(?: in error)?)|original)\s+)?" + rf"(?:(?P{_F4_DECLARED_NUMBER})-share\s+)?sale" + rf"(?:\s+of\s+(?P{_F4_DECLARED_NUMBER})\s+shares?(?:\s+of\s+common\s+stock)?)?" + rf"(?:\s+at\s+\$?\s*(?P{_F4_DECLARED_NUMBER}){_F4_PER_SHARE})?" +) +_F4_CURRENT_CHANGE = ( + r"(?:(?:this amendment\s+)?(?:corrects?|reclassif(?:ies|y)|changes?)|" + r"this amendment (?:is (?:being )?filed|was filed) to (?:correct|reclassify|change))" +) +_F4_EXPLICIT_SALE_RECLASS_RE = re.compile( + rf"^(?:(?P{_F4_CURRENT_CHANGE})\s+)?{_F4_SALE_REFERENCE}" + # Without the active verb before the sale, require a passive reclassification verb. + r"(?(active_change)|\s+(?:was (?:previously reported in error|incorrectly reported) and\s+)?" + r"(?:(?:is|should be)\s+reclassified|should have been reported))" + rf"\s+(?:to|as)\s+(?:a\s+)?(?:(?:bona fide|(?P{_F4_DECLARED_NUMBER})-share)\s+)?" + r"(?Pgift|non-sale|transfer|disposition)\b" + rf"|^{_F4_CURRENT_CHANGE}\s+(?:the\s+)?(?:gift\s+)?(?:transaction\s+)?code\s+(?:from\s+)?" + r"[\"']?s[\"']?(?:\s*\(sale\))?\s+to\s+[\"']?(?P(?!s\b)[a-z])\b", + re.IGNORECASE, +) +_F4_GIFT_REFERENCE = ( + r"(?:(?:the|this|a)\s+)?(?:(?:previously reported|original)\s+)?" + r"(?:gift(?:\s+(?:shares|price|quantity))?|number of (?:gift shares|shares gifted)|" + r"(?:transaction code|price|quantity|(?:number of )?shares)\s+of\s+(?:the|this) gift)\b" +) +_F4_GIFT_CORRECTION_RE = re.compile( + r"(?:^(?:this amendment\s+)?|\bis\s+(?:being\s+)?(?:filed|amended)\s+(?:solely\s+)?to\s+)" + r"(?:corrects?|revises?|updates?|restates?|changes?)\s+(?:an error in\s+)?" + rf"(?:{_F4_GIFT_REFERENCE}|previously reported as\s+[\d,.]+\s+shares?\s+gift\b)|" + rf"^{_F4_GIFT_REFERENCE}\s+(?:was|were|is|are)\s+(?:corrected|revised|updated|changed)\b", + re.IGNORECASE, +) +_F4_ROW_GIFT_ADDITION_RE = re.compile( + rf"(?:(?:this|the) gift (?:was|is) {_F4_OMITTED}|" + rf"(?:this (?:amendment|report) )?{_F4_ROW_REPORT_VERB}s? (?:a|an|one|the) {_F4_OMITTED} gift)" + rf"{_F4_ROW_REPORT_CONTEXT}", + re.IGNORECASE, +) +_F4_ROW_GIFT_ADDITION_DENIAL_RE = re.compile( + rf"(?:this|the) gift (?:was|is) (?:not|never) {_F4_OMITTED}\b|" + rf"(?:this (?:amendment|report) )?(?:does|did) not (?:add|{_F4_ROW_REPORT_VERB}) " + rf"(?:(?:a|an|any|one|the) )?(?:(?:new|additional|{_F4_OMITTED}) )?gifts?" + rf"{_F4_ROW_SALE_DENIAL_CONTEXT}(?=$|(?:\s*,\s*|\s+)(?:and|but)\s+)", + re.IGNORECASE, +) +_F4_PREVIOUSLY_REPORTED_GIFT_RE = re.compile( + rf"(?:the )?({_F4_DECLARED_NUMBER})-share gift (?:was|is) (?:previously|originally|already) (?:reported|disclosed)" + rf"(?:\s+(?:in|on)\s+{_F4_ROW_FILING_REFERENCE})?", + re.IGNORECASE, +) +_F4_RESTORE_SELL_RE = re.compile( + r"(\breclassif(?:ied|y|ying)|\btransaction\s+code|\bcode\s+s\b|" + r"\b(?:was|is|should\s+have\s+been)\s+(?:actually\s+)?(?:a\s+)?(?:[\w-]+\s+){0,2}sale\b|" + r"\b(?:instead\s+of|not)\s+(?:a\s+)?(?:[\w-]+\s+){0,2}(?:gift|non-sale|transfer)\b|" + r"\b(?:from|misreported|(?:erroneously|incorrectly)\s+reported)\s+(?:as\s+)?(?:a\s+)?(?:[\w-]+\s+){0,3}(?:gift|non-sale)\b|" + r"\bpreviously\s+reported\s+as\s+(?:a\s+)?(?:[\w-]+\s+){0,3}(?:gift|non-sale)\b|" + r"重分类|改为卖出|恢复为卖出|并非赠与)", + re.IGNORECASE, +) +_F4_DATE_CORR_RE = re.compile( + r"(transaction\s+date|trade\s+date|date\s+of\s+(?:the\s+)?(?:transaction|sale)|" + r"from\s+\d{4}-\d{2}-\d{2}\s+to\s+\d{4}-\d{2}-\d{2}|交易日期|成交日期)", + re.IGNORECASE, +) +_F4_ISO_DATE_RE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b") +_F4_PRIOR_PRICE_EXPLICIT_RE = re.compile( + r"(?:from|previously(?:\s+reported)?(?:\s+at)?|was|instead\s+of|originally(?:\s+reported)?(?:\s+at)?)" + r"\s+(?:a\s+price\s+of\s+)?\$\s*(\d+(?:,\d{3})*(?:\.\d+)?)\b|" + r"\b(?:price|px)\s+(?:from|was|of)\s+\$?\s*(\d+(?:,\d{3})*(?:\.\d+)?)\b", + re.IGNORECASE, +) +_F4_PRIOR_PRICE_LINKED_RE = re.compile( + r"\b\d+(?:,\d{3})*(?:\.\d+)?\s+shares?\s+at\s+\$\s*(\d+(?:,\d{3})*(?:\.\d+)?)\b|" + r"\b(?:corrects?|correcting|corrected|moves?|moving|moved|amends?|amending|amended)\s+" + r"(?:the\s+|a\s+)?(?:[\w-]+\s+){0,3}?(?:sale|transaction|line|row)\s+at\s+\$\s*(\d+(?:,\d{3})*(?:\.\d+)?)\b", + re.IGNORECASE, +) +_F4_PRIOR_SHARES_RE = re.compile( + r"(?:from|previously(?:\s+reported)?(?:\s+as)?|was|instead\s+of|originally(?:\s+reported)?(?:\s+as)?)" + r"\s+(\d+(?:,\d{3})*(?:\.\d+)?)\s+shares?\b|" + r"\b(\d+(?:,\d{3})*(?:\.\d+)?)\s+shares?\s+(?:at\s+\$|on\s+\d{4}-\d{2}-\d{2})|" + r"(?:misreported|reported|prior|original)\s+(\d+(?:,\d{3})*(?:\.\d+)?)[- ]shares?\s+(?:sale|transaction)\b", + re.IGNORECASE, +) + + +def _f4_tx_code(tx: dict) -> str: + return str(tx.get("code") or tx.get("transaction_code") or "").upper() + + +def _f4_is_sell(tx: dict) -> bool: + return _f4_tx_code(tx) == "S" or str(tx.get("action") or "").lower() == "sell" + + +def _f4_owner_key(tx: dict) -> tuple: + owners = tx.get("owners") + if isinstance(owners, list) and owners: + return tuple(sorted(str(o.get("cik") or o.get("name") or "") for o in owners if isinstance(o, dict))) + return (str(tx.get("owner") or tx.get("insider") or ""),) + + +def _f4_base_sig(tx: dict) -> tuple: + return ( + _f4_owner_key(tx), + str(tx.get("transaction_date") or tx.get("date") or ""), + str(tx.get("security") or ""), + bool(tx.get("derivative")), + ) + + +def _f4_exact_sig(tx: dict) -> tuple: + return ( + _f4_owner_key(tx), + str(tx.get("transaction_date") or tx.get("date") or ""), + str(tx.get("security") or ""), + bool(tx.get("derivative")), + tx.get("shares"), + tx.get("price"), + ) + + +def _f4_owner_sec_sig(tx: dict) -> tuple: + return (_f4_owner_key(tx), str(tx.get("security") or ""), bool(tx.get("derivative"))) + + +def _f4_rev_tuple(tx: dict) -> tuple[str, object, object]: + td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] + return (td, tx.get("shares"), tx.get("price")) + + +def _f4_tx_date_iso(tx: dict) -> str | None: + raw = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] + if not raw: + return None + try: + return date.fromisoformat(raw).isoformat() + except ValueError: + return None + + +def _f4_normalize_acceptance_ts(raw) -> str: + s = str(raw or "").strip() + if not s: + return "" + try: + if re.fullmatch(r"\d{14}", s): + dt = datetime.strptime(s, "%Y%m%d%H%M%S").replace(tzinfo=timezone.utc) + else: + if s.endswith(("Z", "z")): + s = s[:-1] + "+00:00" + dt = datetime.fromisoformat(s) + dt = dt.astimezone(timezone.utc) if dt.tzinfo is not None else dt.replace(tzinfo=timezone.utc) + except ValueError: + return "" + return dt.isoformat(timespec="microseconds") + + +def _f4_matches_num_set(val, target_set: set[float]) -> bool: + vf = _safe_float(val) + return vf is not None and any(math.isclose(vf, t, rel_tol=0.0, abs_tol=1e-6) for t in target_set) + + +def _f4_correction_sentences(rtext: str) -> str: + # Split on sentence boundaries (including periods after trailing numbers like "$30.") while keeping decimals intact. + sents = [s for s in _F4_SENTENCE_BOUNDARY_RE.split(rtext) if s.strip()] + corr_sents = [s for s in sents if _F4_CORRECTION_RE.search(s)] + return ". ".join(corr_sents) if corr_sents else rtext + + +def _f4_stated_sale_conversion_values(rtext: str, *fields: str) -> set[float]: + values: set[float] = set() + for sentence in _f4_statements(rtext): + match = _F4_EXPLICIT_SALE_RECLASS_RE.match(sentence) + if match: + for field in fields: + value = _safe_float((match[field] or "").replace(",", "")) + if value is not None: + values.add(value) + return values + + +def _f4_stated_prior_prices(rtext: str, new_price) -> set[float]: + if conversion_values := _f4_stated_sale_conversion_values(rtext, "source_price"): + return conversion_values + new_f = _safe_float(new_price) + scoped = _f4_correction_sentences(rtext) + explicit: set[float] = set() + for m in _F4_PRIOR_PRICE_EXPLICIT_RE.finditer(scoped): + tok = next((g for g in m.groups() if g), "").replace(",", "") + val = _safe_float(tok) + if val is not None and (new_f is None or not math.isclose(val, new_f, rel_tol=0.0, abs_tol=1e-6)): + explicit.add(val) + if explicit: + return explicit + linked: set[float] = set() + for m in _F4_PRIOR_PRICE_LINKED_RE.finditer(scoped): + tok = next((g for g in m.groups() if g), "").replace(",", "") + val = _safe_float(tok) + if val is not None and (new_f is None or not math.isclose(val, new_f, rel_tol=0.0, abs_tol=1e-6)): + linked.add(val) + return linked + + +def _f4_stated_prior_shares(rtext: str, new_shares) -> set[float]: + if conversion_values := _f4_stated_sale_conversion_values(rtext, "source_shares", "source_prefix_shares"): + return conversion_values + out: set[float] = set() + new_f = _safe_float(new_shares) + for m in _F4_PRIOR_SHARES_RE.finditer(_f4_correction_sentences(rtext)): + tok = next((g for g in m.groups() if g), "").replace(",", "") + val = _safe_float(tok) + if val is not None and (new_f is None or not math.isclose(val, new_f, rel_tol=0.0, abs_tol=1e-6)): + out.add(val) + return out + + +def _f4_has_date_corr_evidence(tx: dict, rtext: str) -> bool: + if _F4_DATE_CORR_RE.search(rtext): + return True + refs = tx.get("footnote_refs") + return isinstance(refs, dict) and any("transactiondate" in str(k).lower() for k in refs) + + +def _f4_has_amount_corr_evidence(tx: dict, rtext: str) -> bool: + if re.search(r"\b(?:price|px|shares?)\b|价格|股数", rtext, re.IGNORECASE): + return True + refs = tx.get("footnote_refs") + return isinstance(refs, dict) and any( + "transactionprice" in str(k).lower() or "transactionshares" in str(k).lower() for k in refs + ) + + +def _f4_extract_ref_ids(refs) -> list[str]: + seen: set[str] = set() + out: list[str] = [] + if isinstance(refs, dict): + for ids in refs.values(): + if isinstance(ids, list): + for fid in ids: + if fid and str(fid) not in seen: + seen.add(str(fid)) + out.append(str(fid)) + elif isinstance(ids, str) and ids not in seen: + seen.add(ids) + out.append(ids) + elif isinstance(refs, list): + for fid in refs: + if fid and str(fid) not in seen: + seen.add(str(fid)) + out.append(str(fid)) + return out + + +def _f4_statements(text: str) -> list[str]: + return [part.strip() for part in _F4_SENTENCE_BOUNDARY_RE.split(text) if part.strip()] + + +def _f4_normalize_share_class(share_class: str) -> str: + return re.sub(_F4_CLASS_DASH, "-", " ".join(share_class.casefold().split())) + + +def _f4_share_class_matches(share_class: str, security: str) -> bool: + if share_class.startswith("class "): + actual = _F4_SECURITY_CLASS_RE.search(security) + return actual is not None and _f4_normalize_share_class(actual[0]) == share_class + return re.search(rf"\b{share_class}\b", security, re.IGNORECASE) is not None + + +class _F4AdditionDeclaration(NamedTuple): + count: int + sales_only: bool + shares: float | None + price: float | None + share_class: str | None + original_date: str | None + + def matches(self, tx: dict) -> bool: + return ( + (not self.sales_only or _f4_is_sell(tx)) + and (self.shares is None or _f4_matches_num_set(tx.get("shares"), {self.shares})) + and (self.price is None or _f4_matches_num_set(tx.get("price"), {self.price})) + and (self.share_class is None or _f4_share_class_matches(self.share_class, str(tx.get("security") or ""))) + and (self.original_date is None or tx.get("original_filing_date") == self.original_date) + ) + + def merged_with(self, other: "_F4AdditionDeclaration") -> "_F4AdditionDeclaration | None": + if self.count != other.count or any( + a is not None and b is not None and a != b for a, b in zip(self[2:], other[2:]) + ): + return None + return _F4AdditionDeclaration( + self.count, + self.sales_only or other.sales_only, + self.shares if self.shares is not None else other.shares, + self.price if self.price is not None else other.price, + self.share_class or other.share_class, + self.original_date or other.original_date, + ) + + +def _f4_declared_filing_date(value: str | None) -> str | None: + if value: + for fmt in ("%B %d %Y", "%b %d %Y"): + try: + return datetime.strptime(value.replace(",", ""), fmt).date().isoformat() + except ValueError: + continue + return value + + +def _f4_sale_addition_declaration(text: str) -> _F4AdditionDeclaration | None: + match = _F4_COUNTED_SALE_ADDITION_RE.fullmatch(text) + if not match or not (match["modifier"] or match["clause"] or match["verb"].lower().startswith("add")): + return None + count = match["count"].lower() + subject = match["object"].lower() + if count.isdigit(): + declared = int(count) + elif count in {"a", "an", "the"}: + declared = int(not subject.endswith("s")) + else: + declared = _F4_COUNT_WORDS.index(count) + shares = _safe_float((match["shares"] or match["share_prefix"] or "").replace(",", "")) + price = _safe_float((match["price"] or "").replace(",", "")) + return _F4AdditionDeclaration( + declared, + subject.startswith("sale"), + shares, + price, + _f4_normalize_share_class(match["share_class"]) if match["share_class"] else None, + _f4_declared_filing_date(match["original_date"]), + ) + + +def _f4_uncounted_row_addition(text: str) -> tuple[_F4AdditionDeclaration, str | None] | None: + if not _F4_ROW_SALE_ADDITION_RE.fullmatch(text): + return None + date_match = _F4_ROW_ADDITION_FILING_DATE_RE.search(text) + original_date = _f4_declared_filing_date(date_match[1]) if date_match else None + qualifier = _F4_ROW_ADDITION_QUALIFIER_RE.search(text) + return _F4AdditionDeclaration(1, True, None, None, None, original_date), qualifier[ + 1 + ].casefold() if qualifier else None + + +class _F4AdditionClaim(NamedTuple): + declaration: _F4AdditionDeclaration + refs: set[int] + counted: bool = True + qualifier: str | None = None + + def matching_rows(self, rows: list[dict], eligible: set[int], qualifiers_by_row: list[set[str]]) -> set[int]: + return { + i + for i in self.refs & eligible + if self.declaration.matches(rows[i]) and (self.qualifier is None or self.qualifier in qualifiers_by_row[i]) + } + + +def _f4_merge_addition_claims( + shared: list[_F4AdditionClaim], + remarks: list[_F4AdditionClaim], + rows: list[dict], + additions: set[int], + qualifiers_by_row: list[set[str]], +) -> list[_F4AdditionClaim]: + claims: list[_F4AdditionClaim] = [] + unpaired: list[_F4AdditionClaim] = [] + remaining_remarks = list(remarks) + all_rows = set(range(len(rows))) + for claim in shared: + copy_in_remarks = claim._replace(refs=all_rows) + if copy_in_remarks in remaining_remarks: + remaining_remarks.remove(copy_in_remarks) + claims.append(claim) + else: + unpaired.append(claim) + # A restated row cannot corroborate a merge. A count that covers the whole accession can establish additions alone. + options: list[dict[int, _F4AdditionClaim]] = [] + for remark in remaining_remarks: + candidates: dict[int, _F4AdditionClaim] = {} + for i, claim in enumerate(unpaired): + if not (remark.counted or claim.counted): + continue + both_counted = claim.counted and remark.counted + if both_counted and claim.declaration.sales_only != remark.declaration.sales_only: + continue + declaration = claim.declaration.merged_with(remark.declaration) + if declaration is None or not declaration.count: + continue + merged = _F4AdditionClaim(declaration, claim.refs, both_counted, claim.qualifier or remark.qualifier) + if merged.counted: + eligible = all_rows if declaration.count == len(rows) and claim.refs == all_rows else additions + if len(merged.matching_rows(rows, eligible, qualifiers_by_row)) >= declaration.count: + candidates[i] = merged + else: + # The counted statement and row description must independently identify the same addition. + linked = claim.matching_rows(rows, additions, qualifiers_by_row) + if len(linked) == 1 and linked == remark.matching_rows(rows, additions, qualifiers_by_row): + candidates[i] = merged + options.append(candidates) + paired: set[int] = set() + for remark, candidates in zip(remaining_remarks, options): + if len(candidates) == 1: + i, merged = next(iter(candidates.items())) + if sum(i in others for others in options) == 1: + claims.append(merged) + paired.add(i) + continue + claims.append(remark) + return claims + [claim for i, claim in enumerate(unpaired) if i not in paired] + + +def _f4_filing_additions_covered( + claims: list[_F4AdditionClaim], rows: list[dict], additions: set[int], qualifiers_by_row: list[set[str]] +) -> bool: + if not claims: + return bool(additions) + options: list[set[int]] = [] + for claim in claims: + count = claim.declaration.count + eligible = claim.matching_rows(rows, additions, qualifiers_by_row) + if not count or len(eligible) < count or len(options) + count > len(additions): + return False + options.extend([eligible] * count) + # Assign every declared transaction to a distinct row, reassigning earlier claims when needed. + options.sort(key=len) + assigned: dict[int, int] = {} + for claim in range(len(options)): + previous: dict[int, tuple[int, int] | None] = {claim: None} + pending = [claim] + for current in pending: + free = options[current] - assigned.keys() + if free: + assigned[free.pop()] = current + while (step := previous[current]) is not None: + current, row = step + assigned[row] = current + break + for row in options[current]: + owner = assigned[row] + if owner not in previous: + previous[owner] = current, row + pending.append(owner) + else: + return False + return True + + +def _f4_conversion_targets( + acc_rows: list[dict], + refs: set[int], + conversion: re.Match[str], + ledger: list[dict], + non_sell_histories: list[list[dict]], + local_gift_corrections: dict[int, list[str]], + local_gift_additions: dict[int, bool], +) -> list[int]: + code = conversion["target_code"] or ("G" if (conversion["target"] or "").casefold() == "gift" else None) + quantity = _safe_float((conversion["target_shares"] or "").replace(",", "")) + candidates = [ + i + for i in refs + if not _f4_is_sell(acc_rows[i]) + and (code is None or _f4_tx_code(acc_rows[i]) == code.upper()) + and (quantity is None or _f4_matches_num_set(acc_rows[i].get("shares"), {quantity})) + ] + if len(candidates) <= 1: + return candidates if len(refs) == 1 else [i for i in candidates if not local_gift_additions.get(i)] + + # Multiple linked gifts can only be distinguished by the corrected transaction and its filing history. + sentence = conversion.string + prior_prices = _f4_stated_prior_prices(sentence, None) + prior_shares = _f4_stated_prior_shares(sentence, None) + matched = [] + for i in candidates: + tx = acc_rows[i] + pool, unlinked = _f4_scoped_pool(ledger, tx, len(ledger)) + if not unlinked and any( + _f4_base_sig(ledger[j]["tx"]) == _f4_base_sig(tx) + and _f4_entry_has_revision( + ledger[j], + shares_target=prior_shares or None, + price_target=prior_prices or None, + exact_shares=tx.get("shares") if not prior_shares and quantity is None else _UNSET, + ) + for j in pool + ): + matched.append(i) + if not matched: + return candidates + # Reject separately reported gifts without promoting an unmatched row by elimination. + remaining = [i for i in matched if not local_gift_additions.get(i)] + removed_addition = len(remaining) != len(matched) + if not removed_addition and len(remaining) == 1: + return remaining + + # A row-specific correction with its own prior native gift accounts for a separate transaction. + independent_gifts = set() + for i in remaining: + tx = acc_rows[i] + if _f4_tx_code(tx) != "G" or i not in local_gift_corrections: + continue + correction = ". ".join(local_gift_corrections[i]) + gift_shares = _f4_stated_prior_shares(correction, tx.get("shares")) + gift_prices = _f4_stated_prior_prices(correction, tx.get("price")) + if not (gift_shares or gift_prices): + continue + linked_date = str(tx.get("original_filing_date") or "").strip() + native = _f4_prior_native_gifts( + non_sell_histories, tx, linked_date, shares_target=gift_shares, price_target=gift_prices + ) + if len(native) == 1: + pool, _ = _f4_scoped_pool(ledger, tx, len(ledger)) + if not _f4_prior_reclassified_gifts(ledger, tx, pool, gift_shares, gift_prices): + independent_gifts.add(i) + unclaimed = [i for i in remaining if i not in independent_gifts] + return unclaimed if removed_addition else unclaimed or remaining + + +def _f4_disclosed_gift_matches( + tx: dict, shares: float, reported_filing: str | None, non_sell_histories: list[list[dict]], ledger: list[dict] +) -> bool: + if not _f4_matches_num_set(tx.get("shares"), {shares}): + return False + if not reported_filing: + return True + owner_security = _f4_owner_sec_sig(tx) + amend_date = str(tx.get("filing_date") or "").strip() + amend_ts = _f4_acceptance_ts(tx) + reported_gifts = { + _f4_base_sig(rev) + for history in non_sell_histories + if _f4_tx_code(history[0]) == "G" and _f4_owner_sec_sig(history[0]) == owner_security + for rev in _f4_non_sell_revisions(history, reported_filing, amend_date, amend_ts) + if rev.get("filing_date") == reported_filing and _f4_matches_num_set(rev.get("shares"), {shares}) + } + reported_gifts.update( + (owner, transaction_date, security, derivative) + for entry in ledger + for filing_date, (owner, transaction_date, security, derivative, gift_shares, _), code in entry["gift_sigs"] + if code == "G" + and filing_date == reported_filing + and (owner, security, derivative) == owner_security + and _f4_matches_num_set(gift_shares, {shares}) + ) + # Only narrow a dated disclosure when the cited filing identifies a known gift. + return not reported_gifts or _f4_base_sig(tx) in reported_gifts + + +def _f4_accession_note_texts( + acc_rows: list[dict], + ledger: list[dict], + non_sell_histories: list[list[dict]], + remark_conversions: list[str], + other_remarks: list[str], +) -> tuple[list[str], list[_F4AdditionClaim], set[int], dict[int, bool]]: + note_rows: dict[tuple[str | None, str], tuple[str, set[int]]] = {} + texts_by_row: list[list[str]] = [[] for _ in acc_rows] + legacy_notes = [[str(tx[key]) for key in ("amendment_reason", "note") if tx.get(key)] for tx in acc_rows] + for i, tx in enumerate(acc_rows): + footnotes = tx.get("footnotes") + if isinstance(footnotes, dict): + for ref_id in _f4_extract_ref_ids(tx.get("footnote_refs")): + for sentence in _f4_statements(str(footnotes.get(ref_id) or "")): + key = (ref_id, sentence.casefold()) + note_rows.setdefault(key, (sentence, set()))[1].add(i) + elif isinstance(footnotes, str) and footnotes: + texts_by_row[i].append(footnotes) + + # An identical filing remark must not widen the references supplied by a linked footnote. + linked_statements = {statement for _, statement in note_rows} + all_rows = set(range(len(acc_rows))) + for sentence in remark_conversions: + statement = sentence.casefold() + if statement not in linked_statements: + note_rows[None, statement] = sentence, all_rows + + local_gift_notes = { + i: [sentence for text in texts_by_row[i] + legacy_notes[i] for sentence in _f4_statements(text)] + for i, tx in enumerate(acc_rows) + if _f4_tx_code(tx) == "G" + } + linked_gift_denials: set[int] = set() + for sentence, refs in chain(note_rows.values(), ((sentence, all_rows) for sentence in other_remarks)): + if _F4_ROW_GIFT_ADDITION_DENIAL_RE.match(sentence): + linked_gift_denials.update(refs) + elif prior_gift := _F4_PREVIOUSLY_REPORTED_GIFT_RE.fullmatch(sentence): + shares = _safe_float(prior_gift[1].replace(",", "")) + if shares is not None: + stated_date = _F4_ROW_ADDITION_FILING_DATE_RE.search(sentence) + reported_filing = _f4_declared_filing_date(stated_date[1]) if stated_date else None + linked_gift_denials.update( + i + for i in refs + if i in local_gift_notes + and _f4_disclosed_gift_matches(acc_rows[i], shares, reported_filing, non_sell_histories, ledger) + ) + for sentence, refs in note_rows.values(): + if len(refs) == 1: + i = next(iter(refs)) + if i in local_gift_notes: + local_gift_notes[i].append(sentence) + local_gift_corrections: dict[int, list[str]] = {} + local_gift_additions: dict[int, bool] = {} + for i, sentences in local_gift_notes.items(): + corrections = [sentence for sentence in sentences if _F4_GIFT_CORRECTION_RE.search(sentence)] + if corrections: + local_gift_corrections[i] = corrections + if any(_F4_ROW_GIFT_ADDITION_RE.fullmatch(sentence) for sentence in sentences): + local_gift_additions[i] = not ( + corrections + or i in linked_gift_denials + or any( + _F4_ROW_GIFT_ADDITION_DENIAL_RE.match(sentence) + or _F4_CORRECTION_RE.search(sentence) + or _F4_EXPLICIT_SALE_RECLASS_RE.match(sentence) + or any(not match["negated"] for match in _F4_PRIOR_DISCLOSURE_RE.finditer(sentence)) + for sentence in sentences + ) + ) + + shared_additions: list[_F4AdditionClaim] = [] + # Conflicting gift-addition evidence cannot justify an inferred sale conversion. + unresolved_conversions = {i for i, is_addition in local_gift_additions.items() if not is_addition} + for sentence, refs in note_rows.values(): + if conversion := _F4_EXPLICIT_SALE_RECLASS_RE.match(sentence): + targets = _f4_conversion_targets( + acc_rows, refs, conversion, ledger, non_sell_histories, local_gift_corrections, local_gift_additions + ) + if len(refs) > 1 and len(targets) == 1 and local_gift_additions.get(targets[0]) is False: + # A shared note cannot resolve the target's contradictory addition evidence. + targets = [] + if len(targets) == 1: + texts_by_row[targets[0]].append(sentence) + else: + unresolved_conversions.update(targets or refs) + continue + if len(refs) > 1 and any(_f4_is_sell(acc_rows[i]) for i in refs): + declaration = _f4_sale_addition_declaration(sentence) + if declaration is not None: + shared_additions.append(_F4AdditionClaim(declaration, refs)) + continue + if row_addition := _f4_uncounted_row_addition(sentence): + declaration, qualifier = row_addition + shared_additions.append(_F4AdditionClaim(declaration, refs, counted=False, qualifier=qualifier)) + continue + for i in refs: + texts_by_row[i].append(sentence) + for row_parts, notes in zip(texts_by_row, legacy_notes): + row_parts.extend(notes) + row_texts = [ + ". ".join(part.strip().rstrip(".") for part in row_parts if part.strip()) for row_parts in texts_by_row + ] + return row_texts, shared_additions, unresolved_conversions, local_gift_additions + + +def _f4_resolve_accession_intents( + acc_rows: list[dict], + ledger: list[dict], + non_sell_histories: list[list[dict]], +) -> tuple[list[tuple[bool, bool]], list[bool], list[str], set[int], set[int]]: + """Resolve per-row (is_add, is_corr) strictly from row-scoped evidence. + + Use filing evidence for a single unambiguous row or an explicit sale addition count + covering every row. Leave unattributed rows in mixed filings uncertain. + """ + remarks_parts = list(dict.fromkeys(rem for tx in acc_rows if (rem := str(tx.get("remarks") or "").strip()))) + remarks_sentences = [sentence for text in remarks_parts for sentence in _f4_statements(text)] + remark_conversions = [] + other_remarks = [] + for sentence in remarks_sentences: + if _F4_EXPLICIT_SALE_RECLASS_RE.match(sentence): + remark_conversions.append(sentence) + else: + other_remarks.append(sentence) + row_texts, shared_additions, unresolved_conversions, local_gift_additions = _f4_accession_note_texts( + acc_rows, + ledger, + non_sell_histories, + remark_conversions, + other_remarks, + ) + independent_gift_additions = {i for i, added in local_gift_additions.items() if added} + prior_disclosures = [ + any(not match["negated"] for match in _F4_PRIOR_DISCLOSURE_RE.finditer(text)) for text in row_texts + ] + row_intents = [] + ambiguous = [i in unresolved_conversions for i in range(len(acc_rows))] + qualifiers_by_row: list[set[str]] = [set() for _ in acc_rows] + row_denies_addition = False + for i, (tx, rt, prior) in enumerate(zip(acc_rows, row_texts, prior_disclosures)): + if _f4_is_sell(tx): + sentences = _f4_statements(rt) + denial = any(_F4_ROW_SALE_DENIAL_RE.match(sentence) for sentence in sentences) + row_denies_addition |= denial + singular_declarations = [] + for sentence in sentences: + declaration = _f4_sale_addition_declaration(sentence) + if declaration is not None and declaration.count == 1: + singular_declarations.append(declaration) + elif row_addition := _f4_uncounted_row_addition(sentence): + declaration, qualifier = row_addition + singular_declarations.append(declaration) + if qualifier is not None: + qualifiers_by_row[i].add(qualifier) + for group in (_F4_SALE_ORDINALS, _F4_SALE_VENUES): + if len(qualifiers_by_row[i].intersection(group)) > 1: + qualifiers_by_row[i].difference_update(group) + ambiguous[i] = True + contradictory = any(not declaration.matches(tx) for declaration in singular_declarations) + if contradictory: + ambiguous[i] = True + addition = not (prior or denial or contradictory) and bool(singular_declarations) + elif i in local_gift_additions: + addition = local_gift_additions[i] + else: + addition = bool(_F4_ADDITION_RE.search(rt)) + row_intents.append((addition, bool(_F4_CORRECTION_RE.search(rt)))) + if not (other_remarks or shared_additions): + return row_intents, ambiguous, row_texts, unresolved_conversions, independent_gift_additions + rem_text = ". ".join(other_remarks) + # shortcut: promote explicit English declarations, and expand for verified filing wording. + all_rows = set(range(len(acc_rows))) + remarks_claims = [] + mixed_filing_evidence = False + for sentence in other_remarks: + declaration = _f4_sale_addition_declaration(sentence) + if declaration is not None: + remarks_claims.append(_F4AdditionClaim(declaration, all_rows)) + elif row_addition := _f4_uncounted_row_addition(sentence): + declaration, qualifier = row_addition + remarks_claims.append(_F4AdditionClaim(declaration, all_rows, counted=False, qualifier=qualifier)) + elif not _F4_REMARKS_METADATA_RE.fullmatch(sentence) or _F4_OTHER_CHANGE_RE.search(sentence): + mixed_filing_evidence = True + claimed_additions = {i for i, (addition, correction) in enumerate(row_intents) if addition and not correction} + claims = _f4_merge_addition_claims(shared_additions, remarks_claims, acc_rows, claimed_additions, qualifiers_by_row) + covering_declaration = ( + claims[0].declaration if len(claims) == 1 and claims[0].counted and claims[0].refs == all_rows else None + ) + filing_add = bool(claims) or bool(_F4_ADDITION_RE.search(rem_text)) + rem_corr = bool(_F4_CORRECTION_RE.search(rem_text)) + if not (filing_add or rem_corr): + return row_intents, ambiguous, row_texts, unresolved_conversions, independent_gift_additions + if ( + len(remarks_parts) <= 1 + and covering_declaration is not None + and covering_declaration.count == len(acc_rows) + and (len(acc_rows) == 1 or covering_declaration.sales_only) + and all(covering_declaration.matches(tx) for tx in acc_rows) + and not mixed_filing_evidence + and not any(ambiguous) + and not rem_corr + and not row_denies_addition + and not any(prior_disclosures) + and not any(correction for _, correction in row_intents) + and not any(_F4_OTHER_CHANGE_RE.search(text) for text in row_texts) + and not any( + not addition and _F4_ADDITION_RE.search(text) for text, (addition, _) in zip(row_texts, row_intents) + ) + and all(_f4_is_sell(tx) for tx in acc_rows) + ): + for tx, (addition, _) in zip(acc_rows, row_intents): + if addition: + continue + pool, _ = _f4_scoped_pool(ledger, tx, len(ledger)) + sig = _f4_exact_sig(tx) + if any(sig in ledger[i]["sigs"] for i in pool): + break + else: + return ( + [(True, False)] * len(acc_rows), + ambiguous, + row_texts, + unresolved_conversions, + independent_gift_additions, + ) + unclaimed_add = filing_add and not _f4_filing_additions_covered( + claims, acc_rows, claimed_additions, qualifiers_by_row + ) + unclaimed_corr = rem_corr and not any(rc for _, rc in row_intents) + if not (unclaimed_add or unclaimed_corr): + return row_intents, ambiguous, row_texts, unresolved_conversions, independent_gift_additions + unattributed = [i for i, (ra, rc) in enumerate(row_intents) if not (ra or rc)] + if len(acc_rows) == 1 and len(unattributed) == 1 and (unclaimed_add != unclaimed_corr): + if unclaimed_add and _f4_is_sell(acc_rows[0]): + ambiguous[0] = True + return row_intents, ambiguous, row_texts, unresolved_conversions, independent_gift_additions + row_intents[0] = (unclaimed_add, unclaimed_corr) + row_texts[0] = ". ".join(filter(None, (row_texts[0], rem_text))) + return row_intents, ambiguous, row_texts, unresolved_conversions, independent_gift_additions + for i in unattributed or range(len(acc_rows)): + ambiguous[i] = True + return row_intents, ambiguous, row_texts, unresolved_conversions, independent_gift_additions + + +def _f4_make_ledger_entry(tx: dict, *, from_orig: bool) -> dict: + shares = tx.get("shares") + fdate = str(tx.get("filing_date") or "").strip() + orig_fdate = str(tx.get("original_filing_date") or "").strip() if not from_orig else "" + filing_dates = {d for d in (fdate, orig_fdate) if d} + return { + "tx": tx, + "orig_tx": tx, + "sigs": {_f4_exact_sig(tx)}, + "revisions": [_f4_rev_tuple(tx)], + "gift_sigs": set(), + "gift_revisions": [], + "shares_set": {shares} if shares is not None else set(), + "filing_dates": filing_dates, + "orig_acceptance_ts": _f4_acceptance_ts(tx), + "orig_accession": str(tx.get("accession") or "").strip() or None, + "from_orig": from_orig, + "reclassified": False, + } + + +def _f4_entry_has_revision( + entry: dict, + *, + dates: set[str] | None = None, + shares_target: set[float] | None = None, + price_target: set[float] | None = None, + exact_shares: object = _UNSET, + exact_price: object = _UNSET, + include_gift_revisions: bool = False, + gift_filing_date: str | None = None, + gift_only: bool = False, +) -> bool: + revs = [] if gift_only else entry["revisions"] + if include_gift_revisions or gift_only: + matching_gf = [rev[1:] for rev in entry["gift_revisions"] if gift_filing_date and rev[0] == gift_filing_date] + revs = matching_gf or revs + [rev[1:] for rev in entry["gift_revisions"]] + for rev_date, rev_shares, rev_price in revs: + if dates is not None and rev_date not in dates: + continue + if shares_target is not None and not _f4_matches_num_set(rev_shares, shares_target): + continue + if price_target is not None and not _f4_matches_num_set(rev_price, price_target): + continue + if exact_shares is not _UNSET and rev_shares != exact_shares: + continue + if exact_price is not _UNSET and rev_price != exact_price: + continue + return True + return False + + +def _f4_record_filing_provenance(ledger: list[dict], idx: int, tx: dict) -> None: + fdate = str(tx.get("filing_date") or "").strip() + if fdate: + ledger[idx]["filing_dates"].add(fdate) + + +def _f4_mark_reclassified(ledger: list[dict], idx: int, tx: dict) -> None: + entry = ledger[idx] + entry["reclassified"] = True + gfdate = str(tx.get("filing_date") or "").strip() + entry["gift_sigs"].add((gfdate, _f4_exact_sig(tx), _f4_tx_code(tx))) + grev = (gfdate, *_f4_rev_tuple(tx)) + if grev not in entry["gift_revisions"]: + entry["gift_revisions"].append(grev) + _f4_record_filing_provenance(ledger, idx, tx) + + +def _f4_update_entry(ledger: list[dict], idx: int, tx: dict, *, restore_if_reclassified: bool = False) -> None: + entry = ledger[idx] + entry["tx"] = tx + entry["sigs"].add(_f4_exact_sig(tx)) + rev = _f4_rev_tuple(tx) + if rev not in entry["revisions"]: + entry["revisions"].append(rev) + if tx.get("shares") is not None: + entry["shares_set"].add(tx.get("shares")) + _f4_record_filing_provenance(ledger, idx, tx) + if restore_if_reclassified and entry["reclassified"]: + entry["reclassified"] = False + + +def _f4_acceptance_ts(tx: dict) -> str: + return _f4_normalize_acceptance_ts(tx.get("acceptance_datetime") or tx.get("acceptanceDateTime")) + + +def _f4_filed_on_or_before(filing_date: str, acceptance_ts: str, amend_date: str, amend_ts: str) -> bool: + if not amend_date or not filing_date: + return True + if filing_date == amend_date and amend_ts and acceptance_ts: + return acceptance_ts <= amend_ts + return filing_date <= amend_date + + +def _f4_scoped_pool( + ledger: list[dict], + tx: dict, + prior_len: int, + *, + ignore_tx_date: bool = False, + prior_dates: set[str] | None = None, + include_gift_revisions: bool = False, +) -> tuple[list[int], bool]: + """Filter ledger indices by filing chronology and filing-date provenance. + + Originals filed strictly after the amendment are excluded even when `original_filing_date` + is absent. Multi-accession ambiguity is intentionally NOT checked here; callers check + `_f4_has_multi_accession_ambiguity` AFTER applying row-level evidence (shares, price, + revision history) so distinct transactions sharing a filing-date chain remain linkable. + """ + amend_fdate = str(tx.get("filing_date") or "").strip() + amend_ts = _f4_acceptance_ts(tx) + + def _filed_on_or_before(entry: dict) -> bool: + earliest = min(entry["filing_dates"], default="") + return _f4_filed_on_or_before(earliest, entry["orig_acceptance_ts"], amend_fdate, amend_ts) + + orig_date = str(tx.get("original_filing_date") or "").strip() + if not orig_date or not any(ledger[i]["filing_dates"] for i in range(prior_len)): + pool = [i for i in range(prior_len) if _filed_on_or_before(ledger[i])] + else: + pool = [ + i for i in range(prior_len) if orig_date in ledger[i]["filing_dates"] and _filed_on_or_before(ledger[i]) + ] + if not pool: + return [], True + if ignore_tx_date and prior_dates: + osig = _f4_owner_sec_sig(tx) + eligible = [ + i + for i in pool + if _f4_owner_sec_sig(ledger[i]["tx"]) == osig + and _f4_entry_has_revision( + ledger[i], + dates=prior_dates, + include_gift_revisions=include_gift_revisions, + gift_filing_date=orig_date or None, + ) + ] + if not eligible: + return [], True + return eligible, False + return pool, False + + +def _f4_has_multi_accession_ambiguity(ledger: list[dict], tx: dict, cands: list[int]) -> bool: + if not str(tx.get("original_filing_date") or "").strip(): + return False + return len({ledger[i]["orig_accession"] for i in cands if ledger[i]["orig_accession"]}) > 1 + + +def _f4_sort_amendment_accessions(all_amend: list[dict]) -> tuple[list[tuple[str, list[dict]]], list[dict]]: + """Group Form 4/A rows by accession and sort by (filing_date, EDGAR acceptanceDateTime, accession).""" + amend_by_acc: dict[str, list[dict]] = {} + for tx in all_amend: + acc = str(tx.get("accession") or f"__amend_{id(tx)}") + amend_by_acc.setdefault(acc, []).append(tx) + + acc_meta: dict[str, tuple[str, str]] = {} + same_day_groups: dict[tuple[tuple, str], list[str]] = {} + for acc, rows in amend_by_acc.items(): + fdate = min(str(r.get("filing_date") or "") for r in rows) + acc_ts = min((ts for r in rows if (ts := _f4_acceptance_ts(r))), default="") + acc_meta[acc] = (fdate, acc_ts) + for ok in {_f4_owner_key(r) for r in rows}: + same_day_groups.setdefault((ok, fdate), []).append(acc) + + def _same_submitter_prefix(acc_a: str, acc_b: str) -> bool: + return "-" in acc_a and "-" in acc_b and acc_a.split("-", 1)[0] == acc_b.split("-", 1)[0] + + uncertain_txs: list[dict] = [] + for (_ok, _fdate), accs in same_day_groups.items(): + if len(accs) < 2: + continue + ambig_accs: set[str] = set() + for i in range(len(accs)): + for j in range(i + 1, len(accs)): + a, b = accs[i], accs[j] + ts_a, ts_b = acc_meta[a][1], acc_meta[b][1] + if bool(ts_a) != bool(ts_b) or (ts_a == ts_b and not _same_submitter_prefix(a, b)): + ambig_accs.update((a, b)) + for a in ambig_accs: + uncertain_txs.extend(amend_by_acc[a]) + + sorted_items = sorted( + amend_by_acc.items(), + key=lambda item: (acc_meta[item[0]][0], acc_meta[item[0]][1], item[0]), + ) + return sorted_items, uncertain_txs + + +def _f4_non_sell_revisions(history: list[dict], linked_date: str, amend_date: str, amend_ts: str) -> list[dict]: + """Return revisions identified by the filing link and filed by the amendment time.""" + original_date = str(history[0].get("filing_date") or "").strip() + links_chain = not linked_date or not original_date or linked_date == original_date + revisions = [] + for rev in history: + revision_date = str(rev.get("filing_date") or "").strip() + if (links_chain or revision_date == linked_date) and _f4_filed_on_or_before( + revision_date, _f4_acceptance_ts(rev), amend_date, amend_ts + ): + revisions.append(rev) + return revisions + + +def _f4_prior_native_gifts( + non_sell_histories: list[list[dict]], + tx: dict, + linked_date: str, + *, + shares_target: set[float] | None = None, + price_target: set[float] | None = None, +) -> list[tuple[int, list[dict]]]: + base = _f4_base_sig(tx) + filing_date = str(tx.get("filing_date") or "").strip() + acceptance_ts = _f4_acceptance_ts(tx) + gifts = [] + for i, history in enumerate(non_sell_histories): + if _f4_tx_code(history[0]) != "G" or _f4_base_sig(history[0]) != base: + continue + revisions = [ + rev + for rev in _f4_non_sell_revisions(history, linked_date, filing_date, acceptance_ts) + if (not shares_target or _f4_matches_num_set(rev.get("shares"), shares_target)) + and (not price_target or _f4_matches_num_set(rev.get("price"), price_target)) + ] + if revisions: + gifts.append((i, revisions)) + return gifts + + +def _f4_prior_reclassified_gifts( + ledger: list[dict], tx: dict, pool: list[int], prior_shares: set[float], prior_prices: set[float] +) -> list[int]: + base = _f4_base_sig(tx) + linked_date = str(tx.get("original_filing_date") or "").strip() or None + return [ + i + for i in pool + if ledger[i]["reclassified"] + and _f4_base_sig(ledger[i]["tx"]) == base + and _f4_entry_has_revision( + ledger[i], + shares_target=prior_shares or None, + price_target=prior_prices or None, + gift_filing_date=linked_date, + gift_only=True, + ) + ] + + +def _f4_reconcile_non_sells( + ledger: list[dict], + non_sell_histories: list[list[dict]], + acc_non_sells: list[tuple[dict, tuple[bool, bool], bool, str, bool, bool]], + prior_len: int, + mark_uncertain, +) -> tuple[set[int], list[tuple[int, dict]]]: + acc_orig_ns_matched: set[int] = set() + acc_matched_ns: set[int] = set() + pending_reclassifications: list[tuple[int, dict]] = [] + native_gift_claims: dict[int, list[dict]] = {} + revision_claims: dict[int, list[dict]] = {} + prior_gift_claims: set[int] = set() + + def reserve_target(target: int, tx: dict) -> None: + if ledger[target]["reclassified"]: + revision_claims.setdefault(target, []).append(tx) + else: + acc_matched_ns.add(target) + pending_reclassifications.append((target, tx)) + + def prefer_active_sales(candidates: list[int], text: str) -> list[int]: + # Prefer an active sale only when an earlier matching pass identified the existing gift separately. + if prior_gift_claims.intersection(candidates) and any( + _F4_EXPLICIT_SALE_RECLASS_RE.match(sentence) for sentence in _f4_statements(text) + ): + return [i for i in candidates if not ledger[i]["reclassified"]] or candidates + return candidates + + acc_added_non_sells: list[dict] = [] + ns_candidates: list[tuple[dict, bool, bool, str]] = [] + for tx, (is_add, is_corr), is_ambig, rtext, unresolved_conversion, independent_gift_addition in acc_non_sells: + base = _f4_base_sig(tx) + code = _f4_tx_code(tx) + shares = tx.get("shares") + orig_date = str(tx.get("original_filing_date") or "").strip() + has_identity = base[0] != ("",) and bool(base[1]) and shares is not None + pool, pool_unlinked = _f4_scoped_pool(ledger, tx, prior_len) + sentences = _f4_statements(rtext) + explicit_sale_conversion = any(_F4_EXPLICIT_SALE_RECLASS_RE.match(sentence) for sentence in sentences) + is_corr = is_corr or explicit_sale_conversion + is_explicit_add = is_add and not is_corr + gift_corrections = [sentence for sentence in sentences if _F4_GIFT_CORRECTION_RE.search(sentence)] + if gift_corrections and not explicit_sale_conversion: + # The new quantity or price identifies the revision, not the transaction being corrected. + correction_text = ". ".join(gift_corrections) + prior_shares = _f4_stated_prior_shares(correction_text, shares) + prior_prices = _f4_stated_prior_prices(correction_text, tx.get("price")) + native_gifts = [] + gift_candidates = [] + if has_identity: + native_gifts = _f4_prior_native_gifts( + non_sell_histories, tx, orig_date, shares_target=prior_shares, price_target=prior_prices + ) + gift_candidates = _f4_prior_reclassified_gifts(ledger, tx, pool, prior_shares, prior_prices) + if len(native_gifts) == 1 and not gift_candidates: + native_gift_claims.setdefault(native_gifts[0][0], []).append(tx) + elif not native_gifts and len(gift_candidates) == 1: + reserve_target(gift_candidates[0], tx) + else: + mark_uncertain(tx) + continue + if unresolved_conversion and not (explicit_sale_conversion or is_explicit_add): + # A quantity match cannot stand in for the unresolved footnote. + continue + if independent_gift_addition and is_explicit_add: + addition_notes = {sentence for sentence in sentences if _F4_ROW_GIFT_ADDITION_RE.fullmatch(sentence)} + omission_note = next(iter(addition_notes)) if len(addition_notes) == 1 else "" + date_ref = _F4_ROW_ADDITION_FILING_DATE_RE.search(omission_note) + omitted_from = _f4_declared_filing_date(date_ref[1]) if date_ref else None + if date_ref and omitted_from: + omission_note = omission_note[: date_ref.start(1)] + omitted_from + omission_note[date_ref.end(1) :] + omission_key = omission_note.casefold() + gift_revision = dict(tx, _f4_confirmed_gift_omission=omission_key) if omitted_from else tx + # An unchanged omission claim can refer to an older filing than the linked amendment. + if has_identity and orig_date and omitted_from and omitted_from < orig_date: + exact = _f4_exact_sig(tx) + linked_gifts = [ + i + for i, revisions in _f4_prior_native_gifts(non_sell_histories, tx, orig_date) + if any( + rev.get("filing_date") == orig_date + and rev.get("_f4_confirmed_gift_omission") == omission_key + and _f4_exact_sig(rev) == exact + for rev in revisions + ) + ] + if len(linked_gifts) == 1: + target = linked_gifts[0] + native_gift_claims.setdefault(target, []).append(gift_revision) + acc_orig_ns_matched.add(target) + continue + if linked_gifts: + mark_uncertain(tx) + continue + # Row-local addition evidence takes precedence over an identical original gift. + acc_added_non_sells.append(gift_revision) + continue + is_sale_conversion = explicit_sale_conversion or (is_corr and bool(_F4_SALE_TO_NONSELL_RE.search(rtext))) + if code == "G" and has_identity and not (is_explicit_add or is_ambig or is_sale_conversion): + exact = _f4_exact_sig(tx) + exact_native_gifts = [ + i + for i, revisions in _f4_prior_native_gifts(non_sell_histories, tx, orig_date) + if any(_f4_tx_code(rev) == code and _f4_exact_sig(rev) == exact for rev in revisions) + ] + if len(exact_native_gifts) == 1 and not any( + ledger[i]["reclassified"] + and _f4_base_sig(ledger[i]["tx"]) == base + and _f4_entry_has_revision( + ledger[i], + dates={_f4_rev_tuple(tx)[0]}, + exact_shares=shares, + exact_price=tx.get("price"), + gift_filing_date=orig_date, + gift_only=True, + ) + for i in pool + ): + target = exact_native_gifts[0] + native_gift_claims.setdefault(target, []).append(tx) + acc_orig_ns_matched.add(target) + continue + ns_idx = None + matching_revisions = [] + filing_date = str(tx.get("filing_date") or "").strip() + acceptance_ts = _f4_acceptance_ts(tx) + for i, history in enumerate(non_sell_histories): + if i in acc_orig_ns_matched or _f4_base_sig(history[0]) != base: + continue + eligible = history[:1] if is_explicit_add else history + matching_revisions = [ + rev + for rev in _f4_non_sell_revisions(eligible, orig_date, filing_date, acceptance_ts) + if _f4_tx_code(rev) == code and (shares is None or rev.get("shares") == shares) + ] + if matching_revisions: + ns_idx = i + break + if ns_idx is not None: + priced_sell_match = ( + not pool_unlinked + and has_identity + and tx.get("price") is not None + and all(rev.get("price") != tx.get("price") for rev in matching_revisions) + and any(i not in acc_matched_ns and _f4_exact_sig(tx) in ledger[i]["sigs"] for i in pool) + ) + has_ledger_sell = not pool_unlinked and any( + i not in acc_matched_ns and _f4_base_sig(ledger[i]["tx"]) == base for i in pool + ) + if priced_sell_match or (has_ledger_sell and is_sale_conversion): + ns_candidates.append((tx, is_add, is_corr, rtext)) + continue + acc_orig_ns_matched.add(ns_idx) + continue + if is_explicit_add: + acc_added_non_sells.append(tx) + continue + if pool_unlinked: + mark_uncertain(tx) + continue + ns_candidates.append((tx, is_add, is_corr, rtext)) + prior_gift_claims.update(revision_claims) + + # Pass A0: explicit corrections stating prior shares/price resolve FIRST in order-independent batch waves + # so specific claims reserve their target before broader claims retry, and new values never hijack unrelated sales. + a0_rows: list[tuple[int, dict, str, set[float], set[float]]] = [] + after_ns_a0: list[tuple[dict, bool, bool, str]] = [] + for idx_ns, (tx, is_add, is_corr, rtext) in enumerate(ns_candidates): + base = _f4_base_sig(tx) + shares = tx.get("shares") + prior_shares = _f4_stated_prior_shares(rtext, shares) if is_corr else set() + prior_prices = _f4_stated_prior_prices(rtext, tx.get("price")) if is_corr else set() + if is_corr and (prior_shares or prior_prices) and base[0] != ("",) and bool(base[1]): + a0_rows.append((idx_ns, tx, rtext, prior_shares, prior_prices)) + else: + after_ns_a0.append((tx, is_add, is_corr, rtext)) + + def _a0_cands(tx: dict, text: str, prior_shares: set[float], prior_prices: set[float]) -> tuple[list[int], bool]: + pool, pool_unlinked = _f4_scoped_pool(ledger, tx, prior_len) + if pool_unlinked: + return [], True + base = _f4_base_sig(tx) + orig_date = str(tx.get("original_filing_date") or "").strip() or None + cands = [ + i + for i in pool + if i not in acc_matched_ns + and _f4_base_sig(ledger[i]["tx"]) == base + and _f4_entry_has_revision( + ledger[i], + shares_target=prior_shares or None, + price_target=prior_prices or None, + include_gift_revisions=ledger[i]["reclassified"], + gift_filing_date=orig_date, + ) + ] + cands = prefer_active_sales(cands, text) + if cands and _f4_has_multi_accession_ambiguity(ledger, tx, cands): + return [], True + return cands, False + + resolved_a0: set[int] = set() + while True: + single_a0_claims: dict[int, list[tuple[int, dict]]] = {} + for idx_ns, tx, rtext, prior_shares, prior_prices in a0_rows: + if idx_ns in resolved_a0: + continue + cands, is_ambig = _a0_cands(tx, rtext, prior_shares, prior_prices) + if not is_ambig and len(cands) == 1: + single_a0_claims.setdefault(cands[0], []).append((idx_ns, tx)) + progressed = False + for target, claimants in single_a0_claims.items(): + if len(claimants) == 1: + idx_ns, tx = claimants[0] + reserve_target(target, tx) + resolved_a0.add(idx_ns) + progressed = True + if not progressed: + break + prior_gift_claims.update(revision_claims) + + for idx_ns, tx, rtext, prior_shares, prior_prices in a0_rows: + if idx_ns in resolved_a0: + continue + cands, is_ambig = _a0_cands(tx, rtext, prior_shares, prior_prices) + if not is_ambig: + already_reclass = [i for i in cands if ledger[i]["reclassified"]] + if len(already_reclass) == 1: + reserve_target(already_reclass[0], tx) + continue + mark_uncertain(tx) + prior_gift_claims.update(revision_claims) + + # Pass A1: exact (base, shares, price) matches first (independent of row order within accession). + after_ns_a1: list[tuple[dict, bool, bool, str]] = [] + for tx, is_add, is_corr, rtext in after_ns_a0: + base = _f4_base_sig(tx) + shares = tx.get("shares") + has_identity = base[0] != ("",) and bool(base[1]) and shares is not None + pool, pool_unlinked = _f4_scoped_pool(ledger, tx, prior_len) + if pool_unlinked: + mark_uncertain(tx) + continue + if has_identity and tx.get("price") is not None: + exact = _f4_exact_sig(tx) + exact_cands = [i for i in pool if i not in acc_matched_ns and exact in ledger[i]["sigs"]] + if exact_cands: + exact_cands = prefer_active_sales(exact_cands, rtext) + cur_exact = [i for i in exact_cands if _f4_exact_sig(ledger[i]["tx"]) == exact] + if cur_exact: + exact_cands = cur_exact + if _f4_has_multi_accession_ambiguity(ledger, tx, exact_cands): + mark_uncertain(tx) + continue + reclass_exact = [i for i in exact_cands if ledger[i]["reclassified"]] + reserve_target(reclass_exact[0] if reclass_exact else exact_cands[0], tx) + continue + after_ns_a1.append((tx, is_add, is_corr, rtext)) + prior_gift_claims.update(revision_claims) + + # Pass A2: unique (base, shares) matches (or uniform-price candidates) after exact matches are reserved. + deferred_ns: list[tuple[dict, bool, bool, str]] = [] + for tx, is_add, is_corr, rtext in after_ns_a1: + base = _f4_base_sig(tx) + shares = tx.get("shares") + has_identity = base[0] != ("",) and bool(base[1]) and shares is not None + pool, _ = _f4_scoped_pool(ledger, tx, prior_len) + if has_identity: + share_cands = [ + i + for i in pool + if i not in acc_matched_ns + and _f4_base_sig(ledger[i]["tx"]) == base + and shares in ledger[i]["shares_set"] + ] + share_cands = prefer_active_sales(share_cands, rtext) + if share_cands and _f4_has_multi_accession_ambiguity(ledger, tx, share_cands): + mark_uncertain(tx) + continue + if len(share_cands) == 1 or ( + len(share_cands) > 1 and len({ledger[i]["tx"].get("price") for i in share_cands}) == 1 + ): + reclass_cands = [i for i in share_cands if ledger[i]["reclassified"]] + reserve_target(reclass_cands[0] if reclass_cands else share_cands[0], tx) + continue + deferred_ns.append((tx, is_add, is_corr, rtext)) + prior_gift_claims.update(revision_claims) + + # Pass B: remaining blank-price links and explicit share-changing corrections. + for tx, _is_add, is_corr, rtext in deferred_ns: + base = _f4_base_sig(tx) + shares = tx.get("shares") + has_identity = base[0] != ("",) and bool(base[1]) and shares is not None + pool, _ = _f4_scoped_pool(ledger, tx, prior_len) + if has_identity: + share_cands = [ + i + for i in pool + if i not in acc_matched_ns + and _f4_base_sig(ledger[i]["tx"]) == base + and shares in ledger[i]["shares_set"] + ] + share_cands = prefer_active_sales(share_cands, rtext) + if share_cands and _f4_has_multi_accession_ambiguity(ledger, tx, share_cands): + mark_uncertain(tx) + continue + if len(share_cands) == 1: + reserve_target(share_cands[0], tx) + continue + if len(share_cands) > 1: + already_reclass = [i for i in share_cands if ledger[i]["reclassified"]] + if len(already_reclass) == 1: + reserve_target(already_reclass[0], tx) + continue + mark_uncertain(tx) + continue + if is_corr and base[0] != ("",) and bool(base[1]): + base_cands = [i for i in pool if i not in acc_matched_ns and _f4_base_sig(ledger[i]["tx"]) == base] + base_cands = prefer_active_sales(base_cands, rtext) + if base_cands and _f4_has_multi_accession_ambiguity(ledger, tx, base_cands): + mark_uncertain(tx) + continue + if len(base_cands) == 1: + reserve_target(base_cands[0], tx) + continue + already_reclass = [i for i in base_cands if ledger[i]["reclassified"]] + if len(already_reclass) == 1: + reserve_target(already_reclass[0], tx) + continue + mark_uncertain(tx) + continue + if not has_identity: + mark_uncertain(tx) + + # An existing gift can attract claims at different match strengths within the same filing. + for target, claimants in native_gift_claims.items(): + if len(claimants) == 1: + non_sell_histories[target].append(claimants[0]) + else: + for tx in claimants: + mark_uncertain(tx) + for target, claimants in revision_claims.items(): + acc_matched_ns.add(target) + if len(claimants) == 1: + pending_reclassifications.append((target, claimants[0])) + else: + for tx in claimants: + mark_uncertain(tx) + non_sell_histories.extend([tx] for tx in acc_added_non_sells) + return acc_matched_ns, pending_reclassifications + + +def _f4_reconcile_sells( + ledger: list[dict], + acc_sells: list[tuple[dict, tuple[bool, bool], bool, str]], + prior_len: int, + mark_uncertain, + *, + excluded_entries: set[int] | None = None, +) -> None: + acc_matched_sell: set[int] = set(excluded_entries or ()) + acc_explicit_adds: list[dict] = [] + sell_candidates: list[tuple[dict, bool, str]] = [] + for tx, (is_add, is_corr), _is_ambig, rtext in acc_sells: + if is_add and not is_corr: + acc_explicit_adds.append(tx) + else: + sell_candidates.append((tx, is_corr, rtext)) + + # Sub-pass 1: exact signature matches in two order-independent batch phases (current-sig before historical alias). + after_exact: list[tuple[dict, bool, str]] = [] + exact_batch: list[tuple[int, dict, bool, str, list[int]]] = [] + for idx_s, (tx, is_corr, rtext) in enumerate(sell_candidates): + corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] + has_explicit_prior_date = ( + is_corr + and _f4_has_date_corr_evidence(tx, rtext) + and bool({d for d in _F4_ISO_DATE_RE.findall(rtext) if d != corr_td}) + ) + has_explicit_prior_shares = is_corr and bool(_f4_stated_prior_shares(rtext, tx.get("shares"))) + has_explicit_prior_price = is_corr and bool(_f4_stated_prior_prices(rtext, tx.get("price"))) + is_field_corr = ( + is_corr + and not _F4_RESTORE_SELL_RE.search(rtext) + and (_f4_has_amount_corr_evidence(tx, rtext) or _f4_has_date_corr_evidence(tx, rtext)) + ) + if has_explicit_prior_date or has_explicit_prior_shares or has_explicit_prior_price or is_field_corr: + after_exact.append((tx, is_corr, rtext)) + continue + pool, pool_unlinked = _f4_scoped_pool(ledger, tx, prior_len) + if pool_unlinked: + mark_uncertain(tx) + continue + exact_batch.append((idx_s, tx, is_corr, rtext, pool)) + + resolved_exact: set[int] = set() + uncertain_exact: set[int] = set() + + def _exact_phase(use_history: bool) -> None: + single_claims: dict[int, list[tuple[int, dict, bool, bool, bool]]] = {} + sym_restatements: dict[tuple[int, ...], list[tuple[int, dict]]] = {} + for idx_s, tx, is_corr, rtext, pool in exact_batch: + if idx_s in resolved_exact or idx_s in uncertain_exact: + continue + exact = _f4_exact_sig(tx) + orig_date = str(tx.get("original_filing_date") or "").strip() or None + is_restore_intent = is_corr and bool(_F4_RESTORE_SELL_RE.search(rtext)) + + def _matches_gift_sig(entry: dict, *, sig=exact, gfd=orig_date) -> bool: + if not entry["gift_sigs"]: + return False + if gfd: + on_date = [gsig for fd, gsig, _code in entry["gift_sigs"] if fd == gfd] + if on_date: + return sig in on_date + return any(gsig == sig for _fd, gsig, _code in entry["gift_sigs"]) + + if use_history: + cands = [ + i + for i in pool + if i not in acc_matched_sell + and (exact in ledger[i]["sigs"] or (is_restore_intent and _matches_gift_sig(ledger[i]))) + ] + else: + cands = [ + i + for i in pool + if i not in acc_matched_sell + and ( + _f4_exact_sig(ledger[i]["tx"]) == exact or (is_restore_intent and _matches_gift_sig(ledger[i])) + ) + ] + if not cands: + continue + if is_restore_intent: + reclass_cands = [i for i in cands if ledger[i]["reclassified"]] + if reclass_cands and _f4_has_multi_accession_ambiguity(ledger, tx, reclass_cands): + mark_uncertain(tx) + uncertain_exact.add(idx_s) + elif len(reclass_cands) == 1: + single_claims.setdefault(reclass_cands[0], []).append((idx_s, tx, True, False, True)) + elif len(reclass_cands) > 1: + mark_uncertain(tx) + uncertain_exact.add(idx_s) + else: + active_cands = [i for i in cands if not ledger[i]["reclassified"]] + if active_cands and _f4_has_multi_accession_ambiguity(ledger, tx, active_cands): + mark_uncertain(tx) + uncertain_exact.add(idx_s) + elif len(active_cands) == 1: + do_update = (not use_history) or is_corr + single_claims.setdefault(active_cands[0], []).append((idx_s, tx, False, False, do_update)) + elif len(active_cands) > 1 and not use_history: + sym_restatements.setdefault(tuple(sorted(active_cands)), []).append((idx_s, tx)) + elif len(active_cands) > 1: + mark_uncertain(tx) + uncertain_exact.add(idx_s) + elif not is_corr: + if _f4_has_multi_accession_ambiguity(ledger, tx, cands): + mark_uncertain(tx) + uncertain_exact.add(idx_s) + elif len(cands) == 1: + single_claims.setdefault(cands[0], []).append((idx_s, tx, False, True, False)) + else: + mark_uncertain(tx) + uncertain_exact.add(idx_s) + + claimed_targets: set[int] = set() + for target, claimants in single_claims.items(): + if len(claimants) == 1: + idx_s, tx, do_restore, mark_unc, do_update = claimants[0] + acc_matched_sell.add(target) + claimed_targets.add(target) + if mark_unc: + mark_uncertain(tx) + elif do_update: + _f4_update_entry(ledger, target, tx, restore_if_reclassified=do_restore) + else: + _f4_record_filing_provenance(ledger, target, tx) + resolved_exact.add(idx_s) + else: + for idx_s, tx, _do_restore, _mark_unc, _do_update in claimants: + mark_uncertain(tx) + uncertain_exact.add(idx_s) + + if sym_restatements: + sym_items: list[tuple[int, dict, tuple[int, ...], tuple[int, ...]]] = [] + grp_avail: dict[tuple[int, ...], tuple[int, ...]] = {} + for slots, claimants in sorted(sym_restatements.items(), key=lambda kv: (len(kv[0]), kv[0])): + avail = tuple(s for s in slots if s not in claimed_targets and s not in acc_matched_sell) + grp_avail[slots] = avail + for idx_s, tx in claimants: + sym_items.append((idx_s, tx, avail, slots)) + + slot_owner: dict[int, int] = {} + + def _augment(item_pos: int, visited: set[int], *, items=sym_items, owners=slot_owner) -> bool: + for slot in items[item_pos][2]: + if slot in visited: + continue + visited.add(slot) + prev = owners.get(slot) + if prev is None or _augment(prev, visited): + owners[slot] = item_pos + return True + return False + + for pos in range(len(sym_items)): + _augment(pos, set()) + + assigned_positions = set(slot_owner.values()) + grp_assigned: dict[tuple[int, ...], list[tuple[int, int, dict]]] = {} + for slot, pos in slot_owner.items(): + idx_s, tx, _avail, grp_key = sym_items[pos] + acc_matched_sell.add(slot) + resolved_exact.add(idx_s) + grp_assigned.setdefault(grp_key, []).append((slot, idx_s, tx)) + + for grp_key, assigned_rows in grp_assigned.items(): + taken_elsewhere = {slot for slot, p in slot_owner.items() if sym_items[p][3] != grp_key} + effective_avail = [s for s in grp_avail[grp_key] if s not in taken_elsewhere] + sample_tx = assigned_rows[0][2] + for s in effective_avail: + _f4_record_filing_provenance(ledger, s, sample_tx) + if len(assigned_rows) < len(effective_avail): + for _slot, _idx_s, tx in assigned_rows: + mark_uncertain(tx) + + for pos, (idx_s, tx, avail, _grp_key) in enumerate(sym_items): + if pos in assigned_positions: + continue + exact = _f4_exact_sig(tx) + other_unmatched = any( + i not in acc_matched_sell + and not ledger[i]["reclassified"] + and _f4_exact_sig(ledger[i]["tx"]) == exact + for i in range(prior_len) + ) + if other_unmatched or not avail: + mark_uncertain(tx) + uncertain_exact.add(idx_s) + + _exact_phase(use_history=False) + _exact_phase(use_history=True) + for idx_s, tx, is_corr, rtext, _pool in exact_batch: + if idx_s not in resolved_exact and idx_s not in uncertain_exact: + after_exact.append((tx, is_corr, rtext)) + + # Sub-pass 2: explicit corrections (price, share, restoration, and date corrections) in order-independent waves. + acc_new_sales: list[dict] = list(acc_explicit_adds) + corr_rows = [(idx, tx, rtext) for idx, (tx, is_corr, rtext) in enumerate(after_exact) if is_corr] + unannotated_rows = [(idx, tx, rtext) for idx, (tx, is_corr, rtext) in enumerate(after_exact) if not is_corr] + + def _corr_match_cands(tx: dict, rtext: str) -> tuple[list[int], bool, bool, bool]: + b = _f4_base_sig(tx) + if b[0] == ("",) or not bool(b[1]): + return [], False, False, False + is_restore_intent = bool(_F4_RESTORE_SELL_RE.search(rtext)) + corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] + has_date_corr = _f4_has_date_corr_evidence(tx, rtext) + prior_dates = {d for d in _F4_ISO_DATE_RE.findall(rtext) if d != corr_td} if has_date_corr else set() + prior_prices = _f4_stated_prior_prices(rtext, tx.get("price")) + prior_shares = _f4_stated_prior_shares(rtext, tx.get("shares")) + shares = tx.get("shares") + price = tx.get("price") + + orig_date = str(tx.get("original_filing_date") or "").strip() or None + + if not prior_dates: + pool, pool_unlinked = _f4_scoped_pool(ledger, tx, prior_len) + if not pool_unlinked: + same_base = [ + i + for i in pool + if i not in acc_matched_sell + and _f4_base_sig(ledger[i]["tx"]) == b + and (is_restore_intent or not ledger[i]["reclassified"]) + ] + if is_restore_intent: + reclass_only = [i for i in same_base if ledger[i]["reclassified"]] + if reclass_only: + same_base = reclass_only + if prior_shares or prior_prices: + unchanged_shares = shares if (not prior_shares and shares is not None) else _UNSET + cands = [ + i + for i in same_base + if _f4_entry_has_revision( + ledger[i], + shares_target=prior_shares or None, + price_target=prior_prices or None, + exact_shares=unchanged_shares, + include_gift_revisions=is_restore_intent, + gift_filing_date=orig_date, + ) + ] + if _f4_has_multi_accession_ambiguity(ledger, tx, cands): + return [], is_restore_intent, False, False + return cands, is_restore_intent, True, False + if shares is not None: + share_matched = [ + i + for i in same_base + if _f4_entry_has_revision( + ledger[i], + exact_shares=shares, + include_gift_revisions=is_restore_intent, + gift_filing_date=orig_date, + ) + ] + if share_matched: + same_base = share_matched + if _f4_has_multi_accession_ambiguity(ledger, tx, same_base): + return [], is_restore_intent, False, False + if same_base: + return same_base, is_restore_intent, False, False + + if has_date_corr: + dpool, dpool_unlinked = _f4_scoped_pool( + ledger, + tx, + prior_len, + ignore_tx_date=True, + prior_dates=prior_dates or None, + include_gift_revisions=is_restore_intent, + ) + if dpool_unlinked: + return [], is_restore_intent, False, True + osig = _f4_owner_sec_sig(tx) + date_cands = [ + i + for i in dpool + if i not in acc_matched_sell + and _f4_owner_sec_sig(ledger[i]["tx"]) == osig + and (is_restore_intent or not ledger[i]["reclassified"]) + ] + if prior_dates or prior_shares or prior_prices: + date_cands = [ + i + for i in date_cands + if _f4_entry_has_revision( + ledger[i], + dates=prior_dates or None, + shares_target=prior_shares or None, + price_target=prior_prices or None, + include_gift_revisions=is_restore_intent, + gift_filing_date=orig_date, + ) + ] + if len(date_cands) > 1 and shares is not None and price is not None and not (prior_shares or prior_prices): + by_sp = [ + i + for i in date_cands + if _f4_entry_has_revision( + ledger[i], + dates=prior_dates or None, + exact_shares=shares, + exact_price=price, + include_gift_revisions=is_restore_intent, + gift_filing_date=orig_date, + ) + ] + if by_sp: + date_cands = by_sp + if len(date_cands) > 1 and shares is not None and not prior_shares: + by_s = [ + i + for i in date_cands + if _f4_entry_has_revision( + ledger[i], + dates=prior_dates or None, + exact_shares=shares, + include_gift_revisions=is_restore_intent, + gift_filing_date=orig_date, + ) + ] + if by_s: + date_cands = by_s + if _f4_has_multi_accession_ambiguity(ledger, tx, date_cands): + return [], is_restore_intent, False, True + return date_cands, is_restore_intent, bool(prior_shares or prior_prices), True + return [], is_restore_intent, False, False + + resolved_corr: set[int] = set() + while True: + single_corr_claims: dict[int, list[tuple[int, dict, bool, bool, bool]]] = {} + for ridx, tx, rtext in corr_rows: + if ridx in resolved_corr: + continue + cands, is_restore_intent, identified_prior, is_date_match = _corr_match_cands(tx, rtext) + if len(cands) == 1: + single_corr_claims.setdefault(cands[0], []).append( + (ridx, tx, is_restore_intent, identified_prior, is_date_match) + ) + progressed = False + for target, claimants in single_corr_claims.items(): + if len(claimants) == 1: + ridx, tx, is_restore_intent, identified_prior, is_date_match = claimants[0] + was_reclassified = ledger[target]["reclassified"] + same_sp = tx.get("shares") is not None and _f4_entry_has_revision( + ledger[target], exact_shares=tx.get("shares"), exact_price=tx.get("price") + ) + acc_matched_sell.add(target) + _f4_update_entry(ledger, target, tx, restore_if_reclassified=is_restore_intent) + if not (identified_prior or (is_restore_intent and was_reclassified) or (is_date_match and same_sp)): + mark_uncertain(tx) + resolved_corr.add(ridx) + progressed = True + if not progressed: + break + + for ridx, tx, _rtext in corr_rows: + if ridx not in resolved_corr: + mark_uncertain(tx) + + # Sub-pass 3: heuristic unannotated share-matched restatements (after explicit corrections). + def _heuristic_share_cands(tx: dict) -> tuple[list[int], bool]: + b = _f4_base_sig(tx) + shares = tx.get("shares") + if shares is None or b[0] == ("",) or not bool(b[1]): + return [], False + pool, pool_unlinked = _f4_scoped_pool(ledger, tx, prior_len) + if pool_unlinked: + return [], True + cands = [ + i + for i in pool + if i not in acc_matched_sell and _f4_base_sig(ledger[i]["tx"]) == b and shares in ledger[i]["shares_set"] + ] + if cands and _f4_has_multi_accession_ambiguity(ledger, tx, cands): + return [], True + return cands, False + + resolved_heur: set[int] = set() + while True: + single_heur_claims: dict[int, list[tuple[int, dict]]] = {} + for ridx, tx, _rtext in unannotated_rows: + if ridx in resolved_heur: + continue + cands, is_ambig = _heuristic_share_cands(tx) + if not is_ambig and len(cands) == 1: + single_heur_claims.setdefault(cands[0], []).append((ridx, tx)) + progressed = False + for target, claimants in single_heur_claims.items(): + if len(claimants) == 1: + ridx, tx = claimants[0] + acc_matched_sell.add(target) + _f4_update_entry(ledger, target, tx) + mark_uncertain(tx) + resolved_heur.add(ridx) + progressed = True + if not progressed: + break + + # Matching all same-day sales cannot rule out a date correction or a repeated gift row. + for ridx, tx, _rtext in unannotated_rows: + if ridx not in resolved_heur: + mark_uncertain(tx) + + # Merge newly disclosed sales from this accession idempotently against existing 4/A-added ledger entries. + acc_new_counts: dict[tuple, list[dict]] = {} + for tx in acc_new_sales: + acc_new_counts.setdefault(_f4_exact_sig(tx), []).append(tx) + existing_counts: dict[tuple, int] = {} + for entry in ledger: + if not entry["from_orig"]: + for sig in entry["sigs"]: + existing_counts[sig] = existing_counts.get(sig, 0) + 1 + for e, rows in acc_new_counts.items(): + need = len(rows) - existing_counts.get(e, 0) + if need > 0: + ledger.extend(_f4_make_ledger_entry(tx, from_orig=False) for tx in rows[:need]) + + +def check_us_insider_trades(symbol: str, *, run=None) -> dict: + if not os.environ.get("SEC_USER_AGENT"): + return { + "sales_90d": None, + "flags": [], + "available": False, + "configured": False, + "truncated": False, + "warnings": [], + } + data = (run or _run_tool)("sec_edgar.py", ["insider_trades", symbol, "--days", "90", "--top", "10"], timeout=30) + result = {"sales_90d": 0, "flags": [], "available": False, "configured": True, "truncated": False, "warnings": []} + if not isinstance(data, dict) or "error" in data or not isinstance(data.get("transactions"), list): + return result + truncated = bool(data.get("truncated")) + sec_warnings = [str(w) for w in (data.get("warnings") or []) if w] + result["truncated"] = truncated + result["warnings"] = sec_warnings + + def _is_amendment_advisory(warning: str) -> bool: + low = warning.lower() + return "amendment" in low and "do not double-count" in low and "unavailable" not in low + + retrieval_warnings = [w for w in sec_warnings if not _is_amendment_advisory(w)] + result["available"] = not truncated and not retrieval_warnings + txs = [tx for tx in data["transactions"] if isinstance(tx, dict)] + + raw_cutoff = str(data.get("since_filing_date") or "").strip()[:10] + try: + tx_cutoff = date.fromisoformat(raw_cutoff).isoformat() if raw_cutoff else None + except ValueError: + tx_cutoff = None + if tx_cutoff is None: + tx_cutoff = (market_now("US").date() - timedelta(days=90)).isoformat() + + all_orig = [tx for tx in txs if str(tx.get("form") or "").upper() != "4/A"] + all_amend = [tx for tx in txs if str(tx.get("form") or "").upper() == "4/A"] + has_amendments = bool(all_amend) or any( + "amendment" in w.lower() or "double-count" in w.lower() for w in sec_warnings + ) + + ledger: list[dict] = [_f4_make_ledger_entry(tx, from_orig=True) for tx in all_orig if _f4_is_sell(tx)] + non_sell_histories: list[list[dict]] = [[tx] for tx in all_orig if not _f4_is_sell(tx)] + affected_owners: set[tuple] = set() + unaligned_global = has_amendments and not all_amend + + def _mark_uncertain(tx: dict) -> None: + nonlocal unaligned_global + ok = _f4_owner_key(tx) + if ok != ("",): + affected_owners.add(ok) + else: + unaligned_global = True + + sorted_acc_items, order_uncertain_txs = _f4_sort_amendment_accessions(all_amend) + for tx in order_uncertain_txs: + _mark_uncertain(tx) + + for _acc, acc_rows in sorted_acc_items: + intents, ambig_flags, row_texts, unresolved_conversions, independent_gift_additions = ( + _f4_resolve_accession_intents(acc_rows, ledger, non_sell_histories) + ) + acc_sells: list[tuple[dict, tuple[bool, bool], bool, str]] = [] + acc_non_sells: list[tuple[dict, tuple[bool, bool], bool, str, bool, bool]] = [] + for i, (tx, intent, is_ambig, rtext) in enumerate(zip(acc_rows, intents, ambig_flags, row_texts)): + if is_ambig: + _mark_uncertain(tx) + if _f4_is_sell(tx): + acc_sells.append((tx, intent, is_ambig, rtext)) + else: + acc_non_sells.append( + (tx, intent, is_ambig, rtext, i in unresolved_conversions, i in independent_gift_additions) + ) + + prior_len = len(ledger) + acc_matched_ns, pending_reclassifications = _f4_reconcile_non_sells( + ledger, non_sell_histories, acc_non_sells, prior_len, _mark_uncertain + ) + _f4_reconcile_sells(ledger, acc_sells, prior_len, _mark_uncertain, excluded_entries=acc_matched_ns) + for target, gtx in pending_reclassifications: + _f4_mark_reclassified(ledger, target, gtx) + + active_sales = [entry for entry in ledger if not entry["reclassified"]] + recent_active_sales: list[dict] = [] + has_undated_sale = False + for entry in active_sales: + td = _f4_tx_date_iso(entry["tx"]) + if td is None: + has_undated_sale = True + elif td >= tx_cutoff: + recent_active_sales.append(entry) + + dedup_sales = len(recent_active_sales) + unaffected_orig_sells = ( + 0 + if unaligned_global + else sum( + 1 + for entry in recent_active_sales + if entry["from_orig"] and _f4_owner_key(entry["tx"]) not in affected_owners + ) + ) + result["sales_90d"] = dedup_sales + result["amendments_present"] = has_amendments + result["count_uncertain"] = bool(has_undated_sale or affected_owners or unaligned_global) + if has_undated_sale: + sec_warnings.append( + "SEC Form 4 sales with missing or invalid transaction dates were excluded from the 90-day count" + ) + if affected_owners or unaligned_global: + sec_warnings.append( + "SEC Form 4/A amendments include unlinked or ambiguous revisions; insider sale count is uncertain" + ) + # Only trigger high-severity buy veto when reconciled, unaffected original Form 4 sells reach threshold. + if unaffected_orig_sells >= 6: + result["flags"].append( + { + "category": "insider", + "severity": "high", + "description": f"近90日 SEC Form 4 记录到 {dedup_sales} 笔内部人卖出", + "source": "data", + } + ) + elif dedup_sales >= 3: + note = ( + "(含 Form 4/A 修订申报,未因未对齐/可能重复记录触发一票否决)" + if has_amendments and dedup_sales >= 6 + else "" + ) + result["flags"].append( + { + "category": "insider", + "severity": "medium", + "description": f"近90日 SEC Form 4 记录到 {dedup_sales} 笔内部人卖出{note}", + "source": "data", + } + ) + return result + + def _cat_cn(cat: str) -> str: return {"insider": "内部人减持", "earnings": "业绩预警", "regulatory": "监管处罚", "industry": "行业政策"}.get( cat, cat @@ -292,6 +2472,14 @@ def compute_risk(flags: list) -> dict: def screen_risk(symbol: str, name: str = "", *, inputs=None, run=None) -> dict: + market = detect_market(symbol) + if market not in ("A", "HK", "US"): + return { + "symbol": symbol, + "name": name, + "market": market, + "error": f"screen_risk only supports A, HK, and US markets (got {market})", + } inputs = inputs or {} def supplied(key): @@ -307,11 +2495,21 @@ def supplied(key): check_technical(symbol, ta=supplied("technical")) if "technical" in inputs else check_technical(symbol) ) ) - lockups = pool.submit(check_lockup, symbol, **({"run": run} if run else {})) - searches = pool.submit(check_news_risks, symbol, name, **({"run": run} if run else {})) - val, tech, lockup, news = (future.result() for future in (valuation, technical, lockups, searches)) + market_specific = None + if market == "A": + market_specific = pool.submit(check_lockup, symbol, **({"run": run} if run else {})) + elif market == "HK": + market_specific = pool.submit(check_hk_disclosures, symbol, **({"run": run} if run else {})) + elif market == "US": + market_specific = pool.submit(check_us_insider_trades, symbol, **({"run": run} if run else {})) + searches = pool.submit(check_news_risks, symbol, name, market=market, **({"run": run} if run else {})) + val = valuation.result() + tech = technical.result() + extra = market_specific.result() if market_specific is not None else None + news = searches.result() all_flags = [] checks = {} + warnings = [] checks["valuation"] = {k: val[k] for k in ("pe", "pb", "status", "available")} all_flags.extend(val["flags"]) @@ -324,23 +2522,55 @@ def supplied(key): } all_flags.extend(tech["flags"]) - checks["lockup"] = {"upcoming_30d": lockup["upcoming_30d"], "available": lockup["available"]} - all_flags.extend(lockup["flags"]) + if market == "A": + checks["lockup"] = {"upcoming_30d": extra["upcoming_30d"], "available": extra["available"]} + all_flags.extend(extra["flags"]) + else: + checks["lockup"] = {"applicable": False, "upcoming_30d": [], "available": True} + if market == "HK": + checks["disclosures"] = { + "matches": extra["matches"], + "available": extra["available"], + "truncated": extra.get("truncated", False), + } + all_flags.extend(extra["flags"]) + warnings.extend(extra.get("warnings") or []) + elif market == "US": + checks["insider_trades"] = { + "sales_90d": extra["sales_90d"], + "available": extra["available"], + "configured": extra["configured"], + "truncated": extra.get("truncated", False), + "count_uncertain": extra.get("count_uncertain", False), + } + all_flags.extend(extra["flags"]) + if not extra["configured"]: + warnings.append("SEC_USER_AGENT not set; SEC Form 4 insider trade risk check skipped") + else: + if extra.get("truncated"): + warnings.append("SEC Form 4 filings were truncated at top 10; insider sales coverage is incomplete") + warnings.extend(extra.get("warnings") or []) checks["news_risks"] = {k: v for k, v in news.items() if k != "flags"} all_flags.extend(news["flags"]) risk = compute_risk(all_flags) - missing = [key for key, value in checks.items() if not value.get("available")] + missing = [ + key + for key, value in checks.items() + if not value.get("available") and not (key == "insider_trades" and value.get("configured") is False) + ] complete = not missing + warnings.extend(f"{key} risk data unavailable or incomplete" for key in missing) return { "symbol": symbol, "name": name, + "market": market, "risk_level": "unknown" if missing and risk["risk_level"] == "low" else risk["risk_level"], "risk_score": risk["risk_score"] if all_flags or complete else None, "veto_buy": risk["veto_buy"] if risk["veto_buy"] or complete else None, "data_complete": complete, - "warnings": [f"{key} risk data unavailable or incomplete" for key in missing], + "warnings": warnings, "flags": all_flags, "checks": checks, } @@ -364,6 +2594,8 @@ def main(): if args.command == "screen": result = screen_risk(args.symbol, args.name) print(json.dumps(result, ensure_ascii=False, default=str)) + if isinstance(result, dict) and "error" in result: + sys.exit(1) elif args.command == "lockup": print(json.dumps(_fetch_lockup(args.symbol), ensure_ascii=False, default=str)) diff --git a/tools/sec_edgar.py b/tools/sec_edgar.py index ee0fa93..e6c29a5 100644 --- a/tools/sec_edgar.py +++ b/tools/sec_edgar.py @@ -8,7 +8,7 @@ import re import sys import time -from datetime import date, timedelta +from datetime import date, datetime, timedelta, timezone from pathlib import Path from xml.etree import ElementTree as ET @@ -70,6 +70,23 @@ def filing_rows(data): ] +def _acceptance_sort_key(row): + raw = str(row.get("acceptanceDateTime") or "").strip() + norm = "" + if raw: + try: + if re.fullmatch(r"\d{14}", raw): + dt = datetime.strptime(raw, "%Y%m%d%H%M%S").replace(tzinfo=timezone.utc) + else: + iso = raw[:-1] + "+00:00" if raw.endswith(("Z", "z")) else raw + dt = datetime.fromisoformat(iso) + dt = dt.astimezone(timezone.utc) if dt.tzinfo is not None else dt.replace(tzinfo=timezone.utc) + norm = dt.isoformat(timespec="microseconds") + except ValueError: + norm = "" + return (row.get("filingDate", ""), norm, row.get("accessionNumber", "")) + + def submissions(cik, forms, cutoff=None): data = cached(f"sec-submissions:{cik}", DAY, lambda: sec_get(f"https://data.sec.gov/submissions/CIK{cik}.json")) if not isinstance(data.get("filings", {}).get("recent"), dict): @@ -97,7 +114,7 @@ def submissions(cik, forms, cutoff=None): rows.extend(filing_rows(extra)) loaded += 1 result = [r for r in rows if r.get("form") in forms and (not cutoff or r.get("filingDate", "") >= cutoff)] - result.sort(key=lambda r: (r.get("filingDate", ""), r.get("accessionNumber", "")), reverse=True) + result.sort(key=_acceptance_sort_key, reverse=True) earliest_unsearched = cutoff or max((r.get("reportDate") or "" for r in result), default="") incomplete = any(f.get("filingTo", "") >= earliest_unsearched for f in relevant[loaded:]) return data.get("name"), result, incomplete @@ -252,6 +269,8 @@ def form4(cik, filing): for r in root.findall("reportingOwner") ] footnotes = {r.get("id"): "".join(r.itertext()) for r in root.findall("footnotes/footnote")} + remarks = (root.findtext("remarks") or "").strip() or None + original_filing_date = (root.findtext("dateOfOriginalSubmission") or "").strip() or None rows = [] for table, tag, derivative in [ ("nonDerivativeTable", "nonDerivativeTransaction", False), @@ -274,7 +293,10 @@ def form4(cik, filing): "ownership": row.findtext("ownershipNature/directOrIndirectOwnership/value"), "footnotes": footnotes, "footnote_refs": footnote_refs(row), + "remarks": remarks, + "original_filing_date": original_filing_date, "filing_date": filing["filingDate"], + "acceptance_datetime": (filing.get("acceptanceDateTime") or "").strip() or None, "form": filing["form"], "accession": filing["accessionNumber"], "filing_url": f"{base}/{document}", @@ -569,7 +591,7 @@ def insider_trades(args): for filing in filings[: args.top]: try: rows = cached( - f"sec-form4:{cik}:{filing['accessionNumber']}", WEEK, lambda filing=filing: form4(cik, filing) + f"sec-form4-v4:{cik}:{filing['accessionNumber']}", WEEK, lambda filing=filing: form4(cik, filing) ) result["transactions"].extend(rows) result["filings_scanned"] += 1 diff --git a/tools/signal_tracker.py b/tools/signal_tracker.py index 7a7962f..4133bef 100644 --- a/tools/signal_tracker.py +++ b/tools/signal_tracker.py @@ -261,46 +261,172 @@ def _valid_bar(bar, require_open=True) -> bool: ) -def _price_factor(rec, bars): +def _verify_no_corporate_action(rec: dict, bars: list, anchor_idx: int, has_price_date: bool, remaining: float) -> bool: + """Verify via complete dividend+split history and exact anchor-bar price match that no + ex-dividend or split invalidated the 1:1 price correspondence between entry_price and adjusted bars.""" + anchor = bars[anchor_idx] + entry = rec.get("entry_price") + low = anchor.get("low") + high = anchor.get("high") + if not ( + isinstance(entry, (int, float)) + and isinstance(low, (int, float)) + and isinstance(high, (int, float)) + and low - 1e-6 <= entry <= high + 1e-6 + ): + return False + + anchor_date = anchor["date"] + last_date = max(bar["date"] for bar in bars) + try: + anchor_dt = datetime.strptime(anchor_date, "%Y-%m-%d").date() + last_dt = datetime.strptime(last_date, "%Y-%m-%d").date() + ref_today = max(datetime.now().date(), last_dt) + except ValueError: + return False + + years_needed = max(2, math.ceil((ref_today - anchor_dt).days / 365.25) + 1) + if years_needed > 20: + return False + + # Omit --market (only supported for ranking A/HK) and pass --no-cache so cached histories cannot miss a new ex-date. + div_data = run_tool( + "value_data.py", + ["dividends", "--symbol", rec["symbol"], "--mode", "history", "--years", str(years_needed), "--no-cache"], + timeout=min(30, max(remaining, 1)), + ) + if not isinstance(div_data, dict) or "error" in div_data or not isinstance(div_data.get("history"), list): + return False + if not div_data.get("source"): + return False + # Require fresh, non-cached corporate-action history and complete verified action coverage. + if div_data.get("cache_bypassed") is not True: + return False + if ( + not div_data["history"] + or div_data.get("splits_checked") is not True + or div_data.get("capital_gains_checked") is not True + or div_data.get("corporate_actions_complete") is not True + ): + return False + warnings = [str(w).lower() for w in (div_data.get("warnings") or [])] + blocked_markers = ( + "missing/invalid", + "unavailable", + "no dividend history", + "absence is not interpreted as zero", + ) + if any(any(marker in w for marker in blocked_markers) for w in warnings): + return False + + # Verify fresh history coverage spans anchor_date..last_date (never trust request-time `as_of`). + years_returned = div_data.get("history_years_requested") + current_through_raw = div_data.get("history_current_through") + covered_from_raw = div_data.get("history_covered_from") + if ( + isinstance(years_returned, bool) + or not isinstance(years_returned, (int, float)) + or years_returned < years_needed + ): + return False + if isinstance(current_through_raw, str) and len(current_through_raw) >= 10: + try: + current_through_dt = datetime.strptime(current_through_raw[:10], "%Y-%m-%d").date() + except ValueError: + return False + if current_through_dt < last_dt: + return False + # Verify anchor_date is strictly after the producer's cutoff (current_through - 365.25 * years_returned). + if (current_through_dt - anchor_dt).days >= int(365.25 * years_returned): + return False + else: + return False + if covered_from_raw is not None: + if not isinstance(covered_from_raw, str) or len(covered_from_raw) < 10: + return False + try: + covered_from_dt = datetime.strptime(covered_from_raw[:10], "%Y-%m-%d").date() + except ValueError: + return False + if covered_from_dt > anchor_dt: + return False + + # Require at least one past/paid event (not only future calendar rows) so history confirms actual coverage. + events = list(div_data.get("history") or []) + list(div_data.get("calendar") or []) + has_past_event = False + for ev in events: + if not isinstance(ev, dict): + return False + status = str(ev.get("status") or "") + ex_date = ev.get("ex_date") + if status in ("实施分配", "paid") and not ex_date: + return False + if not isinstance(ex_date, str) or len(ex_date) < 10: + continue + ex_day = ex_date[:10] + if ex_day <= last_date: + has_past_event = True + if anchor_date < ex_day <= last_date: + return False + if not has_price_date and ex_day == anchor_date: + return False + + for action_key in ("splits", "capital_gains"): + action_rows = div_data.get(action_key) + if action_rows is not None: + if not isinstance(action_rows, list): + return False + for act in action_rows: + if not isinstance(act, dict): + return False + ex_date = act.get("ex_date") + if not isinstance(ex_date, str) or len(ex_date) < 10: + return False + ex_day = ex_date[:10] + if anchor_date < ex_day <= last_date: + return False + if not has_price_date and ex_day == anchor_date: + return False + + return has_past_event + + +def _price_factor(rec, bars, *, remaining: float | None = None): market = rec.get("market") or detect_market(rec["symbol"]) price_date = _price_date(rec.get("price_date") or rec.get("price_as_of"), market) if price_date and price_date > rec["record_date"]: - return None + return None, None if all(bar.get("adjusted") == "none" for bar in bars): - return 1.0 + return 1.0, "unadjusted" anchor_date = price_date or rec["record_date"] has_price_date = price_date is not None anchor_idx = next((i for i, bar in enumerate(bars) if bar["date"] == anchor_date), None) if anchor_idx is None: anchor_idx = next((i for i in range(len(bars) - 1, -1, -1) if bars[i]["date"] <= anchor_date), None) if anchor_idx is None: - return None + return None, None next_bar = next((bar for bar in bars if bar["date"] > anchor_date), None) if ( not has_price_date and next_bar is not None and next_bar.get("adjustment_factor") != bars[anchor_idx].get("adjustment_factor") ): - return None + return None, None elif ( anchor_idx and not has_price_date and bars[anchor_idx - 1].get("adjustment_factor") != bars[anchor_idx].get("adjustment_factor") ): - return None + return None, None anchor = bars[anchor_idx] factor = anchor.get("adjustment_factor") basis = anchor.get("adjusted") - if ( - basis in ("qfq", "total_return") - and all(bar.get("adjusted") == basis for bar in bars) - and not isinstance(factor, bool) - and isinstance(factor, (int, float)) - and math.isfinite(factor) - and factor > 0 - ): - return factor - return None + if basis in ("qfq", "total_return") and all(bar.get("adjusted") == basis for bar in bars): + if not isinstance(factor, bool) and isinstance(factor, (int, float)) and math.isfinite(factor) and factor > 0: + return factor, "adjustment_factor" + if remaining is not None and _verify_no_corporate_action(rec, bars, anchor_idx, has_price_date, remaining): + return 1.0, "no_corporate_action_verified" + return None, None def cmd_evaluate(args): @@ -339,40 +465,45 @@ def cmd_evaluate(args): or min(str(b.get("date", ""))[:10] for b in bars) > rec["record_date"] ): entry.update({"outcome": "skipped_no_data", "return_pct": None, "exit_date": None}) - elif (factor := _price_factor(rec, bars)) is None: - entry.update( - outcome="skipped_price_basis", - return_pct=None, - exit_date=None, - warning="Adjusted or unknown prices lack a verified conversion to the original signal prices", - ) else: - decimal_factor = Decimal(str(factor)) - priced = dict(rec) - for key in ("entry_price", "target_price", "stop_price"): - if priced.get(key) is not None: - priced[key] = float(Decimal(str(priced[key])) * decimal_factor) - ev = _evaluate_bars(priced, bars) - if ev is None: - entry.update({"outcome": "open", "return_pct": None, "exit_date": None}) - else: - outcome, exit_price, exit_date = ev - exit_price = float(Decimal(str(exit_price)) / decimal_factor) - ret = round((exit_price - rec["entry_price"]) / rec["entry_price"] * 100, 2) - if rec.get("direction") == "sell": - ret = -ret - rec.update( - { - "status": "closed", - "outcome": outcome, - "exit_price": exit_price, - "exit_date": exit_date, - "return_pct": ret, - "evaluation_price_basis": {"adjusted": bars[0].get("adjusted"), "factor": factor}, - } + factor, verification = _price_factor(rec, bars, remaining=max(deadline - time.monotonic(), 0)) + if factor is None: + entry.update( + outcome="skipped_price_basis", + return_pct=None, + exit_date=None, + warning="Adjusted or unknown prices lack a verified conversion to the original signal prices", ) - changed = True - entry.update({"outcome": outcome, "return_pct": ret, "exit_date": exit_date}) + else: + decimal_factor = Decimal(str(factor)) + priced = dict(rec) + for key in ("entry_price", "target_price", "stop_price"): + if priced.get(key) is not None: + priced[key] = float(Decimal(str(priced[key])) * decimal_factor) + ev = _evaluate_bars(priced, bars) + if ev is None: + entry.update({"outcome": "open", "return_pct": None, "exit_date": None}) + else: + outcome, exit_price, exit_date = ev + exit_price = float(Decimal(str(exit_price)) / decimal_factor) + ret = round((exit_price - rec["entry_price"]) / rec["entry_price"] * 100, 2) + if rec.get("direction") == "sell": + ret = -ret + basis_info = {"adjusted": bars[0].get("adjusted"), "factor": factor} + if verification == "no_corporate_action_verified": + basis_info["verification"] = verification + rec.update( + { + "status": "closed", + "outcome": outcome, + "exit_price": exit_price, + "exit_date": exit_date, + "return_pct": ret, + "evaluation_price_basis": basis_info, + } + ) + changed = True + entry.update({"outcome": outcome, "return_pct": ret, "exit_date": exit_date}) results.append(entry) if results: try: diff --git a/tools/stock_data.py b/tools/stock_data.py index 14bf418..01e571b 100644 --- a/tools/stock_data.py +++ b/tools/stock_data.py @@ -1361,115 +1361,7 @@ def _quote_stale_marker(market: str): } -_YOUZHIYOUXING_TIAA = { - "TIAA001001": "长钱账户", - "TIAA001002": "海外长钱", - "TIAA001004": "稳钱账户", -} - - -def _quote_tiaa(symbol: str, *, include_disclosures: bool = True) -> dict: - import requests - - disclosure_name = _YOUZHIYOUXING_TIAA.get(symbol) - result = { - "symbol": symbol, - "name": disclosure_name, - "asset_type": "investment_advisory_portfolio", - "type_description": "雪球投顾组合,无统一单位净值", - "manager": None, - "advisor_code": f"A{symbol[4:7]}", - "advisor_org": None, - "advisor_mapping_basis": "tiaa_prefix_best_effort", - "advisor_source_url": None, - "advisor_retrieved_at": None, - "nav": None, - "example_account_performance": None, - "quote_type": None, - "exchange": None, - "source": None, - "source_url": f"https://xueqiu.com/S/{symbol}", - "data_as_of": None, - "fetched_at": datetime.now(timezone.utc).isoformat(), - "official_disclosures": [], - "public_search_results": [], - "disclosure_provider": "youzhiyouxing" if disclosure_name else None, - "disclosure_status": "unavailable" if disclosure_name else "unsupported_provider", - "disclosures_partial": True, - "disclosures_as_of": None, - "note": ( - "投顾组合无统一净值;主理人及完整业绩/持仓需在对应投顾平台登录后查询;" - "官方公开披露仅为部分历史信息,持有人收益随买入时点和调仓跟进不同" - ), - } - try: - from tiaa_disclosures import advisor_metadata - - result.update(advisor_metadata(symbol)) - except Exception: - result.setdefault("warnings", []).append("advisor organization metadata unavailable") - if not include_disclosures and disclosure_name: - return result - - try: - with requests.Session() as session: - session.get( - "https://xueqiu.com/", - headers={"User-Agent": "Mozilla/5.0"}, - timeout=10, - allow_redirects=True, - ).raise_for_status() - response = session.get( - "https://stock.xueqiu.com/v5/stock/quote.json", - params={"symbol": symbol, "extend": "detail"}, - headers={"User-Agent": "Mozilla/5.0", "Referer": "https://xueqiu.com/"}, - timeout=10, - ) - response.raise_for_status() - payload = response.json() - if payload.get("error_code") not in (None, 0): - raise ValueError("xueqiu portfolio metadata unavailable") - quote = (payload.get("data") or {}).get("quote") or {} - if quote.get("symbol") != symbol: - raise ValueError("xueqiu returned different portfolio metadata") - result.update( - name=quote.get("name") or disclosure_name, - quote_type=quote.get("type"), - exchange=quote.get("exchange"), - source="xueqiu", - data_as_of=_unix_quote_time(quote.get("timestamp")), - ) - except Exception: - result.setdefault("warnings", []).append( - "xueqiu portfolio metadata unavailable; type guidance remains available" - ) - if not include_disclosures: - return result - - if disclosure_name and result["name"] in (None, disclosure_name): - try: - from tiaa_disclosures import public_disclosures - - disclosure = public_disclosures(symbol, disclosure_name) - result["official_disclosures"] = disclosure["items"] - result["disclosures_as_of"] = disclosure["as_of"] - if disclosure["items"]: - result["disclosure_status"] = "partial_public" - except Exception: - result.setdefault("warnings", []).append( - "official public disclosures unavailable; type guidance remains available" - ) - elif disclosure_name and result["name"]: - result["disclosure_status"] = "unsupported_provider" - result.setdefault("warnings", []).append("portfolio name does not match the registered disclosure source") - else: - from tiaa_disclosures import search_public - - result["public_search_results"] = search_public(symbol, result["name"]) - if result["public_search_results"]: - result["disclosure_provider"] = "web_search" - result["disclosure_status"] = "search_partial" - return result +# _YOUZHIYOUXING_TIAA and _quote_tiaa live in tools/_fund_data.py and are re-exported below. def cmd_quote(args): @@ -1584,92 +1476,15 @@ def cmd_klines(args): # --------------- open-end fund quote --------------- -def _fund_js_value(text: str, name: str): - match = re.search(rf"\b{re.escape(name)}\s*=\s*", text) - if not match: - raise ValueError(f"eastmoney fund data missing {name}") - try: - return json.JSONDecoder().raw_decode(text[match.end() :])[0] - except json.JSONDecodeError as exc: - raise ValueError(f"eastmoney fund data has invalid {name}") from exc - - -def _fund_nav_date(stamp) -> str: - return datetime.fromtimestamp(stamp / 1000, timezone.utc).astimezone(ZoneInfo("Asia/Shanghai")).date().isoformat() - - -def fund_pingzhong_js(symbol: str) -> str: - """Eastmoney's per-fund JS bundle (NAV, scale, holdings series).""" - import requests - - response = requests.get(f"https://fund.eastmoney.com/pingzhongdata/{symbol}.js", timeout=15) - response.raise_for_status() - return response.text +from _fund_data import ( # noqa: E402 + _quote_tiaa, + fund_pingzhong_js, +) +from _fund_data import cmd_fund_quote as _cmd_fund_quote_impl # noqa: E402 def cmd_fund_quote(args, *, trend_count: int = 0): - symbol = args.symbol - if not re.fullmatch(r"\d{6}", symbol): - return {"error": "open-end fund symbol must be exactly 6 digits"} - try: - text = fund_pingzhong_js(symbol) - if _fund_js_value(text, "fS_code") != symbol: - raise ValueError(f"eastmoney returned a different fund for {symbol}") - name = _fund_js_value(text, "fS_name") - nav_rows = _fund_js_value(text, "Data_netWorthTrend") - accumulated_rows = [] if trend_count else _fund_js_value(text, "Data_ACWorthTrend") - points = [] - for row in reversed(nav_rows): - if not isinstance(row, dict): - continue - nav = _parse_float(row.get("y")) - if nav is None or not math.isfinite(nav) or nav <= 0: - continue - try: - day = _fund_nav_date(row.get("x")) - except (TypeError, ValueError, OverflowError, OSError): - continue - points.append((row, day, nav)) - if len(points) >= max(1, trend_count): - break - if not points: - raise ValueError(f"eastmoney returned no NAV for {symbol}") - latest, nav_date, nav = points[0] - accumulated_by_date = {_fund_nav_date(row[0]): row[1] for row in accumulated_rows} - today = _cn_now().date().isoformat() - result = _clean_row( - { - "symbol": symbol, - "name": name, - "asset_type": "open_end_fund", - "nav": nav, - "accumulated_nav": accumulated_by_date.get(nav_date), - "change_pct": latest.get("equityReturn"), - "nav_date": nav_date, - "data_as_of": nav_date, - "as_of": nav_date, - "as_of_basis": "provider", - "stale": nav_date < today, - "source": "eastmoney", - "source_url": f"https://fund.eastmoney.com/{symbol}.html", - "fetched_at": datetime.now(timezone.utc).isoformat(), - "note": ( - "nav is published end-of-day NAV, not a real-time price; QDII disclosure may lag " - "1-2 trading days; no intraday estimated NAV is provided" - ), - # Eastmoney retired its per-fund intraday estimate (fundgz); its remaining estimate - # page lists every fund at once, so the estimate keys stay but are always unavailable. - "estimated_nav": None, - "estimated_change_pct": None, - "estimated_at": None, - "estimate_status": "unavailable", - } - ) - if trend_count: - result["trend"] = [{"date": day, "close": nav} for _, day, nav in reversed(points)] - return result - except Exception as e: - return {"error": error_message(e)} + return _cmd_fund_quote_impl(args, trend_count=trend_count, fetch_js=fund_pingzhong_js) # --------------- capital_flow --------------- @@ -2809,6 +2624,100 @@ def _sector_rankings_sina(indicator: str) -> list: } +HK_SECTOR_ETFS = { + "3033.HK": "Hang Seng TECH", + "2800.HK": "Broad Hong Kong (HSI)", + "2828.HK": "China Enterprises (HSCEI)", + "3110.HK": "High Dividend", + "3069.HK": "Biotech & Healthcare", + "3191.HK": "Semiconductors", + "2807.HK": "Robotics & AI", + "2809.HK": "Clean Energy", +} + + +def _sector_rankings_hk_tradingview() -> list: + """Aggregate HK market sectors from top HKEX equities via TradingView scanner.""" + columns = ["name", "description", "sector", "change", "market_cap_basic", "Value.Traded"] + body = { + "columns": columns, + "filter": _TV_HK_STOCK_FILTERS, + "sort": {"sortBy": "market_cap_basic", "sortOrder": "desc"}, + "range": [0, 500], + } + payload = _tradingview_scan("hongkong", body) + data = payload.get("data") or [] + buckets: dict[str, dict] = {} + for item in data: + vals = dict(zip(columns, item.get("d") or [])) + sector = vals.get("sector") + change = _parse_float(vals.get("change")) + cap = _parse_float(vals.get("market_cap_basic")) + turnover = _parse_float(vals.get("Value.Traded")) or 0.0 + if not sector or change is None or not math.isfinite(change): + continue + weight = cap if (cap is not None and math.isfinite(cap) and cap > 0) else 1.0 + b = buckets.setdefault( + str(sector), + {"weighted_sum": 0.0, "weight_total": 0.0, "count": 0, "up": 0, "down": 0, "turnover": 0.0, "leader": None}, + ) + b["weighted_sum"] += change * weight + b["weight_total"] += weight + b["count"] += 1 + if change > 0: + b["up"] += 1 + elif change < 0: + b["down"] += 1 + b["turnover"] += turnover + stock_label = vals.get("description") or _clist_symbol("HK", vals.get("name")) + if b["leader"] is None or change > b["leader"][1]: + b["leader"] = (stock_label, change) + rows = [] + for name, b in buckets.items(): + if b["weight_total"] <= 0: + continue + row = { + "name": name, + "change_pct": round(b["weighted_sum"] / b["weight_total"], 4), + "stock_count": b["count"], + "up_count": b["up"], + "down_count": b["down"], + "turnover": round(b["turnover"], 2), + } + if b["leader"]: + row["leading_stock"] = b["leader"][0] + row["leading_change_pct"] = round(b["leader"][1], 4) + rows.append(row) + if not rows: + raise ValueError("TradingView HK sector aggregation returned empty data") + return rows + + +def _sector_rankings_hk_etf() -> list: + """Fallback HK sector/theme proxies from HK-listed ETFs' last two daily closes.""" + import yfinance as yf + + closes = yf.download(list(HK_SECTOR_ETFS), period="10d", auto_adjust=False, progress=False)["Close"] + rows = [] + for symbol, name in HK_SECTOR_ETFS.items(): + series = closes[symbol].dropna() if symbol in closes else [] + if len(series) < 2: + continue + rows.append( + { + "name": name, + "etf": symbol, + "close": round(float(series.iloc[-1]), 4), + "change_pct": round(float(series.iloc[-1] / series.iloc[-2] - 1) * 100, 4), + "as_of": str(series.index[-1])[:10], + "proxy": "HK Sector ETF", + } + ) + if not rows: + raise ValueError("HK sector ETF quotes unavailable") + return rows + + def _sector_rankings_us() -> list: """S&P 500 sector proxies from the SPDR Select Sector ETFs' last two daily closes.""" import yfinance as yf @@ -2837,10 +2746,17 @@ def cmd_sector_rankings(args): board_type = getattr(args, "board_type", "industry") direction = getattr(args, "direction", "top") market = getattr(args, "market", "A") - if market == "US" and board_type != "industry": - return {"error": "US sector rankings support board_type=industry only"} + if market in ("US", "HK") and board_type != "industry": + return {"error": f"{market} sector rankings support board_type=industry only"} if market == "US": sources = [_sourced("yfinance", _sector_rankings_us)] + label = "sector_rankings_us:industry" + elif market == "HK": + sources = [ + _sourced("tradingview", _sector_rankings_hk_tradingview), + _sourced("yfinance", _sector_rankings_hk_etf), + ] + label = "sector_rankings_hk:industry" else: sources = [_sourced("eastmoney", lambda: _sector_rankings_em(board_type))] if board_type == "industry": @@ -2848,10 +2764,9 @@ def cmd_sector_rankings(args): sources += [_sourced("ths", _sector_rankings_ths), _sourced("efinance", _sector_rankings_efinance)] else: sources.append(_sourced("sina", lambda: _sector_rankings_sina("概念"))) + label = f"sector_rankings:{board_type}" try: - rows = _failover( - sources, label="sector_rankings_us:industry" if market == "US" else f"sector_rankings:{board_type}" - ) + rows = _failover(sources, label=label) if not rows: raise ValueError(f"no {board_type} board rankings data") except Exception as e: @@ -2860,6 +2775,9 @@ def cmd_sector_rankings(args): r["board_type"] = board_type if market == "US": r.update(market="US", proxy="SPDR Select Sector ETF") + elif market == "HK": + r.setdefault("market", "HK") + r.setdefault("proxy", "TradingView HK Sector Aggregate") def _pct(row, default): v = row.get("change_pct") @@ -4151,7 +4069,7 @@ def main(): p_sec.add_argument("--top", type=int, default=10) p_sec.add_argument("--direction", default="top", choices=["top", "bottom", "both"]) p_sec.add_argument("--board-type", default="industry", choices=["industry", "concept"]) - p_sec.add_argument("--market", default="A", choices=["A", "US"]) + p_sec.add_argument("--market", default="A", choices=["A", "HK", "US"]) p_cons = sub.add_parser("sector_constituents") p_cons.add_argument("sector") diff --git a/tools/tool_schemas.json b/tools/tool_schemas.json index 31ea10b..12b7569 100644 --- a/tools/tool_schemas.json +++ b/tools/tool_schemas.json @@ -402,6 +402,30 @@ "required": [] } }, + { + "name": "get_macro_anchors", + "description": "查询跨市场宏观、利率、汇率与风险偏好基准(免Key,缓存1小时):包含中美10年期国债收益率与美债2Y(及中美利差/美债10Y-2Y利差bp)、美元指数DXY、USD/CNH、USD/HKD、推导HKD/CNY,以及VIX、COMEX黄金与WTI原油。适用于DCF无风险利率锚、跨币种组合汇率参考与大盘复盘宏观背景", + "parameters": { + "type": "object", + "properties": { + "group": { + "type": "string", + "enum": [ + "all", + "rates", + "fx", + "risk" + ], + "description": "基准分组:all=全部(默认),rates=中美无风险利率,fx=汇率与美元指数,risk=VIX/黄金/原油" + }, + "days": { + "type": "integer", + "description": "历史统计窗口天数(2..365 整数,默认 30)" + } + }, + "required": [] + } + }, { "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不可用。", @@ -731,7 +755,7 @@ }, { "name": "get_sector_rankings", - "description": "获取板块涨跌幅排行。market=A(默认)为A股板块(含领涨股、涨跌家数等),board_type=industry(默认)为行业、concept为概念;market=US用SPDR行业ETF最近两个收盘作美股11个行业代理(仅industry,proxy字段标注,非交易所官方行业数据)。支持查看涨幅榜/跌幅榜/双向", + "description": "获取板块涨跌幅排行。market=A(默认)为A股板块(含领涨股、涨跌家数等),board_type=industry(默认)为行业、concept为概念;market=HK按TradingView港股前500市值股聚合行业涨跌幅(失败回退港股行业ETF代理,仅industry);market=US用SPDR行业ETF最近两个收盘作美股11个行业代理(仅industry,proxy字段标注,非交易所官方行业数据)。支持查看涨幅榜/跌幅榜/双向", "parameters": { "type": "object", "properties": { @@ -760,9 +784,10 @@ "type": "string", "enum": [ "A", + "HK", "US" ], - "description": "市场:A=A股(默认),US=美股行业ETF代理" + "description": "市场:A=A股(默认),HK=港股行业聚合/ETF代理,US=美股行业ETF代理" } } } @@ -990,7 +1015,7 @@ }, { "name": "run_backtest", - "description": "策略回测(AlphaEvo)。读取YAML策略定义,在历史数据上模拟交易,输出收益率/回撤/胜率等指标。只想知道单个技术信号的历史胜率用更轻量的 evaluate_signal。period为实际数据期间,requested_period保留请求期间,warnings提示覆盖差异;年化按实际期间计算。默认前日收盘信号、次日开盘成交;YAML simulation.execution=same_close可复现旧假设。execution返回模型、阻止成交次数和未模拟约束;零成交量及带历史限价的一字板不成交。支持 monthly_momentum:月初首根有效日K收盘观察过去period根对数收益,次日开盘;长周期需预热。", + "description": "策略回测(AlphaEvo)。读取YAML策略定义,在历史数据上模拟交易,输出收益率/回撤/胜率等指标。支持单标的择时策略,也支持逗号分隔多标的组合回测、多仓位(max_positions)、定期再平衡(portfolio.rebalance)与定期定投(dca.frequency/amount,输出时间加权收益 time_weighted_return 与期末持仓)。只想知道单个技术信号的历史胜率用更轻量的 evaluate_signal。period为实际数据期间,requested_period保留请求期间,warnings提示覆盖差异;年化按实际期间计算。默认前日收盘信号、次日开盘成交;YAML simulation.execution=same_close可复现旧假设。", "parameters": { "type": "object", "properties": { @@ -1000,7 +1025,7 @@ }, "symbol": { "type": "string", - "description": "股票代码(A股如600519,美股如AAPL,港股如00700.HK)" + "description": "股票代码,支持单个或逗号分隔多标的同市场组合(如 600519 或 510300,510500,518880)" }, "start": { "type": "string", @@ -1317,13 +1342,13 @@ }, { "name": "screen_risk", - "description": "A股风险专项筛查 — 检查估值、技术预警、解禁、减持、业绩预警、监管和行业政策,返回风险评级和 veto_buy。新闻搜索命中是待核实线索,不是已证实风险。data_complete和warnings标明覆盖;数据不足时risk_level=unknown,risk_score或veto_buy可为null,不能视为低风险", + "description": "风险专项筛查(支持A股、港股、美股) — 检查估值、技术预警、新闻风险线索,并按市场附加专项检查(A股限售解禁、港股HKEX风险公告、美股SEC Form 4内部人卖出,配置SEC_USER_AGENT时启用),返回风险评级和 veto_buy。新闻搜索命中是待核实线索,不是已证实风险。data_complete和warnings标明覆盖;数据不足时risk_level=unknown,risk_score或veto_buy可为null,不能视为低风险", "parameters": { "type": "object", "properties": { "symbol": { "type": "string", - "description": "A股股票代码,如 600519" + "description": "股票代码(A股如 600519,港股如 00700.HK,美股如 AAPL)" }, "name": { "type": "string", @@ -1421,7 +1446,7 @@ }, { "name": "diagnose_data_sources", - "description": "数据源诊断 — 检查当前环境各数据 provider 的包与凭据就绪情况(不探测网络可达性),输出每个市场的可用链路、缺失 env、warnings。工具拿不到数据或报错时调用排查", + "description": "数据源诊断 — 检查当前环境各行情 provider 与辅助服务(搜索引擎、SEC EDGAR、巨潮/HKEX公告、舆情、CDS/宏观)的包与凭据就绪情况;默认不访问网络,probe=true 时可选执行轻量公开端点连通性探测。工具拿不到数据或报错时调用排查", "parameters": { "type": "object", "properties": { @@ -1437,6 +1462,10 @@ "all" ], "description": "市场,默认 all" + }, + "probe": { + "type": "boolean", + "description": "是否对已就绪的公开端点执行轻量 HTTP 连通性探测,默认 false" } } } diff --git a/tools/value_data.py b/tools/value_data.py index 1aa67a7..ccfe5bf 100644 --- a/tools/value_data.py +++ b/tools/value_data.py @@ -11,7 +11,6 @@ from io import BytesIO, StringIO from pathlib import Path from urllib.parse import unquote -from xml.etree import ElementTree import numpy as np import pandas as pd @@ -944,14 +943,27 @@ def dividends(args): from _subproc import run_tool today = market_now(market).date() + no_cache = bool(getattr(args, "no_cache", False)) + + def load_dataset(key, fetch): + if no_cache: + return records(fetch()) + return dataset(key, fetch) + result = { "symbol": args.symbol, "market": market, "as_of": today.isoformat(), + "cache_bypassed": no_cache, + "history_covered_from": None, + "history_current_through": None, + "capital_gains": [], + "capital_gains_checked": False, + "corporate_actions_complete": False, "yield_basis": "cash paid per share in trailing 365 days / latest price, before tax; nominal source cash amounts", } if market == "A": - rows = dataset(f"dividends:{symbol}", lambda: ak.stock_fhps_detail_em(symbol=symbol)) + rows = load_dataset(f"dividends:{symbol}", lambda: ak.stock_fhps_detail_em(symbol=symbol)) events = [ { "report_date": iso(r.get("报告期")), @@ -961,10 +973,17 @@ def dividends(args): "cash_per_share": number(r.get("现金分红-现金分红比例")) / 10 if number(r.get("现金分红-现金分红比例")) is not None else None, + "bonus_ratio": number(r.get("送转股份-送转总比例")), "status": r.get("方案进度"), } for r in rows ] + splits = [ + {"ex_date": ev["ex_date"], "bonus_ratio": ev["bonus_ratio"], "status": ev["status"]} + for ev in events + if ev.get("bonus_ratio") and ev["bonus_ratio"] > 0 + ] + splits_checked = True if args.mode == "calendar": return { "symbol": args.symbol, @@ -975,7 +994,18 @@ def dividends(args): } quote = run_tool("stock_data.py", ["quote", symbol]) or {} price = number(quote.get("price")) - result.update(source="eastmoney", currency="CNY", price=price, price_as_of=quote.get("as_of")) + # Eastmoney RPT_SHAREBONUS_DET covers dividends and bonus/transfer shares, not rights issues (配股 / + # RPT_IPO_ALLOTMENT), and emits no provider-verified coverage cutoff date -> keep coverage unverified. + result.update( + source="eastmoney", + currency="CNY", + price=price, + price_as_of=quote.get("as_of"), + splits=splits, + splits_checked=splits_checked, + history_current_through=None, + corporate_actions_complete=False, + ) else: import yfinance as yf @@ -984,7 +1014,7 @@ def dividends(args): capture( sources, "calendar", - lambda: dataset( + lambda: load_dataset( f"hk-dividend-calendar:{symbol}", lambda: ak.stock_hk_dividend_payout_em(symbol=symbol) ), ) @@ -1022,6 +1052,41 @@ def dividends(args): "calendar": [r for r in calendar if r.get("ex_date") and r["ex_date"] > today.isoformat()], } + def _series_to_rows(series, value_col): + nonzero = series[series.notna() & (series != 0)] + frame = nonzero.to_frame(value_col).reset_index() + if len(frame.columns) >= 1 and frame.columns[0] != "Date": + frame = frame.rename(columns={frame.columns[0]: "Date"}) + return records(frame) + + def verified_actions_bundle(): + # Make one maximum-history request with actions and errors enabled, deriving cash dividends, + # splits, and the provider's actual covered date range from that single verified frame. + hist = ticker.history(period="max", actions=True, raise_errors=True) + if ( + not isinstance(hist, pd.DataFrame) + or hist.empty + or "Stock Splits" not in hist.columns + or "Dividends" not in hist.columns + ): + raise RuntimeError("yfinance history returned no action-bearing price frame") + covered_from = market_date(hist.index.min(), market) + covered_through = market_date(hist.index.max(), market) + if not covered_from or not covered_through: + raise RuntimeError("yfinance history returned invalid bar dates") + cash_rows = _series_to_rows(hist["Dividends"], "cash_per_share") + split_rows = _series_to_rows(hist["Stock Splits"], "ratio") + capital_gains_rows = ( + _series_to_rows(hist["Capital Gains"], "amount") if "Capital Gains" in hist.columns else [] + ) + return { + "cash": cash_rows, + "splits": split_rows, + "capital_gains": capital_gains_rows, + "covered_from": covered_from, + "covered_through": covered_through, + } + def cash_history(): raw = ticker.dividends frame = ( @@ -1031,9 +1096,40 @@ def cash_history(): ) return frame.reset_index() - capture(sources, "cash", lambda: dataset(f"{market.lower()}-dividend-cash:{symbol}", cash_history)) + splits_ok = False + capital_gains_ok = False + splits_rows = [] + capital_gains_rows = [] + covered_from = None + covered_through = None + paid = [] + used_actions_bundle = False + if callable(getattr(ticker, "history", None)): + bundle_key = f"{market.lower()}-actions-v2:{symbol}" + try: + bundle = verified_actions_bundle() if no_cache else cached(bundle_key, DAY, verified_actions_bundle) + except Exception as exc: + bundle = None + if no_cache: + sources.setdefault("warnings", []).append(f"actions: unavailable ({type(exc).__name__})") + if ( + isinstance(bundle, dict) + and isinstance(bundle.get("splits"), list) + and isinstance(bundle.get("cash"), list) + and isinstance(bundle.get("capital_gains"), list) + ): + paid = bundle["cash"] + splits_rows = bundle["splits"] + capital_gains_rows = bundle["capital_gains"] + splits_ok = True + capital_gains_ok = True + covered_from = bundle.get("covered_from") + covered_through = bundle.get("covered_through") if no_cache else None + used_actions_bundle = True + if not used_actions_bundle and not no_cache: + capture(sources, "cash", lambda: load_dataset(f"{market.lower()}-dividend-cash:{symbol}", cash_history)) + paid = sources.get("cash", []) capture(sources, "quote", lambda: ticker.info) - paid = sources.get("cash", []) info = sources.get("quote") or {} if sources.get("warnings"): result["warnings"] = sources["warnings"] @@ -1048,11 +1144,28 @@ def cash_history(): } for r in paid ] + splits = [ + {"ex_date": market_date(r.get("Date"), market), "ratio": number(r.get("ratio"))} + for r in splits_rows + if number(r.get("ratio")) not in (None, 0) + ] + capital_gains = [ + {"ex_date": market_date(r.get("Date"), market), "amount": number(r.get("amount"))} + for r in capital_gains_rows + if number(r.get("amount")) not in (None, 0) + ] price = number(info.get("currentPrice") or info.get("regularMarketPrice")) result.update( source="yfinance cash / eastmoney calendar" if market == "HK" else "yfinance", currency=info.get("currency"), price=price, + splits=splits, + splits_checked=splits_ok, + capital_gains=capital_gains, + capital_gains_checked=capital_gains_ok, + corporate_actions_complete=used_actions_bundle, + history_covered_from=covered_from, + history_current_through=covered_through, ) result["calendar"] = [r for r in calendar if r["ex_date"] and r["ex_date"] > today.isoformat()] cutoff = (today - timedelta(days=365.25 * args.years)).isoformat() @@ -1117,261 +1230,22 @@ def cash_history(): return result -def tracking_error(nav, benchmark): - if not nav or not benchmark: - return { - "annualized_tracking_error_pct": None, - "observations": 0, - "note": "fund NAV or benchmark history unavailable", - } - fund = pd.DataFrame(nav).drop_duplicates("date").set_index("date").sort_index() - index = pd.DataFrame(benchmark).drop_duplicates("date").set_index("date").sort_index() - fund_returns = pd.to_numeric(fund["daily_return_pct"], errors="coerce") / 100 - close = pd.to_numeric(index["close"], errors="coerce") - index_returns = close.pct_change(fill_method=None) - try: - import exchange_calendars as xcals - - calendar = xcals.get_calendar("XSHG") - previous = { - stamp: calendar.previous_session(stamp).date().isoformat() - for stamp in fund.index.union(index.index) - if calendar.is_session(stamp) - } - except Exception: - return {"annualized_tracking_error_pct": None, "observations": 0, "note": "ETF trading calendar unavailable"} - matched = ( - pd.concat( - [ - fund_returns.rename("fund"), - index_returns.rename("benchmark"), - fund.index.to_series().shift().rename("fund_previous"), - index.index.to_series().shift().rename("benchmark_previous"), - pd.Series(previous).rename("session_previous"), - ], - axis=1, - ) - .replace([np.inf, -np.inf], np.nan) - .dropna() - ) - matched = matched[ - (matched["fund_previous"] == matched["session_previous"]) - & (matched["benchmark_previous"] == matched["session_previous"]) - ] - active = matched["fund"] - matched["benchmark"] - return { - "annualized_tracking_error_pct": round(float(active.std(ddof=1) * np.sqrt(252) * 100), 4) - if len(active) >= 2 - else None, - "observations": len(active), - "window_start": matched.index[0] if len(active) else None, - "window_end": matched.index[-1] if len(active) else None, - "basis": "daily published NAV growth minus benchmark close return; sample std, 252 trading days; only matching consecutive ETF trading-session intervals, no missing-date fill", - } +from _etf_data import etf_basket as _etf_basket_impl # noqa: E402 +from _etf_data import fund_disclosed_equities as _fund_disclosed_equities_impl # noqa: E402 +from _etf_data import fund_size_history as _fund_size_history_impl # noqa: E402 +from _etf_data import tracking_error # noqa: E402 def fund_size_history(symbol): - def fetch(): - match = re.search(r"\bData_fluctuationScale\s*=\s*(.*?);", fund_pingzhong_js(symbol), re.S) - if not match: - raise ValueError("fund scale history unavailable") - data = json.loads(match.group(1)) - if len(data["categories"]) != len(data["series"]): - raise ValueError("fund scale dates and observations do not match") - return [ - {"date": iso(stamp), "aum_cny": number(row.get("y")) * 1e8} - for stamp, row in zip(data["categories"], data["series"], strict=True) - if iso(stamp) and number(row.get("y")) is not None - ] - - return cached(f"etf-size:{symbol}", DAY, fetch) + return _fund_size_history_impl(symbol, fetch_js=fund_pingzhong_js, cache_fn=cached) def etf_basket(symbol): - import requests - - def fetch(): - if symbol.startswith("5"): - response = requests.get( - "https://query.sse.com.cn/etfDownload/downloadETF2Bulletin.do", - params={"fundCode": symbol}, - headers={"Referer": "https://www.sse.com.cn/"}, - timeout=20, - ) - source = "SSE PCF" - else: - response = requests.get( - "https://www.szse.cn/api/report/ShowReport/data", - params={ - "SHOWTYPE": "JSON", - "CATALOGID": "sgshqd", - "txtJCorDH": symbol, - "txtStart": (_cn_now().date() - timedelta(days=30)).isoformat(), - "txtEnd": _cn_now().date().isoformat(), - }, - headers={"Referer": "https://www.szse.cn/"}, - timeout=20, - ) - response.raise_for_status() - dates = re.findall(rf"pcf_{re.escape(symbol)}_(\d{{8}})", json.dumps(response.json())) - dates = [d for d in dates if iso(d) and iso(d) <= _cn_now().date().isoformat()] - if not dates: - raise ValueError("no published SZSE PCF found") - response = requests.get( - f"https://reportdocs.static.szse.cn/files/text/ETFDown/pcf_{symbol}_{max(dates)}.xml", timeout=20 - ) - source = "SZSE PCF" - response.raise_for_status() - if b" _cn_now().date().isoformat() - or not unit - or unit <= 0 - or count != len(components) - or not components - ): - raise ValueError("incomplete or mismatched PCF document") - rows = [] - for node in components: - code = node.findtext("InstrumentID") or node.findtext("UnderlyingSecurityID") - quantity = number(node.findtext("Quantity") or node.findtext("ComponentShare")) - if not code or quantity is None or quantity < 0: - raise ValueError("invalid PCF component") - rows.append( - { - "code": code, - "name": node.findtext("InstrumentName") or node.findtext("UnderlyingSymbol"), - "quantity_per_unit": quantity, - "exchange_code": node.findtext("UnderlyingSecurityID") - if root.tag == "SSEPortfolioCompositionFile" - else node.findtext("UnderlyingSecurityIDSource"), - "cash_substitution_flag": node.findtext("SubstitutionFlag") or node.findtext("SubstituteFlag"), - "creation_premium_rate": number( - node.findtext("CreationPremiumRate") or node.findtext("PremiumRatio") - ), - "redemption_discount_rate": number( - node.findtext("RedemptionDiscountRate") or node.findtext("DiscountRatio") - ), - "substitution_cash_amount": number(node.findtext("SubstitutionCashAmount")), - "creation_cash_substitute": number(node.findtext("CreationCashSubstitute")), - "redemption_cash_substitute": number(node.findtext("RedemptionCashSubstitute")), - } - ) - return { - "source": source, - "as_of": stamp, - "previous_trading_day": iso(root.findtext("PreTradingDay")), - "creation_redemption_unit": unit, - "previous_nav": { - "as_of": iso(root.findtext("PreTradingDay")), - "nav_per_unit": number(root.findtext("NAV")), - "nav_per_creation_unit": number(root.findtext("NAVperCU")), - }, - "previous_cash_component": number(root.findtext("PreCashComponent") or root.findtext("CashComponent")), - "estimated_cash_component": number( - root.findtext("EstimatedCashComponent") or root.findtext("EstimateCashComponent") - ), - "cash_unit": "CNY per creation/redemption unit", - "max_cash_substitution_ratio": number(root.findtext("MaxCashRatio")), - "creation_redemption_switch": root.findtext("CreationRedemptionSwitch"), - "creation_flag": root.findtext("Creation"), - "redemption_flag": root.findtext("Redemption"), - "record_count": len(rows), - "complete": True, - "components": rows, - "basis": "complete published creation/redemption basket, not actual fund holdings; quantities per creation unit, rates are fractions", - } - - return cached(f"etf-basket:{symbol}", DAY, fetch) + return _etf_basket_impl(symbol, cache_fn=cached, now_fn=_cn_now) def fund_disclosed_equities(symbol): - import requests - - try: - from akshare.utils.jsonish import loads as decode - except ImportError: - from akshare.utils.demjson import decode - from bs4 import BeautifulSoup - - limit = 10000 - - def fetch(stamp): - response = requests.get( - "https://fundf10.eastmoney.com/FundArchivesDatas.aspx", - params={"type": "jjcc", "code": symbol, "topline": limit, "year": stamp[:4], "month": str(int(stamp[5:7]))}, - headers={"Referer": f"https://fundf10.eastmoney.com/ccmx_{symbol}.html"}, - timeout=20, - ) - response.raise_for_status() - text = response.text - payload = decode(text[text.index("{") : text.rindex("}") + 1]) - soup = BeautifulSoup(payload["content"], "lxml") - for block in soup.select("div.boxitem"): - heading = block.find("h4") - link = heading.find("a", href=True) if heading else None - if not heading or not link or not link["href"].endswith(f"/{symbol}.html"): - continue - match = re.search(r"\d{4}-\d{2}-\d{2}", heading.get_text()) - if not match or match.group() != stamp: - continue - table = block.find("table") - if table is None: - raise ValueError("disclosed equity table unavailable") - frame = pd.read_html(StringIO(str(table)), converters={"股票代码": str})[0] - frame.columns = [re.sub(r"\s+", "", str(c)) for c in frame.columns] - value_column = next((c for c in frame.columns if c in ("持仓市值(万元)", "持仓市值(万元人民币)")), None) - if not {"股票代码", "股票名称", "占净值比例", "持股数(万股)"}.issubset(frame.columns) or not value_column: - raise ValueError("unknown disclosed equity units/schema") - if frame.empty or len(frame) >= limit: - raise ValueError("empty or potentially truncated disclosed equity table") - positions = [] - for row in frame.to_dict("records"): - quantity = number(str(row["持股数(万股)"]).replace(",", "")) - value = number(str(row[value_column]).replace(",", "")) - positions.append( - { - "code": str(row["股票代码"]), - "name": str(row["股票名称"]) if pd.notna(row["股票名称"]) else None, - "weight_pct": number(str(row["占净值比例"]).replace("%", "")), - "quantity_shares": quantity * 10000 if quantity is not None else None, - "market_value_cny": value * 10000 if value is not None else None, - } - ) - return { - "source": "eastmoney periodic equity report", - "as_of": stamp, - "is_realtime": False, - "position_count": len(positions), - "equity_positions": positions, - "coverage": "all received source-table equity rows, not total fund assets; source completeness is not independently verified", - "source_url": f"https://fundf10.eastmoney.com/ccmx_{symbol}.html", - } - raise ValueError("requested semiannual/annual equity report not available") - - end = date(_cn_now().date().year, ((_cn_now().date().month - 1) // 6) * 6 + 1, 1) - timedelta(days=1) - requested = end.isoformat() - for _ in range(2): - stamp = end.isoformat() - try: - result = cached(f"fund-equity-report:{symbol}:{stamp}", DAY, lambda stamp=stamp: fetch(stamp)) - return {**result, "requested_report_date": requested} - except Exception: - end = date(end.year, end.month - 5, 1) - timedelta(days=1) - raise ValueError("latest disclosed semiannual/annual equity report unavailable") + return _fund_disclosed_equities_impl(symbol, cache_fn=cached, now_fn=_cn_now) def etf_details(args): @@ -1787,6 +1661,11 @@ def main(): p.add_argument("--report-date", default="") p.add_argument("--years", type=int, default=10) p.add_argument("--top", type=int, default=20) + p.add_argument( + "--no-cache", + action="store_true", + help="Bypass the 24-hour dataset cache so corporate-action history is fetched fresh", + ) try: args = parser.parse_args() handlers = { diff --git a/typings/openclaw/index.d.ts b/typings/openclaw/index.d.ts index 347cd17..e749066 100644 --- a/typings/openclaw/index.d.ts +++ b/typings/openclaw/index.d.ts @@ -41,6 +41,7 @@ declare module "typebox" { Object(props: Record, opts?: Options): unknown; String(opts?: Options): unknown; Number(opts?: Options): unknown; + Integer(opts?: Options): unknown; Null(opts?: Options): unknown; Unknown(opts?: Options): unknown; Boolean(opts?: Options): unknown;