From 3a2512023de06dae71bb26c778fa8983e3ff2be7 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Thu, 26 Nov 2026 17:36:45 +0800 Subject: [PATCH 01/37] feat: expand HK/US risk & sectors, macro anchors, MCP prompts, portfolio/DCA backtest, and dsh dashboard UX --- README.md | 25 +- docs/backtest-dsl.md | 4 +- docs/data-sources.md | 4 +- docs/hermes-integration.en.md | 4 +- docs/hermes-integration.md | 4 +- docs/mcp.md | 13 +- docs/openclaw-integration.md | 2 +- docs/pi-integration.en.md | 4 +- docs/pi-integration.md | 4 +- docs/tool-behavior.md | 2 +- dsh/README.md | 10 +- dsh/dashboard.ts | 21 + dsh/research-role.ts | 4 +- dsh/web/app.ts | 225 ++++++- dsh/web/index.html | 9 +- dsh/web/style.css | 14 + hermes/plugin.yaml | 1 + hermes/tools.py | 9 +- mcp_host/server.py | 266 ++++++++- openclaw/openclaw.plugin.json | 1 + scripts/tool-calls.mjs | 10 +- strategies/examples/dca_monthly.yaml | 17 + strategies/examples/portfolio_rebalance.yaml | 14 + tests/test_adapter_parity.ts | 2 +- tests/test_backtest_portfolio.py | 102 ++++ tests/test_capabilities.py | 3 +- tests/test_diagnostics.py | 35 ++ tests/test_dsh_dashboard.ts | 31 + tests/test_dsh_discovery.ts | 4 +- tests/test_dsh_integration.ts | 1 + tests/test_dsh_web_poll.ts | 44 +- tests/test_gather.py | 31 +- tests/test_hermes_integration.py | 1 + tests/test_macro_data.py | 99 ++++ tests/test_mcp_integration.py | 86 ++- tests/test_openclaw_integration.ts | 1 + tests/test_pi_integration.ts | 1 + tests/test_risk_screening.py | 120 ++++ tests/test_signal_tracker.py | 57 ++ tests/test_workflow_performance.py | 2 +- tools/_etf_data.py | 294 +++++++++ tools/_fund_data.py | 235 ++++++++ tools/backtest.py | 590 +++++++++++++++++++ tools/capabilities.py | 8 +- tools/diagnostics.py | 140 ++++- tools/gather.py | 21 +- tools/macro_data.py | 330 +++++++++++ tools/risk_screening.py | 179 +++++- tools/signal_tracker.py | 146 +++-- tools/stock_data.py | 314 ++++------ tools/tool_schemas.json | 43 +- tools/value_data.py | 254 +------- 52 files changed, 3222 insertions(+), 619 deletions(-) create mode 100644 strategies/examples/dca_monthly.yaml create mode 100644 strategies/examples/portfolio_rebalance.yaml create mode 100644 tests/test_backtest_portfolio.py create mode 100644 tests/test_macro_data.py create mode 100644 tools/_etf_data.py create mode 100644 tools/_fund_data.py create mode 100644 tools/macro_data.py 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..fdcfc47 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`;`weighting` 支持 `equal`(默认)或 `custom`(配合 `weights: {symbol: weight}`);`drift_threshold` 为 (0, 1) 偏离阈值;`max_positions` 控制多标的信号模式同时持仓上限。混合不同市场/币种代码会明确报错。 +- `dca`(顶层,可选):定期定投配置,单标的或多标的均可使用。`frequency` 支持 `weekly`/`biweekly`/`monthly`/`quarterly`,`amount` 为每期新增投入金额(正有限数)。启用后结果返回 `total_contributed`、`contributions`、`final_holdings` 及时间加权收益率 `metrics.time_weighted_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..6c6a8b3 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/` 暴露为 MCP Resources。 ## 前置条件 @@ -36,16 +36,21 @@ | 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`),静态暴露 18 个高频核心工具。 ## 行为说明 -- **协议**:支持 `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**:21 个 `skills/*/SKILL.md` 已自动暴露为 MCP Prompts(带可选 `request` 参数),`SKILL.md` 与 `references/` 也作为只读 `stock-skill://...` Resources 暴露,无需手动导入即可在支持 Prompts/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..075765b 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 线价格区间一致、且 `get_dividends` 核实记录日至评估区间内无已实施或已公告除权除息事件(且分红历史无日期缺失告警),允许按 `factor=1.0` 结算并在 `evaluation_price_basis` 标注 `verification=no_corporate_action_verified`;发生除权除息、分红查询失败或口径未知时仍返回 `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..543b6c6 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..49c1a5d 100644 --- a/dsh/web/app.ts +++ b/dsh/web/app.ts @@ -114,19 +114,36 @@ 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"]); +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, + 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 +385,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 +587,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 +653,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 +720,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 +751,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 +792,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 +825,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 +835,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 +1106,62 @@ function post(path: string, body?: unknown): Promise { // ---------- interactions ---------- +function hideSearchResults() { + clearTimeout(state.searchTimer); + const box = document.getElementById("search-results"); + if (box) { + box.hidden = true; + box.replaceChildren(); + } +} + +function showToast(text: string) { + clearTimeout(state.undoTimer); + const bar = $("watch-undo"); + bar.replaceChildren(el("span", "", text)); + bar.hidden = false; + state.undoTimer = 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) || /^[A-Za-z0-9.-]{6,}$/.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 +1247,17 @@ $("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", () => { + clearTimeout(state.searchTimer); + const value = $("symbol-input").value; + 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 +1281,57 @@ $("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}。`; + try { window.parent?.postMessage?.({ type: "stock-analysis:ask-agent", symbol: sym, name: label, prompt }, location.origin); } catch { /* ignore */ } + if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) { + void navigator.clipboard.writeText(prompt).catch(() => {}); + } + showToast(`已生成 ${label} 分析提示词并复制到剪贴板`); + 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 next: PriceAlert = {}; + for (const part of input.split(/[,,\s]+/).map(s => s.trim()).filter(Boolean)) { + const up = /^>=?\s*(\d+(?:\.\d+)?)$/.exec(part); + const dn = /^<=?\s*(\d+(?:\.\d+)?)$/.exec(part); + if (up) next.above = Number(up[1]); + else if (dn) next.below = Number(dn[1]); + } + if (next.above !== undefined || next.below !== undefined) state.alerts[sym] = next; + else delete state.alerts[sym]; + 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 +1348,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 +1416,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..3e44eee 100644 --- a/dsh/web/index.html +++ b/dsh/web/index.html @@ -33,13 +33,16 @@

行情

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..7cddc71 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,10 @@ def get_cds_index(args: dict, **kwargs) -> str: ) +def get_macro_anchors(args: dict, **kwargs) -> str: + return _run("macro_data.py", ["anchors", "--group", args.get("group", "all"), "--days", args.get("days", 30)]) + + 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..bb93db7 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,135 @@ 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", + } +) +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 _skills_dir() -> Path: + return tools.TOOLS_DIR.parent / "skills" + + +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 and references/.""" + sdir = _skills_dir() + prompts: dict[str, dict] = {} + resources: dict[str, dict] = {} + if not sdir.is_dir(): + return prompts, resources + 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}" + resources[ref_uri] = { + "uri": ref_uri, + "name": f"{child.name}/references/{ref.name}", + "description": f"Reference material for {child.name}", + "mimeType": "text/markdown" if ref.suffix.lower() == ".md" else "text/plain", + "path": ref, + } + 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 +227,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 +275,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 = 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 +361,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 +425,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 +433,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=18 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/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/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/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..38a57f7 --- /dev/null +++ b/tests/test_backtest_portfolio.py @@ -0,0 +1,102 @@ +"""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): + return pd.DataFrame( + { + "date": pd.to_datetime(dates), + "open": prices, + "high": [p * 1.02 for p in prices], + "low": [p * 0.98 for p in prices], + "close": prices, + "volume": [volume] * len(dates), + "adjusted": ["qfq"] * len(dates), + } + ) + + +def test_monthly_rebalance_sells_winner_and_buys_laggard(): + dates = pd.bdate_range("2025-01-02", periods=65) + # Asset A doubles then stays flat; Asset B stays flat -> rebalance trims A and adds B + 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_monthly_dca_tracks_contributions_and_twr(): + dates = pd.bdate_range("2025-01-02", periods=70) + prices = np.linspace(10.0, 12.0, 70) + datasets = {"AAPL": _make_df(dates, prices)} + strategy = { + "name": "Monthly DCA", + "dca": {"frequency": "monthly", "amount": 5000}, + "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") + assert res["contributions"]["count"] >= 2 + assert res["total_contributed"] == 10_000 + res["contributions"]["count"] * 5000 + assert res["final_equity"] > res["total_contributed"] + assert res["time_weighted_return"] > 0.15 + + +def test_multi_position_signal_mode_holds_multiple_symbols(): + dates = pd.bdate_range("2025-01-02", periods=50) + prices_a = np.linspace(10.0, 15.0, 50) + prices_b = np.linspace(20.0, 26.0, 50) + datasets = {"AAPL": _make_df(dates, prices_a), "MSFT": _make_df(dates, prices_b)} + strategy = { + "name": "Multi Signal", + "entry": {"conditions": [{"indicator": "close", "operator": ">", "value": 5}], "logic": "all"}, + "exit": {"conditions": [], "stop_loss": -0.2, "take_profit": 0.8}, + "position": {"max_positions": 2}, + "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_signal" + held = {h["symbol"] for h in res["final_holdings"]} + assert held == {"AAPL", "MSFT"} + + +def test_mixed_currency_markets_rejected(): + dates = pd.bdate_range("2025-01-02", periods=40) + datasets = {"600519": _make_df(dates, np.full(40, 100.0)), "AAPL": _make_df(dates, np.full(40, 100.0))} + with pytest.raises(ValueError, match="single market"): + backtest.simulate_portfolio(datasets, {"portfolio": {"rebalance": "monthly"}}, capital=100_000) + + +def test_run_backtest_dispatches_comma_separated_symbols(tmp_path, monkeypatch): + dates = pd.bdate_range("2025-01-02", periods=60) + dfs = { + "510300": _make_df(dates, np.linspace(3.0, 3.6, 60)), + "510500": _make_df(dates, np.linspace(5.0, 5.2, 60)), + } + monkeypatch.setattr(backtest, "fetch_kline", lambda sym, *a, **kw: dfs[sym]) + strat_path = tmp_path / "port.yaml" + strat_path.write_text( + "name: TestPort\nportfolio:\n rebalance: monthly\n weighting: equal\ndca:\n frequency: monthly\n amount: 2000\n", + encoding="utf-8", + ) + res = backtest.run_backtest(str(strat_path), "510300,510500", "2025-01-02", "2025-03-27", 50_000) + assert res["symbols"] == ["510300", "510500"] + assert res["total_contributed"] > 50_000 + assert "time_weighted_return" in res["metrics"] + assert res["final_holdings"] 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..d6dd9d3 100644 --- a/tests/test_diagnostics.py +++ b/tests/test_diagnostics.py @@ -144,6 +144,41 @@ 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): + 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_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" + 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..61b310d 100644 --- a/tests/test_dsh_web_poll.ts +++ b/tests/test_dsh_web_poll.ts @@ -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]); }, @@ -102,6 +105,13 @@ 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")) { + return { + ok: true, + status: 200, + json: async () => ({ query: "茅台", results: [{ symbol: "600519", name: "贵州茅台", region: "cn", score: 1 }] }), + }; + } throw new Error("unexpected fetch: " + path); } @@ -180,4 +190,36 @@ 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 posts ask-agent message to parent shell and shows confirmation 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) } }); +} +assert(postedMessages.some(m => (m as { type?: string; symbol?: string }).type === "stock-analysis:ask-agent" && (m as { symbol?: string }).symbol === "018147")); + +// Group & price alert thresholds render badges and highlight rows when triggered. +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"); + +// Name search dropdown picks symbol into watchlist. +byId("symbol-input").value = "茅台"; +for (const listener of byId("symbol-input").listeners.get("input") ?? []) { + listener({}); +} +const lastTimerFn = [...timers.values()].at(-1) as (() => void) | undefined; +if (typeof lastTimerFn === "function") lastTimerFn(); +await new Promise(resolve => setTimeout(resolve, 10)); +assert(JSON.stringify(byId("search-results").children).includes("贵州茅台")); + +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..f9cbea3 --- /dev/null +++ b/tests/test_macro_data.py @@ -0,0 +1,99 @@ +"""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": [42.0, 42.5, 43.0], # scaled by 0.1 -> 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) + + +def test_cli_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 diff --git a/tests/test_mcp_integration.py b/tests/test_mcp_integration.py index fccc903..67a5d45 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,65 @@ 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"}}, + ) + 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 "用户请求: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 "SKILL" in got[5]["result"]["contents"][0]["uri"] + assert got[6]["error"]["code"] == -32602 + + +def test_discovery_and_core_profile_modes(): + got = _by_id( + INIT, + INITIALIZED, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, + { + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": {"name": "stock_tool_search", "arguments": {"query": "DCF 宏观", "limit": 5}}, + }, + {"jsonrpc": "2.0", "id": 4, "method": "tools/list"}, + extra_args=("--discovery",), + ) + assert got[1]["result"]["capabilities"]["tools"]["listChanged"] is True + assert [t["name"] for t in got[2]["result"]["tools"]] == ["stock_tool_search"] + search_payload = json.loads(got[3]["result"]["content"][0]["text"]) + assert search_payload["matched"] >= 1 + expanded = [t["name"] for t in got[4]["result"]["tools"]] + assert "stock_tool_search" in expanded and len(expanded) > 1 + + core = _by_id(INIT, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, extra_args=("--profile", "core")) + core_names = {t["name"] for t in core[2]["result"]["tools"]} + assert len(core_names) == 18 + assert {"get_quote", "get_macro_anchors", "run_backtest"} <= core_names + + 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..165c764 100644 --- a/tests/test_openclaw_integration.ts +++ b/tests/test_openclaw_integration.ts @@ -217,6 +217,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..c40a67c 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -220,3 +220,123 @@ 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 {"transactions": [{"code": "S"}, {"code": "S"}, {"code": "S"}]} + 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_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_signal_tracker.py b/tests/test_signal_tracker.py index 5769c27..89cc52b 100644 --- a/tests/test_signal_tracker.py +++ b/tests/test_signal_tracker.py @@ -589,6 +589,63 @@ 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): + 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"}, + ] + + def fake_run(script, args, **kwargs): + if script == "stock_data.py": + return bars + if script == "value_data.py" and args[0] == "dividends": + return { + "source": "eastmoney", + "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 + 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_occurred_in_window(store, mock_run_tool): + 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"}, + ] + + def fake_run(script, args, **kwargs): + if script == "stock_data.py": + return bars + if script == "value_data.py" and args[0] == "dividends": + return { + "source": "eastmoney", + "history": [{"ex_date": "2026-09-02", "cash_per_share": 2.0, "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"] == 0 + assert result["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_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..6c0ac0f --- /dev/null +++ b/tools/_etf_data.py @@ -0,0 +1,294 @@ +"""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): + 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 (cache_fn or cached)(f"etf-basket:{symbol}", DAY, fetch) + + +def fund_disclosed_equities(symbol, *, cache_fn=None): + 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 = (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..e5898d3 100644 --- a/tools/backtest.py +++ b/tools/backtest.py @@ -2,6 +2,7 @@ """AlphaEvo — strategy backtesting engine with YAML DSL.""" import argparse +import contextlib import json import math import os @@ -658,6 +659,520 @@ def simulate_monthly_market( } +def _schedule_bucket(ts: pd.Timestamp, frequency: str): + if frequency == "weekly": + iso = ts.isocalendar() + return (int(iso.year), int(iso.week)) + if frequency == "biweekly": + iso = ts.isocalendar() + return (int(iso.year), int(iso.week) // 2) + 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 _parse_portfolio_config(strategy: dict, symbols: list[str]) -> 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") + + 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") + weights = {} + for sym in symbols: + w = float(raw_weights.get(sym, 0.0)) + if not math.isfinite(w) or w < 0: + raise ValueError(f"portfolio.weights[{sym}] must be a non-negative finite number") + weights[sym] = w + 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)") + + 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, + "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()) + 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)) + 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}") + + cfg = _parse_portfolio_config(strategy, symbols) + 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") + + stop_loss = float(exit_cfg.get("stop_loss", -1.0)) if "stop_loss" in exit_cfg else None + take_profit = float(exit_cfg.get("take_profit", 1e9)) if "take_profit" in exit_cfg 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] = {} + trades = [] + equity_curve = [] + commission_paid = 0.0 + stamp_tax_paid = 0.0 + blocked_orders = 0 + trade_id = 0 + + signal_mode = bool(entry_conditions) + last_dca_bucket = None + last_rebal_bucket = None + initial_deployed = False + + # Time-weighted return (TWR) tracks pure investment return independent of DCA cash inflows + twr_factor = 1.0 + prev_equity = capital + + def is_tradable(row) -> bool: + return not ("volume" in row and (not pd.notna(row["volume"]) or row["volume"] <= 0)) + + def fill_px(row) -> 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): + nonlocal cash, commission_paid, trade_id + if budget <= 0 or cash <= 0: + return + 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 + 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, + } + ) + + for ts in eval_dates: + date_str = str(ts.date()) + # Refresh last known closes for symbols that have a bar prior to or on 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"]) + + # Step 1: Scheduled DCA contribution (adds fresh cash before orders on schedule boundary) + 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"] + 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: + # Exits first to free cash and slots + 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"]) + 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 sell: + if not is_tradable(row): + blocked_orders += 1 + else: + sell_shares(sym, h["shares"], row, date_str, reason) + + # Entries for non-held symbols 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: + 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): + blocked_orders += 1 + continue + remaining_slots = max(1, cfg["max_positions"] - len(holdings)) + buy_amount(sym, cash / remaining_slots, row, date_str, reason) + else: + # Allocation / Rebalance / DCA mode + rebal_due = False + if not initial_deployed: + rebal_due = True + if cfg["rebalance"] != "none": + last_rebal_bucket = _schedule_bucket(ts, cfg["rebalance"]) + elif cfg["rebalance"] != "none": + bucket = _schedule_bucket(ts, cfg["rebalance"]) + if bucket != last_rebal_bucket: + last_rebal_bucket = bucket + rebal_due = True + + # Estimate current equity using execution prices where available + cur_prices = {} + for sym in symbols: + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is not None: + cur_prices[sym] = fill_px(info["bars"][idx]) + elif sym in last_close: + cur_prices[sym] = last_close[sym] + port_value = cash + sum(h["shares"] * cur_prices.get(s, h["buy_price"]) for s, h in holdings.items()) + + if rebal_due and port_value > 0: + # Check optional drift threshold after initial deployment + do_rebalance = not initial_deployed + if not do_rebalance: + if cfg["drift_threshold"] is None: + do_rebalance = True + else: + max_drift = max( + abs( + (holdings.get(s, {}).get("shares", 0) * cur_prices.get(s, 0.0) / port_value) + - cfg["weights"][s] + ) + for s in symbols + ) + do_rebalance = max_drift >= cfg["drift_threshold"] + + if do_rebalance: + reason = "初始建仓" if not initial_deployed else f"定期再平衡 ({cfg['rebalance']})" + # Sell overweight positions first + for sym in symbols: + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is None or sym not in holdings: + continue + row = info["bars"][idx] + px = cur_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): + blocked_orders += 1 + else: + sell_shares(sym, excess_shares, row, date_str, reason) + # Buy underweight positions + for sym in symbols: + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is None: + continue + row = info["bars"][idx] + px = cur_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): + blocked_orders += 1 + else: + buy_amount(sym, deficit, row, date_str, reason) + initial_deployed = True + elif dca_added > 0: + # Deploy fresh DCA cash into target weights without selling existing holdings + for sym in symbols: + info = per_sym[sym] + idx = info["idx"].get(ts) + if idx is None: + continue + row = info["bars"][idx] + if not is_tradable(row): + blocked_orders += 1 + continue + buy_amount( + sym, dca_added * cfg["weights"][sym], row, date_str, f"定期定投 ({cfg['dca']['frequency']})" + ) + + # Step 3: Mark-to-market at close + 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()) + denom = prev_equity + dca_added + if denom > 0: + twr_factor *= equity / denom + prev_equity = equity + equity_curve.append({"date": date_str, "equity": round(equity, 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, + "trades": trades, + "equity_curve": equity_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": False, + "limitations": [ + "Stops are close signals, not intraday guaranteed stop prices", + "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 --------------- @@ -926,6 +1441,81 @@ 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 + + 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"] + metrics = compute_metrics(sim["trades"], sim["equity_curve"], total_in, final, actual_start, actual_end) + if sim.get("contributions"): + metrics["time_weighted_return"] = sim["time_weighted_return"] + result = { + "strategy": strategy.get("name", "unnamed"), + "symbol": symbol, + "symbols": symbols, + "mode": sim["mode"], + "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"], sim["equity_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..1670994 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,65 @@ 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] + return _check_entry(name, import_name, env_vars, {"category": category}, note) + + +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" + ) + if not any(s["name"] == "sec_edgar" and s["available"] for s in all_services): + top_warnings.append("SEC_USER_AGENT not set — 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 +255,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..421664c --- /dev/null +++ b/tools/macro_data.py @@ -0,0 +1,330 @@ +#!/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", 0.1), + "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 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"} + if isinstance(days, bool) or not isinstance(days, int) or 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", type=int, 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..ca70488 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -13,6 +13,7 @@ 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 +217,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 +276,96 @@ def check_news_risks(symbol: str, name: str = "", *, run=None) -> dict: return result +_HK_DISCLOSURE_HIGH = ("清盘", "winding up", "停牌", "trading halt", "suspension", "监管调查", "investigation") +_HK_DISCLOSURE_MEDIUM = ( + "盈警", + "盈利警告", + "profit warning", + "配售", + "placing", + "供股", + "rights issue", + "减持", + "disposal", +) + + +def check_hk_disclosures(symbol: str, *, run=None) -> dict: + data = (run or _run_tool)( + "value_data.py", ["announcements", symbol, "--category", "all", "--top", "15"], timeout=25 + ) + result = {"matches": [], "flags": [], "available": False} + if not isinstance(data, dict) or "error" in data or not isinstance(data.get("announcements"), list): + return result + result["available"] = True + for item in data["announcements"]: + title = str(item.get("title") or "") + low = title.lower() + sev = None + if any(k in low or k in title for k in _HK_DISCLOSURE_HIGH): + 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 + + +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} + 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} + if not isinstance(data, dict) or "error" in data or not isinstance(data.get("transactions"), list): + return result + result["available"] = True + sales = [ + tx + for tx in data["transactions"] + if str(tx.get("code") or tx.get("transaction_code") or "").upper() == "S" + or str(tx.get("action") or "").lower() == "sell" + ] + result["sales_90d"] = len(sales) + if len(sales) >= 6: + result["flags"].append( + { + "category": "insider", + "severity": "high", + "description": f"近90日 SEC Form 4 记录到 {len(sales)} 笔内部人卖出", + "source": "data", + } + ) + elif len(sales) >= 3: + result["flags"].append( + { + "category": "insider", + "severity": "medium", + "description": f"近90日 SEC Form 4 记录到 {len(sales)} 笔内部人卖出", + "source": "data", + } + ) + return result + + def _cat_cn(cat: str) -> str: return {"insider": "内部人减持", "earnings": "业绩预警", "regulatory": "监管处罚", "industry": "行业政策"}.get( cat, cat @@ -292,6 +402,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 +425,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 +452,44 @@ 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"]} + all_flags.extend(extra["flags"]) + elif market == "US": + checks["insider_trades"] = { + "sales_90d": extra["sales_90d"], + "available": extra["available"], + "configured": extra["configured"], + } + all_flags.extend(extra["flags"]) + if not extra["configured"]: + warnings.append("SEC_USER_AGENT not set; SEC Form 4 insider trade risk check skipped") 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 +513,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/signal_tracker.py b/tools/signal_tracker.py index 7a7962f..5932c3e 100644 --- a/tools/signal_tracker.py +++ b/tools/signal_tracker.py @@ -261,46 +261,91 @@ 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 dividend history + anchor-bar price consistency that no ex-dividend/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 * 0.9 <= entry <= high * 1.1 + ): + return False + + market = rec.get("market") or detect_market(rec["symbol"]) + anchor_date = anchor["date"] + last_date = max(bar["date"] for bar in bars) + div_data = run_tool( + "value_data.py", + ["dividends", "--market", market, "--symbol", rec["symbol"], "--mode", "history", "--years", "2"], + 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 + warnings = div_data.get("warnings") or [] + if any("missing/invalid" in str(w) or "unavailable" in str(w).lower() for w in warnings): + return False + + events = list(div_data.get("history") or []) + list(div_data.get("calendar") or []) + 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 anchor_date < ex_day <= last_date: + return False + if not has_price_date and ex_day == anchor_date: + return False + return True + + +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 +384,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..69c525d 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": "number", + "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..6a4cb2a 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 @@ -1117,261 +1116,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) 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) def etf_details(args): From 2a080fcecceb450f77189c9108333e0863347b7d Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Thu, 26 Nov 2026 18:34:17 +0800 Subject: [PATCH 02/37] fix: address PR #108 review findings across macro, backtest, signals, risk, dsh, and MCP --- docs/backtest-dsl.md | 4 +- docs/mcp.md | 5 +- docs/tool-behavior.md | 2 +- dsh/README.md | 2 +- dsh/web/app.ts | 66 ++++-- dsh/web/index.html | 2 +- hermes/tools.py | 5 +- mcp_host/server.py | 118 ++++++---- openclaw/index.ts | 2 + skills/stock-analysis/SKILL.md | 4 +- tests/e2e/test_openclaw_e2e.ts | 1 + tests/test_backtest_portfolio.py | 228 ++++++++++++++----- tests/test_diagnostics.py | 10 + tests/test_dsh_web_poll.ts | 90 +++++++- tests/test_macro_data.py | 7 +- tests/test_mcp_integration.py | 87 ++++++-- tests/test_openclaw_integration.ts | 1 + tests/test_risk_screening.py | 28 +++ tests/test_signal_tracker.py | 74 +++++- tools/_etf_data.py | 18 +- tools/backtest.py | 347 ++++++++++++++++++++++------- tools/diagnostics.py | 10 +- tools/macro_data.py | 30 ++- tools/risk_screening.py | 22 +- tools/signal_tracker.py | 79 ++++++- tools/tool_schemas.json | 4 +- tools/value_data.py | 43 +++- typings/openclaw/index.d.ts | 1 + 28 files changed, 1015 insertions(+), 275 deletions(-) diff --git a/docs/backtest-dsl.md b/docs/backtest-dsl.md index fdcfc47..b7d263f 100644 --- a/docs/backtest-dsl.md +++ b/docs/backtest-dsl.md @@ -5,8 +5,8 @@ ## 风控、基准与成交 - `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`;`weighting` 支持 `equal`(默认)或 `custom`(配合 `weights: {symbol: weight}`);`drift_threshold` 为 (0, 1) 偏离阈值;`max_positions` 控制多标的信号模式同时持仓上限。混合不同市场/币种代码会明确报错。 -- `dca`(顶层,可选):定期定投配置,单标的或多标的均可使用。`frequency` 支持 `weekly`/`biweekly`/`monthly`/`quarterly`,`amount` 为每期新增投入金额(正有限数)。启用后结果返回 `total_contributed`、`contributions`、`final_holdings` 及时间加权收益率 `metrics.time_weighted_return`(避免定投现金流入扭曲策略表现)。示例见 `strategies/examples/portfolio_rebalance.yaml` 与 `strategies/examples/dca_monthly.yaml`。 +- `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/mcp.md b/docs/mcp.md index 6c6a8b3..83c6caf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,6 +1,6 @@ # MCP 接入指南(WorkBuddy / Claude Desktop / Cursor) -`mcp_host/server.py` 是本插件的 MCP stdio 服务器:一行一条 JSON-RPC 2.0 消息,只用 Python 标准库。它复用所有宿主共用的 JSON Schema(`tools/tool_schemas.json`,经 `hermes/schemas.py` 读取)和参数映射(`hermes/tools.py`),所以 76 个工具的名称、参数和输出与其他宿主一致。同时自动将 21 个 `skills/*/SKILL.md` 暴露为 MCP Prompts、将 `SKILL.md` 与 `references/` 暴露为 MCP Resources。 +`mcp_host/server.py` 是本插件的 MCP stdio 服务器:一行一条 JSON-RPC 2.0 消息,只用 Python 标准库。它复用所有宿主共用的 JSON Schema(`tools/tool_schemas.json`,经 `hermes/schemas.py` 读取)和参数映射(`hermes/tools.py`),所以 76 个工具的名称、参数和输出与其他宿主一致。同时自动将 21 个 `skills/*/SKILL.md` 暴露为 MCP Prompts、将 `SKILL.md`、`references/` 与 `schemas/*.json` 暴露为只读 MCP Resources。 ## 前置条件 @@ -42,6 +42,7 @@ - **按需发现模式**:在 `args` 追加 `"--discovery"`(或设置 `STOCK_MCP_DISCOVERY=1`),初始只暴露 `stock_tool_search`,按中英文关键词搜索命中后返回完整 schema 并在支持动态刷新的客户端中触发 `notifications/tools/list_changed`。 - **核心子集模式**:在 `args` 追加 `"--profile", "core"`(或设置 `STOCK_MCP_PROFILE=core`),静态暴露 18 个高频核心工具。 +- **边界说明**:`--discovery` 与 `--profile core` 仅用于收敛 `tools/list` 的上下文体积,不作为安全授权边界;工具调用权限仍由宿主客户端控制。 ## 行为说明 @@ -50,7 +51,7 @@ - **错误**:未知工具、参数不是对象、未知方法、无法解析的 JSON 作为 JSON-RPC 错误返回(`-32602` / `-32601` / `-32700` / `-32600`)。缺少必填参数、数据源失败、Python CLI 超时则作为工具结果返回:`isError: true`,正文为 `{"error": "..."}`。 - **并发与取消**:每次 `tools/call` 在独立线程里运行。收到 `notifications/cancelled` 后,服务器会结束对应的 Python 子进程,并且不再回复该请求。客户端关闭 stdin 时,服务器结束所有进行中的调用后退出。 - **超时**:沿用 `tools/cli_budgets.json` 的命令预算,与其他宿主一致。 -- **Skills**:21 个 `skills/*/SKILL.md` 已自动暴露为 MCP Prompts(带可选 `request` 参数),`SKILL.md` 与 `references/` 也作为只读 `stock-skill://...` Resources 暴露,无需手动导入即可在支持 Prompts/Resources 的客户端中使用。 +- **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/tool-behavior.md b/docs/tool-behavior.md index 075765b..2b1220e 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 可提供。无 `adjustment_factor` 时,若全部 K 线同属 `qfq`/`total_return`、记录价与锚点 K 线价格区间一致、且 `get_dividends` 核实记录日至评估区间内无已实施或已公告除权除息事件(且分红历史无日期缺失告警),允许按 `factor=1.0` 结算并在 `evaluation_price_basis` 标注 `verification=no_corporate_action_verified`;发生除权除息、分红查询失败或口径未知时仍返回 `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` 在完整覆盖记录日至评估区间的前提下返回非空历史与 `splits_checked=true`、无历史缺失/截断告警,且确认区间内无已实施或已公告的分红/拆合股/送转事件时,允许按 `factor=1.0` 结算并在 `evaluation_price_basis` 标注 `verification=no_corporate_action_verified`;发生除权除息/拆股、历史缺失告警、区间未完整覆盖、查询失败或口径未知时仍返回 `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 543b6c6..41a161a 100644 --- a/dsh/README.md +++ b/dsh/README.md @@ -39,7 +39,7 @@ allowBuilds: 支持 dsh 前端的宿主会在侧栏显示「股票仪表盘」。首屏是自选股行情表:最新价、涨跌幅、涨跌额、今日区间(振幅与昨收位置)、成交额和 30 日走势(悬停可看每日收盘与较首日涨跌),可按列排序、按市场筛选;上方是六市场指数带和 A 股涨跌分布,下方可切换 A / HK / US / JP / KR / TW 查看各市场指数与交易阶段,A 股另有涨跌统计和行业领涨/领跌榜。其他市场没有用少数指数推算全市场宽度。 -自选股支持按中文名/拼音模糊搜索(`/api/search`)或按代码逗号批量导入和删除,最多 30 只,覆盖六个市场;行内支持一键生成/发送 Agent 分析提示词、自定义分组标签筛选与本地价格阈值高亮提醒(保存在浏览器本地偏好)。列表保存在 `$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` 投顾组合显示组合名称和可获取的投顾机构信息,价格一栏标注「无统一净值」。 diff --git a/dsh/web/app.ts b/dsh/web/app.ts index 49c1a5d..d31021c 100644 --- a/dsh/web/app.ts +++ b/dsh/web/app.ts @@ -113,6 +113,7 @@ 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; @@ -797,8 +798,8 @@ function renderRows(flash: Map) { 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.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); @@ -1107,6 +1108,7 @@ function post(path: string, body?: unknown): Promise { // ---------- interactions ---------- function hideSearchResults() { + state.searchSeq++; clearTimeout(state.searchTimer); const box = document.getElementById("search-results"); if (box) { @@ -1129,7 +1131,7 @@ async function runNameSearch(raw: string) { const q = raw.trim(); const box = document.getElementById("search-results"); if (!box) return; - if (!q || /[\s,,、;;]/.test(q) || /^[A-Za-z0-9.-]{6,}$/.test(q)) { + if (!q || /[\s,,、;;]/.test(q) || EXACT_CODE_RE.test(q)) { hideSearchResults(); return; } @@ -1249,7 +1251,13 @@ $("add-form").addEventListener("submit", event => { }); $("symbol-input").addEventListener("input", () => { clearTimeout(state.searchTimer); + state.searchSeq++; const value = $("symbol-input").value; + const q = value.trim(); + if (!q || /[\s,,、;;]/.test(q) || EXACT_CODE_RE.test(q)) { + hideSearchResults(); + return; + } state.searchTimer = setTimeout(() => { void runNameSearch(value); }, 250); }); document.getElementById("search-results")?.addEventListener("click", event => { @@ -1290,11 +1298,14 @@ $("rows").addEventListener("click", event => { const pct = item?.quote?.change_pct; const pricePart = px !== null ? `,当前参考价 ${px}${num(pct) !== null ? `(${fmtPct(pct)})` : ""}` : ""; const prompt = `请用 stock-analysis 全面分析 ${label}(${sym})${pricePart}。`; - try { window.parent?.postMessage?.({ type: "stock-analysis:ask-agent", symbol: sym, name: label, prompt }, location.origin); } catch { /* ignore */ } - if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) { - void navigator.clipboard.writeText(prompt).catch(() => {}); + if (typeof navigator !== "undefined" && typeof navigator.clipboard?.writeText === "function") { + void navigator.clipboard.writeText(prompt).then( + () => showToast(`已复制 ${label} 分析提示词`), + () => showToast(`剪贴板不可用,请手动复制:${prompt}`), + ); + } else { + showToast(`剪贴板不可用,请手动复制:${prompt}`); } - showToast(`已生成 ${label} 分析提示词并复制到剪贴板`); return; } const alertBtn = closest(event, "button[data-alert]"); @@ -1304,17 +1315,38 @@ $("rows").addEventListener("click", event => { 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 next: PriceAlert = {}; - for (const part of input.split(/[,,\s]+/).map(s => s.trim()).filter(Boolean)) { - const up = /^>=?\s*(\d+(?:\.\d+)?)$/.exec(part); - const dn = /^<=?\s*(\d+(?:\.\d+)?)$/.exec(part); - if (up) next.above = Number(up[1]); - else if (dn) next.below = Number(dn[1]); + 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()); + } } - if (next.above !== undefined || next.below !== undefined) state.alerts[sym] = next; - else delete state.alerts[sym]; - savePrefs(); - renderRows(new Map()); } return; } diff --git a/dsh/web/index.html b/dsh/web/index.html index 3e44eee..f947081 100644 --- a/dsh/web/index.html +++ b/dsh/web/index.html @@ -42,7 +42,7 @@

行情

-

支持中文名、拼音首字母模糊搜索,或逗号批量输入代码(A股/基金 6 位代码,投顾 TIAA 代码,港股 .HK,日 .T,韩 .KS/.KQ,台 .TW,美股代码)。最多 30 项。

+

支持中文名、全拼或拼音首字母模糊搜索,或逗号批量输入代码(A股/基金 6 位代码,投顾 TIAA 代码,港股 .HK,日 .T,韩 .KS/.KQ,台 .TW,美股代码)。最多 30 项。

diff --git a/hermes/tools.py b/hermes/tools.py index 7cddc71..8a2ef5f 100644 --- a/hermes/tools.py +++ b/hermes/tools.py @@ -516,7 +516,10 @@ def get_cds_index(args: dict, **kwargs) -> str: def get_macro_anchors(args: dict, **kwargs) -> str: - return _run("macro_data.py", ["anchors", "--group", args.get("group", "all"), "--days", args.get("days", 30)]) + 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: diff --git a/mcp_host/server.py b/mcp_host/server.py index bb93db7..3b7da68 100644 --- a/mcp_host/server.py +++ b/mcp_host/server.py @@ -68,12 +68,25 @@ # 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?") +_MCP_SKILL_PREAMBLE = ( + "[MCP 执行说明]\n" + "你当前通过 MCP 协议接入 stock-analysis 工具集,无需也不要依赖本地 shell 脚本(如 `python3 scripts/gather.py`)或本地文件路径:\n" + "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` 等;若开启了 `--discovery`,先调用 `stock_tool_search` 加载所需工具)。\n" + "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: @@ -87,53 +100,70 @@ def _parse_frontmatter(raw: str) -> tuple[dict[str, str], str]: def _discover_skills() -> tuple[dict[str, dict], dict[str, dict]]: - """Return (prompts_by_name, resources_by_uri) from skills/*/SKILL.md and references/.""" + """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 not sdir.is_dir(): - return prompts, resources - 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}" - resources[ref_uri] = { - "uri": ref_uri, - "name": f"{child.name}/references/{ref.name}", - "description": f"Reference material for {child.name}", - "mimeType": "text/markdown" if ref.suffix.lower() == ".md" else "text/plain", - "path": ref, + 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 @@ -318,7 +348,7 @@ def handle(method: str, params: dict, *, session_state: dict | None = None) -> d if not isinstance(arguments, dict): raise RpcError(-32602, "Prompt arguments must be an object") req = arguments.get("request") - text = prompt["body"] + text = f"{_MCP_SKILL_PREAMBLE}{prompt['body']}" if isinstance(req, str) and req.strip(): text = f"{text}\n\n---\n用户请求:{req.strip()}" return { 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/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/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_backtest_portfolio.py b/tests/test_backtest_portfolio.py index 38a57f7..b50a46a 100644 --- a/tests/test_backtest_portfolio.py +++ b/tests/test_backtest_portfolio.py @@ -7,23 +7,27 @@ from tools import backtest -def _make_df(dates, prices, volume=1_000_000): - return pd.DataFrame( - { - "date": pd.to_datetime(dates), - "open": prices, - "high": [p * 1.02 for p in prices], - "low": [p * 0.98 for p in prices], - "close": prices, - "volume": [volume] * len(dates), - "adjusted": ["qfq"] * len(dates), - } - ) +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) - # Asset A doubles then stays flat; Asset B stays flat -> rebalance trims A and adds B 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)} @@ -42,61 +46,175 @@ def test_monthly_rebalance_sells_winner_and_buys_laggard(): assert 0.4 <= weights["510300"] <= 0.6 -def test_monthly_dca_tracks_contributions_and_twr(): - dates = pd.bdate_range("2025-01-02", periods=70) - prices = np.linspace(10.0, 12.0, 70) - datasets = {"AAPL": _make_df(dates, prices)} +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 = { - "name": "Monthly DCA", - "dca": {"frequency": "monthly", "amount": 5000}, + "dca": {"frequency": "monthly", "amount": 128}, "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") + 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["total_contributed"] == 10_000 + res["contributions"]["count"] * 5000 - assert res["final_equity"] > res["total_contributed"] - assert res["time_weighted_return"] > 0.15 + assert res["final_cash"] == 0.0 + assert any("定期定投" in t["reason"] for t in res["trades"]) -def test_multi_position_signal_mode_holds_multiple_symbols(): - dates = pd.bdate_range("2025-01-02", periods=50) - prices_a = np.linspace(10.0, 15.0, 50) - prices_b = np.linspace(20.0, 26.0, 50) - datasets = {"AAPL": _make_df(dates, prices_a), "MSFT": _make_df(dates, prices_b)} +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 = { - "name": "Multi Signal", "entry": {"conditions": [{"indicator": "close", "operator": ">", "value": 5}], "logic": "all"}, - "exit": {"conditions": [], "stop_loss": -0.2, "take_profit": 0.8}, - "position": {"max_positions": 2}, + "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") - assert res["mode"] == "portfolio_signal" - held = {h["symbol"] for h in res["final_holdings"]} - assert held == {"AAPL", "MSFT"} + 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, + ) -def test_mixed_currency_markets_rejected(): - dates = pd.bdate_range("2025-01-02", periods=40) - datasets = {"600519": _make_df(dates, np.full(40, 100.0)), "AAPL": _make_df(dates, np.full(40, 100.0))} - with pytest.raises(ValueError, match="single market"): - backtest.simulate_portfolio(datasets, {"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_run_backtest_dispatches_comma_separated_symbols(tmp_path, monkeypatch): - dates = pd.bdate_range("2025-01-02", periods=60) - dfs = { - "510300": _make_df(dates, np.linspace(3.0, 3.6, 60)), - "510500": _make_df(dates, np.linspace(5.0, 5.2, 60)), +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}, } - monkeypatch.setattr(backtest, "fetch_kline", lambda sym, *a, **kw: dfs[sym]) - strat_path = tmp_path / "port.yaml" - strat_path.write_text( - "name: TestPort\nportfolio:\n rebalance: monthly\n weighting: equal\ndca:\n frequency: monthly\n amount: 2000\n", - encoding="utf-8", - ) - res = backtest.run_backtest(str(strat_path), "510300,510500", "2025-01-02", "2025-03-27", 50_000) - assert res["symbols"] == ["510300", "510500"] - assert res["total_contributed"] > 50_000 - assert "time_weighted_return" in res["metrics"] - assert res["final_holdings"] + 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, + ) diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py index d6dd9d3..262caea 100644 --- a/tests/test_diagnostics.py +++ b/tests/test_diagnostics.py @@ -145,6 +145,8 @@ def test_baostock_is_listed_in_a_share_diagnostics(self): 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) @@ -162,6 +164,14 @@ def test_services_and_summary_cover_search_sec_sentiment_and_tradingview(self, m 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 + def test_probe_flag_populates_reachability_without_hitting_live_network(self, monkeypatch): probed = [] diff --git a/tests/test_dsh_web_poll.ts b/tests/test_dsh_web_poll.ts index 61b310d..0e6b3fd 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(); }, @@ -74,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", @@ -106,10 +119,18 @@ async function fetch(path: string, options: { method?: string; body?: string } = 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 () => ({ query: "茅台", results: [{ symbol: "600519", name: "贵州茅台", region: "cn", score: 1 }] }), + json: async () => body, }; } throw new Error("unexpected fetch: " + path); @@ -120,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, @@ -190,36 +212,82 @@ for (const listener of windowListeners.get("message") ?? []) { } assert.equal(document.documentElement.style.props.has("--bg"), false, "omitted theme token is removed"); -// Quick analyze posts ask-agent message to parent shell and shows confirmation toast. +// Quick analyze copies prompt to clipboard and reports honest result (no unhandled ask-agent postMessage). 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) } }); } -assert(postedMessages.some(m => (m as { type?: string; symbol?: string }).type === "stock-analysis:ask-agent" && (m as { symbol?: string }).symbol === "018147")); +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(JSON.stringify(byId("watch-undo").children).includes("已复制")); + +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-undo").children).includes("剪贴板不可用")); +clipboardShouldReject = false; -// Group & price alert thresholds render badges and highlight rows when triggered. +// 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"; +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"); +assert(updatedRows.includes("触达 ≥ 1.5"), "triggered price alert badge rendered with whitespace in input"); -// Name search dropdown picks symbol into watchlist. -byId("symbol-input").value = "茅台"; +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-undo").children).includes("提醒格式无效"), "invalid alert format notifies user"); +assert(JSON.stringify(byId("rows").children).includes("触达 ≥ 1.5"), "existing alert preserved after invalid input"); + +// Full pinyin search reaches /api/search, exact code skips search, and cleared input invalidates in-flight response. +byId("symbol-input").value = "guizhoumaotai"; for (const listener of byId("symbol-input").listeners.get("input") ?? []) { listener({}); } -const lastTimerFn = [...timers.values()].at(-1) as (() => void) | undefined; -if (typeof lastTimerFn === "function") lastTimerFn(); +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("贵州茅台")); +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"); + +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)); +// 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_macro_data.py b/tests/test_macro_data.py index f9cbea3..b6c378b 100644 --- a/tests/test_macro_data.py +++ b/tests/test_macro_data.py @@ -21,7 +21,7 @@ def isolated_cache(tmp_path, monkeypatch): 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": [42.0, 42.5, 43.0], # scaled by 0.1 -> 4.30% + "^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], @@ -89,11 +89,14 @@ def test_all_failed_returns_error_and_invalid_inputs_rejected(monkeypatch): 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_invalid_days_exits_nonzero(): +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 67a5d45..e23fb71 100644 --- a/tests/test_mcp_integration.py +++ b/tests/test_mcp_integration.py @@ -98,39 +98,88 @@ def test_prompts_and_resources_expose_bundled_skills(): "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(): - got = _by_id( - INIT, - INITIALIZED, - {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, - { - "jsonrpc": "2.0", - "id": 3, - "method": "tools/call", - "params": {"name": "stock_tool_search", "arguments": {"query": "DCF 宏观", "limit": 5}}, - }, - {"jsonrpc": "2.0", "id": 4, "method": "tools/list"}, - extra_args=("--discovery",), - ) - assert got[1]["result"]["capabilities"]["tools"]["listChanged"] is True - assert [t["name"] for t in got[2]["result"]["tools"]] == ["stock_tool_search"] - search_payload = json.loads(got[3]["result"]["content"][0]["text"]) - assert search_payload["matched"] >= 1 - expanded = [t["name"] for t in got[4]["result"]["tools"]] - assert "stock_tool_search" in expanded and len(expanded) > 1 + 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"}, extra_args=("--profile", "core")) core_names = {t["name"] for t in core[2]["result"]["tools"]} diff --git a/tests/test_openclaw_integration.ts b/tests/test_openclaw_integration.ts index 165c764..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 }), diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index c40a67c..d207a8d 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -293,6 +293,34 @@ def test_us_risk_screening_without_sec_env_stays_complete(monkeypatch): assert any("SEC_USER_AGENT" in w for w in result["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 { + "transactions": [{"code": "S"}, {"code": "S"}, {"code": "S"}], + "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 diff --git a/tests/test_signal_tracker.py b/tests/test_signal_tracker.py index 89cc52b..a56329f 100644 --- a/tests/test_signal_tracker.py +++ b/tests/test_signal_tracker.py @@ -595,13 +595,19 @@ def test_keyless_qfq_settles_when_no_corporate_action_and_price_consistent(store {"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", + "history_years_requested": 2, + "splits_checked": True, + "splits": [], "history": [{"ex_date": "2026-06-15", "cash_per_share": 1.2, "status": "实施分配"}], "calendar": [], "warnings": [], @@ -613,6 +619,7 @@ def fake_run(script, args, **kwargs): 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] saved = st._load_records(store)[0] assert saved["evaluation_price_basis"] == { "adjusted": "qfq", @@ -621,29 +628,84 @@ def fake_run(script, args, **kwargs): } -def test_keyless_qfq_skips_when_ex_dividend_occurred_in_window(store, mock_run_tool): +def test_keyless_qfq_skips_when_ex_dividend_or_split_or_empty_history_or_price_outside_anchor(store, mock_run_tool): + # Case 1: ex-dividend inside window 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", + "history_years_requested": 2, + "splits_checked": True, + "splits": [], + "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, "history_years_requested": 1}, + ] + 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): + 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": "eastmoney", - "history": [{"ex_date": "2026-09-02", "cash_per_share": 2.0, "status": "实施分配"}], + "source": "yfinance", + "as_of": "2026-09-18", + "history_years_requested": 2, + "splits_checked": True, + "splits": [], + "history": [{"ex_date": "2026-08-10", "cash_per_share": 0.25, "status": "paid"}], "calendar": [], "warnings": [], } return None mock_run_tool.side_effect = fake_run - result = st.cmd_evaluate(Namespace(symbol=None, store=str(store))) - assert result["closed"] == 0 - assert result["results"][0]["outcome"] == "skipped_price_basis" + 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"]] def test_verified_adjustment_factor_keeps_split_return_correct(store, mock_run_tool): diff --git a/tools/_etf_data.py b/tools/_etf_data.py index 6c0ac0f..8a6226d 100644 --- a/tools/_etf_data.py +++ b/tools/_etf_data.py @@ -107,9 +107,11 @@ def fetch(): return (cache_fn or cached)(f"etf-size:{symbol}", DAY, fetch) -def etf_basket(symbol, *, cache_fn=None): +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( @@ -126,15 +128,15 @@ def fetch(): "SHOWTYPE": "JSON", "CATALOGID": "sgshqd", "txtJCorDH": symbol, - "txtStart": (_cn_now().date() - timedelta(days=30)).isoformat(), - "txtEnd": _cn_now().date().isoformat(), + "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) <= _cn_now().date().isoformat()] + 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( @@ -157,7 +159,7 @@ def fetch(): if ( fund_code != symbol or not stamp - or stamp > _cn_now().date().isoformat() + or stamp > clock().date().isoformat() or not unit or unit <= 0 or count != len(components) @@ -218,9 +220,11 @@ def fetch(): return (cache_fn or cached)(f"etf-basket:{symbol}", DAY, fetch) -def fund_disclosed_equities(symbol, *, cache_fn=None): +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: @@ -282,7 +286,7 @@ def fetch(stamp): } 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) + 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() diff --git a/tools/backtest.py b/tools/backtest.py index e5898d3..bd42581 100644 --- a/tools/backtest.py +++ b/tools/backtest.py @@ -8,7 +8,7 @@ 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 @@ -659,13 +659,15 @@ 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": - iso = ts.isocalendar() - return (int(iso.year), int(iso.week) // 2) + return (ts.date() - _BIWEEKLY_ANCHOR).days // 14 if frequency == "monthly": return (ts.year, ts.month) if frequency == "quarterly": @@ -673,7 +675,54 @@ def _schedule_bucket(ts: pd.Timestamp, frequency: str): raise ValueError(f"Unsupported schedule frequency: {frequency}") -def _parse_portfolio_config(strategy: dict, symbols: list[str]) -> dict: +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 multi-counter conventions: 8xxxx.HK = RMB counter, 09xxx.HK (9000-9999) = USD ETF counter + 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 <= 9999: + 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 {} @@ -681,6 +730,10 @@ def _parse_portfolio_config(strategy: dict, symbols: list[str]) -> dict: 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"): @@ -690,12 +743,16 @@ def _parse_portfolio_config(strategy: dict, symbols: list[str]) -> dict: 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") - weights = {} - for sym in symbols: - w = float(raw_weights.get(sym, 0.0)) + 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[{sym}] must be a non-negative finite number") - weights[sym] = w + 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)}") @@ -709,6 +766,10 @@ def _parse_portfolio_config(strategy: dict, symbols: list[str]) -> dict: 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") @@ -728,6 +789,7 @@ def _parse_portfolio_config(strategy: dict, symbols: list[str]) -> dict: "weighting": weighting, "weights": weights, "drift_threshold": drift, + "size": size_frac, "max_positions": max_positions, "dca": dca, } @@ -747,10 +809,23 @@ def simulate_portfolio( 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 {} @@ -767,7 +842,6 @@ def simulate_portfolio( if commission + stamp_tax >= 1: raise ValueError(f"simulation commission + stamp_tax must be < 1, got {commission + stamp_tax}") - cfg = _parse_portfolio_config(strategy, symbols) entry_cfg = strategy.get("entry") or {} exit_cfg = strategy.get("exit") or {} entry_conditions = entry_cfg.get("conditions") or [] @@ -778,8 +852,22 @@ def simulate_portfolio( if logic not in ("all", "any"): raise ValueError(f"{side}.logic must be all or any") - stop_loss = float(exit_cfg.get("stop_loss", -1.0)) if "stop_loss" in exit_cfg else None - take_profit = float(exit_cfg.get("take_profit", 1e9)) if "take_profit" in exit_cfg else None + 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): @@ -826,26 +914,36 @@ def simulate_portfolio( 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 - signal_mode = bool(entry_conditions) last_dca_bucket = None last_rebal_bucket = None - initial_deployed = False + target_symbols = [sym for sym in symbols if cfg["weights"].get(sym, 0.0) > 0] + initially_allocated: set[str] = set() - # Time-weighted return (TWR) tracks pure investment return independent of DCA cash inflows + # Time-weighted return (TWR) tracks pure investment return strictly excluding external cash inflows twr_factor = 1.0 prev_equity = capital - def is_tradable(row) -> bool: - return not ("volume" in row and (not pd.notna(row["volume"]) or row["volume"] <= 0)) + 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) -> float: + 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): @@ -888,15 +986,15 @@ def sell_shares(sym: str, shares_to_sell: int, row: dict, date_str: str, reason: if h["shares"] <= 0: del holdings[sym] - def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str): + 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 + 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 + return False cost = shares * buy_price * (1 + commission) commission_paid += shares * buy_price * commission cash -= cost @@ -928,17 +1026,28 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str): "reason": reason, } ) + return True for ts in eval_dates: date_str = str(ts.date()) - # Refresh last known closes for symbols that have a bar prior to or on ts + # 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"]) - # Step 1: Scheduled DCA contribution (adds fresh cash before orders on schedule boundary) + # 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"]) @@ -947,13 +1056,22 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str): elif bucket != last_dca_bucket: last_dca_bucket = bucket dca_added = cfg["dca"]["amount"] - cash += dca_added - total_contributed += dca_added - contributions.append({"date": date_str, "amount": round(dca_added, 2)}) + + 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: - # Exits first to free cash and slots + sold_today: set[str] = set() + # Exits first to free cash and slots; keep blocked risk exits pending across bars for sym in list(holdings.keys()): info = per_sym[sym] idx = info["idx"].get(ts) @@ -964,6 +1082,7 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str): 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"] @@ -980,18 +1099,25 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str): 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): + 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_today.add(sym) - # Entries for non-held symbols up to max_positions + # 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: + if sym in holdings or sym in sold_today: continue info = per_sym[sym] idx = info["idx"].get(ts) @@ -1004,53 +1130,63 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str): if hit: candidates.append((sym, info["bars"][idx], reason)) for sym, row, reason in candidates[:open_slots]: - if not is_tradable(row): + if not is_tradable(row, "buy"): blocked_orders += 1 continue remaining_slots = max(1, cfg["max_positions"] - len(holdings)) - buy_amount(sym, cash / remaining_slots, row, date_str, reason) + buy_amount(sym, cash * cfg["size"] / remaining_slots, row, date_str, reason) else: # Allocation / Rebalance / DCA mode rebal_due = False - if not initial_deployed: - rebal_due = True - if cfg["rebalance"] != "none": - last_rebal_bucket = _schedule_bucket(ts, cfg["rebalance"]) - elif cfg["rebalance"] != "none": + if cfg["rebalance"] != "none": bucket = _schedule_bucket(ts, cfg["rebalance"]) - if bucket != last_rebal_bucket: + if last_rebal_bucket is None: + last_rebal_bucket = bucket + elif bucket != last_rebal_bucket: last_rebal_bucket = bucket rebal_due = True - # Estimate current equity using execution prices where available - cur_prices = {} - for sym in symbols: - info = per_sym[sym] - idx = info["idx"].get(ts) - if idx is not None: - cur_prices[sym] = fill_px(info["bars"][idx]) - elif sym in last_close: - cur_prices[sym] = last_close[sym] - port_value = cash + sum(h["shares"] * cur_prices.get(s, h["buy_price"]) for s, h in holdings.items()) + 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] + if pending_initial and not rebal_due: + unalloc_weight = sum(cfg["weights"][s] for s in pending_initial) + avail_cash_for_init = cash - dca_added if dca_added > 0 else cash + 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()) if rebal_due and port_value > 0: - # Check optional drift threshold after initial deployment - do_rebalance = not initial_deployed - if not do_rebalance: - if cfg["drift_threshold"] is None: - do_rebalance = True - else: - max_drift = max( - abs( - (holdings.get(s, {}).get("shares", 0) * cur_prices.get(s, 0.0) / port_value) - - cfg["weights"][s] - ) - for s in symbols + 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] ) - do_rebalance = max_drift >= cfg["drift_threshold"] + for s in symbols + ) + do_rebalance = max_drift >= cfg["drift_threshold"] if do_rebalance: - reason = "初始建仓" if not initial_deployed else f"定期再平衡 ({cfg['rebalance']})" + reason = f"定期再平衡 ({cfg['rebalance']})" # Sell overweight positions first for sym in symbols: info = per_sym[sym] @@ -1058,13 +1194,13 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str): if idx is None or sym not in holdings: continue row = info["bars"][idx] - px = cur_prices[sym] + 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): + if not is_tradable(row, "sell"): blocked_orders += 1 else: sell_shares(sym, excess_shares, row, date_str, reason) @@ -1075,43 +1211,48 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str): if idx is None: continue row = info["bars"][idx] - px = cur_prices[sym] + 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): + if not is_tradable(row, "buy"): blocked_orders += 1 - else: - buy_amount(sym, deficit, row, date_str, reason) - initial_deployed = True - elif dca_added > 0: - # Deploy fresh DCA cash into target weights without selling existing holdings - for sym in symbols: + elif buy_amount(sym, deficit, row, date_str, reason): + initially_allocated.add(sym) + rebalanced_today = True + + # Deploy fresh DCA cash whenever rebalance did not already deploy it + if dca_added > 0 and not rebalanced_today: + for sym in target_symbols: info = per_sym[sym] idx = info["idx"].get(ts) if idx is None: continue row = info["bars"][idx] - if not is_tradable(row): + if not is_tradable(row, "buy"): blocked_orders += 1 continue buy_amount( sym, dca_added * cfg["weights"][sym], row, date_str, f"定期定投 ({cfg['dca']['frequency']})" ) - # Step 3: Mark-to-market at close + # 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()) - denom = prev_equity + dca_added - if denom > 0: - twr_factor *= equity / denom + 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 = [] @@ -1132,8 +1273,10 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str): "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, @@ -1155,9 +1298,10 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str): "execution": { "model": execution, "blocked_orders": blocked_orders, - "unfilled_order": False, + "unfilled_order": bool(pending_exits), "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", ], @@ -1176,7 +1320,18 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str): # --------------- 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] @@ -1189,9 +1344,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 @@ -1457,6 +1615,14 @@ def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str | 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 = [], [] @@ -1480,14 +1646,27 @@ def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str | sim = simulate_portfolio(datasets, strategy, capital, start=actual_start) final = sim["final_equity"] total_in = sim["total_contributed"] - metrics = compute_metrics(sim["trades"], sim["equity_curve"], total_in, final, actual_start, actual_end) - if sim.get("contributions"): + 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, @@ -1503,7 +1682,7 @@ def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str | "trades": sim["trades"], "equity_curve": sample_curve(sim["equity_curve"]), "diagnosis": diagnose(metrics), - "diagnostics": diagnose_advanced(metrics, sim["trades"], sim["equity_curve"], strategy), + "diagnostics": diagnose_advanced(metrics, sim["trades"], risk_curve, strategy), } if sim.get("contributions"): result["contributions"] = sim["contributions"] diff --git a/tools/diagnostics.py b/tools/diagnostics.py index 1670994..b889177 100644 --- a/tools/diagnostics.py +++ b/tools/diagnostics.py @@ -20,6 +20,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) from _subproc import error_message, json_safe, utf8_stdio # noqa: E402 from capabilities import ALL_MARKETS # noqa: E402 +from sec_edgar import identity as _sec_identity # noqa: E402 # provider -> (import_name, required_env_vars, markets, note) PROVIDERS = { @@ -159,7 +160,14 @@ def _check_provider(name: str) -> dict: def _check_service(name: str) -> dict: category, import_name, env_vars, note = SERVICES[name] - return _check_entry(name, import_name, env_vars, {"category": category}, note) + entry = _check_entry(name, import_name, env_vars, {"category": category}, note) + if name == "sec_edgar" and entry["available"]: + try: + _sec_identity() + except ValueError as exc: + entry["available"] = False + entry["reason"] = f"invalid SEC_USER_AGENT: {exc}" + return entry def _apply_probes(entries: list[dict]) -> None: diff --git a/tools/macro_data.py b/tools/macro_data.py index 421664c..581657e 100644 --- a/tools/macro_data.py +++ b/tools/macro_data.py @@ -32,7 +32,7 @@ ALL_KEYS = GROUPS["rates"] + GROUPS["fx"] + GROUPS["risk"] YF_SPECS = { - "us_10y": ("^TNX", "US 10Y Treasury Yield", "percent", 0.1), + "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), @@ -221,11 +221,35 @@ def _fetch_anchor_uncached(key: str, days: int, bond_cache: dict | None = None) 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"} - if isinstance(days, bool) or not isinstance(days, int) or days < 2 or days > 365: + 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]) @@ -314,7 +338,7 @@ def main(): 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", type=int, default=30) + p.add_argument("--days", default="30") args = parser.parse_args() if not args.command: parser.print_help() diff --git a/tools/risk_screening.py b/tools/risk_screening.py index ca70488..41bb679 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -332,12 +332,23 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: 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} + 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} + 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 - result["available"] = True + 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 + result["available"] = not truncated and not sec_warnings sales = [ tx for tx in data["transactions"] @@ -465,10 +476,15 @@ def supplied(key): "sales_90d": extra["sales_90d"], "available": extra["available"], "configured": extra["configured"], + "truncated": extra.get("truncated", 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"]) diff --git a/tools/signal_tracker.py b/tools/signal_tracker.py index 5932c3e..b51d21f 100644 --- a/tools/signal_tracker.py +++ b/tools/signal_tracker.py @@ -262,8 +262,8 @@ def _valid_bar(bar, require_open=True) -> bool: def _verify_no_corporate_action(rec: dict, bars: list, anchor_idx: int, has_price_date: bool, remaining: float) -> bool: - """Verify via dividend history + anchor-bar price consistency that no ex-dividend/split - invalidated the 1:1 price correspondence between entry_price and adjusted bars.""" + """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") @@ -272,27 +272,71 @@ def _verify_no_corporate_action(rec: dict, bars: list, anchor_idx: int, has_pric isinstance(entry, (int, float)) and isinstance(low, (int, float)) and isinstance(high, (int, float)) - and low * 0.9 <= entry <= high * 1.1 + and low - 1e-6 <= entry <= high + 1e-6 ): return False - market = rec.get("market") or detect_market(rec["symbol"]) 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); history resolves market from symbol across A/HK/US/JP/KR/TW. div_data = run_tool( "value_data.py", - ["dividends", "--market", market, "--symbol", rec["symbol"], "--mode", "history", "--years", "2"], + ["dividends", "--symbol", rec["symbol"], "--mode", "history", "--years", str(years_needed)], 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 - warnings = div_data.get("warnings") or [] - if any("missing/invalid" in str(w) or "unavailable" in str(w).lower() for w in warnings): + # Require explicit corporate-action history and split coverage; empty history is never treated as confirmed zero. + if not div_data["history"] or div_data.get("splits_checked") 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 the returned history window actually covers anchor_date..last_date without silent truncation. + years_returned = div_data.get("history_years_requested") + as_of_raw = div_data.get("as_of") + if ( + isinstance(years_returned, bool) + or not isinstance(years_returned, (int, float)) + or years_returned < years_needed + ): + return False + if isinstance(as_of_raw, str) and len(as_of_raw) >= 10: + try: + as_of_dt = datetime.strptime(as_of_raw[:10], "%Y-%m-%d").date() + except ValueError: + return False + if as_of_dt < last_dt: + return False + # Verify anchor_date is strictly after the producer's cutoff (as_of - 365.25 * years_returned). + if (as_of_dt - anchor_dt).days >= int(365.25 * years_returned): + return False + else: 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 @@ -303,11 +347,30 @@ def _verify_no_corporate_action(rec: dict, bars: list, anchor_idx: int, has_pric 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 - return True + + splits = div_data.get("splits") + if splits is not None: + if not isinstance(splits, list): + return False + for sp in splits: + if not isinstance(sp, dict): + return False + ex_date = sp.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): diff --git a/tools/tool_schemas.json b/tools/tool_schemas.json index 69c525d..12b7569 100644 --- a/tools/tool_schemas.json +++ b/tools/tool_schemas.json @@ -419,8 +419,8 @@ "description": "基准分组:all=全部(默认),rates=中美无风险利率,fx=汇率与美元指数,risk=VIX/黄金/原油" }, "days": { - "type": "number", - "description": "历史统计窗口天数(2..365,默认 30)" + "type": "integer", + "description": "历史统计窗口天数(2..365 整数,默认 30)" } }, "required": [] diff --git a/tools/value_data.py b/tools/value_data.py index 6a4cb2a..fb08352 100644 --- a/tools/value_data.py +++ b/tools/value_data.py @@ -960,10 +960,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, @@ -974,7 +981,14 @@ 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")) + result.update( + source="eastmoney", + currency="CNY", + price=price, + price_as_of=quote.get("as_of"), + splits=splits, + splits_checked=splits_checked, + ) else: import yfinance as yf @@ -1030,7 +1044,23 @@ def cash_history(): ) return frame.reset_index() + def split_history(): + raw = ticker.splits + if raw is None: + return pd.DataFrame(columns=["Date", "ratio"]) + frame = ( + raw.to_frame("ratio") if isinstance(raw, pd.Series) else raw.rename(columns={"Stock Splits": "ratio"}) + ) + return frame.reset_index() + capture(sources, "cash", lambda: dataset(f"{market.lower()}-dividend-cash:{symbol}", cash_history)) + splits_ok = False + splits_rows = [] + try: + splits_rows = dataset(f"{market.lower()}-splits:{symbol}", split_history) + splits_ok = isinstance(splits_rows, list) + except Exception: + splits_ok = False capture(sources, "quote", lambda: ticker.info) paid = sources.get("cash", []) info = sources.get("quote") or {} @@ -1047,11 +1077,18 @@ 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) + ] 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, ) 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() @@ -1127,11 +1164,11 @@ def fund_size_history(symbol): def etf_basket(symbol): - return _etf_basket_impl(symbol, cache_fn=cached) + return _etf_basket_impl(symbol, cache_fn=cached, now_fn=_cn_now) def fund_disclosed_equities(symbol): - return _fund_disclosed_equities_impl(symbol, cache_fn=cached) + return _fund_disclosed_equities_impl(symbol, cache_fn=cached, now_fn=_cn_now) def etf_details(args): 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; From 23b090c225d9199335efb546bdab30b19ccf66d5 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Thu, 26 Nov 2026 19:05:01 +0800 Subject: [PATCH 03/37] fix: enforce allocation exits, pending DCA retries, HKEX currency ranges, and fresh split/dividend checks --- docs/tool-behavior.md | 2 +- tests/test_backtest_portfolio.py | 48 ++++++++++ tests/test_dsh_web_poll.ts | 5 +- tests/test_signal_tracker.py | 45 ++++++--- tests/test_value_data.py | 58 ++++++++++++ tools/backtest.py | 156 ++++++++++++++++++++----------- tools/signal_tracker.py | 22 +++-- tools/value_data.py | 46 ++++++--- 8 files changed, 286 insertions(+), 96 deletions(-) diff --git a/docs/tool-behavior.md b/docs/tool-behavior.md index 2b1220e..55f3d6e 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 可提供。无 `adjustment_factor` 时,仅当全部 K 线同属 `qfq`/`total_return`、记录价严格落在锚点 K 线 `[low, high]` 区间内、且 `get_dividends` 在完整覆盖记录日至评估区间的前提下返回非空历史与 `splits_checked=true`、无历史缺失/截断告警,且确认区间内无已实施或已公告的分红/拆合股/送转事件时,允许按 `factor=1.0` 结算并在 `evaluation_price_basis` 标注 `verification=no_corporate_action_verified`;发生除权除息/拆股、历史缺失告警、区间未完整覆盖、查询失败或口径未知时仍返回 `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` 且 `history_current_through` 覆盖至评估末日)、返回非空历史与经错误上报路径验证的 `splits_checked=true`、无历史缺失/截断告警,且确认区间内无已实施或已公告的分红/拆合股/送转事件时,允许按 `factor=1.0` 结算并在 `evaluation_price_basis` 标注 `verification=no_corporate_action_verified`;发生除权除息/拆股、历史缺失告警、区间未完整覆盖、查询失败或口径未知时仍返回 `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/tests/test_backtest_portfolio.py b/tests/test_backtest_portfolio.py index b50a46a..e37b822 100644 --- a/tests/test_backtest_portfolio.py +++ b/tests/test_backtest_portfolio.py @@ -218,3 +218,51 @@ def test_duplicate_canonical_symbols_and_mixed_hk_counters_rejected(): {"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()) diff --git a/tests/test_dsh_web_poll.ts b/tests/test_dsh_web_poll.ts index 0e6b3fd..d9d3b4a 100644 --- a/tests/test_dsh_web_poll.ts +++ b/tests/test_dsh_web_poll.ts @@ -272,6 +272,7 @@ for (const listener of byId("symbol-input").listeners.get("input") ?? []) { 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") ?? []) { @@ -280,13 +281,15 @@ for (const listener of byId("symbol-input").listeners.get("input") ?? []) { 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 }] }); +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"); diff --git a/tests/test_signal_tracker.py b/tests/test_signal_tracker.py index a56329f..bc88f19 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,7 +594,7 @@ 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): +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"}, @@ -605,6 +610,8 @@ def fake_run(script, args, **kwargs): 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": [], @@ -620,6 +627,7 @@ def fake_run(script, args, **kwargs): 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", @@ -628,8 +636,10 @@ def fake_run(script, args, **kwargs): } -def test_keyless_qfq_skips_when_ex_dividend_or_split_or_empty_history_or_price_outside_anchor(store, mock_run_tool): - # Case 1: ex-dividend inside window +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"}, @@ -638,6 +648,8 @@ def test_keyless_qfq_skips_when_ex_dividend_or_split_or_empty_history_or_price_o 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": [], @@ -651,6 +663,9 @@ def test_keyless_qfq_skips_when_ex_dividend_or_split_or_empty_history_or_price_o {**base_div, "splits": [{"ex_date": "2026-09-02", "ratio": 2.0}]}, {**base_div, "splits_checked": 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 @@ -673,7 +688,7 @@ def test_keyless_qfq_skips_when_ex_dividend_or_split_or_empty_history_or_price_o assert res2["results"][0]["outcome"] == "skipped_price_basis" -def test_keyless_us_total_return_uses_cli_without_market_flag(store, mock_run_tool): +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 @@ -693,6 +708,8 @@ def fake_run(script, args, **kwargs): 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": [], @@ -705,7 +722,7 @@ def fake_run(script, args, **kwargs): 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"]] + assert seen_div_args == [["dividends", "--symbol", "AAPL", "--mode", "history", "--years", "2", "--no-cache"]] def test_verified_adjustment_factor_keeps_split_return_correct(store, mock_run_tool): diff --git a/tests/test_value_data.py b/tests/test_value_data.py index c227c1c..1054817 100644 --- a/tests/test_value_data.py +++ b/tests/test_value_data.py @@ -1380,3 +1380,61 @@ 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. Non-empty action-bearing history with zero splits -> splits_checked=True, splits=[] + hist_calls = [] + + def ok_history(**kwargs): + hist_calls.append(kwargs) + return pd.DataFrame( + {"Close": [100.0, 102.0], "Stock Splits": [0.0, 0.0]}, + index=pd.DatetimeIndex(["2026-08-01", "2026-09-01"], tz="America/New_York", name="Date"), + ) + + ticker_ok = Namespace( + dividends=pd.Series([0.25], index=pd.DatetimeIndex(["2026-08-01"], tz="America/New_York", name="Date")), + 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 res["cache_bypassed"] is True + assert res["history_current_through"] == res["as_of"] + assert hist_calls == [{"period": "max", "actions": True, "raise_errors": True}] + + # 2. Empty DataFrame returned by failed history request must NOT set splits_checked=True + ticker_empty = Namespace( + dividends=ticker_ok.dividends, + history=lambda **kw: pd.DataFrame(), + info=ticker_ok.info, + calendar={}, + ) + 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 + + # 3. Exception raised by history must NOT set splits_checked=True + def boom(**kw): + raise RuntimeError("network error") + + ticker_err = Namespace( + dividends=ticker_ok.dividends, + history=boom, + info=ticker_ok.info, + calendar={}, + ) + 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 diff --git a/tools/backtest.py b/tools/backtest.py index bd42581..2fce098 100644 --- a/tools/backtest.py +++ b/tools/backtest.py @@ -710,13 +710,15 @@ def _infer_currency(symbol: str, market: str, df: pd.DataFrame) -> str | None: if market == "TW": return "TWD" if market == "HK": - # HKEX multi-counter conventions: 8xxxx.HK = RMB counter, 09xxx.HK (9000-9999) = USD ETF counter + # 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 <= 9999: + if (9000 <= code <= 9599) or (9700 <= code <= 9849) or (41500 <= code <= 41599): return "USD" return "HKD" return None @@ -927,6 +929,11 @@ def simulate_portfolio( 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 @@ -1028,6 +1035,50 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str) - ) 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 @@ -1070,47 +1121,7 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str) - # Step 2: Execute either signal-driven multi-position mode or target-allocation/rebalance mode if signal_mode: - sold_today: set[str] = set() - # Exits first to free cash and slots; keep blocked risk exits pending across bars - 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_today.add(sym) + 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) @@ -1137,6 +1148,13 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str) - 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"]) @@ -1150,10 +1168,13 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str) - 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] + 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) - avail_cash_for_init = cash - dca_added if dca_added > 0 else cash + 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) @@ -1176,12 +1197,17 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str) - 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] + 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 ) - for s in symbols + if any(s not in exited_alloc for s in symbols) + else 0.0 ) do_rebalance = max_drift >= cfg["drift_threshold"] @@ -1189,6 +1215,8 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str) - reason = f"定期再平衡 ({cfg['rebalance']})" # 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: @@ -1206,6 +1234,8 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str) - sell_shares(sym, excess_shares, row, date_str, reason) # Buy underweight positions 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: @@ -1221,10 +1251,23 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str) - elif buy_amount(sym, deficit, row, date_str, reason): initially_allocated.add(sym) rebalanced_today = True + pending_dca.clear() - # Deploy fresh DCA cash whenever rebalance did not already deploy it - if dca_added > 0 and not rebalanced_today: - for sym in target_symbols: + # Deploy fresh & retained blocked DCA budgets whenever rebalance did not already deploy them + if not rebalanced_today: + 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] + 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: @@ -1233,9 +1276,8 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str) - if not is_tradable(row, "buy"): blocked_orders += 1 continue - buy_amount( - sym, dca_added * cfg["weights"][sym], row, date_str, f"定期定投 ({cfg['dca']['frequency']})" - ) + 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: @@ -1298,7 +1340,7 @@ def buy_amount(sym: str, budget: float, row: dict, date_str: str, reason: str) - "execution": { "model": execution, "blocked_orders": blocked_orders, - "unfilled_order": bool(pending_exits), + "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", diff --git a/tools/signal_tracker.py b/tools/signal_tracker.py index b51d21f..af26eb2 100644 --- a/tools/signal_tracker.py +++ b/tools/signal_tracker.py @@ -289,17 +289,19 @@ def _verify_no_corporate_action(rec: dict, bars: list, anchor_idx: int, has_pric if years_needed > 20: return False - # Omit --market (only supported for ranking A/HK); history resolves market from symbol across A/HK/US/JP/KR/TW. + # 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)], + ["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 explicit corporate-action history and split coverage; empty history is never treated as confirmed zero. + # Require fresh, non-cached corporate-action history and verified split 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: return False warnings = [str(w).lower() for w in (div_data.get("warnings") or [])] @@ -312,24 +314,24 @@ def _verify_no_corporate_action(rec: dict, bars: list, anchor_idx: int, has_pric if any(any(marker in w for marker in blocked_markers) for w in warnings): return False - # Verify the returned history window actually covers anchor_date..last_date without silent truncation. + # Verify fresh history coverage through at least last_date (do not trust request-time `as_of`). years_returned = div_data.get("history_years_requested") - as_of_raw = div_data.get("as_of") + current_through_raw = div_data.get("history_current_through") if ( isinstance(years_returned, bool) or not isinstance(years_returned, (int, float)) or years_returned < years_needed ): return False - if isinstance(as_of_raw, str) and len(as_of_raw) >= 10: + if isinstance(current_through_raw, str) and len(current_through_raw) >= 10: try: - as_of_dt = datetime.strptime(as_of_raw[:10], "%Y-%m-%d").date() + current_through_dt = datetime.strptime(current_through_raw[:10], "%Y-%m-%d").date() except ValueError: return False - if as_of_dt < last_dt: + if current_through_dt < last_dt: return False - # Verify anchor_date is strictly after the producer's cutoff (as_of - 365.25 * years_returned). - if (as_of_dt - anchor_dt).days >= int(365.25 * years_returned): + # 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 diff --git a/tools/value_data.py b/tools/value_data.py index fb08352..8bdbaca 100644 --- a/tools/value_data.py +++ b/tools/value_data.py @@ -943,14 +943,23 @@ 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_current_through": today.isoformat() if no_cache else None, "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("报告期")), @@ -997,7 +1006,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) ), ) @@ -1044,20 +1053,26 @@ def cash_history(): ) return frame.reset_index() - def split_history(): - raw = ticker.splits - if raw is None: - return pd.DataFrame(columns=["Date", "ratio"]) - frame = ( - raw.to_frame("ratio") if isinstance(raw, pd.Series) else raw.rename(columns={"Stock Splits": "ratio"}) - ) - return frame.reset_index() - - capture(sources, "cash", lambda: dataset(f"{market.lower()}-dividend-cash:{symbol}", cash_history)) + def split_history_verified(): + # Fetch action-bearing price history with raise_errors=True so failed yfinance requests + # (which ticker.splits can silently turn into an empty Series) never set splits_checked=True. + if not callable(getattr(ticker, "history", None)): + raise RuntimeError("split history requires ticker.history") + 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: + raise RuntimeError("yfinance history returned no action-bearing price frame") + splits_series = hist["Stock Splits"] + nonzero = splits_series[splits_series.notna() & (splits_series != 0)] + frame = nonzero.to_frame("ratio").reset_index() + if len(frame.columns) >= 1 and frame.columns[0] != "Date": + frame = frame.rename(columns={frame.columns[0]: "Date"}) + return frame + + capture(sources, "cash", lambda: load_dataset(f"{market.lower()}-dividend-cash:{symbol}", cash_history)) splits_ok = False splits_rows = [] try: - splits_rows = dataset(f"{market.lower()}-splits:{symbol}", split_history) + splits_rows = load_dataset(f"{market.lower()}-splits:{symbol}", split_history_verified) splits_ok = isinstance(splits_rows, list) except Exception: splits_ok = False @@ -1584,6 +1599,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 = { From c51081d104b69f691630a4a63900ab15bf95bc0e Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Thu, 26 Nov 2026 21:27:43 +0800 Subject: [PATCH 04/37] fix: verify provider coverage range, retain DCA on suspended rebalance, deduplicate Form 4/A, and polish dsh/MCP/diagnostics --- docs/mcp.md | 2 +- dsh/web/app.ts | 11 ++-- dsh/web/index.html | 1 + mcp_host/server.py | 40 +++++++++++---- tests/test_backtest_portfolio.py | 24 +++++++++ tests/test_diagnostics.py | 20 ++++++++ tests/test_dsh_web_poll.ts | 28 +++++++++-- tests/test_mcp_integration.py | 21 ++++++-- tests/test_risk_screening.py | 64 ++++++++++++++++++++++++ tests/test_signal_tracker.py | 71 ++++++++++++++++++++++++++ tests/test_value_data.py | 24 +++++---- tools/backtest.py | 26 ++++++---- tools/diagnostics.py | 3 +- tools/risk_screening.py | 59 +++++++++++++++++++--- tools/signal_tracker.py | 12 ++++- tools/value_data.py | 86 +++++++++++++++++++++++--------- 16 files changed, 414 insertions(+), 78 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 83c6caf..beaae8f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -41,7 +41,7 @@ ### 按需发现与精简模式(降低上下文占用) - **按需发现模式**:在 `args` 追加 `"--discovery"`(或设置 `STOCK_MCP_DISCOVERY=1`),初始只暴露 `stock_tool_search`,按中英文关键词搜索命中后返回完整 schema 并在支持动态刷新的客户端中触发 `notifications/tools/list_changed`。 -- **核心子集模式**:在 `args` 追加 `"--profile", "core"`(或设置 `STOCK_MCP_PROFILE=core`),静态暴露 18 个高频核心工具。 +- **核心子集模式**:在 `args` 追加 `"--profile", "core"`(或设置 `STOCK_MCP_PROFILE=core`),静态暴露 19 个高频核心工具(含 `render_stock_report`)。 - **边界说明**:`--discovery` 与 `--profile core` 仅用于收敛 `tools/list` 的上下文体积,不作为安全授权边界;工具调用权限仍由宿主客户端控制。 ## 行为说明 diff --git a/dsh/web/app.ts b/dsh/web/app.ts index d31021c..7ac27c3 100644 --- a/dsh/web/app.ts +++ b/dsh/web/app.ts @@ -143,6 +143,7 @@ const state = { 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, @@ -1118,11 +1119,11 @@ function hideSearchResults() { } function showToast(text: string) { - clearTimeout(state.undoTimer); - const bar = $("watch-undo"); + clearTimeout(state.toastTimer); + const bar = $("watch-toast"); bar.replaceChildren(el("span", "", text)); bar.hidden = false; - state.undoTimer = setTimeout(() => { + state.toastTimer = setTimeout(() => { bar.hidden = true; }, 4500); } @@ -1250,12 +1251,10 @@ $("add-form").addEventListener("submit", event => { if (symbols.length) void changeWatchlist("add", symbols); }); $("symbol-input").addEventListener("input", () => { - clearTimeout(state.searchTimer); - state.searchSeq++; + hideSearchResults(); const value = $("symbol-input").value; const q = value.trim(); if (!q || /[\s,,、;;]/.test(q) || EXACT_CODE_RE.test(q)) { - hideSearchResults(); return; } state.searchTimer = setTimeout(() => { void runNameSearch(value); }, 250); diff --git a/dsh/web/index.html b/dsh/web/index.html index f947081..de2d752 100644 --- a/dsh/web/index.html +++ b/dsh/web/index.html @@ -69,6 +69,7 @@

自选

+
diff --git a/mcp_host/server.py b/mcp_host/server.py index 3b7da68..62c8a28 100644 --- a/mcp_host/server.py +++ b/mcp_host/server.py @@ -49,6 +49,7 @@ "build_watchlist_context", "diagnose_data_sources", "get_market_capabilities", + "render_stock_report", } ) DISCOVERY_TOOL_DEF = { @@ -68,15 +69,32 @@ # 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?") -_MCP_SKILL_PREAMBLE = ( - "[MCP 执行说明]\n" - "你当前通过 MCP 协议接入 stock-analysis 工具集,无需也不要依赖本地 shell 脚本(如 `python3 scripts/gather.py`)或本地文件路径:\n" - "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` 等;若开启了 `--discovery`,先调用 `stock_tool_search` 加载所需工具)。\n" - "2. 若正文引用了 `references/...` 或 `schemas/...` 文件,请通过 MCP `resources/read` 读取对应的 " - "`stock-skill:///references/` 或 `stock-schema://` 资源(例如 `stock-schema://report_schema.json`)。\n\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: @@ -348,7 +366,7 @@ def handle(method: str, params: dict, *, session_state: dict | None = None) -> d if not isinstance(arguments, dict): raise RpcError(-32602, "Prompt arguments must be an object") req = arguments.get("request") - text = f"{_MCP_SKILL_PREAMBLE}{prompt['body']}" + 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 { @@ -475,7 +493,7 @@ def main(argv: list[str] | None = None) -> None: "--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=18 core tools)", + 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 diff --git a/tests/test_backtest_portfolio.py b/tests/test_backtest_portfolio.py index e37b822..32b3b5b 100644 --- a/tests/test_backtest_portfolio.py +++ b/tests/test_backtest_portfolio.py @@ -266,3 +266,27 @@ def test_blocked_dca_contribution_retries_on_next_tradable_bar(): 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 diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py index 262caea..0e3de31 100644 --- a/tests/test_diagnostics.py +++ b/tests/test_diagnostics.py @@ -189,6 +189,26 @@ def fake_probe(name, timeout=4.0): 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 "") + if __name__ == "__main__": import subprocess diff --git a/tests/test_dsh_web_poll.ts b/tests/test_dsh_web_poll.ts index d9d3b4a..5d9cc78 100644 --- a/tests/test_dsh_web_poll.ts +++ b/tests/test_dsh_web_poll.ts @@ -212,7 +212,13 @@ for (const listener of windowListeners.get("message") ?? []) { } assert.equal(document.documentElement.style.props.has("--bg"), false, "omitted theme token is removed"); -// Quick analyze copies prompt to clipboard and reports honest result (no unhandled ask-agent postMessage). +// 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) } }); @@ -221,14 +227,17 @@ 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(JSON.stringify(byId("watch-undo").children).includes("已复制")); +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-undo").children).includes("剪贴板不可用")); +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. @@ -250,10 +259,11 @@ 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-undo").children).includes("提醒格式无效"), "invalid alert format notifies user"); +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, exact code skips search, and cleared input invalidates in-flight response. +// 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({}); @@ -264,6 +274,14 @@ 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") ?? []) { diff --git a/tests/test_mcp_integration.py b/tests/test_mcp_integration.py index e23fb71..4e50ca1 100644 --- a/tests/test_mcp_integration.py +++ b/tests/test_mcp_integration.py @@ -181,10 +181,25 @@ def read_until(target_id): finally: proc.kill() - core = _by_id(INIT, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, extra_args=("--profile", "core")) + 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) == 18 - assert {"get_quote", "get_macro_anchors", "run_backtest"} <= core_names + 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(): diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index d207a8d..bde062d 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -293,6 +293,70 @@ def test_us_risk_screening_without_sec_env_stays_complete(monkeypatch): 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 { + "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: ( + { + "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"]) + + def test_us_risk_screening_truncated_sec_marks_incomplete_and_keeps_flags(monkeypatch): monkeypatch.setenv("SEC_USER_AGENT", "test-app test@example.com") diff --git a/tests/test_signal_tracker.py b/tests/test_signal_tracker.py index bc88f19..2b755e8 100644 --- a/tests/test_signal_tracker.py +++ b/tests/test_signal_tracker.py @@ -725,6 +725,77 @@ def fake_run(script, args, **kwargs): 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) + 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" + + # Once Yahoo's action-bearing history actually covers through 2026-11-24, 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_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 1054817..513ed56 100644 --- a/tests/test_value_data.py +++ b/tests/test_value_data.py @@ -1385,18 +1385,17 @@ def test_us_valuation_history_uses_filed_facts_and_split_adjusted_shares(monkeyp def test_us_dividends_splits_checked_requires_verified_history_and_no_cache(monkeypatch): from tools import value_data - # 1. Non-empty action-bearing history with zero splits -> splits_checked=True, splits=[] + # 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], "Stock Splits": [0.0, 0.0]}, - index=pd.DatetimeIndex(["2026-08-01", "2026-09-01"], tz="America/New_York", name="Date"), + {"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( - dividends=pd.Series([0.25], index=pd.DatetimeIndex(["2026-08-01"], tz="America/New_York", name="Date")), history=ok_history, info={"currentPrice": 100.0, "currency": "USD"}, calendar={}, @@ -1406,35 +1405,38 @@ def ok_history(**kwargs): 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_current_through"] == res["as_of"] + 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 + # 2. Empty DataFrame returned by failed history request must NOT set splits_checked=True or history_current_through ticker_empty = Namespace( - dividends=ticker_ok.dividends, history=lambda **kw: pd.DataFrame(), info=ticker_ok.info, - calendar={}, + 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 + # 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( - dividends=ticker_ok.dividends, history=boom, info=ticker_ok.info, - calendar={}, + 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/tools/backtest.py b/tools/backtest.py index 2fce098..783b5a9 100644 --- a/tools/backtest.py +++ b/tools/backtest.py @@ -1193,6 +1193,13 @@ def process_exits(ts, date_str: str) -> set[str]: # 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 @@ -1226,13 +1233,14 @@ def process_exits(ts, date_str: str) -> set[str]: target_val = port_value * cfg["weights"][sym] cur_val = holdings[sym]["shares"] * px if cur_val > target_val: + pending_dca.pop(sym, None) 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) - # Buy underweight positions + # Buy underweight positions; only clear pending DCA for symbols actually tradable/satisfied for sym in symbols: if sym in exited_alloc or sym in pending_exits: continue @@ -1248,18 +1256,16 @@ def process_exits(ts, date_str: str) -> set[str]: if deficit > 0: if not is_tradable(row, "buy"): blocked_orders += 1 - elif buy_amount(sym, deficit, row, date_str, reason): - initially_allocated.add(sym) + else: + if buy_amount(sym, deficit, row, date_str, reason): + initially_allocated.add(sym) + pending_dca.pop(sym, None) + else: + pending_dca.pop(sym, None) rebalanced_today = True - pending_dca.clear() - # Deploy fresh & retained blocked DCA budgets whenever rebalance did not already deploy them + # Deploy fresh & retained blocked DCA budgets whenever rebalance did not run on this bar if not rebalanced_today: - 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] for sym in list(pending_dca.keys()): if sym in exited_alloc or sym in pending_exits: pending_dca.pop(sym, None) diff --git a/tools/diagnostics.py b/tools/diagnostics.py index b889177..8f22e3f 100644 --- a/tools/diagnostics.py +++ b/tools/diagnostics.py @@ -20,7 +20,6 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) from _subproc import error_message, json_safe, utf8_stdio # noqa: E402 from capabilities import ALL_MARKETS # noqa: E402 -from sec_edgar import identity as _sec_identity # noqa: E402 # provider -> (import_name, required_env_vars, markets, note) PROVIDERS = { @@ -162,6 +161,8 @@ 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"]: + from sec_edgar import identity as _sec_identity + try: _sec_identity() except ValueError as exc: diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 41bb679..b263616 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -349,28 +349,75 @@ def check_us_insider_trades(symbol: str, *, run=None) -> dict: result["truncated"] = truncated result["warnings"] = sec_warnings result["available"] = not truncated and not sec_warnings - sales = [ + raw_sales = [ tx for tx in data["transactions"] if str(tx.get("code") or tx.get("transaction_code") or "").upper() == "S" or str(tx.get("action") or "").lower() == "sell" ] - result["sales_90d"] = len(sales) - if len(sales) >= 6: + has_amendments = any(str(tx.get("form") or "").upper() == "4/A" for tx in data["transactions"]) or any( + "amendment" in w.lower() or "double-count" in w.lower() for w in sec_warnings + ) + + def _sale_sig(tx: dict) -> tuple: + owners = tx.get("owners") + if isinstance(owners, list) and owners: + owner_key = tuple(sorted(str(o.get("cik") or o.get("name") or "") for o in owners if isinstance(o, dict))) + else: + owner_key = (str(tx.get("owner") or tx.get("insider") or ""),) + return ( + owner_key, + 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"), + ) + + # Deduplicate Form 4/A rows that repeat an already-counted transaction from another accession. + originals = [tx for tx in raw_sales if str(tx.get("form") or "").upper() != "4/A"] + amended = [tx for tx in raw_sales if str(tx.get("form") or "").upper() == "4/A"] + seen_counts: dict[tuple, int] = {} + for tx in originals: + sig = _sale_sig(tx) + seen_counts[sig] = seen_counts.get(sig, 0) + 1 + unique_amended = 0 + amended_by_acc: dict[str, list[dict]] = {} + for tx in amended: + acc = str(tx.get("accession") or f"__amend_{id(tx)}") + amended_by_acc.setdefault(acc, []).append(tx) + for acc_rows in amended_by_acc.values(): + acc_sig_counts: dict[tuple, int] = {} + for tx in acc_rows: + sig = _sale_sig(tx) + acc_sig_counts[sig] = acc_sig_counts.get(sig, 0) + 1 + for sig, cnt in acc_sig_counts.items(): + already = seen_counts.get(sig, 0) + if cnt > already: + unique_amended += cnt - already + seen_counts[sig] = cnt + + dedup_sales = len(originals) + unique_amended + result["sales_90d"] = dedup_sales + result["amendments_present"] = has_amendments + # Only trigger high-severity buy veto when confirmed non-amended Form 4 sales reach threshold; + # when Form 4/A amendments could still revise/duplicate fields, cap at medium severity. + if len(originals) >= 6 or (not has_amendments and dedup_sales >= 6): result["flags"].append( { "category": "insider", "severity": "high", - "description": f"近90日 SEC Form 4 记录到 {len(sales)} 笔内部人卖出", + "description": f"近90日 SEC Form 4 记录到 {dedup_sales} 笔内部人卖出", "source": "data", } ) - elif len(sales) >= 3: + 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 记录到 {len(sales)} 笔内部人卖出", + "description": f"近90日 SEC Form 4 记录到 {dedup_sales} 笔内部人卖出{note}", "source": "data", } ) diff --git a/tools/signal_tracker.py b/tools/signal_tracker.py index af26eb2..82d1683 100644 --- a/tools/signal_tracker.py +++ b/tools/signal_tracker.py @@ -314,9 +314,10 @@ def _verify_no_corporate_action(rec: dict, bars: list, anchor_idx: int, has_pric if any(any(marker in w for marker in blocked_markers) for w in warnings): return False - # Verify fresh history coverage through at least last_date (do not trust request-time `as_of`). + # 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)) @@ -335,6 +336,15 @@ def _verify_no_corporate_action(rec: dict, bars: list, anchor_idx: int, has_pric 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 []) diff --git a/tools/value_data.py b/tools/value_data.py index 8bdbaca..f302bc5 100644 --- a/tools/value_data.py +++ b/tools/value_data.py @@ -955,7 +955,8 @@ def load_dataset(key, fetch): "market": market, "as_of": today.isoformat(), "cache_bypassed": no_cache, - "history_current_through": today.isoformat() if no_cache else None, + "history_covered_from": None, + "history_current_through": None, "yield_basis": "cash paid per share in trailing 365 days / latest price, before tax; nominal source cash amounts", } if market == "A": @@ -997,6 +998,8 @@ def load_dataset(key, fetch): price_as_of=quote.get("as_of"), splits=splits, splits_checked=splits_checked, + # Eastmoney stock_fhps_detail_em is a live corporate-action registry query when --no-cache is set. + history_current_through=today.isoformat() if (no_cache and rows) else None, ) else: import yfinance as yf @@ -1044,6 +1047,37 @@ def load_dataset(key, fetch): "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") + return { + "cash": cash_rows, + "splits": split_rows, + "covered_from": covered_from, + "covered_through": covered_through, + } + def cash_history(): raw = ticker.dividends frame = ( @@ -1053,31 +1087,35 @@ def cash_history(): ) return frame.reset_index() - def split_history_verified(): - # Fetch action-bearing price history with raise_errors=True so failed yfinance requests - # (which ticker.splits can silently turn into an empty Series) never set splits_checked=True. - if not callable(getattr(ticker, "history", None)): - raise RuntimeError("split history requires ticker.history") - 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: - raise RuntimeError("yfinance history returned no action-bearing price frame") - splits_series = hist["Stock Splits"] - nonzero = splits_series[splits_series.notna() & (splits_series != 0)] - frame = nonzero.to_frame("ratio").reset_index() - if len(frame.columns) >= 1 and frame.columns[0] != "Date": - frame = frame.rename(columns={frame.columns[0]: "Date"}) - return frame - - capture(sources, "cash", lambda: load_dataset(f"{market.lower()}-dividend-cash:{symbol}", cash_history)) splits_ok = False splits_rows = [] - try: - splits_rows = load_dataset(f"{market.lower()}-splits:{symbol}", split_history_verified) - splits_ok = isinstance(splits_rows, list) - except Exception: - splits_ok = False + covered_from = None + covered_through = None + paid = [] + used_actions_bundle = False + if callable(getattr(ticker, "history", None)): + bundle_key = f"{market.lower()}-actions:{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) + ): + paid = bundle["cash"] + splits_rows = bundle["splits"] + splits_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"] @@ -1104,6 +1142,8 @@ def split_history_verified(): price=price, splits=splits, splits_checked=splits_ok, + 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() From 6114d9f6123453239c408f2d7a5f0960015e521d Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Thu, 26 Nov 2026 23:51:39 +0800 Subject: [PATCH 05/37] fix: keep A-share keyless unverified without allotment coverage, check capital gains, reconcile Form 4/A reclassifications, reserve blocked DCA cash, and guard SEC import --- docs/tool-behavior.md | 2 +- tests/test_backtest_portfolio.py | 62 ++++++++++++++ tests/test_diagnostics.py | 19 +++++ tests/test_risk_screening.py | 39 +++++++++ tests/test_signal_tracker.py | 97 +++++++++++++++++++++- tools/backtest.py | 36 ++++++-- tools/diagnostics.py | 7 +- tools/risk_screening.py | 136 ++++++++++++++++++++++++------- tools/signal_tracker.py | 38 +++++---- tools/value_data.py | 28 ++++++- 10 files changed, 404 insertions(+), 60 deletions(-) diff --git a/docs/tool-behavior.md b/docs/tool-behavior.md index 55f3d6e..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 可提供。无 `adjustment_factor` 时,仅当全部 K 线同属 `qfq`/`total_return`、记录价严格落在锚点 K 线 `[low, high]` 区间内、且 `get_dividends` 绕过 24 小时缓存实时核验(`--no-cache`,`cache_bypassed=true` 且 `history_current_through` 覆盖至评估末日)、返回非空历史与经错误上报路径验证的 `splits_checked=true`、无历史缺失/截断告警,且确认区间内无已实施或已公告的分红/拆合股/送转事件时,允许按 `factor=1.0` 结算并在 `evaluation_price_basis` 标注 `verification=no_corporate_action_verified`;发生除权除息/拆股、历史缺失告警、区间未完整覆盖、查询失败或口径未知时仍返回 `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/tests/test_backtest_portfolio.py b/tests/test_backtest_portfolio.py index 32b3b5b..fe5eefc 100644 --- a/tests/test_backtest_portfolio.py +++ b/tests/test_backtest_portfolio.py @@ -290,3 +290,65 @@ def test_rebalance_plus_dca_retains_blocked_symbol_budget_until_tradable(): 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_diagnostics.py b/tests/test_diagnostics.py index 0e3de31..b841d1d 100644 --- a/tests/test_diagnostics.py +++ b/tests/test_diagnostics.py @@ -209,6 +209,25 @@ def test_cli_returns_structured_json_when_requests_is_unavailable(self): 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 "") + if __name__ == "__main__": import subprocess diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index bde062d..480eb12 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -356,6 +356,45 @@ def fake_run(script, args, **kwargs): 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: ( + { + "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"]) + def test_us_risk_screening_truncated_sec_marks_incomplete_and_keeps_flags(monkeypatch): monkeypatch.setenv("SEC_USER_AGENT", "test-app test@example.com") diff --git a/tests/test_signal_tracker.py b/tests/test_signal_tracker.py index 2b755e8..97d2c91 100644 --- a/tests/test_signal_tracker.py +++ b/tests/test_signal_tracker.py @@ -615,6 +615,9 @@ def fake_run(script, args, **kwargs): "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": [], @@ -653,6 +656,9 @@ def test_keyless_qfq_skips_when_ex_dividend_or_split_or_empty_history_or_price_o "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": [], @@ -662,6 +668,9 @@ def test_keyless_qfq_skips_when_ex_dividend_or_split_or_empty_history_or_price_o {**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}, @@ -713,6 +722,9 @@ def fake_run(script, args, **kwargs): "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": [], @@ -738,6 +750,7 @@ 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 @@ -781,7 +794,26 @@ def bridge(script, args, **kwargs): assert res["closed"] == 0 assert res["results"][0]["outcome"] == "skipped_price_basis" - # Once Yahoo's action-bearing history actually covers through 2026-11-24, verification succeeds + # 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]}, @@ -796,6 +828,69 @@ def bridge(script, args, **kwargs): 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/tools/backtest.py b/tools/backtest.py index 783b5a9..f0cd426 100644 --- a/tools/backtest.py +++ b/tools/backtest.py @@ -1220,6 +1220,23 @@ def process_exits(ts, date_str: str) -> set[str]: 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: @@ -1233,14 +1250,17 @@ def process_exits(ts, date_str: str) -> set[str]: target_val = port_value * cfg["weights"][sym] cur_val = holdings[sym]["shares"] * px if cur_val > target_val: - pending_dca.pop(sym, None) 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) - # Buy underweight positions; only clear pending DCA for symbols actually tradable/satisfied + + # 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 @@ -1257,11 +1277,11 @@ def process_exits(ts, date_str: str) -> set[str]: if not is_tradable(row, "buy"): blocked_orders += 1 else: - if buy_amount(sym, deficit, row, date_str, reason): + 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) - else: - pending_dca.pop(sym, None) + pending_dca.pop(sym, None) rebalanced_today = True # Deploy fresh & retained blocked DCA budgets whenever rebalance did not run on this bar @@ -1282,8 +1302,8 @@ def process_exits(ts, date_str: str) -> set[str]: if not is_tradable(row, "buy"): blocked_orders += 1 continue - buy_amount(sym, budget, row, date_str, f"定期定投 ({cfg['dca']['frequency']})") - pending_dca.pop(sym, None) + 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: diff --git a/tools/diagnostics.py b/tools/diagnostics.py index 8f22e3f..ce03f01 100644 --- a/tools/diagnostics.py +++ b/tools/diagnostics.py @@ -161,13 +161,16 @@ 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"]: - from sec_edgar import identity as _sec_identity - 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 diff --git a/tools/risk_screening.py b/tools/risk_screening.py index b263616..5511d80 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -349,24 +349,23 @@ def check_us_insider_trades(symbol: str, *, run=None) -> dict: result["truncated"] = truncated result["warnings"] = sec_warnings result["available"] = not truncated and not sec_warnings - raw_sales = [ - tx - for tx in data["transactions"] - if str(tx.get("code") or tx.get("transaction_code") or "").upper() == "S" - or str(tx.get("action") or "").lower() == "sell" - ] - has_amendments = any(str(tx.get("form") or "").upper() == "4/A" for tx in data["transactions"]) or any( - "amendment" in w.lower() or "double-count" in w.lower() for w in sec_warnings - ) + txs = [tx for tx in data["transactions"] if isinstance(tx, dict)] - def _sale_sig(tx: dict) -> tuple: + def _is_sell(tx: dict) -> bool: + return ( + str(tx.get("code") or tx.get("transaction_code") or "").upper() == "S" + or str(tx.get("action") or "").lower() == "sell" + ) + + def _owner_key(tx: dict) -> tuple: owners = tx.get("owners") if isinstance(owners, list) and owners: - owner_key = tuple(sorted(str(o.get("cik") or o.get("name") or "") for o in owners if isinstance(o, dict))) - else: - owner_key = (str(tx.get("owner") or tx.get("insider") or ""),) + 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 _exact_sig(tx: dict) -> tuple: return ( - owner_key, + _owner_key(tx), str(tx.get("transaction_date") or tx.get("date") or ""), str(tx.get("security") or ""), bool(tx.get("derivative")), @@ -374,35 +373,110 @@ def _sale_sig(tx: dict) -> tuple: tx.get("price"), ) - # Deduplicate Form 4/A rows that repeat an already-counted transaction from another accession. - originals = [tx for tx in raw_sales if str(tx.get("form") or "").upper() != "4/A"] - amended = [tx for tx in raw_sales if str(tx.get("form") or "").upper() == "4/A"] + def _base_sig(tx: dict) -> tuple: + return ( + _owner_key(tx), + str(tx.get("transaction_date") or tx.get("date") or ""), + str(tx.get("security") or ""), + bool(tx.get("derivative")), + ) + + 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 + ) + + # Start with original Form 4 sells, then reconcile Form 4/A amendments before counting. + active_orig_sells = [tx for tx in all_orig if _is_sell(tx)] + reclassified_indices: set[int] = set() + affected_owners: set[tuple] = set() + unaligned_global = has_amendments and not all_amend + + # 1. Reconcile non-sell 4/A rows (e.g., an S transaction corrected to Gift G): remove superseded original sells. + for tx in all_amend: + if _is_sell(tx): + continue + exact = _exact_sig(tx) + base = _base_sig(tx) + matched_idx = next( + ( + i + for i, orig in enumerate(active_orig_sells) + if i not in reclassified_indices and _exact_sig(orig) == exact + ), + None, + ) + if matched_idx is None: + matched_idx = next( + ( + i + for i, orig in enumerate(active_orig_sells) + if i not in reclassified_indices + and _base_sig(orig) == base + and tx.get("shares") is not None + and orig.get("shares") == tx.get("shares") + ), + None, + ) + if matched_idx is None and base[1]: + matched_idx = next( + ( + i + for i, orig in enumerate(active_orig_sells) + if i not in reclassified_indices and _base_sig(orig) == base + ), + None, + ) + if matched_idx is not None: + reclassified_indices.add(matched_idx) + else: + ok = _owner_key(tx) + if ok != ("",): + affected_owners.add(ok) + else: + unaligned_global = True + + confirmed_orig_sells = [tx for i, tx in enumerate(active_orig_sells) if i not in reclassified_indices] + + # 2. Deduplicate Form 4/A sell rows against confirmed original sells; flag unaligned 4/A sells. seen_counts: dict[tuple, int] = {} - for tx in originals: - sig = _sale_sig(tx) + for tx in confirmed_orig_sells: + sig = _exact_sig(tx) seen_counts[sig] = seen_counts.get(sig, 0) + 1 - unique_amended = 0 + unique_amended_sells = 0 amended_by_acc: dict[str, list[dict]] = {} - for tx in amended: + for tx in all_amend: + if not _is_sell(tx): + continue acc = str(tx.get("accession") or f"__amend_{id(tx)}") amended_by_acc.setdefault(acc, []).append(tx) for acc_rows in amended_by_acc.values(): acc_sig_counts: dict[tuple, int] = {} + acc_sample: dict[tuple, dict] = {} for tx in acc_rows: - sig = _sale_sig(tx) + sig = _exact_sig(tx) acc_sig_counts[sig] = acc_sig_counts.get(sig, 0) + 1 + acc_sample[sig] = tx for sig, cnt in acc_sig_counts.items(): already = seen_counts.get(sig, 0) if cnt > already: - unique_amended += cnt - already + unique_amended_sells += cnt - already seen_counts[sig] = cnt - - dedup_sales = len(originals) + unique_amended + ok = _owner_key(acc_sample[sig]) + if ok != ("",): + affected_owners.add(ok) + else: + unaligned_global = True + + dedup_sales = len(confirmed_orig_sells) + unique_amended_sells + unaffected_orig_sells = ( + 0 if unaligned_global else sum(1 for tx in confirmed_orig_sells if _owner_key(tx) not in affected_owners) + ) result["sales_90d"] = dedup_sales result["amendments_present"] = has_amendments - # Only trigger high-severity buy veto when confirmed non-amended Form 4 sales reach threshold; - # when Form 4/A amendments could still revise/duplicate fields, cap at medium severity. - if len(originals) >= 6 or (not has_amendments and dedup_sales >= 6): + # 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", @@ -412,7 +486,11 @@ def _sale_sig(tx: dict) -> tuple: } ) elif dedup_sales >= 3: - note = "(含 Form 4/A 修订申报,未因可能重复计数触发一票否决)" if has_amendments and dedup_sales >= 6 else "" + note = ( + "(含 Form 4/A 修订申报,未因未对齐/可能重复记录触发一票否决)" + if has_amendments and dedup_sales >= 6 + else "" + ) result["flags"].append( { "category": "insider", diff --git a/tools/signal_tracker.py b/tools/signal_tracker.py index 82d1683..4133bef 100644 --- a/tools/signal_tracker.py +++ b/tools/signal_tracker.py @@ -299,10 +299,15 @@ def _verify_no_corporate_action(rec: dict, bars: list, anchor_idx: int, has_pric return False if not div_data.get("source"): return False - # Require fresh, non-cached corporate-action history and verified split coverage. + # 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: + 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 = ( @@ -366,21 +371,22 @@ def _verify_no_corporate_action(rec: dict, bars: list, anchor_idx: int, has_pric if not has_price_date and ex_day == anchor_date: return False - splits = div_data.get("splits") - if splits is not None: - if not isinstance(splits, list): - return False - for sp in splits: - if not isinstance(sp, dict): - return False - ex_date = sp.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: + 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 diff --git a/tools/value_data.py b/tools/value_data.py index f302bc5..ccfe5bf 100644 --- a/tools/value_data.py +++ b/tools/value_data.py @@ -957,6 +957,9 @@ def load_dataset(key, fetch): "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": @@ -991,6 +994,8 @@ def load_dataset(key, fetch): } quote = run_tool("stock_data.py", ["quote", symbol]) or {} price = number(quote.get("price")) + # 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", @@ -998,8 +1003,8 @@ def load_dataset(key, fetch): price_as_of=quote.get("as_of"), splits=splits, splits_checked=splits_checked, - # Eastmoney stock_fhps_detail_em is a live corporate-action registry query when --no-cache is set. - history_current_through=today.isoformat() if (no_cache and rows) else None, + history_current_through=None, + corporate_actions_complete=False, ) else: import yfinance as yf @@ -1071,9 +1076,13 @@ def verified_actions_bundle(): 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, } @@ -1088,13 +1097,15 @@ def cash_history(): return frame.reset_index() 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:{symbol}" + 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: @@ -1105,10 +1116,13 @@ def cash_history(): 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 @@ -1135,6 +1149,11 @@ def cash_history(): 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", @@ -1142,6 +1161,9 @@ def cash_history(): 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, ) From 7c4f589e490aed1c8a8cb53ce3dc9d3cd5079f5e Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 00:22:01 +0800 Subject: [PATCH 06/37] fix: make Form 4/A reconciliation idempotent and surface real SEC failure reason in diagnostics --- tests/test_diagnostics.py | 3 + tests/test_risk_screening.py | 84 +++++++++++++++++++++++ tools/diagnostics.py | 6 +- tools/risk_screening.py | 129 +++++++++++++++++++++-------------- 4 files changed, 167 insertions(+), 55 deletions(-) diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py index b841d1d..acf06d0 100644 --- a/tests/test_diagnostics.py +++ b/tests/test_diagnostics.py @@ -171,6 +171,8 @@ def test_sec_user_agent_without_email_is_reported_invalid(self, monkeypatch): 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 = [] @@ -227,6 +229,7 @@ def fail_sec_import(name, *args, **kwargs): 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__": diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 480eb12..a794412 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -395,6 +395,90 @@ def fake_run(script, args, **kwargs): 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: ( + { + "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: ( + { + "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: ( + { + "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 test_us_risk_screening_truncated_sec_marks_incomplete_and_keeps_flags(monkeypatch): monkeypatch.setenv("SEC_USER_AGENT", "test-app test@example.com") diff --git a/tools/diagnostics.py b/tools/diagnostics.py index ce03f01..88b4009 100644 --- a/tools/diagnostics.py +++ b/tools/diagnostics.py @@ -204,8 +204,10 @@ def diagnose(market: str = "all", probe: bool = False) -> dict: top_warnings.append( "No search engine configured (TAVILY/BRAVE/SERPAPI/BOCHA/SEARXNG); news search tools unavailable" ) - if not any(s["name"] == "sec_edgar" and s["available"] for s in all_services): - top_warnings.append("SEC_USER_AGENT not set — US 13F / Form 4 / SEC filings 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": { diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 5511d80..0e888c0 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -393,57 +393,66 @@ def _base_sig(tx: dict) -> tuple: affected_owners: set[tuple] = set() unaligned_global = has_amendments and not all_amend - # 1. Reconcile non-sell 4/A rows (e.g., an S transaction corrected to Gift G): remove superseded original sells. + # 1. Reconcile non-sell 4/A rows (e.g., an S transaction corrected to Gift G) idempotently per accession. + # Require matching (owner, date, security, derivative) AND shares so an unrelated same-date gift never drops a sale. + non_sell_by_acc: dict[str, list[dict]] = {} for tx in all_amend: if _is_sell(tx): continue - exact = _exact_sig(tx) - base = _base_sig(tx) - matched_idx = next( - ( - i - for i, orig in enumerate(active_orig_sells) - if i not in reclassified_indices and _exact_sig(orig) == exact - ), - None, - ) - if matched_idx is None: - matched_idx = next( - ( - i - for i, orig in enumerate(active_orig_sells) - if i not in reclassified_indices - and _base_sig(orig) == base - and tx.get("shares") is not None - and orig.get("shares") == tx.get("shares") - ), - None, - ) - if matched_idx is None and base[1]: - matched_idx = next( - ( - i - for i, orig in enumerate(active_orig_sells) - if i not in reclassified_indices and _base_sig(orig) == base - ), - None, - ) - if matched_idx is not None: - reclassified_indices.add(matched_idx) - else: - ok = _owner_key(tx) - if ok != ("",): - affected_owners.add(ok) - else: - unaligned_global = True + acc = str(tx.get("accession") or f"__amend_nonsell_{id(tx)}") + non_sell_by_acc.setdefault(acc, []).append(tx) + + for acc_rows in non_sell_by_acc.values(): + acc_matched: set[int] = set() + for tx in acc_rows: + exact = _exact_sig(tx) + base = _base_sig(tx) + shares = tx.get("shares") + has_identity = base[0] != ("",) and bool(base[1]) and shares is not None + matched_idx = None + if has_identity: + matched_idx = next( + ( + i + for i, orig in enumerate(active_orig_sells) + if i not in acc_matched and _exact_sig(orig) == exact + ), + None, + ) + if matched_idx is None: + matched_idx = next( + ( + i + for i, orig in enumerate(active_orig_sells) + if i not in acc_matched and _base_sig(orig) == base and orig.get("shares") == shares + ), + None, + ) + if matched_idx is not None: + acc_matched.add(matched_idx) + reclassified_indices.add(matched_idx) + elif not has_identity: + # Missing owner/date/shares prevents confirming linkage; keep original sales and flag uncertainty. + ok = _owner_key(tx) + if ok != ("",): + affected_owners.add(ok) + else: + unaligned_global = True + # Otherwise (valid identity & shares that match no original sale), treat as an unrelated non-sell filing. confirmed_orig_sells = [tx for i, tx in enumerate(active_orig_sells) if i not in reclassified_indices] - # 2. Deduplicate Form 4/A sell rows against confirmed original sells; flag unaligned 4/A sells. - seen_counts: dict[tuple, int] = {} + # 2. Match Form 4/A sell rows against confirmed original sells by base signature (owner, date, security, derivative) + # so restatements (e.g. revised price/shares) never inflate sales_90d; keep truly separate transactions idempotently. + orig_base_counts: dict[tuple, int] = {} + orig_exact_counts: dict[tuple, int] = {} for tx in confirmed_orig_sells: - sig = _exact_sig(tx) - seen_counts[sig] = seen_counts.get(sig, 0) + 1 + b = _base_sig(tx) + e = _exact_sig(tx) + orig_base_counts[b] = orig_base_counts.get(b, 0) + 1 + orig_exact_counts[e] = orig_exact_counts.get(e, 0) + 1 + + max_base_seen = dict(orig_base_counts) unique_amended_sells = 0 amended_by_acc: dict[str, list[dict]] = {} for tx in all_amend: @@ -451,19 +460,33 @@ def _base_sig(tx: dict) -> tuple: continue acc = str(tx.get("accession") or f"__amend_{id(tx)}") amended_by_acc.setdefault(acc, []).append(tx) + for acc_rows in amended_by_acc.values(): - acc_sig_counts: dict[tuple, int] = {} - acc_sample: dict[tuple, dict] = {} + acc_base_counts: dict[tuple, int] = {} + acc_exact_counts: dict[tuple, int] = {} + acc_sample_base: dict[tuple, dict] = {} + acc_sample_exact: dict[tuple, dict] = {} for tx in acc_rows: - sig = _exact_sig(tx) - acc_sig_counts[sig] = acc_sig_counts.get(sig, 0) + 1 - acc_sample[sig] = tx - for sig, cnt in acc_sig_counts.items(): - already = seen_counts.get(sig, 0) + b = _base_sig(tx) + e = _exact_sig(tx) + acc_base_counts[b] = acc_base_counts.get(b, 0) + 1 + acc_exact_counts[e] = acc_exact_counts.get(e, 0) + 1 + acc_sample_base[b] = tx + acc_sample_exact[e] = tx + for b, cnt in acc_base_counts.items(): + already = max_base_seen.get(b, 0) if cnt > already: unique_amended_sells += cnt - already - seen_counts[sig] = cnt - ok = _owner_key(acc_sample[sig]) + max_base_seen[b] = cnt + ok = _owner_key(acc_sample_base[b]) + if ok != ("",): + affected_owners.add(ok) + else: + unaligned_global = True + for e, cnt in acc_exact_counts.items(): + if cnt > orig_exact_counts.get(e, 0): + # Restatement with changed price/shares or new amended sell: mark owner uncertain for buy-veto threshold. + ok = _owner_key(acc_sample_exact[e]) if ok != ("",): affected_owners.add(ok) else: From 9aa92dc8c12c6fd2c4aa4c9ba2711e535ee6bcc7 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 00:43:45 +0800 Subject: [PATCH 07/37] fix: distinguish Form 4/A additions vs corrections with two-pass original-filing reconciliation --- tests/test_risk_screening.py | 109 ++++++++++++++ tools/risk_screening.py | 281 ++++++++++++++++++++++++++--------- 2 files changed, 316 insertions(+), 74 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index a794412..2fe962e 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -479,6 +479,115 @@ def fake_run(script, args, **kwargs): 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: ( + { + "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."}, + footnote_refs=["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["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."}, + footnote_refs=["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 not True + + # 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."}, + footnote_refs=["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 + + # 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) + add_s2 = dict(one_orig[0], form="4/A", accession="0001-26-000071", shares=300, price=12.0) + 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"]) + def test_us_risk_screening_truncated_sec_marks_incomplete_and_keeps_flags(monkeypatch): monkeypatch.setenv("SEC_USER_AGENT", "test-app test@example.com") diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 0e888c0..06ae69e 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -5,6 +5,7 @@ import json import math import os +import re import sys from concurrent.futures import Future, ThreadPoolExecutor from datetime import timedelta @@ -351,11 +352,11 @@ def check_us_insider_trades(symbol: str, *, run=None) -> dict: result["available"] = not truncated and not sec_warnings txs = [tx for tx in data["transactions"] if isinstance(tx, dict)] + def _tx_code(tx: dict) -> str: + return str(tx.get("code") or tx.get("transaction_code") or "").upper() + def _is_sell(tx: dict) -> bool: - return ( - str(tx.get("code") or tx.get("transaction_code") or "").upper() == "S" - or str(tx.get("action") or "").lower() == "sell" - ) + return _tx_code(tx) == "S" or str(tx.get("action") or "").lower() == "sell" def _owner_key(tx: dict) -> tuple: owners = tx.get("owners") @@ -381,20 +382,67 @@ def _base_sig(tx: dict) -> tuple: bool(tx.get("derivative")), ) + _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+)?transaction|" + r"late[- ]?report(?:ed|ing)|补报|漏报|遗漏)", + re.IGNORECASE, + ) + _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)|更正|修正|重分类|误报)", + re.IGNORECASE, + ) + + def _amendment_text(tx: dict) -> str: + parts: list[str] = [] + footnotes = tx.get("footnotes") + refs = tx.get("footnote_refs") + if isinstance(footnotes, dict) and footnotes: + if isinstance(refs, list) and refs: + parts.extend(str(footnotes.get(r) or "") for r in refs if footnotes.get(r)) + else: + parts.extend(str(v) for v in footnotes.values() if v) + elif isinstance(footnotes, str) and footnotes: + parts.append(footnotes) + for key in ("remarks", "amendment_reason", "note"): + if tx.get(key): + parts.append(str(tx[key])) + return " ".join(parts) + + def _amendment_intent(tx: dict) -> tuple[bool, bool]: + text = _amendment_text(tx) + if not text: + return False, False + return bool(_ADDITION_RE.search(text)), bool(_CORRECTION_RE.search(text)) + 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 ) - # Start with original Form 4 sells, then reconcile Form 4/A amendments before counting. + # Start with original Form 4 sells and original Form 4 non-sells. active_orig_sells = [tx for tx in all_orig if _is_sell(tx)] + orig_non_sells = [tx for tx in all_orig if not _is_sell(tx)] reclassified_indices: set[int] = set() affected_owners: set[tuple] = set() unaligned_global = has_amendments and not all_amend - # 1. Reconcile non-sell 4/A rows (e.g., an S transaction corrected to Gift G) idempotently per accession. - # Require matching (owner, date, security, derivative) AND shares so an unrelated same-date gift never drops a sale. + def _mark_uncertain(tx: dict) -> None: + nonlocal unaligned_global + ok = _owner_key(tx) + if ok != ("",): + affected_owners.add(ok) + else: + unaligned_global = True + + # 1. Reconcile non-sell 4/A rows idempotently per accession in two passes: + # - First skip rows that match an existing original non-sell Form 4 (e.g., footnote-only amendment to a Form 4 gift). + # - Pass A resolves unambiguous exact (base, shares, price) and unique (base, shares) matches across all accessions. + # - Pass B resolves remaining rows (blank-price multi-candidate links or explicit corrections with changed shares), + # retaining ambiguous candidates and flagging uncertainty rather than deleting an arbitrary sale. non_sell_by_acc: dict[str, list[dict]] = {} for tx in all_amend: if _is_sell(tx): @@ -402,58 +450,122 @@ def _base_sig(tx: dict) -> tuple: acc = str(tx.get("accession") or f"__amend_nonsell_{id(tx)}") non_sell_by_acc.setdefault(acc, []).append(tx) - for acc_rows in non_sell_by_acc.values(): + acc_nonsell_matched: dict[str, set[int]] = {} + deferred_nonsells: list[tuple[str, dict]] = [] + + for acc, acc_rows in non_sell_by_acc.items(): + orig_ns_matched: set[int] = set() acc_matched: set[int] = set() + acc_nonsell_matched[acc] = acc_matched for tx in acc_rows: - exact = _exact_sig(tx) + is_add, is_corr = _amendment_intent(tx) base = _base_sig(tx) + code = _tx_code(tx) shares = tx.get("shares") + # Match against original non-sell Form 4 filings first so amending a Form 4 gift never removes a sale. + ns_idx = next( + ( + i + for i, orig_ns in enumerate(orig_non_sells) + if i not in orig_ns_matched + and _base_sig(orig_ns) == base + and _tx_code(orig_ns) == code + and (shares is None or orig_ns.get("shares") == shares) + ), + None, + ) + if ns_idx is not None: + orig_ns_matched.add(ns_idx) + continue + if is_add and not is_corr: + # Explicitly newly added non-sell transaction (e.g., omitted gift): keep separate from sales. + continue + + exact = _exact_sig(tx) has_identity = base[0] != ("",) and bool(base[1]) and shares is not None - matched_idx = None + if has_identity and tx.get("price") is not None: + exact_cands = [ + i for i, orig in enumerate(active_orig_sells) if i not in acc_matched and _exact_sig(orig) == exact + ] + if exact_cands: + acc_matched.add(exact_cands[0]) + reclassified_indices.add(exact_cands[0]) + continue if has_identity: - matched_idx = next( - ( - i - for i, orig in enumerate(active_orig_sells) - if i not in acc_matched and _exact_sig(orig) == exact - ), - None, - ) - if matched_idx is None: - matched_idx = next( - ( - i - for i, orig in enumerate(active_orig_sells) - if i not in acc_matched and _base_sig(orig) == base and orig.get("shares") == shares - ), - None, - ) - if matched_idx is not None: - acc_matched.add(matched_idx) - reclassified_indices.add(matched_idx) - elif not has_identity: - # Missing owner/date/shares prevents confirming linkage; keep original sales and flag uncertainty. - ok = _owner_key(tx) - if ok != ("",): - affected_owners.add(ok) - else: - unaligned_global = True - # Otherwise (valid identity & shares that match no original sale), treat as an unrelated non-sell filing. + share_cands = [ + i + for i, orig in enumerate(active_orig_sells) + if i not in acc_matched and _base_sig(orig) == base and orig.get("shares") == shares + ] + if len(share_cands) == 1 or ( + len(share_cands) > 1 and len({active_orig_sells[i].get("price") for i in share_cands}) == 1 + ): + acc_matched.add(share_cands[0]) + reclassified_indices.add(share_cands[0]) + continue + if len(share_cands) > 1: + deferred_nonsells.append((acc, tx)) + continue + deferred_nonsells.append((acc, tx)) + + for acc, tx in deferred_nonsells: + acc_matched = acc_nonsell_matched[acc] + is_add, is_corr = _amendment_intent(tx) + base = _base_sig(tx) + shares = tx.get("shares") + has_identity = base[0] != ("",) and bool(base[1]) and shares is not None + if has_identity: + share_cands = [ + i + for i, orig in enumerate(active_orig_sells) + if i not in acc_matched and _base_sig(orig) == base and orig.get("shares") == shares + ] + if len(share_cands) > 1: + already_reclass = [i for i in share_cands if i in reclassified_indices] + if len(already_reclass) == 1: + # Successive correction omitting price links to the already-identified sale; do not drop another. + acc_matched.add(already_reclass[0]) + continue + # Ambiguous blank-price correction across distinct candidates: retain all candidates & flag uncertainty. + _mark_uncertain(tx) + continue + if is_corr and base[0] != ("",) and bool(base[1]): + # Explicit correction where shares/price changed (e.g. 6-share S corrected to 7-share G). + base_cands = [ + i for i, orig in enumerate(active_orig_sells) if i not in acc_matched and _base_sig(orig) == base + ] + if len(base_cands) == 1: + acc_matched.add(base_cands[0]) + reclassified_indices.add(base_cands[0]) + continue + already_reclass = [i for i in base_cands if i in reclassified_indices] + if len(already_reclass) == 1: + acc_matched.add(already_reclass[0]) + continue + _mark_uncertain(tx) + continue + if not has_identity: + _mark_uncertain(tx) + # Otherwise: valid non-sell row with different shares and no correction note -> unrelated gift; keep separate. confirmed_orig_sells = [tx for i, tx in enumerate(active_orig_sells) if i not in reclassified_indices] - # 2. Match Form 4/A sell rows against confirmed original sells by base signature (owner, date, security, derivative) - # so restatements (e.g. revised price/shares) never inflate sales_90d; keep truly separate transactions idempotently. - orig_base_counts: dict[tuple, int] = {} + # 2. Match Form 4/A sell rows against ALL original Form 4 sells (before gift reclassification) so: + # - Exact duplicates or share-matched price restatements never inflate sales_90d regardless of filing order; + # - Explicitly omitted/added sales and distinct newly disclosed (shares, price) sales are counted separately; + # - Identical newly added sales repeated across accessions are deduplicated idempotently by exact signature. orig_exact_counts: dict[tuple, int] = {} - for tx in confirmed_orig_sells: - b = _base_sig(tx) + orig_share_counts: dict[tuple, int] = {} + orig_base_counts: dict[tuple, int] = {} + for tx in active_orig_sells: e = _exact_sig(tx) - orig_base_counts[b] = orig_base_counts.get(b, 0) + 1 + s_key = (_base_sig(tx), tx.get("shares")) + b = _base_sig(tx) orig_exact_counts[e] = orig_exact_counts.get(e, 0) + 1 + orig_share_counts[s_key] = orig_share_counts.get(s_key, 0) + 1 + orig_base_counts[b] = orig_base_counts.get(b, 0) + 1 - max_base_seen = dict(orig_base_counts) - unique_amended_sells = 0 + max_added_exact: dict[tuple, int] = {} amended_by_acc: dict[str, list[dict]] = {} for tx in all_amend: if not _is_sell(tx): @@ -462,42 +574,58 @@ def _base_sig(tx: dict) -> tuple: amended_by_acc.setdefault(acc, []).append(tx) for acc_rows in amended_by_acc.values(): - acc_base_counts: dict[tuple, int] = {} - acc_exact_counts: dict[tuple, int] = {} - acc_sample_base: dict[tuple, dict] = {} - acc_sample_exact: dict[tuple, dict] = {} + used_orig_exact: dict[tuple, int] = {} + used_orig_share: dict[tuple, int] = {} + used_orig_base: dict[tuple, int] = {} + acc_added_exact: dict[tuple, int] = {} for tx in acc_rows: - b = _base_sig(tx) + is_add, is_corr = _amendment_intent(tx) e = _exact_sig(tx) - acc_base_counts[b] = acc_base_counts.get(b, 0) + 1 - acc_exact_counts[e] = acc_exact_counts.get(e, 0) + 1 - acc_sample_base[b] = tx - acc_sample_exact[e] = tx - for b, cnt in acc_base_counts.items(): - already = max_base_seen.get(b, 0) - if cnt > already: - unique_amended_sells += cnt - already - max_base_seen[b] = cnt - ok = _owner_key(acc_sample_base[b]) - if ok != ("",): - affected_owners.add(ok) - else: - unaligned_global = True - for e, cnt in acc_exact_counts.items(): - if cnt > orig_exact_counts.get(e, 0): - # Restatement with changed price/shares or new amended sell: mark owner uncertain for buy-veto threshold. - ok = _owner_key(acc_sample_exact[e]) - if ok != ("",): - affected_owners.add(ok) - else: - unaligned_global = True - + b = _base_sig(tx) + s_key = (b, tx.get("shares")) + + # Explicit omitted/added transaction: count as an addition (do not swallow into existing same-day sells). + if is_add and not is_corr: + acc_added_exact[e] = acc_added_exact.get(e, 0) + 1 + _mark_uncertain(tx) + continue + + # Exact duplicate of an original Form 4 sell (before reclassification). + if used_orig_exact.get(e, 0) < orig_exact_counts.get(e, 0): + used_orig_exact[e] = used_orig_exact.get(e, 0) + 1 + used_orig_share[s_key] = used_orig_share.get(s_key, 0) + 1 + used_orig_base[b] = used_orig_base.get(b, 0) + 1 + continue + + # Share-matched restatement (e.g., price revised on an original Form 4 sell): adds 0 rows. + if tx.get("shares") is not None and used_orig_share.get(s_key, 0) < orig_share_counts.get(s_key, 0): + used_orig_share[s_key] = used_orig_share.get(s_key, 0) + 1 + used_orig_base[b] = used_orig_base.get(b, 0) + 1 + _mark_uncertain(tx) + continue + + # Explicit correction changing share count of an original Form 4 sell: adds 0 rows, flags uncertainty. + if is_corr and used_orig_base.get(b, 0) < orig_base_counts.get(b, 0): + used_orig_base[b] = used_orig_base.get(b, 0) + 1 + _mark_uncertain(tx) + continue + + # Distinct sale first disclosed in this 4/A accession (different shares/price or new date/security). + acc_added_exact[e] = acc_added_exact.get(e, 0) + 1 + _mark_uncertain(tx) + + for e, cnt in acc_added_exact.items(): + if cnt > max_added_exact.get(e, 0): + max_added_exact[e] = cnt + + unique_amended_sells = sum(max_added_exact.values()) dedup_sales = len(confirmed_orig_sells) + unique_amended_sells unaffected_orig_sells = ( 0 if unaligned_global else sum(1 for tx in confirmed_orig_sells if _owner_key(tx) not in affected_owners) ) result["sales_90d"] = dedup_sales result["amendments_present"] = has_amendments + result["count_uncertain"] = bool(affected_owners or unaligned_global) # Only trigger high-severity buy veto when reconciled, unaffected original Form 4 sells reach threshold. if unaffected_orig_sells >= 6: result["flags"].append( @@ -625,6 +753,7 @@ def supplied(key): "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"]: @@ -632,6 +761,10 @@ def supplied(key): else: if extra.get("truncated"): warnings.append("SEC Form 4 filings were truncated at top 10; insider sales coverage is incomplete") + if extra.get("count_uncertain"): + warnings.append( + "SEC Form 4/A amendments include unlinked or ambiguous revisions; insider sale count is uncertain" + ) warnings.extend(extra.get("warnings") or []) checks["news_risks"] = {k: v for k, v in news.items() if k != "flags"} From 514362e258522c9f55aa6225b42a742ae9ebcab2 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 01:07:40 +0800 Subject: [PATCH 08/37] fix: align Form 4/A parser footnote_refs and remarks, enforce order-independent matching, and harden HKEX disclosure checks --- tests/test_risk_screening.py | 228 ++++++++++++++++++++++++- tools/risk_screening.py | 317 ++++++++++++++++++++++++----------- tools/sec_edgar.py | 2 + 3 files changed, 440 insertions(+), 107 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 2fe962e..247986f 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -510,11 +510,15 @@ def _run_us(tx_list): orig_gift, form="4/A", accession="0001-26-000051", - footnotes={"F1": "Filing amended solely to add gift recipient footnote."}, - footnote_refs=["F1"], + 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 @@ -527,12 +531,15 @@ def _run_us(tx_list): direction="other", shares=7, price=None, - footnotes={"F1": "Corrects previously misreported 6-share sale to a 7-share gift."}, - footnote_refs=["F1"], + 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 not True + 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 = [ @@ -546,8 +553,11 @@ def _run_us(tx_list): transaction_date="2026-10-08", shares=100, price=150.0, - footnotes={"F1": "Amends original Form 4 to report an inadvertently omitted third sale."}, - footnote_refs=["F1"], + 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 @@ -567,6 +577,12 @@ def _run_us(tx_list): 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 @@ -588,6 +604,204 @@ def _run_us(tx_list): 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 (Weaxs P2 & CodeRabbit Major 594): row-order invariance — each original sale matched at most once + orig_pair = [ + dict(six_orig[0], transaction_date="2026-10-21", shares=100, price=150.0), + dict(six_orig[0], transaction_date="2026-10-21", shares=50, price=160.0), + ] + amend_155 = dict(orig_pair[0], form="4/A", accession="0001-26-000091", price=155.0) + amend_150 = dict(orig_pair[0], form="4/A", accession="0001-26-000091", price=150.0) + assert _run_us(orig_pair + [amend_155, amend_150])["checks"]["insider_trades"]["sales_90d"] == 3 + assert _run_us(orig_pair + [amend_150, amend_155])["checks"]["insider_trades"]["sales_90d"] == 3 + + # 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: ( + { + "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_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): + # 1. Resumption / lifting of suspension must NOT trigger high-severity buy veto + res_resume = risk_screening.screen_risk( + "00700.HK", + "Tencent", + inputs={ + "quote": {"pe": 18, "pb": 3}, + "technical": {"signal_score": 65, "buy_signal": "BUY", "trend": {"overall": "bullish"}}, + }, + run=lambda script, args, **kw: ( + { + "announcements": [{"date": "2026-10-01", "title": "LIFTING OF SUSPENSION AND RESUMPTION OF TRADING"}], + "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. Provider-incomplete HKEX response (truncated=True with < 15 rows) marks unavailable & data_complete=False + res_trunc = risk_screening.screen_risk( + "00700.HK", + "Tencent", + inputs={ + "quote": {"pe": 18, "pb": 3}, + "technical": {"signal_score": 65, "buy_signal": "BUY", "trend": {"overall": "bullish"}}, + }, + 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") diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 06ae69e..a892454 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -277,7 +277,13 @@ def check_news_risks(symbol: str, name: str = "", *, run=None, market: str | Non return result -_HK_DISCLOSURE_HIGH = ("清盘", "winding up", "停牌", "trading halt", "suspension", "监管调查", "investigation") +_HK_DISCLOSURE_HIGH_ALWAYS = ("清盘", "winding up", "监管调查", "investigation") +_HK_DISCLOSURE_SUSPENSION = ("停牌", "trading halt", "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 = ( "盈警", "盈利警告", @@ -289,21 +295,36 @@ def check_news_risks(symbol: str, name: str = "", *, run=None, market: str | Non "减持", "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", "15"], timeout=25 + "value_data.py", ["announcements", symbol, "--category", "all", "--top", str(_HK_SCREEN_TOP)], timeout=25 ) - result = {"matches": [], "flags": [], "available": False} + 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 - result["available"] = True - for item in data["announcements"]: + 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 "") low = title.lower() sev = None - if any(k in low or k in title for k in _HK_DISCLOSURE_HIGH): + 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", "suspension")) + and "停牌" not in title.replace("复牌", "") + ) + if any(k in low or k in title for k in _HK_DISCLOSURE_HIGH_ALWAYS) or ( + not is_resumption_only and any(k in low or k in title for k in _HK_DISCLOSURE_SUSPENSION) + ): sev = "high" elif any(k in low or k in title for k in _HK_DISCLOSURE_MEDIUM): sev = "medium" @@ -349,7 +370,13 @@ def check_us_insider_trades(symbol: str, *, run=None) -> dict: sec_warnings = [str(w) for w in (data.get("warnings") or []) if w] result["truncated"] = truncated result["warnings"] = sec_warnings - result["available"] = not truncated and not 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)] def _tx_code(tx: dict) -> str: @@ -395,27 +422,45 @@ def _base_sig(tx: dict) -> tuple: re.IGNORECASE, ) - def _amendment_text(tx: dict) -> str: - parts: list[str] = [] - footnotes = tx.get("footnotes") - refs = tx.get("footnote_refs") - if isinstance(footnotes, dict) and footnotes: - if isinstance(refs, list) and refs: - parts.extend(str(footnotes.get(r) or "") for r in refs if footnotes.get(r)) - else: - parts.extend(str(v) for v in footnotes.values() if v) - elif isinstance(footnotes, str) and footnotes: - parts.append(footnotes) - for key in ("remarks", "amendment_reason", "note"): - if tx.get(key): - parts.append(str(tx[key])) - return " ".join(parts) + def _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 _amendment_intent(tx: dict) -> tuple[bool, bool]: - text = _amendment_text(tx) - if not text: - return False, False - return bool(_ADDITION_RE.search(text)), bool(_CORRECTION_RE.search(text)) + footnotes = tx.get("footnotes") + ref_ids = _extract_ref_ids(tx.get("footnote_refs")) + row_parts: list[str] = [] + if isinstance(footnotes, dict) and footnotes and ref_ids: + row_parts.extend(str(footnotes[fid]) for fid in ref_ids if footnotes.get(fid)) + elif isinstance(footnotes, str) and footnotes: + row_parts.append(footnotes) + if row_parts: + row_text = " ".join(row_parts) + row_add, row_corr = bool(_ADDITION_RE.search(row_text)), bool(_CORRECTION_RE.search(row_text)) + if row_add or row_corr: + return row_add, row_corr + # Fall back to filing-level remarks / explicit amendment notes only when row-scoped footnotes do not decide. + filing_parts = [str(tx[k]) for k in ("remarks", "amendment_reason", "note") if tx.get(k)] + if filing_parts: + filing_text = " ".join(filing_parts) + return bool(_ADDITION_RE.search(filing_text)), bool(_CORRECTION_RE.search(filing_text)) + return False, False 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"] @@ -438,11 +483,12 @@ def _mark_uncertain(tx: dict) -> None: else: unaligned_global = True - # 1. Reconcile non-sell 4/A rows idempotently per accession in two passes: - # - First skip rows that match an existing original non-sell Form 4 (e.g., footnote-only amendment to a Form 4 gift). - # - Pass A resolves unambiguous exact (base, shares, price) and unique (base, shares) matches across all accessions. - # - Pass B resolves remaining rows (blank-price multi-candidate links or explicit corrections with changed shares), - # retaining ambiguous candidates and flagging uncertainty rather than deleting an arbitrary sale. + # 1. Reconcile non-sell 4/A rows idempotently per accession in order-independent passes: + # - First match against original non-sell Form 4 rows (e.g., footnote-only amendment to a Form 4 gift). + # - Pass A1 resolves exact (base, shares, price) matches across ALL accessions first (independent of row order). + # - Pass A2 resolves unique (base, shares) matches per accession after exact matches have been reserved. + # - Pass B resolves remaining deferred rows (blank-price multi-candidate links or explicit corrections with + # changed shares), retaining ambiguous candidates and flagging uncertainty rather than dropping an arbitrary sale. non_sell_by_acc: dict[str, list[dict]] = {} for tx in all_amend: if _is_sell(tx): @@ -451,18 +497,17 @@ def _mark_uncertain(tx: dict) -> None: non_sell_by_acc.setdefault(acc, []).append(tx) acc_nonsell_matched: dict[str, set[int]] = {} - deferred_nonsells: list[tuple[str, dict]] = [] + unmatched_after_ns: dict[str, list[dict]] = {} for acc, acc_rows in non_sell_by_acc.items(): orig_ns_matched: set[int] = set() - acc_matched: set[int] = set() - acc_nonsell_matched[acc] = acc_matched + acc_nonsell_matched[acc] = set() + rem: list[dict] = [] for tx in acc_rows: is_add, is_corr = _amendment_intent(tx) base = _base_sig(tx) code = _tx_code(tx) shares = tx.get("shares") - # Match against original non-sell Form 4 filings first so amending a Form 4 gift never removes a sale. ns_idx = next( ( i @@ -478,12 +523,21 @@ def _mark_uncertain(tx: dict) -> None: orig_ns_matched.add(ns_idx) continue if is_add and not is_corr: - # Explicitly newly added non-sell transaction (e.g., omitted gift): keep separate from sales. continue + rem.append(tx) + unmatched_after_ns[acc] = rem - exact = _exact_sig(tx) + # Pass A1: exact (base, shares, price) matches across all accessions first. + after_a1: dict[str, list[dict]] = {} + for acc, rows in unmatched_after_ns.items(): + acc_matched = acc_nonsell_matched[acc] + rem: list[dict] = [] + for tx in rows: + base = _base_sig(tx) + shares = tx.get("shares") has_identity = base[0] != ("",) and bool(base[1]) and shares is not None if has_identity and tx.get("price") is not None: + exact = _exact_sig(tx) exact_cands = [ i for i, orig in enumerate(active_orig_sells) if i not in acc_matched and _exact_sig(orig) == exact ] @@ -491,6 +545,17 @@ def _mark_uncertain(tx: dict) -> None: acc_matched.add(exact_cands[0]) reclassified_indices.add(exact_cands[0]) continue + rem.append(tx) + after_a1[acc] = rem + + # Pass A2: unique (base, shares) matches (or uniform-price candidates) after exact matches are reserved. + deferred_nonsells: list[tuple[str, dict]] = [] + for acc, rows in after_a1.items(): + acc_matched = acc_nonsell_matched[acc] + for tx in rows: + base = _base_sig(tx) + shares = tx.get("shares") + has_identity = base[0] != ("",) and bool(base[1]) and shares is not None if has_identity: share_cands = [ i @@ -503,11 +568,9 @@ def _mark_uncertain(tx: dict) -> None: acc_matched.add(share_cands[0]) reclassified_indices.add(share_cands[0]) continue - if len(share_cands) > 1: - deferred_nonsells.append((acc, tx)) - continue deferred_nonsells.append((acc, tx)) + # Pass B: handle remaining multi-candidate blank-price links and explicit share-changing corrections. for acc, tx in deferred_nonsells: acc_matched = acc_nonsell_matched[acc] is_add, is_corr = _amendment_intent(tx) @@ -520,17 +583,18 @@ def _mark_uncertain(tx: dict) -> None: for i, orig in enumerate(active_orig_sells) if i not in acc_matched and _base_sig(orig) == base and orig.get("shares") == shares ] + if len(share_cands) == 1: + acc_matched.add(share_cands[0]) + reclassified_indices.add(share_cands[0]) + continue if len(share_cands) > 1: already_reclass = [i for i in share_cands if i in reclassified_indices] if len(already_reclass) == 1: - # Successive correction omitting price links to the already-identified sale; do not drop another. acc_matched.add(already_reclass[0]) continue - # Ambiguous blank-price correction across distinct candidates: retain all candidates & flag uncertainty. _mark_uncertain(tx) continue if is_corr and base[0] != ("",) and bool(base[1]): - # Explicit correction where shares/price changed (e.g. 6-share S corrected to 7-share G). base_cands = [ i for i, orig in enumerate(active_orig_sells) if i not in acc_matched and _base_sig(orig) == base ] @@ -546,26 +610,12 @@ def _mark_uncertain(tx: dict) -> None: continue if not has_identity: _mark_uncertain(tx) - # Otherwise: valid non-sell row with different shares and no correction note -> unrelated gift; keep separate. confirmed_orig_sells = [tx for i, tx in enumerate(active_orig_sells) if i not in reclassified_indices] - # 2. Match Form 4/A sell rows against ALL original Form 4 sells (before gift reclassification) so: - # - Exact duplicates or share-matched price restatements never inflate sales_90d regardless of filing order; - # - Explicitly omitted/added sales and distinct newly disclosed (shares, price) sales are counted separately; - # - Identical newly added sales repeated across accessions are deduplicated idempotently by exact signature. - orig_exact_counts: dict[tuple, int] = {} - orig_share_counts: dict[tuple, int] = {} - orig_base_counts: dict[tuple, int] = {} - for tx in active_orig_sells: - e = _exact_sig(tx) - s_key = (_base_sig(tx), tx.get("shares")) - b = _base_sig(tx) - orig_exact_counts[e] = orig_exact_counts.get(e, 0) + 1 - orig_share_counts[s_key] = orig_share_counts.get(s_key, 0) + 1 - orig_base_counts[b] = orig_base_counts.get(b, 0) + 1 - - max_added_exact: dict[tuple, int] = {} + # 2. Match Form 4/A sell rows against ALL original Form 4 sells (before gift reclassification) reserving each + # original by row identity across all match types, exact matches first (independent of XML row order). + # Process accessions chronologically so later amendments can correct previously added sales. amended_by_acc: dict[str, list[dict]] = {} for tx in all_amend: if not _is_sell(tx): @@ -573,52 +623,114 @@ def _mark_uncertain(tx: dict) -> None: acc = str(tx.get("accession") or f"__amend_{id(tx)}") amended_by_acc.setdefault(acc, []).append(tx) - for acc_rows in amended_by_acc.values(): - used_orig_exact: dict[tuple, int] = {} - used_orig_share: dict[tuple, int] = {} - used_orig_base: dict[tuple, int] = {} - acc_added_exact: dict[tuple, int] = {} + sorted_acc_items = sorted( + amended_by_acc.items(), + key=lambda item: (min(str(r.get("filing_date") or "") for r in item[1]), item[0]), + ) + + added_sales: list[dict] = [] + for _acc, acc_rows in sorted_acc_items: + acc_matched_orig: set[int] = set() + acc_explicit_adds: list[dict] = [] + acc_candidates: list[tuple[dict, bool]] = [] # (tx, is_corr) for tx in acc_rows: is_add, is_corr = _amendment_intent(tx) - e = _exact_sig(tx) - b = _base_sig(tx) - s_key = (b, tx.get("shares")) - - # Explicit omitted/added transaction: count as an addition (do not swallow into existing same-day sells). if is_add and not is_corr: - acc_added_exact[e] = acc_added_exact.get(e, 0) + 1 - _mark_uncertain(tx) - continue - - # Exact duplicate of an original Form 4 sell (before reclassification). - if used_orig_exact.get(e, 0) < orig_exact_counts.get(e, 0): - used_orig_exact[e] = used_orig_exact.get(e, 0) + 1 - used_orig_share[s_key] = used_orig_share.get(s_key, 0) + 1 - used_orig_base[b] = used_orig_base.get(b, 0) + 1 - continue + acc_explicit_adds.append(tx) + else: + acc_candidates.append((tx, is_corr)) - # Share-matched restatement (e.g., price revised on an original Form 4 sell): adds 0 rows. - if tx.get("shares") is not None and used_orig_share.get(s_key, 0) < orig_share_counts.get(s_key, 0): - used_orig_share[s_key] = used_orig_share.get(s_key, 0) + 1 - used_orig_base[b] = used_orig_base.get(b, 0) + 1 - _mark_uncertain(tx) - continue + # Sub-pass 1: exact matches against original Form 4 sells first. + after_exact: list[tuple[dict, bool]] = [] + for tx, is_corr in acc_candidates: + exact = _exact_sig(tx) + idx = next( + ( + i + for i, orig in enumerate(active_orig_sells) + if i not in acc_matched_orig and _exact_sig(orig) == exact + ), + None, + ) + if idx is not None: + acc_matched_orig.add(idx) + else: + after_exact.append((tx, is_corr)) - # Explicit correction changing share count of an original Form 4 sell: adds 0 rows, flags uncertainty. - if is_corr and used_orig_base.get(b, 0) < orig_base_counts.get(b, 0): - used_orig_base[b] = used_orig_base.get(b, 0) + 1 + # Sub-pass 2: share-matched restatements against remaining unmatched original Form 4 sells. + after_share: list[tuple[dict, bool]] = [] + for tx, is_corr in after_exact: + b = _base_sig(tx) + shares = tx.get("shares") + idx = None + if shares is not None and b[0] != ("",) and bool(b[1]): + idx = next( + ( + i + for i, orig in enumerate(active_orig_sells) + if i not in acc_matched_orig and _base_sig(orig) == b and orig.get("shares") == shares + ), + None, + ) + if idx is not None: + acc_matched_orig.add(idx) _mark_uncertain(tx) - continue - - # Distinct sale first disclosed in this 4/A accession (different shares/price or new date/security). - acc_added_exact[e] = acc_added_exact.get(e, 0) + 1 - _mark_uncertain(tx) - - for e, cnt in acc_added_exact.items(): - if cnt > max_added_exact.get(e, 0): - max_added_exact[e] = cnt + else: + after_share.append((tx, is_corr)) - unique_amended_sells = sum(max_added_exact.values()) + # Sub-pass 3: explicit corrections against remaining original sells OR previously added 4/A sales. + acc_new_sales: list[dict] = list(acc_explicit_adds) + for tx, is_corr in after_share: + b = _base_sig(tx) + if is_corr and b[0] != ("",) and bool(b[1]): + idx = next( + ( + i + for i, orig in enumerate(active_orig_sells) + if i not in acc_matched_orig and _base_sig(orig) == b + ), + None, + ) + if idx is not None: + acc_matched_orig.add(idx) + _mark_uncertain(tx) + continue + # Check if this explicit correction updates a previously added 4/A sale. + shares = tx.get("shares") + add_idx = None + if shares is not None: + add_idx = next( + ( + i + for i, prev in enumerate(added_sales) + if _base_sig(prev) == b and prev.get("shares") == shares + ), + None, + ) + if add_idx is None: + base_add_cands = [i for i, prev in enumerate(added_sales) if _base_sig(prev) == b] + if len(base_add_cands) == 1: + add_idx = base_add_cands[0] + if add_idx is not None: + added_sales[add_idx] = tx + _mark_uncertain(tx) + continue + acc_new_sales.append(tx) + + # Merge newly disclosed sales from this accession idempotently by exact signature. + acc_new_counts: dict[tuple, list[dict]] = {} + for tx in acc_new_sales: + acc_new_counts.setdefault(_exact_sig(tx), []).append(tx) + existing_counts: dict[tuple, int] = {} + for prev in added_sales: + e = _exact_sig(prev) + existing_counts[e] = existing_counts.get(e, 0) + 1 + for e, rows in acc_new_counts.items(): + need = len(rows) - existing_counts.get(e, 0) + if need > 0: + added_sales.extend(rows[:need]) + + unique_amended_sells = len(added_sales) dedup_sales = len(confirmed_orig_sells) + unique_amended_sells unaffected_orig_sells = ( 0 if unaligned_global else sum(1 for tx in confirmed_orig_sells if _owner_key(tx) not in affected_owners) @@ -745,8 +857,13 @@ def supplied(key): else: checks["lockup"] = {"applicable": False, "upcoming_30d": [], "available": True} if market == "HK": - checks["disclosures"] = {"matches": extra["matches"], "available": extra["available"]} + 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"], diff --git a/tools/sec_edgar.py b/tools/sec_edgar.py index ee0fa93..5b42248 100644 --- a/tools/sec_edgar.py +++ b/tools/sec_edgar.py @@ -252,6 +252,7 @@ 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 rows = [] for table, tag, derivative in [ ("nonDerivativeTable", "nonDerivativeTransaction", False), @@ -274,6 +275,7 @@ def form4(cik, filing): "ownership": row.findtext("ownershipNature/directOrIndirectOwnership/value"), "footnotes": footnotes, "footnote_refs": footnote_refs(row), + "remarks": remarks, "filing_date": filing["filingDate"], "form": filing["form"], "accession": filing["accessionNumber"], From 447f01d20c0e1a0a9f2a419f5d67a260e72cdc64 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 01:30:46 +0800 Subject: [PATCH 09/37] fix(risk): unify Form 4/A chronological ledger, scope remarks, version cache, detect HKEX halt phrasing --- tests/test_risk_screening.py | 243 +++++++++++++++++++++-- tests/test_sec_edgar.py | 45 +++++ tools/risk_screening.py | 368 ++++++++++++++++++----------------- tools/sec_edgar.py | 2 +- 4 files changed, 469 insertions(+), 189 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 247986f..d3702df 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -761,18 +761,226 @@ def test_real_sec_form4_xml_boundary_with_risk_screening(monkeypatch): 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): + return risk_screening.screen_risk( + "AAPL", + "Apple", + inputs=base_inputs, + run=lambda script, args, **kw: ( + { + "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) + assert res_mixed["checks"]["insider_trades"]["sales_90d"] == 3 + assert res_mixed["checks"]["insider_trades"]["count_uncertain"] is True + + 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"]) + + def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): - # 1. Resumption / lifting of suspension must NOT trigger high-severity buy veto + 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={ - "quote": {"pe": 18, "pb": 3}, - "technical": {"signal_score": 65, "buy_signal": "BUY", "trend": {"overall": "bullish"}}, - }, + inputs=base_inputs, run=lambda script, args, **kw: ( { - "announcements": [{"date": "2026-10-01", "title": "LIFTING OF SUSPENSION AND RESUMPTION OF TRADING"}], + "announcements": [ + { + "date": "2026-10-01", + "title": "LIFTING OF SUSPENSION AND RESUMPTION OF TRADING", + "type": "Trading Halt", + } + ], "truncated": False, } if script == "value_data.py" @@ -783,14 +991,27 @@ def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_ assert res_resume["checks"]["disclosures"]["available"] is True assert not any(f["category"] == "disclosure" for f in res_resume["flags"]) - # 2. Provider-incomplete HKEX response (truncated=True with < 15 rows) marks unavailable & data_complete=False + # 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={ - "quote": {"pe": 18, "pb": 3}, - "technical": {"signal_score": 65, "buy_signal": "BUY", "trend": {"overall": "bullish"}}, - }, + inputs=base_inputs, run=lambda script, args, **kw: ( {"announcements": [{"date": "2026-10-01", "title": "Profit Warning"}], "truncated": True} if script == "value_data.py" diff --git a/tests/test_sec_edgar.py b/tests/test_sec_edgar.py index 2a43059..0ae64a5 100644 --- a/tests/test_sec_edgar.py +++ b/tests/test_sec_edgar.py @@ -565,3 +565,48 @@ 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): + import _cache as cache_mod + + monkeypatch.setattr(cache_mod, "CACHE_DIR", tmp_path) + accn = "0000320193-26-000201" + # Pre-seed legacy unversioned cache entry missing the `remarks` field. + sec_edgar.cached( + f"sec-form4:0000320193:{accn}", + sec_edgar.WEEK, + lambda: [{"form": "4/A", "transaction_code": "S", "shares": 10}], + ) + + 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"], + "accessionNumber": [accn], + "filingDate": ["2026-10-12"], + "reportDate": ["2026-10-10"], + "primaryDocument": ["form4a.xml"], + }, + "files": [], + } + } + ) + return response( + """00003201932026-10-10S10150DAmending to report an inadvertently omitted sale.""" + ) + + monkeypatch.setattr("requests.get", get) + result = sec_edgar.insider_trades(Namespace(symbol="AAPL", days=90, top=10)) + assert result["transactions"][0]["remarks"] == "Amending to report an inadvertently omitted sale." + v2_rows = sec_edgar.cached( + f"sec-form4-v2:0000320193:{accn}", + sec_edgar.WEEK, + lambda: pytest.fail("expected v2 Form 4 cache entry to be populated"), + ) + assert v2_rows[0]["remarks"] == "Amending to report an inadvertently omitted sale." diff --git a/tools/risk_screening.py b/tools/risk_screening.py index a892454..f9441ad 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -278,7 +278,7 @@ def check_news_risks(symbol: str, name: str = "", *, run=None, market: str | Non _HK_DISCLOSURE_HIGH_ALWAYS = ("清盘", "winding up", "监管调查", "investigation") -_HK_DISCLOSURE_SUSPENSION = ("停牌", "trading halt", "suspension") +_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, @@ -315,15 +315,22 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: 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", "suspension")) + 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 any(k in low or k in title for k in _HK_DISCLOSURE_SUSPENSION) + not is_resumption_only and has_suspension ): sev = "high" elif any(k in low or k in title for k in _HK_DISCLOSURE_MEDIUM): @@ -442,7 +449,7 @@ def _extract_ref_ids(refs) -> list[str]: out.append(str(fid)) return out - def _amendment_intent(tx: dict) -> tuple[bool, bool]: + def _row_scoped_intent(tx: dict) -> tuple[bool, bool]: footnotes = tx.get("footnotes") ref_ids = _extract_ref_ids(tx.get("footnote_refs")) row_parts: list[str] = [] @@ -450,17 +457,41 @@ def _amendment_intent(tx: dict) -> tuple[bool, bool]: row_parts.extend(str(footnotes[fid]) for fid in ref_ids if footnotes.get(fid)) elif isinstance(footnotes, str) and footnotes: row_parts.append(footnotes) - if row_parts: - row_text = " ".join(row_parts) - row_add, row_corr = bool(_ADDITION_RE.search(row_text)), bool(_CORRECTION_RE.search(row_text)) - if row_add or row_corr: - return row_add, row_corr - # Fall back to filing-level remarks / explicit amendment notes only when row-scoped footnotes do not decide. - filing_parts = [str(tx[k]) for k in ("remarks", "amendment_reason", "note") if tx.get(k)] - if filing_parts: - filing_text = " ".join(filing_parts) - return bool(_ADDITION_RE.search(filing_text)), bool(_CORRECTION_RE.search(filing_text)) - return False, False + row_parts.extend(str(tx[k]) for k in ("amendment_reason", "note") if tx.get(k)) + if not row_parts: + return False, False + row_text = " ".join(row_parts) + return bool(_ADDITION_RE.search(row_text)), bool(_CORRECTION_RE.search(row_text)) + + def _resolve_accession_intents(acc_rows: list[dict]) -> tuple[list[tuple[bool, bool]], list[bool]]: + row_intents = [_row_scoped_intent(tx) for tx in acc_rows] + ambiguous = [False] * len(acc_rows) + seen_remarks: set[str] = set() + remarks_parts: list[str] = [] + for tx in acc_rows: + rem = str(tx.get("remarks") or "").strip() + if rem and rem not in seen_remarks: + seen_remarks.add(rem) + remarks_parts.append(rem) + if not remarks_parts: + return row_intents, ambiguous + rem_text = " ".join(remarks_parts) + rem_add, rem_corr = bool(_ADDITION_RE.search(rem_text)), bool(_CORRECTION_RE.search(rem_text)) + if not (rem_add or rem_corr): + return row_intents, ambiguous + unclaimed_add = rem_add and not any(ra for ra, _ in row_intents) + unclaimed_corr = rem_corr and not any(rc for _, rc in row_intents) + if not (unclaimed_add or unclaimed_corr): + return row_intents, ambiguous + unattributed = [i for i, (ra, rc) in enumerate(row_intents) if not (ra or rc)] + if len(unattributed) == 1 and (unclaimed_add != unclaimed_corr): + row_intents[unattributed[0]] = (unclaimed_add, unclaimed_corr) + else: + # Filing-level remarks cannot be uniquely attributed (multiple unattributed rows or mixed intent); + # keep rows conservative and surface uncertainty instead of broadcasting to every row. + for i in unattributed: + ambiguous[i] = True + return row_intents, ambiguous 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"] @@ -468,10 +499,20 @@ def _amendment_intent(tx: dict) -> tuple[bool, bool]: "amendment" in w.lower() or "double-count" in w.lower() for w in sec_warnings ) - # Start with original Form 4 sells and original Form 4 non-sells. - active_orig_sells = [tx for tx in all_orig if _is_sell(tx)] - orig_non_sells = [tx for tx in all_orig if not _is_sell(tx)] - reclassified_indices: set[int] = set() + def _make_ledger_entry(tx: dict, *, from_orig: bool) -> dict: + shares = tx.get("shares") + return { + "tx": tx, + "orig_tx": tx, + "sigs": {_exact_sig(tx)}, + "shares_set": {shares} if shares is not None else set(), + "from_orig": from_orig, + "reclassified": False, + } + + # Unified chronological transaction ledger initialized from original Form 4 filings. + ledger: list[dict] = [_make_ledger_entry(tx, from_orig=True) for tx in all_orig if _is_sell(tx)] + known_non_sells: list[dict] = [tx for tx in all_orig if not _is_sell(tx)] affected_owners: set[tuple] = set() unaligned_global = has_amendments and not all_amend @@ -483,36 +524,48 @@ def _mark_uncertain(tx: dict) -> None: else: unaligned_global = True - # 1. Reconcile non-sell 4/A rows idempotently per accession in order-independent passes: - # - First match against original non-sell Form 4 rows (e.g., footnote-only amendment to a Form 4 gift). - # - Pass A1 resolves exact (base, shares, price) matches across ALL accessions first (independent of row order). - # - Pass A2 resolves unique (base, shares) matches per accession after exact matches have been reserved. - # - Pass B resolves remaining deferred rows (blank-price multi-candidate links or explicit corrections with - # changed shares), retaining ambiguous candidates and flagging uncertainty rather than dropping an arbitrary sale. - non_sell_by_acc: dict[str, list[dict]] = {} + # Group ALL Form 4/A rows (sells and non-sells together) by accession and process chronologically so later + # amendments can correct or reclassify sales first introduced in earlier Form 4/A filings. + amend_by_acc: dict[str, list[dict]] = {} for tx in all_amend: - if _is_sell(tx): - continue - acc = str(tx.get("accession") or f"__amend_nonsell_{id(tx)}") - non_sell_by_acc.setdefault(acc, []).append(tx) - - acc_nonsell_matched: dict[str, set[int]] = {} - unmatched_after_ns: dict[str, list[dict]] = {} - - for acc, acc_rows in non_sell_by_acc.items(): - orig_ns_matched: set[int] = set() - acc_nonsell_matched[acc] = set() - rem: list[dict] = [] - for tx in acc_rows: - is_add, is_corr = _amendment_intent(tx) + acc = str(tx.get("accession") or f"__amend_{id(tx)}") + amend_by_acc.setdefault(acc, []).append(tx) + + sorted_acc_items = sorted( + amend_by_acc.items(), + key=lambda item: (min(str(r.get("filing_date") or "") for r in item[1]), item[0]), + ) + + for _acc, acc_rows in sorted_acc_items: + intents, ambig_flags = _resolve_accession_intents(acc_rows) + acc_sells: list[tuple[dict, tuple[bool, bool], bool]] = [] + acc_non_sells: list[tuple[dict, tuple[bool, bool], bool]] = [] + for tx, intent, is_ambig in zip(acc_rows, intents, ambig_flags): + if is_ambig: + _mark_uncertain(tx) + if _is_sell(tx): + acc_sells.append((tx, intent, is_ambig)) + else: + acc_non_sells.append((tx, intent, is_ambig)) + + # Match against the ledger snapshot as of BEFORE this accession's own newly added sales. + prior_len = len(ledger) + + # 1. Reconcile this accession's non-sell 4/A rows against known non-sells and prior ledger entries + # (original Form 4 sells + sells added by earlier Form 4/A accessions) in order-independent passes. + acc_orig_ns_matched: set[int] = set() + acc_matched_ns: set[int] = set() + acc_added_non_sells: list[dict] = [] + ns_candidates: list[tuple[dict, bool, bool]] = [] + for tx, (is_add, is_corr), _is_ambig in acc_non_sells: base = _base_sig(tx) code = _tx_code(tx) shares = tx.get("shares") ns_idx = next( ( i - for i, orig_ns in enumerate(orig_non_sells) - if i not in orig_ns_matched + for i, orig_ns in enumerate(known_non_sells) + if i not in acc_orig_ns_matched and _base_sig(orig_ns) == base and _tx_code(orig_ns) == code and (shares is None or orig_ns.get("shares") == shares) @@ -520,144 +573,118 @@ def _mark_uncertain(tx: dict) -> None: None, ) if ns_idx is not None: - orig_ns_matched.add(ns_idx) + acc_orig_ns_matched.add(ns_idx) continue if is_add and not is_corr: + acc_added_non_sells.append(tx) continue - rem.append(tx) - unmatched_after_ns[acc] = rem - - # Pass A1: exact (base, shares, price) matches across all accessions first. - after_a1: dict[str, list[dict]] = {} - for acc, rows in unmatched_after_ns.items(): - acc_matched = acc_nonsell_matched[acc] - rem: list[dict] = [] - for tx in rows: + ns_candidates.append((tx, is_add, is_corr)) + + # Pass A1: exact (base, shares, price) matches first (independent of row order within accession). + after_ns_a1: list[tuple[dict, bool, bool]] = [] + for tx, is_add, is_corr in ns_candidates: base = _base_sig(tx) shares = tx.get("shares") has_identity = base[0] != ("",) and bool(base[1]) and shares is not None if has_identity and tx.get("price") is not None: exact = _exact_sig(tx) - exact_cands = [ - i for i, orig in enumerate(active_orig_sells) if i not in acc_matched and _exact_sig(orig) == exact - ] + exact_cands = [i for i in range(prior_len) if i not in acc_matched_ns and exact in ledger[i]["sigs"]] if exact_cands: - acc_matched.add(exact_cands[0]) - reclassified_indices.add(exact_cands[0]) + acc_matched_ns.add(exact_cands[0]) + ledger[exact_cands[0]]["reclassified"] = True continue - rem.append(tx) - after_a1[acc] = rem - - # Pass A2: unique (base, shares) matches (or uniform-price candidates) after exact matches are reserved. - deferred_nonsells: list[tuple[str, dict]] = [] - for acc, rows in after_a1.items(): - acc_matched = acc_nonsell_matched[acc] - for tx in rows: + after_ns_a1.append((tx, is_add, is_corr)) + + # Pass A2: unique (base, shares) matches (or uniform-price candidates) after exact matches are reserved. + deferred_ns: list[tuple[dict, bool, bool]] = [] + for tx, is_add, is_corr in after_ns_a1: base = _base_sig(tx) shares = tx.get("shares") has_identity = base[0] != ("",) and bool(base[1]) and shares is not None if has_identity: share_cands = [ i - for i, orig in enumerate(active_orig_sells) - if i not in acc_matched and _base_sig(orig) == base and orig.get("shares") == shares + for i in range(prior_len) + if i not in acc_matched_ns + and _base_sig(ledger[i]["tx"]) == base + and shares in ledger[i]["shares_set"] ] if len(share_cands) == 1 or ( - len(share_cands) > 1 and len({active_orig_sells[i].get("price") for i in share_cands}) == 1 + len(share_cands) > 1 and len({ledger[i]["tx"].get("price") for i in share_cands}) == 1 ): - acc_matched.add(share_cands[0]) - reclassified_indices.add(share_cands[0]) + acc_matched_ns.add(share_cands[0]) + ledger[share_cands[0]]["reclassified"] = True continue - deferred_nonsells.append((acc, tx)) + deferred_ns.append((tx, is_add, is_corr)) - # Pass B: handle remaining multi-candidate blank-price links and explicit share-changing corrections. - for acc, tx in deferred_nonsells: - acc_matched = acc_nonsell_matched[acc] - is_add, is_corr = _amendment_intent(tx) - base = _base_sig(tx) - shares = tx.get("shares") - has_identity = base[0] != ("",) and bool(base[1]) and shares is not None - if has_identity: - share_cands = [ - i - for i, orig in enumerate(active_orig_sells) - if i not in acc_matched and _base_sig(orig) == base and orig.get("shares") == shares - ] - if len(share_cands) == 1: - acc_matched.add(share_cands[0]) - reclassified_indices.add(share_cands[0]) - continue - if len(share_cands) > 1: - already_reclass = [i for i in share_cands if i in reclassified_indices] + # Pass B: handle remaining multi-candidate blank-price links and explicit share-changing corrections. + for tx, _is_add, is_corr in deferred_ns: + base = _base_sig(tx) + shares = tx.get("shares") + has_identity = base[0] != ("",) and bool(base[1]) and shares is not None + if has_identity: + share_cands = [ + i + for i in range(prior_len) + if i not in acc_matched_ns + and _base_sig(ledger[i]["tx"]) == base + and shares in ledger[i]["shares_set"] + ] + if len(share_cands) == 1: + acc_matched_ns.add(share_cands[0]) + ledger[share_cands[0]]["reclassified"] = True + continue + if len(share_cands) > 1: + already_reclass = [i for i in share_cands if ledger[i]["reclassified"]] + if len(already_reclass) == 1: + acc_matched_ns.add(already_reclass[0]) + continue + _mark_uncertain(tx) + continue + if is_corr and base[0] != ("",) and bool(base[1]): + base_cands = [ + i for i in range(prior_len) if i not in acc_matched_ns and _base_sig(ledger[i]["tx"]) == base + ] + if len(base_cands) == 1: + acc_matched_ns.add(base_cands[0]) + ledger[base_cands[0]]["reclassified"] = True + continue + already_reclass = [i for i in base_cands if ledger[i]["reclassified"]] if len(already_reclass) == 1: - acc_matched.add(already_reclass[0]) + acc_matched_ns.add(already_reclass[0]) continue _mark_uncertain(tx) continue - if is_corr and base[0] != ("",) and bool(base[1]): - base_cands = [ - i for i, orig in enumerate(active_orig_sells) if i not in acc_matched and _base_sig(orig) == base - ] - if len(base_cands) == 1: - acc_matched.add(base_cands[0]) - reclassified_indices.add(base_cands[0]) - continue - already_reclass = [i for i in base_cands if i in reclassified_indices] - if len(already_reclass) == 1: - acc_matched.add(already_reclass[0]) - continue - _mark_uncertain(tx) - continue - if not has_identity: - _mark_uncertain(tx) - - confirmed_orig_sells = [tx for i, tx in enumerate(active_orig_sells) if i not in reclassified_indices] - - # 2. Match Form 4/A sell rows against ALL original Form 4 sells (before gift reclassification) reserving each - # original by row identity across all match types, exact matches first (independent of XML row order). - # Process accessions chronologically so later amendments can correct previously added sales. - amended_by_acc: dict[str, list[dict]] = {} - for tx in all_amend: - if not _is_sell(tx): - continue - acc = str(tx.get("accession") or f"__amend_{id(tx)}") - amended_by_acc.setdefault(acc, []).append(tx) + if not has_identity: + _mark_uncertain(tx) - sorted_acc_items = sorted( - amended_by_acc.items(), - key=lambda item: (min(str(r.get("filing_date") or "") for r in item[1]), item[0]), - ) + known_non_sells.extend(acc_added_non_sells) - added_sales: list[dict] = [] - for _acc, acc_rows in sorted_acc_items: - acc_matched_orig: set[int] = set() + # 2. Match this accession's sell 4/A rows against all prior ledger entries (reserving each entry by row + # identity across match types, exact matches first, independent of XML row order). + acc_matched_sell: set[int] = set() acc_explicit_adds: list[dict] = [] - acc_candidates: list[tuple[dict, bool]] = [] # (tx, is_corr) - for tx in acc_rows: - is_add, is_corr = _amendment_intent(tx) + sell_candidates: list[tuple[dict, bool]] = [] + for tx, (is_add, is_corr), _is_ambig in acc_sells: if is_add and not is_corr: acc_explicit_adds.append(tx) else: - acc_candidates.append((tx, is_corr)) + sell_candidates.append((tx, is_corr)) - # Sub-pass 1: exact matches against original Form 4 sells first. + # Sub-pass 1: exact matches against prior ledger entries first. after_exact: list[tuple[dict, bool]] = [] - for tx, is_corr in acc_candidates: + for tx, is_corr in sell_candidates: exact = _exact_sig(tx) idx = next( - ( - i - for i, orig in enumerate(active_orig_sells) - if i not in acc_matched_orig and _exact_sig(orig) == exact - ), + (i for i in range(prior_len) if i not in acc_matched_sell and exact in ledger[i]["sigs"]), None, ) if idx is not None: - acc_matched_orig.add(idx) + acc_matched_sell.add(idx) else: after_exact.append((tx, is_corr)) - # Sub-pass 2: share-matched restatements against remaining unmatched original Form 4 sells. + # Sub-pass 2: share-matched restatements against remaining prior ledger entries. after_share: list[tuple[dict, bool]] = [] for tx, is_corr in after_exact: b = _base_sig(tx) @@ -667,73 +694,60 @@ def _mark_uncertain(tx: dict) -> None: idx = next( ( i - for i, orig in enumerate(active_orig_sells) - if i not in acc_matched_orig and _base_sig(orig) == b and orig.get("shares") == shares + for i in range(prior_len) + if i not in acc_matched_sell + and _base_sig(ledger[i]["tx"]) == b + and shares in ledger[i]["shares_set"] ), None, ) if idx is not None: - acc_matched_orig.add(idx) + acc_matched_sell.add(idx) + ledger[idx]["tx"] = tx + ledger[idx]["sigs"].add(_exact_sig(tx)) _mark_uncertain(tx) else: after_share.append((tx, is_corr)) - # Sub-pass 3: explicit corrections against remaining original sells OR previously added 4/A sales. + # Sub-pass 3: explicit corrections against remaining prior ledger entries (original or earlier 4/A sales). acc_new_sales: list[dict] = list(acc_explicit_adds) for tx, is_corr in after_share: b = _base_sig(tx) if is_corr and b[0] != ("",) and bool(b[1]): idx = next( - ( - i - for i, orig in enumerate(active_orig_sells) - if i not in acc_matched_orig and _base_sig(orig) == b - ), + (i for i in range(prior_len) if i not in acc_matched_sell and _base_sig(ledger[i]["tx"]) == b), None, ) if idx is not None: - acc_matched_orig.add(idx) - _mark_uncertain(tx) - continue - # Check if this explicit correction updates a previously added 4/A sale. - shares = tx.get("shares") - add_idx = None - if shares is not None: - add_idx = next( - ( - i - for i, prev in enumerate(added_sales) - if _base_sig(prev) == b and prev.get("shares") == shares - ), - None, - ) - if add_idx is None: - base_add_cands = [i for i, prev in enumerate(added_sales) if _base_sig(prev) == b] - if len(base_add_cands) == 1: - add_idx = base_add_cands[0] - if add_idx is not None: - added_sales[add_idx] = tx + acc_matched_sell.add(idx) + ledger[idx]["tx"] = tx + ledger[idx]["sigs"].add(_exact_sig(tx)) + if tx.get("shares") is not None: + ledger[idx]["shares_set"].add(tx.get("shares")) _mark_uncertain(tx) continue acc_new_sales.append(tx) - # Merge newly disclosed sales from this accession idempotently by exact signature. + # 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(_exact_sig(tx), []).append(tx) existing_counts: dict[tuple, int] = {} - for prev in added_sales: - e = _exact_sig(prev) - existing_counts[e] = existing_counts.get(e, 0) + 1 + 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: - added_sales.extend(rows[:need]) + ledger.extend(_make_ledger_entry(tx, from_orig=False) for tx in rows[:need]) - unique_amended_sells = len(added_sales) - dedup_sales = len(confirmed_orig_sells) + unique_amended_sells + active_sales = [entry for entry in ledger if not entry["reclassified"]] + dedup_sales = len(active_sales) unaffected_orig_sells = ( - 0 if unaligned_global else sum(1 for tx in confirmed_orig_sells if _owner_key(tx) not in affected_owners) + 0 + if unaligned_global + else sum(1 for entry in active_sales if entry["from_orig"] and _owner_key(entry["tx"]) not in affected_owners) ) result["sales_90d"] = dedup_sales result["amendments_present"] = has_amendments diff --git a/tools/sec_edgar.py b/tools/sec_edgar.py index 5b42248..749bfd9 100644 --- a/tools/sec_edgar.py +++ b/tools/sec_edgar.py @@ -571,7 +571,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-v2:{cik}:{filing['accessionNumber']}", WEEK, lambda filing=filing: form4(cik, filing) ) result["transactions"].extend(rows) result["filings_scanned"] += 1 From 9600d2cc29cef5c4ba3f166d9472e3cc38c4e170 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 02:27:53 +0800 Subject: [PATCH 10/37] fix(risk): tighten Form 4/A restoration, unlinked uncertainty, gift precedence, 90d tx window, original_filing_date --- tests/test_risk_screening.py | 203 +++++++++++++++++- tests/test_sec_edgar.py | 34 +-- tools/risk_screening.py | 396 +++++++++++++++++++++++++++-------- tools/sec_edgar.py | 4 +- 4 files changed, 530 insertions(+), 107 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index d3702df..0baab2e 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -314,6 +314,7 @@ def test_us_risk_screening_deduplicates_form4a_amendments_before_veto(monkeypatc 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"], @@ -345,6 +346,7 @@ def fake_run(script, args, **kwargs): }, 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"], @@ -383,6 +385,7 @@ def fake_run(script, args, **kwargs): }, 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"], @@ -421,6 +424,7 @@ def fake_run(script, args, **kwargs): }, 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"], @@ -445,6 +449,7 @@ def fake_run(script, args, **kwargs): }, 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"], @@ -468,6 +473,7 @@ def fake_run(script, args, **kwargs): }, 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"], @@ -489,6 +495,7 @@ def _run_us(tx_list): }, 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"], @@ -590,8 +597,24 @@ def _run_us(tx_list): # 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) - add_s2 = dict(one_orig[0], form="4/A", accession="0001-26-000071", shares=300, price=12.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"]) @@ -618,14 +641,17 @@ def _run_us(tx_list): assert res_seventh["veto_buy"] is True # Branch H (Weaxs P2 & CodeRabbit Major 594): row-order invariance — each original sale matched at most once - orig_pair = [ - dict(six_orig[0], transaction_date="2026-10-21", shares=100, price=150.0), - dict(six_orig[0], transaction_date="2026-10-21", shares=50, price=160.0), - ] - amend_155 = dict(orig_pair[0], form="4/A", accession="0001-26-000091", price=155.0) - amend_150 = dict(orig_pair[0], form="4/A", accession="0001-26-000091", price=150.0) - assert _run_us(orig_pair + [amend_155, amend_150])["checks"]["insider_trades"]["sales_90d"] == 3 - assert _run_us(orig_pair + [amend_150, amend_155])["checks"]["insider_trades"]["sales_90d"] == 3 + 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) + assert _run_us(orig_single + [amend_155, amend_150])["checks"]["insider_trades"]["sales_90d"] == 2 + assert _run_us(orig_single + [amend_150, amend_155])["checks"]["insider_trades"]["sales_90d"] == 2 + # 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] @@ -749,6 +775,7 @@ def test_real_sec_form4_xml_boundary_with_risk_screening(monkeypatch): }, 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"], @@ -770,13 +797,14 @@ def test_form4_amendment_remarks_scoping_and_chronological_ledger_chain(monkeypa "technical": {"signal_score": 60, "buy_signal": "HOLD", "trend": {"overall": "neutral"}}, } - def _screen(txs): + 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"], @@ -961,6 +989,159 @@ def _parse(accn, fdate, form, doc): 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. Plural/counted remarks ("two omitted sales") with only 1 row footnote must NOT treat all additions as claimed + 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.", + ) + # 2 rows total -> single remaining unattributed row absorbs the 2nd remarked addition -> 4 sales + assert _screen(orig_rows + [two_omit_r1, two_omit_r2])["checks"]["insider_trades"]["sales_90d"] == 4 + # 3 rows (2 unattributed rows for 1 remaining addition) -> cannot identify which is added -> count_uncertain=True + two_omit_r3 = dict(two_omit_r2, shares=100, price=150.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"]["count_uncertain"] is True + + # 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 + def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): base_inputs = { diff --git a/tests/test_sec_edgar.py b/tests/test_sec_edgar.py index 0ae64a5..0f1f6fd 100644 --- a/tests/test_sec_edgar.py +++ b/tests/test_sec_edgar.py @@ -568,16 +568,22 @@ def flow(start, end, value, filed, form="10-Q"): 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" - # Pre-seed legacy unversioned cache entry missing the `remarks` field. - sec_edgar.cached( - f"sec-form4:0000320193:{accn}", - sec_edgar.WEEK, - lambda: [{"form": "4/A", "transaction_code": "S", "shares": 10}], - ) + 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`. + for prefix in ("sec-form4", "sec-form4-v2"): + sec_edgar.cached( + f"{prefix}:0000320193:{accn}", + sec_edgar.WEEK, + lambda: [{"form": "4/A", "transaction_code": "S", "shares": 10}], + ) def get(url, **kwargs): if url.endswith("company_tickers.json"): @@ -589,8 +595,8 @@ def get(url, **kwargs): "recent": { "form": ["4/A"], "accessionNumber": [accn], - "filingDate": ["2026-10-12"], - "reportDate": ["2026-10-10"], + "filingDate": [recent_filing], + "reportDate": [tx_date], "primaryDocument": ["form4a.xml"], }, "files": [], @@ -598,15 +604,17 @@ def get(url, **kwargs): } ) return response( - """00003201932026-10-10S10150DAmending to report an inadvertently omitted sale.""" + 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)) assert result["transactions"][0]["remarks"] == "Amending to report an inadvertently omitted sale." - v2_rows = sec_edgar.cached( - f"sec-form4-v2:0000320193:{accn}", + assert result["transactions"][0]["original_filing_date"] == orig_filing + v3_rows = sec_edgar.cached( + f"sec-form4-v3:0000320193:{accn}", sec_edgar.WEEK, - lambda: pytest.fail("expected v2 Form 4 cache entry to be populated"), + lambda: pytest.fail("expected v3 Form 4 cache entry to be populated"), ) - assert v2_rows[0]["remarks"] == "Amending to report an inadvertently omitted sale." + assert v3_rows[0]["remarks"] == "Amending to report an inadvertently omitted sale." + assert v3_rows[0]["original_filing_date"] == orig_filing diff --git a/tools/risk_screening.py b/tools/risk_screening.py index f9441ad..d87f726 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -8,7 +8,7 @@ import re import sys from concurrent.futures import Future, ThreadPoolExecutor -from datetime import timedelta +from datetime import date, timedelta sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) @@ -418,7 +418,7 @@ def _base_sig(tx: dict) -> tuple: _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+)?transaction|" + r"add(?:ed|ing|itional)\s+(?:a\s+)?(?:previously\s+omitted\s+)?transactions?|" r"late[- ]?report(?:ed|ing)|补报|漏报|遗漏)", re.IGNORECASE, ) @@ -428,6 +428,71 @@ def _base_sig(tx: dict) -> tuple: r"replaces?|supersedes?|restat(?:ed|es|ing|ement)|更正|修正|重分类|误报)", re.IGNORECASE, ) + _SALE_RECLASS_RE = re.compile( + r"(\b(?:sale|sold|sell|code\s+s|transaction\s+code|reclassif(?:ied|y|ying)|instead\s+of|should\s+have\s+been)\b|" + r"\bto\s+(?:a\s+)?(?:bona\s+fide\s+)?gift\b|卖出|出售|重分类|改为赠与)", + re.IGNORECASE, + ) + _COUNT_WORDS = { + "two": 2, + "three": 3, + "four": 4, + "five": 5, + "six": 6, + "seven": 7, + "eight": 8, + "nine": 9, + "ten": 10, + "both": 2, + "several": 2, + "multiple": 2, + "两": 2, + "二": 2, + "三": 3, + "四": 4, + "五": 5, + "多": 2, + "若干": 2, + } + _ADD_COUNT_RE = re.compile( + r"(?:\b([2-9]|\d{2,}|two|three|four|five|six|seven|eight|nine|ten|both|several|multiple)\b" + r"(?:\s+\w+){0,3}\s+(?:omitted|unreported|additional|late[- ]?reported)\b|" + r"(?:adds?|adding|added|reports?|reporting|reported)\s+" + r"\b([2-9]|\d{2,}|two|three|four|five|six|seven|eight|nine|ten|both|several|multiple)\b|" + r"(两|二|三|四|五|多|若干)\s*笔?\s*(?:遗漏|漏报|补报))", + re.IGNORECASE, + ) + _ADD_PLURAL_RE = re.compile( + r"(?:omitted|unreported|additional|late[- ]?reported)\s+(?:sales|transactions|dispositions|lines|rows)\b", + re.IGNORECASE, + ) + _CORR_COUNT_RE = re.compile( + r"(?:corrects?|correcting|corrected|reclassif(?:ies|ying|ied)|restates?|restating|restated)\s+" + r"\b([2-9]|\d{2,}|two|three|four|five|six|seven|eight|nine|ten|both|several|multiple)\b|" + r"(两|二|三|四|五|多|若干)\s*笔?\s*(?:更正|修正|重分类|误报)", + re.IGNORECASE, + ) + + def _remarks_intent_count(text: str, *, kind: str) -> int: + if kind == "add": + if not _ADDITION_RE.search(text): + return 0 + count = 1 + for m in _ADD_COUNT_RE.finditer(text): + tok = next((g for g in m.groups() if g), "").lower() + n = int(tok) if tok.isdigit() else _COUNT_WORDS.get(tok, 1) + count = max(count, n) + if count == 1 and _ADD_PLURAL_RE.search(text): + count = 2 + return count + if not _CORRECTION_RE.search(text): + return 0 + count = 1 + for m in _CORR_COUNT_RE.finditer(text): + tok = next((g for g in m.groups() if g), "").lower() + n = int(tok) if tok.isdigit() else _COUNT_WORDS.get(tok, 1) + count = max(count, n) + return count def _extract_ref_ids(refs) -> list[str]: seen: set[str] = set() @@ -449,7 +514,7 @@ def _extract_ref_ids(refs) -> list[str]: out.append(str(fid)) return out - def _row_scoped_intent(tx: dict) -> tuple[bool, bool]: + def _row_scoped_text(tx: dict) -> str: footnotes = tx.get("footnotes") ref_ids = _extract_ref_ids(tx.get("footnote_refs")) row_parts: list[str] = [] @@ -458,13 +523,16 @@ def _row_scoped_intent(tx: dict) -> tuple[bool, bool]: elif isinstance(footnotes, str) and footnotes: row_parts.append(footnotes) row_parts.extend(str(tx[k]) for k in ("amendment_reason", "note") if tx.get(k)) - if not row_parts: - return False, False - row_text = " ".join(row_parts) - return bool(_ADDITION_RE.search(row_text)), bool(_CORRECTION_RE.search(row_text)) - - def _resolve_accession_intents(acc_rows: list[dict]) -> tuple[list[tuple[bool, bool]], list[bool]]: - row_intents = [_row_scoped_intent(tx) for tx in acc_rows] + return " ".join(row_parts) + + def _resolve_accession_intents( + acc_rows: list[dict], + ) -> tuple[list[tuple[bool, bool]], list[bool], list[str], bool]: + row_texts = [_row_scoped_text(tx) for tx in acc_rows] + row_intents = [ + (bool(_ADDITION_RE.search(rt)), bool(_CORRECTION_RE.search(rt))) if rt else (False, False) + for rt in row_texts + ] ambiguous = [False] * len(acc_rows) seen_remarks: set[str] = set() remarks_parts: list[str] = [] @@ -474,24 +542,41 @@ def _resolve_accession_intents(acc_rows: list[dict]) -> tuple[list[tuple[bool, b seen_remarks.add(rem) remarks_parts.append(rem) if not remarks_parts: - return row_intents, ambiguous + return row_intents, ambiguous, row_texts, False rem_text = " ".join(remarks_parts) - rem_add, rem_corr = bool(_ADDITION_RE.search(rem_text)), bool(_CORRECTION_RE.search(rem_text)) - if not (rem_add or rem_corr): - return row_intents, ambiguous - unclaimed_add = rem_add and not any(ra for ra, _ in row_intents) - unclaimed_corr = rem_corr and not any(rc for _, rc in row_intents) + rem_add_count = _remarks_intent_count(rem_text, kind="add") + rem_corr_count = _remarks_intent_count(rem_text, kind="corr") + if not (rem_add_count or rem_corr_count): + return row_intents, ambiguous, row_texts, False + claimed_add_count = sum(1 for ra, _ in row_intents if ra) + claimed_corr_count = sum(1 for _, rc in row_intents if rc) + unclaimed_add = rem_add_count > claimed_add_count + unclaimed_corr = rem_corr_count > claimed_corr_count if not (unclaimed_add or unclaimed_corr): - return row_intents, ambiguous + return row_intents, ambiguous, row_texts, False unattributed = [i for i, (ra, rc) in enumerate(row_intents) if not (ra or rc)] if len(unattributed) == 1 and (unclaimed_add != unclaimed_corr): row_intents[unattributed[0]] = (unclaimed_add, unclaimed_corr) - else: - # Filing-level remarks cannot be uniquely attributed (multiple unattributed rows or mixed intent); - # keep rows conservative and surface uncertainty instead of broadcasting to every row. - for i in unattributed: + row_texts[unattributed[0]] = f"{row_texts[unattributed[0]]} {rem_text}".strip() + return row_intents, ambiguous, row_texts, False + # Filing-level remarks cannot be uniquely attributed (multiple unattributed rows, mixed intent, or + # remarks declaring more additions/corrections than attributed rows); surface uncertainty instead of + # broadcasting to every row. + for i in unattributed: + ambiguous[i] = True + row_texts[i] = f"{row_texts[i]} {rem_text}".strip() + if not unattributed: + for i in range(len(acc_rows)): ambiguous[i] = True - return row_intents, ambiguous + return row_intents, ambiguous, row_texts, unclaimed_add + + 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"] @@ -501,11 +586,14 @@ def _resolve_accession_intents(acc_rows: list[dict]) -> tuple[list[tuple[bool, b def _make_ledger_entry(tx: dict, *, from_orig: bool) -> dict: shares = tx.get("shares") + fdate = str(tx.get("filing_date") or "").strip() return { "tx": tx, "orig_tx": tx, "sigs": {_exact_sig(tx)}, "shares_set": {shares} if shares is not None else set(), + "filing_dates": {fdate} if fdate else set(), + "orig_accession": str(tx.get("accession") or "").strip() or None, "from_orig": from_orig, "reclassified": False, } @@ -524,8 +612,42 @@ def _mark_uncertain(tx: dict) -> None: else: unaligned_global = True + def _scoped_pool(tx: dict, prior_len: int) -> tuple[list[int], bool]: + 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)): + return list(range(prior_len)), False + pool = [i for i in range(prior_len) if orig_date in ledger[i]["filing_dates"]] + if not pool: + return [], True + b = _base_sig(tx) + same_base_accs = { + ledger[i]["orig_accession"] for i in pool if _base_sig(ledger[i]["tx"]) == b and ledger[i]["orig_accession"] + } + if len(same_base_accs) > 1: + return [], True + return pool, False + + def _mark_reclassified(idx: int, tx: dict) -> None: + entry = ledger[idx] + entry["reclassified"] = True + fdate = str(tx.get("filing_date") or "").strip() + if fdate: + entry["filing_dates"].add(fdate) + + def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) -> None: + entry = ledger[idx] + entry["tx"] = tx + entry["sigs"].add(_exact_sig(tx)) + if tx.get("shares") is not None: + entry["shares_set"].add(tx.get("shares")) + fdate = str(tx.get("filing_date") or "").strip() + if fdate: + entry["filing_dates"].add(fdate) + if restore_if_reclassified and entry["reclassified"]: + entry["reclassified"] = False + # Group ALL Form 4/A rows (sells and non-sells together) by accession and process chronologically so later - # amendments can correct or reclassify sales first introduced in earlier Form 4/A filings. + # amendments can correct, reclassify, or restore sales from original Form 4 or earlier Form 4/A filings. amend_by_acc: dict[str, list[dict]] = {} for tx in all_amend: acc = str(tx.get("accession") or f"__amend_{id(tx)}") @@ -537,16 +659,16 @@ def _mark_uncertain(tx: dict) -> None: ) for _acc, acc_rows in sorted_acc_items: - intents, ambig_flags = _resolve_accession_intents(acc_rows) - acc_sells: list[tuple[dict, tuple[bool, bool], bool]] = [] - acc_non_sells: list[tuple[dict, tuple[bool, bool], bool]] = [] - for tx, intent, is_ambig in zip(acc_rows, intents, ambig_flags): + intents, ambig_flags, row_texts, acc_has_unclaimed_add = _resolve_accession_intents(acc_rows) + acc_sells: list[tuple[dict, tuple[bool, bool], bool, str]] = [] + acc_non_sells: list[tuple[dict, tuple[bool, bool], bool, str]] = [] + for tx, intent, is_ambig, rtext in zip(acc_rows, intents, ambig_flags, row_texts): if is_ambig: _mark_uncertain(tx) if _is_sell(tx): - acc_sells.append((tx, intent, is_ambig)) + acc_sells.append((tx, intent, is_ambig, rtext)) else: - acc_non_sells.append((tx, intent, is_ambig)) + acc_non_sells.append((tx, intent, is_ambig, rtext)) # Match against the ledger snapshot as of BEFORE this accession's own newly added sales. prior_len = len(ledger) @@ -557,10 +679,13 @@ def _mark_uncertain(tx: dict) -> None: acc_matched_ns: set[int] = set() acc_added_non_sells: list[dict] = [] ns_candidates: list[tuple[dict, bool, bool]] = [] - for tx, (is_add, is_corr), _is_ambig in acc_non_sells: + for tx, (is_add, is_corr), _is_ambig, rtext in acc_non_sells: base = _base_sig(tx) code = _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_ambig = _scoped_pool(tx, prior_len) ns_idx = next( ( i @@ -569,15 +694,42 @@ def _mark_uncertain(tx: dict) -> None: and _base_sig(orig_ns) == base and _tx_code(orig_ns) == code and (shares is None or orig_ns.get("shares") == shares) + and (not orig_date or not orig_ns.get("filing_date") or orig_ns.get("filing_date") == orig_date) ), None, ) if ns_idx is not None: + # Resolve explicit sale reclassifications (or priced exact matches to a prior sale whose price differs + # from the existing non-sell) against the ledger before applying the non-sell restatement shortcut. + priced_sell_match = ( + not pool_ambig + and has_identity + and tx.get("price") is not None + and known_non_sells[ns_idx].get("price") != tx.get("price") + and any(i not in acc_matched_ns and _exact_sig(tx) in ledger[i]["sigs"] for i in pool) + ) + has_ledger_sell = not pool_ambig and any( + i not in acc_matched_ns and _base_sig(ledger[i]["tx"]) == base for i in pool + ) + has_active_ledger_sell = not pool_ambig and any( + i not in acc_matched_ns and not ledger[i]["reclassified"] and _base_sig(ledger[i]["tx"]) == base + for i in pool + ) + if priced_sell_match or (is_corr and has_ledger_sell and bool(_SALE_RECLASS_RE.search(rtext))): + ns_candidates.append((tx, is_add, is_corr)) + continue + if is_corr and has_active_ledger_sell: + acc_orig_ns_matched.add(ns_idx) + _mark_uncertain(tx) + continue acc_orig_ns_matched.add(ns_idx) continue if is_add and not is_corr: acc_added_non_sells.append(tx) continue + if pool_ambig: + _mark_uncertain(tx) + continue ns_candidates.append((tx, is_add, is_corr)) # Pass A1: exact (base, shares, price) matches first (independent of row order within accession). @@ -586,12 +738,19 @@ def _mark_uncertain(tx: dict) -> None: base = _base_sig(tx) shares = tx.get("shares") has_identity = base[0] != ("",) and bool(base[1]) and shares is not None + pool, pool_ambig = _scoped_pool(tx, prior_len) + if pool_ambig: + _mark_uncertain(tx) + continue if has_identity and tx.get("price") is not None: exact = _exact_sig(tx) - exact_cands = [i for i in range(prior_len) if i not in acc_matched_ns and exact in ledger[i]["sigs"]] + exact_cands = [i for i in pool if i not in acc_matched_ns and exact in ledger[i]["sigs"]] if exact_cands: - acc_matched_ns.add(exact_cands[0]) - ledger[exact_cands[0]]["reclassified"] = True + # Prefer already-reclassified entry for idempotence across successive gift 4/A filings. + reclass_exact = [i for i in exact_cands if ledger[i]["reclassified"]] + target = reclass_exact[0] if reclass_exact else exact_cands[0] + acc_matched_ns.add(target) + _mark_reclassified(target, tx) continue after_ns_a1.append((tx, is_add, is_corr)) @@ -601,10 +760,11 @@ def _mark_uncertain(tx: dict) -> None: base = _base_sig(tx) shares = tx.get("shares") has_identity = base[0] != ("",) and bool(base[1]) and shares is not None + pool, _ = _scoped_pool(tx, prior_len) if has_identity: share_cands = [ i - for i in range(prior_len) + for i in pool if i not in acc_matched_ns and _base_sig(ledger[i]["tx"]) == base and shares in ledger[i]["shares_set"] @@ -612,8 +772,10 @@ def _mark_uncertain(tx: dict) -> None: if len(share_cands) == 1 or ( len(share_cands) > 1 and len({ledger[i]["tx"].get("price") for i in share_cands}) == 1 ): - acc_matched_ns.add(share_cands[0]) - ledger[share_cands[0]]["reclassified"] = True + reclass_cands = [i for i in share_cands if ledger[i]["reclassified"]] + target = reclass_cands[0] if reclass_cands else share_cands[0] + acc_matched_ns.add(target) + _mark_reclassified(target, tx) continue deferred_ns.append((tx, is_add, is_corr)) @@ -622,17 +784,18 @@ def _mark_uncertain(tx: dict) -> None: base = _base_sig(tx) shares = tx.get("shares") has_identity = base[0] != ("",) and bool(base[1]) and shares is not None + pool, _ = _scoped_pool(tx, prior_len) if has_identity: share_cands = [ i - for i in range(prior_len) + for i in pool if i not in acc_matched_ns and _base_sig(ledger[i]["tx"]) == base and shares in ledger[i]["shares_set"] ] if len(share_cands) == 1: acc_matched_ns.add(share_cands[0]) - ledger[share_cands[0]]["reclassified"] = True + _mark_reclassified(share_cands[0], tx) continue if len(share_cands) > 1: already_reclass = [i for i in share_cands if ledger[i]["reclassified"]] @@ -642,12 +805,10 @@ def _mark_uncertain(tx: dict) -> None: _mark_uncertain(tx) continue if is_corr and base[0] != ("",) and bool(base[1]): - base_cands = [ - i for i in range(prior_len) if i not in acc_matched_ns and _base_sig(ledger[i]["tx"]) == base - ] + base_cands = [i for i in pool if i not in acc_matched_ns and _base_sig(ledger[i]["tx"]) == base] if len(base_cands) == 1: acc_matched_ns.add(base_cands[0]) - ledger[base_cands[0]]["reclassified"] = True + _mark_reclassified(base_cands[0], tx) continue already_reclass = [i for i in base_cands if ledger[i]["reclassified"]] if len(already_reclass) == 1: @@ -665,7 +826,7 @@ def _mark_uncertain(tx: dict) -> None: acc_matched_sell: set[int] = set() acc_explicit_adds: list[dict] = [] sell_candidates: list[tuple[dict, bool]] = [] - for tx, (is_add, is_corr), _is_ambig in acc_sells: + 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: @@ -674,59 +835,109 @@ def _mark_uncertain(tx: dict) -> None: # Sub-pass 1: exact matches against prior ledger entries first. after_exact: list[tuple[dict, bool]] = [] for tx, is_corr in sell_candidates: + pool, pool_ambig = _scoped_pool(tx, prior_len) + if pool_ambig: + _mark_uncertain(tx) + continue exact = _exact_sig(tx) - idx = next( - (i for i in range(prior_len) if i not in acc_matched_sell and exact in ledger[i]["sigs"]), - None, - ) - if idx is not None: - acc_matched_sell.add(idx) + exact_cands = [i for i in pool if i not in acc_matched_sell and exact in ledger[i]["sigs"]] + if exact_cands: + if is_corr: + reclass_cands = [i for i in exact_cands if ledger[i]["reclassified"]] + if len(reclass_cands) == 1 or ( + len(reclass_cands) > 1 + and len({(ledger[i]["tx"].get("price"), ledger[i]["tx"].get("shares")) for i in reclass_cands}) + == 1 + ): + target = reclass_cands[0] + acc_matched_sell.add(target) + _update_entry(target, tx, restore_if_reclassified=True) + elif reclass_cands: + _mark_uncertain(tx) + else: + target = exact_cands[0] + acc_matched_sell.add(target) + _update_entry(target, tx) + else: + active_cands = [i for i in exact_cands if not ledger[i]["reclassified"]] + if active_cands: + acc_matched_sell.add(active_cands[0]) + _update_entry(active_cands[0], tx) + else: + # Unannotated restatement of a previously reclassified sale: keep gift state & mark uncertain. + acc_matched_sell.add(exact_cands[0]) + _mark_uncertain(tx) else: after_exact.append((tx, is_corr)) - # Sub-pass 2: share-matched restatements against remaining prior ledger entries. + # Sub-pass 2: share-matched restatements against remaining prior ledger entries (order-independent: + # multiple distinct-price or mixed-state candidates are left unresolved and marked uncertain). after_share: list[tuple[dict, bool]] = [] for tx, is_corr in after_exact: b = _base_sig(tx) shares = tx.get("shares") - idx = None + pool, _ = _scoped_pool(tx, prior_len) + share_cands: list[int] = [] if shares is not None and b[0] != ("",) and bool(b[1]): - idx = next( - ( - i - for i in range(prior_len) - if i not in acc_matched_sell - and _base_sig(ledger[i]["tx"]) == b - and shares in ledger[i]["shares_set"] - ), - None, - ) - if idx is not None: - acc_matched_sell.add(idx) - ledger[idx]["tx"] = tx - ledger[idx]["sigs"].add(_exact_sig(tx)) + share_cands = [ + i + for i in pool + if i not in acc_matched_sell + and _base_sig(ledger[i]["tx"]) == b + and shares in ledger[i]["shares_set"] + ] + if len(share_cands) == 1 or ( + len(share_cands) > 1 + and len({(ledger[i]["tx"].get("price"), ledger[i]["reclassified"]) for i in share_cands}) == 1 + ): + target = share_cands[0] + acc_matched_sell.add(target) + was_reclassified = ledger[target]["reclassified"] + _update_entry(target, tx, restore_if_reclassified=is_corr) + if not (is_corr and was_reclassified): + _mark_uncertain(tx) + elif len(share_cands) > 1: _mark_uncertain(tx) else: after_share.append((tx, is_corr)) - # Sub-pass 3: explicit corrections against remaining prior ledger entries (original or earlier 4/A sales). + # Sub-pass 3: explicit corrections against remaining prior ledger entries (order-independent: resolve only + # when a unique or symmetric candidate exists; otherwise mark uncertain without inflating count). acc_new_sales: list[dict] = list(acc_explicit_adds) for tx, is_corr in after_share: b = _base_sig(tx) - if is_corr and b[0] != ("",) and bool(b[1]): - idx = next( - (i for i in range(prior_len) if i not in acc_matched_sell and _base_sig(ledger[i]["tx"]) == b), - None, - ) - if idx is not None: - acc_matched_sell.add(idx) - ledger[idx]["tx"] = tx - ledger[idx]["sigs"].add(_exact_sig(tx)) - if tx.get("shares") is not None: - ledger[idx]["shares_set"].add(tx.get("shares")) - _mark_uncertain(tx) - continue - acc_new_sales.append(tx) + pool, _ = _scoped_pool(tx, prior_len) + if is_corr: + if b[0] != ("",) and bool(b[1]): + base_cands = [i for i in pool if i not in acc_matched_sell and _base_sig(ledger[i]["tx"]) == b] + if len(base_cands) == 1 or ( + len(base_cands) > 1 + and len( + { + (ledger[i]["tx"].get("shares"), ledger[i]["tx"].get("price"), ledger[i]["reclassified"]) + for i in base_cands + } + ) + == 1 + ): + target = base_cands[0] + acc_matched_sell.add(target) + _update_entry(target, tx, restore_if_reclassified=True) + _mark_uncertain(tx) + continue + _mark_uncertain(tx) + continue + # Sub-pass 4: only confirm an unlinked sell row as a new sale when filing evidence supports an addition + # (unclaimed remarks addition, or every prior entry on that base signature was already reserved in this + # same accession). Otherwise report uncertainty without inflating the confirmed sale count. + has_prior_same_base = any(_base_sig(ledger[i]["tx"]) == b for i in pool) + all_prior_same_base_reserved = has_prior_same_base and all( + i in acc_matched_sell for i in pool if _base_sig(ledger[i]["tx"]) == b + ) + if acc_has_unclaimed_add or all_prior_same_base_reserved: + acc_new_sales.append(tx) + else: + _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]] = {} @@ -742,12 +953,33 @@ def _mark_uncertain(tx: dict) -> None: if need > 0: ledger.extend(_make_ledger_entry(tx, from_orig=False) for tx in rows[:need]) + def _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 + active_sales = [entry for entry in ledger if not entry["reclassified"]] - dedup_sales = len(active_sales) + recent_active_sales: list[tuple[dict, bool]] = [] + for entry in active_sales: + td = _tx_date_iso(entry["tx"]) + if td is None: + recent_active_sales.append((entry, False)) + elif td >= tx_cutoff: + recent_active_sales.append((entry, True)) + + dedup_sales = len(recent_active_sales) unaffected_orig_sells = ( 0 if unaligned_global - else sum(1 for entry in active_sales if entry["from_orig"] and _owner_key(entry["tx"]) not in affected_owners) + else sum( + 1 + for entry, has_valid_date in recent_active_sales + if has_valid_date and entry["from_orig"] and _owner_key(entry["tx"]) not in affected_owners + ) ) result["sales_90d"] = dedup_sales result["amendments_present"] = has_amendments diff --git a/tools/sec_edgar.py b/tools/sec_edgar.py index 749bfd9..70437f0 100644 --- a/tools/sec_edgar.py +++ b/tools/sec_edgar.py @@ -253,6 +253,7 @@ def form4(cik, filing): ] 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), @@ -276,6 +277,7 @@ def form4(cik, filing): "footnotes": footnotes, "footnote_refs": footnote_refs(row), "remarks": remarks, + "original_filing_date": original_filing_date, "filing_date": filing["filingDate"], "form": filing["form"], "accession": filing["accessionNumber"], @@ -571,7 +573,7 @@ def insider_trades(args): for filing in filings[: args.top]: try: rows = cached( - f"sec-form4-v2:{cik}:{filing['accessionNumber']}", WEEK, lambda filing=filing: form4(cik, filing) + f"sec-form4-v3:{cik}:{filing['accessionNumber']}", WEEK, lambda filing=filing: form4(cik, filing) ) result["transactions"].extend(rows) result["filings_scanned"] += 1 From 77d93fa3ecdb8cb67509eed7c3b7038ea48be7b4 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 04:59:32 +0800 Subject: [PATCH 11/37] fix(risk): tighten sale reclassification regex, avoid false gift restore on price edits, link date corrections --- tests/test_risk_screening.py | 58 +++++++++++ tools/risk_screening.py | 196 ++++++++++++++++++++++++++++------- 2 files changed, 216 insertions(+), 38 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 0baab2e..6a929fa 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -1142,6 +1142,64 @@ def _parse(accn, fdate, form, doc): 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 + + # 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"]) + def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): base_inputs = { diff --git a/tools/risk_screening.py b/tools/risk_screening.py index d87f726..9c1e2da 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -428,11 +428,29 @@ def _base_sig(tx: dict) -> tuple: r"replaces?|supersedes?|restat(?:ed|es|ing|ement)|更正|修正|重分类|误报)", re.IGNORECASE, ) - _SALE_RECLASS_RE = re.compile( - r"(\b(?:sale|sold|sell|code\s+s|transaction\s+code|reclassif(?:ied|y|ying)|instead\s+of|should\s+have\s+been)\b|" - r"\bto\s+(?:a\s+)?(?:bona\s+fide\s+)?gift\b|卖出|出售|重分类|改为赠与)", + _SALE_TO_NONSELL_RE = re.compile( + r"(reclassif(?:ied|y|ying)|transaction\s+code|\bcode\s+s\s+to\b|" + r"(?:from|misreported|erroneously\s+reported|incorrectly\s+reported)\s+(?:as\s+)?(?:a\s+)?(?:[\w-]+\s+){0,3}(?:sale|sell|sold)\b|" + r"(?: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"(?: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, ) + _RESTORE_SELL_RE = re.compile( + r"(reclassif(?:ied|y|ying)|transaction\s+code|\bcode\s+s\b|" + r"(?:was|is|should\s+have\s+been)\s+(?:actually\s+)?(?:a\s+)?(?:open[- ]market\s+)?sale\b|" + r"(?:instead\s+of|not)\s+(?:a\s+)?(?:[\w-]+\s+){0,2}(?:gift|non-sale|transfer)\b|" + r"(?:from|misreported|erroneously\s+reported|incorrectly\s+reported)\s+(?:as\s+)?(?:a\s+)?(?:[\w-]+\s+){0,3}(?:gift|non-sale)\b|" + r"重分类|改为卖出|恢复为卖出|并非赠与)", + re.IGNORECASE, + ) + _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, + ) + _ISO_DATE_RE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b") _COUNT_WORDS = { "two": 2, "three": 3, @@ -612,18 +630,37 @@ def _mark_uncertain(tx: dict) -> None: else: unaligned_global = True - def _scoped_pool(tx: dict, prior_len: int) -> tuple[list[int], bool]: + def _owner_sec_sig(tx: dict) -> tuple: + return (_owner_key(tx), str(tx.get("security") or ""), bool(tx.get("derivative"))) + + def _has_date_corr_evidence(tx: dict, rtext: str) -> bool: + if _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 _scoped_pool(tx: dict, prior_len: int, *, ignore_tx_date: bool = False) -> tuple[list[int], bool]: 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)): return list(range(prior_len)), False pool = [i for i in range(prior_len) if orig_date in ledger[i]["filing_dates"]] if not pool: return [], True - b = _base_sig(tx) - same_base_accs = { - ledger[i]["orig_accession"] for i in pool if _base_sig(ledger[i]["tx"]) == b and ledger[i]["orig_accession"] - } - if len(same_base_accs) > 1: + if ignore_tx_date: + osig = _owner_sec_sig(tx) + same_accs = { + ledger[i]["orig_accession"] + for i in pool + if _owner_sec_sig(ledger[i]["tx"]) == osig and ledger[i]["orig_accession"] + } + else: + b = _base_sig(tx) + same_accs = { + ledger[i]["orig_accession"] + for i in pool + if _base_sig(ledger[i]["tx"]) == b and ledger[i]["orig_accession"] + } + if len(same_accs) > 1: return [], True return pool, False @@ -711,17 +748,9 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) has_ledger_sell = not pool_ambig and any( i not in acc_matched_ns and _base_sig(ledger[i]["tx"]) == base for i in pool ) - has_active_ledger_sell = not pool_ambig and any( - i not in acc_matched_ns and not ledger[i]["reclassified"] and _base_sig(ledger[i]["tx"]) == base - for i in pool - ) - if priced_sell_match or (is_corr and has_ledger_sell and bool(_SALE_RECLASS_RE.search(rtext))): + if priced_sell_match or (is_corr and has_ledger_sell and bool(_SALE_TO_NONSELL_RE.search(rtext))): ns_candidates.append((tx, is_add, is_corr)) continue - if is_corr and has_active_ledger_sell: - acc_orig_ns_matched.add(ns_idx) - _mark_uncertain(tx) - continue acc_orig_ns_matched.add(ns_idx) continue if is_add and not is_corr: @@ -825,24 +854,31 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) # identity across match types, exact matches first, independent of XML row order). acc_matched_sell: set[int] = set() acc_explicit_adds: list[dict] = [] - sell_candidates: list[tuple[dict, bool]] = [] - for tx, (is_add, is_corr), _is_ambig, _rtext in acc_sells: + 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)) + sell_candidates.append((tx, is_corr, rtext)) # Sub-pass 1: exact matches against prior ledger entries first. - after_exact: list[tuple[dict, bool]] = [] - for tx, is_corr in sell_candidates: + after_exact: list[tuple[dict, bool, str]] = [] + for tx, is_corr, rtext in sell_candidates: pool, pool_ambig = _scoped_pool(tx, prior_len) if pool_ambig: _mark_uncertain(tx) continue exact = _exact_sig(tx) exact_cands = [i for i in pool if i not in acc_matched_sell and exact in ledger[i]["sigs"]] - if exact_cands: - if is_corr: + is_restore_intent = is_corr and bool(_RESTORE_SELL_RE.search(rtext)) + corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] + has_explicit_prior_date = ( + is_corr + and _has_date_corr_evidence(tx, rtext) + and bool({d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td}) + ) + if exact_cands and not has_explicit_prior_date: + if is_restore_intent: reclass_cands = [i for i in exact_cands if ledger[i]["reclassified"]] if len(reclass_cands) == 1 or ( len(reclass_cands) > 1 @@ -855,37 +891,53 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) elif reclass_cands: _mark_uncertain(tx) else: - target = exact_cands[0] - acc_matched_sell.add(target) - _update_entry(target, tx) + # Restoration intent with no reclassified exact match: defer to Sub-pass 2/3 rather than + # hijacking an unrelated active sale that happens to share the corrected price. + after_exact.append((tx, is_corr, rtext)) else: active_cands = [i for i in exact_cands if not ledger[i]["reclassified"]] if active_cands: acc_matched_sell.add(active_cands[0]) _update_entry(active_cands[0], tx) + elif is_corr: + # Price/share correction without restoration intent must not restore a reclassified gift + # whose historical price happens to equal the corrected price of another active sale. + after_exact.append((tx, is_corr, rtext)) else: # Unannotated restatement of a previously reclassified sale: keep gift state & mark uncertain. acc_matched_sell.add(exact_cands[0]) _mark_uncertain(tx) else: - after_exact.append((tx, is_corr)) + after_exact.append((tx, is_corr, rtext)) # Sub-pass 2: share-matched restatements against remaining prior ledger entries (order-independent: # multiple distinct-price or mixed-state candidates are left unresolved and marked uncertain). - after_share: list[tuple[dict, bool]] = [] - for tx, is_corr in after_exact: + after_share: list[tuple[dict, bool, str]] = [] + for tx, is_corr, rtext in after_exact: b = _base_sig(tx) shares = tx.get("shares") pool, _ = _scoped_pool(tx, prior_len) + is_restore_intent = is_corr and bool(_RESTORE_SELL_RE.search(rtext)) + corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] + has_explicit_prior_date = ( + is_corr + and _has_date_corr_evidence(tx, rtext) + and bool({d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td}) + ) share_cands: list[int] = [] - if shares is not None and b[0] != ("",) and bool(b[1]): + if not has_explicit_prior_date and shares is not None and b[0] != ("",) and bool(b[1]): share_cands = [ i for i in pool if i not in acc_matched_sell and _base_sig(ledger[i]["tx"]) == b and shares in ledger[i]["shares_set"] + and (is_restore_intent or not ledger[i]["reclassified"] or not is_corr) ] + if is_restore_intent: + reclass_share = [i for i in share_cands if ledger[i]["reclassified"]] + if reclass_share: + share_cands = reclass_share if len(share_cands) == 1 or ( len(share_cands) > 1 and len({(ledger[i]["tx"].get("price"), ledger[i]["reclassified"]) for i in share_cands}) == 1 @@ -893,23 +945,40 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) target = share_cands[0] acc_matched_sell.add(target) was_reclassified = ledger[target]["reclassified"] - _update_entry(target, tx, restore_if_reclassified=is_corr) - if not (is_corr and was_reclassified): + _update_entry(target, tx, restore_if_reclassified=is_restore_intent) + if not (is_restore_intent and was_reclassified): _mark_uncertain(tx) elif len(share_cands) > 1: _mark_uncertain(tx) else: - after_share.append((tx, is_corr)) + after_share.append((tx, is_corr, rtext)) # Sub-pass 3: explicit corrections against remaining prior ledger entries (order-independent: resolve only # when a unique or symmetric candidate exists; otherwise mark uncertain without inflating count). acc_new_sales: list[dict] = list(acc_explicit_adds) - for tx, is_corr in after_share: + for tx, is_corr, rtext in after_share: b = _base_sig(tx) pool, _ = _scoped_pool(tx, prior_len) + is_restore_intent = is_corr and bool(_RESTORE_SELL_RE.search(rtext)) + corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] + has_explicit_prior_date = ( + is_corr + and _has_date_corr_evidence(tx, rtext) + and bool({d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td}) + ) if is_corr: if b[0] != ("",) and bool(b[1]): - base_cands = [i for i in pool if i not in acc_matched_sell and _base_sig(ledger[i]["tx"]) == b] + base_cands = ( + [] + if has_explicit_prior_date + else [ + i + for i in pool + if i not in acc_matched_sell + and _base_sig(ledger[i]["tx"]) == b + and (is_restore_intent or not ledger[i]["reclassified"]) + ] + ) if len(base_cands) == 1 or ( len(base_cands) > 1 and len( @@ -922,9 +991,60 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) ): target = base_cands[0] acc_matched_sell.add(target) - _update_entry(target, tx, restore_if_reclassified=True) + _update_entry(target, tx, restore_if_reclassified=is_restore_intent) _mark_uncertain(tx) continue + # Explicit transaction-date correction: link via prior date / original filing when unique. + if not base_cands and _has_date_corr_evidence(tx, rtext): + dpool, dpool_ambig = _scoped_pool(tx, prior_len, ignore_tx_date=True) + if not dpool_ambig: + osig = _owner_sec_sig(tx) + corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] + prior_dates = {d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td} + date_cands = [ + i + for i in dpool + if i not in acc_matched_sell + and _owner_sec_sig(ledger[i]["tx"]) == osig + and (is_restore_intent or not ledger[i]["reclassified"]) + ] + if prior_dates: + by_prior = [ + i + for i in date_cands + if str( + ledger[i]["tx"].get("transaction_date") or ledger[i]["tx"].get("date") or "" + )[:10] + in prior_dates + ] + if by_prior: + date_cands = by_prior + shares = tx.get("shares") + price = tx.get("price") + if len(date_cands) > 1 and shares is not None and price is not None: + by_sp = [ + i + for i in date_cands + if shares in ledger[i]["shares_set"] and ledger[i]["tx"].get("price") == price + ] + if by_sp: + date_cands = by_sp + if len(date_cands) > 1 and shares is not None: + by_s = [i for i in date_cands if shares in ledger[i]["shares_set"]] + if by_s: + date_cands = by_s + if len(date_cands) == 1: + target = date_cands[0] + acc_matched_sell.add(target) + same_sp = ( + shares is not None + and shares in ledger[target]["shares_set"] + and ledger[target]["tx"].get("price") == price + ) + _update_entry(target, tx, restore_if_reclassified=is_restore_intent) + if not same_sp: + _mark_uncertain(tx) + continue _mark_uncertain(tx) continue # Sub-pass 4: only confirm an unlinked sell row as a new sale when filing evidence supports an addition From 87b22cd64e4236c5710fa562fce43d5f4b6caa0b Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 07:50:48 +0800 Subject: [PATCH 12/37] fix(risk): strict prior-date/price matching, order-independent batch correction waves, preserve confirmed veto --- tests/test_risk_screening.py | 129 ++++++++++ tools/risk_screening.py | 445 ++++++++++++++++++++++++----------- 2 files changed, 443 insertions(+), 131 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 6a929fa..03e2564 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -1180,6 +1180,14 @@ def _parse(accn, fdate, form, doc): 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"), @@ -1200,6 +1208,127 @@ def _parse(accn, fdate, form, doc): 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], transaction_date="2026-08-03", shares=100, price=10.0), + dict(orig_rows[0], transaction_date="2026-08-04", shares=100, price=10.0), + ] + [dict(orig_rows[0], 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"] + == res_batch_21["checks"]["insider_trades"]["count_uncertain"] + ) + # 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 + ) + def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): base_inputs = { diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 9c1e2da..bc1f7c7 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -451,6 +451,44 @@ def _base_sig(tx: dict) -> tuple: re.IGNORECASE, ) _ISO_DATE_RE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b") + _PRIOR_PRICE_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+)?)\b|" + r"\b(?:price|px)\s+(?:from|was|of)\s+\$?\s*(\d+(?:\.\d+)?)\b|" + r"\bat\s+\$\s*(\d+(?:\.\d+)?)\b", + re.IGNORECASE, + ) + _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})", + re.IGNORECASE, + ) + + def _stated_prior_prices(rtext: str, new_price) -> set[float]: + out: set[float] = set() + new_f = _safe_float(new_price) + for m in _PRIOR_PRICE_RE.finditer(rtext): + tok = next((g for g in m.groups() if g), "") + 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 _stated_prior_shares(rtext: str, new_shares) -> set[float]: + out: set[float] = set() + new_f = _safe_float(new_shares) + for m in _PRIOR_SHARES_RE.finditer(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 _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) + _COUNT_WORDS = { "two": 2, "three": 3, @@ -639,7 +677,13 @@ def _has_date_corr_evidence(tx: dict, rtext: str) -> bool: refs = tx.get("footnote_refs") return isinstance(refs, dict) and any("transactiondate" in str(k).lower() for k in refs) - def _scoped_pool(tx: dict, prior_len: int, *, ignore_tx_date: bool = False) -> tuple[list[int], bool]: + def _scoped_pool( + tx: dict, + prior_len: int, + *, + ignore_tx_date: bool = False, + prior_dates: set[str] | None = None, + ) -> tuple[list[int], bool]: 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)): return list(range(prior_len)), False @@ -648,18 +692,24 @@ def _scoped_pool(tx: dict, prior_len: int, *, ignore_tx_date: bool = False) -> t return [], True if ignore_tx_date: osig = _owner_sec_sig(tx) - same_accs = { - ledger[i]["orig_accession"] - for i in pool - if _owner_sec_sig(ledger[i]["tx"]) == osig and ledger[i]["orig_accession"] - } - else: - b = _base_sig(tx) - same_accs = { - ledger[i]["orig_accession"] - for i in pool - if _base_sig(ledger[i]["tx"]) == b and ledger[i]["orig_accession"] - } + eligible = [i for i in pool if _owner_sec_sig(ledger[i]["tx"]) == osig] + if prior_dates: + eligible = [ + i + for i in eligible + if str(ledger[i]["tx"].get("transaction_date") or ledger[i]["tx"].get("date") or "")[:10] + in prior_dates + ] + if not eligible: + return [], True + same_accs = {ledger[i]["orig_accession"] for i in eligible if ledger[i]["orig_accession"]} + if len(same_accs) > 1: + return [], True + return eligible if prior_dates else pool, False + b = _base_sig(tx) + same_accs = { + ledger[i]["orig_accession"] for i in pool if _base_sig(ledger[i]["tx"]) == b and ledger[i]["orig_accession"] + } if len(same_accs) > 1: return [], True return pool, False @@ -910,13 +960,24 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) else: after_exact.append((tx, is_corr, rtext)) - # Sub-pass 2: share-matched restatements against remaining prior ledger entries (order-independent: - # multiple distinct-price or mixed-state candidates are left unresolved and marked uncertain). - after_share: list[tuple[dict, bool, str]] = [] - for tx, is_corr, rtext in after_exact: + # Sub-pass 2: share-matched restatements against remaining prior ledger entries (order-independent batch + # waves: multiple distinct-price or mixed-state candidates are deferred and left uncertain unless uniquely + # resolved by stated prior price or non-conflicting reservations). + pending_share = list(enumerate(after_exact)) + resolved_share: set[int] = set() + uncertain_share: set[int] = set() + + def _share_match_cands( + tx: dict, + is_corr: bool, + rtext: str, + *, + p_len: int = prior_len, + matched: set[int] = acc_matched_sell, + ) -> tuple[list[int], bool, bool, bool]: b = _base_sig(tx) shares = tx.get("shares") - pool, _ = _scoped_pool(tx, prior_len) + pool, _ = _scoped_pool(tx, p_len) is_restore_intent = is_corr and bool(_RESTORE_SELL_RE.search(rtext)) corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] has_explicit_prior_date = ( @@ -924,132 +985,254 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) and _has_date_corr_evidence(tx, rtext) and bool({d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td}) ) - share_cands: list[int] = [] - if not has_explicit_prior_date and shares is not None and b[0] != ("",) and bool(b[1]): - share_cands = [ - i - for i in pool - if i not in acc_matched_sell - and _base_sig(ledger[i]["tx"]) == b - and shares in ledger[i]["shares_set"] - and (is_restore_intent or not ledger[i]["reclassified"] or not is_corr) - ] - if is_restore_intent: - reclass_share = [i for i in share_cands if ledger[i]["reclassified"]] - if reclass_share: - share_cands = reclass_share - if len(share_cands) == 1 or ( - len(share_cands) > 1 - and len({(ledger[i]["tx"].get("price"), ledger[i]["reclassified"]) for i in share_cands}) == 1 - ): - target = share_cands[0] - acc_matched_sell.add(target) - was_reclassified = ledger[target]["reclassified"] - _update_entry(target, tx, restore_if_reclassified=is_restore_intent) - if not (is_restore_intent and was_reclassified): - _mark_uncertain(tx) - elif len(share_cands) > 1: + if has_explicit_prior_date or shares is None or b[0] == ("",) or not bool(b[1]): + return [], is_restore_intent, False, False + cands = [ + i + for i in pool + if i not in matched + and _base_sig(ledger[i]["tx"]) == b + and shares in ledger[i]["shares_set"] + and (is_restore_intent or not ledger[i]["reclassified"] or not is_corr) + ] + if is_restore_intent: + reclass_share = [i for i in cands if ledger[i]["reclassified"]] + if reclass_share: + cands = reclass_share + prior_prices = _stated_prior_prices(rtext, tx.get("price")) if is_corr else set() + if prior_prices and cands: + # Require matching the stated prior price; never substitute a different price when unmatched. + filtered = [i for i in cands if _matches_num_set(ledger[i]["tx"].get("price"), prior_prices)] + return filtered, is_restore_intent, True, True + return cands, is_restore_intent, False, False + + while True: + single_claims: dict[int, list[tuple[int, dict, bool, bool]]] = {} + sym_claims: dict[tuple[int, ...], list[tuple[int, dict, bool, bool]]] = {} + for ridx, (tx, is_corr, rtext) in pending_share: + if ridx in resolved_share or ridx in uncertain_share: + continue + cands, is_restore_intent, identified_prior, _ = _share_match_cands(tx, is_corr, rtext) + if len(cands) == 1: + single_claims.setdefault(cands[0], []).append((ridx, tx, is_restore_intent, identified_prior)) + elif ( + len(cands) > 1 + and len({(ledger[i]["tx"].get("price"), ledger[i]["reclassified"]) for i in cands}) == 1 + ): + sym_claims.setdefault(tuple(sorted(cands)), []).append( + (ridx, tx, is_restore_intent, identified_prior) + ) + progressed = False + claimed_targets: set[int] = set() + for target, claimants in single_claims.items(): + if len(claimants) == 1: + ridx, tx, is_restore_intent, identified_prior = claimants[0] + was_reclassified = ledger[target]["reclassified"] + acc_matched_sell.add(target) + claimed_targets.add(target) + _update_entry(target, tx, restore_if_reclassified=is_restore_intent) + if not (identified_prior or (is_restore_intent and was_reclassified)): + _mark_uncertain(tx) + resolved_share.add(ridx) + progressed = True + for slots, claimants in sym_claims.items(): + if any(s in claimed_targets for s in slots): + continue + if len(claimants) <= len(slots): + for slot, (ridx, tx, is_restore_intent, identified_prior) in zip(slots, claimants): + was_reclassified = ledger[slot]["reclassified"] + acc_matched_sell.add(slot) + _update_entry(slot, tx, restore_if_reclassified=is_restore_intent) + if not (identified_prior or (is_restore_intent and was_reclassified)): + _mark_uncertain(tx) + resolved_share.add(ridx) + progressed = True + if not progressed: + break + + after_share: list[tuple[dict, bool, str]] = [] + for ridx, (tx, is_corr, rtext) in pending_share: + if ridx in resolved_share: + continue + cands, _is_restore, _ident, had_prior_price = _share_match_cands(tx, is_corr, rtext) + if len(cands) >= 1 or had_prior_price: _mark_uncertain(tx) else: after_share.append((tx, is_corr, rtext)) - # Sub-pass 3: explicit corrections against remaining prior ledger entries (order-independent: resolve only - # when a unique or symmetric candidate exists; otherwise mark uncertain without inflating count). + # Sub-pass 3: explicit corrections against remaining prior ledger entries (order-independent batch waves: + # resolve non-conflicting unique assignments iteratively against the shared pre-wave ledger state so both + # row orders produce identical ledger dates, confirmed counts, and uncertainty marks). acc_new_sales: list[dict] = list(acc_explicit_adds) - for tx, is_corr, rtext in after_share: + corr_rows = [(idx, tx, rtext) for idx, (tx, is_corr, rtext) in enumerate(after_share) if is_corr] + unlinked_non_corr = [(tx, rtext) for tx, is_corr, rtext in after_share if not is_corr] + + def _corr_match_cands( + tx: dict, + rtext: str, + *, + p_len: int = prior_len, + matched: set[int] = acc_matched_sell, + ) -> tuple[list[int], bool, bool, bool]: b = _base_sig(tx) - pool, _ = _scoped_pool(tx, prior_len) - is_restore_intent = is_corr and bool(_RESTORE_SELL_RE.search(rtext)) + if b[0] == ("",) or not bool(b[1]): + return [], False, False, False + is_restore_intent = bool(_RESTORE_SELL_RE.search(rtext)) corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] - has_explicit_prior_date = ( - is_corr - and _has_date_corr_evidence(tx, rtext) - and bool({d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td}) + prior_dates = ( + {d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td} + if _has_date_corr_evidence(tx, rtext) + else set() ) - if is_corr: - if b[0] != ("",) and bool(b[1]): - base_cands = ( - [] - if has_explicit_prior_date - else [ + prior_prices = _stated_prior_prices(rtext, tx.get("price")) + prior_shares = _stated_prior_shares(rtext, tx.get("shares")) + if not prior_dates: + pool, pool_ambig = _scoped_pool(tx, p_len) + if not pool_ambig: + base_cands = [ + i + for i in pool + if i not in matched + and _base_sig(ledger[i]["tx"]) == b + and (is_restore_intent or not ledger[i]["reclassified"]) + ] + if prior_shares: + base_cands = [ i - for i in pool - if i not in acc_matched_sell - and _base_sig(ledger[i]["tx"]) == b - and (is_restore_intent or not ledger[i]["reclassified"]) + for i in base_cands + if any(_matches_num_set(s, prior_shares) for s in ledger[i]["shares_set"]) ] + if prior_prices: + base_cands = [ + i for i in base_cands if _matches_num_set(ledger[i]["tx"].get("price"), prior_prices) + ] + if base_cands: + return base_cands, is_restore_intent, bool(prior_shares or prior_prices), False + # Explicit transaction-date correction: link via prior date / original filing when unique. + if _has_date_corr_evidence(tx, rtext): + dpool, dpool_ambig = _scoped_pool( + tx, + p_len, + ignore_tx_date=True, + prior_dates=prior_dates or None, + ) + if dpool_ambig: + return [], is_restore_intent, False, True + osig = _owner_sec_sig(tx) + date_cands = [ + i + for i in dpool + if i not in matched + and _owner_sec_sig(ledger[i]["tx"]) == osig + and (is_restore_intent or not ledger[i]["reclassified"]) + ] + if prior_dates: + # Strict prior-date match: never substitute a different date when the stated prior date is absent. + date_cands = [ + i + for i in date_cands + if str(ledger[i]["tx"].get("transaction_date") or ledger[i]["tx"].get("date") or "")[:10] + in prior_dates + ] + if prior_shares: + date_cands = [ + i for i in date_cands if any(_matches_num_set(s, prior_shares) for s in ledger[i]["shares_set"]) + ] + if prior_prices: + date_cands = [i for i in date_cands if _matches_num_set(ledger[i]["tx"].get("price"), prior_prices)] + shares = tx.get("shares") + price = tx.get("price") + if len(date_cands) > 1 and shares is not None and price is not None: + by_sp = [ + i + for i in date_cands + if shares in ledger[i]["shares_set"] and ledger[i]["tx"].get("price") == price + ] + if by_sp: + date_cands = by_sp + if len(date_cands) > 1 and shares is not None: + by_s = [i for i in date_cands if shares in ledger[i]["shares_set"]] + if by_s: + date_cands = by_s + 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]]] = {} + sym_corr_claims: dict[tuple[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) ) - if len(base_cands) == 1 or ( - len(base_cands) > 1 - and len( - { - (ledger[i]["tx"].get("shares"), ledger[i]["tx"].get("price"), ledger[i]["reclassified"]) - for i in base_cands - } - ) - == 1 - ): - target = base_cands[0] - acc_matched_sell.add(target) - _update_entry(target, tx, restore_if_reclassified=is_restore_intent) + elif ( + len(cands) > 1 + and len( + { + ( + str(ledger[i]["tx"].get("transaction_date") or ledger[i]["tx"].get("date") or "")[:10], + ledger[i]["tx"].get("shares"), + ledger[i]["tx"].get("price"), + ledger[i]["reclassified"], + ) + for i in cands + } + ) + == 1 + ): + sym_corr_claims.setdefault(tuple(sorted(cands)), []).append( + (ridx, tx, is_restore_intent, identified_prior, is_date_match) + ) + progressed = False + claimed_targets: set[int] = set() + for target, claimants in single_corr_claims.items(): + if len(claimants) == 1: + ridx, tx, is_restore_intent, identified_prior, is_date_match = claimants[0] + same_sp = ( + tx.get("shares") is not None + and tx.get("shares") in ledger[target]["shares_set"] + and ledger[target]["tx"].get("price") == tx.get("price") + ) + acc_matched_sell.add(target) + claimed_targets.add(target) + _update_entry(target, tx, restore_if_reclassified=is_restore_intent) + if not ((is_date_match and (same_sp or identified_prior)) or identified_prior): _mark_uncertain(tx) - continue - # Explicit transaction-date correction: link via prior date / original filing when unique. - if not base_cands and _has_date_corr_evidence(tx, rtext): - dpool, dpool_ambig = _scoped_pool(tx, prior_len, ignore_tx_date=True) - if not dpool_ambig: - osig = _owner_sec_sig(tx) - corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] - prior_dates = {d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td} - date_cands = [ - i - for i in dpool - if i not in acc_matched_sell - and _owner_sec_sig(ledger[i]["tx"]) == osig - and (is_restore_intent or not ledger[i]["reclassified"]) - ] - if prior_dates: - by_prior = [ - i - for i in date_cands - if str( - ledger[i]["tx"].get("transaction_date") or ledger[i]["tx"].get("date") or "" - )[:10] - in prior_dates - ] - if by_prior: - date_cands = by_prior - shares = tx.get("shares") - price = tx.get("price") - if len(date_cands) > 1 and shares is not None and price is not None: - by_sp = [ - i - for i in date_cands - if shares in ledger[i]["shares_set"] and ledger[i]["tx"].get("price") == price - ] - if by_sp: - date_cands = by_sp - if len(date_cands) > 1 and shares is not None: - by_s = [i for i in date_cands if shares in ledger[i]["shares_set"]] - if by_s: - date_cands = by_s - if len(date_cands) == 1: - target = date_cands[0] - acc_matched_sell.add(target) - same_sp = ( - shares is not None - and shares in ledger[target]["shares_set"] - and ledger[target]["tx"].get("price") == price - ) - _update_entry(target, tx, restore_if_reclassified=is_restore_intent) - if not same_sp: - _mark_uncertain(tx) - continue + resolved_corr.add(ridx) + progressed = True + for slots, claimants in sym_corr_claims.items(): + if any(s in claimed_targets for s in slots): + continue + if len(claimants) <= len(slots): + for slot, (ridx, tx, is_restore_intent, identified_prior, is_date_match) in zip(slots, claimants): + same_sp = ( + tx.get("shares") is not None + and tx.get("shares") in ledger[slot]["shares_set"] + and ledger[slot]["tx"].get("price") == tx.get("price") + ) + acc_matched_sell.add(slot) + _update_entry(slot, tx, restore_if_reclassified=is_restore_intent) + if not ((is_date_match and (same_sp or identified_prior)) or identified_prior): + _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) - continue - # Sub-pass 4: only confirm an unlinked sell row as a new sale when filing evidence supports an addition - # (unclaimed remarks addition, or every prior entry on that base signature was already reserved in this - # same accession). Otherwise report uncertainty without inflating the confirmed sale count. + + # Sub-pass 4: only confirm an unlinked sell row as a new sale when filing evidence supports an addition + # (unclaimed remarks addition, or every prior entry on that base signature was already reserved in this + # same accession). Otherwise report uncertainty without inflating the confirmed sale count. + for tx, _rtext in unlinked_non_corr: + b = _base_sig(tx) + pool, _ = _scoped_pool(tx, prior_len) has_prior_same_base = any(_base_sig(ledger[i]["tx"]) == b for i in pool) all_prior_same_base_reserved = has_prior_same_base and all( i in acc_matched_sell for i in pool if _base_sig(ledger[i]["tx"]) == b From 8c2b96e6adb0e4aa0f7fb62aa2f0a4fe27a16a6f Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 08:07:30 +0800 Subject: [PATCH 13/37] fix(risk): parse grouped prior prices, defer multi-accession ambiguity, route prior-share edits, drop positional symmetric assignment --- tests/test_risk_screening.py | 121 ++++++++++++++++++++++++- tools/risk_screening.py | 168 +++++++++++++++-------------------- 2 files changed, 189 insertions(+), 100 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 03e2564..84cdbf0 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -1310,10 +1310,8 @@ def _parse(accn, fdate, form, doc): 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"] - == res_batch_21["checks"]["insider_trades"]["count_uncertain"] - ) + 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, @@ -1329,6 +1327,121 @@ def _parse(accn, fdate, form, doc): 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", + footnotes={"F1": "Corrects 200 shares at $20 on 2026-08-03 to 2026-07-31."}, + 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=11.0, + footnotes={"F1": "Corrects transaction date from 2026-08-03 to 2026-07-31 at $11."}, + 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"] == res_sym_ba["checks"]["insider_trades"]["sales_90d"] + assert res_sym_ab["checks"]["insider_trades"]["count_uncertain"] is True + assert res_sym_ba["checks"]["insider_trades"]["count_uncertain"] is True + def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): base_inputs = { diff --git a/tools/risk_screening.py b/tools/risk_screening.py index bc1f7c7..a8ebdf4 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -453,9 +453,9 @@ def _base_sig(tx: dict) -> tuple: _ISO_DATE_RE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b") _PRIOR_PRICE_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+)?)\b|" - r"\b(?:price|px)\s+(?:from|was|of)\s+\$?\s*(\d+(?:\.\d+)?)\b|" - r"\bat\s+\$\s*(\d+(?:\.\d+)?)\b", + 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|" + r"\bat\s+\$\s*(\d+(?:,\d{3})*(?:\.\d+)?)\b", re.IGNORECASE, ) _PRIOR_SHARES_RE = re.compile( @@ -469,7 +469,7 @@ def _stated_prior_prices(rtext: str, new_price) -> set[float]: out: set[float] = set() new_f = _safe_float(new_price) for m in _PRIOR_PRICE_RE.finditer(rtext): - tok = next((g for g in m.groups() if g), "") + 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) @@ -683,6 +683,7 @@ def _scoped_pool( *, ignore_tx_date: bool = False, prior_dates: set[str] | None = None, + check_multi_acc: bool = True, ) -> tuple[list[int], bool]: 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)): @@ -702,16 +703,20 @@ def _scoped_pool( ] if not eligible: return [], True - same_accs = {ledger[i]["orig_accession"] for i in eligible if ledger[i]["orig_accession"]} + if check_multi_acc: + same_accs = {ledger[i]["orig_accession"] for i in eligible if ledger[i]["orig_accession"]} + if len(same_accs) > 1: + return [], True + return eligible if prior_dates else pool, False + if check_multi_acc: + b = _base_sig(tx) + same_accs = { + ledger[i]["orig_accession"] + for i in pool + if _base_sig(ledger[i]["tx"]) == b and ledger[i]["orig_accession"] + } if len(same_accs) > 1: return [], True - return eligible if prior_dates else pool, False - b = _base_sig(tx) - same_accs = { - ledger[i]["orig_accession"] for i in pool if _base_sig(ledger[i]["tx"]) == b and ledger[i]["orig_accession"] - } - if len(same_accs) > 1: - return [], True return pool, False def _mark_reclassified(idx: int, tx: dict) -> None: @@ -914,12 +919,6 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) # Sub-pass 1: exact matches against prior ledger entries first. after_exact: list[tuple[dict, bool, str]] = [] for tx, is_corr, rtext in sell_candidates: - pool, pool_ambig = _scoped_pool(tx, prior_len) - if pool_ambig: - _mark_uncertain(tx) - continue - exact = _exact_sig(tx) - exact_cands = [i for i in pool if i not in acc_matched_sell and exact in ledger[i]["sigs"]] is_restore_intent = is_corr and bool(_RESTORE_SELL_RE.search(rtext)) corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] has_explicit_prior_date = ( @@ -927,14 +926,21 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) and _has_date_corr_evidence(tx, rtext) and bool({d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td}) ) - if exact_cands and not has_explicit_prior_date: + has_explicit_prior_shares = is_corr and bool(_stated_prior_shares(rtext, tx.get("shares"))) + has_explicit_prior_price = is_corr and bool(_stated_prior_prices(rtext, tx.get("price"))) + if has_explicit_prior_date or has_explicit_prior_shares or has_explicit_prior_price: + after_exact.append((tx, is_corr, rtext)) + continue + pool, pool_ambig = _scoped_pool(tx, prior_len) + if pool_ambig: + _mark_uncertain(tx) + continue + exact = _exact_sig(tx) + exact_cands = [i for i in pool if i not in acc_matched_sell and exact in ledger[i]["sigs"]] + if exact_cands: if is_restore_intent: reclass_cands = [i for i in exact_cands if ledger[i]["reclassified"]] - if len(reclass_cands) == 1 or ( - len(reclass_cands) > 1 - and len({(ledger[i]["tx"].get("price"), ledger[i]["tx"].get("shares")) for i in reclass_cands}) - == 1 - ): + if len(reclass_cands) == 1: target = reclass_cands[0] acc_matched_sell.add(target) _update_entry(target, tx, restore_if_reclassified=True) @@ -961,11 +967,10 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) after_exact.append((tx, is_corr, rtext)) # Sub-pass 2: share-matched restatements against remaining prior ledger entries (order-independent batch - # waves: multiple distinct-price or mixed-state candidates are deferred and left uncertain unless uniquely - # resolved by stated prior price or non-conflicting reservations). + # waves: only non-conflicting unique candidates are committed; rows stating changed prior shares or prior + # dates route directly to Sub-pass 3, and indistinguishable multi-candidate groups stay uncertain). pending_share = list(enumerate(after_exact)) resolved_share: set[int] = set() - uncertain_share: set[int] = set() def _share_match_cands( tx: dict, @@ -977,7 +982,6 @@ def _share_match_cands( ) -> tuple[list[int], bool, bool, bool]: b = _base_sig(tx) shares = tx.get("shares") - pool, _ = _scoped_pool(tx, p_len) is_restore_intent = is_corr and bool(_RESTORE_SELL_RE.search(rtext)) corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] has_explicit_prior_date = ( @@ -985,8 +989,19 @@ def _share_match_cands( and _has_date_corr_evidence(tx, rtext) and bool({d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td}) ) - if has_explicit_prior_date or shares is None or b[0] == ("",) or not bool(b[1]): + has_explicit_prior_shares = is_corr and bool(_stated_prior_shares(rtext, shares)) + if ( + has_explicit_prior_date + or has_explicit_prior_shares + or shares is None + or b[0] == ("",) + or not bool(b[1]) + ): return [], is_restore_intent, False, False + prior_prices = _stated_prior_prices(rtext, tx.get("price")) if is_corr else set() + pool, pool_ambig = _scoped_pool(tx, p_len, check_multi_acc=not bool(prior_prices)) + if pool_ambig: + return [], is_restore_intent, False, bool(prior_prices) cands = [ i for i in pool @@ -999,54 +1014,39 @@ def _share_match_cands( reclass_share = [i for i in cands if ledger[i]["reclassified"]] if reclass_share: cands = reclass_share - prior_prices = _stated_prior_prices(rtext, tx.get("price")) if is_corr else set() + orig_date = str(tx.get("original_filing_date") or "").strip() if prior_prices and cands: # Require matching the stated prior price; never substitute a different price when unmatched. filtered = [i for i in cands if _matches_num_set(ledger[i]["tx"].get("price"), prior_prices)] + if ( + orig_date + and len({ledger[i]["orig_accession"] for i in filtered if ledger[i]["orig_accession"]}) > 1 + ): + return [], is_restore_intent, False, True return filtered, is_restore_intent, True, True + if orig_date and len({ledger[i]["orig_accession"] for i in cands if ledger[i]["orig_accession"]}) > 1: + return [], is_restore_intent, False, True return cands, is_restore_intent, False, False while True: single_claims: dict[int, list[tuple[int, dict, bool, bool]]] = {} - sym_claims: dict[tuple[int, ...], list[tuple[int, dict, bool, bool]]] = {} for ridx, (tx, is_corr, rtext) in pending_share: - if ridx in resolved_share or ridx in uncertain_share: + if ridx in resolved_share: continue cands, is_restore_intent, identified_prior, _ = _share_match_cands(tx, is_corr, rtext) if len(cands) == 1: single_claims.setdefault(cands[0], []).append((ridx, tx, is_restore_intent, identified_prior)) - elif ( - len(cands) > 1 - and len({(ledger[i]["tx"].get("price"), ledger[i]["reclassified"]) for i in cands}) == 1 - ): - sym_claims.setdefault(tuple(sorted(cands)), []).append( - (ridx, tx, is_restore_intent, identified_prior) - ) progressed = False - claimed_targets: set[int] = set() for target, claimants in single_claims.items(): if len(claimants) == 1: ridx, tx, is_restore_intent, identified_prior = claimants[0] was_reclassified = ledger[target]["reclassified"] acc_matched_sell.add(target) - claimed_targets.add(target) _update_entry(target, tx, restore_if_reclassified=is_restore_intent) if not (identified_prior or (is_restore_intent and was_reclassified)): _mark_uncertain(tx) resolved_share.add(ridx) progressed = True - for slots, claimants in sym_claims.items(): - if any(s in claimed_targets for s in slots): - continue - if len(claimants) <= len(slots): - for slot, (ridx, tx, is_restore_intent, identified_prior) in zip(slots, claimants): - was_reclassified = ledger[slot]["reclassified"] - acc_matched_sell.add(slot) - _update_entry(slot, tx, restore_if_reclassified=is_restore_intent) - if not (identified_prior or (is_restore_intent and was_reclassified)): - _mark_uncertain(tx) - resolved_share.add(ridx) - progressed = True if not progressed: break @@ -1054,15 +1054,15 @@ def _share_match_cands( for ridx, (tx, is_corr, rtext) in pending_share: if ridx in resolved_share: continue - cands, _is_restore, _ident, had_prior_price = _share_match_cands(tx, is_corr, rtext) - if len(cands) >= 1 or had_prior_price: + cands, _is_restore, _ident, stop_here = _share_match_cands(tx, is_corr, rtext) + if len(cands) >= 1 or stop_here: _mark_uncertain(tx) else: after_share.append((tx, is_corr, rtext)) # Sub-pass 3: explicit corrections against remaining prior ledger entries (order-independent batch waves: - # resolve non-conflicting unique assignments iteratively against the shared pre-wave ledger state so both - # row orders produce identical ledger dates, confirmed counts, and uncertainty marks). + # resolve only non-conflicting unique assignments iteratively against the shared pre-wave ledger state so + # both row orders produce identical ledger dates, confirmed counts, and uncertainty marks). acc_new_sales: list[dict] = list(acc_explicit_adds) corr_rows = [(idx, tx, rtext) for idx, (tx, is_corr, rtext) in enumerate(after_share) if is_corr] unlinked_non_corr = [(tx, rtext) for tx, is_corr, rtext in after_share if not is_corr] @@ -1078,6 +1078,7 @@ def _corr_match_cands( if b[0] == ("",) or not bool(b[1]): return [], False, False, False is_restore_intent = bool(_RESTORE_SELL_RE.search(rtext)) + orig_date = str(tx.get("original_filing_date") or "").strip() corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] prior_dates = ( {d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td} @@ -1087,7 +1088,7 @@ def _corr_match_cands( prior_prices = _stated_prior_prices(rtext, tx.get("price")) prior_shares = _stated_prior_shares(rtext, tx.get("shares")) if not prior_dates: - pool, pool_ambig = _scoped_pool(tx, p_len) + pool, pool_ambig = _scoped_pool(tx, p_len, check_multi_acc=False) if not pool_ambig: base_cands = [ i @@ -1106,15 +1107,22 @@ def _corr_match_cands( base_cands = [ i for i in base_cands if _matches_num_set(ledger[i]["tx"].get("price"), prior_prices) ] + if ( + orig_date + and len({ledger[i]["orig_accession"] for i in base_cands if ledger[i]["orig_accession"]}) > 1 + ): + return [], is_restore_intent, False, False if base_cands: return base_cands, is_restore_intent, bool(prior_shares or prior_prices), False - # Explicit transaction-date correction: link via prior date / original filing when unique. + # Explicit transaction-date correction: link via prior date / original filing after applying explicit + # row identifiers (old shares/price or unchanged shares/price), then check accession uniqueness. if _has_date_corr_evidence(tx, rtext): dpool, dpool_ambig = _scoped_pool( tx, p_len, ignore_tx_date=True, prior_dates=prior_dates or None, + check_multi_acc=False, ) if dpool_ambig: return [], is_restore_intent, False, True @@ -1154,13 +1162,17 @@ def _corr_match_cands( by_s = [i for i in date_cands if shares in ledger[i]["shares_set"]] if by_s: date_cands = by_s + if ( + orig_date + and len({ledger[i]["orig_accession"] for i in date_cands if ledger[i]["orig_accession"]}) > 1 + ): + 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]]] = {} - sym_corr_claims: dict[tuple[int, ...], list[tuple[int, dict, bool, bool, bool]]] = {} for ridx, tx, rtext in corr_rows: if ridx in resolved_corr: continue @@ -1169,26 +1181,7 @@ def _corr_match_cands( single_corr_claims.setdefault(cands[0], []).append( (ridx, tx, is_restore_intent, identified_prior, is_date_match) ) - elif ( - len(cands) > 1 - and len( - { - ( - str(ledger[i]["tx"].get("transaction_date") or ledger[i]["tx"].get("date") or "")[:10], - ledger[i]["tx"].get("shares"), - ledger[i]["tx"].get("price"), - ledger[i]["reclassified"], - ) - for i in cands - } - ) - == 1 - ): - sym_corr_claims.setdefault(tuple(sorted(cands)), []).append( - (ridx, tx, is_restore_intent, identified_prior, is_date_match) - ) progressed = False - claimed_targets: set[int] = set() for target, claimants in single_corr_claims.items(): if len(claimants) == 1: ridx, tx, is_restore_intent, identified_prior, is_date_match = claimants[0] @@ -1198,28 +1191,11 @@ def _corr_match_cands( and ledger[target]["tx"].get("price") == tx.get("price") ) acc_matched_sell.add(target) - claimed_targets.add(target) _update_entry(target, tx, restore_if_reclassified=is_restore_intent) if not ((is_date_match and (same_sp or identified_prior)) or identified_prior): _mark_uncertain(tx) resolved_corr.add(ridx) progressed = True - for slots, claimants in sym_corr_claims.items(): - if any(s in claimed_targets for s in slots): - continue - if len(claimants) <= len(slots): - for slot, (ridx, tx, is_restore_intent, identified_prior, is_date_match) in zip(slots, claimants): - same_sp = ( - tx.get("shares") is not None - and tx.get("shares") in ledger[slot]["shares_set"] - and ledger[slot]["tx"].get("price") == tx.get("price") - ) - acc_matched_sell.add(slot) - _update_entry(slot, tx, restore_if_reclassified=is_restore_intent) - if not ((is_date_match and (same_sp or identified_prior)) or identified_prior): - _mark_uncertain(tx) - resolved_corr.add(ridx) - progressed = True if not progressed: break From 547ffaccb112410ecaefc86da07b9c6b6ee12c01 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 08:19:59 +0800 Subject: [PATCH 14/37] fix(risk): match same-revision prior tuples, batch two-phase exact matching, prioritize explicit corrections over heuristic share match --- tests/test_risk_screening.py | 176 +++++++++++++- tools/risk_screening.py | 441 +++++++++++++++++++++-------------- 2 files changed, 437 insertions(+), 180 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 84cdbf0..0026b5f 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -1377,7 +1377,9 @@ def _parse(accn, fdate, form, doc): filing_date="2026-08-08", original_filing_date="2026-08-06", transaction_date="2026-07-31", - footnotes={"F1": "Corrects 200 shares at $20 on 2026-08-03 to 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") @@ -1432,16 +1434,182 @@ def _parse(accn, fdate, form, doc): filing_date="2026-08-08", original_filing_date="2026-08-05", transaction_date="2026-07-31", - price=11.0, - footnotes={"F1": "Corrects transaction date from 2026-08-03 to 2026-07-31 at $11."}, + 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"] == res_sym_ba["checks"]["insider_trades"]["sales_90d"] + 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"]}, + ) + 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 + + # 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 + def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): base_inputs = { diff --git a/tools/risk_screening.py b/tools/risk_screening.py index a8ebdf4..9abbf8f 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -451,11 +451,16 @@ def _base_sig(tx: dict) -> tuple: re.IGNORECASE, ) _ISO_DATE_RE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b") - _PRIOR_PRICE_RE = re.compile( + _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|" - r"\bat\s+\$\s*(\d+(?:,\d{3})*(?:\.\d+)?)\b", + r"\b(?:price|px)\s+(?:from|was|of)\s+\$?\s*(\d+(?:,\d{3})*(?:\.\d+)?)\b", + re.IGNORECASE, + ) + _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, ) _PRIOR_SHARES_RE = re.compile( @@ -465,20 +470,34 @@ def _base_sig(tx: dict) -> tuple: re.IGNORECASE, ) + def _correction_sentences(rtext: str) -> str: + sents = [s for s in re.split(r"[.!?;。!?;]+", rtext) if s.strip()] + corr_sents = [s for s in sents if _CORRECTION_RE.search(s)] + return ". ".join(corr_sents) if corr_sents else rtext + def _stated_prior_prices(rtext: str, new_price) -> set[float]: - out: set[float] = set() new_f = _safe_float(new_price) - for m in _PRIOR_PRICE_RE.finditer(rtext): + scoped = _correction_sentences(rtext) + explicit: set[float] = set() + for m in _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)): - out.add(val) - return out + explicit.add(val) + if explicit: + return explicit + linked: set[float] = set() + for m in _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 _stated_prior_shares(rtext: str, new_shares) -> set[float]: out: set[float] = set() new_f = _safe_float(new_shares) - for m in _PRIOR_SHARES_RE.finditer(rtext): + for m in _PRIOR_SHARES_RE.finditer(_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)): @@ -640,6 +659,10 @@ def _resolve_accession_intents( "amendment" in w.lower() or "double-count" in w.lower() for w in sec_warnings ) + def _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 _make_ledger_entry(tx: dict, *, from_orig: bool) -> dict: shares = tx.get("shares") fdate = str(tx.get("filing_date") or "").strip() @@ -647,6 +670,7 @@ def _make_ledger_entry(tx: dict, *, from_orig: bool) -> dict: "tx": tx, "orig_tx": tx, "sigs": {_exact_sig(tx)}, + "revisions": [_rev_tuple(tx)], "shares_set": {shares} if shares is not None else set(), "filing_dates": {fdate} if fdate else set(), "orig_accession": str(tx.get("accession") or "").strip() or None, @@ -654,6 +678,29 @@ def _make_ledger_entry(tx: dict, *, from_orig: bool) -> dict: "reclassified": False, } + def _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, + ) -> bool: + for rev_date, rev_shares, rev_price in entry["revisions"]: + if dates is not None and rev_date not in dates: + continue + if shares_target is not None and not _matches_num_set(rev_shares, shares_target): + continue + if price_target is not None and not _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 + # Unified chronological transaction ledger initialized from original Form 4 filings. ledger: list[dict] = [_make_ledger_entry(tx, from_orig=True) for tx in all_orig if _is_sell(tx)] known_non_sells: list[dict] = [tx for tx in all_orig if not _is_sell(tx)] @@ -730,6 +777,9 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) entry = ledger[idx] entry["tx"] = tx entry["sigs"].add(_exact_sig(tx)) + rev = _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")) fdate = str(tx.get("filing_date") or "").strip() @@ -830,6 +880,9 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) exact = _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: + cur_exact = [i for i in exact_cands if _exact_sig(ledger[i]["tx"]) == exact] + if cur_exact: + exact_cands = cur_exact # Prefer already-reclassified entry for idempotence across successive gift 4/A filings. reclass_exact = [i for i in exact_cands if ledger[i]["reclassified"]] target = reclass_exact[0] if reclass_exact else exact_cands[0] @@ -916,10 +969,13 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) else: sell_candidates.append((tx, is_corr, rtext)) - # Sub-pass 1: exact matches against prior ledger entries first. + # Sub-pass 1: exact signature matches resolved in two order-independent batch phases: + # Phase 1a: current-signature exact matches first (so a current $11 row claims its entry before a $10 + # row can claim it via a historical $10 alias). + # Phase 1b: historical-signature alias matches only for non-conflicting unique claims. after_exact: list[tuple[dict, bool, str]] = [] - for tx, is_corr, rtext in sell_candidates: - is_restore_intent = is_corr and bool(_RESTORE_SELL_RE.search(rtext)) + 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 @@ -935,137 +991,91 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) if pool_ambig: _mark_uncertain(tx) continue - exact = _exact_sig(tx) - exact_cands = [i for i in pool if i not in acc_matched_sell and exact in ledger[i]["sigs"]] - if exact_cands: - if is_restore_intent: - reclass_cands = [i for i in exact_cands if ledger[i]["reclassified"]] - if len(reclass_cands) == 1: - target = reclass_cands[0] - acc_matched_sell.add(target) - _update_entry(target, tx, restore_if_reclassified=True) - elif reclass_cands: - _mark_uncertain(tx) - else: - # Restoration intent with no reclassified exact match: defer to Sub-pass 2/3 rather than - # hijacking an unrelated active sale that happens to share the corrected price. - after_exact.append((tx, is_corr, rtext)) - else: - active_cands = [i for i in exact_cands if not ledger[i]["reclassified"]] - if active_cands: - acc_matched_sell.add(active_cands[0]) - _update_entry(active_cands[0], tx) - elif is_corr: - # Price/share correction without restoration intent must not restore a reclassified gift - # whose historical price happens to equal the corrected price of another active sale. - after_exact.append((tx, is_corr, rtext)) - else: - # Unannotated restatement of a previously reclassified sale: keep gift state & mark uncertain. - acc_matched_sell.add(exact_cands[0]) - _mark_uncertain(tx) - else: - after_exact.append((tx, is_corr, rtext)) + exact_batch.append((idx_s, tx, is_corr, rtext, pool)) - # Sub-pass 2: share-matched restatements against remaining prior ledger entries (order-independent batch - # waves: only non-conflicting unique candidates are committed; rows stating changed prior shares or prior - # dates route directly to Sub-pass 3, and indistinguishable multi-candidate groups stay uncertain). - pending_share = list(enumerate(after_exact)) - resolved_share: set[int] = set() + resolved_exact: set[int] = set() + uncertain_exact: set[int] = set() - def _share_match_cands( - tx: dict, - is_corr: bool, - rtext: str, + def _exact_phase( + use_history: bool, *, - p_len: int = prior_len, + batch: list[tuple[int, dict, bool, str, list[int]]] = exact_batch, matched: set[int] = acc_matched_sell, - ) -> tuple[list[int], bool, bool, bool]: - b = _base_sig(tx) - shares = tx.get("shares") - is_restore_intent = is_corr and bool(_RESTORE_SELL_RE.search(rtext)) - corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] - has_explicit_prior_date = ( - is_corr - and _has_date_corr_evidence(tx, rtext) - and bool({d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td}) - ) - has_explicit_prior_shares = is_corr and bool(_stated_prior_shares(rtext, shares)) - if ( - has_explicit_prior_date - or has_explicit_prior_shares - or shares is None - or b[0] == ("",) - or not bool(b[1]) - ): - return [], is_restore_intent, False, False - prior_prices = _stated_prior_prices(rtext, tx.get("price")) if is_corr else set() - pool, pool_ambig = _scoped_pool(tx, p_len, check_multi_acc=not bool(prior_prices)) - if pool_ambig: - return [], is_restore_intent, False, bool(prior_prices) - cands = [ - i - for i in pool - if i not in matched - and _base_sig(ledger[i]["tx"]) == b - and shares in ledger[i]["shares_set"] - and (is_restore_intent or not ledger[i]["reclassified"] or not is_corr) - ] - if is_restore_intent: - reclass_share = [i for i in cands if ledger[i]["reclassified"]] - if reclass_share: - cands = reclass_share - orig_date = str(tx.get("original_filing_date") or "").strip() - if prior_prices and cands: - # Require matching the stated prior price; never substitute a different price when unmatched. - filtered = [i for i in cands if _matches_num_set(ledger[i]["tx"].get("price"), prior_prices)] - if ( - orig_date - and len({ledger[i]["orig_accession"] for i in filtered if ledger[i]["orig_accession"]}) > 1 - ): - return [], is_restore_intent, False, True - return filtered, is_restore_intent, True, True - if orig_date and len({ledger[i]["orig_accession"] for i in cands if ledger[i]["orig_accession"]}) > 1: - return [], is_restore_intent, False, True - return cands, is_restore_intent, False, False - - while True: + resolved: set[int] = resolved_exact, + uncertain: set[int] = uncertain_exact, + ) -> None: single_claims: dict[int, list[tuple[int, dict, bool, bool]]] = {} - for ridx, (tx, is_corr, rtext) in pending_share: - if ridx in resolved_share: + sym_restatements: dict[tuple[int, ...], list[tuple[int, dict]]] = {} + for idx_s, tx, is_corr, rtext, pool in batch: + if idx_s in resolved or idx_s in uncertain: continue - cands, is_restore_intent, identified_prior, _ = _share_match_cands(tx, is_corr, rtext) - if len(cands) == 1: - single_claims.setdefault(cands[0], []).append((ridx, tx, is_restore_intent, identified_prior)) - progressed = False + exact = _exact_sig(tx) + if use_history: + cands = [i for i in pool if i not in matched and exact in ledger[i]["sigs"]] + else: + cands = [i for i in pool if i not in matched and _exact_sig(ledger[i]["tx"]) == exact] + if not cands: + continue + is_restore_intent = is_corr and bool(_RESTORE_SELL_RE.search(rtext)) + if is_restore_intent: + reclass_cands = [i for i in cands if ledger[i]["reclassified"]] + if len(reclass_cands) == 1: + single_claims.setdefault(reclass_cands[0], []).append((idx_s, tx, True, False)) + elif len(reclass_cands) > 1: + _mark_uncertain(tx) + uncertain.add(idx_s) + else: + active_cands = [i for i in cands if not ledger[i]["reclassified"]] + if len(active_cands) == 1: + single_claims.setdefault(active_cands[0], []).append((idx_s, tx, False, False)) + elif len(active_cands) > 1 and not use_history: + # Multiple active entries currently share the exact same signature: reserve slots cleanly + # without mutating ledger values so identical restatements never inflate counts. + sym_restatements.setdefault(tuple(sorted(active_cands)), []).append((idx_s, tx)) + elif len(active_cands) > 1: + _mark_uncertain(tx) + uncertain.add(idx_s) + elif not is_corr: + # Unannotated restatement of a previously reclassified sale: keep gift state & mark uncertain. + if len(cands) == 1: + single_claims.setdefault(cands[0], []).append((idx_s, tx, False, True)) + else: + _mark_uncertain(tx) + uncertain.add(idx_s) + + claimed_targets: set[int] = set() for target, claimants in single_claims.items(): if len(claimants) == 1: - ridx, tx, is_restore_intent, identified_prior = claimants[0] - was_reclassified = ledger[target]["reclassified"] - acc_matched_sell.add(target) - _update_entry(target, tx, restore_if_reclassified=is_restore_intent) - if not (identified_prior or (is_restore_intent and was_reclassified)): + idx_s, tx, do_restore, mark_unc = claimants[0] + matched.add(target) + claimed_targets.add(target) + if not mark_unc: + _update_entry(target, tx, restore_if_reclassified=do_restore) + else: _mark_uncertain(tx) - resolved_share.add(ridx) - progressed = True - if not progressed: - break - - after_share: list[tuple[dict, bool, str]] = [] - for ridx, (tx, is_corr, rtext) in pending_share: - if ridx in resolved_share: - continue - cands, _is_restore, _ident, stop_here = _share_match_cands(tx, is_corr, rtext) - if len(cands) >= 1 or stop_here: - _mark_uncertain(tx) - else: - after_share.append((tx, is_corr, rtext)) + resolved.add(idx_s) + else: + for idx_s, tx, _do_restore, _mark_unc in claimants: + _mark_uncertain(tx) + uncertain.add(idx_s) + for slots, claimants in sym_restatements.items(): + avail = [s for s in slots if s not in claimed_targets and s not in matched] + for slot, (idx_s, _tx) in zip(avail, claimants): + matched.add(slot) + resolved.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 3: explicit corrections against remaining prior ledger entries (order-independent batch waves: - # resolve only non-conflicting unique assignments iteratively against the shared pre-wave ledger state so - # both row orders produce identical ledger dates, confirmed counts, and uncertainty marks). + # Sub-pass 2: ALL explicit corrections (is_corr=True: price, share, restoration, and date corrections) + # resolved together in ONE order-independent batch wave BEFORE heuristic unannotated share matching so + # an explicit correction always claims its identified target ahead of an unannotated share restatement. acc_new_sales: list[dict] = list(acc_explicit_adds) - corr_rows = [(idx, tx, rtext) for idx, (tx, is_corr, rtext) in enumerate(after_share) if is_corr] - unlinked_non_corr = [(tx, rtext) for tx, is_corr, rtext in after_share if not is_corr] + 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, @@ -1080,43 +1090,63 @@ def _corr_match_cands( is_restore_intent = bool(_RESTORE_SELL_RE.search(rtext)) orig_date = str(tx.get("original_filing_date") or "").strip() corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] - prior_dates = ( - {d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td} - if _has_date_corr_evidence(tx, rtext) - else set() - ) + has_date_corr = _has_date_corr_evidence(tx, rtext) + prior_dates = {d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td} if has_date_corr else set() prior_prices = _stated_prior_prices(rtext, tx.get("price")) prior_shares = _stated_prior_shares(rtext, tx.get("shares")) + shares = tx.get("shares") + price = tx.get("price") + if not prior_dates: pool, pool_ambig = _scoped_pool(tx, p_len, check_multi_acc=False) if not pool_ambig: - base_cands = [ + same_base = [ i for i in pool if i not in matched and _base_sig(ledger[i]["tx"]) == b and (is_restore_intent or not ledger[i]["reclassified"]) ] - if prior_shares: - base_cands = [ + 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: + # Require stated prior shares and/or prior price (and unchanged shares if only price changed) + # to match a SINGLE revision of the ledger entry. + unchanged_shares = shares if (not prior_shares and shares is not None) else _UNSET + cands = [ i - for i in base_cands - if any(_matches_num_set(s, prior_shares) for s in ledger[i]["shares_set"]) - ] - if prior_prices: - base_cands = [ - i for i in base_cands if _matches_num_set(ledger[i]["tx"].get("price"), prior_prices) + for i in same_base + if _entry_has_revision( + ledger[i], + shares_target=prior_shares or None, + price_target=prior_prices or None, + exact_shares=unchanged_shares, + ) ] + if ( + orig_date + and len({ledger[i]["orig_accession"] for i in cands if ledger[i]["orig_accession"]}) > 1 + ): + return [], is_restore_intent, False, False + return cands, is_restore_intent, True, False + # No stated prior shares/price: prefer share-matched entries on same base first, else same base. + if shares is not None: + share_matched = [i for i in same_base if shares in ledger[i]["shares_set"]] + if share_matched: + same_base = share_matched if ( orig_date - and len({ledger[i]["orig_accession"] for i in base_cands if ledger[i]["orig_accession"]}) > 1 + and len({ledger[i]["orig_accession"] for i in same_base if ledger[i]["orig_accession"]}) > 1 ): return [], is_restore_intent, False, False - if base_cands: - return base_cands, is_restore_intent, bool(prior_shares or prior_prices), False - # Explicit transaction-date correction: link via prior date / original filing after applying explicit - # row identifiers (old shares/price or unchanged shares/price), then check accession uniqueness. - if _has_date_corr_evidence(tx, rtext): + if same_base: + return same_base, is_restore_intent, False, False + + # Explicit transaction-date correction: link via prior date / original filing after matching stated + # prior fields against a single revision, then check accession uniqueness. + if has_date_corr: dpool, dpool_ambig = _scoped_pool( tx, p_len, @@ -1134,32 +1164,43 @@ def _corr_match_cands( and _owner_sec_sig(ledger[i]["tx"]) == osig and (is_restore_intent or not ledger[i]["reclassified"]) ] - if prior_dates: - # Strict prior-date match: never substitute a different date when the stated prior date is absent. + if prior_dates or prior_shares or prior_prices: + # Strict same-revision match: never combine old shares from revision 1 with price from revision 2, + # and never substitute a different date when a stated prior date has no match. date_cands = [ i for i in date_cands - if str(ledger[i]["tx"].get("transaction_date") or ledger[i]["tx"].get("date") or "")[:10] - in prior_dates - ] - if prior_shares: - date_cands = [ - i for i in date_cands if any(_matches_num_set(s, prior_shares) for s in ledger[i]["shares_set"]) + if _entry_has_revision( + ledger[i], + dates=prior_dates or None, + shares_target=prior_shares or None, + price_target=prior_prices or None, + ) ] - if prior_prices: - date_cands = [i for i in date_cands if _matches_num_set(ledger[i]["tx"].get("price"), prior_prices)] - shares = tx.get("shares") - price = tx.get("price") - if len(date_cands) > 1 and shares is not None and price is not None: + 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 shares in ledger[i]["shares_set"] and ledger[i]["tx"].get("price") == price + if _entry_has_revision( + ledger[i], + dates=prior_dates or None, + exact_shares=shares, + exact_price=price, + ) ] if by_sp: date_cands = by_sp - if len(date_cands) > 1 and shares is not None: - by_s = [i for i in date_cands if shares in ledger[i]["shares_set"]] + if len(date_cands) > 1 and shares is not None and not prior_shares: + by_s = [ + i + for i in date_cands + if _entry_has_revision(ledger[i], dates=prior_dates or None, exact_shares=shares) + ] if by_s: date_cands = by_s if ( @@ -1185,14 +1226,15 @@ def _corr_match_cands( for target, claimants in single_corr_claims.items(): if len(claimants) == 1: ridx, tx, is_restore_intent, identified_prior, is_date_match = claimants[0] - same_sp = ( - tx.get("shares") is not None - and tx.get("shares") in ledger[target]["shares_set"] - and ledger[target]["tx"].get("price") == tx.get("price") + was_reclassified = ledger[target]["reclassified"] + same_sp = tx.get("shares") is not None and _entry_has_revision( + ledger[target], exact_shares=tx.get("shares"), exact_price=tx.get("price") ) acc_matched_sell.add(target) _update_entry(target, tx, restore_if_reclassified=is_restore_intent) - if not ((is_date_match and (same_sp or identified_prior)) or identified_prior): + 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 @@ -1203,10 +1245,57 @@ def _corr_match_cands( if ridx not in resolved_corr: _mark_uncertain(tx) - # Sub-pass 4: only confirm an unlinked sell row as a new sale when filing evidence supports an addition - # (unclaimed remarks addition, or every prior entry on that base signature was already reserved in this - # same accession). Otherwise report uncertainty without inflating the confirmed sale count. - for tx, _rtext in unlinked_non_corr: + # Sub-pass 3: heuristic unannotated share-matched restatements (is_corr=False only, order-independent batch + # waves, running AFTER explicit corrections so heuristic restatements never steal explicit targets). + def _heuristic_share_cands( + tx: dict, + *, + p_len: int = prior_len, + matched: set[int] = acc_matched_sell, + ) -> list[int]: + b = _base_sig(tx) + shares = tx.get("shares") + if shares is None or b[0] == ("",) or not bool(b[1]): + return [] + pool, pool_ambig = _scoped_pool(tx, p_len) + if pool_ambig: + return [] + return [ + i + for i in pool + if i not in matched and _base_sig(ledger[i]["tx"]) == b and shares in ledger[i]["shares_set"] + ] + + 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 = _heuristic_share_cands(tx) + if 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) + _update_entry(target, tx) + _mark_uncertain(tx) + resolved_heur.add(ridx) + progressed = True + if not progressed: + break + + # Sub-pass 4: remaining unlinked unannotated sell rows — confirm as new sale ONLY when filing evidence + # supports an addition (unclaimed remarks addition, or all prior entries on that base signature were already + # reserved in this same accession). Otherwise report uncertainty without inflating the confirmed sale count. + for ridx, tx, _rtext in unannotated_rows: + if ridx in resolved_heur: + continue + if _heuristic_share_cands(tx): + _mark_uncertain(tx) + continue b = _base_sig(tx) pool, _ = _scoped_pool(tx, prior_len) has_prior_same_base = any(_base_sig(ledger[i]["tx"]) == b for i in pool) From d1e90c5bb1392982192d48cd72cca393b7bd8247 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 08:42:06 +0800 Subject: [PATCH 15/37] fix(risk): preserve decimals in sentence split, avoid historical revert, resolve overlapping exact groups via max matching --- tests/test_risk_screening.py | 69 +++++++++++++++++++++++++++++++++ tools/risk_screening.py | 74 ++++++++++++++++++++++++++++-------- 2 files changed, 128 insertions(+), 15 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 0026b5f..13d7ba3 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -1550,10 +1550,21 @@ def _parse(accn, fdate, form, doc): 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 = [ @@ -1610,6 +1621,64 @@ def _parse(accn, fdate, form, doc): 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 + def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): base_inputs = { diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 9abbf8f..d6972b0 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -471,7 +471,8 @@ def _base_sig(tx: dict) -> tuple: ) def _correction_sentences(rtext: str) -> str: - sents = [s for s in re.split(r"[.!?;。!?;]+", rtext) if s.strip()] + # Split on sentence boundaries without splitting decimal numbers such as "$20.50" or "1,250.50". + sents = [s for s in re.split(r"(?:(? None: - single_claims: dict[int, list[tuple[int, dict, bool, bool]]] = {} + 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 batch: if idx_s in resolved or idx_s in uncertain: @@ -1020,17 +1022,20 @@ def _exact_phase( if is_restore_intent: reclass_cands = [i for i in cands if ledger[i]["reclassified"]] if len(reclass_cands) == 1: - single_claims.setdefault(reclass_cands[0], []).append((idx_s, tx, True, False)) + single_claims.setdefault(reclass_cands[0], []).append((idx_s, tx, True, False, True)) elif len(reclass_cands) > 1: _mark_uncertain(tx) uncertain.add(idx_s) else: active_cands = [i for i in cands if not ledger[i]["reclassified"]] if len(active_cands) == 1: - single_claims.setdefault(active_cands[0], []).append((idx_s, tx, False, False)) + # Unannotated historical match only reserves the entry without reverting its current tx. + 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: - # Multiple active entries currently share the exact same signature: reserve slots cleanly - # without mutating ledger values so identical restatements never inflate counts. + # Multiple active entries currently share the exact same signature: resolve slots across + # all overlapping groups together below (narrowest/filing-scoped first) so traversal order + # never displaces a scoped restatement. sym_restatements.setdefault(tuple(sorted(active_cands)), []).append((idx_s, tx)) elif len(active_cands) > 1: _mark_uncertain(tx) @@ -1038,7 +1043,7 @@ def _exact_phase( elif not is_corr: # Unannotated restatement of a previously reclassified sale: keep gift state & mark uncertain. if len(cands) == 1: - single_claims.setdefault(cands[0], []).append((idx_s, tx, False, True)) + single_claims.setdefault(cands[0], []).append((idx_s, tx, False, True, False)) else: _mark_uncertain(tx) uncertain.add(idx_s) @@ -1046,23 +1051,62 @@ def _exact_phase( claimed_targets: set[int] = set() for target, claimants in single_claims.items(): if len(claimants) == 1: - idx_s, tx, do_restore, mark_unc = claimants[0] + idx_s, tx, do_restore, mark_unc, do_update = claimants[0] matched.add(target) claimed_targets.add(target) - if not mark_unc: - _update_entry(target, tx, restore_if_reclassified=do_restore) - else: + if mark_unc: _mark_uncertain(tx) + elif do_update: + _update_entry(target, tx, restore_if_reclassified=do_restore) resolved.add(idx_s) else: - for idx_s, tx, _do_restore, _mark_unc in claimants: + for idx_s, tx, _do_restore, _mark_unc, _do_update in claimants: _mark_uncertain(tx) uncertain.add(idx_s) - for slots, claimants in sym_restatements.items(): - avail = [s for s in slots if s not in claimed_targets and s not in matched] - for slot, (idx_s, _tx) in zip(avail, claimants): + + if sym_restatements: + # Maximum bipartite matching across all overlapping symmetric exact-match groups, ordered + # deterministically from narrowest (filing-scoped) to broadest (unscoped) so scoped rows reserve + # their filing's slots first and unscoped rows take remaining slots regardless of input order. + sym_items: list[tuple[int, dict, 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 matched) + for idx_s, tx in claimants: + sym_items.append((idx_s, tx, avail)) + + 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()) + for slot, pos in slot_owner.items(): + idx_s, _tx, _avail = sym_items[pos] matched.add(slot) resolved.add(idx_s) + for pos, (idx_s, tx, avail) in enumerate(sym_items): + if pos in assigned_positions: + continue + # Do not let a displaced restatement from an overlapping conflict inflate the confirmed count. + exact = _exact_sig(tx) + other_unmatched = any( + i not in matched and not ledger[i]["reclassified"] and _exact_sig(ledger[i]["tx"]) == exact + for i in range(p_len) + ) + if other_unmatched or not avail: + _mark_uncertain(tx) + uncertain.add(idx_s) _exact_phase(use_history=False) _exact_phase(use_history=True) From c8004afe1c7a5e5fcbffbaa62bbbc2003c35b2f8 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 09:39:04 +0800 Subject: [PATCH 16/37] fix(risk): preserve filing_date provenance on symmetric and historical exact restatements --- tests/test_risk_screening.py | 60 ++++++++++++++++++++++++++++++++++++ tools/risk_screening.py | 19 +++++++----- 2 files changed, 71 insertions(+), 8 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 13d7ba3..2214bf2 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -1679,6 +1679,66 @@ def _parse(accn, fdate, form, doc): 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 + def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): base_inputs = { diff --git a/tools/risk_screening.py b/tools/risk_screening.py index d6972b0..7fb18a2 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -767,12 +767,14 @@ def _scoped_pool( return [], True return pool, False - def _mark_reclassified(idx: int, tx: dict) -> None: - entry = ledger[idx] - entry["reclassified"] = True + def _record_filing_provenance(idx: int, tx: dict) -> None: fdate = str(tx.get("filing_date") or "").strip() if fdate: - entry["filing_dates"].add(fdate) + ledger[idx]["filing_dates"].add(fdate) + + def _mark_reclassified(idx: int, tx: dict) -> None: + ledger[idx]["reclassified"] = True + _record_filing_provenance(idx, tx) def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) -> None: entry = ledger[idx] @@ -783,9 +785,7 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) entry["revisions"].append(rev) if tx.get("shares") is not None: entry["shares_set"].add(tx.get("shares")) - fdate = str(tx.get("filing_date") or "").strip() - if fdate: - entry["filing_dates"].add(fdate) + _record_filing_provenance(idx, tx) if restore_if_reclassified and entry["reclassified"]: entry["reclassified"] = False @@ -1058,6 +1058,8 @@ def _exact_phase( _mark_uncertain(tx) elif do_update: _update_entry(target, tx, restore_if_reclassified=do_restore) + else: + _record_filing_provenance(target, tx) resolved.add(idx_s) else: for idx_s, tx, _do_restore, _mark_unc, _do_update in claimants: @@ -1092,8 +1094,9 @@ def _augment(item_pos: int, visited: set[int], *, items=sym_items, owners=slot_o assigned_positions = set(slot_owner.values()) for slot, pos in slot_owner.items(): - idx_s, _tx, _avail = sym_items[pos] + idx_s, tx, _avail = sym_items[pos] matched.add(slot) + _record_filing_provenance(slot, tx) resolved.add(idx_s) for pos, (idx_s, tx, avail) in enumerate(sym_items): if pos in assigned_positions: From 4319a6c8afb46c9c721627bf402d68fe3007de4b Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 09:53:02 +0800 Subject: [PATCH 17/37] fix(risk): record symmetric provenance across full candidate set and flag ambiguity on partial exact matches --- tests/test_risk_screening.py | 69 ++++++++++++++++++++++++++++++++++++ tools/risk_screening.py | 28 ++++++++++++--- 2 files changed, 92 insertions(+), 5 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 2214bf2..7b5f5e1 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -1739,6 +1739,75 @@ def _parse(accn, fdate, form, doc): 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 + def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): base_inputs = { diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 7fb18a2..c2156c6 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -1070,11 +1070,13 @@ def _exact_phase( # Maximum bipartite matching across all overlapping symmetric exact-match groups, ordered # deterministically from narrowest (filing-scoped) to broadest (unscoped) so scoped rows reserve # their filing's slots first and unscoped rows take remaining slots regardless of input order. - sym_items: list[tuple[int, dict, tuple[int, ...]]] = [] + 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 matched) + grp_avail[slots] = avail for idx_s, tx in claimants: - sym_items.append((idx_s, tx, avail)) + sym_items.append((idx_s, tx, avail, slots)) slot_owner: dict[int, int] = {} @@ -1093,12 +1095,28 @@ def _augment(item_pos: int, visited: set[int], *, items=sym_items, owners=slot_o _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 = sym_items[pos] + idx_s, tx, _avail, grp_key = sym_items[pos] matched.add(slot) - _record_filing_provenance(slot, tx) resolved.add(idx_s) - for pos, (idx_s, tx, avail) in enumerate(sym_items): + grp_assigned.setdefault(grp_key, []).append((slot, idx_s, tx)) + + # Record filing_date provenance symmetrically: when a group saturates all of its remaining + # available slots (unique or full-group restatement), provenance is exact; when fewer rows than + # identical slots match, attach provenance to the full candidate set (never an arbitrary single + # slot) and mark uncertainty. + 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: + _record_filing_provenance(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 # Do not let a displaced restatement from an overlapping conflict inflate the confirmed count. From 01204287c7ce2279ae49c7bbd3390f5f9a4ad484 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 11:22:50 +0800 Subject: [PATCH 18/37] fix(risk): bound remarks additions, match prior date revisions, and order same-day 4/A by acceptance timestamp --- tests/test_risk_screening.py | 173 ++++++++++++++++++++++++++++++++ tests/test_sec_edgar.py | 38 ++++--- tools/risk_screening.py | 187 +++++++++++++++++++++++++++-------- tools/sec_edgar.py | 24 ++++- 4 files changed, 363 insertions(+), 59 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 7b5f5e1..14c3bec 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -1808,6 +1808,179 @@ def _parse(accn, fdate, form, doc): assert res_ambig_ab["veto_buy"] is False assert res_ambig_ba["veto_buy"] is False + # 30. Remarks declaring one correction and one omitted addition must cap unlinked remarks-backed additions at 1 + # even when both 4/A rows changed shares and price (so net sales = 2, not 3, and no medium-risk flag). + 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, + } + cap_row1 = { + "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": "Amending to correct one transaction and add an omitted transaction.", + } + cap_row2 = { + "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": 250.0, + "price": None, + "remarks": "Amending to correct one transaction and add an omitted transaction.", + } + res_cap_12 = _screen([cap_orig, cap_row1, cap_row2], since_filing_date="2026-10-01") + res_cap_21 = _screen([cap_orig, cap_row2, cap_row1], since_filing_date="2026-10-01") + assert res_cap_12["checks"]["insider_trades"]["sales_90d"] == 2 + assert res_cap_21["checks"]["insider_trades"]["sales_90d"] == 2 + 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"]) + + # 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 + def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): base_inputs = { diff --git a/tests/test_sec_edgar.py b/tests/test_sec_edgar.py index 0f1f6fd..838b5af 100644 --- a/tests/test_sec_edgar.py +++ b/tests/test_sec_edgar.py @@ -577,14 +577,18 @@ def test_form4_cache_key_version_re_parses_remarks_over_legacy_cache(monkeypatch 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`. - for prefix in ("sec-form4", "sec-form4-v2"): + # 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}}) @@ -593,11 +597,12 @@ def get(url, **kwargs): { "filings": { "recent": { - "form": ["4/A"], - "accessionNumber": [accn], - "filingDate": [recent_filing], - "reportDate": [tx_date], - "primaryDocument": ["form4a.xml"], + "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": [], } @@ -609,12 +614,17 @@ def get(url, **kwargs): monkeypatch.setattr("requests.get", get) result = sec_edgar.insider_trades(Namespace(symbol="AAPL", days=90, top=10)) - assert result["transactions"][0]["remarks"] == "Amending to report an inadvertently omitted sale." - assert result["transactions"][0]["original_filing_date"] == orig_filing - v3_rows = sec_edgar.cached( - f"sec-form4-v3:0000320193:{accn}", + # 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 v3 Form 4 cache entry to be populated"), + lambda: pytest.fail("expected v4 Form 4 cache entry to be populated"), ) - assert v3_rows[0]["remarks"] == "Amending to report an inadvertently omitted sale." - assert v3_rows[0]["original_filing_date"] == orig_filing + 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/tools/risk_screening.py b/tools/risk_screening.py index c2156c6..395cedb 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -8,7 +8,7 @@ import re import sys from concurrent.futures import Future, ThreadPoolExecutor -from datetime import date, timedelta +from datetime import date, datetime, timedelta, timezone sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) @@ -549,26 +549,35 @@ def _matches_num_set(val, target_set: set[float]) -> bool: re.IGNORECASE, ) - def _remarks_intent_count(text: str, *, kind: str) -> int: + _UNBOUNDED_COUNT_WORDS = {"several", "multiple", "多", "若干"} + + def _remarks_intent_count(text: str, *, kind: str) -> tuple[int, bool]: if kind == "add": if not _ADDITION_RE.search(text): - return 0 + return 0, False count = 1 + has_explicit_bound = False + unbounded = False for m in _ADD_COUNT_RE.finditer(text): tok = next((g for g in m.groups() if g), "").lower() n = int(tok) if tok.isdigit() else _COUNT_WORDS.get(tok, 1) count = max(count, n) - if count == 1 and _ADD_PLURAL_RE.search(text): - count = 2 - return count + if tok in _UNBOUNDED_COUNT_WORDS: + unbounded = True + else: + has_explicit_bound = True + if not has_explicit_bound and _ADD_PLURAL_RE.search(text): + count = max(count, 2) + unbounded = True + return count, (unbounded and not has_explicit_bound) if not _CORRECTION_RE.search(text): - return 0 + return 0, False count = 1 for m in _CORR_COUNT_RE.finditer(text): tok = next((g for g in m.groups() if g), "").lower() n = int(tok) if tok.isdigit() else _COUNT_WORDS.get(tok, 1) count = max(count, n) - return count + return count, False def _extract_ref_ids(refs) -> list[str]: seen: set[str] = set() @@ -603,7 +612,7 @@ def _row_scoped_text(tx: dict) -> str: def _resolve_accession_intents( acc_rows: list[dict], - ) -> tuple[list[tuple[bool, bool]], list[bool], list[str], bool]: + ) -> tuple[list[tuple[bool, bool]], list[bool], list[str], int | None]: row_texts = [_row_scoped_text(tx) for tx in acc_rows] row_intents = [ (bool(_ADDITION_RE.search(rt)), bool(_CORRECTION_RE.search(rt))) if rt else (False, False) @@ -618,33 +627,35 @@ def _resolve_accession_intents( seen_remarks.add(rem) remarks_parts.append(rem) if not remarks_parts: - return row_intents, ambiguous, row_texts, False + return row_intents, ambiguous, row_texts, 0 rem_text = " ".join(remarks_parts) - rem_add_count = _remarks_intent_count(rem_text, kind="add") - rem_corr_count = _remarks_intent_count(rem_text, kind="corr") + rem_add_count, rem_add_unbounded = _remarks_intent_count(rem_text, kind="add") + rem_corr_count, _ = _remarks_intent_count(rem_text, kind="corr") if not (rem_add_count or rem_corr_count): - return row_intents, ambiguous, row_texts, False + return row_intents, ambiguous, row_texts, 0 claimed_add_count = sum(1 for ra, _ in row_intents if ra) claimed_corr_count = sum(1 for _, rc in row_intents if rc) - unclaimed_add = rem_add_count > claimed_add_count + unclaimed_add_count = max(0, rem_add_count - claimed_add_count) + unclaimed_add = unclaimed_add_count > 0 unclaimed_corr = rem_corr_count > claimed_corr_count if not (unclaimed_add or unclaimed_corr): - return row_intents, ambiguous, row_texts, False + return row_intents, ambiguous, row_texts, 0 unattributed = [i for i, (ra, rc) in enumerate(row_intents) if not (ra or rc)] if len(unattributed) == 1 and (unclaimed_add != unclaimed_corr): row_intents[unattributed[0]] = (unclaimed_add, unclaimed_corr) row_texts[unattributed[0]] = f"{row_texts[unattributed[0]]} {rem_text}".strip() - return row_intents, ambiguous, row_texts, False + return row_intents, ambiguous, row_texts, 0 # Filing-level remarks cannot be uniquely attributed (multiple unattributed rows, mixed intent, or # remarks declaring more additions/corrections than attributed rows); surface uncertainty instead of - # broadcasting to every row. + # broadcasting to every row, and preserve the bounded remarks-backed addition count. for i in unattributed: ambiguous[i] = True row_texts[i] = f"{row_texts[i]} {rem_text}".strip() if not unattributed: for i in range(len(acc_rows)): ambiguous[i] = True - return row_intents, ambiguous, row_texts, unclaimed_add + add_budget: int | None = None if (rem_add_unbounded and not unclaimed_corr) else unclaimed_add_count + return row_intents, ambiguous, row_texts, add_budget raw_cutoff = str(data.get("since_filing_date") or "").strip()[:10] try: @@ -667,13 +678,15 @@ def _rev_tuple(tx: dict) -> tuple[str, object, object]: def _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": {_exact_sig(tx)}, "revisions": [_rev_tuple(tx)], "shares_set": {shares} if shares is not None else set(), - "filing_dates": {fdate} if fdate else set(), + "filing_dates": filing_dates, "orig_accession": str(tx.get("accession") or "").strip() or None, "from_orig": from_orig, "reclassified": False, @@ -743,12 +756,7 @@ def _scoped_pool( osig = _owner_sec_sig(tx) eligible = [i for i in pool if _owner_sec_sig(ledger[i]["tx"]) == osig] if prior_dates: - eligible = [ - i - for i in eligible - if str(ledger[i]["tx"].get("transaction_date") or ledger[i]["tx"].get("date") or "")[:10] - in prior_dates - ] + eligible = [i for i in eligible if _entry_has_revision(ledger[i], dates=prior_dates)] if not eligible: return [], True if check_multi_acc: @@ -758,10 +766,19 @@ def _scoped_pool( return eligible if prior_dates else pool, False if check_multi_acc: b = _base_sig(tx) + osig = (b[0], b[2], b[3]) same_accs = { ledger[i]["orig_accession"] for i in pool - if _base_sig(ledger[i]["tx"]) == b and ledger[i]["orig_accession"] + if ledger[i]["orig_accession"] + and ( + _base_sig(ledger[i]["tx"]) == b + or ( + bool(b[1]) + and _owner_sec_sig(ledger[i]["tx"]) == osig + and _entry_has_revision(ledger[i], dates={b[1][:10]}) + ) + ) } if len(same_accs) > 1: return [], True @@ -789,20 +806,80 @@ def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) if restore_if_reclassified and entry["reclassified"]: entry["reclassified"] = False - # Group ALL Form 4/A rows (sells and non-sells together) by accession and process chronologically so later - # amendments can correct, reclassify, or restore sales from original Form 4 or earlier Form 4/A filings. + def _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 _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") + + # Group ALL Form 4/A rows (sells and non-sells together) by accession and process chronologically by + # (filing_date, EDGAR acceptanceDateTime, accession) so same-day amendments from different submitting agents + # execute in actual acceptance order. When same-day filings lack comparable acceptance timestamps across + # submitting agents (or mix present and missing timestamps), flag uncertainty for the affected owner. 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 := _normalize_acceptance_ts(r.get("acceptance_datetime") or r.get("acceptanceDateTime"))) + ), + default="", + ) + acc_meta[acc] = (fdate, acc_ts) + for ok in {_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] + + 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: + for tx in amend_by_acc[a]: + _mark_uncertain(tx) + sorted_acc_items = sorted( amend_by_acc.items(), - key=lambda item: (min(str(r.get("filing_date") or "") for r in item[1]), item[0]), + key=lambda item: (acc_meta[item[0]][0], acc_meta[item[0]][1], item[0]), ) for _acc, acc_rows in sorted_acc_items: - intents, ambig_flags, row_texts, acc_has_unclaimed_add = _resolve_accession_intents(acc_rows) + intents, ambig_flags, row_texts, acc_unclaimed_add_count = _resolve_accession_intents(acc_rows) acc_sells: list[tuple[dict, tuple[bool, bool], bool, str]] = [] acc_non_sells: list[tuple[dict, tuple[bool, bool], bool, str]] = [] for tx, intent, is_ambig, rtext in zip(acc_rows, intents, ambig_flags, row_texts): @@ -1353,8 +1430,11 @@ def _heuristic_share_cands( break # Sub-pass 4: remaining unlinked unannotated sell rows — confirm as new sale ONLY when filing evidence - # supports an addition (unclaimed remarks addition, or all prior entries on that base signature were already - # reserved in this same accession). Otherwise report uncertainty without inflating the confirmed sale count. + # supports an addition (pigeonhole proof when all prior entries on that base signature were reserved in + # this accession, or bounded by the integer number of unclaimed additions stated in remarks). Excess + # unattributable rows stay uncertain without inflating the confirmed sale count. + remarks_add_cands: list[dict] = [] + pigeonhole_adds = 0 for ridx, tx, _rtext in unannotated_rows: if ridx in resolved_heur: continue @@ -1367,11 +1447,43 @@ def _heuristic_share_cands( all_prior_same_base_reserved = has_prior_same_base and all( i in acc_matched_sell for i in pool if _base_sig(ledger[i]["tx"]) == b ) - if acc_has_unclaimed_add or all_prior_same_base_reserved: + if all_prior_same_base_reserved: acc_new_sales.append(tx) + pigeonhole_adds += 1 + elif acc_unclaimed_add_count is None or acc_unclaimed_add_count > 0: + remarks_add_cands.append(tx) else: _mark_uncertain(tx) + if remarks_add_cands: + rem_add_budget = ( + None if acc_unclaimed_add_count is None else max(0, acc_unclaimed_add_count - pigeonhole_adds) + ) + if rem_add_budget is None or len(remarks_add_cands) <= rem_add_budget: + acc_new_sales.extend(remarks_add_cands) + else: + # More unlinked rows than remarks-backed additions: cap added rows at rem_add_budget in + # deterministic, None-safe order and keep all affected rows marked uncertain. + def _cand_sort_key(tx: dict) -> tuple: + td = _tx_date_iso(tx) + shares_v = _safe_float(tx.get("shares")) + price_v = _safe_float(tx.get("price")) + return ( + 0 if (td is None or td >= tx_cutoff) else 1, + _owner_key(tx), + str(tx.get("transaction_date") or tx.get("date") or ""), + str(tx.get("security") or ""), + bool(tx.get("derivative")), + (0, shares_v) if shares_v is not None else (1, 0.0), + (0, price_v) if price_v is not None else (1, 0.0), + ) + + ordered_cands = sorted(remarks_add_cands, key=_cand_sort_key) + if rem_add_budget > 0: + acc_new_sales.extend(ordered_cands[:rem_add_budget]) + for tx in ordered_cands: + _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: @@ -1386,15 +1498,6 @@ def _heuristic_share_cands( if need > 0: ledger.extend(_make_ledger_entry(tx, from_orig=False) for tx in rows[:need]) - def _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 - active_sales = [entry for entry in ledger if not entry["reclassified"]] recent_active_sales: list[tuple[dict, bool]] = [] for entry in active_sales: diff --git a/tools/sec_edgar.py b/tools/sec_edgar.py index 70437f0..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 @@ -279,6 +296,7 @@ def form4(cik, filing): "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}", @@ -573,7 +591,7 @@ def insider_trades(args): for filing in filings[: args.top]: try: rows = cached( - f"sec-form4-v3:{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 From 04ba8d9c08f0636283e6a38b947c39a5b2eb013d Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 13:14:55 +0800 Subject: [PATCH 19/37] refactor(risk): drop speculative remarks addition budgets and check multi-accession ambiguity after row evidence --- tests/test_risk_screening.py | 259 ++++- tools/risk_screening.py | 2015 ++++++++++++++++------------------ 2 files changed, 1182 insertions(+), 1092 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 14c3bec..322cd49 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -976,8 +976,10 @@ def _parse(accn, fdate, form, doc): assert res_scoped["checks"]["insider_trades"]["count_uncertain"] is False res_mixed = _screen(orig_rows + mixed_rows) - assert res_mixed["checks"]["insider_trades"]["sales_90d"] == 3 + # 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 @@ -1037,7 +1039,8 @@ def _parse(accn, fdate, form, doc): assert res_unlinked["checks"]["insider_trades"]["count_uncertain"] is True assert not any(f["category"] == "insider" for f in res_unlinked["flags"]) - # 6. Plural/counted remarks ("two omitted sales") with only 1 row footnote must NOT treat all additions as claimed + # 6. Multi-row filing-level remarks never override missing row footnotes: row-scoped F1 confirms +1 addition, + # exact unannotated restatements match existing sales, and unlinked rows stay conservative + uncertain. two_omit_r1 = dict( orig_rows[0], form="4/A", @@ -1056,13 +1059,29 @@ def _parse(accn, fdate, form, doc): footnote_refs={}, remarks="Amending to report two omitted sales.", ) - # 2 rows total -> single remaining unattributed row absorbs the 2nd remarked addition -> 4 sales - assert _screen(orig_rows + [two_omit_r1, two_omit_r2])["checks"]["insider_trades"]["sales_90d"] == 4 - # 3 rows (2 unattributed rows for 1 remaining addition) -> cannot identify which is added -> count_uncertain=True - two_omit_r3 = dict(two_omit_r2, shares=100, price=150.0) + 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( @@ -1808,8 +1827,8 @@ def _parse(accn, fdate, form, doc): assert res_ambig_ab["veto_buy"] is False assert res_ambig_ba["veto_buy"] is False - # 30. Remarks declaring one correction and one omitted addition must cap unlinked remarks-backed additions at 1 - # even when both 4/A rows changed shares and price (so net sales = 2, not 3, and no medium-risk flag). + # 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", @@ -1823,44 +1842,116 @@ def _parse(accn, fdate, form, doc): "shares": 100.0, "price": 100.0, } - cap_row1 = { - "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": "Amending to correct one transaction and add an omitted transaction.", - } - cap_row2 = { - "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": 250.0, - "price": None, - "remarks": "Amending to correct one transaction and add an omitted transaction.", - } - res_cap_12 = _screen([cap_orig, cap_row1, cap_row2], since_filing_date="2026-10-01") - res_cap_21 = _screen([cap_orig, cap_row2, cap_row1], since_filing_date="2026-10-01") - assert res_cap_12["checks"]["insider_trades"]["sales_90d"] == 2 - assert res_cap_21["checks"]["insider_trades"]["sales_90d"] == 2 - 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"]) + 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. @@ -1981,6 +2072,82 @@ def _parse(accn, fdate, form, doc): ) 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 = _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 = _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 + def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): base_inputs = { diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 395cedb..70cfe6d 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -359,482 +359,396 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: return result -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 +_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)|更正|修正|重分类|误报)", + re.IGNORECASE, +) +_F4_SALE_TO_NONSELL_RE = re.compile( + r"(reclassif(?:ied|y|ying)|transaction\s+code|\bcode\s+s\s+to\b|" + r"(?:from|misreported|erroneously\s+reported|incorrectly\s+reported)\s+(?:as\s+)?(?:a\s+)?(?:[\w-]+\s+){0,3}(?:sale|sell|sold)\b|" + r"(?: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"(?: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_RESTORE_SELL_RE = re.compile( + r"(reclassif(?:ied|y|ying)|transaction\s+code|\bcode\s+s\b|" + r"(?:was|is|should\s+have\s+been)\s+(?:actually\s+)?(?:a\s+)?(?:open[- ]market\s+)?sale\b|" + r"(?:instead\s+of|not)\s+(?:a\s+)?(?:[\w-]+\s+){0,2}(?:gift|non-sale|transfer)\b|" + r"(?:from|misreported|erroneously\s+reported|incorrectly\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, +) +_F4_NONSELL_OBJECT_RE = re.compile( + r"\b(?:gift|gifts|award|awards|grant|grants|option|options|rsu|rsus|transfer|transfers|withholding|exercise|exercises)\b|" + r"赠与|授予|行权|预扣", + re.IGNORECASE, +) +_F4_SELL_OR_GENERIC_OBJECT_RE = re.compile( + r"\b(?:sale|sales|sell|sold|disposition|dispositions|transaction|transactions|trade|trades|line|lines|row|rows)\b|" + r"卖出|减持|交易|笔", + re.IGNORECASE, +) - 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)] +def _f4_tx_code(tx: dict) -> str: + return str(tx.get("code") or tx.get("transaction_code") or "").upper() - def _tx_code(tx: dict) -> str: - return str(tx.get("code") or tx.get("transaction_code") or "").upper() - - def _is_sell(tx: dict) -> bool: - return _tx_code(tx) == "S" or str(tx.get("action") or "").lower() == "sell" - - def _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 _exact_sig(tx: dict) -> tuple: - return ( - _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 _base_sig(tx: dict) -> tuple: - return ( - _owner_key(tx), - str(tx.get("transaction_date") or tx.get("date") or ""), - str(tx.get("security") or ""), - bool(tx.get("derivative")), - ) +def _f4_is_sell(tx: dict) -> bool: + return _f4_tx_code(tx) == "S" or str(tx.get("action") or "").lower() == "sell" - _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, - ) - _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)|更正|修正|重分类|误报)", - re.IGNORECASE, - ) - _SALE_TO_NONSELL_RE = re.compile( - r"(reclassif(?:ied|y|ying)|transaction\s+code|\bcode\s+s\s+to\b|" - r"(?:from|misreported|erroneously\s+reported|incorrectly\s+reported)\s+(?:as\s+)?(?:a\s+)?(?:[\w-]+\s+){0,3}(?:sale|sell|sold)\b|" - r"(?: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"(?: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, - ) - _RESTORE_SELL_RE = re.compile( - r"(reclassif(?:ied|y|ying)|transaction\s+code|\bcode\s+s\b|" - r"(?:was|is|should\s+have\s+been)\s+(?:actually\s+)?(?:a\s+)?(?:open[- ]market\s+)?sale\b|" - r"(?:instead\s+of|not)\s+(?:a\s+)?(?:[\w-]+\s+){0,2}(?:gift|non-sale|transfer)\b|" - r"(?:from|misreported|erroneously\s+reported|incorrectly\s+reported)\s+(?:as\s+)?(?:a\s+)?(?:[\w-]+\s+){0,3}(?:gift|non-sale)\b|" - r"重分类|改为卖出|恢复为卖出|并非赠与)", - re.IGNORECASE, - ) - _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, - ) - _ISO_DATE_RE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b") - _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, - ) - _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, - ) - _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})", - re.IGNORECASE, - ) - def _correction_sentences(rtext: str) -> str: - # Split on sentence boundaries without splitting decimal numbers such as "$20.50" or "1,250.50". - sents = [s for s in re.split(r"(?:(? set[float]: - new_f = _safe_float(new_price) - scoped = _correction_sentences(rtext) - explicit: set[float] = set() - for m in _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 _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 _stated_prior_shares(rtext: str, new_shares) -> set[float]: - out: set[float] = set() - new_f = _safe_float(new_shares) - for m in _PRIOR_SHARES_RE.finditer(_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 _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) - - _COUNT_WORDS = { - "two": 2, - "three": 3, - "four": 4, - "five": 5, - "six": 6, - "seven": 7, - "eight": 8, - "nine": 9, - "ten": 10, - "both": 2, - "several": 2, - "multiple": 2, - "两": 2, - "二": 2, - "三": 3, - "四": 4, - "五": 5, - "多": 2, - "若干": 2, - } - _ADD_COUNT_RE = re.compile( - r"(?:\b([2-9]|\d{2,}|two|three|four|five|six|seven|eight|nine|ten|both|several|multiple)\b" - r"(?:\s+\w+){0,3}\s+(?:omitted|unreported|additional|late[- ]?reported)\b|" - r"(?:adds?|adding|added|reports?|reporting|reported)\s+" - r"\b([2-9]|\d{2,}|two|three|four|five|six|seven|eight|nine|ten|both|several|multiple)\b|" - r"(两|二|三|四|五|多|若干)\s*笔?\s*(?:遗漏|漏报|补报))", - re.IGNORECASE, - ) - _ADD_PLURAL_RE = re.compile( - r"(?:omitted|unreported|additional|late[- ]?reported)\s+(?:sales|transactions|dispositions|lines|rows)\b", - re.IGNORECASE, +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")), ) - _CORR_COUNT_RE = re.compile( - r"(?:corrects?|correcting|corrected|reclassif(?:ies|ying|ied)|restates?|restating|restated)\s+" - r"\b([2-9]|\d{2,}|two|three|four|five|six|seven|eight|nine|ten|both|several|multiple)\b|" - r"(两|二|三|四|五|多|若干)\s*笔?\s*(?:更正|修正|重分类|误报)", - re.IGNORECASE, + + +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"), ) - _UNBOUNDED_COUNT_WORDS = {"several", "multiple", "多", "若干"} - - def _remarks_intent_count(text: str, *, kind: str) -> tuple[int, bool]: - if kind == "add": - if not _ADDITION_RE.search(text): - return 0, False - count = 1 - has_explicit_bound = False - unbounded = False - for m in _ADD_COUNT_RE.finditer(text): - tok = next((g for g in m.groups() if g), "").lower() - n = int(tok) if tok.isdigit() else _COUNT_WORDS.get(tok, 1) - count = max(count, n) - if tok in _UNBOUNDED_COUNT_WORDS: - unbounded = True - else: - has_explicit_bound = True - if not has_explicit_bound and _ADD_PLURAL_RE.search(text): - count = max(count, 2) - unbounded = True - return count, (unbounded and not has_explicit_bound) - if not _CORRECTION_RE.search(text): - return 0, False - count = 1 - for m in _CORR_COUNT_RE.finditer(text): - tok = next((g for g in m.groups() if g), "").lower() - n = int(tok) if tok.isdigit() else _COUNT_WORDS.get(tok, 1) - count = max(count, n) - return count, False - - def _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 _row_scoped_text(tx: dict) -> str: - footnotes = tx.get("footnotes") - ref_ids = _extract_ref_ids(tx.get("footnote_refs")) - row_parts: list[str] = [] - if isinstance(footnotes, dict) and footnotes and ref_ids: - row_parts.extend(str(footnotes[fid]) for fid in ref_ids if footnotes.get(fid)) - elif isinstance(footnotes, str) and footnotes: - row_parts.append(footnotes) - row_parts.extend(str(tx[k]) for k in ("amendment_reason", "note") if tx.get(k)) - return " ".join(row_parts) - - def _resolve_accession_intents( - acc_rows: list[dict], - ) -> tuple[list[tuple[bool, bool]], list[bool], list[str], int | None]: - row_texts = [_row_scoped_text(tx) for tx in acc_rows] - row_intents = [ - (bool(_ADDITION_RE.search(rt)), bool(_CORRECTION_RE.search(rt))) if rt else (False, False) - for rt in row_texts - ] - ambiguous = [False] * len(acc_rows) - seen_remarks: set[str] = set() - remarks_parts: list[str] = [] - for tx in acc_rows: - rem = str(tx.get("remarks") or "").strip() - if rem and rem not in seen_remarks: - seen_remarks.add(rem) - remarks_parts.append(rem) - if not remarks_parts: - return row_intents, ambiguous, row_texts, 0 - rem_text = " ".join(remarks_parts) - rem_add_count, rem_add_unbounded = _remarks_intent_count(rem_text, kind="add") - rem_corr_count, _ = _remarks_intent_count(rem_text, kind="corr") - if not (rem_add_count or rem_corr_count): - return row_intents, ambiguous, row_texts, 0 - claimed_add_count = sum(1 for ra, _ in row_intents if ra) - claimed_corr_count = sum(1 for _, rc in row_intents if rc) - unclaimed_add_count = max(0, rem_add_count - claimed_add_count) - unclaimed_add = unclaimed_add_count > 0 - unclaimed_corr = rem_corr_count > claimed_corr_count - if not (unclaimed_add or unclaimed_corr): - return row_intents, ambiguous, row_texts, 0 - unattributed = [i for i, (ra, rc) in enumerate(row_intents) if not (ra or rc)] - if len(unattributed) == 1 and (unclaimed_add != unclaimed_corr): - row_intents[unattributed[0]] = (unclaimed_add, unclaimed_corr) - row_texts[unattributed[0]] = f"{row_texts[unattributed[0]]} {rem_text}".strip() - return row_intents, ambiguous, row_texts, 0 - # Filing-level remarks cannot be uniquely attributed (multiple unattributed rows, mixed intent, or - # remarks declaring more additions/corrections than attributed rows); surface uncertainty instead of - # broadcasting to every row, and preserve the bounded remarks-backed addition count. - for i in unattributed: - ambiguous[i] = True - row_texts[i] = f"{row_texts[i]} {rem_text}".strip() - if not unattributed: - for i in range(len(acc_rows)): - ambiguous[i] = True - add_budget: int | None = None if (rem_add_unbounded and not unclaimed_corr) else unclaimed_add_count - return row_intents, ambiguous, row_texts, add_budget - 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() +def _f4_owner_sec_sig(tx: dict) -> tuple: + return (_f4_owner_key(tx), str(tx.get("security") or ""), bool(tx.get("derivative"))) - 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 - ) - def _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_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 _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": {_exact_sig(tx)}, - "revisions": [_rev_tuple(tx)], - "shares_set": {shares} if shares is not None else set(), - "filing_dates": filing_dates, - "orig_accession": str(tx.get("accession") or "").strip() or None, - "from_orig": from_orig, - "reclassified": False, - } - def _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, - ) -> bool: - for rev_date, rev_shares, rev_price in entry["revisions"]: - if dates is not None and rev_date not in dates: - continue - if shares_target is not None and not _matches_num_set(rev_shares, shares_target): - continue - if price_target is not None and not _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_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 - # Unified chronological transaction ledger initialized from original Form 4 filings. - ledger: list[dict] = [_make_ledger_entry(tx, from_orig=True) for tx in all_orig if _is_sell(tx)] - known_non_sells: list[dict] = [tx for tx in all_orig if not _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 = _owner_key(tx) - if ok != ("",): - affected_owners.add(ok) +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: - unaligned_global = True + 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 without splitting decimal numbers such as "$20.50" or "1,250.50". + sents = [s for s in re.split(r"(?:(? set[float]: + 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]: + 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 _owner_sec_sig(tx: dict) -> tuple: - return (_owner_key(tx), str(tx.get("security") or ""), bool(tx.get("derivative"))) - - def _has_date_corr_evidence(tx: dict, rtext: str) -> bool: - if _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 _scoped_pool( - tx: dict, - prior_len: int, - *, - ignore_tx_date: bool = False, - prior_dates: set[str] | None = None, - check_multi_acc: bool = True, - ) -> tuple[list[int], bool]: - 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)): - return list(range(prior_len)), False + +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_row_scoped_text(tx: dict) -> str: + footnotes = tx.get("footnotes") + ref_ids = _f4_extract_ref_ids(tx.get("footnote_refs")) + row_parts: list[str] = [] + if isinstance(footnotes, dict) and footnotes and ref_ids: + row_parts.extend(str(footnotes[fid]) for fid in ref_ids if footnotes.get(fid)) + elif isinstance(footnotes, str) and footnotes: + row_parts.append(footnotes) + row_parts.extend(str(tx[k]) for k in ("amendment_reason", "note") if tx.get(k)) + return " ".join(row_parts) + + +def _f4_resolve_accession_intents( + acc_rows: list[dict], +) -> tuple[list[tuple[bool, bool]], list[bool], list[str]]: + """Resolve per-row (is_add, is_corr) strictly from row-scoped evidence. + + Filing-level is attributed ONLY for a single-row Form 4/A with pure + single-intent remarks (and never promotes a non-sell-only remark onto a sell row). + Multi-row or mixed-intent filing remarks are never parsed into speculative addition + budgets; unattributed rows are surfaced as uncertain instead. + """ + row_texts = [_f4_row_scoped_text(tx) for tx in acc_rows] + row_intents = [ + (bool(_F4_ADDITION_RE.search(rt)), bool(_F4_CORRECTION_RE.search(rt))) if rt else (False, False) + for rt in row_texts + ] + ambiguous = [False] * len(acc_rows) + seen_remarks: set[str] = set() + remarks_parts: list[str] = [] + for tx in acc_rows: + rem = str(tx.get("remarks") or "").strip() + if rem and rem not in seen_remarks: + seen_remarks.add(rem) + remarks_parts.append(rem) + if not remarks_parts: + return row_intents, ambiguous, row_texts + rem_text = " ".join(remarks_parts) + rem_add = bool(_F4_ADDITION_RE.search(rem_text)) + rem_corr = bool(_F4_CORRECTION_RE.search(rem_text)) + if not (rem_add or rem_corr): + return row_intents, ambiguous, row_texts + unclaimed_add = rem_add and not any(ra for ra, _ in row_intents) + 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 + 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]) + and _F4_NONSELL_OBJECT_RE.search(rem_text) + and not _F4_SELL_OR_GENERIC_OBJECT_RE.search(rem_text) + ): + ambiguous[0] = True + return row_intents, ambiguous, row_texts + row_intents[0] = (unclaimed_add, unclaimed_corr) + row_texts[0] = f"{row_texts[0]} {rem_text}".strip() + return row_intents, ambiguous, row_texts + for i in unattributed or range(len(acc_rows)): + ambiguous[i] = True + return row_intents, ambiguous, row_texts + + +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)], + "shares_set": {shares} if shares is not None else set(), + "filing_dates": filing_dates, + "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, +) -> bool: + for rev_date, rev_shares, rev_price in entry["revisions"]: + 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: + ledger[idx]["reclassified"] = True + _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_scoped_pool( + ledger: list[dict], + tx: dict, + prior_len: int, + *, + ignore_tx_date: bool = False, + prior_dates: set[str] | None = None, +) -> tuple[list[int], bool]: + """Filter ledger indices by filing-date provenance (and optional prior transaction dates). + + 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. + """ + 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 = list(range(prior_len)) + else: pool = [i for i in range(prior_len) if orig_date in ledger[i]["filing_dates"]] if not pool: return [], True - if ignore_tx_date: - osig = _owner_sec_sig(tx) - eligible = [i for i in pool if _owner_sec_sig(ledger[i]["tx"]) == osig] - if prior_dates: - eligible = [i for i in eligible if _entry_has_revision(ledger[i], dates=prior_dates)] - if not eligible: - return [], True - if check_multi_acc: - same_accs = {ledger[i]["orig_accession"] for i in eligible if ledger[i]["orig_accession"]} - if len(same_accs) > 1: - return [], True - return eligible if prior_dates else pool, False - if check_multi_acc: - b = _base_sig(tx) - osig = (b[0], b[2], b[3]) - same_accs = { - ledger[i]["orig_accession"] - for i in pool - if ledger[i]["orig_accession"] - and ( - _base_sig(ledger[i]["tx"]) == b - or ( - bool(b[1]) - and _owner_sec_sig(ledger[i]["tx"]) == osig - and _entry_has_revision(ledger[i], dates={b[1][:10]}) - ) - ) - } - if len(same_accs) > 1: - return [], True - return pool, False - - def _record_filing_provenance(idx: int, tx: dict) -> None: - fdate = str(tx.get("filing_date") or "").strip() - if fdate: - ledger[idx]["filing_dates"].add(fdate) - - def _mark_reclassified(idx: int, tx: dict) -> None: - ledger[idx]["reclassified"] = True - _record_filing_provenance(idx, tx) - - def _update_entry(idx: int, tx: dict, *, restore_if_reclassified: bool = False) -> None: - entry = ledger[idx] - entry["tx"] = tx - entry["sigs"].add(_exact_sig(tx)) - rev = _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")) - _record_filing_provenance(idx, tx) - if restore_if_reclassified and entry["reclassified"]: - entry["reclassified"] = False - - def _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 _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") - - # Group ALL Form 4/A rows (sells and non-sells together) by accession and process chronologically by - # (filing_date, EDGAR acceptanceDateTime, accession) so same-day amendments from different submitting agents - # execute in actual acceptance order. When same-day filings lack comparable acceptance timestamps across - # submitting agents (or mix present and missing timestamps), flag uncertainty for the affected owner. + 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) + ] + 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)}") @@ -848,17 +762,18 @@ def _normalize_acceptance_ts(raw) -> str: ( ts for r in rows - if (ts := _normalize_acceptance_ts(r.get("acceptance_datetime") or r.get("acceptanceDateTime"))) + if (ts := _f4_normalize_acceptance_ts(r.get("acceptance_datetime") or r.get("acceptanceDateTime"))) ), default="", ) acc_meta[acc] = (fdate, acc_ts) - for ok in {_owner_key(r) for r in rows}: + 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 @@ -870,638 +785,646 @@ def _same_submitter_prefix(acc_a: str, acc_b: str) -> bool: 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: - for tx in amend_by_acc[a]: - _mark_uncertain(tx) + uncertain_txs.extend(amend_by_acc[a]) - sorted_acc_items = sorted( + sorted_items = sorted( amend_by_acc.items(), key=lambda item: (acc_meta[item[0]][0], acc_meta[item[0]][1], item[0]), ) - - for _acc, acc_rows in sorted_acc_items: - intents, ambig_flags, row_texts, acc_unclaimed_add_count = _resolve_accession_intents(acc_rows) - acc_sells: list[tuple[dict, tuple[bool, bool], bool, str]] = [] - acc_non_sells: list[tuple[dict, tuple[bool, bool], bool, str]] = [] - for tx, intent, is_ambig, rtext in zip(acc_rows, intents, ambig_flags, row_texts): - if is_ambig: - _mark_uncertain(tx) - if _is_sell(tx): - acc_sells.append((tx, intent, is_ambig, rtext)) - else: - acc_non_sells.append((tx, intent, is_ambig, rtext)) - - # Match against the ledger snapshot as of BEFORE this accession's own newly added sales. - prior_len = len(ledger) - - # 1. Reconcile this accession's non-sell 4/A rows against known non-sells and prior ledger entries - # (original Form 4 sells + sells added by earlier Form 4/A accessions) in order-independent passes. - acc_orig_ns_matched: set[int] = set() - acc_matched_ns: set[int] = set() - acc_added_non_sells: list[dict] = [] - ns_candidates: list[tuple[dict, bool, bool]] = [] - for tx, (is_add, is_corr), _is_ambig, rtext in acc_non_sells: - base = _base_sig(tx) - code = _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_ambig = _scoped_pool(tx, prior_len) - ns_idx = next( - ( - i - for i, orig_ns in enumerate(known_non_sells) - if i not in acc_orig_ns_matched - and _base_sig(orig_ns) == base - and _tx_code(orig_ns) == code - and (shares is None or orig_ns.get("shares") == shares) - and (not orig_date or not orig_ns.get("filing_date") or orig_ns.get("filing_date") == orig_date) - ), - None, + return sorted_items, uncertain_txs + + +def _f4_reconcile_non_sells( + ledger: list[dict], + known_non_sells: list[dict], + acc_non_sells: list[tuple[dict, tuple[bool, bool], bool, str]], + prior_len: int, + mark_uncertain, +) -> None: + acc_orig_ns_matched: set[int] = set() + acc_matched_ns: set[int] = set() + acc_added_non_sells: list[dict] = [] + ns_candidates: list[tuple[dict, bool, bool, str]] = [] + for tx, (is_add, is_corr), _is_ambig, rtext 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) + ns_idx = next( + ( + i + for i, orig_ns in enumerate(known_non_sells) + if i not in acc_orig_ns_matched + and _f4_base_sig(orig_ns) == base + and _f4_tx_code(orig_ns) == code + and (shares is None or orig_ns.get("shares") == shares) + and (not orig_date or not orig_ns.get("filing_date") or orig_ns.get("filing_date") == orig_date) + ), + None, + ) + if ns_idx is not None: + priced_sell_match = ( + not pool_unlinked + and has_identity + and tx.get("price") is not None + and known_non_sells[ns_idx].get("price") != tx.get("price") + and any(i not in acc_matched_ns and _f4_exact_sig(tx) in ledger[i]["sigs"] for i in pool) ) - if ns_idx is not None: - # Resolve explicit sale reclassifications (or priced exact matches to a prior sale whose price differs - # from the existing non-sell) against the ledger before applying the non-sell restatement shortcut. - priced_sell_match = ( - not pool_ambig - and has_identity - and tx.get("price") is not None - and known_non_sells[ns_idx].get("price") != tx.get("price") - and any(i not in acc_matched_ns and _exact_sig(tx) in ledger[i]["sigs"] for i in pool) - ) - has_ledger_sell = not pool_ambig and any( - i not in acc_matched_ns and _base_sig(ledger[i]["tx"]) == base for i in pool - ) - if priced_sell_match or (is_corr and has_ledger_sell and bool(_SALE_TO_NONSELL_RE.search(rtext))): - ns_candidates.append((tx, is_add, is_corr)) + 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 (is_corr and has_ledger_sell and bool(_F4_SALE_TO_NONSELL_RE.search(rtext))): + ns_candidates.append((tx, is_add, is_corr, rtext)) + continue + acc_orig_ns_matched.add(ns_idx) + continue + if is_add and not is_corr: + acc_added_non_sells.append(tx) + continue + if pool_unlinked: + mark_uncertain(tx) + continue + ns_candidates.append((tx, is_add, is_corr, rtext)) + + # 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 ns_candidates: + 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: + 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 - acc_orig_ns_matched.add(ns_idx) + reclass_exact = [i for i in exact_cands if ledger[i]["reclassified"]] + target = reclass_exact[0] if reclass_exact else exact_cands[0] + acc_matched_ns.add(target) + _f4_mark_reclassified(ledger, target, tx) continue - if is_add and not is_corr: - acc_added_non_sells.append(tx) + after_ns_a1.append((tx, is_add, is_corr, rtext)) + + # 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"] + ] + if share_cands and _f4_has_multi_accession_ambiguity(ledger, tx, share_cands): + mark_uncertain(tx) continue - if pool_ambig: - _mark_uncertain(tx) + 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"]] + target = reclass_cands[0] if reclass_cands else share_cands[0] + acc_matched_ns.add(target) + _f4_mark_reclassified(ledger, target, tx) continue - ns_candidates.append((tx, is_add, is_corr)) - - # Pass A1: exact (base, shares, price) matches first (independent of row order within accession). - after_ns_a1: list[tuple[dict, bool, bool]] = [] - for tx, is_add, is_corr in ns_candidates: - base = _base_sig(tx) - shares = tx.get("shares") - has_identity = base[0] != ("",) and bool(base[1]) and shares is not None - pool, pool_ambig = _scoped_pool(tx, prior_len) - if pool_ambig: - _mark_uncertain(tx) + deferred_ns.append((tx, is_add, is_corr, rtext)) + + # 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"] + ] + if share_cands and _f4_has_multi_accession_ambiguity(ledger, tx, share_cands): + mark_uncertain(tx) continue - if has_identity and tx.get("price") is not None: - exact = _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: - cur_exact = [i for i in exact_cands if _exact_sig(ledger[i]["tx"]) == exact] - if cur_exact: - exact_cands = cur_exact - # Prefer already-reclassified entry for idempotence across successive gift 4/A filings. - reclass_exact = [i for i in exact_cands if ledger[i]["reclassified"]] - target = reclass_exact[0] if reclass_exact else exact_cands[0] - acc_matched_ns.add(target) - _mark_reclassified(target, tx) - continue - after_ns_a1.append((tx, is_add, is_corr)) - - # Pass A2: unique (base, shares) matches (or uniform-price candidates) after exact matches are reserved. - deferred_ns: list[tuple[dict, bool, bool]] = [] - for tx, is_add, is_corr in after_ns_a1: - base = _base_sig(tx) - shares = tx.get("shares") - has_identity = base[0] != ("",) and bool(base[1]) and shares is not None - pool, _ = _scoped_pool(tx, prior_len) - if has_identity: - share_cands = [ - i - for i in pool - if i not in acc_matched_ns - and _base_sig(ledger[i]["tx"]) == base - and shares in ledger[i]["shares_set"] - ] - 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"]] - target = reclass_cands[0] if reclass_cands else share_cands[0] - acc_matched_ns.add(target) - _mark_reclassified(target, tx) - continue - deferred_ns.append((tx, is_add, is_corr)) - - # Pass B: handle remaining multi-candidate blank-price links and explicit share-changing corrections. - for tx, _is_add, is_corr in deferred_ns: - base = _base_sig(tx) - shares = tx.get("shares") - has_identity = base[0] != ("",) and bool(base[1]) and shares is not None - pool, _ = _scoped_pool(tx, prior_len) - if has_identity: - share_cands = [ - i - for i in pool - if i not in acc_matched_ns - and _base_sig(ledger[i]["tx"]) == base - and shares in ledger[i]["shares_set"] - ] - if len(share_cands) == 1: - acc_matched_ns.add(share_cands[0]) - _mark_reclassified(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: - acc_matched_ns.add(already_reclass[0]) - 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 _base_sig(ledger[i]["tx"]) == base] - if len(base_cands) == 1: - acc_matched_ns.add(base_cands[0]) - _mark_reclassified(base_cands[0], tx) - continue - already_reclass = [i for i in base_cands if ledger[i]["reclassified"]] + if len(share_cands) == 1: + acc_matched_ns.add(share_cands[0]) + _f4_mark_reclassified(ledger, 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: acc_matched_ns.add(already_reclass[0]) continue - _mark_uncertain(tx) + mark_uncertain(tx) continue - if not has_identity: - _mark_uncertain(tx) + 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] + prior_shares = _f4_stated_prior_shares(rtext, shares) + prior_prices = _f4_stated_prior_prices(rtext, tx.get("price")) + if prior_shares or prior_prices: + base_cands = [ + i + for i in base_cands + if _f4_entry_has_revision( + ledger[i], + shares_target=prior_shares or None, + price_target=prior_prices or None, + ) + ] + if base_cands and _f4_has_multi_accession_ambiguity(ledger, tx, base_cands): + mark_uncertain(tx) + continue + if len(base_cands) == 1: + acc_matched_ns.add(base_cands[0]) + _f4_mark_reclassified(ledger, base_cands[0], tx) + continue + already_reclass = [i for i in base_cands if ledger[i]["reclassified"]] + if len(already_reclass) == 1: + acc_matched_ns.add(already_reclass[0]) + continue + mark_uncertain(tx) + continue + if not has_identity: + mark_uncertain(tx) + + known_non_sells.extend(acc_added_non_sells) + + +def _f4_reconcile_sells( + ledger: list[dict], + acc_sells: list[tuple[dict, tuple[bool, bool], bool, str]], + prior_len: int, + mark_uncertain, +) -> None: + acc_matched_sell: set[int] = set() + 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)) - known_non_sells.extend(acc_added_non_sells) + resolved_exact: set[int] = set() + uncertain_exact: set[int] = set() - # 2. Match this accession's sell 4/A rows against all prior ledger entries (reserving each entry by row - # identity across match types, exact matches first, independent of XML row order). - acc_matched_sell: set[int] = set() - 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 resolved in two order-independent batch phases: - # Phase 1a: current-signature exact matches first (so a current $11 row claims its entry before a $10 - # row can claim it via a historical $10 alias). - # Phase 1b: historical-signature alias matches only for non-conflicting unique claims. - 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 _has_date_corr_evidence(tx, rtext) - and bool({d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td}) - ) - has_explicit_prior_shares = is_corr and bool(_stated_prior_shares(rtext, tx.get("shares"))) - has_explicit_prior_price = is_corr and bool(_stated_prior_prices(rtext, tx.get("price"))) - if has_explicit_prior_date or has_explicit_prior_shares or has_explicit_prior_price: - after_exact.append((tx, is_corr, rtext)) + 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 - pool, pool_ambig = _scoped_pool(tx, prior_len) - if pool_ambig: - _mark_uncertain(tx) + exact = _f4_exact_sig(tx) + if use_history: + cands = [i for i in pool if i not in acc_matched_sell and exact in ledger[i]["sigs"]] + else: + cands = [i for i in pool if i not in acc_matched_sell and _f4_exact_sig(ledger[i]["tx"]) == exact] + if not cands: 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, - *, - batch: list[tuple[int, dict, bool, str, list[int]]] = exact_batch, - matched: set[int] = acc_matched_sell, - resolved: set[int] = resolved_exact, - uncertain: set[int] = uncertain_exact, - p_len: int = prior_len, - ) -> 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 batch: - if idx_s in resolved or idx_s in uncertain: - continue - exact = _exact_sig(tx) - if use_history: - cands = [i for i in pool if i not in matched and exact in ledger[i]["sigs"]] - else: - cands = [i for i in pool if i not in matched and _exact_sig(ledger[i]["tx"]) == exact] - if not cands: - continue - is_restore_intent = is_corr and bool(_RESTORE_SELL_RE.search(rtext)) - if is_restore_intent: - reclass_cands = [i for i in cands if ledger[i]["reclassified"]] - if 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.add(idx_s) - else: - active_cands = [i for i in cands if not ledger[i]["reclassified"]] - if len(active_cands) == 1: - # Unannotated historical match only reserves the entry without reverting its current tx. - 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: - # Multiple active entries currently share the exact same signature: resolve slots across - # all overlapping groups together below (narrowest/filing-scoped first) so traversal order - # never displaces a scoped restatement. - sym_restatements.setdefault(tuple(sorted(active_cands)), []).append((idx_s, tx)) - elif len(active_cands) > 1: - _mark_uncertain(tx) - uncertain.add(idx_s) - elif not is_corr: - # Unannotated restatement of a previously reclassified sale: keep gift state & mark uncertain. - if len(cands) == 1: - single_claims.setdefault(cands[0], []).append((idx_s, tx, False, True, False)) - else: - _mark_uncertain(tx) - uncertain.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] - matched.add(target) - claimed_targets.add(target) - if mark_unc: - _mark_uncertain(tx) - elif do_update: - _update_entry(target, tx, restore_if_reclassified=do_restore) + is_restore_intent = is_corr and bool(_F4_RESTORE_SELL_RE.search(rtext)) + 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: - _record_filing_provenance(target, tx) - resolved.add(idx_s) + 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: - for idx_s, tx, _do_restore, _mark_unc, _do_update in claimants: - _mark_uncertain(tx) - uncertain.add(idx_s) - - if sym_restatements: - # Maximum bipartite matching across all overlapping symmetric exact-match groups, ordered - # deterministically from narrowest (filing-scoped) to broadest (unscoped) so scoped rows reserve - # their filing's slots first and unscoped rows take remaining slots regardless of input order. - 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 matched) - 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] - matched.add(slot) - resolved.add(idx_s) - grp_assigned.setdefault(grp_key, []).append((slot, idx_s, tx)) - - # Record filing_date provenance symmetrically: when a group saturates all of its remaining - # available slots (unique or full-group restatement), provenance is exact; when fewer rows than - # identical slots match, attach provenance to the full candidate set (never an arbitrary single - # slot) and mark uncertainty. - 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: - _record_filing_provenance(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: + _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 - # Do not let a displaced restatement from an overlapping conflict inflate the confirmed count. - exact = _exact_sig(tx) - other_unmatched = any( - i not in matched and not ledger[i]["reclassified"] and _exact_sig(ledger[i]["tx"]) == exact - for i in range(p_len) - ) - if other_unmatched or not avail: - _mark_uncertain(tx) - uncertain.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: ALL explicit corrections (is_corr=True: price, share, restoration, and date corrections) - # resolved together in ONE order-independent batch wave BEFORE heuristic unannotated share matching so - # an explicit correction always claims its identified target ahead of an unannotated share restatement. - 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, - *, - p_len: int = prior_len, - matched: set[int] = acc_matched_sell, - ) -> tuple[list[int], bool, bool, bool]: - b = _base_sig(tx) - if b[0] == ("",) or not bool(b[1]): - return [], False, False, False - is_restore_intent = bool(_RESTORE_SELL_RE.search(rtext)) - orig_date = str(tx.get("original_filing_date") or "").strip() - corr_td = str(tx.get("transaction_date") or tx.get("date") or "").strip()[:10] - has_date_corr = _has_date_corr_evidence(tx, rtext) - prior_dates = {d for d in _ISO_DATE_RE.findall(rtext) if d != corr_td} if has_date_corr else set() - prior_prices = _stated_prior_prices(rtext, tx.get("price")) - prior_shares = _stated_prior_shares(rtext, tx.get("shares")) - shares = tx.get("shares") - price = tx.get("price") - - if not prior_dates: - pool, pool_ambig = _scoped_pool(tx, p_len, check_multi_acc=False) - if not pool_ambig: - same_base = [ - i - for i in pool - if i not in matched - and _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: - # Require stated prior shares and/or prior price (and unchanged shares if only price changed) - # to match a SINGLE revision of the ledger entry. - unchanged_shares = shares if (not prior_shares and shares is not None) else _UNSET - cands = [ - i - for i in same_base - if _entry_has_revision( - ledger[i], - shares_target=prior_shares or None, - price_target=prior_prices or None, - exact_shares=unchanged_shares, - ) - ] - if ( - orig_date - and len({ledger[i]["orig_accession"] for i in cands if ledger[i]["orig_accession"]}) > 1 - ): - return [], is_restore_intent, False, False - return cands, is_restore_intent, True, False - # No stated prior shares/price: prefer share-matched entries on same base first, else same base. - if shares is not None: - share_matched = [i for i in same_base if shares in ledger[i]["shares_set"]] - if share_matched: - same_base = share_matched - if ( - orig_date - and len({ledger[i]["orig_accession"] for i in same_base if ledger[i]["orig_accession"]}) > 1 - ): - return [], is_restore_intent, False, False - if same_base: - return same_base, is_restore_intent, False, False - - # Explicit transaction-date correction: link via prior date / original filing after matching stated - # prior fields against a single revision, then check accession uniqueness. - if has_date_corr: - dpool, dpool_ambig = _scoped_pool( - tx, - p_len, - ignore_tx_date=True, - prior_dates=prior_dates or None, - check_multi_acc=False, + 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 dpool_ambig: - return [], is_restore_intent, False, True - osig = _owner_sec_sig(tx) - date_cands = [ + 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") + + if not prior_dates: + pool, pool_unlinked = _f4_scoped_pool(ledger, tx, prior_len) + if not pool_unlinked: + same_base = [ i - for i in dpool - if i not in matched - and _owner_sec_sig(ledger[i]["tx"]) == osig + 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 prior_dates or prior_shares or prior_prices: - # Strict same-revision match: never combine old shares from revision 1 with price from revision 2, - # and never substitute a different date when a stated prior date has no match. - date_cands = [ + 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 date_cands - if _entry_has_revision( + for i in same_base + if _f4_entry_has_revision( ledger[i], - dates=prior_dates or None, shares_target=prior_shares or None, price_target=prior_prices or None, + exact_shares=unchanged_shares, ) ] - 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 _entry_has_revision( - ledger[i], - dates=prior_dates or None, - exact_shares=shares, - exact_price=price, - ) - ] - 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 _entry_has_revision(ledger[i], dates=prior_dates or None, exact_shares=shares) - ] - if by_s: - date_cands = by_s - if ( - orig_date - and len({ledger[i]["orig_accession"] for i in date_cands if ledger[i]["orig_accession"]}) > 1 - ): - 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 _entry_has_revision( - ledger[target], exact_shares=tx.get("shares"), exact_price=tx.get("price") - ) - acc_matched_sell.add(target) - _update_entry(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 (is_corr=False only, order-independent batch - # waves, running AFTER explicit corrections so heuristic restatements never steal explicit targets). - def _heuristic_share_cands( - tx: dict, - *, - p_len: int = prior_len, - matched: set[int] = acc_matched_sell, - ) -> list[int]: - b = _base_sig(tx) - shares = tx.get("shares") - if shares is None or b[0] == ("",) or not bool(b[1]): - return [] - pool, pool_ambig = _scoped_pool(tx, p_len) - if pool_ambig: - return [] - return [ + 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 shares in ledger[i]["shares_set"]] + 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 + ) + if dpool_unlinked: + return [], is_restore_intent, False, True + osig = _f4_owner_sec_sig(tx) + date_cands = [ i - for i in pool - if i not in matched and _base_sig(ledger[i]["tx"]) == b and shares in ledger[i]["shares_set"] + 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, + ) + ] + 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 + ) + ] + 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) + ] + 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 = _heuristic_share_cands(tx) - if 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) - _update_entry(target, tx) - _mark_uncertain(tx) - resolved_heur.add(ridx) - progressed = True - if not progressed: - break - - # Sub-pass 4: remaining unlinked unannotated sell rows — confirm as new sale ONLY when filing evidence - # supports an addition (pigeonhole proof when all prior entries on that base signature were reserved in - # this accession, or bounded by the integer number of unclaimed additions stated in remarks). Excess - # unattributable rows stay uncertain without inflating the confirmed sale count. - remarks_add_cands: list[dict] = [] - pigeonhole_adds = 0 + 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 - if _heuristic_share_cands(tx): - _mark_uncertain(tx) - continue - b = _base_sig(tx) - pool, _ = _scoped_pool(tx, prior_len) - has_prior_same_base = any(_base_sig(ledger[i]["tx"]) == b for i in pool) - all_prior_same_base_reserved = has_prior_same_base and all( - i in acc_matched_sell for i in pool if _base_sig(ledger[i]["tx"]) == b - ) - if all_prior_same_base_reserved: - acc_new_sales.append(tx) - pigeonhole_adds += 1 - elif acc_unclaimed_add_count is None or acc_unclaimed_add_count > 0: - remarks_add_cands.append(tx) - else: - _mark_uncertain(tx) + 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 + + # Sub-pass 4: remaining unlinked unannotated sell rows are confirmed as new sales ONLY on + # deterministic pigeonhole proof (every prior entry on that base signature was reserved in this + # accession). Unattributable rows stay conservative and uncertain without guessing from remarks. + for ridx, tx, _rtext in unannotated_rows: + if ridx in resolved_heur: + continue + cands, is_ambig = _heuristic_share_cands(tx) + if cands or is_ambig: + mark_uncertain(tx) + continue + b = _f4_base_sig(tx) + pool, pool_unlinked = _f4_scoped_pool(ledger, tx, prior_len) + if pool_unlinked: + mark_uncertain(tx) + continue + same_base_pool = [i for i in pool if _f4_base_sig(ledger[i]["tx"]) == b] + if same_base_pool and all(i in acc_matched_sell for i in same_base_pool): + acc_new_sales.append(tx) + else: + 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]) - if remarks_add_cands: - rem_add_budget = ( - None if acc_unclaimed_add_count is None else max(0, acc_unclaimed_add_count - pigeonhole_adds) - ) - if rem_add_budget is None or len(remarks_add_cands) <= rem_add_budget: - acc_new_sales.extend(remarks_add_cands) + +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)] + known_non_sells: 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 = _f4_resolve_accession_intents(acc_rows) + acc_sells: list[tuple[dict, tuple[bool, bool], bool, str]] = [] + acc_non_sells: list[tuple[dict, tuple[bool, bool], bool, str]] = [] + for tx, intent, is_ambig, rtext in 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: - # More unlinked rows than remarks-backed additions: cap added rows at rem_add_budget in - # deterministic, None-safe order and keep all affected rows marked uncertain. - def _cand_sort_key(tx: dict) -> tuple: - td = _tx_date_iso(tx) - shares_v = _safe_float(tx.get("shares")) - price_v = _safe_float(tx.get("price")) - return ( - 0 if (td is None or td >= tx_cutoff) else 1, - _owner_key(tx), - str(tx.get("transaction_date") or tx.get("date") or ""), - str(tx.get("security") or ""), - bool(tx.get("derivative")), - (0, shares_v) if shares_v is not None else (1, 0.0), - (0, price_v) if price_v is not None else (1, 0.0), - ) + acc_non_sells.append((tx, intent, is_ambig, rtext)) - ordered_cands = sorted(remarks_add_cands, key=_cand_sort_key) - if rem_add_budget > 0: - acc_new_sales.extend(ordered_cands[:rem_add_budget]) - for tx in ordered_cands: - _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(_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(_make_ledger_entry(tx, from_orig=False) for tx in rows[:need]) + prior_len = len(ledger) + _f4_reconcile_non_sells(ledger, known_non_sells, acc_non_sells, prior_len, _mark_uncertain) + _f4_reconcile_sells(ledger, acc_sells, prior_len, _mark_uncertain) active_sales = [entry for entry in ledger if not entry["reclassified"]] recent_active_sales: list[tuple[dict, bool]] = [] for entry in active_sales: - td = _tx_date_iso(entry["tx"]) + td = _f4_tx_date_iso(entry["tx"]) if td is None: recent_active_sales.append((entry, False)) elif td >= tx_cutoff: @@ -1514,7 +1437,7 @@ def _cand_sort_key(tx: dict) -> tuple: else sum( 1 for entry, has_valid_date in recent_active_sales - if has_valid_date and entry["from_orig"] and _owner_key(entry["tx"]) not in affected_owners + if has_valid_date and entry["from_orig"] and _f4_owner_key(entry["tx"]) not in affected_owners ) ) result["sales_90d"] = dedup_sales From 2cbb708bc7bcb00d0001546072e355ad625272e6 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 13:39:39 +0800 Subject: [PATCH 20/37] fix(risk): enforce filing chronology, preserve gift revisions, and prioritize stated prior values in non-sell matching --- tests/test_risk_screening.py | 142 ++++++++++++++++++++++++++++++++++- tools/risk_screening.py | 142 ++++++++++++++++++++++++++++++----- 2 files changed, 262 insertions(+), 22 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 322cd49..2da9ef5 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -1250,9 +1250,12 @@ def _parse(accn, fdate, form, doc): # 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], transaction_date="2026-08-03", shares=100, price=10.0), - dict(orig_rows[0], transaction_date="2026-08-04", shares=100, price=10.0), - ] + [dict(orig_rows[0], transaction_date=f"2026-08-0{i}", shares=100, price=10.0) for i in range(5, 10)] + 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", @@ -2124,6 +2127,8 @@ def _parse(accn, fdate, form, doc): "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 @@ -2134,6 +2139,8 @@ def _parse(accn, fdate, form, doc): 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 @@ -2148,6 +2155,135 @@ def _parse(accn, fdate, form, doc): 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"] == 3 + assert res_undated["checks"]["insider_trades"]["count_uncertain"] is True + def test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): base_inputs = { diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 70cfe6d..023c8fb 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -382,9 +382,9 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: ) _F4_RESTORE_SELL_RE = re.compile( r"(reclassif(?:ied|y|ying)|transaction\s+code|\bcode\s+s\b|" - r"(?:was|is|should\s+have\s+been)\s+(?:actually\s+)?(?:a\s+)?(?:open[- ]market\s+)?sale\b|" + r"(?:was|is|should\s+have\s+been)\s+(?:actually\s+)?(?:a\s+)?(?:[\w-]+\s+){0,2}sale\b|" r"(?:instead\s+of|not)\s+(?:a\s+)?(?:[\w-]+\s+){0,2}(?:gift|non-sale|transfer)\b|" - r"(?:from|misreported|erroneously\s+reported|incorrectly\s+reported)\s+(?:as\s+)?(?:a\s+)?(?:[\w-]+\s+){0,3}(?:gift|non-sale)\b|" + r"(?:from|misreported|(?:erroneously|incorrectly|previously)\s+reported)\s+(?:as\s+)?(?:a\s+)?(?:[\w-]+\s+){0,3}(?:gift|non-sale)\b|" r"重分类|改为卖出|恢复为卖出|并非赠与)", re.IGNORECASE, ) @@ -502,8 +502,8 @@ def _f4_matches_num_set(val, target_set: set[float]) -> bool: def _f4_correction_sentences(rtext: str) -> str: - # Split on sentence boundaries without splitting decimal numbers such as "$20.50" or "1,250.50". - sents = [s for s in re.split(r"(?:(? dict: "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_normalize_acceptance_ts( + tx.get("acceptance_datetime") or tx.get("acceptanceDateTime") + ), "orig_accession": str(tx.get("accession") or "").strip() or None, "from_orig": from_orig, "reclassified": False, @@ -666,8 +671,10 @@ def _f4_entry_has_revision( price_target: set[float] | None = None, exact_shares: object = _UNSET, exact_price: object = _UNSET, + include_gift_revisions: bool = False, ) -> bool: - for rev_date, rev_shares, rev_price in entry["revisions"]: + revs = entry["revisions"] + (entry["gift_revisions"] if include_gift_revisions else []) + 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): @@ -689,7 +696,12 @@ def _f4_record_filing_provenance(ledger: list[dict], idx: int, tx: dict) -> None def _f4_mark_reclassified(ledger: list[dict], idx: int, tx: dict) -> None: - ledger[idx]["reclassified"] = True + entry = ledger[idx] + entry["reclassified"] = True + entry["gift_sigs"].add(_f4_exact_sig(tx)) + rev = _f4_rev_tuple(tx) + if rev not in entry["gift_revisions"]: + entry["gift_revisions"].append(rev) _f4_record_filing_provenance(ledger, idx, tx) @@ -714,18 +726,35 @@ def _f4_scoped_pool( *, 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-date provenance (and optional prior transaction dates). + """Filter ledger indices by filing chronology and filing-date provenance. - Multi-accession ambiguity is intentionally NOT checked here; callers check + 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_normalize_acceptance_ts(tx.get("acceptance_datetime") or tx.get("acceptanceDateTime")) + + def _filed_on_or_before(entry: dict) -> bool: + if not amend_fdate or not entry["filing_dates"]: + return True + earliest = min(entry["filing_dates"]) + if earliest > amend_fdate: + return False + if earliest == amend_fdate and amend_ts and entry["orig_acceptance_ts"]: + return entry["orig_acceptance_ts"] <= amend_ts + return True + 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 = list(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"]] + 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: @@ -733,7 +762,8 @@ def _f4_scoped_pool( 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) + 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) ] if not eligible: return [], True @@ -848,9 +878,48 @@ def _f4_reconcile_non_sells( continue ns_candidates.append((tx, is_add, is_corr, rtext)) + # Pass A0: explicit corrections stating prior shares/price resolve FIRST against prior revisions + # so new values (e.g., 200-sh sale -> 100-sh gift at $0) never hijack an unrelated 100-sh sale in Pass A1/A2. + after_ns_a0: list[tuple[dict, bool, bool, str]] = [] + for tx, is_add, is_corr, rtext in 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]): + pool, pool_unlinked = _f4_scoped_pool(ledger, tx, prior_len) + if pool_unlinked: + mark_uncertain(tx) + continue + base_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, + ) + ] + if base_cands and _f4_has_multi_accession_ambiguity(ledger, tx, base_cands): + mark_uncertain(tx) + continue + if len(base_cands) == 1: + acc_matched_ns.add(base_cands[0]) + _f4_mark_reclassified(ledger, base_cands[0], tx) + continue + already_reclass = [i for i in base_cands if ledger[i]["reclassified"]] + if len(already_reclass) == 1: + acc_matched_ns.add(already_reclass[0]) + continue + mark_uncertain(tx) + continue + after_ns_a0.append((tx, is_add, is_corr, rtext)) + # 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 ns_candidates: + 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 @@ -1015,13 +1084,26 @@ def _exact_phase(use_history: bool) -> None: if idx_s in resolved_exact or idx_s in uncertain_exact: continue exact = _f4_exact_sig(tx) + is_restore_intent = is_corr and bool(_F4_RESTORE_SELL_RE.search(rtext)) if use_history: - cands = [i for i in pool if i not in acc_matched_sell and exact in ledger[i]["sigs"]] + cands = [ + i + for i in pool + if i not in acc_matched_sell + and (exact in ledger[i]["sigs"] or (is_restore_intent and exact in ledger[i]["gift_sigs"])) + ] else: - cands = [i for i in pool if i not in acc_matched_sell and _f4_exact_sig(ledger[i]["tx"]) == exact] + 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 exact in ledger[i]["gift_sigs"]) + ) + ] if not cands: continue - is_restore_intent = is_corr and bool(_F4_RESTORE_SELL_RE.search(rtext)) 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): @@ -1178,13 +1260,19 @@ def _corr_match_cands(tx: dict, rtext: str) -> tuple[list[int], bool, bool, bool shares_target=prior_shares or None, price_target=prior_prices or None, exact_shares=unchanged_shares, + include_gift_revisions=is_restore_intent, ) ] 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 shares in ledger[i]["shares_set"]] + share_matched = [ + i + for i in same_base + if shares in ledger[i]["shares_set"] + or (is_restore_intent and any(rev[1] == shares for rev in ledger[i]["gift_revisions"])) + ] if share_matched: same_base = share_matched if _f4_has_multi_accession_ambiguity(ledger, tx, same_base): @@ -1194,7 +1282,12 @@ def _corr_match_cands(tx: dict, rtext: str) -> tuple[list[int], bool, bool, bool if has_date_corr: dpool, dpool_unlinked = _f4_scoped_pool( - ledger, tx, prior_len, ignore_tx_date=True, prior_dates=prior_dates or None + 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 @@ -1215,6 +1308,7 @@ def _corr_match_cands(tx: dict, rtext: str) -> tuple[list[int], bool, bool, bool dates=prior_dates or None, shares_target=prior_shares or None, price_target=prior_prices or None, + include_gift_revisions=is_restore_intent, ) ] if len(date_cands) > 1 and shares is not None and price is not None and not (prior_shares or prior_prices): @@ -1222,7 +1316,11 @@ def _corr_match_cands(tx: dict, rtext: str) -> tuple[list[int], bool, bool, bool i for i in date_cands if _f4_entry_has_revision( - ledger[i], dates=prior_dates or None, exact_shares=shares, exact_price=price + ledger[i], + dates=prior_dates or None, + exact_shares=shares, + exact_price=price, + include_gift_revisions=is_restore_intent, ) ] if by_sp: @@ -1231,7 +1329,12 @@ def _corr_match_cands(tx: dict, rtext: str) -> tuple[list[int], bool, bool, bool by_s = [ i for i in date_cands - if _f4_entry_has_revision(ledger[i], dates=prior_dates or None, exact_shares=shares) + if _f4_entry_has_revision( + ledger[i], + dates=prior_dates or None, + exact_shares=shares, + include_gift_revisions=is_restore_intent, + ) ] if by_s: date_cands = by_s @@ -1426,6 +1529,7 @@ def _mark_uncertain(tx: dict) -> None: for entry in active_sales: td = _f4_tx_date_iso(entry["tx"]) if td is None: + _mark_uncertain(entry["tx"]) recent_active_sales.append((entry, False)) elif td >= tx_cutoff: recent_active_sales.append((entry, True)) From 0684a2b329cd855bdcff7a2a827d6a37e756e8db Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 14:48:53 +0800 Subject: [PATCH 21/37] fix(risk): tighten restore regex, batch Pass A0 waves, defer gift revision commits, and scope gift revisions by filing date --- tests/test_risk_screening.py | 183 ++++++++++++++++++++++++++++++++ tools/risk_screening.py | 199 +++++++++++++++++++++++------------ 2 files changed, 314 insertions(+), 68 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 2da9ef5..1332b3f 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -2284,6 +2284,189 @@ def _parse(accn, fdate, form, doc): assert res_undated["checks"]["insider_trades"]["sales_90d"] == 3 assert res_undated["checks"]["insider_trades"]["count_uncertain"] is True + # 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 test_hk_disclosures_resumption_notice_no_veto_and_incomplete_provider_marks_unavailable(): base_inputs = { diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 023c8fb..4f51bce 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -372,19 +372,20 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: re.IGNORECASE, ) _F4_SALE_TO_NONSELL_RE = re.compile( - r"(reclassif(?:ied|y|ying)|transaction\s+code|\bcode\s+s\s+to\b|" - r"(?:from|misreported|erroneously\s+reported|incorrectly\s+reported)\s+(?:as\s+)?(?:a\s+)?(?:[\w-]+\s+){0,3}(?:sale|sell|sold)\b|" - r"(?: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"(?:instead\s+of|not)\s+(?:a\s+)?(?:[\w-]+\s+){0,2}(?:sale|sell|sold)\b|" + 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_RESTORE_SELL_RE = re.compile( - r"(reclassif(?:ied|y|ying)|transaction\s+code|\bcode\s+s\b|" - r"(?:was|is|should\s+have\s+been)\s+(?:actually\s+)?(?:a\s+)?(?:[\w-]+\s+){0,2}sale\b|" - r"(?:instead\s+of|not)\s+(?:a\s+)?(?:[\w-]+\s+){0,2}(?:gift|non-sale|transfer)\b|" - r"(?:from|misreported|(?:erroneously|incorrectly|previously)\s+reported)\s+(?:as\s+)?(?:a\s+)?(?:[\w-]+\s+){0,3}(?:gift|non-sale)\b|" + 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, ) @@ -672,8 +673,16 @@ def _f4_entry_has_revision( exact_shares: object = _UNSET, exact_price: object = _UNSET, include_gift_revisions: bool = False, + gift_filing_date: str | None = None, ) -> bool: - revs = entry["revisions"] + (entry["gift_revisions"] if include_gift_revisions else []) + if include_gift_revisions: + if gift_filing_date: + matching_gf = [rev[1:] for rev in entry["gift_revisions"] if rev[0] == gift_filing_date] + revs = matching_gf if matching_gf else entry["revisions"] + [rev[1:] for rev in entry["gift_revisions"]] + else: + revs = entry["revisions"] + [rev[1:] for rev in entry["gift_revisions"]] + else: + revs = entry["revisions"] for rev_date, rev_shares, rev_price in revs: if dates is not None and rev_date not in dates: continue @@ -698,10 +707,11 @@ def _f4_record_filing_provenance(ledger: list[dict], idx: int, tx: dict) -> None def _f4_mark_reclassified(ledger: list[dict], idx: int, tx: dict) -> None: entry = ledger[idx] entry["reclassified"] = True - entry["gift_sigs"].add(_f4_exact_sig(tx)) - rev = _f4_rev_tuple(tx) - if rev not in entry["gift_revisions"]: - entry["gift_revisions"].append(rev) + gfdate = str(tx.get("filing_date") or "").strip() + entry["gift_sigs"].add((gfdate, _f4_exact_sig(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) @@ -763,7 +773,12 @@ def _filed_on_or_before(entry: dict) -> bool: 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) + 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 @@ -830,9 +845,10 @@ def _f4_reconcile_non_sells( acc_non_sells: list[tuple[dict, tuple[bool, bool], bool, str]], prior_len: int, mark_uncertain, -) -> None: +) -> 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]] = [] acc_added_non_sells: list[dict] = [] ns_candidates: list[tuple[dict, bool, bool, str]] = [] for tx, (is_add, is_corr), _is_ambig, rtext in acc_non_sells: @@ -878,44 +894,74 @@ def _f4_reconcile_non_sells( continue ns_candidates.append((tx, is_add, is_corr, rtext)) - # Pass A0: explicit corrections stating prior shares/price resolve FIRST against prior revisions - # so new values (e.g., 200-sh sale -> 100-sh gift at $0) never hijack an unrelated 100-sh sale in Pass A1/A2. + # 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 tx, is_add, is_corr, rtext in ns_candidates: + 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]): - pool, pool_unlinked = _f4_scoped_pool(ledger, tx, prior_len) - if pool_unlinked: - mark_uncertain(tx) - continue - base_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, - ) - ] - if base_cands and _f4_has_multi_accession_ambiguity(ledger, tx, base_cands): - mark_uncertain(tx) - continue - if len(base_cands) == 1: - acc_matched_ns.add(base_cands[0]) - _f4_mark_reclassified(ledger, base_cands[0], tx) + 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, 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, + ) + ] + 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 - already_reclass = [i for i in base_cands if ledger[i]["reclassified"]] + cands, is_ambig = _a0_cands(tx, 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] + acc_matched_ns.add(target) + pending_reclassifications.append((target, tx)) + resolved_a0.add(idx_ns) + progressed = True + if not progressed: + break + + 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, prior_shares, prior_prices) + if not is_ambig: + already_reclass = [i for i in cands if ledger[i]["reclassified"]] if len(already_reclass) == 1: acc_matched_ns.add(already_reclass[0]) + pending_reclassifications.append((already_reclass[0], tx)) continue - mark_uncertain(tx) - continue - after_ns_a0.append((tx, is_add, is_corr, rtext)) + mark_uncertain(tx) # Pass A1: exact (base, shares, price) matches first (independent of row order within accession). after_ns_a1: list[tuple[dict, bool, bool, str]] = [] @@ -940,7 +986,7 @@ def _f4_reconcile_non_sells( reclass_exact = [i for i in exact_cands if ledger[i]["reclassified"]] target = reclass_exact[0] if reclass_exact else exact_cands[0] acc_matched_ns.add(target) - _f4_mark_reclassified(ledger, target, tx) + pending_reclassifications.append((target, tx)) continue after_ns_a1.append((tx, is_add, is_corr, rtext)) @@ -968,12 +1014,12 @@ def _f4_reconcile_non_sells( reclass_cands = [i for i in share_cands if ledger[i]["reclassified"]] target = reclass_cands[0] if reclass_cands else share_cands[0] acc_matched_ns.add(target) - _f4_mark_reclassified(ledger, target, tx) + pending_reclassifications.append((target, tx)) continue deferred_ns.append((tx, is_add, is_corr, rtext)) # Pass B: remaining blank-price links and explicit share-changing corrections. - for tx, _is_add, is_corr, rtext in deferred_ns: + 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 @@ -991,39 +1037,29 @@ def _f4_reconcile_non_sells( continue if len(share_cands) == 1: acc_matched_ns.add(share_cands[0]) - _f4_mark_reclassified(ledger, share_cands[0], tx) + pending_reclassifications.append((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: acc_matched_ns.add(already_reclass[0]) + pending_reclassifications.append((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] - prior_shares = _f4_stated_prior_shares(rtext, shares) - prior_prices = _f4_stated_prior_prices(rtext, tx.get("price")) - if prior_shares or prior_prices: - base_cands = [ - i - for i in base_cands - if _f4_entry_has_revision( - ledger[i], - shares_target=prior_shares or None, - price_target=prior_prices or None, - ) - ] if base_cands and _f4_has_multi_accession_ambiguity(ledger, tx, base_cands): mark_uncertain(tx) continue if len(base_cands) == 1: acc_matched_ns.add(base_cands[0]) - _f4_mark_reclassified(ledger, base_cands[0], tx) + pending_reclassifications.append((base_cands[0], tx)) continue already_reclass = [i for i in base_cands if ledger[i]["reclassified"]] if len(already_reclass) == 1: acc_matched_ns.add(already_reclass[0]) + pending_reclassifications.append((already_reclass[0], tx)) continue mark_uncertain(tx) continue @@ -1031,6 +1067,7 @@ def _f4_reconcile_non_sells( mark_uncertain(tx) known_non_sells.extend(acc_added_non_sells) + return acc_matched_ns, pending_reclassifications def _f4_reconcile_sells( @@ -1038,8 +1075,10 @@ def _f4_reconcile_sells( 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() + 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: @@ -1084,13 +1123,24 @@ def _exact_phase(use_history: bool) -> None: 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 in entry["gift_sigs"] if fd == gfd] + if on_date: + return sig in on_date + return any(gsig == sig for _fd, gsig 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 exact in ledger[i]["gift_sigs"])) + and (exact in ledger[i]["sigs"] or (is_restore_intent and _matches_gift_sig(ledger[i]))) ] else: cands = [ @@ -1098,8 +1148,7 @@ def _exact_phase(use_history: bool) -> None: for i in pool if i not in acc_matched_sell and ( - _f4_exact_sig(ledger[i]["tx"]) == exact - or (is_restore_intent and exact in ledger[i]["gift_sigs"]) + _f4_exact_sig(ledger[i]["tx"]) == exact or (is_restore_intent and _matches_gift_sig(ledger[i])) ) ] if not cands: @@ -1236,6 +1285,8 @@ def _corr_match_cands(tx: dict, rtext: str) -> tuple[list[int], bool, bool, bool 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: @@ -1261,6 +1312,7 @@ def _corr_match_cands(tx: dict, rtext: str) -> tuple[list[int], bool, bool, bool 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): @@ -1270,8 +1322,12 @@ def _corr_match_cands(tx: dict, rtext: str) -> tuple[list[int], bool, bool, bool share_matched = [ i for i in same_base - if shares in ledger[i]["shares_set"] - or (is_restore_intent and any(rev[1] == shares for rev in ledger[i]["gift_revisions"])) + 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 @@ -1309,6 +1365,7 @@ def _corr_match_cands(tx: dict, rtext: str) -> tuple[list[int], bool, bool, bool 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): @@ -1321,6 +1378,7 @@ def _corr_match_cands(tx: dict, rtext: str) -> tuple[list[int], bool, bool, bool exact_shares=shares, exact_price=price, include_gift_revisions=is_restore_intent, + gift_filing_date=orig_date, ) ] if by_sp: @@ -1334,6 +1392,7 @@ def _corr_match_cands(tx: dict, rtext: str) -> tuple[list[int], bool, bool, bool dates=prior_dates or None, exact_shares=shares, include_gift_revisions=is_restore_intent, + gift_filing_date=orig_date, ) ] if by_s: @@ -1521,8 +1580,12 @@ def _mark_uncertain(tx: dict) -> None: acc_non_sells.append((tx, intent, is_ambig, rtext)) prior_len = len(ledger) - _f4_reconcile_non_sells(ledger, known_non_sells, acc_non_sells, prior_len, _mark_uncertain) - _f4_reconcile_sells(ledger, acc_sells, prior_len, _mark_uncertain) + acc_matched_ns, pending_reclassifications = _f4_reconcile_non_sells( + ledger, known_non_sells, 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[tuple[dict, bool]] = [] From da258e0c7d9d459f6f10fcc9efd6e891cf2483e9 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 15:10:35 +0800 Subject: [PATCH 22/37] fix(risk): require filing evidence for SEC sale counts --- tests/test_risk_screening.py | 402 ++++++++++++++++++++++++++++++++++- tools/risk_screening.py | 250 +++++++++++++++------- 2 files changed, 564 insertions(+), 88 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 1332b3f..5ff2845 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -258,7 +258,10 @@ def test_us_risk_screening_uses_sec_form4_when_configured(monkeypatch): def fake_run(script, args, **kwargs): calls.append((script, args)) if script == "sec_edgar.py" and args[0] == "insider_trades": - return {"transactions": [{"code": "S"}, {"code": "S"}, {"code": "S"}]} + 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( @@ -640,12 +643,14 @@ def _run_us(tx_list): assert res_seventh["checks"]["insider_trades"]["sales_90d"] == 7 assert res_seventh["veto_buy"] is True - # Branch H (Weaxs P2 & CodeRabbit Major 594): row-order invariance — each original sale matched at most once + # 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) - assert _run_us(orig_single + [amend_155, amend_150])["checks"]["insider_trades"]["sales_90d"] == 2 - assert _run_us(orig_single + [amend_150, amend_155])["checks"]["insider_trades"]["sales_90d"] == 2 + 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]): @@ -1039,8 +1044,7 @@ def _parse(accn, fdate, form, doc): assert res_unlinked["checks"]["insider_trades"]["count_uncertain"] is True assert not any(f["category"] == "insider" for f in res_unlinked["flags"]) - # 6. Multi-row filing-level remarks never override missing row footnotes: row-scoped F1 confirms +1 addition, - # exact unannotated restatements match existing sales, and unlinked rows stay conservative + uncertain. + # 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", @@ -2281,8 +2285,9 @@ def _parse(accn, fdate, form, doc): 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"] == 3 + 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 = [ @@ -2468,6 +2473,386 @@ def _parse(accn, fdate, form, doc): 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 test_form4_screen_cli_requires_affirmative_matching_addition_count(monkeypatch): + 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__') +""" + 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 + ] + fixture = { + "stock_data.py": {"pe": 25, "pb": 5}, + "technical.py": {"signal_score": 60, "buy_signal": "HOLD"}, + "sec_edgar.py": {"transactions": originals + amendments, "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 + assert json.loads(cli.stdout)["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_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) + 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}, @@ -2536,7 +2921,8 @@ def test_us_risk_screening_truncated_sec_marks_incomplete_and_keeps_flags(monkey def fake_run(script, args, **kwargs): if script == "sec_edgar.py" and args[0] == "insider_trades": return { - "transactions": [{"code": "S"}, {"code": "S"}, {"code": "S"}], + "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"], } diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 4f51bce..c036984 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -368,7 +368,41 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: _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"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_OMITTED = r"(?:(?:previously|inadvertently)\s+)?(?:omitted|unreported)" +_F4_REMARKS_DATE = r"[a-z]+ \d{1,2},? \d{4}" +_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[1-9]\d{{0,3}}|an?|the|{'|'.join(_F4_COUNT_WORDS[1:])})\s+" + rf"(?:(?P{_F4_OMITTED}|additional)\s+)?(?Psale(?: transactions?|s)?|transactions?)" + r"(?:\s+of (?:[\d,.]+\s+)?(?:(?:common|ordinary|class [a-z])\s+)?shares?)?" + rf"(?:\s+(?P(?:(?:that\s+)?(?:was|were)\s+)?{_F4_OMITTED})" + rf"(?:\s+from the (?:original )?(?:form 4|filing)(?: filed on {_F4_REMARKS_DATE})?)?)?" + r"(?:\s+by the reporting (?:person|owner))?", + re.IGNORECASE | re.ASCII, +) +_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( @@ -380,6 +414,19 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: r"重分类|改为赠与|误报为卖出|并非卖出)", re.IGNORECASE, ) +_F4_SALE_REFERENCE = ( + r"(?:(?:the|a)\s+)?(?:(?:previously reported|original)\s+)?(?:[\d,.]+-share\s+)?sale" + r"(?:\s+of\s+[\d,.]+\s+shares?)?(?:\s+at\s+\$?\s*[\d,.]+)?" +) +_F4_CURRENT_CHANGE = r"(?:this amendment\s+)?(?:corrects?|reclassif(?:ies|y)|changes?)" +_F4_EXPLICIT_SALE_RECLASS_RE = re.compile( + rf"^(?:{_F4_CURRENT_CHANGE}\s+" + rf"{_F4_SALE_REFERENCE}|{_F4_SALE_REFERENCE}\s+" + r"(?:was previously reported in error and\s+)?(?:is|should be)\s+reclassified)" + r"\s+(?:to|as)\s+(?:a\s+)?(?:(?:bona fide|[\d,.]+-share)\s+)?(?:gift|non-sale|transfer|disposition)\b" + rf"|^{_F4_CURRENT_CHANGE}\s+(?:the\s+)?(?:transaction\s+)?code\s+(?:from\s+)?s\s+to\s+(?!s\b)[a-z]\b", + 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|" @@ -414,16 +461,6 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: r"(?:misreported|reported|prior|original)\s+(\d+(?:,\d{3})*(?:\.\d+)?)[- ]shares?\s+(?:sale|transaction)\b", re.IGNORECASE, ) -_F4_NONSELL_OBJECT_RE = re.compile( - r"\b(?:gift|gifts|award|awards|grant|grants|option|options|rsu|rsus|transfer|transfers|withholding|exercise|exercises)\b|" - r"赠与|授予|行权|预扣", - re.IGNORECASE, -) -_F4_SELL_OR_GENERIC_OBJECT_RE = re.compile( - r"\b(?:sale|sales|sell|sold|disposition|dispositions|transaction|transactions|trade|trades|line|lines|row|rows)\b|" - r"卖出|减持|交易|笔", - re.IGNORECASE, -) def _f4_tx_code(tx: dict) -> str: @@ -504,7 +541,7 @@ def _f4_matches_num_set(val, target_set: set[float]) -> bool: 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 re.split(r"(?:\.(?=\s|$)|[!?;。!?;])+", rtext) if s.strip()] + 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 @@ -591,18 +628,23 @@ def _f4_row_scoped_text(tx: dict) -> str: def _f4_resolve_accession_intents( acc_rows: list[dict], + ledger: list[dict], ) -> tuple[list[tuple[bool, bool]], list[bool], list[str]]: """Resolve per-row (is_add, is_corr) strictly from row-scoped evidence. - Filing-level is attributed ONLY for a single-row Form 4/A with pure - single-intent remarks (and never promotes a non-sell-only remark onto a sell row). - Multi-row or mixed-intent filing remarks are never parsed into speculative addition - budgets; unattributed rows are surfaced as uncertain instead. + Use filing remarks for a single unambiguous row or an explicit sale addition count + covering every row. Leave unattributed rows in mixed filings uncertain. """ row_texts = [_f4_row_scoped_text(tx) for tx in acc_rows] + prior_disclosures = [ + any(not match["negated"] for match in _F4_PRIOR_DISCLOSURE_RE.finditer(text)) for text in row_texts + ] row_intents = [ - (bool(_F4_ADDITION_RE.search(rt)), bool(_F4_CORRECTION_RE.search(rt))) if rt else (False, False) - for rt in row_texts + ( + bool(_F4_ADDITION_RE.search(rt)) and not (_f4_is_sell(tx) and prior), + bool(_F4_CORRECTION_RE.search(rt)), + ) + for tx, rt, prior in zip(acc_rows, row_texts, prior_disclosures) ] ambiguous = [False] * len(acc_rows) seen_remarks: set[str] = set() @@ -615,22 +657,59 @@ def _f4_resolve_accession_intents( if not remarks_parts: return row_intents, ambiguous, row_texts rem_text = " ".join(remarks_parts) - rem_add = bool(_F4_ADDITION_RE.search(rem_text)) + # shortcut: promote explicit English declarations, and expand for verified filing wording. + statements = [] + mixed_remarks = False + for part in _F4_SENTENCE_BOUNDARY_RE.split(rem_text): + sentence = part.strip() + match = _F4_COUNTED_SALE_ADDITION_RE.fullmatch(sentence) + if match and (match["modifier"] or match["clause"] or match["verb"].lower().startswith("add")): + statements.append(match) + elif sentence and (not _F4_REMARKS_METADATA_RE.fullmatch(sentence) or _F4_OTHER_CHANGE_RE.search(sentence)): + mixed_remarks = True + counted = statements[0] if len(statements) == 1 else None + declared_additions = 0 + if counted: + count = counted["count"].lower() + if count.isdigit(): + declared_additions = int(count) + elif count in {"a", "an", "the"}: + declared_additions = int(not counted["object"].lower().endswith("s")) + else: + declared_additions = _F4_COUNT_WORDS.index(count) + rem_add = bool(statements) or bool(_F4_ADDITION_RE.search(rem_text)) rem_corr = bool(_F4_CORRECTION_RE.search(rem_text)) if not (rem_add or rem_corr): return row_intents, ambiguous, row_texts - unclaimed_add = rem_add and not any(ra for ra, _ in row_intents) + if ( + counted + and len(remarks_parts) == 1 + and declared_additions == len(acc_rows) + and (len(acc_rows) == 1 or counted["object"].lower().startswith("sale")) + and not mixed_remarks + and not rem_corr + 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 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 + claimed_additions = sum(addition for addition, _ in row_intents) + unclaimed_add = rem_add and claimed_additions < (declared_additions or 1) 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 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]) - and _F4_NONSELL_OBJECT_RE.search(rem_text) - and not _F4_SELL_OR_GENERIC_OBJECT_RE.search(rem_text) - ): + if unclaimed_add and _f4_is_sell(acc_rows[0]): ambiguous[0] = True return row_intents, ambiguous, row_texts row_intents[0] = (unclaimed_add, unclaimed_corr) @@ -849,6 +928,22 @@ def _f4_reconcile_non_sells( acc_orig_ns_matched: set[int] = set() acc_matched_ns: set[int] = set() pending_reclassifications: list[tuple[int, 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 _F4_EXPLICIT_SALE_RECLASS_RE.match(text.strip()): + 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 in acc_non_sells: @@ -908,7 +1003,7 @@ def _f4_reconcile_non_sells( else: after_ns_a0.append((tx, is_add, is_corr, rtext)) - def _a0_cands(tx: dict, prior_shares: set[float], prior_prices: set[float]) -> tuple[list[int], bool]: + 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 @@ -927,6 +1022,7 @@ def _a0_cands(tx: dict, prior_shares: set[float], prior_prices: set[float]) -> t 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 @@ -934,34 +1030,34 @@ def _a0_cands(tx: dict, prior_shares: set[float], prior_prices: set[float]) -> t 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: + 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, prior_shares, prior_prices) + 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] - acc_matched_ns.add(target) - pending_reclassifications.append((target, tx)) + 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: + 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, prior_shares, prior_prices) + 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: - acc_matched_ns.add(already_reclass[0]) - pending_reclassifications.append((already_reclass[0], tx)) + 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]] = [] @@ -977,6 +1073,7 @@ def _a0_cands(tx: dict, prior_shares: set[float], prior_prices: set[float]) -> t 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 @@ -984,11 +1081,10 @@ def _a0_cands(tx: dict, prior_shares: set[float], prior_prices: set[float]) -> t mark_uncertain(tx) continue reclass_exact = [i for i in exact_cands if ledger[i]["reclassified"]] - target = reclass_exact[0] if reclass_exact else exact_cands[0] - acc_matched_ns.add(target) - pending_reclassifications.append((target, tx)) + 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]] = [] @@ -1005,6 +1101,7 @@ def _a0_cands(tx: dict, prior_shares: set[float], prior_prices: set[float]) -> t 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 @@ -1012,14 +1109,13 @@ def _a0_cands(tx: dict, prior_shares: set[float], prior_prices: set[float]) -> t 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"]] - target = reclass_cands[0] if reclass_cands else share_cands[0] - acc_matched_ns.add(target) - pending_reclassifications.append((target, tx)) + 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: + 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 @@ -1032,40 +1128,46 @@ def _a0_cands(tx: dict, prior_shares: set[float], prior_prices: set[float]) -> t 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: - acc_matched_ns.add(share_cands[0]) - pending_reclassifications.append((share_cands[0], tx)) + 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: - acc_matched_ns.add(already_reclass[0]) - pending_reclassifications.append((already_reclass[0], tx)) + 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: - acc_matched_ns.add(base_cands[0]) - pending_reclassifications.append((base_cands[0], tx)) + reserve_target(base_cands[0], tx) continue already_reclass = [i for i in base_cands if ledger[i]["reclassified"]] if len(already_reclass) == 1: - acc_matched_ns.add(already_reclass[0]) - pending_reclassifications.append((already_reclass[0], tx)) + 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 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) known_non_sells.extend(acc_added_non_sells) return acc_matched_ns, pending_reclassifications @@ -1473,25 +1575,9 @@ def _heuristic_share_cands(tx: dict) -> tuple[list[int], bool]: if not progressed: break - # Sub-pass 4: remaining unlinked unannotated sell rows are confirmed as new sales ONLY on - # deterministic pigeonhole proof (every prior entry on that base signature was reserved in this - # accession). Unattributable rows stay conservative and uncertain without guessing from remarks. + # 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 in resolved_heur: - continue - cands, is_ambig = _heuristic_share_cands(tx) - if cands or is_ambig: - mark_uncertain(tx) - continue - b = _f4_base_sig(tx) - pool, pool_unlinked = _f4_scoped_pool(ledger, tx, prior_len) - if pool_unlinked: - mark_uncertain(tx) - continue - same_base_pool = [i for i in pool if _f4_base_sig(ledger[i]["tx"]) == b] - if same_base_pool and all(i in acc_matched_sell for i in same_base_pool): - acc_new_sales.append(tx) - else: + if ridx not in resolved_heur: mark_uncertain(tx) # Merge newly disclosed sales from this accession idempotently against existing 4/A-added ledger entries. @@ -1568,7 +1654,7 @@ def _mark_uncertain(tx: dict) -> None: _mark_uncertain(tx) for _acc, acc_rows in sorted_acc_items: - intents, ambig_flags, row_texts = _f4_resolve_accession_intents(acc_rows) + intents, ambig_flags, row_texts = _f4_resolve_accession_intents(acc_rows, ledger) acc_sells: list[tuple[dict, tuple[bool, bool], bool, str]] = [] acc_non_sells: list[tuple[dict, tuple[bool, bool], bool, str]] = [] for tx, intent, is_ambig, rtext in zip(acc_rows, intents, ambig_flags, row_texts): @@ -1588,14 +1674,14 @@ def _mark_uncertain(tx: dict) -> None: _f4_mark_reclassified(ledger, target, gtx) active_sales = [entry for entry in ledger if not entry["reclassified"]] - recent_active_sales: list[tuple[dict, bool]] = [] + 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: - _mark_uncertain(entry["tx"]) - recent_active_sales.append((entry, False)) + has_undated_sale = True elif td >= tx_cutoff: - recent_active_sales.append((entry, True)) + recent_active_sales.append(entry) dedup_sales = len(recent_active_sales) unaffected_orig_sells = ( @@ -1603,13 +1689,21 @@ def _mark_uncertain(tx: dict) -> None: if unaligned_global else sum( 1 - for entry, has_valid_date in recent_active_sales - if has_valid_date and entry["from_orig"] and _f4_owner_key(entry["tx"]) not in affected_owners + 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(affected_owners or unaligned_global) + 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( @@ -1750,10 +1844,6 @@ def supplied(key): else: if extra.get("truncated"): warnings.append("SEC Form 4 filings were truncated at top 10; insider sales coverage is incomplete") - if extra.get("count_uncertain"): - warnings.append( - "SEC Form 4/A amendments include unlinked or ambiguous revisions; insider sale count is uncertain" - ) warnings.extend(extra.get("warnings") or []) checks["news_risks"] = {k: v for k, v in news.items() if k != "flags"} From b1694a83de0dbf4fd369fbccdf6d9faf11d320e7 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 16:20:34 +0800 Subject: [PATCH 23/37] fix(risk): corroborate SEC sale and gift amendment evidence --- tests/test_risk_screening.py | 175 +++++++++++++++++++++++++++++++ tools/risk_screening.py | 194 +++++++++++++++++++++++++++-------- 2 files changed, 329 insertions(+), 40 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 5ff2845..91edf2a 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -2681,6 +2681,181 @@ def test_form4_unlinked_date_correction_does_not_create_a_sale(monkeypatch): 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), + ("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 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 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(monkeypatch, [*originals, linked]) + assert result["checks"]["insider_trades"]["sales_90d"] == expected + + +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) + 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 + + 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) diff --git a/tools/risk_screening.py b/tools/risk_screening.py index c036984..fd87c29 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -373,13 +373,14 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: 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_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[1-9]\d{{0,3}}|an?|the|{'|'.join(_F4_COUNT_WORDS[1:])})\s+" + rf"(?P{_F4_SALE_COUNT})\s+" rf"(?:(?P{_F4_OMITTED}|additional)\s+)?(?Psale(?: transactions?|s)?|transactions?)" r"(?:\s+of (?:[\d,.]+\s+)?(?:(?:common|ordinary|class [a-z])\s+)?shares?)?" rf"(?:\s+(?P(?:(?:that\s+)?(?:was|were)\s+)?{_F4_OMITTED})" @@ -387,6 +388,37 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: 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_ROW_SALE_DESCRIPTION = rf"(?:(?:first|second|third|fourth|fifth|private|open-market)\s+)?{_F4_ROW_SALE}" +_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_REPORT_CONTEXT = ( + r"(?:\s+from\s+(?: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})?)?" + 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_RE = re.compile( + rf"(?:{_F4_ROW_SALE_SUBJECT}\s+(?:was|is)\s+(?:not|never)\s+(?:{_F4_OMITTED}|newly reported)|" + 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_REPORT_CONTEXT}" + r"(?:\s+in\s+(?:this|the)\s+(?:amendment|form 4(?:/a)?|report))?", + 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}|" @@ -415,7 +447,7 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: re.IGNORECASE, ) _F4_SALE_REFERENCE = ( - r"(?:(?:the|a)\s+)?(?:(?:previously reported|original)\s+)?(?:[\d,.]+-share\s+)?sale" + r"(?:(?:the|a)\s+)?(?:(?:previously (?:misreported|reported(?: in error)?)|original)\s+)?(?:[\d,.]+-share\s+)?sale" r"(?:\s+of\s+[\d,.]+\s+shares?)?(?:\s+at\s+\$?\s*[\d,.]+)?" ) _F4_CURRENT_CHANGE = r"(?:this amendment\s+)?(?:corrects?|reclassif(?:ies|y)|changes?)" @@ -424,7 +456,20 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: rf"{_F4_SALE_REFERENCE}|{_F4_SALE_REFERENCE}\s+" r"(?:was previously reported in error and\s+)?(?:is|should be)\s+reclassified)" r"\s+(?:to|as)\s+(?:a\s+)?(?:(?:bona fide|[\d,.]+-share)\s+)?(?:gift|non-sale|transfer|disposition)\b" - rf"|^{_F4_CURRENT_CHANGE}\s+(?:the\s+)?(?:transaction\s+)?code\s+(?:from\s+)?s\s+to\s+(?!s\b)[a-z]\b", + rf"|^{_F4_CURRENT_CHANGE}\s+(?:the\s+)?(?:gift\s+)?(?:transaction\s+)?code\s+(?:from\s+)?" + r"[\"']?s[\"']?(?:\s*\(sale\))?\s+to\s+[\"']?(?!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_RESTORE_SELL_RE = re.compile( @@ -623,7 +668,26 @@ def _f4_row_scoped_text(tx: dict) -> str: elif isinstance(footnotes, str) and footnotes: row_parts.append(footnotes) row_parts.extend(str(tx[k]) for k in ("amendment_reason", "note") if tx.get(k)) - return " ".join(row_parts) + return ". ".join(part.strip().rstrip(".") for part in row_parts if part.strip()) + + +def _f4_statements(text: str) -> list[str]: + return [part.strip() for part in _F4_SENTENCE_BOUNDARY_RE.split(text) if part.strip()] + + +def _f4_sale_addition_declaration(text: str) -> tuple[int, bool] | 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) + return declared, subject.startswith("sale") def _f4_resolve_accession_intents( @@ -639,13 +703,25 @@ def _f4_resolve_accession_intents( prior_disclosures = [ any(not match["negated"] for match in _F4_PRIOR_DISCLOSURE_RE.finditer(text)) for text in row_texts ] - row_intents = [ - ( - bool(_F4_ADDITION_RE.search(rt)) and not (_f4_is_sell(tx) and prior), - bool(_F4_CORRECTION_RE.search(rt)), - ) - for tx, rt, prior in zip(acc_rows, row_texts, prior_disclosures) - ] + row_intents = [] + row_denies_addition = False + for tx, rt, prior in zip(acc_rows, row_texts, prior_disclosures): + if _f4_is_sell(tx): + sentences = _f4_statements(rt) + denial = any(_F4_ROW_SALE_DENIAL_RE.fullmatch(sentence) for sentence in sentences) + row_denies_addition |= denial + addition = ( + not prior + and not denial + and any( + _F4_ROW_SALE_ADDITION_RE.fullmatch(sentence) + or ((declaration := _f4_sale_addition_declaration(sentence)) is not None and declaration[0] == 1) + for sentence in sentences + ) + ) + else: + addition = bool(_F4_ADDITION_RE.search(rt)) + row_intents.append((addition, bool(_F4_CORRECTION_RE.search(rt)))) ambiguous = [False] * len(acc_rows) seen_remarks: set[str] = set() remarks_parts: list[str] = [] @@ -660,37 +736,30 @@ def _f4_resolve_accession_intents( # shortcut: promote explicit English declarations, and expand for verified filing wording. statements = [] mixed_remarks = False - for part in _F4_SENTENCE_BOUNDARY_RE.split(rem_text): - sentence = part.strip() - match = _F4_COUNTED_SALE_ADDITION_RE.fullmatch(sentence) - if match and (match["modifier"] or match["clause"] or match["verb"].lower().startswith("add")): - statements.append(match) - elif sentence and (not _F4_REMARKS_METADATA_RE.fullmatch(sentence) or _F4_OTHER_CHANGE_RE.search(sentence)): + for sentence in _f4_statements(rem_text): + declaration = _f4_sale_addition_declaration(sentence) + if declaration is not None: + statements.append(declaration) + elif not _F4_REMARKS_METADATA_RE.fullmatch(sentence) or _F4_OTHER_CHANGE_RE.search(sentence): mixed_remarks = True - counted = statements[0] if len(statements) == 1 else None - declared_additions = 0 - if counted: - count = counted["count"].lower() - if count.isdigit(): - declared_additions = int(count) - elif count in {"a", "an", "the"}: - declared_additions = int(not counted["object"].lower().endswith("s")) - else: - declared_additions = _F4_COUNT_WORDS.index(count) + declared_additions, sales_declared = statements[0] if len(statements) == 1 else (0, False) rem_add = bool(statements) or bool(_F4_ADDITION_RE.search(rem_text)) rem_corr = bool(_F4_CORRECTION_RE.search(rem_text)) if not (rem_add or rem_corr): return row_intents, ambiguous, row_texts if ( - counted - and len(remarks_parts) == 1 + len(remarks_parts) == 1 and declared_additions == len(acc_rows) - and (len(acc_rows) == 1 or counted["object"].lower().startswith("sale")) + and (len(acc_rows) == 1 or sales_declared) and not mixed_remarks 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): @@ -713,7 +782,7 @@ def _f4_resolve_accession_intents( ambiguous[0] = True return row_intents, ambiguous, row_texts row_intents[0] = (unclaimed_add, unclaimed_corr) - row_texts[0] = f"{row_texts[0]} {rem_text}".strip() + row_texts[0] = ". ".join(filter(None, (row_texts[0], rem_text))) return row_intents, ambiguous, row_texts for i in unattributed or range(len(acc_rows)): ambiguous[i] = True @@ -753,15 +822,12 @@ def _f4_entry_has_revision( exact_price: object = _UNSET, include_gift_revisions: bool = False, gift_filing_date: str | None = None, + gift_only: bool = False, ) -> bool: - if include_gift_revisions: - if gift_filing_date: - matching_gf = [rev[1:] for rev in entry["gift_revisions"] if rev[0] == gift_filing_date] - revs = matching_gf if matching_gf else entry["revisions"] + [rev[1:] for rev in entry["gift_revisions"]] - else: - revs = entry["revisions"] + [rev[1:] for rev in entry["gift_revisions"]] - else: - revs = entry["revisions"] + 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 @@ -928,6 +994,7 @@ def _f4_reconcile_non_sells( acc_orig_ns_matched: set[int] = set() acc_matched_ns: set[int] = set() pending_reclassifications: list[tuple[int, dict]] = [] + original_gift_claims: dict[int, list[dict]] = {} revision_claims: dict[int, list[dict]] = {} prior_gift_claims: set[int] = set() @@ -940,7 +1007,9 @@ def reserve_target(target: int, tx: dict) -> None: 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 _F4_EXPLICIT_SALE_RECLASS_RE.match(text.strip()): + 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 @@ -951,8 +1020,48 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: code = _f4_tx_code(tx) shares = tx.get("shares") orig_date = str(tx.get("original_filing_date") or "").strip() + filing_date = str(tx.get("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) + gift_corrections = [sentence for sentence in sentences if _F4_GIFT_CORRECTION_RE.search(sentence)] + if gift_corrections and not any(_F4_EXPLICIT_SALE_RECLASS_RE.match(sentence) for sentence in sentences): + # 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")) + original_gifts = [ + i + for i, orig_ns in enumerate(known_non_sells) + if has_identity + and _f4_base_sig(orig_ns) == base + and _f4_tx_code(orig_ns) == "G" + and (not orig_date or not orig_ns.get("filing_date") or orig_ns.get("filing_date") == orig_date) + and (not filing_date or str(orig_ns.get("filing_date") or "") <= filing_date) + and (not prior_shares or _f4_matches_num_set(orig_ns.get("shares"), prior_shares)) + and (not prior_prices or _f4_matches_num_set(orig_ns.get("price"), prior_prices)) + ] + gift_candidates = [ + i + for i in pool + if has_identity + and 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=orig_date or None, + gift_only=True, + ) + ] + if len(original_gifts) == 1 and not gift_candidates: + original_gift_claims.setdefault(original_gifts[0], []).append(tx) + elif not original_gifts and len(gift_candidates) == 1: + reserve_target(gift_candidates[0], tx) + else: + mark_uncertain(tx) + continue ns_idx = next( ( i @@ -988,6 +1097,7 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: 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. @@ -1161,6 +1271,10 @@ def _a0_cands(tx: dict, text: str, prior_shares: set[float], prior_prices: set[f mark_uncertain(tx) # An existing gift can attract claims at different match strengths within the same filing. + for claimants in original_gift_claims.values(): + if len(claimants) > 1: + for tx in claimants: + mark_uncertain(tx) for target, claimants in revision_claims.items(): acc_matched_ns.add(target) if len(claimants) == 1: From b0b0f78d0e1913dbc44121fdb2d28c7eb64d161d Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 17:41:38 +0800 Subject: [PATCH 24/37] fix(risk): retain SEC amendment evidence and gift history --- tests/test_risk_screening.py | 215 +++++++++++++++++++++++++--- tools/risk_screening.py | 262 +++++++++++++++++++++++------------ 2 files changed, 373 insertions(+), 104 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 91edf2a..74672c9 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -2554,7 +2554,7 @@ def test_form4_accession_explicitly_adds_all_its_sale_rows(monkeypatch): assert result["checks"]["insider_trades"]["count_uncertain"] is True -def test_form4_screen_cli_requires_affirmative_matching_addition_count(monkeypatch): +def _screen_form4_cli(monkeypatch, rows): import json import subprocess import sys @@ -2571,6 +2571,25 @@ def test_form4_screen_cli_requires_affirmative_matching_addition_count(monkeypat 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, @@ -2607,22 +2626,8 @@ def test_form4_screen_cli_requires_affirmative_matching_addition_count(monkeypat ) for row in originals ] - fixture = { - "stock_data.py": {"pe": 25, "pb": 5}, - "technical.py": {"signal_score": 60, "buy_signal": "HOLD"}, - "sec_edgar.py": {"transactions": originals + amendments, "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 - assert json.loads(cli.stdout)["checks"]["insider_trades"]["sales_90d"] == expected + 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): @@ -2731,14 +2736,22 @@ def test_form4_linked_footnote_requires_affirmative_sale_addition(monkeypatch): 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( @@ -2746,8 +2759,85 @@ def test_form4_linked_footnote_requires_affirmative_sale_addition(monkeypatch): footnotes={"F1": first_note, "F2": "This sale was omitted from the original Form 4"}, footnote_refs={"transactionDate/value": ["F1", "F2"]}, ) - result = _screen_form4(monkeypatch, [*originals, linked]) + 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_gift_quantity_correction_preserves_unrelated_sale_and_veto(monkeypatch): @@ -2848,7 +2938,7 @@ def test_form4_gift_quantity_correction_preserves_unrelated_sale_and_veto(monkey assert result["veto_buy"] is (not uncertain) original_gifts = [native_gift, dict(native_gift, shares=120)] - broad = dict(correction, shares=180) + 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]) @@ -2856,6 +2946,93 @@ def test_form4_gift_quantity_correction_preserves_unrelated_sale_and_veto(monkey assert result["checks"]["insider_trades"]["count_uncertain"] 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_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_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) diff --git a/tools/risk_screening.py b/tools/risk_screening.py index fd87c29..bf9005b 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -7,6 +7,7 @@ import os import re import sys +from collections import Counter from concurrent.futures import Future, ThreadPoolExecutor from datetime import date, datetime, timedelta, timezone @@ -411,12 +412,19 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: 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_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_REPORT_CONTEXT}" - r"(?:\s+in\s+(?:this|the)\s+(?:amendment|form 4(?:/a)?|report))?", + 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|$)|[!?;。!?;])+") @@ -659,18 +667,6 @@ def _f4_extract_ref_ids(refs) -> list[str]: return out -def _f4_row_scoped_text(tx: dict) -> str: - footnotes = tx.get("footnotes") - ref_ids = _f4_extract_ref_ids(tx.get("footnote_refs")) - row_parts: list[str] = [] - if isinstance(footnotes, dict) and footnotes and ref_ids: - row_parts.extend(str(footnotes[fid]) for fid in ref_ids if footnotes.get(fid)) - elif isinstance(footnotes, str) and footnotes: - row_parts.append(footnotes) - row_parts.extend(str(tx[k]) for k in ("amendment_reason", "note") if tx.get(k)) - return ". ".join(part.strip().rstrip(".") for part in row_parts if part.strip()) - - def _f4_statements(text: str) -> list[str]: return [part.strip() for part in _F4_SENTENCE_BOUNDARY_RE.split(text) if part.strip()] @@ -690,16 +686,48 @@ def _f4_sale_addition_declaration(text: str) -> tuple[int, bool] | None: return declared, subject.startswith("sale") +def _f4_accession_note_texts(acc_rows: list[dict]) -> tuple[list[str], list[str]]: + row_refs = [_f4_extract_ref_ids(tx.get("footnote_refs")) for tx in acc_rows] + ref_counts = Counter(ref_id for refs in row_refs for ref_id in refs) + shared_additions: dict[tuple[str, str], str] = {} + row_texts = [] + for tx, refs in zip(acc_rows, row_refs): + row_parts = [] + footnotes = tx.get("footnotes") + if isinstance(footnotes, dict): + for ref_id in refs: + if not footnotes.get(ref_id): + continue + note = str(footnotes[ref_id]) + if ref_counts[ref_id] == 1 or not _f4_is_sell(tx): + row_parts.append(note) + continue + # A shared note's addition statements cannot identify which row was added. + for sentence in _f4_statements(note): + if ( + _F4_ROW_SALE_ADDITION_RE.fullmatch(sentence) + or _f4_sale_addition_declaration(sentence) is not None + ): + shared_additions[ref_id, sentence.casefold()] = sentence + else: + row_parts.append(sentence) + elif isinstance(footnotes, str) and footnotes: + row_parts.append(footnotes) + row_parts.extend(str(tx[key]) for key in ("amendment_reason", "note") if tx.get(key)) + row_texts.append(". ".join(part.strip().rstrip(".") for part in row_parts if part.strip())) + return row_texts, list(shared_additions.values()) + + def _f4_resolve_accession_intents( acc_rows: list[dict], ledger: list[dict], ) -> tuple[list[tuple[bool, bool]], list[bool], list[str]]: """Resolve per-row (is_add, is_corr) strictly from row-scoped evidence. - Use filing remarks for a single unambiguous row or an explicit sale addition count + Use filing evidence for a single unambiguous row or an explicit sale addition count covering every row. Leave unattributed rows in mixed filings uncertain. """ - row_texts = [_f4_row_scoped_text(tx) for tx in acc_rows] + row_texts, shared_additions = _f4_accession_note_texts(acc_rows) prior_disclosures = [ any(not match["negated"] for match in _F4_PRIOR_DISCLOSURE_RE.finditer(text)) for text in row_texts ] @@ -708,7 +736,7 @@ def _f4_resolve_accession_intents( for tx, rt, prior in zip(acc_rows, row_texts, prior_disclosures): if _f4_is_sell(tx): sentences = _f4_statements(rt) - denial = any(_F4_ROW_SALE_DENIAL_RE.fullmatch(sentence) for sentence in sentences) + denial = any(_F4_ROW_SALE_DENIAL_RE.match(sentence) for sentence in sentences) row_denies_addition |= denial addition = ( not prior @@ -730,28 +758,35 @@ def _f4_resolve_accession_intents( if rem and rem not in seen_remarks: seen_remarks.add(rem) remarks_parts.append(rem) - if not remarks_parts: + if not (remarks_parts or shared_additions): return row_intents, ambiguous, row_texts rem_text = " ".join(remarks_parts) # shortcut: promote explicit English declarations, and expand for verified filing wording. - statements = [] - mixed_remarks = False + shared_counts = Counter( + declaration + for sentence in shared_additions + if (declaration := _f4_sale_addition_declaration(sentence)) is not None + ) + remarks_counts = Counter() + mixed_filing_evidence = len(shared_additions) > shared_counts.total() for sentence in _f4_statements(rem_text): declaration = _f4_sale_addition_declaration(sentence) if declaration is not None: - statements.append(declaration) + remarks_counts[declaration] += 1 elif not _F4_REMARKS_METADATA_RE.fullmatch(sentence) or _F4_OTHER_CHANGE_RE.search(sentence): - mixed_remarks = True - declared_additions, sales_declared = statements[0] if len(statements) == 1 else (0, False) - rem_add = bool(statements) or bool(_F4_ADDITION_RE.search(rem_text)) + mixed_filing_evidence = True + # Merge equivalent counts across sources while retaining separate declarations within either source. + declarations = shared_counts | remarks_counts + declared_additions, sales_declared = next(iter(declarations)) if declarations.total() == 1 else (0, False) + filing_add = bool(shared_additions or declarations) or bool(_F4_ADDITION_RE.search(rem_text)) rem_corr = bool(_F4_CORRECTION_RE.search(rem_text)) - if not (rem_add or rem_corr): + if not (filing_add or rem_corr): return row_intents, ambiguous, row_texts if ( - len(remarks_parts) == 1 + len(remarks_parts) <= 1 and declared_additions == len(acc_rows) and (len(acc_rows) == 1 or sales_declared) - and not mixed_remarks + and not mixed_filing_evidence and not rem_corr and not row_denies_addition and not any(prior_disclosures) @@ -771,8 +806,10 @@ def _f4_resolve_accession_intents( break else: return [(True, False)] * len(acc_rows), ambiguous, row_texts - claimed_additions = sum(addition for addition, _ in row_intents) - unclaimed_add = rem_add and claimed_additions < (declared_additions or 1) + claimed_additions = sum( + addition for tx, (addition, _) in zip(acc_rows, row_intents) if not shared_additions or _f4_is_sell(tx) + ) + unclaimed_add = filing_add and claimed_additions < (declared_additions or 1) 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 @@ -803,9 +840,7 @@ def _f4_make_ledger_entry(tx: dict, *, from_orig: bool) -> dict: "gift_revisions": [], "shares_set": {shares} if shares is not None else set(), "filing_dates": filing_dates, - "orig_acceptance_ts": _f4_normalize_acceptance_ts( - tx.get("acceptance_datetime") or tx.get("acceptanceDateTime") - ), + "orig_acceptance_ts": _f4_acceptance_ts(tx), "orig_accession": str(tx.get("accession") or "").strip() or None, "from_orig": from_orig, "reclassified": False, @@ -874,6 +909,18 @@ def _f4_update_entry(ledger: list[dict], idx: int, tx: dict, *, restore_if_recla 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, @@ -891,17 +938,11 @@ def _f4_scoped_pool( revision history) so distinct transactions sharing a filing-date chain remain linkable. """ amend_fdate = str(tx.get("filing_date") or "").strip() - amend_ts = _f4_normalize_acceptance_ts(tx.get("acceptance_datetime") or tx.get("acceptanceDateTime")) + amend_ts = _f4_acceptance_ts(tx) def _filed_on_or_before(entry: dict) -> bool: - if not amend_fdate or not entry["filing_dates"]: - return True - earliest = min(entry["filing_dates"]) - if earliest > amend_fdate: - return False - if earliest == amend_fdate and amend_ts and entry["orig_acceptance_ts"]: - return entry["orig_acceptance_ts"] <= amend_ts - return True + 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)): @@ -948,14 +989,7 @@ def _f4_sort_amendment_accessions(all_amend: list[dict]) -> tuple[list[tuple[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_normalize_acceptance_ts(r.get("acceptance_datetime") or r.get("acceptanceDateTime"))) - ), - default="", - ) + 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) @@ -984,9 +1018,39 @@ def _same_submitter_prefix(acc_a: str, acc_b: str) -> bool: return sorted_items, uncertain_txs +def _f4_non_sell_revisions(history: list[dict], linked_date: str) -> list[dict]: + """An original filing link identifies the chain, while a revision link identifies its filed rows.""" + original_date = str(history[0].get("filing_date") or "").strip() + if not linked_date or not original_date or linked_date == original_date: + return history + return [row for row in history if str(row.get("filing_date") or "").strip() == linked_date] + + +def _f4_prior_native_gifts( + non_sell_histories: list[list[dict]], tx: dict, linked_date: str +) -> 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) + if _f4_filed_on_or_before( + str(rev.get("filing_date") or "").strip(), _f4_acceptance_ts(rev), filing_date, acceptance_ts + ) + ] + if revisions: + gifts.append((i, revisions)) + return gifts + + def _f4_reconcile_non_sells( ledger: list[dict], - known_non_sells: list[dict], + non_sell_histories: list[list[dict]], acc_non_sells: list[tuple[dict, tuple[bool, bool], bool, str]], prior_len: int, mark_uncertain, @@ -994,7 +1058,7 @@ def _f4_reconcile_non_sells( acc_orig_ns_matched: set[int] = set() acc_matched_ns: set[int] = set() pending_reclassifications: list[tuple[int, dict]] = [] - original_gift_claims: dict[int, list[dict]] = {} + native_gift_claims: dict[int, list[dict]] = {} revision_claims: dict[int, list[dict]] = {} prior_gift_claims: set[int] = set() @@ -1015,13 +1079,13 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: acc_added_non_sells: list[dict] = [] ns_candidates: list[tuple[dict, bool, bool, str]] = [] - for tx, (is_add, is_corr), _is_ambig, rtext in acc_non_sells: + for tx, (is_add, is_corr), is_ambig, rtext 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() - filing_date = str(tx.get("filing_date") or "").strip() has_identity = base[0] != ("",) and bool(base[1]) and shares is not None + is_explicit_add = is_add and not is_corr pool, pool_unlinked = _f4_scoped_pool(ledger, tx, prior_len) sentences = _f4_statements(rtext) gift_corrections = [sentence for sentence in sentences if _F4_GIFT_CORRECTION_RE.search(sentence)] @@ -1030,16 +1094,15 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: 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")) - original_gifts = [ + prior_native_gifts = _f4_prior_native_gifts(non_sell_histories, tx, orig_date) if has_identity else [] + native_gifts = [ i - for i, orig_ns in enumerate(known_non_sells) - if has_identity - and _f4_base_sig(orig_ns) == base - and _f4_tx_code(orig_ns) == "G" - and (not orig_date or not orig_ns.get("filing_date") or orig_ns.get("filing_date") == orig_date) - and (not filing_date or str(orig_ns.get("filing_date") or "") <= filing_date) - and (not prior_shares or _f4_matches_num_set(orig_ns.get("shares"), prior_shares)) - and (not prior_prices or _f4_matches_num_set(orig_ns.get("price"), prior_prices)) + for i, revisions in prior_native_gifts + if any( + (not prior_shares or _f4_matches_num_set(rev.get("shares"), prior_shares)) + and (not prior_prices or _f4_matches_num_set(rev.get("price"), prior_prices)) + for rev in revisions + ) ] gift_candidates = [ i @@ -1055,42 +1118,69 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: gift_only=True, ) ] - if len(original_gifts) == 1 and not gift_candidates: - original_gift_claims.setdefault(original_gifts[0], []).append(tx) - elif not original_gifts and len(gift_candidates) == 1: + if len(native_gifts) == 1 and not gift_candidates: + native_gift_claims.setdefault(native_gifts[0], []).append(tx) + elif not native_gifts and len(gift_candidates) == 1: reserve_target(gift_candidates[0], tx) else: mark_uncertain(tx) continue - ns_idx = next( - ( + is_sale_conversion = 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, orig_ns in enumerate(known_non_sells) - if i not in acc_orig_ns_matched - and _f4_base_sig(orig_ns) == base - and _f4_tx_code(orig_ns) == code - and (shares is None or orig_ns.get("shares") == shares) - and (not orig_date or not orig_ns.get("filing_date") or orig_ns.get("filing_date") == orig_date) - ), - None, - ) + 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 = [] + 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) + 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 known_non_sells[ns_idx].get("price") != tx.get("price") + 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 (is_corr and has_ledger_sell and bool(_F4_SALE_TO_NONSELL_RE.search(rtext))): + 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_add and not is_corr: + if is_explicit_add: acc_added_non_sells.append(tx) continue if pool_unlinked: @@ -1271,8 +1361,10 @@ def _a0_cands(tx: dict, text: str, prior_shares: set[float], prior_prices: set[f mark_uncertain(tx) # An existing gift can attract claims at different match strengths within the same filing. - for claimants in original_gift_claims.values(): - if len(claimants) > 1: + 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(): @@ -1282,7 +1374,7 @@ def _a0_cands(tx: dict, text: str, prior_shares: set[float], prior_prices: set[f else: for tx in claimants: mark_uncertain(tx) - known_non_sells.extend(acc_added_non_sells) + non_sell_histories.extend([tx] for tx in acc_added_non_sells) return acc_matched_ns, pending_reclassifications @@ -1751,7 +1843,7 @@ def _is_amendment_advisory(warning: str) -> bool: ) ledger: list[dict] = [_f4_make_ledger_entry(tx, from_orig=True) for tx in all_orig if _f4_is_sell(tx)] - known_non_sells: list[dict] = [tx for tx in all_orig if not _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 @@ -1781,7 +1873,7 @@ def _mark_uncertain(tx: dict) -> None: prior_len = len(ledger) acc_matched_ns, pending_reclassifications = _f4_reconcile_non_sells( - ledger, known_non_sells, acc_non_sells, prior_len, _mark_uncertain + 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: From d7211b824765bca5f0a70fb6c9ef1e0154cc40a9 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 19:36:12 +0800 Subject: [PATCH 25/37] fix(risk): scope Form 4 amendment evidence before matching --- tests/test_risk_screening.py | 102 ++++++++++++++++++ tools/risk_screening.py | 199 +++++++++++++++++++++++++++-------- 2 files changed, 258 insertions(+), 43 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 74672c9..a78d2f8 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -2840,6 +2840,67 @@ def test_form4_shared_omitted_gifts_do_not_change_sale_certainty(monkeypatch): assert result["veto_buy"] is True +def test_form4_shared_conversion_note_is_scoped_to_the_gift(monkeypatch): + from itertools import permutations + + converted = _form4_sale(200, transaction_date="2026-11-18") + restated = _form4_sale(100, price=30) + sales = [converted, restated, *(_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", + "footnotes": {"F1": "Corrects the sale of 200 shares at $20 to a gift."}, + "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]) + 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_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_shares, separate_evidence, expected, uncertain in ( + (100, False, 2, False), + (200, False, 2, True), + (200, True, 3, False), + ): + footnotes = { + "F1": f"This amendment adds one omitted sale of {shared_shares} shares.", + "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 + + 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))] @@ -2944,6 +3005,12 @@ def test_form4_gift_quantity_correction_preserves_unrelated_sale_and_veto(monkey 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): @@ -2972,6 +3039,41 @@ def test_form4_native_gift_revision_ignores_later_same_day_filings(monkeypatch): 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) diff --git a/tools/risk_screening.py b/tools/risk_screening.py index bf9005b..88ae4dc 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -10,6 +10,7 @@ from collections import Counter from concurrent.futures import Future, ThreadPoolExecutor from datetime import date, datetime, timedelta, timezone +from typing import NamedTuple sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) @@ -383,9 +384,9 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: 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+)?(?Psale(?: transactions?|s)?|transactions?)" - r"(?:\s+of (?:[\d,.]+\s+)?(?:(?:common|ordinary|class [a-z])\s+)?shares?)?" + r"(?:\s+of (?:(?P\d+(?:,\d{3})*(?:\.\d+)?)\s+)?(?:(?Pcommon|ordinary|class [a-z])\s+)?shares?)?" rf"(?:\s+(?P(?:(?:that\s+)?(?:was|were)\s+)?{_F4_OMITTED})" - rf"(?:\s+from the (?:original )?(?:form 4|filing)(?: filed on {_F4_REMARKS_DATE})?)?)?" + 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, ) @@ -463,9 +464,10 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: rf"^(?:{_F4_CURRENT_CHANGE}\s+" rf"{_F4_SALE_REFERENCE}|{_F4_SALE_REFERENCE}\s+" r"(?:was previously reported in error and\s+)?(?:is|should be)\s+reclassified)" - r"\s+(?:to|as)\s+(?:a\s+)?(?:(?:bona fide|[\d,.]+-share)\s+)?(?:gift|non-sale|transfer|disposition)\b" + r"\s+(?:to|as)\s+(?:a\s+)?(?:(?:bona fide|(?P[\d,.]+)-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+[\"']?(?!s\b)[a-z]\b", + r"[\"']?s[\"']?(?:\s*\(sale\))?\s+to\s+[\"']?(?P(?!s\b)[a-z])\b", re.IGNORECASE, ) _F4_GIFT_REFERENCE = ( @@ -671,7 +673,15 @@ def _f4_statements(text: str) -> list[str]: return [part.strip() for part in _F4_SENTENCE_BOUNDARY_RE.split(text) if part.strip()] -def _f4_sale_addition_declaration(text: str) -> tuple[int, bool] | None: +class _F4AdditionDeclaration(NamedTuple): + count: int + sales_only: bool + shares: float | None + share_class: str + original_date: str + + +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 @@ -683,14 +693,86 @@ def _f4_sale_addition_declaration(text: str) -> tuple[int, bool] | None: declared = int(not subject.endswith("s")) else: declared = _F4_COUNT_WORDS.index(count) - return declared, subject.startswith("sale") + shares = _safe_float((match["shares"] or "").replace(",", "")) + return _F4AdditionDeclaration( + declared, + subject.startswith("sale"), + shares, + (match["share_class"] or "").casefold(), + (match["original_date"] or "").replace(",", "").casefold(), + ) + + +def _f4_filing_additions_covered(declarations: Counter[_F4AdditionDeclaration], claimed: list[dict]) -> bool: + if not declarations: + return bool(claimed) + remaining = sorted(claimed, key=_f4_is_sell) + # Satisfy specific singular declarations first. Use non-sales first for generic declarations. + ordered = sorted(declarations, key=lambda d: (d.count != 1 or d.shares is None, not d.sales_only)) + for declaration in ordered: + if not declaration.count: + return False + quantity = declaration.shares if declaration.count == 1 else None + count = declaration.count * declarations[declaration] + matches = [ + i + for i, tx in enumerate(remaining) + if (not declaration.sales_only or _f4_is_sell(tx)) + and (quantity is None or _safe_float(tx.get("shares")) == quantity) + ] + if len(matches) < count: + return False + used = set(matches[:count]) + remaining = [tx for i, tx in enumerate(remaining) if i not in used] + return True + + +def _f4_shared_conversion_targets( + acc_rows: list[dict], refs: list[int], conversion: re.Match[str], ledger: list[dict] +) -> 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 + + # 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) + return matched or candidates -def _f4_accession_note_texts(acc_rows: list[dict]) -> tuple[list[str], list[str]]: +def _f4_accession_note_texts(acc_rows: list[dict], ledger: list[dict]) -> tuple[list[str], list[str], set[int]]: row_refs = [_f4_extract_ref_ids(tx.get("footnote_refs")) for tx in acc_rows] - ref_counts = Counter(ref_id for refs in row_refs for ref_id in refs) + ref_rows: dict[str, list[int]] = {} + for i, refs in enumerate(row_refs): + for ref_id in refs: + ref_rows.setdefault(ref_id, []).append(i) shared_additions: dict[tuple[str, str], str] = {} - row_texts = [] + shared_conversions: dict[tuple[str, str], re.Match[str]] = {} + texts_by_row: list[list[str]] = [] for tx, refs in zip(acc_rows, row_refs): row_parts = [] footnotes = tx.get("footnotes") @@ -699,23 +781,37 @@ def _f4_accession_note_texts(acc_rows: list[dict]) -> tuple[list[str], list[str] if not footnotes.get(ref_id): continue note = str(footnotes[ref_id]) - if ref_counts[ref_id] == 1 or not _f4_is_sell(tx): + if len(ref_rows[ref_id]) == 1: row_parts.append(note) continue - # A shared note's addition statements cannot identify which row was added. for sentence in _f4_statements(note): - if ( + key = (ref_id, sentence.casefold()) + if conversion := _F4_EXPLICIT_SALE_RECLASS_RE.match(sentence): + shared_conversions[key] = conversion + elif _f4_is_sell(tx) and ( _F4_ROW_SALE_ADDITION_RE.fullmatch(sentence) or _f4_sale_addition_declaration(sentence) is not None ): - shared_additions[ref_id, sentence.casefold()] = sentence + shared_additions[key] = sentence else: row_parts.append(sentence) elif isinstance(footnotes, str) and footnotes: row_parts.append(footnotes) row_parts.extend(str(tx[key]) for key in ("amendment_reason", "note") if tx.get(key)) - row_texts.append(". ".join(part.strip().rstrip(".") for part in row_parts if part.strip())) - return row_texts, list(shared_additions.values()) + texts_by_row.append(row_parts) + + unresolved_conversions: set[int] = set() + for (ref_id, _), conversion in shared_conversions.items(): + refs = ref_rows[ref_id] + targets = _f4_shared_conversion_targets(acc_rows, refs, conversion, ledger) + if len(targets) == 1: + texts_by_row[targets[0]].append(conversion.string) + else: + unresolved_conversions.update(targets or refs) + row_texts = [ + ". ".join(part.strip().rstrip(".") for part in row_parts if part.strip()) for row_parts in texts_by_row + ] + return row_texts, list(shared_additions.values()), unresolved_conversions def _f4_resolve_accession_intents( @@ -727,30 +823,37 @@ def _f4_resolve_accession_intents( Use filing evidence for a single unambiguous row or an explicit sale addition count covering every row. Leave unattributed rows in mixed filings uncertain. """ - row_texts, shared_additions = _f4_accession_note_texts(acc_rows) + row_texts, shared_additions, unresolved_conversions = _f4_accession_note_texts(acc_rows, ledger) 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))] row_denies_addition = False - for tx, rt, prior in zip(acc_rows, row_texts, prior_disclosures): + 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 = [ + declaration + for sentence in sentences + if (declaration := _f4_sale_addition_declaration(sentence)) is not None and declaration.count == 1 + ] + quantity = _safe_float(tx.get("shares")) + if any(d.shares is not None and d.shares != quantity for d in singular_declarations): + ambiguous[i] = True addition = ( not prior and not denial - and any( - _F4_ROW_SALE_ADDITION_RE.fullmatch(sentence) - or ((declaration := _f4_sale_addition_declaration(sentence)) is not None and declaration[0] == 1) - for sentence in sentences + and ( + any(_F4_ROW_SALE_ADDITION_RE.fullmatch(sentence) for sentence in sentences) + or any(d.shares is None or d.shares == quantity for d in singular_declarations) ) ) else: addition = bool(_F4_ADDITION_RE.search(rt)) row_intents.append((addition, bool(_F4_CORRECTION_RE.search(rt)))) - ambiguous = [False] * len(acc_rows) seen_remarks: set[str] = set() remarks_parts: list[str] = [] for tx in acc_rows: @@ -775,18 +878,24 @@ def _f4_resolve_accession_intents( remarks_counts[declaration] += 1 elif not _F4_REMARKS_METADATA_RE.fullmatch(sentence) or _F4_OTHER_CHANGE_RE.search(sentence): mixed_filing_evidence = True - # Merge equivalent counts across sources while retaining separate declarations within either source. + # Cross-source copies share a declaration only when their parsed transaction details agree. declarations = shared_counts | remarks_counts - declared_additions, sales_declared = next(iter(declarations)) if declarations.total() == 1 else (0, False) + covering_declaration = next(iter(declarations)) if declarations.total() == 1 else None filing_add = bool(shared_additions or declarations) 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 if ( len(remarks_parts) <= 1 - and declared_additions == len(acc_rows) - and (len(acc_rows) == 1 or sales_declared) + and covering_declaration is not None + and covering_declaration.count == len(acc_rows) + and (len(acc_rows) == 1 or covering_declaration.sales_only) + and ( + covering_declaration.shares is None + or (len(acc_rows) == 1 and covering_declaration.shares == _safe_float(acc_rows[0].get("shares"))) + ) and not mixed_filing_evidence + and not any(ambiguous) and not rem_corr and not row_denies_addition and not any(prior_disclosures) @@ -806,10 +915,12 @@ def _f4_resolve_accession_intents( break else: return [(True, False)] * len(acc_rows), ambiguous, row_texts - claimed_additions = sum( - addition for tx, (addition, _) in zip(acc_rows, row_intents) if not shared_additions or _f4_is_sell(tx) - ) - unclaimed_add = filing_add and claimed_additions < (declared_additions or 1) + claimed_additions = [ + tx + for tx, (addition, correction) in zip(acc_rows, row_intents) + if addition and not correction and (not shared_additions or _f4_is_sell(tx)) + ] + unclaimed_add = filing_add and not _f4_filing_additions_covered(declarations, claimed_additions) 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 @@ -1018,12 +1129,18 @@ def _same_submitter_prefix(acc_a: str, acc_b: str) -> bool: return sorted_items, uncertain_txs -def _f4_non_sell_revisions(history: list[dict], linked_date: str) -> list[dict]: - """An original filing link identifies the chain, while a revision link identifies its filed rows.""" +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() - if not linked_date or not original_date or linked_date == original_date: - return history - return [row for row in history if str(row.get("filing_date") or "").strip() == linked_date] + 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( @@ -1036,13 +1153,7 @@ def _f4_prior_native_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) - if _f4_filed_on_or_before( - str(rev.get("filing_date") or "").strip(), _f4_acceptance_ts(rev), filing_date, acceptance_ts - ) - ] + revisions = _f4_non_sell_revisions(history, linked_date, filing_date, acceptance_ts) if revisions: gifts.append((i, revisions)) return gifts @@ -1152,13 +1263,15 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: 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) + 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: From daf41dcbf9f9810991660f551f0e1308cd28d9f1 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 19:44:06 +0800 Subject: [PATCH 26/37] fix(risk): validate amendment claims against linked rows --- tests/test_risk_screening.py | 171 +++++++++++++++++---- tools/risk_screening.py | 284 +++++++++++++++++++++++------------ 2 files changed, 328 insertions(+), 127 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index a78d2f8..c2d1163 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -2844,28 +2844,45 @@ def test_form4_shared_conversion_note_is_scoped_to_the_gift(monkeypatch): from itertools import permutations converted = _form4_sale(200, transaction_date="2026-11-18") - restated = _form4_sale(100, price=30) - sales = [converted, restated, *(_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", - "footnotes": {"F1": "Corrects the sale of 200 shares at $20 to a gift."}, - "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))), + other_sales = [_form4_sale(n, transaction_date="2026-11-19") for n in range(401, 406)] + for note, restated_fields, competing_price in ( + ("Corrects the sale of 200 shares at $20 to a gift.", {}, None), + ("Corrects the sale of 200 shares to a gift.", {}, None), + ("The 200-share sale should be reclassified to a gift.", {}, None), + ("This amendment is filed to correct the sale of 200 shares at $20 to a gift.", {}, None), + ("The sale of 200 shares at $20 should have been reported as a gift.", {}, None), + ("Corrects the sale of 200 shares at 20 to a gift.", {"shares": 200}, 25), + ( + "Corrects the sale of 200 shares at $20 to a 200-share gift.", + {"transaction_date": converted["transaction_date"]}, + None, + ), ): - for ordered in permutations(amendments): - result = _screen_form4_cli(monkeypatch, [*originals, *ordered]) - assert result["checks"]["insider_trades"]["sales_90d"] == 6 - assert result["checks"]["insider_trades"]["count_uncertain"] is False - assert result["veto_buy"] is True + 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 def test_form4_addition_declarations_keep_transaction_quantity(monkeypatch): @@ -2877,13 +2894,20 @@ def test_form4_addition_declarations_keep_transaction_quantity(monkeypatch): "original_filing_date": "2026-11-21", "remarks": "This amendment reports one omitted sale of 100 shares.", } - for shared_shares, separate_evidence, expected, uncertain in ( - (100, False, 2, False), - (200, False, 2, True), - (200, True, 3, False), + 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": f"This amendment adds one omitted sale of {shared_shares} shares.", + "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.", } @@ -2898,7 +2922,100 @@ def test_form4_addition_declarations_keep_transaction_quantity(monkeypatch): ] result = _screen_form4_cli(monkeypatch, [original, *rows]) assert result["checks"]["insider_trades"]["sales_90d"] == expected - assert result["checks"]["insider_trades"]["count_uncertain"] is uncertain + 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 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 def test_form4_gift_quantity_correction_preserves_unrelated_sale_and_veto(monkeypatch): diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 88ae4dc..938d2d9 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -7,7 +7,6 @@ import os import re import sys -from collections import Counter from concurrent.futures import Future, ThreadPoolExecutor from datetime import date, datetime, timedelta, timezone from typing import NamedTuple @@ -378,13 +377,16 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: _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_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+)?(?Psale(?: transactions?|s)?|transactions?)" - r"(?:\s+of (?:(?P\d+(?:,\d{3})*(?:\.\d+)?)\s+)?(?:(?Pcommon|ordinary|class [a-z])\s+)?shares?)?" + rf"(?:(?P{_F4_OMITTED}|additional)\s+)?(?:(?P{_F4_DECLARED_NUMBER})-share\s+)?" + r"(?Psale(?: transactions?|s)?|transactions?)" + rf"(?:\s+of (?:(?P{_F4_DECLARED_NUMBER})\s+)?(?:(?Pcommon|ordinary|class [a-z])\s+)?shares?)?" + rf"(?:\s+at\s+\$?\s*(?P{_F4_DECLARED_NUMBER}))?" 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))?", @@ -455,15 +457,22 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: r"重分类|改为赠与|误报为卖出|并非卖出)", re.IGNORECASE, ) +_F4_SALE_AMOUNT = r"\d+(?:,\d{3})*(?:\.\d+)?" _F4_SALE_REFERENCE = ( - r"(?:(?:the|a)\s+)?(?:(?:previously (?:misreported|reported(?: in error)?)|original)\s+)?(?:[\d,.]+-share\s+)?sale" - r"(?:\s+of\s+[\d,.]+\s+shares?)?(?:\s+at\s+\$?\s*[\d,.]+)?" + r"(?:(?:the|a)\s+)?(?:(?:previously (?:misreported|reported(?: in error)?)|original)\s+)?" + rf"(?:(?P{_F4_SALE_AMOUNT})-share\s+)?sale" + rf"(?:\s+of\s+(?P{_F4_SALE_AMOUNT})\s+shares?)?" + rf"(?:\s+at\s+\$?\s*(?P{_F4_SALE_AMOUNT}))?" +) +_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_CURRENT_CHANGE = r"(?:this amendment\s+)?(?:corrects?|reclassif(?:ies|y)|changes?)" _F4_EXPLICIT_SALE_RECLASS_RE = re.compile( - rf"^(?:{_F4_CURRENT_CHANGE}\s+" - rf"{_F4_SALE_REFERENCE}|{_F4_SALE_REFERENCE}\s+" - r"(?:was previously reported in error and\s+)?(?:is|should be)\s+reclassified)" + 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 and\s+)?" + r"(?:(?:is|should be)\s+reclassified|should have been reported))" r"\s+(?:to|as)\s+(?:a\s+)?(?:(?:bona fide|(?P[\d,.]+)-share)\s+)?" r"(?Pgift|non-sale|transfer|disposition)\b" rf"|^{_F4_CURRENT_CHANGE}\s+(?:the\s+)?(?:gift\s+)?(?:transaction\s+)?code\s+(?:from\s+)?" @@ -601,7 +610,21 @@ def _f4_correction_sentences(rtext: str) -> str: 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() @@ -622,6 +645,8 @@ def _f4_stated_prior_prices(rtext: str, new_price) -> set[float]: 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)): @@ -677,8 +702,25 @@ class _F4AdditionDeclaration(NamedTuple): count: int sales_only: bool shares: float | None - share_class: str - original_date: str + 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 re.search(rf"\b{self.share_class}\b", str(tx.get("security") or ""), re.IGNORECASE) is not None + ) + and (self.original_date is None or tx.get("original_filing_date") == self.original_date) + ) + + def refines(self, other: "_F4AdditionDeclaration") -> bool: + # Only fill in omitted details when the known details and count agree. + return self[:2] == other[:2] and all(b is None or a == b for a, b in zip(self[2:], other[2:])) def _f4_sale_addition_declaration(text: str) -> _F4AdditionDeclaration | None: @@ -693,37 +735,97 @@ def _f4_sale_addition_declaration(text: str) -> _F4AdditionDeclaration | None: declared = int(not subject.endswith("s")) else: declared = _F4_COUNT_WORDS.index(count) - shares = _safe_float((match["shares"] or "").replace(",", "")) + shares = _safe_float((match["shares"] or match["share_prefix"] or "").replace(",", "")) + price = _safe_float((match["price"] or "").replace(",", "")) + original_date = match["original_date"] + if original_date: + for fmt in ("%B %d %Y", "%b %d %Y"): + try: + original_date = datetime.strptime(original_date.replace(",", ""), fmt).date().isoformat() + break + except ValueError: + continue return _F4AdditionDeclaration( declared, subject.startswith("sale"), shares, - (match["share_class"] or "").casefold(), - (match["original_date"] or "").replace(",", "").casefold(), + price, + match["share_class"].casefold() if match["share_class"] else None, + original_date, ) -def _f4_filing_additions_covered(declarations: Counter[_F4AdditionDeclaration], claimed: list[dict]) -> bool: - if not declarations: - return bool(claimed) - remaining = sorted(claimed, key=_f4_is_sell) - # Satisfy specific singular declarations first. Use non-sales first for generic declarations. - ordered = sorted(declarations, key=lambda d: (d.count != 1 or d.shares is None, not d.sales_only)) - for declaration in ordered: - if not declaration.count: - return False - quantity = declaration.shares if declaration.count == 1 else None - count = declaration.count * declarations[declaration] - matches = [ +_F4AdditionClaim = tuple[_F4AdditionDeclaration | None, set[int]] + + +def _f4_merge_addition_claims( + shared: list[_F4AdditionClaim], remarks: list[_F4AdditionDeclaration], all_rows: set[int] +) -> list[_F4AdditionClaim]: + claims: list[_F4AdditionClaim] = [] + unpaired: list[_F4AdditionClaim] = [] + for declaration, refs in shared: + if declaration in remarks: + remarks.remove(declaration) + claims.append((declaration, refs)) + else: + unpaired.append((declaration, refs)) + # A remarks copy may omit details. Pair it only with a single compatible shared statement. + options = [ + [ i - for i, tx in enumerate(remaining) - if (not declaration.sales_only or _f4_is_sell(tx)) - and (quantity is None or _safe_float(tx.get("shares")) == quantity) + for i, (shared_decl, _) in enumerate(unpaired) + if shared_decl is not None and (shared_decl.refines(declaration) or declaration.refines(shared_decl)) ] - if len(matches) < count: + for declaration in remarks + ] + paired: set[int] = set() + for declaration, candidates in zip(remarks, options): + if len(candidates) == 1 and sum(candidates[0] in others for others in options) == 1: + i = candidates[0] + shared_decl, refs = unpaired[i] + assert shared_decl is not None + claims.append((shared_decl if shared_decl.refines(declaration) else declaration, refs)) + paired.add(i) + else: + claims.append((declaration, all_rows)) + 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]) -> bool: + if not claims: + return bool(additions) + options: list[set[int]] = [] + for declaration, refs in claims: + count = declaration.count if declaration is not None else 1 + eligible = { + i + for i in refs & additions + if (declaration.matches(rows[i]) if declaration is not None else _f4_is_sell(rows[i])) + } + 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 - used = set(matches[:count]) - remaining = [tx for i, tx in enumerate(remaining) if i not in used] return True @@ -764,54 +866,45 @@ def _f4_shared_conversion_targets( return matched or candidates -def _f4_accession_note_texts(acc_rows: list[dict], ledger: list[dict]) -> tuple[list[str], list[str], set[int]]: - row_refs = [_f4_extract_ref_ids(tx.get("footnote_refs")) for tx in acc_rows] - ref_rows: dict[str, list[int]] = {} - for i, refs in enumerate(row_refs): - for ref_id in refs: - ref_rows.setdefault(ref_id, []).append(i) - shared_additions: dict[tuple[str, str], str] = {} - shared_conversions: dict[tuple[str, str], re.Match[str]] = {} - texts_by_row: list[list[str]] = [] - for tx, refs in zip(acc_rows, row_refs): - row_parts = [] +def _f4_accession_note_texts( + acc_rows: list[dict], ledger: list[dict] +) -> tuple[list[str], list[_F4AdditionClaim], set[int]]: + note_rows: dict[tuple[str, str], tuple[str, set[int]]] = {} + texts_by_row: list[list[str]] = [[] for _ in acc_rows] + for i, tx in enumerate(acc_rows): footnotes = tx.get("footnotes") if isinstance(footnotes, dict): - for ref_id in refs: - if not footnotes.get(ref_id): - continue - note = str(footnotes[ref_id]) - if len(ref_rows[ref_id]) == 1: - row_parts.append(note) - continue - for sentence in _f4_statements(note): + 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()) - if conversion := _F4_EXPLICIT_SALE_RECLASS_RE.match(sentence): - shared_conversions[key] = conversion - elif _f4_is_sell(tx) and ( - _F4_ROW_SALE_ADDITION_RE.fullmatch(sentence) - or _f4_sale_addition_declaration(sentence) is not None - ): - shared_additions[key] = sentence - else: - row_parts.append(sentence) + note_rows.setdefault(key, (sentence, set()))[1].add(i) elif isinstance(footnotes, str) and footnotes: - row_parts.append(footnotes) - row_parts.extend(str(tx[key]) for key in ("amendment_reason", "note") if tx.get(key)) - texts_by_row.append(row_parts) + texts_by_row[i].append(footnotes) + shared_additions: list[_F4AdditionClaim] = [] unresolved_conversions: set[int] = set() - for (ref_id, _), conversion in shared_conversions.items(): - refs = ref_rows[ref_id] - targets = _f4_shared_conversion_targets(acc_rows, refs, conversion, ledger) - if len(targets) == 1: - texts_by_row[targets[0]].append(conversion.string) - else: - unresolved_conversions.update(targets or refs) + for sentence, refs in note_rows.values(): + if len(refs) > 1: + if conversion := _F4_EXPLICIT_SALE_RECLASS_RE.match(sentence): + targets = _f4_shared_conversion_targets(acc_rows, sorted(refs), conversion, ledger) + if len(targets) == 1: + texts_by_row[targets[0]].append(sentence) + else: + unresolved_conversions.update(targets or refs) + continue + if any(_f4_is_sell(acc_rows[i]) for i in refs): + declaration = _f4_sale_addition_declaration(sentence) + if declaration is not None or _F4_ROW_SALE_ADDITION_RE.fullmatch(sentence): + shared_additions.append((declaration, refs)) + continue + for i in refs: + texts_by_row[i].append(sentence) + for row_parts, tx in zip(texts_by_row, acc_rows): + row_parts.extend(str(tx[key]) for key in ("amendment_reason", "note") if tx.get(key)) row_texts = [ ". ".join(part.strip().rstrip(".") for part in row_parts if part.strip()) for row_parts in texts_by_row ] - return row_texts, list(shared_additions.values()), unresolved_conversions + return row_texts, shared_additions, unresolved_conversions def _f4_resolve_accession_intents( @@ -840,15 +933,16 @@ def _f4_resolve_accession_intents( for sentence in sentences if (declaration := _f4_sale_addition_declaration(sentence)) is not None and declaration.count == 1 ] - quantity = _safe_float(tx.get("shares")) - if any(d.shares is not None and d.shares != quantity for d in singular_declarations): + contradictory = any(not declaration.matches(tx) for declaration in singular_declarations) + if contradictory: ambiguous[i] = True addition = ( not prior and not denial + and not contradictory and ( - any(_F4_ROW_SALE_ADDITION_RE.fullmatch(sentence) for sentence in sentences) - or any(d.shares is None or d.shares == quantity for d in singular_declarations) + bool(singular_declarations) + or any(_F4_ROW_SALE_ADDITION_RE.fullmatch(sentence) for sentence in sentences) ) ) else: @@ -865,23 +959,18 @@ def _f4_resolve_accession_intents( return row_intents, ambiguous, row_texts rem_text = " ".join(remarks_parts) # shortcut: promote explicit English declarations, and expand for verified filing wording. - shared_counts = Counter( - declaration - for sentence in shared_additions - if (declaration := _f4_sale_addition_declaration(sentence)) is not None - ) - remarks_counts = Counter() - mixed_filing_evidence = len(shared_additions) > shared_counts.total() + remarks_declarations = [] + mixed_filing_evidence = False for sentence in _f4_statements(rem_text): declaration = _f4_sale_addition_declaration(sentence) if declaration is not None: - remarks_counts[declaration] += 1 + remarks_declarations.append(declaration) elif not _F4_REMARKS_METADATA_RE.fullmatch(sentence) or _F4_OTHER_CHANGE_RE.search(sentence): mixed_filing_evidence = True - # Cross-source copies share a declaration only when their parsed transaction details agree. - declarations = shared_counts | remarks_counts - covering_declaration = next(iter(declarations)) if declarations.total() == 1 else None - filing_add = bool(shared_additions or declarations) or bool(_F4_ADDITION_RE.search(rem_text)) + all_rows = set(range(len(acc_rows))) + claims = _f4_merge_addition_claims(shared_additions, remarks_declarations, all_rows) + covering_declaration = claims[0][0] if len(claims) == 1 and claims[0][1] == 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 @@ -890,10 +979,7 @@ def _f4_resolve_accession_intents( and covering_declaration is not None and covering_declaration.count == len(acc_rows) and (len(acc_rows) == 1 or covering_declaration.sales_only) - and ( - covering_declaration.shares is None - or (len(acc_rows) == 1 and covering_declaration.shares == _safe_float(acc_rows[0].get("shares"))) - ) + and all(covering_declaration.matches(tx) for tx in acc_rows) and not mixed_filing_evidence and not any(ambiguous) and not rem_corr @@ -915,12 +1001,8 @@ def _f4_resolve_accession_intents( break else: return [(True, False)] * len(acc_rows), ambiguous, row_texts - claimed_additions = [ - tx - for tx, (addition, correction) in zip(acc_rows, row_intents) - if addition and not correction and (not shared_additions or _f4_is_sell(tx)) - ] - unclaimed_add = filing_add and not _f4_filing_additions_covered(declarations, claimed_additions) + claimed_additions = {i for i, (addition, correction) in enumerate(row_intents) if addition and not correction} + unclaimed_add = filing_add and not _f4_filing_additions_covered(claims, acc_rows, claimed_additions) 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 @@ -1196,11 +1278,13 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: 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 - is_explicit_add = is_add and not is_corr 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 any(_F4_EXPLICIT_SALE_RECLASS_RE.match(sentence) for sentence in sentences): + 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) @@ -1236,7 +1320,7 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: else: mark_uncertain(tx) continue - is_sale_conversion = is_corr and bool(_F4_SALE_TO_NONSELL_RE.search(rtext)) + 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 = [ From fbce5c27622acb4606e38e063244b30903df5566 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 19:50:52 +0800 Subject: [PATCH 27/37] fix(risk): corroborate shared Form 4/A evidence --- tests/test_risk_screening.py | 105 +++++++++++-- tools/risk_screening.py | 289 +++++++++++++++++++++++------------ 2 files changed, 285 insertions(+), 109 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index c2d1163..56179cb 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -2843,21 +2843,25 @@ def test_form4_shared_omitted_gifts_do_not_change_sale_certainty(monkeypatch): def test_form4_shared_conversion_note_is_scoped_to_the_gift(monkeypatch): from itertools import permutations - converted = _form4_sale(200, transaction_date="2026-11-18") other_sales = [_form4_sale(n, transaction_date="2026-11-19") for n in range(401, 406)] - for note, restated_fields, competing_price in ( - ("Corrects the sale of 200 shares at $20 to a gift.", {}, None), - ("Corrects the sale of 200 shares to a gift.", {}, None), - ("The 200-share sale should be reclassified to a gift.", {}, None), - ("This amendment is filed to correct the sale of 200 shares at $20 to a gift.", {}, None), - ("The sale of 200 shares at $20 should have been reported as a gift.", {}, None), - ("Corrects the sale of 200 shares at 20 to a gift.", {"shares": 200}, 25), + 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, "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": converted["transaction_date"]}, + {"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: @@ -2885,6 +2889,43 @@ def test_form4_shared_conversion_note_is_scoped_to_the_gift(monkeypatch): 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"] + if certain: + assert check["sales_90d"] == 6 + assert check["count_uncertain"] is not certain + assert result["veto_buy"] is certain + + def test_form4_addition_declarations_keep_transaction_quantity(monkeypatch): original = _form4_sale(200) amendment = { @@ -3018,6 +3059,52 @@ def test_form4_addition_declarations_respect_filing_evidence(monkeypatch): assert result["checks"]["insider_trades"]["count_uncertain"] is True +def test_form4_additions_match_compatible_statements_and_independent_row_details(monkeypatch): + original = _form4_sale(400, 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), + ( + "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}.", + "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))] diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 938d2d9..ce6d18b 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -385,7 +385,8 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: 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 (?:(?P{_F4_DECLARED_NUMBER})\s+)?(?:(?Pcommon|ordinary|class [a-z])\s+)?shares?)?" + rf"(?:\s+of (?(share_prefix)|(?:(?P{_F4_DECLARED_NUMBER})\s+)?)" + r"(?:(?Pcommon|ordinary|class [a-z])\s+)?shares?)?" rf"(?:\s+at\s+\$?\s*(?P{_F4_DECLARED_NUMBER}))?" rf"(?:\s+(?P(?:(?:that\s+)?(?:was|were)\s+)?{_F4_OMITTED})" rf"(?:\s+from the (?:original )?(?:form 4|filing)(?: filed on (?P{_F4_REMARKS_DATE}))?)?)?" @@ -395,7 +396,10 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: _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_ROW_SALE_DESCRIPTION = rf"(?:(?:first|second|third|fourth|fifth|private|open-market)\s+)?{_F4_ROW_SALE}" +_F4_SALE_ORDINAL = r"(?:first|second|third|fourth|fifth)" +_F4_ROW_SALE_DESCRIPTION = rf"(?:(?:{_F4_SALE_ORDINAL}|private|open-market)\s+)?{_F4_ROW_SALE}" +_F4_ROW_ADDITION_ORDINAL_RE = re.compile(rf"\b({_F4_SALE_ORDINAL})\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_REPORT_CONTEXT = ( @@ -457,12 +461,11 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: r"重分类|改为赠与|误报为卖出|并非卖出)", re.IGNORECASE, ) -_F4_SALE_AMOUNT = r"\d+(?:,\d{3})*(?:\.\d+)?" _F4_SALE_REFERENCE = ( r"(?:(?:the|a)\s+)?(?:(?:previously (?:misreported|reported(?: in error)?)|original)\s+)?" - rf"(?:(?P{_F4_SALE_AMOUNT})-share\s+)?sale" - rf"(?:\s+of\s+(?P{_F4_SALE_AMOUNT})\s+shares?)?" - rf"(?:\s+at\s+\$?\s*(?P{_F4_SALE_AMOUNT}))?" + 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})(?:\s+per\s+share)?)?" ) _F4_CURRENT_CHANGE = ( r"(?:(?:this amendment\s+)?(?:corrects?|reclassif(?:ies|y)|changes?)|" @@ -473,7 +476,7 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: # Without the active verb before the sale, require a passive reclassification verb. r"(?(active_change)|\s+(?:was previously reported in error and\s+)?" r"(?:(?:is|should be)\s+reclassified|should have been reported))" - r"\s+(?:to|as)\s+(?:a\s+)?(?:(?:bona fide|(?P[\d,.]+)-share)\s+)?" + 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", @@ -718,9 +721,29 @@ def matches(self, tx: dict) -> bool: and (self.original_date is None or tx.get("original_filing_date") == self.original_date) ) - def refines(self, other: "_F4AdditionDeclaration") -> bool: - # Only fill in omitted details when the known details and count agree. - return self[:2] == other[:2] and all(b is None or a == b for a, b in zip(self[2:], other[2:])) + def merged_with(self, other: "_F4AdditionDeclaration") -> "_F4AdditionDeclaration | None": + if self[:2] != other[:2] 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, + 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: @@ -737,70 +760,82 @@ def _f4_sale_addition_declaration(text: str) -> _F4AdditionDeclaration | None: declared = _F4_COUNT_WORDS.index(count) shares = _safe_float((match["shares"] or match["share_prefix"] or "").replace(",", "")) price = _safe_float((match["price"] or "").replace(",", "")) - original_date = match["original_date"] - if original_date: - for fmt in ("%B %d %Y", "%b %d %Y"): - try: - original_date = datetime.strptime(original_date.replace(",", ""), fmt).date().isoformat() - break - except ValueError: - continue return _F4AdditionDeclaration( declared, subject.startswith("sale"), shares, price, match["share_class"].casefold() if match["share_class"] else None, - original_date, + _f4_declared_filing_date(match["original_date"]), ) -_F4AdditionClaim = tuple[_F4AdditionDeclaration | None, set[int]] +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 + ordinal = _F4_ROW_ADDITION_ORDINAL_RE.search(text) + return _F4AdditionDeclaration(1, True, None, None, None, original_date), ordinal[1].casefold() if ordinal else None + + +class _F4AdditionClaim(NamedTuple): + declaration: _F4AdditionDeclaration + refs: set[int] + counted: bool = True + ordinal: str | None = None def _f4_merge_addition_claims( - shared: list[_F4AdditionClaim], remarks: list[_F4AdditionDeclaration], all_rows: set[int] + shared: list[_F4AdditionClaim], remarks: list[_F4AdditionDeclaration], rows: list[dict] ) -> list[_F4AdditionClaim]: claims: list[_F4AdditionClaim] = [] unpaired: list[_F4AdditionClaim] = [] - for declaration, refs in shared: - if declaration in remarks: - remarks.remove(declaration) - claims.append((declaration, refs)) + remaining_remarks = list(remarks) + for claim in shared: + if claim.counted and claim.declaration in remaining_remarks: + remaining_remarks.remove(claim.declaration) + claims.append(claim) else: - unpaired.append((declaration, refs)) - # A remarks copy may omit details. Pair it only with a single compatible shared statement. - options = [ - [ - i - for i, (shared_decl, _) in enumerate(unpaired) - if shared_decl is not None and (shared_decl.refines(declaration) or declaration.refines(shared_decl)) - ] - for declaration in remarks - ] + unpaired.append(claim) + # Pair overlapping cross-source claims only if their combined details can describe the linked rows. + options: list[dict[int, _F4AdditionDeclaration]] = [] + for declaration in remaining_remarks: + candidates: dict[int, _F4AdditionDeclaration] = {} + for i, claim in enumerate(unpaired): + if ( + claim.counted + and (merged := claim.declaration.merged_with(declaration)) is not None + and merged.count + and sum(merged.matches(rows[j]) for j in claim.refs) >= merged.count + ): + candidates[i] = merged + options.append(candidates) paired: set[int] = set() - for declaration, candidates in zip(remarks, options): - if len(candidates) == 1 and sum(candidates[0] in others for others in options) == 1: - i = candidates[0] - shared_decl, refs = unpaired[i] - assert shared_decl is not None - claims.append((shared_decl if shared_decl.refines(declaration) else declaration, refs)) - paired.add(i) - else: - claims.append((declaration, all_rows)) + all_rows = set(range(len(rows))) + for declaration, 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(_F4AdditionClaim(merged, unpaired[i].refs)) + paired.add(i) + continue + claims.append(_F4AdditionClaim(declaration, all_rows)) 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]) -> bool: +def _f4_filing_additions_covered( + claims: list[_F4AdditionClaim], rows: list[dict], additions: set[int], ordinals_by_row: list[set[str]] +) -> bool: if not claims: return bool(additions) options: list[set[int]] = [] - for declaration, refs in claims: - count = declaration.count if declaration is not None else 1 + for claim in claims: + count = claim.declaration.count eligible = { i - for i in refs & additions - if (declaration.matches(rows[i]) if declaration is not None else _f4_is_sell(rows[i])) + for i in claim.refs & additions + if claim.declaration.matches(rows[i]) and (claim.ordinal is None or claim.ordinal in ordinals_by_row[i]) } if not count or len(eligible) < count or len(options) + count > len(additions): return False @@ -830,7 +865,12 @@ def _f4_filing_additions_covered(claims: list[_F4AdditionClaim], rows: list[dict def _f4_shared_conversion_targets( - acc_rows: list[dict], refs: list[int], conversion: re.Match[str], ledger: list[dict] + 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]], ) -> list[int]: code = conversion["target_code"] or ("G" if (conversion["target"] or "").casefold() == "gift" else None) quantity = _safe_float((conversion["target_shares"] or "").replace(",", "")) @@ -863,11 +903,33 @@ def _f4_shared_conversion_targets( for j in pool ): matched.append(i) - return matched or candidates + if len(matched) <= 1: + return matched or candidates + + # A row-specific correction with its own prior native gift accounts for a separate transaction. + independent_gifts = set() + for i in matched: + 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) + return [i for i in matched if i not in independent_gifts] or matched def _f4_accession_note_texts( - acc_rows: list[dict], ledger: list[dict] + acc_rows: list[dict], ledger: list[dict], non_sell_histories: list[list[dict]] ) -> tuple[list[str], list[_F4AdditionClaim], set[int]]: note_rows: dict[tuple[str, str], tuple[str, set[int]]] = {} texts_by_row: list[list[str]] = [[] for _ in acc_rows] @@ -881,12 +943,19 @@ def _f4_accession_note_texts( elif isinstance(footnotes, str) and footnotes: texts_by_row[i].append(footnotes) + local_gift_corrections: dict[int, list[str]] = {} + for sentence, refs in note_rows.values(): + if len(refs) == 1 and _F4_GIFT_CORRECTION_RE.search(sentence): + local_gift_corrections.setdefault(next(iter(refs)), []).append(sentence) + shared_additions: list[_F4AdditionClaim] = [] unresolved_conversions: set[int] = set() for sentence, refs in note_rows.values(): if len(refs) > 1: if conversion := _F4_EXPLICIT_SALE_RECLASS_RE.match(sentence): - targets = _f4_shared_conversion_targets(acc_rows, sorted(refs), conversion, ledger) + targets = _f4_shared_conversion_targets( + acc_rows, refs, conversion, ledger, non_sell_histories, local_gift_corrections + ) if len(targets) == 1: texts_by_row[targets[0]].append(sentence) else: @@ -894,8 +963,12 @@ def _f4_accession_note_texts( continue if any(_f4_is_sell(acc_rows[i]) for i in refs): declaration = _f4_sale_addition_declaration(sentence) - if declaration is not None or _F4_ROW_SALE_ADDITION_RE.fullmatch(sentence): - shared_additions.append((declaration, refs)) + if declaration is not None: + shared_additions.append(_F4AdditionClaim(declaration, refs)) + continue + if row_addition := _f4_uncounted_row_addition(sentence): + declaration, ordinal = row_addition + shared_additions.append(_F4AdditionClaim(declaration, refs, counted=False, ordinal=ordinal)) continue for i in refs: texts_by_row[i].append(sentence) @@ -910,41 +983,40 @@ def _f4_accession_note_texts( 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]]: """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. """ - row_texts, shared_additions, unresolved_conversions = _f4_accession_note_texts(acc_rows, ledger) + row_texts, shared_additions, unresolved_conversions = _f4_accession_note_texts(acc_rows, ledger, non_sell_histories) 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))] + ordinals_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 = [ - declaration - for sentence in sentences - if (declaration := _f4_sale_addition_declaration(sentence)) is not None and declaration.count == 1 - ] + 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, ordinal = row_addition + singular_declarations.append(declaration) + if ordinal is not None: + ordinals_by_row[i].add(ordinal) contradictory = any(not declaration.matches(tx) for declaration in singular_declarations) if contradictory: ambiguous[i] = True - addition = ( - not prior - and not denial - and not contradictory - and ( - bool(singular_declarations) - or any(_F4_ROW_SALE_ADDITION_RE.fullmatch(sentence) for sentence in sentences) - ) - ) + addition = not (prior or denial or contradictory) and bool(singular_declarations) else: addition = bool(_F4_ADDITION_RE.search(rt)) row_intents.append((addition, bool(_F4_CORRECTION_RE.search(rt)))) @@ -968,8 +1040,10 @@ def _f4_resolve_accession_intents( elif not _F4_REMARKS_METADATA_RE.fullmatch(sentence) or _F4_OTHER_CHANGE_RE.search(sentence): mixed_filing_evidence = True all_rows = set(range(len(acc_rows))) - claims = _f4_merge_addition_claims(shared_additions, remarks_declarations, all_rows) - covering_declaration = claims[0][0] if len(claims) == 1 and claims[0][1] == all_rows else None + claims = _f4_merge_addition_claims(shared_additions, remarks_declarations, acc_rows) + 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): @@ -1002,7 +1076,9 @@ def _f4_resolve_accession_intents( else: return [(True, False)] * len(acc_rows), ambiguous, row_texts claimed_additions = {i for i, (addition, correction) in enumerate(row_intents) if addition and not correction} - unclaimed_add = filing_add and not _f4_filing_additions_covered(claims, acc_rows, claimed_additions) + unclaimed_add = filing_add and not _f4_filing_additions_covered( + claims, acc_rows, claimed_additions, ordinals_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 @@ -1226,7 +1302,12 @@ def _f4_non_sell_revisions(history: list[dict], linked_date: str, amend_date: st def _f4_prior_native_gifts( - non_sell_histories: list[list[dict]], tx: dict, linked_date: str + 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() @@ -1235,12 +1316,37 @@ def _f4_prior_native_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 = _f4_non_sell_revisions(history, linked_date, filing_date, acceptance_ts) + 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]], @@ -1289,32 +1395,15 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: 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")) - prior_native_gifts = _f4_prior_native_gifts(non_sell_histories, tx, orig_date) if has_identity else [] - native_gifts = [ - i - for i, revisions in prior_native_gifts - if any( - (not prior_shares or _f4_matches_num_set(rev.get("shares"), prior_shares)) - and (not prior_prices or _f4_matches_num_set(rev.get("price"), prior_prices)) - for rev in revisions - ) - ] - gift_candidates = [ - i - for i in pool - if has_identity - and 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=orig_date or None, - gift_only=True, + 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], []).append(tx) + 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: @@ -2057,7 +2146,7 @@ def _mark_uncertain(tx: dict) -> None: _mark_uncertain(tx) for _acc, acc_rows in sorted_acc_items: - intents, ambig_flags, row_texts = _f4_resolve_accession_intents(acc_rows, ledger) + intents, ambig_flags, row_texts = _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]] = [] for tx, intent, is_ambig, rtext in zip(acc_rows, intents, ambig_flags, row_texts): From 9fde3fb1caab0416b7ccbe2b49bbfd4022c349b9 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 20:05:31 +0800 Subject: [PATCH 28/37] fix(risk): keep unresolved amendments from changing sale counts --- tests/test_risk_screening.py | 50 ++++++++++-- tools/risk_screening.py | 146 +++++++++++++++++++---------------- 2 files changed, 123 insertions(+), 73 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 56179cb..8b277e2 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 @@ -2853,6 +2855,12 @@ def test_form4_shared_conversion_note_is_scoped_to_the_gift(monkeypatch): (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, @@ -2920,12 +2928,36 @@ def test_form4_shared_conversion_preserves_independently_corrected_gift(monkeypa for ordered in permutations((gift, sell, revised)): result = _screen_form4_cli(monkeypatch, [converted, restated, *other_sales, *prior_gifts, *ordered]) check = result["checks"]["insider_trades"] - if certain: - assert check["sales_90d"] == 6 + assert check["sales_90d"] == (6 if certain else 7) assert check["count_uncertain"] is not certain assert result["veto_buy"] is certain +@pytest.mark.parametrize( + "note", + [ + "Corrects the sale of 200 shares at $20 to a 300-share gift.", + "Corrects the transaction code from S to F.", + ], +) +def test_form4_conversion_note_must_match_the_linked_non_sell(monkeypatch, note): + 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}, + 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 + + def test_form4_addition_declarations_keep_transaction_quantity(monkeypatch): original = _form4_sale(200) amendment = { @@ -2981,6 +3013,8 @@ def test_form4_addition_declarations_respect_filing_evidence(monkeypatch): ("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", @@ -3060,7 +3094,7 @@ def test_form4_addition_declarations_respect_filing_evidence(monkeypatch): def test_form4_additions_match_compatible_statements_and_independent_row_details(monkeypatch): - original = _form4_sale(400, price=30) + original = _form4_sale(200, price=30) amendment = { "form": "4/A", "accession": "0000000123-26-000002", @@ -3072,6 +3106,8 @@ def test_form4_additions_match_compatible_statements_and_independent_row_details ("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", "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", "", @@ -3083,7 +3119,7 @@ def test_form4_additions_match_compatible_statements_and_independent_row_details ("one omitted sale", "", "one omitted 200-share sale of 100 shares", None, 1, True), ): footnotes = { - "F1": f"This amendment reports {shared}.", + "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.", } @@ -3503,7 +3539,11 @@ def file_revision(row, day, **fields): assert check["sales_90d"] == 1 assert check["count_uncertain"] is False - same_size_gift = dict(gift, shares=100) + 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" diff --git a/tools/risk_screening.py b/tools/risk_screening.py index ce6d18b..1908a71 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -378,6 +378,7 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: _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_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+)?" @@ -387,7 +388,7 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: r"(?Psale(?: transactions?|s)?|transactions?)" rf"(?:\s+of (?(share_prefix)|(?:(?P{_F4_DECLARED_NUMBER})\s+)?)" r"(?:(?Pcommon|ordinary|class [a-z])\s+)?shares?)?" - rf"(?:\s+at\s+\$?\s*(?P{_F4_DECLARED_NUMBER}))?" + 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))?", @@ -396,9 +397,9 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: _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_ORDINAL = r"(?:first|second|third|fourth|fifth)" -_F4_ROW_SALE_DESCRIPTION = rf"(?:(?:{_F4_SALE_ORDINAL}|private|open-market)\s+)?{_F4_ROW_SALE}" -_F4_ROW_ADDITION_ORDINAL_RE = re.compile(rf"\b({_F4_SALE_ORDINAL})\s+{_F4_ROW_SALE}\b", re.IGNORECASE) +_F4_SALE_QUALIFIER = r"(?:first|second|third|fourth|fifth|private|open-market)" +_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}" @@ -465,7 +466,7 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: 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})(?:\s+per\s+share)?)?" + rf"(?:\s+at\s+\$?\s*(?P{_F4_DECLARED_NUMBER}){_F4_PER_SHARE})?" ) _F4_CURRENT_CHANGE = ( r"(?:(?:this amendment\s+)?(?:corrects?|reclassif(?:ies|y)|changes?)|" @@ -474,7 +475,7 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: _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 and\s+)?" + 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" @@ -775,57 +776,58 @@ def _f4_uncounted_row_addition(text: str) -> tuple[_F4AdditionDeclaration, str | 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 - ordinal = _F4_ROW_ADDITION_ORDINAL_RE.search(text) - return _F4AdditionDeclaration(1, True, None, None, None, original_date), ordinal[1].casefold() if ordinal 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 - ordinal: str | None = None + qualifier: str | None = None def _f4_merge_addition_claims( - shared: list[_F4AdditionClaim], remarks: list[_F4AdditionDeclaration], rows: list[dict] + shared: list[_F4AdditionClaim], remarks: list[_F4AdditionClaim], rows: list[dict], additions: set[int] ) -> list[_F4AdditionClaim]: claims: list[_F4AdditionClaim] = [] unpaired: list[_F4AdditionClaim] = [] remaining_remarks = list(remarks) + all_rows = set(range(len(rows))) for claim in shared: - if claim.counted and claim.declaration in remaining_remarks: - remaining_remarks.remove(claim.declaration) + 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) - # Pair overlapping cross-source claims only if their combined details can describe the linked rows. + # A restated row cannot corroborate a merge. A count that covers the whole accession can establish additions alone. options: list[dict[int, _F4AdditionDeclaration]] = [] - for declaration in remaining_remarks: + for remark in remaining_remarks: candidates: dict[int, _F4AdditionDeclaration] = {} for i, claim in enumerate(unpaired): - if ( - claim.counted - and (merged := claim.declaration.merged_with(declaration)) is not None - and merged.count - and sum(merged.matches(rows[j]) for j in claim.refs) >= merged.count - ): + if not (remark.counted and claim.counted and (merged := claim.declaration.merged_with(remark.declaration))): + continue + eligible = all_rows if merged.count == len(rows) and claim.refs == all_rows else claim.refs & additions + if merged.count and sum(merged.matches(rows[j]) for j in eligible) >= merged.count: candidates[i] = merged options.append(candidates) paired: set[int] = set() - all_rows = set(range(len(rows))) - for declaration, candidates in zip(remaining_remarks, options): + 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(_F4AdditionClaim(merged, unpaired[i].refs)) paired.add(i) continue - claims.append(_F4AdditionClaim(declaration, all_rows)) + 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], ordinals_by_row: list[set[str]] + claims: list[_F4AdditionClaim], rows: list[dict], additions: set[int], qualifiers_by_row: list[set[str]] ) -> bool: if not claims: return bool(additions) @@ -835,7 +837,8 @@ def _f4_filing_additions_covered( eligible = { i for i in claim.refs & additions - if claim.declaration.matches(rows[i]) and (claim.ordinal is None or claim.ordinal in ordinals_by_row[i]) + if claim.declaration.matches(rows[i]) + and (claim.qualifier is None or claim.qualifier in qualifiers_by_row[i]) } if not count or len(eligible) < count or len(options) + count > len(additions): return False @@ -864,7 +867,7 @@ def _f4_filing_additions_covered( return True -def _f4_shared_conversion_targets( +def _f4_conversion_targets( acc_rows: list[dict], refs: set[int], conversion: re.Match[str], @@ -951,25 +954,24 @@ def _f4_accession_note_texts( shared_additions: list[_F4AdditionClaim] = [] unresolved_conversions: set[int] = set() for sentence, refs in note_rows.values(): - if len(refs) > 1: - if conversion := _F4_EXPLICIT_SALE_RECLASS_RE.match(sentence): - targets = _f4_shared_conversion_targets( - acc_rows, refs, conversion, ledger, non_sell_histories, local_gift_corrections - ) - if len(targets) == 1: - texts_by_row[targets[0]].append(sentence) - else: - unresolved_conversions.update(targets or refs) + if conversion := _F4_EXPLICIT_SALE_RECLASS_RE.match(sentence): + targets = _f4_conversion_targets( + acc_rows, refs, conversion, ledger, non_sell_histories, local_gift_corrections + ) + 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 - if 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, ordinal = row_addition - shared_additions.append(_F4AdditionClaim(declaration, refs, counted=False, ordinal=ordinal)) - continue for i in refs: texts_by_row[i].append(sentence) for row_parts, tx in zip(texts_by_row, acc_rows): @@ -984,7 +986,7 @@ 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]]: +) -> tuple[list[tuple[bool, bool]], list[bool], list[str], 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 @@ -996,7 +998,7 @@ def _f4_resolve_accession_intents( ] row_intents = [] ambiguous = [i in unresolved_conversions for i in range(len(acc_rows))] - ordinals_by_row: list[set[str]] = [set() for _ in 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): @@ -1009,10 +1011,10 @@ def _f4_resolve_accession_intents( if declaration is not None and declaration.count == 1: singular_declarations.append(declaration) elif row_addition := _f4_uncounted_row_addition(sentence): - declaration, ordinal = row_addition + declaration, qualifier = row_addition singular_declarations.append(declaration) - if ordinal is not None: - ordinals_by_row[i].add(ordinal) + if qualifier is not None: + qualifiers_by_row[i].add(qualifier) contradictory = any(not declaration.matches(tx) for declaration in singular_declarations) if contradictory: ambiguous[i] = True @@ -1028,26 +1030,30 @@ def _f4_resolve_accession_intents( seen_remarks.add(rem) remarks_parts.append(rem) if not (remarks_parts or shared_additions): - return row_intents, ambiguous, row_texts + return row_intents, ambiguous, row_texts, unresolved_conversions rem_text = " ".join(remarks_parts) # shortcut: promote explicit English declarations, and expand for verified filing wording. - remarks_declarations = [] + all_rows = set(range(len(acc_rows))) + remarks_claims = [] mixed_filing_evidence = False for sentence in _f4_statements(rem_text): declaration = _f4_sale_addition_declaration(sentence) if declaration is not None: - remarks_declarations.append(declaration) + 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 - all_rows = set(range(len(acc_rows))) - claims = _f4_merge_addition_claims(shared_additions, remarks_declarations, acc_rows) + 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) 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 + return row_intents, ambiguous, row_texts, unresolved_conversions if ( len(remarks_parts) <= 1 and covering_declaration is not None @@ -1074,25 +1080,24 @@ def _f4_resolve_accession_intents( if any(sig in ledger[i]["sigs"] for i in pool): break else: - return [(True, False)] * len(acc_rows), ambiguous, row_texts - claimed_additions = {i for i, (addition, correction) in enumerate(row_intents) if addition and not correction} + return [(True, False)] * len(acc_rows), ambiguous, row_texts, unresolved_conversions unclaimed_add = filing_add and not _f4_filing_additions_covered( - claims, acc_rows, claimed_additions, ordinals_by_row + 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 + return row_intents, ambiguous, row_texts, unresolved_conversions 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 + return row_intents, ambiguous, row_texts, unresolved_conversions row_intents[0] = (unclaimed_add, unclaimed_corr) row_texts[0] = ". ".join(filter(None, (row_texts[0], rem_text))) - return row_intents, ambiguous, row_texts + return row_intents, ambiguous, row_texts, unresolved_conversions for i in unattributed or range(len(acc_rows)): ambiguous[i] = True - return row_intents, ambiguous, row_texts + return row_intents, ambiguous, row_texts, unresolved_conversions def _f4_make_ledger_entry(tx: dict, *, from_orig: bool) -> dict: @@ -1350,7 +1355,7 @@ def _f4_prior_reclassified_gifts( 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]], + acc_non_sells: list[tuple[dict, tuple[bool, bool], bool, str, bool]], prior_len: int, mark_uncertain, ) -> tuple[set[int], list[tuple[int, dict]]]: @@ -1378,7 +1383,7 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: acc_added_non_sells: list[dict] = [] ns_candidates: list[tuple[dict, bool, bool, str]] = [] - for tx, (is_add, is_corr), is_ambig, rtext in acc_non_sells: + for tx, (is_add, is_corr), is_ambig, rtext, unresolved_conversion in acc_non_sells: base = _f4_base_sig(tx) code = _f4_tx_code(tx) shares = tx.get("shares") @@ -1409,6 +1414,9 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: 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 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) @@ -2146,16 +2154,18 @@ def _mark_uncertain(tx: dict) -> None: _mark_uncertain(tx) for _acc, acc_rows in sorted_acc_items: - intents, ambig_flags, row_texts = _f4_resolve_accession_intents(acc_rows, ledger, non_sell_histories) + intents, ambig_flags, row_texts, unresolved_conversions = _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]] = [] - for tx, intent, is_ambig, rtext in zip(acc_rows, intents, ambig_flags, row_texts): + acc_non_sells: list[tuple[dict, tuple[bool, bool], bool, str, 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)) + acc_non_sells.append((tx, intent, is_ambig, rtext, i in unresolved_conversions)) prior_len = len(ledger) acc_matched_ns, pending_reclassifications = _f4_reconcile_non_sells( From b42724b71659ef098167ec17e778340be409dfcc Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 20:11:15 +0800 Subject: [PATCH 29/37] fix(risk): apply conversion scope to filing remarks --- tests/test_risk_screening.py | 35 ++++++++++++++++++++++++++------- tools/risk_screening.py | 38 ++++++++++++++++++++++++------------ 2 files changed, 53 insertions(+), 20 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 8b277e2..56975f1 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -2932,15 +2932,35 @@ def test_form4_shared_conversion_preserves_independently_corrected_gift(monkeypa 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( - "note", + "note, expected_sales", [ - "Corrects the sale of 200 shares at $20 to a 300-share gift.", - "Corrects the transaction code from S to F.", + ("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), ], ) -def test_form4_conversion_note_must_match_the_linked_non_sell(monkeypatch, note): +@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, @@ -2950,12 +2970,13 @@ def test_form4_conversion_note_must_match_the_linked_non_sell(monkeypatch, note) original_filing_date="2026-11-21", transaction_code="G", price=None, - footnotes={"F1": note}, + 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"] == 1 - assert check["count_uncertain"] is True + assert check["sales_90d"] == expected_sales + assert check["count_uncertain"] is bool(expected_sales) def test_form4_addition_declarations_keep_transaction_quantity(monkeypatch): diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 1908a71..5d58a45 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -932,9 +932,9 @@ def _f4_conversion_targets( def _f4_accession_note_texts( - acc_rows: list[dict], ledger: list[dict], non_sell_histories: list[list[dict]] + acc_rows: list[dict], ledger: list[dict], non_sell_histories: list[list[dict]], remark_conversions: list[str] ) -> tuple[list[str], list[_F4AdditionClaim], set[int]]: - note_rows: dict[tuple[str, str], tuple[str, set[int]]] = {} + note_rows: dict[tuple[str | None, str], tuple[str, set[int]]] = {} texts_by_row: list[list[str]] = [[] for _ in acc_rows] for i, tx in enumerate(acc_rows): footnotes = tx.get("footnotes") @@ -946,6 +946,14 @@ def _f4_accession_note_texts( 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_corrections: dict[int, list[str]] = {} for sentence, refs in note_rows.values(): if len(refs) == 1 and _F4_GIFT_CORRECTION_RE.search(sentence): @@ -992,7 +1000,18 @@ def _f4_resolve_accession_intents( Use filing evidence for a single unambiguous row or an explicit sale addition count covering every row. Leave unattributed rows in mixed filings uncertain. """ - row_texts, shared_additions, unresolved_conversions = _f4_accession_note_texts(acc_rows, ledger, non_sell_histories) + 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 = _f4_accession_note_texts( + acc_rows, ledger, non_sell_histories, remark_conversions + ) prior_disclosures = [ any(not match["negated"] for match in _F4_PRIOR_DISCLOSURE_RE.finditer(text)) for text in row_texts ] @@ -1022,21 +1041,14 @@ def _f4_resolve_accession_intents( else: addition = bool(_F4_ADDITION_RE.search(rt)) row_intents.append((addition, bool(_F4_CORRECTION_RE.search(rt)))) - seen_remarks: set[str] = set() - remarks_parts: list[str] = [] - for tx in acc_rows: - rem = str(tx.get("remarks") or "").strip() - if rem and rem not in seen_remarks: - seen_remarks.add(rem) - remarks_parts.append(rem) - if not (remarks_parts or shared_additions): + if not (other_remarks or shared_additions): return row_intents, ambiguous, row_texts, unresolved_conversions - rem_text = " ".join(remarks_parts) + 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 _f4_statements(rem_text): + for sentence in other_remarks: declaration = _f4_sale_addition_declaration(sentence) if declaration is not None: remarks_claims.append(_F4AdditionClaim(declaration, all_rows)) From 034622ac8d4254fdf94d5e95b923667d45b54a1a Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 22:20:48 +0800 Subject: [PATCH 30/37] fix(risk): reconcile independently identified Form 4 amendments --- tests/test_risk_screening.py | 77 ++++++++++++++++++++++++++++ tools/risk_screening.py | 98 ++++++++++++++++++++++++++++-------- 2 files changed, 153 insertions(+), 22 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 56975f1..d16305d 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -2895,6 +2895,17 @@ def test_form4_shared_conversion_note_is_scoped_to_the_gift(monkeypatch): 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 def test_form4_shared_conversion_preserves_independently_corrected_gift(monkeypatch): @@ -2951,6 +2962,47 @@ def test_form4_shared_conversion_preserves_independently_corrected_gift(monkeypa assert result["veto_buy"] is True +@pytest.mark.parametrize( + "gift_note, shared_note, conversion_date, expected_sales", + [ + ("This gift was previously unreported.", False, "2026-11-20", 6), + ("This amendment reports one omitted gift.", False, "2026-11-20", 6), + ("This gift was previously unreported.", True, "2026-11-20", 7), + ("This gift was previously unreported. This gift was not omitted.", False, "2026-11-20", 7), + ("This gift was previously unreported.", False, "2026-11-17", 7), + ], +) +def test_form4_shared_conversion_preserves_independently_added_gift( + monkeypatch, gift_note, shared_note, conversion_date, expected_sales +): + sale = _form4_sale(200) + originals = [sale, *(_form4_sale(n, transaction_date="2026-11-19") for n in range(401, 407))] + 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}, + } + converted = _form4_sale( + 200, + **amendment, + transaction_date=conversion_date, + transaction_code="G", + price=None, + footnote_refs={"transactionCoding": ["F1", "F2"] if shared_note else ["F1"]}, + ) + added = _form4_sale( + 100, **amendment, transaction_code="G", price=None, 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) + + @pytest.mark.parametrize( "note, expected_sales", [ @@ -3114,6 +3166,27 @@ def test_form4_addition_declarations_respect_filing_evidence(monkeypatch): assert result["checks"]["insider_trades"]["count_uncertain"] is True +@pytest.mark.parametrize("security, class_matches", [("Class A Common Stock", True), ("Class A-1 Common Stock", False)]) +def test_form4_addition_matches_complete_share_class(monkeypatch, 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": "This amendment reports one omitted sale of 100 Class A 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 = { @@ -3127,6 +3200,10 @@ def test_form4_additions_match_compatible_statements_and_independent_row_details ("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), + ("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", "the omitted first sale", None, 2, True), ("the omitted private sale", "", "the omitted open-market sale", None, 2, True), ( diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 5d58a45..24b4f55 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -495,6 +495,19 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: 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_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|" @@ -711,13 +724,15 @@ class _F4AdditionDeclaration(NamedTuple): original_date: str | None def matches(self, tx: dict) -> bool: + class_end = r"\b(?!-\w)" if (self.share_class or "").startswith("class ") else r"\b" + security = str(tx.get("security") or "") 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 re.search(rf"\b{self.share_class}\b", str(tx.get("security") or ""), re.IGNORECASE) is not None + or re.search(rf"\b{self.share_class}{class_end}", security, re.IGNORECASE) is not None ) and (self.original_date is None or tx.get("original_filing_date") == self.original_date) ) @@ -788,9 +803,20 @@ class _F4AdditionClaim(NamedTuple): 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] + 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] = [] @@ -804,22 +830,34 @@ def _f4_merge_addition_claims( 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, _F4AdditionDeclaration]] = [] + options: list[dict[int, _F4AdditionClaim]] = [] for remark in remaining_remarks: - candidates: dict[int, _F4AdditionDeclaration] = {} + candidates: dict[int, _F4AdditionClaim] = {} for i, claim in enumerate(unpaired): - if not (remark.counted and claim.counted and (merged := claim.declaration.merged_with(remark.declaration))): + if not (remark.counted or claim.counted): + continue + declaration = claim.declaration.merged_with(remark.declaration) + if declaration is None or not declaration.count: continue - eligible = all_rows if merged.count == len(rows) and claim.refs == all_rows else claim.refs & additions - if merged.count and sum(merged.matches(rows[j]) for j in eligible) >= merged.count: - candidates[i] = merged + merged = _F4AdditionClaim( + declaration, claim.refs, claim.counted and remark.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(_F4AdditionClaim(merged, unpaired[i].refs)) + claims.append(merged) paired.add(i) continue claims.append(remark) @@ -834,12 +872,7 @@ def _f4_filing_additions_covered( options: list[set[int]] = [] for claim in claims: count = claim.declaration.count - eligible = { - i - for i in claim.refs & additions - if claim.declaration.matches(rows[i]) - and (claim.qualifier is None or claim.qualifier in qualifiers_by_row[i]) - } + 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) @@ -874,6 +907,7 @@ def _f4_conversion_targets( ledger: list[dict], non_sell_histories: list[list[dict]], local_gift_corrections: dict[int, list[str]], + local_gift_additions: set[int], ) -> list[int]: code = conversion["target_code"] or ("G" if (conversion["target"] or "").casefold() == "gift" else None) quantity = _safe_float((conversion["target_shares"] or "").replace(",", "")) @@ -885,7 +919,7 @@ def _f4_conversion_targets( and (quantity is None or _f4_matches_num_set(acc_rows[i].get("shares"), {quantity})) ] if len(candidates) <= 1: - return candidates + return candidates if len(refs) == 1 else [i for i in candidates if i not in local_gift_additions] # Multiple linked gifts can only be distinguished by the corrected transaction and its filing history. sentence = conversion.string @@ -906,8 +940,12 @@ def _f4_conversion_targets( for j in pool ): matched.append(i) + if not matched: + return candidates + # Reject separately reported gifts without promoting an unmatched row by elimination. + matched = [i for i in matched if i not in local_gift_additions] if len(matched) <= 1: - return matched or candidates + return matched # A row-specific correction with its own prior native gift accounts for a separate transaction. independent_gifts = set() @@ -954,17 +992,33 @@ def _f4_accession_note_texts( if statement not in linked_statements: note_rows[None, statement] = sentence, all_rows - local_gift_corrections: dict[int, list[str]] = {} + local_gift_notes: dict[int, list[str]] = {} for sentence, refs in note_rows.values(): - if len(refs) == 1 and _F4_GIFT_CORRECTION_RE.search(sentence): - local_gift_corrections.setdefault(next(iter(refs)), []).append(sentence) + if len(refs) == 1: + i = next(iter(refs)) + if _f4_tx_code(acc_rows[i]) == "G": + local_gift_notes.setdefault(i, []).append(sentence) + local_gift_corrections: dict[int, list[str]] = {} + local_gift_additions: set[int] = set() + 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 + elif any(_F4_ROW_GIFT_ADDITION_RE.fullmatch(sentence) for sentence in sentences) and not 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 + ): + local_gift_additions.add(i) shared_additions: list[_F4AdditionClaim] = [] unresolved_conversions: set[int] = set() 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 + acc_rows, refs, conversion, ledger, non_sell_histories, local_gift_corrections, local_gift_additions ) if len(targets) == 1: texts_by_row[targets[0]].append(sentence) @@ -1058,7 +1112,7 @@ def _f4_resolve_accession_intents( 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) + 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 ) From 40c6ec0814185b967224835d36861ca7c1a7e6a5 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 22:32:04 +0800 Subject: [PATCH 31/37] fix(risk): preserve contradictory Form 4 amendment evidence --- tests/test_risk_screening.py | 120 +++++++++++++++++++++++++++++++---- tools/risk_screening.py | 118 ++++++++++++++++++++++------------ 2 files changed, 184 insertions(+), 54 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index d16305d..3026824 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -2906,6 +2906,7 @@ def test_form4_shared_conversion_note_is_scoped_to_the_gift(monkeypatch): 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): @@ -2963,38 +2964,50 @@ def test_form4_shared_conversion_preserves_independently_corrected_gift(monkeypa @pytest.mark.parametrize( - "gift_note, shared_note, conversion_date, expected_sales", + "gift_note, shared_note, conversion_date, denial_source, expected_sales", [ - ("This gift was previously unreported.", False, "2026-11-20", 6), - ("This amendment reports one omitted gift.", False, "2026-11-20", 6), - ("This gift was previously unreported.", True, "2026-11-20", 7), - ("This gift was previously unreported. This gift was not omitted.", False, "2026-11-20", 7), - ("This gift was previously unreported.", False, "2026-11-17", 7), + ("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", "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), ], ) def test_form4_shared_conversion_preserves_independently_added_gift( - monkeypatch, gift_note, shared_note, conversion_date, expected_sales + monkeypatch, gift_note, shared_note, conversion_date, denial_source, expected_sales ): sale = _form4_sale(200) - originals = [sale, *(_form4_sale(n, transaction_date="2026-11-19") for n in range(401, 407))] + 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}, + "footnotes": {"F1": "Corrects the sale of 200 shares at $20 to a gift.", "F2": gift_note, "F3": denial}, } + if denial_source == "remarks": + amendment["remarks"] = denial + 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": ["F1", "F2"] if shared_note else ["F1"]}, + footnote_refs={"transactionCoding": [*references, "F2"] if shared_note else references}, ) added = _form4_sale( - 100, **amendment, transaction_code="G", price=None, footnote_refs={"transactionCoding": ["F1", "F2"]} + 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"] @@ -3003,6 +3016,59 @@ def test_form4_shared_conversion_preserves_independently_added_gift( assert result["veto_buy"] is (expected_sales == 6) +@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) + + +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", [ @@ -3166,8 +3232,17 @@ def test_form4_addition_declarations_respect_filing_evidence(monkeypatch): assert result["checks"]["insider_trades"]["count_uncertain"] is True -@pytest.mark.parametrize("security, class_matches", [("Class A Common Stock", True), ("Class A-1 Common Stock", False)]) -def test_form4_addition_matches_complete_share_class(monkeypatch, security, class_matches): +@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, @@ -3176,7 +3251,7 @@ def test_form4_addition_matches_complete_share_class(monkeypatch, security, clas filing_date="2026-11-22", original_filing_date="2026-11-21", security=security, - footnotes={"F1": "This amendment reports one omitted sale of 100 Class A shares."}, + 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]) @@ -3201,9 +3276,26 @@ def test_form4_additions_match_compatible_statements_and_independent_row_details ("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), ( diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 24b4f55..0183327 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -379,6 +379,9 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: _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+)?" @@ -387,7 +390,7 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: 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+)?)" - r"(?:(?Pcommon|ordinary|class [a-z])\s+)?shares?)?" + 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}))?)?)?" @@ -397,7 +400,9 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: _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_QUALIFIER = r"(?:first|second|third|fourth|fifth|private|open-market)" +_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) @@ -715,6 +720,17 @@ 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 @@ -724,27 +740,22 @@ class _F4AdditionDeclaration(NamedTuple): original_date: str | None def matches(self, tx: dict) -> bool: - class_end = r"\b(?!-\w)" if (self.share_class or "").startswith("class ") else r"\b" - security = str(tx.get("security") or "") 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 re.search(rf"\b{self.share_class}{class_end}", security, re.IGNORECASE) is not None - ) + 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[:2] != other[:2] or any( + 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, + 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, @@ -781,7 +792,7 @@ def _f4_sale_addition_declaration(text: str) -> _F4AdditionDeclaration | None: subject.startswith("sale"), shares, price, - match["share_class"].casefold() if match["share_class"] else None, + _f4_normalize_share_class(match["share_class"]) if match["share_class"] else None, _f4_declared_filing_date(match["original_date"]), ) @@ -836,12 +847,13 @@ def _f4_merge_addition_claims( 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, claim.counted and remark.counted, claim.qualifier or remark.qualifier - ) + 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: @@ -907,7 +919,7 @@ def _f4_conversion_targets( ledger: list[dict], non_sell_histories: list[list[dict]], local_gift_corrections: dict[int, list[str]], - local_gift_additions: set[int], + 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(",", "")) @@ -919,7 +931,7 @@ def _f4_conversion_targets( 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 i not in local_gift_additions] + 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 @@ -943,9 +955,7 @@ def _f4_conversion_targets( if not matched: return candidates # Reject separately reported gifts without promoting an unmatched row by elimination. - matched = [i for i in matched if i not in local_gift_additions] - if len(matched) <= 1: - return matched + matched = [i for i in matched if not local_gift_additions.get(i)] # A row-specific correction with its own prior native gift accounts for a separate transaction. independent_gifts = set() @@ -966,14 +976,19 @@ def _f4_conversion_targets( 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) - return [i for i in matched if i not in independent_gifts] or matched + return [i for i in matched if i not in independent_gifts] def _f4_accession_note_texts( - acc_rows: list[dict], ledger: list[dict], non_sell_histories: list[list[dict]], remark_conversions: list[str] -) -> tuple[list[str], list[_F4AdditionClaim], set[int]]: + acc_rows: list[dict], + ledger: list[dict], + non_sell_histories: list[list[dict]], + remark_conversions: list[str], + filing_denies_gift_additions: bool, +) -> 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): @@ -992,29 +1007,42 @@ def _f4_accession_note_texts( if statement not in linked_statements: note_rows[None, statement] = sentence, all_rows - local_gift_notes: dict[int, list[str]] = {} + 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 note_rows.values(): + if _F4_ROW_GIFT_ADDITION_DENIAL_RE.match(sentence): + linked_gift_denials.update(refs) if len(refs) == 1: i = next(iter(refs)) - if _f4_tx_code(acc_rows[i]) == "G": - local_gift_notes.setdefault(i, []).append(sentence) + if i in local_gift_notes: + local_gift_notes[i].append(sentence) local_gift_corrections: dict[int, list[str]] = {} - local_gift_additions: set[int] = set() + 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 - elif any(_F4_ROW_GIFT_ADDITION_RE.fullmatch(sentence) for sentence in sentences) and not 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 - ): - local_gift_additions.add(i) + if any(_F4_ROW_GIFT_ADDITION_RE.fullmatch(sentence) for sentence in sentences): + local_gift_additions[i] = not ( + corrections + or filing_denies_gift_additions + 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] = [] - unresolved_conversions: set[int] = set() + # 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( @@ -1036,12 +1064,12 @@ def _f4_accession_note_texts( continue for i in refs: texts_by_row[i].append(sentence) - for row_parts, tx in zip(texts_by_row, acc_rows): - row_parts.extend(str(tx[key]) for key in ("amendment_reason", "note") if tx.get(key)) + 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 + return row_texts, shared_additions, unresolved_conversions, local_gift_additions def _f4_resolve_accession_intents( @@ -1063,8 +1091,12 @@ def _f4_resolve_accession_intents( remark_conversions.append(sentence) else: other_remarks.append(sentence) - row_texts, shared_additions, unresolved_conversions = _f4_accession_note_texts( - acc_rows, ledger, non_sell_histories, remark_conversions + row_texts, shared_additions, unresolved_conversions, local_gift_additions = _f4_accession_note_texts( + acc_rows, + ledger, + non_sell_histories, + remark_conversions, + filing_denies_gift_additions=any(_F4_ROW_GIFT_ADDITION_DENIAL_RE.match(sentence) for sentence in other_remarks), ) prior_disclosures = [ any(not match["negated"] for match in _F4_PRIOR_DISCLOSURE_RE.finditer(text)) for text in row_texts @@ -1088,10 +1120,16 @@ def _f4_resolve_accession_intents( 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)))) From d1dd1dbbeaad67703cfc3aaee16096cfbbf4fbdc Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 22:38:20 +0800 Subject: [PATCH 32/37] fix(risk): scope prior gift disclosures to matching rows --- tests/test_risk_screening.py | 11 +++++++++-- tools/risk_screening.py | 27 ++++++++++++++++++++------- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 3026824..1c9b85d 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -2973,6 +2973,8 @@ def test_form4_shared_conversion_preserves_independently_corrected_gift(monkeypa ("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), @@ -2992,8 +2994,13 @@ def test_form4_shared_conversion_preserves_independently_added_gift( "original_filing_date": "2026-11-21", "footnotes": {"F1": "Corrects the sale of 200 shares at $20 to a gift.", "F2": gift_note, "F3": denial}, } - if denial_source == "remarks": - amendment["remarks"] = 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, diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 0183327..0f7fd8e 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -9,6 +9,7 @@ import sys from concurrent.futures import Future, ThreadPoolExecutor 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__))) @@ -513,6 +514,10 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: 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)", + 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|" @@ -955,11 +960,14 @@ def _f4_conversion_targets( if not matched: return candidates # Reject separately reported gifts without promoting an unmatched row by elimination. - matched = [i for i in matched if not local_gift_additions.get(i)] + 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 matched: + for i in remaining: tx = acc_rows[i] if _f4_tx_code(tx) != "G" or i not in local_gift_corrections: continue @@ -976,7 +984,8 @@ def _f4_conversion_targets( 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) - return [i for i in matched if i not in independent_gifts] + unclaimed = [i for i in remaining if i not in independent_gifts] + return unclaimed if removed_addition else unclaimed or remaining def _f4_accession_note_texts( @@ -984,7 +993,7 @@ def _f4_accession_note_texts( ledger: list[dict], non_sell_histories: list[list[dict]], remark_conversions: list[str], - filing_denies_gift_additions: bool, + 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] @@ -1013,9 +1022,14 @@ def _f4_accession_note_texts( if _f4_tx_code(tx) == "G" } linked_gift_denials: set[int] = set() - for sentence, refs in note_rows.values(): + 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: + linked_gift_denials.update(i for i in refs if _f4_matches_num_set(acc_rows[i].get("shares"), {shares})) + for sentence, refs in note_rows.values(): if len(refs) == 1: i = next(iter(refs)) if i in local_gift_notes: @@ -1029,7 +1043,6 @@ def _f4_accession_note_texts( if any(_F4_ROW_GIFT_ADDITION_RE.fullmatch(sentence) for sentence in sentences): local_gift_additions[i] = not ( corrections - or filing_denies_gift_additions or i in linked_gift_denials or any( _F4_ROW_GIFT_ADDITION_DENIAL_RE.match(sentence) @@ -1096,7 +1109,7 @@ def _f4_resolve_accession_intents( ledger, non_sell_histories, remark_conversions, - filing_denies_gift_additions=any(_F4_ROW_GIFT_ADDITION_DENIAL_RE.match(sentence) for sentence in other_remarks), + other_remarks, ) prior_disclosures = [ any(not match["negated"] for match in _F4_PRIOR_DISCLOSURE_RE.finditer(text)) for text in row_texts From 3cff6bc7306e623bfa225d46288ae2aed3fa6cec Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 23:15:42 +0800 Subject: [PATCH 33/37] fix(risk): retain independently reported Form 4 gifts --- tests/test_risk_screening.py | 79 ++++++++++++++++++++++++++++++++++++ tools/risk_screening.py | 56 +++++++++++++++++-------- 2 files changed, 117 insertions(+), 18 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 1c9b85d..0b98867 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -2979,6 +2979,7 @@ def test_form4_shared_conversion_preserves_independently_corrected_gift(monkeypa ("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( @@ -3023,6 +3024,39 @@ def test_form4_shared_conversion_preserves_independently_added_gift( 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 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) + + @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 @@ -3056,6 +3090,23 @@ def test_form4_shared_conversion_respects_independent_gift_addition_and_correcti 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): @@ -3572,6 +3623,34 @@ def test_form4_native_gift_corrections_preserve_revision_history(monkeypatch): 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"]}, + ) + for linked_filing, uncertain in (("2026-11-22", False), ("2026-11-21", False), (None, True)): + follow_up = dict( + added, + accession="0000000123-26-000003", + filing_date="2026-11-23", + original_filing_date=linked_filing, + shares=120, + footnotes={"F1": "Corrects this gift from 100 shares to 120 shares."}, + ) + result = _screen_form4_cli(monkeypatch, [*sales, original, follow_up, added]) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == 6 + assert check["count_uncertain"] is uncertain, linked_filing + assert result["veto_buy"] is (not uncertain), 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) diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 0f7fd8e..43e8406 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -409,10 +409,13 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: _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_REPORT_CONTEXT = ( - r"(?:\s+from\s+(?:the\s+)?(?:report(?:ing)? person's\s+)?" +_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})?)?" + 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( @@ -515,7 +518,8 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: re.IGNORECASE, ) _F4_PREVIOUSLY_REPORTED_GIFT_RE = re.compile( - rf"(?:the )?({_F4_DECLARED_NUMBER})-share gift (?:was|is) (?:previously|originally|already) (?:reported|disclosed)", + rf"(?:the )?({_F4_DECLARED_NUMBER})-share gift (?:was|is) (?:previously|originally|already) (?:reported|disclosed)" + rf"(?:\s+in\s+{_F4_ROW_FILING_REFERENCE})?", re.IGNORECASE, ) _F4_RESTORE_SELL_RE = re.compile( @@ -1061,6 +1065,9 @@ def _f4_accession_note_texts( 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: @@ -1089,7 +1096,7 @@ 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]]: +) -> 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 @@ -1111,6 +1118,7 @@ def _f4_resolve_accession_intents( 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 ] @@ -1147,7 +1155,7 @@ def _f4_resolve_accession_intents( 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 + 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))) @@ -1170,7 +1178,7 @@ def _f4_resolve_accession_intents( 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 + return row_intents, ambiguous, row_texts, unresolved_conversions, independent_gift_additions if ( len(remarks_parts) <= 1 and covering_declaration is not None @@ -1197,24 +1205,30 @@ def _f4_resolve_accession_intents( if any(sig in ledger[i]["sigs"] for i in pool): break else: - return [(True, False)] * len(acc_rows), ambiguous, row_texts, unresolved_conversions + 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 + 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 + 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 + 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 + return row_intents, ambiguous, row_texts, unresolved_conversions, independent_gift_additions def _f4_make_ledger_entry(tx: dict, *, from_orig: bool) -> dict: @@ -1472,7 +1486,7 @@ def _f4_prior_reclassified_gifts( 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]], + 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]]]: @@ -1500,7 +1514,7 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: 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 in acc_non_sells: + 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") @@ -1534,6 +1548,10 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: 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: + # Row-local addition evidence takes precedence over an identical earlier gift. + acc_added_non_sells.append(tx) + 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) @@ -2271,18 +2289,20 @@ def _mark_uncertain(tx: dict) -> None: _mark_uncertain(tx) for _acc, acc_rows in sorted_acc_items: - intents, ambig_flags, row_texts, unresolved_conversions = _f4_resolve_accession_intents( - acc_rows, ledger, non_sell_histories + 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]] = [] + 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)) + 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( From 6bad3cc557ded698221a4e407b79ba47a7dd648c Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 23:31:49 +0800 Subject: [PATCH 34/37] fix(risk): match gift revisions to their cited filings --- tests/test_risk_screening.py | 82 ++++++++++++++++++++++++++++++++++++ tools/risk_screening.py | 59 ++++++++++++++++++++++++-- 2 files changed, 138 insertions(+), 3 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 0b98867..3392e4c 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -3028,6 +3028,7 @@ def test_form4_shared_conversion_preserves_independently_added_gift( "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), @@ -3057,6 +3058,41 @@ def test_form4_prior_gift_disclosure_with_filing_reference(monkeypatch, remark, assert result["veto_buy"] is (expected_sales == 6) +@pytest.mark.parametrize("restate_prior_gift", [False, True]) +def test_form4_dated_disclosure_identifies_the_reported_gift(monkeypatch, restate_prior_gift): + 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-19", + transaction_date="2026-11-18", + 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 19, 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"] == 6 + assert check["count_uncertain"] is False + assert result["veto_buy"] is True + + @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 @@ -3651,6 +3687,52 @@ def test_form4_explicit_gift_addition_preserves_identical_original(monkeypatch): assert result["veto_buy"] is (not uncertain), linked_filing +@pytest.mark.parametrize("repeat_filing", ["2026-11-22", "2026-11-23"]) +def test_form4_repeated_dated_gift_omission_preserves_one_history(monkeypatch, repeat_filing): + 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"], + ) + 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."}, + ) + result = _screen_form4_cli(monkeypatch, [*sales, 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_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) diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 43e8406..31375a0 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -519,7 +519,7 @@ def check_hk_disclosures(symbol: str, *, run=None) -> dict: ) _F4_PREVIOUSLY_REPORTED_GIFT_RE = re.compile( rf"(?:the )?({_F4_DECLARED_NUMBER})-share gift (?:was|is) (?:previously|originally|already) (?:reported|disclosed)" - rf"(?:\s+in\s+{_F4_ROW_FILING_REFERENCE})?", + rf"(?:\s+(?:in|on)\s+{_F4_ROW_FILING_REFERENCE})?", re.IGNORECASE, ) _F4_RESTORE_SELL_RE = re.compile( @@ -992,6 +992,27 @@ def _f4_conversion_targets( 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]] +) -> 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}) + } + # 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], @@ -1032,7 +1053,14 @@ def _f4_accession_note_texts( elif prior_gift := _F4_PREVIOUSLY_REPORTED_GIFT_RE.fullmatch(sentence): shares = _safe_float(prior_gift[1].replace(",", "")) if shares is not None: - linked_gift_denials.update(i for i in refs if _f4_matches_num_set(acc_rows[i].get("shares"), {shares})) + 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) + ) for sentence, refs in note_rows.values(): if len(refs) == 1: i = next(iter(refs)) @@ -1549,7 +1577,32 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: # A quantity match cannot stand in for the unresolved footnote. continue if independent_gift_addition and is_explicit_add: - # Row-local addition evidence takes precedence over an identical earlier gift. + addition_notes = {sentence for sentence in sentences if _F4_ROW_GIFT_ADDITION_RE.fullmatch(sentence)} + # An unchanged omission claim can refer to an older filing than the linked amendment. + if has_identity and len(addition_notes) == 1 and orig_date: + date_ref = _F4_ROW_ADDITION_FILING_DATE_RE.search(next(iter(addition_notes))) + omitted_from = _f4_declared_filing_date(date_ref[1]) if date_ref else None + if 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( + str(rev.get("form") or "").upper() == "4/A" + and rev.get("filing_date") == orig_date + 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(tx) + 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(tx) continue is_sale_conversion = explicit_sale_conversion or (is_corr and bool(_F4_SALE_TO_NONSELL_RE.search(rtext))) From 3127437d8e577b18a94c61d40e04579e81ae9563 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Fri, 27 Nov 2026 23:38:55 +0800 Subject: [PATCH 35/37] fix(risk): require prior omission evidence for gift restatements --- tests/test_risk_screening.py | 35 +++++++++++++++++++++++++ tools/risk_screening.py | 50 +++++++++++++++++++----------------- 2 files changed, 61 insertions(+), 24 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 3392e4c..5a5718f 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -3733,6 +3733,41 @@ def test_form4_repeated_dated_gift_omission_preserves_one_history(monkeypatch, r assert result["veto_buy"] is True +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."}, + ) + for linked_filing in (None, "2026-11-21", "2026-11-23"): + result = _screen_form4_cli( + monkeypatch, [*sales, original, restatement, added, dict(correction, original_filing_date=linked_filing)] + ) + check = result["checks"]["insider_trades"] + assert check["sales_90d"] == 6 + assert check["count_uncertain"] is (linked_filing is None) + assert result["veto_buy"] is (linked_filing is not None) + + 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) diff --git a/tools/risk_screening.py b/tools/risk_screening.py index 31375a0..f59df41 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -1578,32 +1578,34 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: 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 + 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 len(addition_notes) == 1 and orig_date: - date_ref = _F4_ROW_ADDITION_FILING_DATE_RE.search(next(iter(addition_notes))) - omitted_from = _f4_declared_filing_date(date_ref[1]) if date_ref else None - if 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( - str(rev.get("form") or "").upper() == "4/A" - and rev.get("filing_date") == orig_date - 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(tx) - acc_orig_ns_matched.add(target) - continue - if linked_gifts: - mark_uncertain(tx) - continue + 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(tx) + 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): From 08f14113c0bae79d01bb55d3c83c030c213bbf4a Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Sat, 28 Nov 2026 10:49:21 +0800 Subject: [PATCH 36/37] fix(risk): reconcile cited gift disclosures consistently --- tests/test_risk_screening.py | 192 +++++++++++++++++++++++++++++------ tools/risk_screening.py | 21 +++- 2 files changed, 179 insertions(+), 34 deletions(-) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 5a5718f..829de54 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -3058,8 +3058,18 @@ def test_form4_prior_gift_disclosure_with_filing_reference(monkeypatch, remark, assert result["veto_buy"] is (expected_sales == 6) -@pytest.mark.parametrize("restate_prior_gift", [False, True]) -def test_form4_dated_disclosure_identifies_the_reported_gift(monkeypatch, restate_prior_gift): +@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) @@ -3067,8 +3077,8 @@ def test_form4_dated_disclosure_identifies_the_reported_gift(monkeypatch, restat prior = _form4_sale( 100, accession="0000000123-26-000004", - filing_date="2026-11-19", - transaction_date="2026-11-18", + filing_date="2026-11-20", + transaction_date=prior_transaction_date, transaction_code="G", price=None, ) @@ -3077,7 +3087,7 @@ def test_form4_dated_disclosure_identifies_the_reported_gift(monkeypatch, restat "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 19, 2026.", + "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"]}) @@ -3088,9 +3098,57 @@ def test_form4_dated_disclosure_identifies_the_reported_gift(monkeypatch, restat for ordered in permutations(rows): result = _screen_form4_cli(monkeypatch, [*originals, prior, *ordered]) check = result["checks"]["insider_trades"] - assert check["sales_90d"] == 6 - assert check["count_uncertain"] is False - assert result["veto_buy"] is True + assert check["sales_90d"] == expected_sales + assert check["count_uncertain"] is count_uncertain + assert result["veto_buy"] is (not count_uncertain) + + +@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) @pytest.mark.parametrize("conversion_date, expected_sales", [("2026-11-20", 6), ("2026-11-17", 7)]) @@ -3671,24 +3729,46 @@ def test_form4_explicit_gift_addition_preserves_identical_original(monkeypatch): footnotes={"F1": "This gift was unreported."}, footnote_refs={"transactionAmounts/transactionShares/value": ["F1"]}, ) - for linked_filing, uncertain in (("2026-11-22", False), ("2026-11-21", False), (None, True)): - follow_up = dict( - added, - accession="0000000123-26-000003", - filing_date="2026-11-23", - original_filing_date=linked_filing, - shares=120, - footnotes={"F1": "Corrects this gift from 100 shares to 120 shares."}, - ) - result = _screen_form4_cli(monkeypatch, [*sales, original, follow_up, added]) + 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 uncertain, linked_filing - assert result["veto_buy"] is (not uncertain), linked_filing + 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", ["2026-11-22", "2026-11-23"]) -def test_form4_repeated_dated_gift_omission_preserves_one_history(monkeypatch, repeat_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", @@ -3707,6 +3787,7 @@ def test_form4_repeated_dated_gift_omission_preserves_one_history(monkeypatch, r 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, @@ -3726,13 +3807,52 @@ def test_form4_repeated_dated_gift_omission_preserves_one_history(monkeypatch, r shares=130, footnotes={"F1": "Corrects this gift from 120 shares to 130 shares."}, ) - result = _screen_form4_cli(monkeypatch, [*sales, corrected_again, corrected, repeated, added]) + 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") + 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) @@ -3758,14 +3878,28 @@ def test_form4_dated_gift_addition_does_not_merge_with_a_plain_restatement(monke shares=120, footnotes={"F1": "Corrects this gift from 100 shares to 120 shares."}, ) - for linked_filing in (None, "2026-11-21", "2026-11-23"): - result = _screen_form4_cli( - monkeypatch, [*sales, original, restatement, added, dict(correction, original_filing_date=linked_filing)] - ) + 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 is None) - assert result["veto_buy"] is (linked_filing is not None) + 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): diff --git a/tools/risk_screening.py b/tools/risk_screening.py index f59df41..a13fdad 100644 --- a/tools/risk_screening.py +++ b/tools/risk_screening.py @@ -993,7 +993,7 @@ def _f4_conversion_targets( def _f4_disclosed_gift_matches( - tx: dict, shares: float, reported_filing: str | None, non_sell_histories: list[list[dict]] + 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 @@ -1009,6 +1009,15 @@ def _f4_disclosed_gift_matches( 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 @@ -1059,7 +1068,7 @@ def _f4_accession_note_texts( 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) + 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: @@ -1321,7 +1330,7 @@ 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))) + 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) @@ -1581,6 +1590,8 @@ def prefer_active_sales(candidates: list[int], text: str) -> list[int]: 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. @@ -1922,10 +1933,10 @@ 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 in entry["gift_sigs"] if fd == 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 in entry["gift_sigs"]) + return any(gsig == sig for _fd, gsig, _code in entry["gift_sigs"]) if use_history: cands = [ From 1e51755394246eee797aede0a773c164a1d67c09 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Sat, 28 Nov 2026 11:39:51 +0800 Subject: [PATCH 37/37] test(risk): verify Form 4 gift history and uncertainty --- tests/test_risk_screening.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/tests/test_risk_screening.py b/tests/test_risk_screening.py index 829de54..d9f2ea2 100644 --- a/tests/test_risk_screening.py +++ b/tests/test_risk_screening.py @@ -3058,6 +3058,24 @@ def test_form4_prior_gift_disclosure_with_filing_reference(monkeypatch, remark, 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", [ @@ -3101,6 +3119,8 @@ def test_form4_dated_disclosure_identifies_the_reported_gift( 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)]) @@ -3149,6 +3169,10 @@ def test_form4_dated_disclosure_identifies_a_reclassified_gift(monkeypatch, cite 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)]) @@ -3836,6 +3860,12 @@ def test_form4_same_day_omissions_of_identical_gifts_remain_uncertain(monkeypatc 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",