stock-analysis-plugin 0.2.10 → 0.2.12
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 +237 -381
- package/docs/mcp.md +60 -0
- package/hermes/__init__.py +35 -0
- package/hermes/plugin.yaml +131 -0
- package/hermes/schemas.py +6 -0
- package/hermes/tools.py +630 -0
- package/mcp_host/__init__.py +1 -0
- package/mcp_host/__main__.py +3 -0
- package/mcp_host/server.py +222 -0
- package/package.json +17 -10
- package/pi/index.ts +53 -2887
- package/scripts/cli-json.mjs +23 -0
- package/scripts/exec-process.mjs +89 -0
- package/scripts/setup-python.mjs +37 -4
- package/scripts/tool-calls.mjs +489 -0
- package/skills/event-driven/SKILL.md +2 -2
- package/skills/growth-quality/SKILL.md +1 -1
- package/skills/stock-analysis/SKILL.md +12 -7
- package/skills/stock-analysis/references/stateless-analysis.md +9 -1
- package/tools/_cache.py +13 -0
- package/tools/_subproc.py +46 -0
- package/tools/alert_rules.py +65 -16
- package/tools/backtest.py +3 -3
- package/tools/capabilities.py +32 -9
- package/tools/cli_budgets.json +2 -0
- package/tools/diagnostics.py +3 -4
- package/tools/gather.py +2 -6
- package/tools/import_parser.py +3 -4
- package/tools/lixinger.py +119 -27
- package/tools/market_regime.py +5 -2
- package/tools/market_review.py +5 -6
- package/tools/name_resolver.py +82 -21
- package/tools/report_renderer.py +3 -3
- package/tools/requirements.txt +6 -5
- package/tools/risk_screening.py +3 -2
- package/tools/screener.py +6 -4
- package/tools/search_intel.py +81 -12
- package/tools/sec_edgar.py +266 -0
- package/tools/sec_holders.py +6 -0
- package/tools/signal_tracker.py +11 -10
- package/tools/stateless_analysis.py +115 -0
- package/tools/stock_data.py +707 -222
- package/tools/tiaa_disclosures.py +267 -0
- package/tools/tool_schemas.json +2704 -0
- package/tools/trading_calendar.py +65 -30
- package/tools/value_data.py +366 -134
- package/tools/watchlist.py +43 -5
|
@@ -17,7 +17,7 @@ description: 综合股票分析:联合技术、基本面、资金、消息和
|
|
|
17
17
|
|
|
18
18
|
## 无状态分析扩展
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
当用户要求同行比较、组合风险/压力测试、目标权重调仓、仓位预算、DCF 估值或新旧分析比较时,MUST 读取[无状态研究工具](references/stateless-analysis.md),分别使用 compare_stocks、analyze_portfolio_risk、plan_portfolio_rebalance、calculate_position_size、calculate_dcf_valuation、compare_analysis_snapshots。所有用户状态均由本次输入提供;调仓计划数量不等于成交,现金不足或整手差额必须读取 unfilled 说明。
|
|
21
21
|
|
|
22
22
|
## 意图路由表
|
|
23
23
|
|
|
@@ -29,8 +29,9 @@ description: 综合股票分析:联合技术、基本面、资金、消息和
|
|
|
29
29
|
|------|---------|
|
|
30
30
|
| 个股买卖时机 | `get_technical_analysis` → `get_market_capabilities` → 当前市场支持的资金/风险工具 → `detect_market_regime`。A股可加 `get_capital_flow`(summary) 和 `screen_risk`;其他市场不得用缺失的资金或风险数据。veto_buy=true 则不入场;大盘下跌时个股看多信号降级为轻仓试错或等待;HOLD/WAIT 给出可观察触发条件 |
|
|
31
31
|
| 个股状态速览 | `get_quote` + `get_technical_analysis` |
|
|
32
|
+
| 场外公募基金净值 | `get_fund_quote`(6 位基金代码,如 018147) |
|
|
32
33
|
| 异动归因 | `detect_anomaly` + `get_news` |
|
|
33
|
-
| 大盘择时 | `detect_market_regime
|
|
34
|
+
| 大盘择时 | `detect_market_regime`;可补充 `get_market_stats(market)` 看涨跌家数,美股行业强弱用 `get_sector_rankings(market=US)`(ETF 代理) |
|
|
34
35
|
|
|
35
36
|
## 执行流程
|
|
36
37
|
|
|
@@ -42,11 +43,13 @@ description: 综合股票分析:联合技术、基本面、资金、消息和
|
|
|
42
43
|
python3 scripts/gather.py <symbol>
|
|
43
44
|
```
|
|
44
45
|
|
|
45
|
-
解析返回的 JSON 数据。如果某个字段为 `null` 或包含 `error
|
|
46
|
+
解析返回的 JSON 数据。如果某个字段为 `null` 或包含 `error`,表示该数据不可用,基于可用数据继续分析。大盘状态按股票所属市场查询,A/HK/US/JP/KR/TW 均使用各自指数;非 A 股板块热点不可用时 sector_heat=false,不能套用 A 股状态或把 false 解读成无热点。
|
|
46
47
|
|
|
47
48
|
解读实时行情前先调 `get_trading_phase` 确认该市场当前盘中阶段(盘前/早盘/午间休市/午盘/交易中/盘后/休市),避免把休市时的静态快照当作盘中信号解读。
|
|
48
49
|
|
|
49
|
-
|
|
50
|
+
场外公募基金净值查询使用 `get_fund_quote(symbol="018147")`,不要当作股票实时报价。`nav` 是 `nav_date` 对应的已披露日终净值而非实时价;`accumulated_nav` 为累计净值,`change_pct` 为日涨跌幅。`estimated_nav` 是估算值且可能为 `null`,缺失时不得编造或当作实时成交价;QDII 净值可能滞后 1-2 交易日,须披露实际 `nav_date`。`TIAAxxxxxx` 使用 `get_quote` 获取投顾组合识别与无统一净值提示,不推算组合净值。`advisor_code/advisor_org` 按 TIAA 前三位机构段与资本市场标准网基金投顾业务编码表进行 best-effort 映射,来源和抓取时间随结果返回;投顾机构不等于主理人,查不到时保留 null。`official_disclosures` 目前仅对确认属于有知有行的 `TIAA001001/TIAA001002/TIAA001004` 提供,其他 TIAA 组合不得套用该站文章;有搜索配置时可返回 `disclosure_status=search_partial` 和 `public_search_results`,其中每项均为 `verification=unverified_search_result`,只能作为待核实线索,否则为 `unsupported_provider`。官方披露含发布日期、摘要、正文摘录和 URL;`disclosures_partial=true` 时必须视为不完整历史披露,不能当作实时业绩或完整成分基金清单。示例账户收益不等于用户收益,引用基金代码时必须保留对应文章日期和链接。
|
|
51
|
+
|
|
52
|
+
港股 `get_quote` 自动按 yfinance → 腾讯 → finnhub → longbridge 容灾,腾讯无需 API key,使用 `r_hk` 实时报价通道(`hk` 通道延迟约 15 分钟)。腾讯港股成交量为股,成交额及市值为港元;PB、换手率、量比为 null 时按缺失处理。腾讯也是港股 `get_kline` 的第二个源,以及美股报价和 K 线在 finnhub / longbridge 之后、alphavantage 之前的备用源;腾讯 K 线为前复权(`adjusted: "qfq"`),与 yfinance 的全收益口径不同。
|
|
50
53
|
|
|
51
54
|
### 第二步:综合研判
|
|
52
55
|
|
|
@@ -88,7 +91,7 @@ python3 scripts/gather.py <symbol>
|
|
|
88
91
|
- 行情:`get_quote.price`、`get_quote.data_as_of`。
|
|
89
92
|
- 财务:`get_financials.report_date`、`get_financials.roe`,以及历史 `periods` 中实际返回的 `report_date`、`roe`,路径含数字下标。
|
|
90
93
|
- 回测:`run_backtest.metrics.total_trades`、`run_backtest.metrics.win_rate`。
|
|
91
|
-
每项保留原始 value,并按第 2 项填写 source/as_of;正文中的数字及其他证据的 as_of
|
|
94
|
+
每项保留原始 value,并按第 2 项填写 source/as_of;正文中的数字及其他证据的 as_of 元数据不替代独立引用。漏项先补齐再提交。报价过期时保留原始价格与时间作为历史证据;结论与风险说明均以报价的 data_as_of 为行情覆盖截止点,明确该时点至分析日及之后的行情变动未知,等待新报价后再制定当前数值交易计划。
|
|
92
95
|
4. 调用 `render_stock_report`:快速问答用 `brief`,完整研判用 `full`。
|
|
93
96
|
5. 输出渲染后的 Markdown;只在用户要求机器可读数据时附加结构化 JSON。
|
|
94
97
|
|
|
@@ -117,13 +120,13 @@ python3 scripts/gather.py <symbol>
|
|
|
117
120
|
|
|
118
121
|
按用户问题选择数据,完整说明口径、采样覆盖和缺失项:
|
|
119
122
|
|
|
120
|
-
- 判断估值贵贱:`get_valuation_history(symbol, years=5)` 的 PE-TTM/PB 历史正值分位与 Band;亏损 PE
|
|
123
|
+
- 判断估值贵贱:`get_valuation_history(symbol, years=5)` 的 PE-TTM/PB 历史正值分位与 Band;亏损 PE 不计算分位,实际采样不足五年必须说明;美股为 SEC 申报派生的周采样,读取 `share_basis/warnings`。
|
|
121
124
|
- 读多年财报:`get_financials(symbol, periods=10, annual=true)`;A 股按年报筛选,港股按源实际可得年度数返回。财报期不等于公告日,年报历史不能用于假定当时已知信息的回测。
|
|
122
125
|
- 财报季排期:`get_earnings_calendar(report_date="YYYY-MM-DD", symbol=...)`,区分最新预约日期、实际披露日期和已公告业绩预告,不把预告当业绩实绩。
|
|
123
126
|
- 股东变化:`get_shareholder_structure`。A 股北向值是财报十大流通股东中的 HKSCC 名义持股,缺席不等于零,不能当成日度北向买卖;港股南向值按港交所披露日期使用。
|
|
124
127
|
- 大盘估值:`get_index_valuation(symbol="000300", years=5)`;中证近期 PE1 不冒充 PE-TTM、PB 或多年分位。
|
|
125
128
|
- ETF:`get_etf_details(symbol="510300", benchmark="sh000300")`。折溢价须看净值/行情日期;披露持仓不是完整实时申赎篮子,指数成分与基金持仓分别呈现。跟踪误差必须给出用户认可的基准。
|
|
126
|
-
- 股息:`get_dividends`
|
|
129
|
+
- 股息:`get_dividends` 区分历史、未来已公布除息日历和排行;history/calendar 支持 A/HK/US/JP/KR/TW,排行仍仅 A/HK。预案不计入已实现 TTM 股息。名义每股现金未重算送转股口径,遇送转股时不得据此精确比较持有收益。
|
|
127
130
|
- 两融:`get_margin_trading(include_ratio=true)` 的 `margin_buy_ratio_pct` 只使用同日成交额;null 表示不可计算。
|
|
128
131
|
|
|
129
132
|
慢变数据存于 `~/.stock-analysis/cache`:财报、基本信息及新历史数据按天,板块映射按周;行情仍实时查询。输出中的报告期/数据日期决定能否用于判断,缓存命中不代表数据已更新。
|
|
@@ -136,4 +139,6 @@ get_shareholder_structure 的 northbound 优先使用沪深官方季度总量;
|
|
|
136
139
|
|
|
137
140
|
信号价格使用原始报价口径,自动记录的默认 `record_date` 与 `price_date` 均按标的市场时区确定(显式 `date` 不变),并保存原始 `price_as_of`;`price_date` 晚于 `record_date` 时拒绝记录与结算。多头 target 必须高于 entry、stop 必须低于 entry,空头相反,否则拒绝记录。开盘先触 stop 按 open 结算,先触 target 按 target 保守结算;日内顺序未知的双触发仍 stop 优先。复权 K 线需有该报价日的可核实 adjustment_factor,才能换算入场/目标/止损及收益;缺失时 skipped_price_basis 并保持未结算,不得猜测拆股或除权比例,重复日期返回 skipped_no_data。记录日无 K 线时仅在前后因子一致(或已有明确报价日)时使用最近锚点;旧信号缺少报价时点且记录日因子发生变化时必须保持未结算。evaluate_signals 返回 complete/deferred/warnings;预算耗尽时已完成结果保存,未处理记录下次重试。当前仅日线 Tushare、Alpha Vantage 提供可验证换算系数,其余复权来源可能跳过结算。
|
|
138
141
|
|
|
142
|
+
用户说“我的自选股”且未提供代码时,先调用 get_watchlist 读取 dsh 侧栏列表,再把 symbols 传给 run_watchlist_analysis 或 build_watchlist_context;空列表要如实说明,不自行补股票池。
|
|
143
|
+
|
|
139
144
|
自选股上下文异动检查失败时 anomaly_status=unavailable、anomaly_count=null,并提供 anomaly_error/warnings;summary.partial 不得写成无异常或完整成功。
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
|
|
14
14
|
传 `previous/current`,每项 `{text, source, period, metrics}`;正文上限200000字符,metrics 形状同上(可为空),`max_changes` 默认30、上限100。
|
|
15
15
|
|
|
16
|
-
先查询原始公告;HTML 可用 extract_article
|
|
16
|
+
先查询原始公告;HTML/PDF 可用 extract_article,默认3000字符。用于披露比较时按所需正文设置 max_chars(上限200000)并检查 truncated;truncated=true 不能当作全文。无文本层的 PDF 仍需宿主 OCR 或用户提供,MUST NOT 把标题、链接或搜索摘要冒充全文。缺少正文时仍可分析已核实的财务指标,但不要调用要求正文的比较工具。
|
|
17
17
|
|
|
18
18
|
工具输出精确到传入文本行号的变化片段、来源、截断标志和指标差异。文本差异本身不等于经营变化;Agent 要阅读上下文,说明发生了什么、与原预期的关系和可能反证,并引用原文。金额单位和 basis 一致才计算 delta;前期值大于0才计算普通增长率,亏损转盈另述。报告期可不同,但必须核实是可比同长期间(年度/同比单季等),累计季度不能直接当单季。
|
|
19
19
|
|
|
@@ -49,6 +49,14 @@
|
|
|
49
49
|
|
|
50
50
|
lot_size 来自用户或可核实交易规则,尤其港股不能统一猜100股。工具不覆盖券商最低收费、未提供税费、跳空和流动性风险。quantity=0 表示当前约束下不足一个交易单位,MUST NOT 向上凑整。
|
|
51
51
|
|
|
52
|
+
## DCF 估值:calculate_dcf_valuation
|
|
53
|
+
|
|
54
|
+
A/港/美股可先调用 `get_financials(symbol, annual=true, periods=5, include_dcf_inputs=true)` 取年度收入、营业利润、税、现金流、资本开支、现金、债务、少数股东权益和股本。美股优先 SEC companyfacts,A 股和港股配置 `LIXINGER_TOKEN` 时优先理杏仁;主源缺失字段按同财年同币种用 Yahoo 补齐(租赁口径不同,不跨源补),并在 `field_sources` 标注。A 股 `operating_income` 是营业利润(含投资收益和公允价值变动),不等于 EBIT,用作经营利润率前需剔除。仍缺的字段列在 `missing_fields` 且为 null,MUST 向用户索取或另行核实,不能补默认值。`total_debt` 不含租赁;租赁负债在 `lease_liabilities`,是否计入 `debt` 由调用方明确。传给 `calculate_dcf_valuation` 时 `minority_interest` 对应 `minority_interests`,`total_debt`(加上选定的租赁)对应 `debt`。
|
|
55
|
+
|
|
56
|
+
必需 `currency,units,base_revenue,revenue_growth,operating_margin,tax_rate,sales_to_capital,wacc,terminal_growth,terminal_wacc,terminal_roic,diluted_shares`。逐年数组长度相同且为1..10年;比例均为小数。可选 `cash,debt,minority_interests,nonoperating_assets,other_claims,current_price`。所有金额和股数口径一致。
|
|
57
|
+
|
|
58
|
+
工具按达摩达兰 FCFF 口径计算:税后营业利润减去收入增量/销售资本比得到FCFF,终值再投资率为 `terminal_growth/terminal_roic`。输出企业价值、股权价值、每股价值、终值占比和 3x3 终值 WACC/增长敏感性。它不估计 WACC、ERP、国家风险、β或行业销售资本比,也不处理期权、租赁、金融企业和失败概率。结果是假设驱动估值,MUST NOT 当作买卖信号。
|
|
59
|
+
|
|
52
60
|
## 事件研究:analyze_event_study
|
|
53
61
|
|
|
54
62
|
通常直接传 `symbol,benchmark,start_date,end_date,event_dates`,由共享 Python 核心取数,避免模型复述整段K线。股票与基准应属于同一市场;代码模式输出实际覆盖区间和提供方复权标记,没有标记时明确未指定,不用调用方猜测覆盖。开始日期须覆盖事件前一交易日、结束日期须覆盖最长事件窗口。也可使用下面的显式价格模式,两种模式互斥。
|
package/tools/_cache.py
CHANGED
|
@@ -36,6 +36,16 @@ def cached_values(namespace, ttl):
|
|
|
36
36
|
yield entry.get("data")
|
|
37
37
|
|
|
38
38
|
|
|
39
|
+
def _prune(path, ttl):
|
|
40
|
+
"""Drop expired siblings of a fresh entry so date-scoped keys cannot grow the cache forever."""
|
|
41
|
+
cutoff = time.time() - ttl
|
|
42
|
+
for old in CACHE_DIR.glob(f"{path.name.split('-', 1)[0]}-*"):
|
|
43
|
+
if old.stem != path.stem and old.suffix in (".json", ".lock"):
|
|
44
|
+
with contextlib.suppress(OSError):
|
|
45
|
+
if old.stat().st_mtime < cutoff:
|
|
46
|
+
old.unlink()
|
|
47
|
+
|
|
48
|
+
|
|
39
49
|
@contextlib.contextmanager
|
|
40
50
|
def file_lock(path, timeout=5):
|
|
41
51
|
"""Coordinate processes using a stable lock inode, with bounded waiting."""
|
|
@@ -116,6 +126,8 @@ def cached(key: str, ttl: int, fetch):
|
|
|
116
126
|
# shortcut: slow fetches may outlast lock wait; prefer duplicate work to blocking callers indefinitely.
|
|
117
127
|
with contextlib.suppress(OSError):
|
|
118
128
|
stack.enter_context(file_lock(path.with_suffix(".lock")))
|
|
129
|
+
# A held lock must look fresh so another key's prune never unlinks it mid-fetch.
|
|
130
|
+
os.utime(path.with_suffix(".lock"))
|
|
119
131
|
entry = _read(path, ttl)
|
|
120
132
|
if entry and "data" in entry:
|
|
121
133
|
return entry["data"]
|
|
@@ -128,6 +140,7 @@ def cached(key: str, ttl: int, fetch):
|
|
|
128
140
|
json.dump(
|
|
129
141
|
{"key": key, "fetched_at": time.time(), "data": result}, stream, ensure_ascii=False, allow_nan=False
|
|
130
142
|
)
|
|
143
|
+
_prune(path, ttl)
|
|
131
144
|
except (OSError, ValueError, TypeError):
|
|
132
145
|
pass
|
|
133
146
|
return result
|
package/tools/_subproc.py
CHANGED
|
@@ -11,6 +11,7 @@ import json
|
|
|
11
11
|
import math
|
|
12
12
|
import os
|
|
13
13
|
import re
|
|
14
|
+
import signal
|
|
14
15
|
import socket
|
|
15
16
|
import subprocess
|
|
16
17
|
import sys
|
|
@@ -64,6 +65,45 @@ def find_python() -> str:
|
|
|
64
65
|
return venv if os.path.exists(venv) else sys.executable
|
|
65
66
|
|
|
66
67
|
|
|
68
|
+
# A CLI that calls sibling CLIs must die with them: each child leads its own process group.
|
|
69
|
+
TREE_POPEN = (
|
|
70
|
+
{"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if sys.platform == "win32" else {"start_new_session": True}
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def terminate_tree(proc) -> None:
|
|
75
|
+
"""Kill a TREE_POPEN child and every process it started."""
|
|
76
|
+
if sys.platform == "win32":
|
|
77
|
+
try:
|
|
78
|
+
subprocess.run(
|
|
79
|
+
["taskkill", "/F", "/T", "/PID", str(proc.pid)],
|
|
80
|
+
stdin=subprocess.DEVNULL,
|
|
81
|
+
stdout=subprocess.DEVNULL,
|
|
82
|
+
stderr=subprocess.DEVNULL,
|
|
83
|
+
timeout=10,
|
|
84
|
+
check=False,
|
|
85
|
+
)
|
|
86
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
87
|
+
proc.kill()
|
|
88
|
+
else:
|
|
89
|
+
with contextlib.suppress(ProcessLookupError, PermissionError):
|
|
90
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def run_tree(cmd: list, *, timeout: float) -> subprocess.CompletedProcess:
|
|
94
|
+
"""subprocess.run(capture_output, text) whose timeout also kills grandchildren."""
|
|
95
|
+
with subprocess.Popen(
|
|
96
|
+
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", **TREE_POPEN
|
|
97
|
+
) as proc:
|
|
98
|
+
try:
|
|
99
|
+
stdout, stderr = proc.communicate(timeout=timeout)
|
|
100
|
+
except BaseException: # timeout or Ctrl+C: the new session no longer receives terminal signals
|
|
101
|
+
terminate_tree(proc)
|
|
102
|
+
proc.communicate()
|
|
103
|
+
raise
|
|
104
|
+
return subprocess.CompletedProcess(cmd, proc.returncode, stdout, stderr)
|
|
105
|
+
|
|
106
|
+
|
|
67
107
|
def run_tool(
|
|
68
108
|
script: str, args: list, timeout: int | None = None, parse_json: bool = True, preserve_errors: bool = False
|
|
69
109
|
):
|
|
@@ -79,6 +119,7 @@ def run_tool(
|
|
|
79
119
|
return payload if parse_json else json.dumps(payload, ensure_ascii=False)
|
|
80
120
|
|
|
81
121
|
try:
|
|
122
|
+
# Not run_tree: a nested CLI must stay in the caller's process group so the host's tree kill reaches it.
|
|
82
123
|
r = subprocess.run(
|
|
83
124
|
[find_python(), os.path.join(TOOLS_DIR, script), *args],
|
|
84
125
|
capture_output=True,
|
|
@@ -172,6 +213,11 @@ def scrub_secrets(msg: str) -> str:
|
|
|
172
213
|
return _SECRET_PARAM_RE.sub(r"\1***", msg)
|
|
173
214
|
|
|
174
215
|
|
|
216
|
+
def error_message(exc: BaseException, limit: int = 300) -> str:
|
|
217
|
+
"""Exception text for stdout JSON: secrets scrubbed, provider bodies bounded."""
|
|
218
|
+
return scrub_secrets(str(exc))[:limit]
|
|
219
|
+
|
|
220
|
+
|
|
175
221
|
def json_safe(obj):
|
|
176
222
|
"""Replace non-finite floats (inf/-inf/nan, e.g. an all-flat P&L profit_loss_ratio)
|
|
177
223
|
with None so json.dumps never emits the non-standard Infinity/NaN tokens that
|
package/tools/alert_rules.py
CHANGED
|
@@ -13,8 +13,8 @@ from datetime import datetime, timezone
|
|
|
13
13
|
from pathlib import Path
|
|
14
14
|
|
|
15
15
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
16
|
+
from _subproc import error_message, utf8_stdio
|
|
16
17
|
from _subproc import run_tool as _run_json # noqa: E402
|
|
17
|
-
from _subproc import utf8_stdio
|
|
18
18
|
from stock_data import detect_market # noqa: E402
|
|
19
19
|
|
|
20
20
|
RULE_TYPES = {
|
|
@@ -140,28 +140,77 @@ def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
|
140
140
|
needs_anom = any(r.get("type") == "anomaly" for r in rules)
|
|
141
141
|
needs_risk = any(r.get("type") in ("risk_veto", "risk_level_at_least") for r in rules)
|
|
142
142
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
jobs
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
143
|
+
needs_quote = (
|
|
144
|
+
needs_anom
|
|
145
|
+
or needs_risk
|
|
146
|
+
or any(r.get("type") in ("price_below", "price_above", "change_pct_above", "change_pct_below") for r in rules)
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
# Share one market snapshot while retaining 60-bar alerts and 120-bar risk analysis.
|
|
150
|
+
with ThreadPoolExecutor(max_workers=4) as pool:
|
|
151
|
+
jobs = {}
|
|
152
|
+
if needs_quote:
|
|
153
|
+
quote_job = pool.submit(_run_json, "stock_data.py", ["quote", symbol])
|
|
154
|
+
jobs["quote"] = quote_job
|
|
155
|
+
if needs_tech or needs_anom or needs_risk:
|
|
156
|
+
from technical import analyze_records
|
|
157
|
+
|
|
158
|
+
kline_job = pool.submit(
|
|
159
|
+
_run_json,
|
|
160
|
+
"stock_data.py",
|
|
161
|
+
["kline", symbol, "--period", "daily", "--count", "120" if needs_risk else "60"],
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
def analyze(count):
|
|
165
|
+
records = kline_job.result()
|
|
166
|
+
try:
|
|
167
|
+
return analyze_records(symbol, records[-count:] if isinstance(records, list) else records)
|
|
168
|
+
except Exception as exc:
|
|
169
|
+
return {"error": f"Technical analysis failed ({type(exc).__name__})"}
|
|
170
|
+
|
|
171
|
+
if needs_risk:
|
|
172
|
+
from risk_screening import screen_risk
|
|
173
|
+
|
|
174
|
+
technical_job = pool.submit(analyze, 120)
|
|
175
|
+
|
|
176
|
+
def collect_risk():
|
|
177
|
+
try:
|
|
178
|
+
return screen_risk(
|
|
179
|
+
symbol, inputs={"quote": quote_job, "technical": technical_job}, run=_run_json
|
|
180
|
+
)
|
|
181
|
+
except Exception as exc:
|
|
182
|
+
return {"error": f"Risk analysis failed ({type(exc).__name__})"}
|
|
183
|
+
|
|
184
|
+
jobs["risk"] = pool.submit(collect_risk)
|
|
185
|
+
if needs_tech:
|
|
186
|
+
jobs["tech"] = pool.submit(analyze, 60)
|
|
187
|
+
if needs_anom:
|
|
188
|
+
from anomaly_detect import detect_anomalies
|
|
189
|
+
|
|
190
|
+
def anomalies():
|
|
191
|
+
records = kline_job.result()
|
|
192
|
+
try:
|
|
193
|
+
return detect_anomalies(
|
|
194
|
+
symbol,
|
|
195
|
+
records=records[-60:] if isinstance(records, list) else records,
|
|
196
|
+
quote=quote_job.result(),
|
|
197
|
+
run=_run_json,
|
|
198
|
+
)
|
|
199
|
+
except Exception as exc:
|
|
200
|
+
return {"error": f"Anomaly analysis failed ({type(exc).__name__})"}
|
|
201
|
+
|
|
202
|
+
jobs["anom"] = pool.submit(anomalies)
|
|
203
|
+
fetched = {key: future.result() for key, future in jobs.items()}
|
|
155
204
|
fetched = {
|
|
156
205
|
key: value if isinstance(value, dict) and "error" not in value else None for key, value in fetched.items()
|
|
157
206
|
}
|
|
158
|
-
quote = fetched
|
|
207
|
+
quote = fetched.get("quote") or {}
|
|
159
208
|
tech = fetched.get("tech")
|
|
160
209
|
anom = fetched.get("anom")
|
|
161
210
|
risk = fetched.get("risk")
|
|
162
211
|
|
|
163
212
|
warnings = []
|
|
164
|
-
if not quote or quote.get("price") is None:
|
|
213
|
+
if needs_quote and (not quote or quote.get("price") is None):
|
|
165
214
|
warnings.append("quote fetch failed or missing price — price/change rules cannot fire")
|
|
166
215
|
if needs_tech and not tech:
|
|
167
216
|
warnings.append("technical analysis fetch failed — volume_ratio rules cannot fire")
|
|
@@ -234,7 +283,7 @@ def main():
|
|
|
234
283
|
try:
|
|
235
284
|
rules = json.loads(raw)
|
|
236
285
|
except json.JSONDecodeError as e:
|
|
237
|
-
print(json.dumps({"error": f"invalid rules JSON: {e}"}, ensure_ascii=False))
|
|
286
|
+
print(json.dumps({"error": f"invalid rules JSON: {error_message(e)}"}, ensure_ascii=False))
|
|
238
287
|
sys.exit(1)
|
|
239
288
|
|
|
240
289
|
result = check_rules(args.symbol, rules)
|
package/tools/backtest.py
CHANGED
|
@@ -15,7 +15,7 @@ import yaml
|
|
|
15
15
|
|
|
16
16
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
17
17
|
|
|
18
|
-
from _subproc import json_safe, run_tool, utf8_stdio
|
|
18
|
+
from _subproc import error_message, json_safe, run_tool, utf8_stdio
|
|
19
19
|
from stock_data import detect_market
|
|
20
20
|
from technical import (
|
|
21
21
|
bollinger_series,
|
|
@@ -894,7 +894,7 @@ def _benchmark_comparison(
|
|
|
894
894
|
df = fetch_kline(symbol, start, end)
|
|
895
895
|
_validate_adjustment_basis(df)
|
|
896
896
|
except Exception as e:
|
|
897
|
-
return {"symbol": symbol, "error":
|
|
897
|
+
return {"symbol": symbol, "error": error_message(e)}
|
|
898
898
|
if len(df) < 2:
|
|
899
899
|
return {"symbol": symbol, "error": f"Insufficient benchmark data: {len(df)} rows"}
|
|
900
900
|
dates = pd.to_datetime(df["date"], errors="coerce")
|
|
@@ -1128,7 +1128,7 @@ def main():
|
|
|
1128
1128
|
result = {"error": f"Unknown command: {args.command}"}
|
|
1129
1129
|
except Exception as e:
|
|
1130
1130
|
# A traceback would leave stdout empty; hosts need valid JSON even on failure.
|
|
1131
|
-
print(json.dumps({"error":
|
|
1131
|
+
print(json.dumps({"error": error_message(e)}, ensure_ascii=False))
|
|
1132
1132
|
sys.exit(1)
|
|
1133
1133
|
|
|
1134
1134
|
print(json.dumps(json_safe(result), ensure_ascii=False, default=str))
|
package/tools/capabilities.py
CHANGED
|
@@ -30,21 +30,25 @@ TOOL_MATRIX = {
|
|
|
30
30
|
"analyze_portfolio_risk": {"markets": ALL_MARKETS, "reason": None},
|
|
31
31
|
"plan_portfolio_rebalance": {"markets": ALL_MARKETS, "reason": None},
|
|
32
32
|
"calculate_position_size": {"markets": ALL_MARKETS, "reason": None},
|
|
33
|
+
"calculate_dcf_valuation": {"markets": ALL_MARKETS, "reason": None},
|
|
33
34
|
"analyze_event_study": {"markets": ALL_MARKETS, "reason": None},
|
|
34
35
|
"validate_backtest": {"markets": ALL_MARKETS, "reason": None},
|
|
35
36
|
"compare_analysis_snapshots": {"markets": ALL_MARKETS, "reason": None},
|
|
36
|
-
"get_announcements": {
|
|
37
|
+
"get_announcements": {
|
|
38
|
+
"markets": ["A", "HK", "US"],
|
|
39
|
+
"reason": "cninfo A-share / HKEXnews HK / SEC EDGAR US disclosures only",
|
|
40
|
+
},
|
|
37
41
|
"get_us_holdings": {"markets": ["US"], "reason": "SEC manager holdings or verified issuer-CUSIP reverse lookup"},
|
|
38
42
|
"get_insider_trades": {"markets": ["US"], "reason": "SEC issuer Form 4 only"},
|
|
39
|
-
"get_valuation_history": {"markets": ["A", "HK"], "reason": "A/HK
|
|
43
|
+
"get_valuation_history": {"markets": ["A", "HK", "US"], "reason": "A/HK providers; US derived from SEC filings"},
|
|
40
44
|
"get_index_valuation": {"markets": ["A"], "reason": "Chinese index valuation only"},
|
|
41
45
|
"get_earnings_calendar": {
|
|
42
|
-
"markets": ["A", "HK"],
|
|
43
|
-
"reason": "A-share disclosed calendar / HK single-symbol provider schedule",
|
|
46
|
+
"markets": ["A", "HK", "US", "JP"],
|
|
47
|
+
"reason": "A-share disclosed calendar / HK/US/JP single-symbol provider schedule",
|
|
44
48
|
},
|
|
45
49
|
"get_shareholder_structure": {"markets": ["A", "HK"], "reason": "A-share shareholder reports / HK southbound only"},
|
|
46
50
|
"get_etf_details": {"markets": ["A"], "reason": "A-share ETF portfolio/NAV/size only"},
|
|
47
|
-
"get_dividends": {"markets":
|
|
51
|
+
"get_dividends": {"markets": ALL_MARKETS, "reason": None}, # ranking mode stays A/HK only
|
|
48
52
|
"get_kline": {"markets": ALL_MARKETS, "reason": None},
|
|
49
53
|
"get_quote": {"markets": ALL_MARKETS, "reason": None},
|
|
50
54
|
"get_news": {"markets": ALL_MARKETS, "reason": None},
|
|
@@ -57,16 +61,16 @@ TOOL_MATRIX = {
|
|
|
57
61
|
"detect_anomaly": {"markets": ALL_MARKETS, "reason": None},
|
|
58
62
|
"get_stock_info": {"markets": ALL_MARKETS, "reason": None},
|
|
59
63
|
"resolve_stock_sectors": {"markets": ["A", "HK"], "reason": "A-share and HK only"},
|
|
60
|
-
"detect_market_regime": {"markets":
|
|
64
|
+
"detect_market_regime": {"markets": ALL_MARKETS, "reason": None},
|
|
61
65
|
"get_market_review": {"markets": ["A", "HK", "US"], "reason": "review data coverage is CN/HK/US only"},
|
|
62
66
|
# A-share only
|
|
63
67
|
"get_capital_flow": {"markets": ["A"], "reason": "A-share only (akshare data)"},
|
|
64
68
|
"get_chip_distribution": {"markets": ["A"], "reason": "A-share only"},
|
|
65
|
-
"get_sector_rankings": {"markets": ["A"], "reason": "A-share
|
|
69
|
+
"get_sector_rankings": {"markets": ["A", "US"], "reason": "A-share boards; US sector ETF proxies"},
|
|
66
70
|
"get_sector_constituents": {"markets": ["A"], "reason": "A-share only"},
|
|
67
|
-
"get_market_stats": {"markets": ["A"], "reason": "A-share only"},
|
|
71
|
+
"get_market_stats": {"markets": ["A", "HK", "US"], "reason": "full-market snapshot breadth; limits A-share only"},
|
|
68
72
|
"get_fundamental_context": {"markets": ["A"], "reason": "A-share only"},
|
|
69
|
-
"resolve_stock_name": {"markets": ["A"], "reason": "A
|
|
73
|
+
"resolve_stock_name": {"markets": ["A", "HK", "US"], "reason": "A/HK/US name indexes only"},
|
|
70
74
|
"get_limit_up_pool": {"markets": ["A"], "reason": "A-share only"},
|
|
71
75
|
"get_dragon_tiger": {"markets": ["A"], "reason": "A-share only"},
|
|
72
76
|
"get_hot_stocks": {"markets": ["A"], "reason": "A-share only"},
|
|
@@ -90,6 +94,25 @@ TOOL_MATRIX = {
|
|
|
90
94
|
"record_signal": {"markets": ALL_MARKETS, "reason": None},
|
|
91
95
|
"evaluate_signals": {"markets": ALL_MARKETS, "reason": None},
|
|
92
96
|
"get_signal_summary": {"markets": ALL_MARKETS, "reason": None},
|
|
97
|
+
"evaluate_signal": {"markets": ALL_MARKETS, "reason": None},
|
|
98
|
+
"run_backtest": {"markets": ALL_MARKETS, "reason": None},
|
|
99
|
+
"screen_stocks": {"markets": ["A", "HK", "US"], "reason": "full-market snapshots exist for A/HK/US only"},
|
|
100
|
+
"get_fund_quote": {"markets": ["A"], "reason": "mainland China open-end fund NAV only"},
|
|
101
|
+
# symbol-driven workflows; per-tool market limits above still apply inside them
|
|
102
|
+
"run_watchlist_analysis": {"markets": ALL_MARKETS, "reason": None},
|
|
103
|
+
"build_watchlist_context": {"markets": ALL_MARKETS, "reason": None},
|
|
104
|
+
"analyze_position_context": {"markets": ALL_MARKETS, "reason": None},
|
|
105
|
+
"check_alert_rules": {"markets": ALL_MARKETS, "reason": None},
|
|
106
|
+
"parse_stock_list": {"markets": ALL_MARKETS, "reason": None},
|
|
107
|
+
"get_watchlist": {"markets": ALL_MARKETS, "reason": None},
|
|
108
|
+
"check_trading_day": {"markets": ALL_MARKETS, "reason": None},
|
|
109
|
+
"get_trading_days": {"markets": ALL_MARKETS, "reason": None},
|
|
110
|
+
"get_review_history": {"markets": ["A", "HK", "US"], "reason": "market review archives cover CN/HK/US only"},
|
|
111
|
+
# market-agnostic utilities
|
|
112
|
+
"render_stock_report": {"markets": ALL_MARKETS, "reason": None},
|
|
113
|
+
"render_market_report": {"markets": ["A", "HK", "US"], "reason": "market review reports cover CN/HK/US only"},
|
|
114
|
+
"diagnose_data_sources": {"markets": ALL_MARKETS, "reason": None},
|
|
115
|
+
"get_market_capabilities": {"markets": ALL_MARKETS, "reason": None},
|
|
93
116
|
}
|
|
94
117
|
|
|
95
118
|
|
package/tools/cli_budgets.json
CHANGED
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
"risk_screening.py:screen": 450,
|
|
10
10
|
"signal_tracker.py:evaluate": 300,
|
|
11
11
|
"stock_data.py:market_stats": 240,
|
|
12
|
+
"name_resolver.py:resolve": 360,
|
|
13
|
+
"import_parser.py:parse": 360,
|
|
12
14
|
"market_review.py:review": 300,
|
|
13
15
|
"anomaly_detect.py:detect": 390,
|
|
14
16
|
"position_context.py:analyze": 300,
|
package/tools/diagnostics.py
CHANGED
|
@@ -30,11 +30,11 @@ PROVIDERS = {
|
|
|
30
30
|
"lixinger": (
|
|
31
31
|
"requests",
|
|
32
32
|
["LIXINGER_TOKEN"],
|
|
33
|
-
["A"],
|
|
34
|
-
"optional index
|
|
33
|
+
["A", "HK"],
|
|
34
|
+
"optional index PB, CN/HK company valuation and statements; subscription permissions not probed",
|
|
35
35
|
),
|
|
36
36
|
"efinance": ("efinance", [], ["A"], None),
|
|
37
|
-
"tencent": ("requests", [], ["A"], "qt.gtimg.cn quote/kline, no auth (issue #25)"),
|
|
37
|
+
"tencent": ("requests", [], ["A", "HK", "US"], "qt.gtimg.cn quote/kline, no auth (issue #25)"),
|
|
38
38
|
"sina": (
|
|
39
39
|
"requests",
|
|
40
40
|
[],
|
|
@@ -42,7 +42,6 @@ PROVIDERS = {
|
|
|
42
42
|
"hq.sinajs.cn quote + daily kline, no auth; full-market snapshot via akshare (issue #25)",
|
|
43
43
|
),
|
|
44
44
|
"xueqiu": ("akshare", ["XUEQIU_TOKEN"], ["A"], "industry board fallback via akshare"),
|
|
45
|
-
"pytdx": ("pytdx", [], ["A"], "connects to public Tencent servers"),
|
|
46
45
|
"baostock": ("baostock", [], ["A"], None),
|
|
47
46
|
"yfinance": ("yfinance", [], ["HK", "US", "JP", "KR", "TW"], "quote may be delayed 15-20min"),
|
|
48
47
|
"finnhub": ("finnhub", ["FINNHUB_API_KEY"], ["HK", "US"], None),
|
package/tools/gather.py
CHANGED
|
@@ -106,12 +106,8 @@ def gather_analysis(symbol: str, *, session=None) -> dict:
|
|
|
106
106
|
"news": ("search_intel.py", ["search", _news_query(symbol)]),
|
|
107
107
|
"social_sentiment": ("search_intel.py", ["sentiment", symbol]),
|
|
108
108
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
result = _run_all(tasks, symbol, session=session, with_risk=True)
|
|
112
|
-
if market not in ("A", "HK", "US"):
|
|
113
|
-
result["regime"] = {"error": f"Market regime unavailable for {market}"}
|
|
114
|
-
return result
|
|
109
|
+
tasks["regime"] = ("market_regime.py", ["detect", market])
|
|
110
|
+
return _run_all(tasks, symbol, session=session, with_risk=True)
|
|
115
111
|
|
|
116
112
|
|
|
117
113
|
def gather_technical(symbol: str, kline_count: int = 120, with_quote: bool = False) -> dict:
|
package/tools/import_parser.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""Parse stock list from freeform text / CSV / markdown.
|
|
3
3
|
|
|
4
|
-
Extracts symbols using regex heuristics + name_resolver for A
|
|
4
|
+
Extracts symbols using regex heuristics + name_resolver for A/HK/US Chinese names.
|
|
5
5
|
"""
|
|
6
6
|
|
|
7
7
|
import argparse
|
|
@@ -210,8 +210,7 @@ def parse(text: str) -> dict:
|
|
|
210
210
|
hits = []
|
|
211
211
|
if hits and isinstance(hits, list) and hits[0].get("code"):
|
|
212
212
|
top_hit = hits[0]
|
|
213
|
-
#
|
|
214
|
-
# (e.g. "腾讯" → "拓新药业" via pinyin). Reject low-confidence hits.
|
|
213
|
+
# Reject low-confidence fuzzy matches instead of mapping an unknown name to a stock.
|
|
215
214
|
score = top_hit.get("score")
|
|
216
215
|
hit_name = top_hit.get("name", "")
|
|
217
216
|
is_exact = (name in hit_name) or (hit_name in name)
|
|
@@ -223,7 +222,7 @@ def parse(text: str) -> dict:
|
|
|
223
222
|
items.append(
|
|
224
223
|
{
|
|
225
224
|
"symbol": code,
|
|
226
|
-
"market":
|
|
225
|
+
"market": detect_market(code),
|
|
227
226
|
"name": hit_name,
|
|
228
227
|
"resolved_from": name,
|
|
229
228
|
}
|