@weaxs/openclaw-stock-analysis 0.1.3 → 0.1.5

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.
@@ -0,0 +1,28 @@
1
+ {%- import '_macros.j2' as m -%}
2
+ {{ m.decision_emoji(decision_type) }} **{{ stock_name }}({{ stock_code }})** | {{ m.decision_label(decision_type) }} · 评分 {{ sentiment_score }} · 置信 {{ m.confidence_label(confidence) }}
3
+
4
+ {% if core_conclusion and core_conclusion.one_sentence -%}
5
+ > {{ core_conclusion.one_sentence }}
6
+ {%- endif %}
7
+ {% if risk_screening and risk_screening.veto_buy %}
8
+ ⚠️ **一票否决** — 风险筛查触发,建议谨慎。
9
+ {% endif %}
10
+
11
+ {% set dp = data_perspective or {} -%}
12
+ {% set pp = dp.price_position or {} -%}
13
+ {% set ts = dp.trend_status or {} -%}
14
+ - 📈 **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is not none %}({{ '看多' if ts.is_bullish else '看空' }}){% endif %}
15
+ - 💰 **价位:** 现价 {{ m.fmt_num(pp.current_price) }} | 支撑 {{ m.fmt_num(pp.support_level) }} | 压力 {{ m.fmt_num(pp.resistance_level) }}
16
+
17
+ {% set bp = battle_plan or {} -%}
18
+ {% if bp -%}
19
+ - 🎯 **作战:** 买点 {{ m.fmt_num(bp.ideal_buy) }} | 止损 {{ m.fmt_num(bp.stop_loss) }} | 止盈 {{ m.fmt_num(bp.take_profit) }} | 仓位 {{ bp.suggested_position or '-' }}
20
+ {%- endif %}
21
+
22
+ {% set intel = intelligence or {} -%}
23
+ {% if intel.positive_catalysts -%}
24
+ ✅ **利好:** {{ intel.positive_catalysts | join(';') }}
25
+ {% endif %}
26
+ {% if intel.risk_alerts -%}
27
+ ⚠️ **风险:** {{ intel.risk_alerts | join(';') }}
28
+ {% endif %}
@@ -0,0 +1,108 @@
1
+ {%- import '_macros.j2' as m -%}
2
+ # {{ stock_name }}({{ stock_code }})分析报告
3
+
4
+ **分析日期:** {{ analysis_date }} | **决策:** {{ m.decision_emoji(decision_type) }} {{ m.decision_label(decision_type) }} | **情绪分:** {{ sentiment_score }}/100 | **置信度:** {{ m.confidence_label(confidence) }}
5
+
6
+ {% if core_conclusion -%}
7
+ > **核心结论:** {{ core_conclusion.one_sentence }}
8
+ {% if core_conclusion.signal_type %}> **信号类型:** {{ core_conclusion.signal_type }}{% if core_conclusion.time_sensitivity %} | **时效:** {{ core_conclusion.time_sensitivity }}{% endif %}{% endif %}
9
+ {%- endif %}
10
+
11
+ {% if risk_screening and risk_screening.veto_buy %}
12
+ > ⚠️ **一票否决(veto_buy):** 风险筛查触发否决条件,建议谨慎。
13
+ {% endif %}
14
+
15
+ ## 市场环境
16
+
17
+ {% if market_environment -%}
18
+ - **市场阶段:** {{ market_environment.regime_cn or market_environment.regime or '-' }}{% if market_environment.confidence is not none %}(置信度 {{ m.fmt_num(market_environment.confidence) }}){% endif %}
19
+ {% if market_environment.recommended_skills -%}
20
+ - **推荐策略:** {{ market_environment.recommended_skills | join('、') }}
21
+ {%- endif %}
22
+ {%- else -%}
23
+ - 数据缺失
24
+ {%- endif %}
25
+
26
+ ## 风险筛查
27
+
28
+ {% if risk_screening -%}
29
+ - **风险等级:** {{ m.risk_emoji(risk_screening.risk_level) }} {{ risk_screening.risk_level or '-' }} | **风险分:** {{ risk_screening.risk_score }}/100
30
+ {% if risk_screening.flags -%}
31
+ - **风险标记:**
32
+ {% for f in risk_screening.flags %} - [{{ f.severity }}] {{ f.category }}:{{ f.description }}
33
+ {% endfor %}
34
+ {%- else -%}
35
+ - **风险标记:** 无显著风险标记
36
+ {%- endif %}
37
+ {%- else -%}
38
+ - 数据缺失
39
+ {%- endif %}
40
+
41
+ ## 技术分析
42
+
43
+ {% set dp = data_perspective or {} -%}
44
+ {% set ts = dp.trend_status or {} -%}
45
+ {% set pp = dp.price_position or {} -%}
46
+ {% set vol = dp.volume_analysis or {} -%}
47
+ {% set chip = dp.chip_structure or {} -%}
48
+ - **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is not none %}({{ '看多' if ts.is_bullish else '看空' }}){% endif %}{% if ts.trend_score is not none %} 趋势分 {{ m.fmt_num(ts.trend_score) }}{% endif %}
49
+ - **价格结构:** 现价 {{ 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
+ - **量价:** 量比 {{ 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
+ {% if chip and (chip.profit_ratio is not none or chip.avg_cost is not none) -%}
52
+ - **筹码:** 获利盘 {{ m.change_pct(chip.profit_ratio) }} | 平均成本 {{ m.fmt_num(chip.avg_cost) }}{% if chip.concentration is not none %} | 集中度 {{ m.fmt_num(chip.concentration) }}{% endif %}
53
+ {%- endif %}
54
+
55
+ ## 消息面
56
+
57
+ {% set intel = intelligence or {} -%}
58
+ {% if intel.latest_news -%}
59
+ - **最新动态:** {{ intel.latest_news }}
60
+ {%- endif %}
61
+ {% if intel.sentiment_summary -%}
62
+ - **舆情摘要:** {{ intel.sentiment_summary }}
63
+ {%- endif %}
64
+ {% if intel.positive_catalysts -%}
65
+ - **利好催化:**
66
+ {% for c in intel.positive_catalysts %} - ✅ {{ c }}
67
+ {% endfor %}
68
+ {%- endif %}
69
+ {% if intel.risk_alerts -%}
70
+ - **风险提示:**
71
+ {% for a in intel.risk_alerts %} - ⚠️ {{ a }}
72
+ {% endfor %}
73
+ {%- endif %}
74
+
75
+ ## 作战计划
76
+
77
+ {% set bp = battle_plan or {} -%}
78
+ {% if bp -%}
79
+ - **理想买点:** {{ m.fmt_num(bp.ideal_buy) }} | **次级买点:** {{ m.fmt_num(bp.secondary_buy) }}
80
+ - **止损:** {{ m.fmt_num(bp.stop_loss) }} | **止盈:** {{ m.fmt_num(bp.take_profit) }}
81
+ - **建议仓位:** {{ bp.suggested_position or '-' }}
82
+ {% if bp.entry_plan %}- **进场计划:** {{ bp.entry_plan }}
83
+ {% endif %}{% if bp.risk_control %}- **风控要点:** {{ bp.risk_control }}
84
+ {% endif %}{% if bp.action_checklist -%}
85
+ - **操作清单:**
86
+ {% for item in bp.action_checklist %} - [ ] {{ item }}
87
+ {% endfor %}
88
+ {%- endif %}
89
+ {%- else -%}
90
+ - 暂无作战计划
91
+ {%- endif %}
92
+
93
+ {% if core_conclusion and core_conclusion.position_advice -%}
94
+ ## 仓位建议
95
+
96
+ - **空仓者:** {{ core_conclusion.position_advice.no_position or '-' }}
97
+ - **持仓者:** {{ core_conclusion.position_advice.has_position or '-' }}
98
+ {%- endif %}
99
+
100
+ {% if risk_warning -%}
101
+ ## 风险提示
102
+
103
+ {% for w in risk_warning %}- {{ w }}
104
+ {% endfor %}
105
+ {%- endif %}
106
+
107
+ ---
108
+ *本报告由 stock-analysis-plugin 渲染,仅供参考,不构成投资建议。*
@@ -0,0 +1,238 @@
1
+ #!/usr/bin/env python3
2
+ """Stateless alert rule check — evaluate user rules against current market snapshot.
3
+
4
+ Does NOT store history, does NOT push, does NOT schedule. Host agent decides when to poll.
5
+ """
6
+
7
+ import argparse
8
+ import json
9
+ import subprocess
10
+ import sys
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+
14
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
15
+ from stock_data import detect_market # noqa: E402
16
+
17
+ TOOLS_DIR = Path(__file__).resolve().parent
18
+
19
+
20
+ def _find_python() -> str:
21
+ venv = TOOLS_DIR.parent / ".venv" / "bin" / "python3"
22
+ return str(venv) if venv.exists() else sys.executable
23
+
24
+
25
+ def _run_json(script: str, args: list[str], timeout: int = 30):
26
+ cmd = [_find_python(), str(TOOLS_DIR / script)] + args
27
+ try:
28
+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
29
+ if r.returncode == 0 and r.stdout.strip():
30
+ return json.loads(r.stdout)
31
+ except Exception:
32
+ pass
33
+ return None
34
+
35
+
36
+ RULE_TYPES = {
37
+ "price_below",
38
+ "price_above",
39
+ "change_pct_above",
40
+ "change_pct_below",
41
+ "volume_ratio_above",
42
+ "anomaly",
43
+ "risk_veto",
44
+ "risk_level_at_least",
45
+ }
46
+
47
+
48
+ def _severity_for(rule_type: str) -> str:
49
+ return {
50
+ "risk_veto": "high",
51
+ "risk_level_at_least": "high",
52
+ "anomaly": "medium",
53
+ "price_below": "medium",
54
+ "price_above": "medium",
55
+ "change_pct_above": "medium",
56
+ "change_pct_below": "medium",
57
+ "volume_ratio_above": "medium",
58
+ }.get(rule_type, "low")
59
+
60
+
61
+ def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) -> dict | None:
62
+ rtype = rule.get("type")
63
+ value = rule.get("value")
64
+ if rtype not in RULE_TYPES:
65
+ return {"rule": rtype, "triggered": False, "error": f"unknown rule type: {rtype}"}
66
+
67
+ price = quote.get("price")
68
+ change_pct = quote.get("change_pct")
69
+
70
+ if rtype == "price_below":
71
+ if price is not None and value is not None and float(price) < float(value):
72
+ return {
73
+ "rule": rtype,
74
+ "triggered": True,
75
+ "value": value,
76
+ "actual": price,
77
+ "severity": _severity_for(rtype),
78
+ "message": f"现价 {price} 跌破 {value}",
79
+ }
80
+ elif rtype == "price_above":
81
+ if price is not None and value is not None and float(price) > float(value):
82
+ return {
83
+ "rule": rtype,
84
+ "triggered": True,
85
+ "value": value,
86
+ "actual": price,
87
+ "severity": _severity_for(rtype),
88
+ "message": f"现价 {price} 突破 {value}",
89
+ }
90
+ elif rtype == "change_pct_above":
91
+ if change_pct is not None and value is not None and float(change_pct) > float(value):
92
+ return {
93
+ "rule": rtype,
94
+ "triggered": True,
95
+ "value": value,
96
+ "actual": change_pct,
97
+ "severity": _severity_for(rtype),
98
+ "message": f"涨幅 {change_pct}% 超过 {value}%",
99
+ }
100
+ elif rtype == "change_pct_below":
101
+ if change_pct is not None and value is not None and float(change_pct) < float(value):
102
+ return {
103
+ "rule": rtype,
104
+ "triggered": True,
105
+ "value": value,
106
+ "actual": change_pct,
107
+ "severity": _severity_for(rtype),
108
+ "message": f"跌幅 {change_pct}% 低于 {value}%",
109
+ }
110
+ elif rtype == "volume_ratio_above":
111
+ vol_data = (tech or {}).get("volume", {})
112
+ ratio = vol_data.get("volume_ratio")
113
+ if ratio is not None and value is not None and float(ratio) > float(value):
114
+ return {
115
+ "rule": rtype,
116
+ "triggered": True,
117
+ "value": value,
118
+ "actual": ratio,
119
+ "severity": _severity_for(rtype),
120
+ "message": f"量比 {ratio} 超过 {value}",
121
+ }
122
+ elif rtype == "anomaly":
123
+ # value is an anomaly type string, e.g. "macd_golden_cross"
124
+ anomalies = (anom or {}).get("anomalies", [])
125
+ for a in anomalies:
126
+ if a.get("type") == value:
127
+ return {
128
+ "rule": rtype,
129
+ "triggered": True,
130
+ "value": value,
131
+ "severity": a.get("severity", "medium"),
132
+ "message": a.get("description", f"命中异动 {value}"),
133
+ }
134
+ elif rtype == "risk_veto":
135
+ if (risk or {}).get("veto_buy"):
136
+ return {"rule": rtype, "triggered": True, "severity": "high", "message": "风险筛查触发一票否决"}
137
+ elif rtype == "risk_level_at_least":
138
+ order = {"low": 0, "medium": 1, "high": 2}
139
+ cur = order.get((risk or {}).get("risk_level"))
140
+ want = order.get(value)
141
+ if cur is not None and want is not None and cur >= want:
142
+ return {
143
+ "rule": rtype,
144
+ "triggered": True,
145
+ "value": value,
146
+ "actual": (risk or {}).get("risk_level"),
147
+ "severity": "high",
148
+ "message": f"风险等级 {(risk or {}).get('risk_level')} ≥ {value}",
149
+ }
150
+
151
+ return None
152
+
153
+
154
+ def check_rules(symbol: str, rules: list[dict]) -> dict:
155
+ if not rules:
156
+ return {"symbol": symbol, "error": "no rules provided"}
157
+
158
+ needs_tech = any(r.get("type") == "volume_ratio_above" for r in rules)
159
+ needs_anom = any(r.get("type") == "anomaly" for r in rules)
160
+ needs_risk = any(r.get("type") in ("risk_veto", "risk_level_at_least") for r in rules)
161
+
162
+ quote = _run_json("stock_data.py", ["quote", symbol]) or {}
163
+ tech = _run_json("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"]) if needs_tech else None
164
+ anom = _run_json("anomaly_detect.py", ["detect", symbol]) if needs_anom else None
165
+ risk = _run_json("risk_screening.py", ["screen", symbol]) if needs_risk else None
166
+
167
+ warnings = []
168
+ if not quote or quote.get("price") is None:
169
+ warnings.append("quote fetch failed or missing price — price/change rules cannot fire")
170
+ if needs_tech and not tech:
171
+ warnings.append("technical analysis fetch failed — volume_ratio rules cannot fire")
172
+ if needs_anom and not anom:
173
+ warnings.append("anomaly fetch failed — anomaly rules cannot fire")
174
+ if needs_risk and not risk:
175
+ warnings.append("risk screening fetch failed — risk rules cannot fire")
176
+
177
+ hits = []
178
+ evaluated = []
179
+ for rule in rules:
180
+ result = _check_rule(rule, quote, tech, anom, risk)
181
+ if result is None:
182
+ evaluated.append({"rule": rule.get("type"), "triggered": False})
183
+ else:
184
+ evaluated.append(result)
185
+ if result.get("triggered"):
186
+ hits.append(result)
187
+
188
+ return {
189
+ "meta": {
190
+ "provider": "alert_rules",
191
+ "fetched_at": datetime.now(timezone.utc).isoformat(),
192
+ "freshness": "realtime_or_latest_trade_day",
193
+ "fallback_used": False,
194
+ "warnings": warnings,
195
+ },
196
+ "symbol": symbol,
197
+ "market": detect_market(symbol),
198
+ "triggered": len(hits) > 0,
199
+ "hit_count": len(hits),
200
+ "hits": hits,
201
+ "evaluated": evaluated,
202
+ }
203
+
204
+
205
+ def main():
206
+ parser = argparse.ArgumentParser(description="Stateless alert rule check")
207
+ sub = parser.add_subparsers(dest="command")
208
+ p = sub.add_parser("check")
209
+ p.add_argument("symbol")
210
+ p.add_argument("--rules", help='JSON array of rules, or "-" for stdin')
211
+ p.add_argument("--rules-b64", help="Base64-encoded JSON rules")
212
+
213
+ args = parser.parse_args()
214
+ if not args.command:
215
+ parser.print_help()
216
+ sys.exit(1)
217
+
218
+ if args.rules_b64:
219
+ import base64
220
+
221
+ raw = base64.b64decode(args.rules_b64).decode("utf-8")
222
+ elif args.rules == "-" or args.rules is None:
223
+ raw = sys.stdin.read()
224
+ else:
225
+ raw = args.rules
226
+ try:
227
+ rules = json.loads(raw)
228
+ except json.JSONDecodeError as e:
229
+ print(json.dumps({"error": f"invalid rules JSON: {e}"}, ensure_ascii=False))
230
+ sys.exit(1)
231
+
232
+ result = check_rules(args.symbol, rules)
233
+ json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
234
+ print()
235
+
236
+
237
+ if __name__ == "__main__":
238
+ main()
package/tools/backtest.py CHANGED
@@ -458,6 +458,120 @@ def diagnose(metrics: dict) -> dict:
458
458
  return {"strengths": strengths, "weaknesses": weaknesses, "suggestions": suggestions}
459
459
 
460
460
 
461
+ def diagnose_advanced(metrics: dict, trades: list, equity_curve: list, strategy: dict) -> dict:
462
+ """Extra agent-friendly diagnostics: failure reason, regime fit, parameter hints."""
463
+ exit_cfg = strategy.get("exit") or {}
464
+ sl_val = exit_cfg.get("stop_loss")
465
+ stop_loss = float(sl_val) if sl_val is not None else -0.10
466
+ tp_val = exit_cfg.get("take_profit")
467
+ take_profit = float(tp_val) if tp_val is not None else 0.50
468
+
469
+ total = metrics.get("total_trades", 0)
470
+ win_rate = metrics.get("win_rate", 0)
471
+ plr = metrics.get("profit_loss_ratio", 0)
472
+ mdd = abs(metrics.get("max_drawdown", 0))
473
+ total_return = metrics.get("total_return", 0)
474
+
475
+ # trade_count_quality
476
+ if total < 5:
477
+ trade_count_quality = "too_low"
478
+ elif total < 15:
479
+ trade_count_quality = "marginal"
480
+ else:
481
+ trade_count_quality = "sufficient"
482
+
483
+ # main_failure_reason — pick the most impactful weakness
484
+ sell_trades = [t for t in trades if t.get("action") == "sell"]
485
+ stop_hits = sum(
486
+ 1
487
+ for t in sell_trades
488
+ if (t.get("reason") or "").startswith("stop_loss")
489
+ or (t.get("pnl_pct", 0) is not None and t.get("pnl_pct", 0) <= stop_loss * 100 + 0.5)
490
+ )
491
+ stop_ratio = stop_hits / max(1, len(sell_trades))
492
+
493
+ main_failure_reason = None
494
+ if total_return < 0:
495
+ if stop_ratio > 0.5:
496
+ main_failure_reason = "止损频繁触发,可能过紧或市场震荡不匹配"
497
+ elif win_rate < 0.35:
498
+ main_failure_reason = "胜率过低,入场信号质量差"
499
+ elif plr < 1:
500
+ main_failure_reason = "盈亏比不足,盈利未能覆盖亏损"
501
+ else:
502
+ main_failure_reason = "整体信号频次或时机不佳"
503
+ elif mdd > 0.25:
504
+ main_failure_reason = "收益为正但回撤过大,风险控制不足"
505
+
506
+ # regime_fit — infer from equity curve shape
507
+ regime_fit = "unknown"
508
+ if len(equity_curve) >= 3:
509
+ # split into halves, compare
510
+ mid = len(equity_curve) // 2
511
+ first = equity_curve[mid][1] if isinstance(equity_curve[mid], list) else equity_curve[mid]
512
+ last = equity_curve[-1][1] if isinstance(equity_curve[-1], list) else equity_curve[-1]
513
+ start_v = equity_curve[0][1] if isinstance(equity_curve[0], list) else equity_curve[0]
514
+ first_half = (first - start_v) / start_v if start_v else 0
515
+ second_half = (last - first) / first if first else 0
516
+ if first_half > 0.05 and second_half > 0.05:
517
+ regime_fit = "consistent_across_periods"
518
+ elif first_half > 0.05 and second_half < -0.02:
519
+ regime_fit = "better_in_early_period"
520
+ elif first_half < -0.02 and second_half > 0.05:
521
+ regime_fit = "better_in_late_period"
522
+ elif win_rate > 0.5 and total_return > 0:
523
+ regime_fit = "better_in_trend_market"
524
+ else:
525
+ regime_fit = "regime_dependent"
526
+
527
+ # suggested_parameter_changes
528
+ suggestions = []
529
+ if stop_ratio > 0.5 and total_return < 0:
530
+ suggestions.append(
531
+ {
532
+ "parameter": "exit.stop_loss",
533
+ "from": stop_loss,
534
+ "to": round(stop_loss * 1.5, 3),
535
+ "reason": "止损过紧,被震荡打出",
536
+ }
537
+ )
538
+ if plr < 1 and win_rate > 0.4:
539
+ suggestions.append(
540
+ {
541
+ "parameter": "exit.take_profit",
542
+ "from": take_profit,
543
+ "to": round(take_profit * 1.3, 3),
544
+ "reason": "止盈过早,盈亏比偏低",
545
+ }
546
+ )
547
+ if trade_count_quality == "too_low":
548
+ suggestions.append(
549
+ {
550
+ "parameter": "entry.*",
551
+ "from": None,
552
+ "to": None,
553
+ "reason": "入场条件过严,交易次数不足",
554
+ }
555
+ )
556
+ if mdd > 0.25:
557
+ suggestions.append(
558
+ {
559
+ "parameter": "position.size",
560
+ "from": None,
561
+ "to": None,
562
+ "reason": "回撤大,考虑降低仓位比例",
563
+ }
564
+ )
565
+
566
+ return {
567
+ "trade_count_quality": trade_count_quality,
568
+ "main_failure_reason": main_failure_reason,
569
+ "regime_fit": regime_fit,
570
+ "stop_loss_hit_ratio": round(stop_ratio, 2),
571
+ "suggested_parameter_changes": suggestions,
572
+ }
573
+
574
+
461
575
  def sample_curve(curve: list, max_points: int = 200) -> list:
462
576
  if len(curve) <= max_points:
463
577
  return curve
@@ -497,6 +611,7 @@ def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str |
497
611
  "trades": sim["trades"],
498
612
  "equity_curve": sample_curve(sim["equity_curve"]),
499
613
  "diagnosis": diagnose(metrics),
614
+ "diagnostics": diagnose_advanced(metrics, sim["trades"], sim["equity_curve"], strategy),
500
615
  }
501
616
 
502
617
 
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env python3
2
+ """Market capability boundaries — tell agent what a given market supports.
3
+
4
+ Prevents agents from calling A-share-only tools on HK/US and vice versa.
5
+ """
6
+
7
+ import argparse
8
+ import json
9
+ import sys
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+
13
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
14
+ from stock_data import detect_market
15
+
16
+ # tool_name -> {markets: [supported markets], reason: str for unsupported}
17
+ TOOL_MATRIX = {
18
+ "get_kline": {"markets": ["A", "HK", "US"], "reason": None},
19
+ "get_quote": {"markets": ["A", "HK", "US"], "reason": None},
20
+ "get_news": {"markets": ["A", "HK", "US"], "reason": None},
21
+ "get_financials": {"markets": ["A", "HK", "US"], "reason": None},
22
+ "get_technical_analysis": {"markets": ["A", "HK", "US"], "reason": None},
23
+ "analyze_pattern": {"markets": ["A", "HK", "US"], "reason": None},
24
+ "get_market_indices": {"markets": ["A", "HK", "US"], "reason": None},
25
+ "calculate_ma": {"markets": ["A", "HK", "US"], "reason": None},
26
+ "get_volume_analysis": {"markets": ["A", "HK", "US"], "reason": None},
27
+ "detect_anomaly": {"markets": ["A", "HK", "US"], "reason": None},
28
+ "get_stock_info": {"markets": ["A", "HK", "US"], "reason": None},
29
+ "detect_market_regime": {"markets": ["A", "HK", "US"], "reason": None},
30
+ "get_market_review": {"markets": ["A", "HK", "US"], "reason": None},
31
+ # A-share only
32
+ "get_capital_flow": {"markets": ["A"], "reason": "A-share only (akshare data)"},
33
+ "get_chip_distribution": {"markets": ["A"], "reason": "A-share only"},
34
+ "get_sector_rankings": {"markets": ["A"], "reason": "A-share only"},
35
+ "get_market_stats": {"markets": ["A"], "reason": "A-share only"},
36
+ "get_fundamental_context": {"markets": ["A"], "reason": "A-share only"},
37
+ "resolve_stock_name": {"markets": ["A"], "reason": "A-share name/pinyin index only"},
38
+ # US-leaning
39
+ "get_social_sentiment": {
40
+ "markets": ["US"],
41
+ "reason": "sentiment providers are US-centric; requires SENTIMENT_API_KEY",
42
+ },
43
+ "get_trending_sentiment": {
44
+ "markets": ["A", "HK", "US"],
45
+ "reason": None,
46
+ },
47
+ # search-based, market-agnostic
48
+ "search_stock_news": {"markets": ["A", "HK", "US"], "reason": None},
49
+ "search_comprehensive_intel": {"markets": ["A", "HK", "US"], "reason": None},
50
+ "extract_article": {"markets": ["A", "HK", "US"], "reason": None},
51
+ "screen_risk": {"markets": ["A", "HK", "US"], "reason": None},
52
+ }
53
+
54
+
55
+ def get_capabilities(market: str) -> dict:
56
+ market = market.upper()
57
+ supported = []
58
+ unsupported = []
59
+ for tool, spec in TOOL_MATRIX.items():
60
+ if market in spec["markets"]:
61
+ supported.append(tool)
62
+ else:
63
+ unsupported.append({"tool": tool, "reason": spec["reason"] or "not supported"})
64
+
65
+ return {
66
+ "meta": {
67
+ "provider": "capabilities",
68
+ "fetched_at": datetime.now(timezone.utc).isoformat(),
69
+ "freshness": "static",
70
+ "fallback_used": False,
71
+ "warnings": [],
72
+ },
73
+ "market": market,
74
+ "supported": supported,
75
+ "unsupported": unsupported,
76
+ }
77
+
78
+
79
+ def main():
80
+ parser = argparse.ArgumentParser(description="Market capability boundaries")
81
+ sub = parser.add_subparsers(dest="command")
82
+ p = sub.add_parser("get")
83
+ grp = p.add_mutually_exclusive_group(required=True)
84
+ grp.add_argument("--market", type=str.upper, choices=["A", "HK", "US"], help="Market code")
85
+ grp.add_argument("--symbol", help="Stock symbol (auto-detects market)")
86
+ args = parser.parse_args()
87
+
88
+ if not args.command:
89
+ parser.print_help()
90
+ sys.exit(1)
91
+
92
+ market = args.market or detect_market(args.symbol)
93
+ result = get_capabilities(market)
94
+ if args.symbol:
95
+ result["symbol"] = args.symbol
96
+ json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
97
+ print()
98
+
99
+
100
+ if __name__ == "__main__":
101
+ main()