stock-analysis-plugin 0.2.5 → 0.2.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +126 -15
- package/package.json +2 -1
- package/pi/index.ts +918 -72
- package/schemas/market_review_schema.json +12 -5
- package/schemas/report_schema.json +68 -4
- package/scripts/cli-timeout.mjs +27 -0
- package/scripts/json-input.mjs +26 -0
- package/scripts/setup-python.mjs +6 -6
- package/skills/bull-trend/SKILL.md +34 -10
- package/skills/bull-trend/references/fat-tails.md +91 -0
- package/skills/bull-trend/scripts/tail_analysis.py +132 -0
- package/skills/event-driven/SKILL.md +6 -0
- package/skills/growth-quality/SKILL.md +6 -0
- package/skills/market-review/SKILL.md +2 -0
- package/skills/stock-analysis/SKILL.md +25 -5
- package/skills/stock-analysis/references/stateless-analysis.md +66 -0
- package/skills/stock-screener/SKILL.md +7 -1
- package/skills/strategy-backtest/SKILL.md +13 -0
- package/skills/wisburg-research/SKILL.md +2 -0
- package/templates/market_review/full.md.j2 +7 -0
- package/templates/stock_analysis/_evidence.md.j2 +11 -0
- package/templates/stock_analysis/brief.md.j2 +6 -1
- package/templates/stock_analysis/full.md.j2 +8 -3
- package/tools/_subproc.py +66 -11
- package/tools/alert_rules.py +32 -4
- package/tools/backtest.py +95 -18
- package/tools/capabilities.py +11 -0
- package/tools/cli_budgets.json +26 -0
- package/tools/gather.py +24 -16
- package/tools/lixinger.py +100 -0
- package/tools/market_regime.py +7 -3
- package/tools/market_review.py +37 -15
- package/tools/position_context.py +20 -2
- package/tools/report_renderer.py +2 -0
- package/tools/risk_screening.py +45 -17
- package/tools/screener.py +74 -24
- package/tools/sec_edgar.py +346 -0
- package/tools/sec_holders.py +263 -0
- package/tools/signal_tracker.py +218 -24
- package/tools/stateless_analysis.py +630 -0
- package/tools/stock_data.py +170 -32
- package/tools/technical.py +16 -2
- package/tools/value_data.py +159 -0
- package/tools/watchlist.py +24 -1
- package/tools/watchlist_context.py +25 -10
|
@@ -5,6 +5,18 @@ description: 综合股票分析:联合技术、基本面、资金、消息和
|
|
|
5
5
|
|
|
6
6
|
# 综合股票分析
|
|
7
7
|
|
|
8
|
+
在启用原生工具发现的 Pi 中,所需工具尚未暴露时,先用 `tool_search` 搜索确切工具名或英文关键词,再按本文流程调用;其搜索器目前不对中文分词。旧 Pi 或其他宿主按当前实际提供的工具直接执行。
|
|
9
|
+
|
|
10
|
+
在 dsh 提供 `stock_tool_search` 且所需工具尚未暴露时,先搜索中文功能关键词或确切工具名,加载后按原名调用;搜索不执行分析。没有发现入口时直接使用当前提供的工具。
|
|
11
|
+
|
|
12
|
+
美股机构研究调用 `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` 时不能将旧记录当作已完整检索。存在修订先读原文,不能自动推断变化。
|
|
13
|
+
|
|
14
|
+
美股内部人研究调用 `get_insider_trades(symbol, days=90, top=10)`,需设置含真实联系邮箱的 `SEC_USER_AGENT`。`days` 按申报日期过滤,`top` 限制文件数;只将代码 P/S 视作买卖信号,授予、行权、赠与等保留原始代码和脚注,衍生品单列。Form 4/A 与原申报勿重复计算,检查截断和失败提示;`screen_risk` 仍仅支持 A 股。
|
|
15
|
+
|
|
16
|
+
## 无状态分析扩展
|
|
17
|
+
|
|
18
|
+
当用户要求同行比较、组合风险、仓位预算或新旧分析比较时,MUST 读取[无状态研究工具](references/stateless-analysis.md),分别使用 compare_stocks、analyze_portfolio_risk、calculate_position_size、compare_analysis_snapshots。所有用户状态均由本次输入提供。
|
|
19
|
+
|
|
8
20
|
## 意图路由表
|
|
9
21
|
|
|
10
22
|
快速问答先判断意图,按下表走最短调用链;完整综合研判走下方执行流程(gather 采集管线),不受此表限制。单工具可答的问题按各工具描述中的适用场景选择,本表不再重复。
|
|
@@ -22,16 +34,18 @@ description: 综合股票分析:联合技术、基本面、资金、消息和
|
|
|
22
34
|
|
|
23
35
|
### 第一步:采集数据
|
|
24
36
|
|
|
25
|
-
|
|
37
|
+
运行数据采集脚本(并行采集行情、K 线、财务、资金、筹码、新闻、舆情、风险和大盘状态;技术指标复用本次 K 线计算):
|
|
26
38
|
|
|
27
39
|
```bash
|
|
28
40
|
python3 scripts/gather.py <symbol>
|
|
29
41
|
```
|
|
30
42
|
|
|
31
|
-
解析返回的 JSON 数据。如果某个字段为 `null
|
|
43
|
+
解析返回的 JSON 数据。如果某个字段为 `null` 或包含 `error`,表示该数据不可用,基于可用数据继续分析。大盘状态按股票所属市场查询;日/韩/台市场暂不支持,标明缺失,不能套用 A 股状态。
|
|
32
44
|
|
|
33
45
|
解读实时行情前先调 `get_trading_phase` 确认该市场当前盘中阶段(盘前/早盘/午间休市/午盘/交易中/盘后/休市),避免把休市时的静态快照当作盘中信号解读。
|
|
34
46
|
|
|
47
|
+
港股 `get_quote` 自动按 yfinance → 腾讯 → finnhub → longbridge 容灾,腾讯无需 API key,使用 `r_hk` 实时报价通道(`hk` 通道延迟约 15 分钟)。腾讯港股成交量为股,成交额及市值为港元;PB、换手率、量比为 null 时按缺失处理。该备用源只覆盖报价,K 线仍走原链路。
|
|
48
|
+
|
|
35
49
|
### 第二步:综合研判
|
|
36
50
|
|
|
37
51
|
根据获取的数据进行多维度分析:
|
|
@@ -60,24 +74,26 @@ python3 scripts/gather.py <symbol>
|
|
|
60
74
|
|
|
61
75
|
**风险筛查**:
|
|
62
76
|
- 7维度风险标记(估值极端/技术预警/解禁到期/内部人减持/业绩预警/监管处罚/行业政策)
|
|
63
|
-
- 风险评级(low/medium/high)和一票否决(veto_buy
|
|
77
|
+
- 风险评级(low/medium/high/unknown)和一票否决(veto_buy);查看 data_complete、warnings,unknown 或 null 表示缺少数据,不能据此判定低风险或已通过检查
|
|
64
78
|
- 如果 veto_buy=true,必须在报告中醒目提示
|
|
65
79
|
|
|
66
80
|
### 第三步:渲染研报
|
|
67
81
|
|
|
68
82
|
1. 按 [报告 schema](../../schemas/report_schema.json) 构建结构化报告。
|
|
69
|
-
2. 每个结论只使用成功返回的数据;缺失维度在 `risk_warning`
|
|
83
|
+
2. 每个结论只使用成功返回的数据;缺失维度在 `risk_warning` 中说明影响。必须填写 `evidence`,每项使用原始工具结果路径(如 `get_quote.price`)、读者可理解的 `label`、原始 `value`、实际 `source` 和数据时间 `as_of`;未知来源或时间填 null,不用采集时间替代。历史财报与顶层快照分别引用日期、币种和单位,不把不同期间的数值拼成同一结论。 来源与时间沿证据 path 继承最近父对象的 source(该键缺失时用 snapshot_source)和 data_as_of,子对象的对应值(包括显式 null)覆盖祖先;数组项及 warnings 字符串同样继承,不能仅因叶子字段没有来源就填 null。整条路径均未提供对应元数据时才填 null,不能用工具名或策略方法名代替来源;as_of 保留完整数据时间及其时区。report_date 是财报报告期,应单独引用 value,不能当成披露日期或 data_as_of。证据 path 不含调用参数,例如 get_financials.periods.0.roe;股票名称未返回时 stock_name 填“未知”,不能凭常识补名;已知返回对象中未提供的末级字段可用 value=null 表示未知,其 source/as_of 可填 null,若填写则必须来自已知父对象;不能编成空数组、字符串或数值,不能跨缺失对象或数组编造路径;错误 value 保留原始字符串,不加 error: 前缀。请求的期间或文件路径不证明实际数据覆盖期或文件内容,需与实际返回数据区分。
|
|
84
|
+
同时填写 `data_quality.flags/limitations`:关键数据缺失用 `partial_data`,明确过期行情用 `stale_quote`,同期间同口径来源冲突用 `conflicting_data`,回测/信号样本不足用 `insufficient_sample`。出现这些限制时降低置信度,不能给出 strong_buy;没有有效现价时不编造数值交易计划。数据完整时 flags 为空数组,限制仍按实际模拟条件说明。
|
|
70
85
|
3. 调用 `render_stock_report`:快速问答用 `brief`,完整研判用 `full`。
|
|
71
86
|
4. 输出渲染后的 Markdown;只在用户要求机器可读数据时附加结构化 JSON。
|
|
72
87
|
|
|
73
88
|
## 信号跟踪闭环
|
|
74
89
|
|
|
75
90
|
- 给出明确买卖建议(方向 + 入场价/目标价/止损价)时,调 `record_signal` 存档,`source` 填触发该建议的 skill 名(如 `stock-analysis`、`dragon-head`)。
|
|
76
|
-
- 后续会话用 `evaluate_signals` 结算到期信号(target_hit/stop_hit/timeout 并回写收益),用 `get_signal_summary`
|
|
91
|
+
- 后续会话用 `evaluate_signals` 结算到期信号(target_hit/stop_hit/timeout 并回写收益),用 `get_signal_summary` 复盘胜率与平均收益(可按 source/symbol/status 过滤),同时报告 `return_samples/sample_warning`,缺失收益不按零计;这些是观察性建议记录,不是扣除成本的策略回测。
|
|
77
92
|
- 信号持久化在本地 JSONL(`$STOCK_SIGNAL_STORE` 或 `~/.stock-analysis/signals.jsonl`);是否记录由宿主 Agent 决定,不阻塞报告输出。
|
|
78
93
|
|
|
79
94
|
## 注意事项
|
|
80
95
|
- `get_kline` 的 A 股股票/ETF 数据为前复权,每条记录 `adjusted="qfq"`;显式指数 `sh000xxx` / `sz399xxx` 为原始点位,`adjusted="none"`。复权数据源全部失败时说明数据缺失,不用未复权价格补算指标或信号。
|
|
96
|
+
- 行情读取 `source/fetched_at/data_as_of`,`fetched_at` 是 UTC 采集时间;`as_of_basis=trading_calendar` 是日历推断,不能声称是提供方报价时间。提供方时间未知时明确说明时效性未核实。
|
|
81
97
|
- 始终提供风险提示
|
|
82
98
|
- 不做绝对化的涨跌预测
|
|
83
99
|
- 建议用户结合自身风险偏好做决策
|
|
@@ -106,3 +122,7 @@ python3 scripts/gather.py <symbol>
|
|
|
106
122
|
get_shareholder_structure 的 northbound 优先使用沪深官方季度总量;northbound_nominee 只是十大股东推断,不能混同。get_etf_details 的 basket 是完整已发布 PCF,对价数量/现金替代规则不是基金实际持仓或NAV权重。HK 股息排行使用 get_dividends(mode=ranking, market=HK),年度口径不能称 TTM。
|
|
107
123
|
|
|
108
124
|
实际披露股票持仓可用 get_etf_details(include_full_holdings=true) 获取半年度/年度表;按 as_of 解释,数量为股、市值为人民币元。默认不取大量明细;不是实时全资产组合,不与 PCF 对价数量混同。
|
|
125
|
+
|
|
126
|
+
信号价格使用原始报价口径。复权 K 线需有记录日的可核实 adjustment_factor,才能换算入场/目标/止损及收益;缺失时 skipped_price_basis 并保持未结算,不得猜测拆股或除权比例。evaluate_signals 返回 complete/deferred/warnings;预算耗尽时已完成结果保存,未处理记录下次重试。当前仅日线 Tushare、Alpha Vantage 提供可验证换算系数,其余复权来源可能跳过结算。
|
|
127
|
+
|
|
128
|
+
自选股上下文异动检查失败时 anomaly_status=unavailable、anomaly_count=null,并提供 anomaly_error/warnings;summary.partial 不得写成无异常或完整成功。
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# 无状态研究工具
|
|
2
|
+
|
|
3
|
+
这些工具在一次调用中计算,不维护自选股、账户、规则或历史。宿主/用户显式提供本次持仓、历史快照与正文。采集继续用已有行情、财务、公告工具。MUST 从原始结果取值、保留来源和时点;MUST NOT 补造缺失值、股票池或持仓。缺少必需输入时只索取该输入。
|
|
4
|
+
|
|
5
|
+
## 同行比较:compare_stocks
|
|
6
|
+
|
|
7
|
+
1. 确定用户提供或有明确行业依据的可比股票,调用 get_financials/get_quote/get_stock_info;必要时 resolve_stock_sectors。不要用全市场估值直接代替同行。
|
|
8
|
+
2. 传 `companies`(2..30项),每项 `{symbol, period, metrics}`。`metrics` 每项 `{name, value, unit, basis, source?}`,缺失 value=null。`period` 是指标的共同报告期或估值日;同一公司不同期间的指标应分批比较。
|
|
9
|
+
3. 核实单位。A 股 roe/net_profit_margin/gross_margin 可能是百分数,而 Yahoo roe/profit_margin 是小数;只有确定源口径时才换算并记录依据。金额单位必须含币种。不同年度、TTM 与单季、合并与母公司报表分开。
|
|
10
|
+
4. 工具只有 unit/basis/period 完全一致且至少两项有效数值时返回 ascending。它表示升序,MUST NOT 称为买入排名。亏损 PE、负 PB 和行业特有口径需另行说明,不按“越低越好”解释。
|
|
11
|
+
|
|
12
|
+
## 公告财报比较:analyze_disclosure_changes
|
|
13
|
+
|
|
14
|
+
传 `previous/current`,每项 `{text, source, period, metrics}`;正文上限200000字符,metrics 形状同上(可为空),`max_changes` 默认30、上限100。
|
|
15
|
+
|
|
16
|
+
先查询原始公告;HTML 可用 extract_article,但它默认截断正文,不能将其结果自动视为全文。PDF/OCR 由宿主文档读取能力或用户提供,MUST NOT 把标题、链接或搜索摘要冒充全文。缺少正文时仍可分析已核实的财务指标,但不要调用要求正文的比较工具。
|
|
17
|
+
|
|
18
|
+
工具输出精确到传入文本行号的变化片段、来源、截断标志和指标差异。文本差异本身不等于经营变化;Agent 要阅读上下文,说明发生了什么、与原预期的关系和可能反证,并引用原文。金额单位和 basis 一致才计算 delta;前期值大于0才计算普通增长率,亏损转盈另述。报告期可不同,但必须核实是可比同长期间(年度/同比单季等),累计季度不能直接当单季。
|
|
19
|
+
|
|
20
|
+
## 组合风险:analyze_portfolio_risk
|
|
21
|
+
|
|
22
|
+
输入 `base_currency`、基准币种 `cash>=0`、`positions`(1..100项)。持仓 `{symbol, quantity, price, currency, cost?, stop_price?, sector?, as_of?}`,现货多头;重复标的先汇总。价格/数量为正,单位由调用方确认。
|
|
23
|
+
|
|
24
|
+
可选 `fx_rates:[{currency,rate}]`,rate 表示一单位非基准币种兑换多少基准币种;基准币种隐含1,禁止重复。缺汇率不能部分汇总冒充总资产。相同币种现金先换成基准币种再输入;其他币种现金可按现金类头寸单独注明,不能当股票计算相关性。
|
|
25
|
+
|
|
26
|
+
输出总权益、现金权重、单股权重、行业/币种敞口和持仓 HHI(不含现金项)。`price_pnl_base` 是按当前汇率折算的本币价格盈亏,MUST NOT 称为包含汇兑损益的账户真实收益;缺任何成本时为null。`stop_loss_risk_base` 是从现价到止损的损失情景,缺任何止损时为null,不保证成交。
|
|
27
|
+
|
|
28
|
+
可选 `histories:[{symbol,prices:[{date,close}]}]`,工具按每对标的共同日期计算收益相关性;至少4个共同价格点、存在波动才有结果。不是组合收益率或汇率调整后的相关性;少样本、跨时区非同步收盘和缺交易日都应说明,不从相关性推断因果。缺历史时明确相关性未计算。
|
|
29
|
+
|
|
30
|
+
## 仓位预算:calculate_position_size
|
|
31
|
+
|
|
32
|
+
必需 `equity,cash,entry_price,stop_price,risk_fraction,lot_size`。风险比例0..1,止损正且低于入场价,现金0..equity,交易单位正整数。所有金额同币种。
|
|
33
|
+
|
|
34
|
+
可选 `max_position_fraction=1`(0..1)、`fee_rate=0` 与 `slippage_rate=0`(每边比例0..0.1)。买入现金按 entry×(1+slippage)×(1+fee),止损回收按 stop×(1-slippage)×(1-fee);每股差额计入风险预算。现金、风险和本次最大买入资金分别向下取整到lot,取最小数量。已有同股持仓时,先扣减用户允许的新增仓位和风险额度,不能把本次额度当成最终账户仓位限制。
|
|
35
|
+
|
|
36
|
+
lot_size 来自用户或可核实交易规则,尤其港股不能统一猜100股。工具不覆盖券商最低收费、未提供税费、跳空和流动性风险。quantity=0 表示当前约束下不足一个交易单位,MUST NOT 向上凑整。
|
|
37
|
+
|
|
38
|
+
## 事件研究:analyze_event_study
|
|
39
|
+
|
|
40
|
+
通常直接传 `symbol,benchmark,start_date,end_date,event_dates`,由共享 Python 核心取数,避免模型复述整段K线。股票与基准应属于同一市场;代码模式输出实际覆盖区间和提供方复权标记,没有标记时明确未指定,不用调用方猜测覆盖。开始日期须覆盖事件前一交易日、结束日期须覆盖最长事件窗口。也可使用下面的显式价格模式,两种模式互斥。
|
|
41
|
+
|
|
42
|
+
传 `prices,benchmark_prices`(各2..20000条 `{date:"YYYY-MM-DD",close}`)、`event_dates`(1..100个唯一日期)、`price_basis`(明确股票与基准各自复权口径)。可选 `horizons`(1..20个0..250整数,默认0/1/5/10/20)。复用 get_kline,先核实数据覆盖事件前一交易日至最大窗口结束。
|
|
43
|
+
|
|
44
|
+
事件日映射到股票序列中不早于指定日期的首日;盘后事件应显式使用下一交易日。基点是该日前一个股票交易日收盘;horizon=0表示事件当日收盘。基准必须同市场,并在两个端点都有数据,缺失时不移动事件日期。收益差是股票与基准各自买入持有收益的差(百分点),不等于因果影响。
|
|
45
|
+
|
|
46
|
+
MUST 核实完整交易日、复权、币种和股息处理。工具无法从缺行判断是停牌、节假日还是数据故障。重叠事件标识意味着样本不独立;少样本均值不能作为稳定预测。
|
|
47
|
+
|
|
48
|
+
## 回测稳健性:validate_backtest
|
|
49
|
+
|
|
50
|
+
通常传 `symbols:[代码],start_date,end_date,strategies`,Python 直接复用现有 K 线获取;不要让模型抄写数千条行情。也可使用下面的显式 datasets 模式,两种模式互斥。读取每个标的 data_coverage,实际覆盖不足时缩小结论范围;提供方未标记价格口径时须说明。代码模式共享CLI预算660秒、事件研究300秒,宿主另留退出余量。
|
|
51
|
+
|
|
52
|
+
传 `datasets`(1..5项 `{symbol,price_basis,bars}`,bars 是按日期升序的 date/open/high/low/close/volume,每组最多2000条)、`strategies`(1..5项 `{name,strategy}`,完整既有DSL的JSON对象)。可选 `train_bars=126,test_bars=63`(各30..1000)、`capital=1000000`。每组至少训练+测试长度。
|
|
53
|
+
|
|
54
|
+
通过现有 get_kline 取完整数据,读取用户策略后转换为JSON;parameters 引用复用现有引擎解析。候选应事先确定,只在用户要求优化时扩展候选,MUST NOT 看测试窗口收益后反复改参数并仍称样本外。
|
|
55
|
+
|
|
56
|
+
每个标的独立滚动训练,按训练总收益选候选(并列按输入顺序),在其后的非重叠完整测试窗口评估。返回每个候选的训练结果、选中者及测试结果;全区间 sensitivity 是样本内比较。尾部不足完整测试窗口会报告unused_tail_bars。
|
|
57
|
+
|
|
58
|
+
选择使用相同初始资金下的实际 `final_equity`,不使用展示精度舍入后的收益。所有入场/退出条件先校验,未触发的条件也不能绕过检查;坏候选单独返回 error,不中断合法候选。无法定义的 `profit_loss_ratio` 为null,不能当作0;其余数值溢出或无效Unicode输入返回JSON错误。
|
|
59
|
+
|
|
60
|
+
每个窗口从现金和重新初始化的指标开始,不拼成连续组合;MUST NOT 把各窗口年化收益平均当成实际年化。只允许next_open。关注候选错误、交易数和未平仓;收益含未平仓市值,交易统计仅含已平仓。不同标的和不同参数的收益分散程度是稳健性证据,不是自动策略认证。缺少历史股票池、退市样本、公司行为和限价数据时保留原回测限制。
|
|
61
|
+
|
|
62
|
+
## 快照比较:compare_analysis_snapshots
|
|
63
|
+
|
|
64
|
+
传 `previous/current` JSON对象;嵌套字典按JSON Pointer输出变化,数组按整体比较。批量股票应先以symbol构造字典,时间戳/采集耗时等机械字段先按需求排除,避免无意义变化。
|
|
65
|
+
|
|
66
|
+
状态为added/removed/changed/unavailable/recovered。null 或包含error的对象表示不可用;removed只表示键从输入消失,MUST NOT 自动解释为退市、卖出或业务事件。缺少历史输入时仅做当前分析;持久化、调度及通知由宿主负责。
|
|
@@ -5,6 +5,8 @@ description: 全市场股票筛选:按市场、估值、成长、趋势或自
|
|
|
5
5
|
|
|
6
6
|
# 全市场股票筛选
|
|
7
7
|
|
|
8
|
+
显式筛选条件缺少数据时工具返回 `error`,不能把该条件当作已通过。`filters_applied` 只包含实际执行的条件,基于返回的覆盖情况说明候选范围。
|
|
9
|
+
|
|
8
10
|
## 执行流程
|
|
9
11
|
|
|
10
12
|
### 第一步:确定筛选条件
|
|
@@ -64,7 +66,9 @@ python3 tools/screener.py screen --market A --top 20
|
|
|
64
66
|
- 建议结合个股深度分析后再做决策
|
|
65
67
|
```
|
|
66
68
|
|
|
67
|
-
|
|
69
|
+
每个候选必须读取 `factor_coverage.available/missing/ratio/effective_weights`。ratio 是已覆盖因子的原始权重之和;L1 与 L2 的 effective_weights 均按可用因子重归一化,缺失或非有限值不按零分计,排序前先按实际可用因子计算综合分,effective_scores 保留实际参与计算的各组分数;用 sum(effective_scores[g] × effective_weights[g]) × market_sentiment.multiplier 核对 scores.final(四舍五入至一位)。scores.momentum 仍保留 L1 参考值,L2 贡献以 effective_scores.momentum 为准。相同分数但缺失因子不同的候选不能视为同等证据,报告缺失项和覆盖度,不以 `enriched=true` 代替覆盖判断。`scores.final=null` 表示没有足够因子计算,不能作为高分候选推荐。
|
|
70
|
+
|
|
71
|
+
完成标准:列出实际生效的市场、过滤条件、排序口径和候选数量,且推荐理由只使用返回数据,并说明因子覆盖。
|
|
68
72
|
|
|
69
73
|
## 策略模板
|
|
70
74
|
|
|
@@ -91,3 +95,5 @@ dividend_report_date: "2025-12-31"
|
|
|
91
95
|
### 补充数据覆盖
|
|
92
96
|
|
|
93
97
|
股息筛选支持 A/HK:A 股为报告期已实施方案股息率,HK 为 HKEX/LSEG 年度股息率。两者都不是当前价 TTM;使用结果的 yield_basis 和 report_date,缺失不当零。
|
|
98
|
+
|
|
99
|
+
选股的 top 必须为正整数;超时预算按候选数量与采集批次计算。
|
|
@@ -7,6 +7,12 @@ description: 策略回测:定义或读取 AlphaEvo YAML 策略,回测收益
|
|
|
7
7
|
|
|
8
8
|
开始前读取[短线交易决策框架](../stock-analysis/references/short-term-trading.md)的风险单位和回测约束。回测用于反证策略,不把样本内收益包装成预测。
|
|
9
9
|
|
|
10
|
+
解读回测时,`period` 是实际取得的数据期间,`requested_period` 保留用户请求,`warnings` 提示两者差异。年化收益按实际期间计算;覆盖不完整时明确说明,不能声称完成了完整请求期间的验证。买入预算包含佣金,`position.size` 为 0..1 的资金比例。
|
|
11
|
+
|
|
12
|
+
## 无状态分析扩展
|
|
13
|
+
|
|
14
|
+
滚动样本外、参数敏感性或跨标的验证时,MUST 读取[无状态研究工具](../stock-analysis/references/stateless-analysis.md)的 validate_backtest 分支。复用 get_kline,传完整OHLCV和事先确定的DSL候选;样本内sensitivity不等于样本外验证。
|
|
15
|
+
|
|
10
16
|
## 工作流程
|
|
11
17
|
|
|
12
18
|
### 第一步:策略定义
|
|
@@ -40,6 +46,7 @@ exit:
|
|
|
40
46
|
take_profit: 0.15 # 止盈比例
|
|
41
47
|
|
|
42
48
|
simulation:
|
|
49
|
+
execution: next_open # 默认:前日收盘信号,次日开盘成交
|
|
43
50
|
slippage: 0.001 # 滑点(买卖双边),默认 0.001
|
|
44
51
|
commission: 0.00025 # 佣金(买卖双边,券商自定;A股常见万2.5),默认 0.0015
|
|
45
52
|
stamp_tax: 0.0005 # 印花税(仅卖出收;A股 0.05%,其他市场按当下实际费率,无则省略),默认 0
|
|
@@ -68,6 +75,10 @@ python3 tools/backtest.py run <path.yaml> <symbol> --start <date> --end <date>
|
|
|
68
75
|
- `--start` / `--end`:回测时间范围(可选,默认近一年)
|
|
69
76
|
- 初始资金默认 100 万,可用 `--capital` 调整
|
|
70
77
|
|
|
78
|
+
默认 `simulation.execution=next_open`:信号在前一交易日收盘确定,下一有效交易日按开盘价加滑点成交;交易同时保留 `signal_date` 与实际 `date`。最后一天新信号没有后续开盘时不能成交。需要复现旧结果时显式使用 `same_close`,并说明它按信号日收盘成交,可能高估可执行收益。零/缺失成交量(已有 volume 字段时)阻止成交;一字涨跌停仅在输入提供同口径历史 `limit_up/limit_down` 时保守阻止,不猜 ST、IPO 或 ETF 限价。
|
|
79
|
+
|
|
80
|
+
读取 `execution.model/blocked_orders/unfilled_order/limitations` 并说明未成交情况。止损、止盈和移动止损均是收盘信号,不承诺盘中按阈值成交;次日跳空按实际开盘价计算。没有历史限价数据时,不能声称已验证涨跌停可成交性。
|
|
81
|
+
|
|
71
82
|
### 第三步:分析结果
|
|
72
83
|
|
|
73
84
|
回测完成后,按共享框架的风险单位和回测约束解释原始结果。针对本工具:
|
|
@@ -77,6 +88,8 @@ python3 tools/backtest.py run <path.yaml> <symbol> --start <date> --end <date>
|
|
|
77
88
|
- 使用用户指定的互斥日期区间分别运行样本内和样本外回测。
|
|
78
89
|
- 成本假设引用结果中的 `costs` 字段(实际生效的佣金/滑点/印花税费率与实付费用合计),未模拟的费用与成交约束列入限制。
|
|
79
90
|
|
|
91
|
+
趋势策略或用户要求肥尾收益诊断时,读取 [肥尾度量与趋势收益诊断](../bull-trend/references/fat-tails.md)的盈利集中度部分,基于平仓 `pnl` 计算大赢家贡献和删除敏感性。只有用户询问市场收益分布时才进入 κ 分支。
|
|
92
|
+
|
|
80
93
|
未模拟的结算、涨跌停、复权或特定市场费用列入限制,结论限定为该模拟条件下的历史表现。
|
|
81
94
|
|
|
82
95
|
### 第四步:诊断
|
|
@@ -7,6 +7,8 @@ description: 智堡投研检索:查找机构研报、财报公告、电话会
|
|
|
7
7
|
|
|
8
8
|
智堡 MCP 涵盖海外投行研报、国内券商研究、资管报告、央行/政府文献、电话会纪要和财报公告。首先检查这些 MCP 工具是否可用;不可用时直接改用 `search_comprehensive_intel`。
|
|
9
9
|
|
|
10
|
+
港股估值功课调用 `get_valuation_history(symbol, years=10)`;配置 `LIXINGER_TOKEN` 时优先理杏仁非金融公司每日 PE-TTM/PB,失败回退百度。以返回的实际窗口和正值样本计算分位及 Band,不混接同一指标的不同来源,不将缺失解释为低估。
|
|
11
|
+
|
|
10
12
|
## 可用工具
|
|
11
13
|
|
|
12
14
|
智堡 MCP 提供以下工具(通过 `mcp__wisburg-mcp-server__` 前缀调用):
|
|
@@ -4,6 +4,13 @@
|
|
|
4
4
|
{% set t = temperature or {} -%}
|
|
5
5
|
**温度:** {{ m.signal_emoji(t.signal) }} {{ m.fmt_num(t.score, 1) }}/100 | **信号灯:** {{ m.signal_label(t.signal) }} | **策略姿态:** {{ m.stance_label(strategy_stance) }}
|
|
6
6
|
|
|
7
|
+
{% if data_quality and data_quality.limitations -%}
|
|
8
|
+
**数据限制:**
|
|
9
|
+
{% for limitation in data_quality.limitations %}
|
|
10
|
+
- {{ limitation }}
|
|
11
|
+
{% endfor %}
|
|
12
|
+
{%- endif %}
|
|
13
|
+
|
|
7
14
|
{% if regime and (regime.regime_cn or regime.regime) -%}
|
|
8
15
|
> **市场阶段:** {{ regime.regime_cn or regime.regime }}{% if regime.confidence is not none %}(置信度 {{ m.fmt_num(regime.confidence) }}){% endif %}{% if regime.recommended_skills %} | **推荐策略:** {{ regime.recommended_skills | join('、') }}{% endif %}
|
|
9
16
|
{%- endif %}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{% if data_quality or evidence %}
|
|
2
|
+
|
|
3
|
+
### 本次数据与限制
|
|
4
|
+
|
|
5
|
+
{% for item in evidence or [] %}
|
|
6
|
+
- **{{ item.label or '数据依据' }}:** {{ item.value if item.value is not none else '未知' }}(来源:{{ item.source or '未标明' }};数据时间:{{ item.as_of or '未知' }})
|
|
7
|
+
{% endfor %}
|
|
8
|
+
{% for limitation in (data_quality or {}).limitations or [] %}
|
|
9
|
+
- {{ limitation }}
|
|
10
|
+
{% endfor %}
|
|
11
|
+
{% endif %}
|
|
@@ -7,11 +7,14 @@
|
|
|
7
7
|
{% if risk_screening and risk_screening.veto_buy %}
|
|
8
8
|
⚠️ **一票否决** — 风险筛查触发,建议谨慎。
|
|
9
9
|
{% endif %}
|
|
10
|
+
{% if risk_screening and (risk_screening.data_complete is sameas false or risk_screening.risk_level == 'unknown') %}
|
|
11
|
+
⚠️ **数据不完整** — 当前风险筛查不能判定为低风险。
|
|
12
|
+
{% endif %}
|
|
10
13
|
|
|
11
14
|
{% set dp = data_perspective or {} -%}
|
|
12
15
|
{% set pp = dp.price_position or {} -%}
|
|
13
16
|
{% set ts = dp.trend_status or {} -%}
|
|
14
|
-
- 📈 **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is
|
|
17
|
+
- 📈 **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is boolean %}({{ '看多' if ts.is_bullish else '看空' }}){% endif %}
|
|
15
18
|
- 💰 **价位:** 现价 {{ m.fmt_num(pp.current_price) }} | 支撑 {{ m.fmt_num(pp.support_level) }} | 压力 {{ m.fmt_num(pp.resistance_level) }}
|
|
16
19
|
|
|
17
20
|
{% set bp = battle_plan or {} -%}
|
|
@@ -26,3 +29,5 @@
|
|
|
26
29
|
{% if intel.risk_alerts -%}
|
|
27
30
|
⚠️ **风险:** {{ intel.risk_alerts | join(';') }}
|
|
28
31
|
{% endif %}
|
|
32
|
+
|
|
33
|
+
{% include "stock_analysis/_evidence.md.j2" %}
|
|
@@ -26,12 +26,15 @@
|
|
|
26
26
|
## 风险筛查
|
|
27
27
|
|
|
28
28
|
{% if risk_screening -%}
|
|
29
|
-
- **风险等级:** {{ m.risk_emoji(risk_screening.risk_level) }} {{ risk_screening.risk_level or '-' }} | **风险分:** {{ risk_screening.risk_score }}/100
|
|
29
|
+
- **风险等级:** {{ m.risk_emoji(risk_screening.risk_level) }} {{ risk_screening.risk_level or '-' }} | **风险分:** {{ m.fmt_num(risk_screening.risk_score, 0) }}/100
|
|
30
|
+
{% if risk_screening.data_complete is sameas false or risk_screening.risk_level == 'unknown' -%}
|
|
31
|
+
- **数据不完整:** {{ risk_screening.warnings | join(';') }},当前结果不能判定为低风险。
|
|
32
|
+
{% endif %}
|
|
30
33
|
{% if risk_screening.flags -%}
|
|
31
34
|
- **风险标记:**
|
|
32
35
|
{% for f in risk_screening.flags %} - [{{ f.severity }}] {{ f.category }}:{{ f.description }}
|
|
33
36
|
{% endfor %}
|
|
34
|
-
{%-
|
|
37
|
+
{%- elif risk_screening.data_complete is not sameas false and risk_screening.risk_level != 'unknown' -%}
|
|
35
38
|
- **风险标记:** 无显著风险标记
|
|
36
39
|
{%- endif %}
|
|
37
40
|
{%- else -%}
|
|
@@ -45,7 +48,7 @@
|
|
|
45
48
|
{% set pp = dp.price_position or {} -%}
|
|
46
49
|
{% set vol = dp.volume_analysis or {} -%}
|
|
47
50
|
{% set chip = dp.chip_structure or {} -%}
|
|
48
|
-
- **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is
|
|
51
|
+
- **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is boolean %}({{ '看多' if ts.is_bullish else '看空' }}){% endif %}{% if ts.trend_score is not none %} 趋势分 {{ m.fmt_num(ts.trend_score) }}{% endif %}
|
|
49
52
|
- **价格结构:** 现价 {{ m.fmt_num(pp.current_price) }} | 偏离 MA5 {{ m.change_pct(pp.bias_ma5) }} | 支撑 {{ m.fmt_num(pp.support_level) }} | 压力 {{ m.fmt_num(pp.resistance_level) }}
|
|
50
53
|
- **量价:** 量比 {{ m.fmt_num(vol.volume_ratio) }}{% if vol.volume_status %}({{ vol.volume_status }}){% endif %}{% if vol.turnover_rate is not none %} | 换手率 {{ m.change_pct(vol.turnover_rate) }}{% endif %}
|
|
51
54
|
{% if chip and (chip.profit_ratio is not none or chip.avg_cost is not none) -%}
|
|
@@ -104,5 +107,7 @@
|
|
|
104
107
|
{% endfor %}
|
|
105
108
|
{%- endif %}
|
|
106
109
|
|
|
110
|
+
{% include "stock_analysis/_evidence.md.j2" %}
|
|
111
|
+
|
|
107
112
|
---
|
|
108
113
|
*本报告由 stock-analysis-plugin 渲染,仅供参考,不构成投资建议。*
|
package/tools/_subproc.py
CHANGED
|
@@ -14,10 +14,44 @@ import re
|
|
|
14
14
|
import socket
|
|
15
15
|
import subprocess
|
|
16
16
|
import sys
|
|
17
|
+
from pathlib import Path
|
|
17
18
|
|
|
18
19
|
TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
19
20
|
|
|
20
21
|
|
|
22
|
+
COMMAND_BUDGETS = json.loads((Path(TOOLS_DIR) / "cli_budgets.json").read_text(encoding="utf-8"))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def command_timeout(script: str, args: list) -> int:
|
|
26
|
+
key = f"{Path(script).name}:{args[0] if args else ''}"
|
|
27
|
+
budget = COMMAND_BUDGETS.get(key, COMMAND_BUDGETS["default"])
|
|
28
|
+
|
|
29
|
+
def option(name, default):
|
|
30
|
+
return args[args.index(name) + 1] if name in args and args.index(name) + 1 < len(args) else default
|
|
31
|
+
|
|
32
|
+
def positive_int(value, default):
|
|
33
|
+
return int(value) if str(value).isdigit() and int(value) > 0 else default
|
|
34
|
+
|
|
35
|
+
if key == "screener.py:screen":
|
|
36
|
+
top = positive_int(option("--top", 20), 20)
|
|
37
|
+
workers = COMMAND_BUDGETS["l2_workers"]
|
|
38
|
+
budget += math.ceil(top / workers) * COMMAND_BUDGETS["l2_batch"]
|
|
39
|
+
elif key in ("watchlist.py:analyze", "watchlist_context.py:build"):
|
|
40
|
+
count = len([s for s in str(args[1] if len(args) > 1 else "").split(",") if s.strip()])
|
|
41
|
+
workers = positive_int(option("--workers", 3), 3)
|
|
42
|
+
budget += math.ceil(count / workers) * COMMAND_BUDGETS["watchlist_item"]
|
|
43
|
+
if key == "watchlist_context.py:build":
|
|
44
|
+
budget += math.ceil(count / min(workers * 2, 6)) * COMMAND_BUDGETS["anomaly_detect.py:detect"]
|
|
45
|
+
if "--include-market-review" in args:
|
|
46
|
+
budget += 3 * COMMAND_BUDGETS["market_review.py:review"] + 30
|
|
47
|
+
elif key == "market_review.py:review" and option("--market", "A") == "all":
|
|
48
|
+
budget = 3 * budget + 30
|
|
49
|
+
elif key == "technical.py:analyze" and "--periods" in args:
|
|
50
|
+
periods = {p.strip() for p in str(option("--periods", "daily")).split(",") if p.strip()}
|
|
51
|
+
budget *= len(periods | {option("--period", "daily")})
|
|
52
|
+
return budget
|
|
53
|
+
|
|
54
|
+
|
|
21
55
|
def find_python() -> str:
|
|
22
56
|
"""Prefer the repo .venv interpreter; fall back to the current one.
|
|
23
57
|
|
|
@@ -29,12 +63,20 @@ def find_python() -> str:
|
|
|
29
63
|
return venv if os.path.exists(venv) else sys.executable
|
|
30
64
|
|
|
31
65
|
|
|
32
|
-
def run_tool(
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
66
|
+
def run_tool(
|
|
67
|
+
script: str, args: list, timeout: int | None = None, parse_json: bool = True, preserve_errors: bool = False
|
|
68
|
+
):
|
|
69
|
+
"""Run a sibling CLI; opt in to safe error data, otherwise keep the None sentinel."""
|
|
70
|
+
|
|
71
|
+
if timeout is None:
|
|
72
|
+
timeout = command_timeout(script, args)
|
|
73
|
+
|
|
74
|
+
def failure(message, code):
|
|
75
|
+
if not preserve_errors:
|
|
76
|
+
return None
|
|
77
|
+
payload = {"error": scrub_secrets(message), "error_code": code}
|
|
78
|
+
return payload if parse_json else json.dumps(payload, ensure_ascii=False)
|
|
79
|
+
|
|
38
80
|
try:
|
|
39
81
|
r = subprocess.run(
|
|
40
82
|
[find_python(), os.path.join(TOOLS_DIR, script), *args],
|
|
@@ -43,11 +85,24 @@ def run_tool(script: str, args: list, timeout: int = 30, parse_json: bool = True
|
|
|
43
85
|
encoding="utf-8",
|
|
44
86
|
timeout=timeout,
|
|
45
87
|
)
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
88
|
+
raw = r.stdout.strip()
|
|
89
|
+
if not raw:
|
|
90
|
+
return failure("Python command returned no JSON", "empty_output")
|
|
91
|
+
if not preserve_errors:
|
|
92
|
+
return (json.loads(raw) if parse_json else raw) if r.returncode == 0 else None
|
|
93
|
+
try:
|
|
94
|
+
payload = json.loads(raw)
|
|
95
|
+
except ValueError:
|
|
96
|
+
return failure("Python command returned invalid JSON", "invalid_json")
|
|
97
|
+
if isinstance(payload, dict) and isinstance(payload.get("error"), str):
|
|
98
|
+
return failure(payload["error"], payload.get("error_code", "tool_error"))
|
|
99
|
+
if r.returncode != 0:
|
|
100
|
+
return failure(f"Python command failed (exit {r.returncode})", "process_failed")
|
|
101
|
+
return payload if parse_json else raw
|
|
102
|
+
except subprocess.TimeoutExpired:
|
|
103
|
+
return failure(f"Command timed out after {timeout}s", "timeout")
|
|
104
|
+
except Exception as exc:
|
|
105
|
+
return failure(f"Python command failed ({type(exc).__name__})", "process_failed")
|
|
51
106
|
|
|
52
107
|
|
|
53
108
|
def utf8_stdio() -> None:
|
package/tools/alert_rules.py
CHANGED
|
@@ -6,6 +6,7 @@ Does NOT store history, does NOT push, does NOT schedule. Host agent decides whe
|
|
|
6
6
|
|
|
7
7
|
import argparse
|
|
8
8
|
import json
|
|
9
|
+
import math
|
|
9
10
|
import sys
|
|
10
11
|
from concurrent.futures import ThreadPoolExecutor
|
|
11
12
|
from datetime import datetime, timezone
|
|
@@ -31,8 +32,14 @@ RULE_TYPES = {
|
|
|
31
32
|
def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) -> dict | None:
|
|
32
33
|
rtype = rule.get("type")
|
|
33
34
|
value = rule.get("value")
|
|
34
|
-
if rtype not in RULE_TYPES:
|
|
35
|
+
if not isinstance(rtype, str) or rtype not in RULE_TYPES:
|
|
35
36
|
return {"rule": rtype, "triggered": False, "error": f"unknown rule type: {rtype}"}
|
|
37
|
+
if rtype in ("price_below", "price_above", "change_pct_above", "change_pct_below", "volume_ratio_above"):
|
|
38
|
+
try:
|
|
39
|
+
if isinstance(value, bool) or not math.isfinite(float(value)):
|
|
40
|
+
raise ValueError
|
|
41
|
+
except (ValueError, TypeError):
|
|
42
|
+
return {"rule": rtype, "triggered": False, "error": "Rule value must be a finite number"}
|
|
36
43
|
|
|
37
44
|
price = quote.get("price")
|
|
38
45
|
change_pct = quote.get("change_pct")
|
|
@@ -90,6 +97,8 @@ def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) ->
|
|
|
90
97
|
"message": f"量比 {ratio} 超过 {value}",
|
|
91
98
|
}
|
|
92
99
|
elif rtype == "anomaly":
|
|
100
|
+
if not isinstance(value, str) or not value:
|
|
101
|
+
return {"rule": rtype, "triggered": False, "error": "Anomaly type must be a nonempty string"}
|
|
93
102
|
# value is an anomaly type string, e.g. "macd_golden_cross"
|
|
94
103
|
anomalies = (anom or {}).get("anomalies", [])
|
|
95
104
|
for a in anomalies:
|
|
@@ -106,6 +115,8 @@ def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) ->
|
|
|
106
115
|
return {"rule": rtype, "triggered": True, "severity": "high", "message": "风险筛查触发一票否决"}
|
|
107
116
|
elif rtype == "risk_level_at_least":
|
|
108
117
|
order = {"low": 0, "medium": 1, "high": 2}
|
|
118
|
+
if not isinstance(value, str) or value not in order:
|
|
119
|
+
return {"rule": rtype, "triggered": False, "error": "Risk threshold must be low/medium/high"}
|
|
109
120
|
cur = order.get((risk or {}).get("risk_level"))
|
|
110
121
|
want = order.get(value)
|
|
111
122
|
if cur is not None and want is not None and cur >= want:
|
|
@@ -122,7 +133,7 @@ def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) ->
|
|
|
122
133
|
|
|
123
134
|
|
|
124
135
|
def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
125
|
-
if not rules:
|
|
136
|
+
if not isinstance(rules, list) or not rules or any(not isinstance(rule, dict) for rule in rules):
|
|
126
137
|
return {"symbol": symbol, "error": "no rules provided"}
|
|
127
138
|
|
|
128
139
|
needs_tech = any(r.get("type") == "volume_ratio_above" for r in rules)
|
|
@@ -141,6 +152,9 @@ def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
|
141
152
|
with ThreadPoolExecutor(max_workers=len(jobs)) as pool:
|
|
142
153
|
futures = {key: pool.submit(_run_json, script, args) for key, (script, args) in jobs.items()}
|
|
143
154
|
fetched = {key: future.result() for key, future in futures.items()}
|
|
155
|
+
fetched = {
|
|
156
|
+
key: value if isinstance(value, dict) and "error" not in value else None for key, value in fetched.items()
|
|
157
|
+
}
|
|
144
158
|
quote = fetched["quote"] or {}
|
|
145
159
|
tech = fetched.get("tech")
|
|
146
160
|
anom = fetched.get("anom")
|
|
@@ -153,13 +167,25 @@ def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
|
153
167
|
warnings.append("technical analysis fetch failed — volume_ratio rules cannot fire")
|
|
154
168
|
if needs_anom and not anom:
|
|
155
169
|
warnings.append("anomaly fetch failed — anomaly rules cannot fire")
|
|
156
|
-
if needs_risk and not risk:
|
|
170
|
+
if needs_risk and (not risk or risk.get("data_complete") is False or risk.get("risk_level") == "unknown"):
|
|
157
171
|
warnings.append("risk screening fetch failed — risk rules cannot fire")
|
|
158
172
|
|
|
159
173
|
hits = []
|
|
160
174
|
evaluated = []
|
|
161
175
|
for rule in rules:
|
|
162
|
-
|
|
176
|
+
rtype = rule.get("type")
|
|
177
|
+
missing = (
|
|
178
|
+
(rtype in ("price_below", "price_above") and quote.get("price") is None)
|
|
179
|
+
or (rtype in ("change_pct_below", "change_pct_above") and quote.get("change_pct") is None)
|
|
180
|
+
or (rtype == "volume_ratio_above" and (tech or {}).get("volume", {}).get("volume_ratio") is None)
|
|
181
|
+
or (rtype == "anomaly" and not isinstance((anom or {}).get("anomalies"), list))
|
|
182
|
+
or (rtype == "risk_veto" and (risk or {}).get("veto_buy") is None)
|
|
183
|
+
or (rtype == "risk_level_at_least" and (risk or {}).get("risk_level") not in ("low", "medium", "high"))
|
|
184
|
+
)
|
|
185
|
+
if missing:
|
|
186
|
+
result = {"rule": rtype, "triggered": False, "error": "Required source data unavailable"}
|
|
187
|
+
else:
|
|
188
|
+
result = _check_rule(rule, quote, tech, anom, risk)
|
|
163
189
|
if result is None:
|
|
164
190
|
evaluated.append({"rule": rule.get("type"), "triggered": False})
|
|
165
191
|
else:
|
|
@@ -214,6 +240,8 @@ def main():
|
|
|
214
240
|
result = check_rules(args.symbol, rules)
|
|
215
241
|
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
|
216
242
|
print()
|
|
243
|
+
if "error" in result:
|
|
244
|
+
sys.exit(1)
|
|
217
245
|
|
|
218
246
|
|
|
219
247
|
if __name__ == "__main__":
|