stock-analysis-plugin 0.1.10

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.
Files changed (84) hide show
  1. package/README.md +498 -0
  2. package/package.json +88 -0
  3. package/pi/index.ts +1142 -0
  4. package/schemas/market_review_schema.json +176 -0
  5. package/schemas/report_schema.json +131 -0
  6. package/scripts/setup-python.mjs +57 -0
  7. package/scripts/sync-version.sh +56 -0
  8. package/scripts/venv-python.mjs +20 -0
  9. package/skills/bottom-volume/SKILL.md +63 -0
  10. package/skills/bottom-volume/scripts/gather.py +22 -0
  11. package/skills/box-oscillation/SKILL.md +72 -0
  12. package/skills/box-oscillation/scripts/gather.py +22 -0
  13. package/skills/bull-trend/SKILL.md +60 -0
  14. package/skills/bull-trend/scripts/gather.py +22 -0
  15. package/skills/chan-theory/SKILL.md +71 -0
  16. package/skills/chan-theory/scripts/gather.py +22 -0
  17. package/skills/dragon-head/SKILL.md +69 -0
  18. package/skills/dragon-head/scripts/gather.py +22 -0
  19. package/skills/emotion-cycle/SKILL.md +65 -0
  20. package/skills/emotion-cycle/scripts/gather.py +22 -0
  21. package/skills/event-driven/SKILL.md +73 -0
  22. package/skills/event-driven/scripts/gather.py +22 -0
  23. package/skills/expectation-repricing/SKILL.md +72 -0
  24. package/skills/expectation-repricing/scripts/gather.py +22 -0
  25. package/skills/growth-quality/SKILL.md +74 -0
  26. package/skills/growth-quality/scripts/gather.py +22 -0
  27. package/skills/hot-theme/SKILL.md +74 -0
  28. package/skills/hot-theme/scripts/gather.py +22 -0
  29. package/skills/ma-crossover/SKILL.md +63 -0
  30. package/skills/ma-crossover/scripts/gather.py +22 -0
  31. package/skills/market-review/SKILL.md +70 -0
  32. package/skills/market-review/scripts/gather.py +23 -0
  33. package/skills/one-yang-three-yin/SKILL.md +74 -0
  34. package/skills/one-yang-three-yin/scripts/gather.py +22 -0
  35. package/skills/shrink-pullback/SKILL.md +59 -0
  36. package/skills/shrink-pullback/scripts/gather.py +22 -0
  37. package/skills/stock-analysis/SKILL.md +134 -0
  38. package/skills/stock-analysis/scripts/gather.py +22 -0
  39. package/skills/stock-screener/SKILL.md +68 -0
  40. package/skills/stock-screener/scripts/gather.py +22 -0
  41. package/skills/strategy-backtest/SKILL.md +129 -0
  42. package/skills/strategy-backtest/scripts/gather.py +23 -0
  43. package/skills/volume-breakout/SKILL.md +58 -0
  44. package/skills/volume-breakout/scripts/gather.py +22 -0
  45. package/skills/wave-theory/SKILL.md +67 -0
  46. package/skills/wave-theory/scripts/gather.py +22 -0
  47. package/skills/wisburg-research/SKILL.md +119 -0
  48. package/strategies/examples/bottom_volume.yaml +47 -0
  49. package/strategies/examples/box_oscillation.yaml +41 -0
  50. package/strategies/examples/bull_trend.yaml +42 -0
  51. package/strategies/examples/dragon_head.yaml +45 -0
  52. package/strategies/examples/emotion_cycle.yaml +43 -0
  53. package/strategies/examples/ma_crossover.yaml +34 -0
  54. package/strategies/examples/rsi_oversold.yaml +35 -0
  55. package/strategies/examples/shrink_pullback.yaml +45 -0
  56. package/strategies/examples/volume_breakout.yaml +42 -0
  57. package/templates/_macros.j2 +90 -0
  58. package/templates/market_review/full.md.j2 +103 -0
  59. package/templates/stock_analysis/brief.md.j2 +28 -0
  60. package/templates/stock_analysis/full.md.j2 +108 -0
  61. package/tools/__init__.py +0 -0
  62. package/tools/alert_rules.py +243 -0
  63. package/tools/anomaly_detect.py +575 -0
  64. package/tools/backtest.py +764 -0
  65. package/tools/capabilities.py +108 -0
  66. package/tools/diagnostics.py +146 -0
  67. package/tools/gather.py +157 -0
  68. package/tools/import_parser.py +279 -0
  69. package/tools/market_regime.py +252 -0
  70. package/tools/market_review.py +155 -0
  71. package/tools/name_resolver.py +136 -0
  72. package/tools/pattern.py +515 -0
  73. package/tools/position_context.py +161 -0
  74. package/tools/report_renderer.py +116 -0
  75. package/tools/requirements.txt +15 -0
  76. package/tools/risk_screening.py +323 -0
  77. package/tools/screener.py +219 -0
  78. package/tools/search_intel.py +504 -0
  79. package/tools/stock_data.py +1721 -0
  80. package/tools/technical.py +642 -0
  81. package/tools/trading_calendar.py +226 -0
  82. package/tools/volume_analysis.py +178 -0
  83. package/tools/watchlist.py +66 -0
  84. package/tools/watchlist_context.py +185 -0
@@ -0,0 +1,243 @@
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, encoding="utf-8", 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
+ # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
239
+ # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
240
+ for _s in (sys.stdout, sys.stderr):
241
+ if hasattr(_s, "reconfigure"):
242
+ _s.reconfigure(encoding="utf-8")
243
+ main()