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,764 @@
1
+ #!/usr/bin/env python3
2
+ """AlphaEvo — strategy backtesting engine with YAML DSL."""
3
+
4
+ import argparse
5
+ import json
6
+ import math
7
+ import os
8
+ import re
9
+ import subprocess
10
+ import sys
11
+ from datetime import datetime, timedelta
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+ import yaml
16
+
17
+ # --------------- Strategy Loading ---------------
18
+
19
+
20
+ def load_strategy(path: str) -> dict:
21
+ with open(path, encoding="utf-8") as f:
22
+ strat = yaml.safe_load(f)
23
+ params = strat.get("parameters", {})
24
+ _resolve_refs(strat, params)
25
+ return strat
26
+
27
+
28
+ def _resolve_refs(obj, params: dict):
29
+ if isinstance(obj, dict):
30
+ for k, v in obj.items():
31
+ if isinstance(v, str):
32
+ obj[k] = _substitute(v, params)
33
+ else:
34
+ _resolve_refs(v, params)
35
+ elif isinstance(obj, list):
36
+ for i, v in enumerate(obj):
37
+ if isinstance(v, str):
38
+ obj[i] = _substitute(v, params)
39
+ else:
40
+ _resolve_refs(v, params)
41
+
42
+
43
+ def _substitute(s: str, params: dict):
44
+ def _repl(m):
45
+ key = m.group(1)
46
+ val = params.get(key, m.group(0))
47
+ return str(val)
48
+
49
+ result = re.sub(r"\{(\w+)\}", _repl, s)
50
+ try:
51
+ return float(result) if "." in result else int(result)
52
+ except (ValueError, TypeError):
53
+ return result
54
+
55
+
56
+ # --------------- Data Fetching ---------------
57
+
58
+
59
+ def fetch_kline(symbol: str, start: str | None, end: str | None) -> pd.DataFrame:
60
+ script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "stock_data.py")
61
+ count = 500
62
+ if start and end:
63
+ d0 = datetime.strptime(start, "%Y-%m-%d")
64
+ d1 = datetime.strptime(end, "%Y-%m-%d")
65
+ count = max((d1 - d0).days + 60, 300)
66
+
67
+ r = subprocess.run(
68
+ [sys.executable, script, "kline", symbol, "--period", "daily", "--count", str(count)],
69
+ capture_output=True,
70
+ text=True,
71
+ encoding="utf-8",
72
+ )
73
+ data = json.loads(r.stdout)
74
+ if isinstance(data, dict) and "error" in data:
75
+ raise RuntimeError(data["error"])
76
+
77
+ df = pd.DataFrame(data)
78
+ for c in ["open", "high", "low", "close", "volume"]:
79
+ if c in df.columns:
80
+ df[c] = pd.to_numeric(df[c], errors="coerce")
81
+ df["date"] = pd.to_datetime(df["date"], errors="coerce")
82
+ df = df.sort_values("date").reset_index(drop=True)
83
+
84
+ if start:
85
+ df = df[df["date"] >= start]
86
+ if end:
87
+ df = df[df["date"] <= end]
88
+ return df.reset_index(drop=True)
89
+
90
+
91
+ # --------------- Indicators (inline) ---------------
92
+
93
+
94
+ def compute_rsi(close: pd.Series, period: int = 14) -> pd.Series:
95
+ delta = close.diff()
96
+ gain = delta.where(delta > 0, 0.0).rolling(period).mean()
97
+ loss = (-delta.where(delta < 0, 0.0)).rolling(period).mean()
98
+ rs = gain / loss.replace(0, np.nan)
99
+ return (100 - 100 / (1 + rs)).fillna(50)
100
+
101
+
102
+ def compute_ma(close: pd.Series, period: int) -> pd.Series:
103
+ return close.rolling(period).mean()
104
+
105
+
106
+ def compute_ema(close: pd.Series, period: int) -> pd.Series:
107
+ return close.ewm(span=period, adjust=False).mean()
108
+
109
+
110
+ def compute_macd_dif(close: pd.Series) -> pd.Series:
111
+ return compute_ema(close, 12) - compute_ema(close, 26)
112
+
113
+
114
+ def compute_macd_dea(close: pd.Series) -> pd.Series:
115
+ return compute_macd_dif(close).ewm(span=9, adjust=False).mean()
116
+
117
+
118
+ def compute_macd_hist(close: pd.Series) -> pd.Series:
119
+ return 2 * (compute_macd_dif(close) - compute_macd_dea(close))
120
+
121
+
122
+ def compute_volume_ratio(volume: pd.Series, period: int = 5) -> pd.Series:
123
+ ma = volume.rolling(period).mean()
124
+ return (volume / ma.replace(0, np.nan)).fillna(1)
125
+
126
+
127
+ def compute_price_change(close: pd.Series) -> pd.Series:
128
+ return close.pct_change() * 100
129
+
130
+
131
+ def compute_bollinger_position(close: pd.Series, period: int = 20) -> pd.Series:
132
+ mid = close.rolling(period).mean()
133
+ std = close.rolling(period).std()
134
+ upper = mid + 2 * std
135
+ lower = mid - 2 * std
136
+ width = (upper - lower).replace(0, np.nan)
137
+ return ((close - lower) / width).fillna(0.5)
138
+
139
+
140
+ def compute_ma_diff(close: pd.Series, period: int | None = None) -> pd.Series:
141
+ """Difference between two MAs. Period encodes both: e.g. 510 = MA5 - MA10, 1020 = MA10 - MA20."""
142
+ if period and period >= 100:
143
+ fast = period // 100
144
+ slow = period % 100
145
+ if slow == 0:
146
+ slow = fast * 4
147
+ else:
148
+ fast = 5
149
+ slow = 20
150
+ return compute_ma(close, fast) - compute_ma(close, slow)
151
+
152
+
153
+ def compute_ema_diff(close: pd.Series, period: int | None = None) -> pd.Series:
154
+ if period and period >= 100:
155
+ fast = period // 100
156
+ slow = period % 100
157
+ if slow == 0:
158
+ slow = fast * 4
159
+ else:
160
+ fast = 12
161
+ slow = 26
162
+ return compute_ema(close, fast) - compute_ema(close, slow)
163
+
164
+
165
+ def get_indicator(df: pd.DataFrame, name: str, period: int | None = None) -> pd.Series:
166
+ close = df["close"]
167
+ dispatch = {
168
+ "rsi": lambda: compute_rsi(close, period or 14),
169
+ "ma": lambda: compute_ma(close, period or 20),
170
+ "ema": lambda: compute_ema(close, period or 20),
171
+ "macd_dif": lambda: compute_macd_dif(close),
172
+ "macd_dea": lambda: compute_macd_dea(close),
173
+ "macd": lambda: compute_macd_hist(close),
174
+ "ma_diff": lambda: compute_ma_diff(close, period),
175
+ "ema_diff": lambda: compute_ema_diff(close, period),
176
+ "volume_ratio": lambda: compute_volume_ratio(df["volume"], period or 5),
177
+ "price_change": lambda: compute_price_change(close),
178
+ "bollinger_position": lambda: compute_bollinger_position(close, period or 20),
179
+ "close": lambda: close,
180
+ "volume": lambda: df["volume"].astype(float),
181
+ }
182
+ fn = dispatch.get(name.lower())
183
+ if fn is None:
184
+ raise ValueError(f"Unknown indicator: {name}")
185
+ return fn()
186
+
187
+
188
+ # --------------- Condition Evaluation ---------------
189
+
190
+
191
+ def check_condition(series: pd.Series, operator: str, value: float, idx: int) -> bool:
192
+ if idx < 1 or idx >= len(series):
193
+ return False
194
+ cur = float(series.iloc[idx])
195
+ ops = {
196
+ ">": cur > value,
197
+ "<": cur < value,
198
+ ">=": cur >= value,
199
+ "<=": cur <= value,
200
+ "==": abs(cur - value) < 1e-6,
201
+ }
202
+ if operator in ops:
203
+ return ops[operator]
204
+ prev = float(series.iloc[idx - 1])
205
+ if operator == "cross_above":
206
+ return prev <= value and cur > value
207
+ if operator == "cross_below":
208
+ return prev >= value and cur < value
209
+ return False
210
+
211
+
212
+ def evaluate_conditions(df: pd.DataFrame, conditions: list, logic: str, idx: int, cache: dict) -> tuple[bool, str]:
213
+ results = []
214
+ reasons = []
215
+ for cond in conditions:
216
+ ind_name = cond["indicator"]
217
+ period = cond.get("period")
218
+ if isinstance(period, str):
219
+ try:
220
+ period = int(float(period))
221
+ except (ValueError, TypeError):
222
+ period = None
223
+
224
+ cache_key = f"{ind_name}_{period}"
225
+ if cache_key not in cache:
226
+ cache[cache_key] = get_indicator(df, ind_name, period)
227
+ series = cache[cache_key]
228
+
229
+ op = cond["operator"]
230
+ val = float(cond["value"])
231
+ hit = check_condition(series, op, val, idx)
232
+ results.append(hit)
233
+ if hit:
234
+ cur_val = round(float(series.iloc[idx]), 2)
235
+ label = f"{ind_name}({period})" if period else ind_name
236
+ reasons.append(f"{label} = {cur_val} {op} {val}")
237
+
238
+ if logic == "all":
239
+ return all(results), "; ".join(reasons)
240
+ return any(results), "; ".join(reasons)
241
+
242
+
243
+ # --------------- Simulation ---------------
244
+
245
+
246
+ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> dict:
247
+ market = "A" if re.match(r"^\d{6}$", symbol) else "OTHER"
248
+ lot_size = 100 if market == "A" else 1
249
+ sim_cfg = strategy.get("simulation", {})
250
+ slippage = float(sim_cfg.get("slippage", 0.001))
251
+ commission = float(sim_cfg.get("commission", 0.0015))
252
+
253
+ entry = strategy.get("entry", {})
254
+ exit_ = strategy.get("exit", {})
255
+ position_cfg = strategy.get("position", {})
256
+ size_frac = float(position_cfg.get("size", 1.0))
257
+ stop_loss = float(exit_.get("stop_loss", -0.10))
258
+ take_profit = float(exit_.get("take_profit", 0.50))
259
+
260
+ entry_conditions = entry.get("conditions", [])
261
+ entry_logic = entry.get("logic", "all")
262
+ exit_conditions = exit_.get("conditions", [])
263
+ exit_logic = exit_.get("logic", "any")
264
+
265
+ cache: dict = {}
266
+ trades = []
267
+ equity_curve = []
268
+ holding = None
269
+ cash = capital
270
+ trade_id = 0
271
+
272
+ for i in range(1, len(df)):
273
+ row = df.iloc[i]
274
+ date_str = str(row["date"].date()) if hasattr(row["date"], "date") else str(row["date"])
275
+ price = float(row["close"])
276
+
277
+ if holding is None:
278
+ hit, reason = evaluate_conditions(df, entry_conditions, entry_logic, i, cache)
279
+ if hit:
280
+ buy_price = price * (1 + slippage)
281
+ buy_amount = cash * size_frac
282
+ shares = int(buy_amount / buy_price / lot_size) * lot_size
283
+ if shares <= 0:
284
+ continue
285
+ cost = shares * buy_price * (1 + commission)
286
+ cash -= cost
287
+ trade_id += 1
288
+ holding = {
289
+ "id": trade_id,
290
+ "buy_date": date_str,
291
+ "buy_price": round(buy_price, 4),
292
+ "shares": shares,
293
+ "cost": cost,
294
+ }
295
+ trades.append(
296
+ {
297
+ "id": trade_id,
298
+ "type": "buy",
299
+ "date": date_str,
300
+ "price": round(buy_price, 2),
301
+ "shares": shares,
302
+ "amount": round(cost, 2),
303
+ "reason": reason,
304
+ }
305
+ )
306
+ else:
307
+ pnl_pct = (price - holding["buy_price"]) / holding["buy_price"]
308
+ sell = False
309
+ reason = ""
310
+
311
+ if pnl_pct <= stop_loss:
312
+ sell, reason = True, f"止损触发 ({round(pnl_pct * 100, 1)}% <= {round(stop_loss * 100, 1)}%)"
313
+ elif pnl_pct >= take_profit:
314
+ sell, reason = True, f"止盈触发 ({round(pnl_pct * 100, 1)}% >= {round(take_profit * 100, 1)}%)"
315
+ elif exit_conditions:
316
+ sell, reason = evaluate_conditions(df, exit_conditions, exit_logic, i, cache)
317
+
318
+ if sell:
319
+ sell_price = price * (1 - slippage)
320
+ proceeds = holding["shares"] * sell_price * (1 - commission)
321
+ cash += proceeds
322
+ pnl = proceeds - holding["cost"]
323
+ days = 0
324
+ try:
325
+ d0 = datetime.strptime(holding["buy_date"], "%Y-%m-%d")
326
+ d1 = datetime.strptime(date_str, "%Y-%m-%d")
327
+ days = (d1 - d0).days
328
+ except ValueError:
329
+ pass
330
+ trade_id_sell = holding["id"]
331
+ trades.append(
332
+ {
333
+ "id": trade_id_sell,
334
+ "type": "sell",
335
+ "date": date_str,
336
+ "price": round(sell_price, 2),
337
+ "shares": holding["shares"],
338
+ "amount": round(proceeds, 2),
339
+ "reason": reason,
340
+ "pnl": round(pnl, 2),
341
+ "pnl_pct": round(pnl / holding["cost"], 4),
342
+ "holding_days": days,
343
+ }
344
+ )
345
+ holding = None
346
+
347
+ equity = cash
348
+ if holding:
349
+ equity += holding["shares"] * price
350
+ equity_curve.append({"date": date_str, "equity": round(equity, 2)})
351
+
352
+ if holding:
353
+ last_price = float(df["close"].iloc[-1])
354
+ equity = cash + holding["shares"] * last_price
355
+ equity_curve[-1]["equity"] = round(equity, 2)
356
+
357
+ return {
358
+ "trades": trades,
359
+ "equity_curve": equity_curve,
360
+ "final_equity": equity_curve[-1]["equity"] if equity_curve else capital,
361
+ }
362
+
363
+
364
+ # --------------- Metrics ---------------
365
+
366
+
367
+ def compute_metrics(trades: list, equity_curve: list, initial: float, final: float, start: str, end: str) -> dict:
368
+ sell_trades = [t for t in trades if t["type"] == "sell"]
369
+ total_trades = len(sell_trades)
370
+ winning = [t for t in sell_trades if t.get("pnl", 0) > 0]
371
+ losing = [t for t in sell_trades if t.get("pnl", 0) <= 0]
372
+
373
+ total_return = (final - initial) / initial if initial else 0
374
+ try:
375
+ d0 = datetime.strptime(start, "%Y-%m-%d")
376
+ d1 = datetime.strptime(end, "%Y-%m-%d")
377
+ years = (d1 - d0).days / 365.25
378
+ except (ValueError, TypeError):
379
+ years = 1
380
+ annual_return = (1 + total_return) ** (1 / max(years, 0.01)) - 1 if total_return > -1 else total_return
381
+
382
+ equities = pd.Series([e["equity"] for e in equity_curve], dtype=float)
383
+ peak = equities.cummax()
384
+ dd = (equities - peak) / peak
385
+ max_drawdown = float(dd.min()) if len(dd) > 0 else 0
386
+
387
+ daily_returns = equities.pct_change().dropna()
388
+ if len(daily_returns) > 1 and daily_returns.std() > 0:
389
+ sharpe = (daily_returns.mean() - 0.03 / 252) / daily_returns.std() * math.sqrt(252)
390
+ else:
391
+ sharpe = 0
392
+
393
+ win_rate = len(winning) / total_trades if total_trades else 0
394
+ avg_win = np.mean([t["pnl"] for t in winning]) if winning else 0
395
+ avg_loss = abs(np.mean([t["pnl"] for t in losing])) if losing else 1
396
+ pl_ratio = avg_win / avg_loss if avg_loss > 0 else float("inf")
397
+
398
+ avg_days = np.mean([t.get("holding_days", 0) for t in sell_trades]) if sell_trades else 0
399
+
400
+ max_cw = max_cl = cw = cl = 0
401
+ for t in sell_trades:
402
+ if t.get("pnl", 0) > 0:
403
+ cw += 1
404
+ cl = 0
405
+ else:
406
+ cl += 1
407
+ cw = 0
408
+ max_cw = max(max_cw, cw)
409
+ max_cl = max(max_cl, cl)
410
+
411
+ return {
412
+ "total_return": round(total_return, 4),
413
+ "annual_return": round(annual_return, 4),
414
+ "max_drawdown": round(max_drawdown, 4),
415
+ "sharpe_ratio": round(sharpe, 2),
416
+ "win_rate": round(win_rate, 4),
417
+ "profit_loss_ratio": round(pl_ratio, 2),
418
+ "total_trades": total_trades,
419
+ "winning_trades": len(winning),
420
+ "losing_trades": len(losing),
421
+ "avg_holding_days": round(avg_days, 1),
422
+ "max_consecutive_wins": max_cw,
423
+ "max_consecutive_losses": max_cl,
424
+ }
425
+
426
+
427
+ def diagnose(metrics: dict) -> dict:
428
+ strengths, weaknesses, suggestions = [], [], []
429
+ wr = metrics["win_rate"]
430
+ if wr >= 0.6:
431
+ strengths.append(f"胜率较高 ({round(wr * 100, 1)}%)")
432
+ elif wr < 0.4:
433
+ weaknesses.append(f"胜率偏低 ({round(wr * 100, 1)}%)")
434
+
435
+ plr = metrics["profit_loss_ratio"]
436
+ if plr >= 2:
437
+ strengths.append(f"盈亏比优秀 ({plr}:1)")
438
+ elif plr < 1:
439
+ weaknesses.append(f"盈亏比不足 ({plr}:1)")
440
+ suggestions.append("考虑提高止盈目标或收紧止损")
441
+
442
+ mdd = abs(metrics["max_drawdown"])
443
+ if mdd > 0.2:
444
+ weaknesses.append(f"最大回撤较大 ({round(mdd * 100, 1)}%)")
445
+ suggestions.append("建议增加止损保护或减小仓位比例")
446
+ elif mdd < 0.1:
447
+ strengths.append(f"回撤控制良好 ({round(mdd * 100, 1)}%)")
448
+
449
+ sr = metrics["sharpe_ratio"]
450
+ if sr > 1.5:
451
+ strengths.append(f"夏普比率优秀 ({sr})")
452
+ elif sr < 0.5:
453
+ weaknesses.append(f"风险调整收益较低(夏普={sr})")
454
+
455
+ if metrics["total_trades"] < 5:
456
+ weaknesses.append("交易次数过少,统计意义有限")
457
+ suggestions.append("考虑放宽入场条件或延长回测周期")
458
+
459
+ return {"strengths": strengths, "weaknesses": weaknesses, "suggestions": suggestions}
460
+
461
+
462
+ def diagnose_advanced(metrics: dict, trades: list, equity_curve: list, strategy: dict) -> dict:
463
+ """Extra agent-friendly diagnostics: failure reason, regime fit, parameter hints."""
464
+ exit_cfg = strategy.get("exit") or {}
465
+ sl_val = exit_cfg.get("stop_loss")
466
+ stop_loss = float(sl_val) if sl_val is not None else -0.10
467
+ tp_val = exit_cfg.get("take_profit")
468
+ take_profit = float(tp_val) if tp_val is not None else 0.50
469
+
470
+ total = metrics.get("total_trades", 0)
471
+ win_rate = metrics.get("win_rate", 0)
472
+ plr = metrics.get("profit_loss_ratio", 0)
473
+ mdd = abs(metrics.get("max_drawdown", 0))
474
+ total_return = metrics.get("total_return", 0)
475
+
476
+ # trade_count_quality
477
+ if total < 5:
478
+ trade_count_quality = "too_low"
479
+ elif total < 15:
480
+ trade_count_quality = "marginal"
481
+ else:
482
+ trade_count_quality = "sufficient"
483
+
484
+ # main_failure_reason — pick the most impactful weakness
485
+ sell_trades = [t for t in trades if t.get("action") == "sell"]
486
+ stop_hits = sum(
487
+ 1
488
+ for t in sell_trades
489
+ if (t.get("reason") or "").startswith("stop_loss")
490
+ or (t.get("pnl_pct", 0) is not None and t.get("pnl_pct", 0) <= stop_loss * 100 + 0.5)
491
+ )
492
+ stop_ratio = stop_hits / max(1, len(sell_trades))
493
+
494
+ main_failure_reason = None
495
+ if total_return < 0:
496
+ if stop_ratio > 0.5:
497
+ main_failure_reason = "止损频繁触发,可能过紧或市场震荡不匹配"
498
+ elif win_rate < 0.35:
499
+ main_failure_reason = "胜率过低,入场信号质量差"
500
+ elif plr < 1:
501
+ main_failure_reason = "盈亏比不足,盈利未能覆盖亏损"
502
+ else:
503
+ main_failure_reason = "整体信号频次或时机不佳"
504
+ elif mdd > 0.25:
505
+ main_failure_reason = "收益为正但回撤过大,风险控制不足"
506
+
507
+ # regime_fit — infer from equity curve shape
508
+ regime_fit = "unknown"
509
+ if len(equity_curve) >= 3:
510
+ # split into halves, compare
511
+ mid = len(equity_curve) // 2
512
+ first = equity_curve[mid][1] if isinstance(equity_curve[mid], list) else equity_curve[mid]
513
+ last = equity_curve[-1][1] if isinstance(equity_curve[-1], list) else equity_curve[-1]
514
+ start_v = equity_curve[0][1] if isinstance(equity_curve[0], list) else equity_curve[0]
515
+ first_half = (first - start_v) / start_v if start_v else 0
516
+ second_half = (last - first) / first if first else 0
517
+ if first_half > 0.05 and second_half > 0.05:
518
+ regime_fit = "consistent_across_periods"
519
+ elif first_half > 0.05 and second_half < -0.02:
520
+ regime_fit = "better_in_early_period"
521
+ elif first_half < -0.02 and second_half > 0.05:
522
+ regime_fit = "better_in_late_period"
523
+ elif win_rate > 0.5 and total_return > 0:
524
+ regime_fit = "better_in_trend_market"
525
+ else:
526
+ regime_fit = "regime_dependent"
527
+
528
+ # suggested_parameter_changes
529
+ suggestions = []
530
+ if stop_ratio > 0.5 and total_return < 0:
531
+ suggestions.append(
532
+ {
533
+ "parameter": "exit.stop_loss",
534
+ "from": stop_loss,
535
+ "to": round(stop_loss * 1.5, 3),
536
+ "reason": "止损过紧,被震荡打出",
537
+ }
538
+ )
539
+ if plr < 1 and win_rate > 0.4:
540
+ suggestions.append(
541
+ {
542
+ "parameter": "exit.take_profit",
543
+ "from": take_profit,
544
+ "to": round(take_profit * 1.3, 3),
545
+ "reason": "止盈过早,盈亏比偏低",
546
+ }
547
+ )
548
+ if trade_count_quality == "too_low":
549
+ suggestions.append(
550
+ {
551
+ "parameter": "entry.*",
552
+ "from": None,
553
+ "to": None,
554
+ "reason": "入场条件过严,交易次数不足",
555
+ }
556
+ )
557
+ if mdd > 0.25:
558
+ suggestions.append(
559
+ {
560
+ "parameter": "position.size",
561
+ "from": None,
562
+ "to": None,
563
+ "reason": "回撤大,考虑降低仓位比例",
564
+ }
565
+ )
566
+
567
+ return {
568
+ "trade_count_quality": trade_count_quality,
569
+ "main_failure_reason": main_failure_reason,
570
+ "regime_fit": regime_fit,
571
+ "stop_loss_hit_ratio": round(stop_ratio, 2),
572
+ "suggested_parameter_changes": suggestions,
573
+ }
574
+
575
+
576
+ def sample_curve(curve: list, max_points: int = 200) -> list:
577
+ if len(curve) <= max_points:
578
+ return curve
579
+ step = len(curve) / max_points
580
+ indices = [int(i * step) for i in range(max_points)]
581
+ if indices[-1] != len(curve) - 1:
582
+ indices.append(len(curve) - 1)
583
+ return [curve[i] for i in indices]
584
+
585
+
586
+ # --------------- Entry Points ---------------
587
+
588
+
589
+ def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str | None, capital: float) -> dict:
590
+ strategy = load_strategy(strategy_path)
591
+
592
+ if not end:
593
+ end = datetime.now().strftime("%Y-%m-%d")
594
+ if not start:
595
+ start = (datetime.now() - timedelta(days=365)).strftime("%Y-%m-%d")
596
+
597
+ df = fetch_kline(symbol, start, end)
598
+ if len(df) < 30:
599
+ return {"error": f"Insufficient data: {len(df)} rows (need at least 30)"}
600
+
601
+ sim = simulate(df, strategy, capital, symbol)
602
+ final = sim["final_equity"]
603
+ metrics = compute_metrics(sim["trades"], sim["equity_curve"], capital, final, start, end)
604
+
605
+ return {
606
+ "strategy": strategy.get("name", "unnamed"),
607
+ "symbol": symbol,
608
+ "period": f"{start} to {end}",
609
+ "initial_capital": capital,
610
+ "final_capital": final,
611
+ "metrics": metrics,
612
+ "trades": sim["trades"],
613
+ "equity_curve": sample_curve(sim["equity_curve"]),
614
+ "diagnosis": diagnose(metrics),
615
+ "diagnostics": diagnose_advanced(metrics, sim["trades"], sim["equity_curve"], strategy),
616
+ }
617
+
618
+
619
+ def evaluate_result(path: str) -> dict:
620
+ with open(path, encoding="utf-8") as f:
621
+ data = json.load(f)
622
+ trades = data.get("trades", [])
623
+ curve = data.get("equity_curve", [])
624
+ initial = data.get("initial_capital", 1000000)
625
+ final = data.get("final_capital", initial)
626
+ period = data.get("period", "unknown")
627
+ parts = period.split(" to ") if " to " in period else [period, period]
628
+ metrics = compute_metrics(trades, curve, initial, final, parts[0], parts[1])
629
+ data["metrics"] = metrics
630
+ data["diagnosis"] = diagnose(metrics)
631
+ return data
632
+
633
+
634
+ # --------------- Signal Evaluation ---------------
635
+
636
+ SIGNAL_DEFINITIONS = {
637
+ "macd_golden_cross": lambda df, i: (
638
+ i >= 1
639
+ and float(compute_macd_dif(df["close"]).iloc[i]) > float(compute_macd_dea(df["close"]).iloc[i])
640
+ and float(compute_macd_dif(df["close"]).iloc[i - 1]) <= float(compute_macd_dea(df["close"]).iloc[i - 1])
641
+ ),
642
+ "macd_death_cross": lambda df, i: (
643
+ i >= 1
644
+ and float(compute_macd_dif(df["close"]).iloc[i]) < float(compute_macd_dea(df["close"]).iloc[i])
645
+ and float(compute_macd_dif(df["close"]).iloc[i - 1]) >= float(compute_macd_dea(df["close"]).iloc[i - 1])
646
+ ),
647
+ "rsi_oversold": lambda df, i: float(compute_rsi(df["close"], 14).iloc[i]) < 30,
648
+ "rsi_overbought": lambda df, i: float(compute_rsi(df["close"], 14).iloc[i]) > 70,
649
+ "breakout_20d": lambda df, i: (
650
+ i >= 20
651
+ and float(df["close"].iloc[i]) > float(df["high"].iloc[i - 20 : i].max())
652
+ and float(df["close"].iloc[i - 1]) <= float(df["high"].iloc[i - 20 : i].max())
653
+ ),
654
+ "breakdown_20d": lambda df, i: (
655
+ i >= 20
656
+ and float(df["close"].iloc[i]) < float(df["low"].iloc[i - 20 : i].min())
657
+ and float(df["close"].iloc[i - 1]) >= float(df["low"].iloc[i - 20 : i].min())
658
+ ),
659
+ "volume_surge": lambda df, i: (
660
+ i >= 20 and float(df["volume"].iloc[i]) > 2.0 * float(df["volume"].iloc[i - 20 : i].mean())
661
+ ),
662
+ "ma_golden_cross": lambda df, i: (
663
+ i >= 20
664
+ and float(compute_ma(df["close"], 5).iloc[i]) > float(compute_ma(df["close"], 20).iloc[i])
665
+ and float(compute_ma(df["close"], 5).iloc[i - 1]) <= float(compute_ma(df["close"], 20).iloc[i - 1])
666
+ ),
667
+ "ma_death_cross": lambda df, i: (
668
+ i >= 20
669
+ and float(compute_ma(df["close"], 5).iloc[i]) < float(compute_ma(df["close"], 20).iloc[i])
670
+ and float(compute_ma(df["close"], 5).iloc[i - 1]) >= float(compute_ma(df["close"], 20).iloc[i - 1])
671
+ ),
672
+ }
673
+
674
+
675
+ def evaluate_signal(symbol: str, signal_name: str, forward_days: list[int] = None, lookback: int = 250) -> dict:
676
+ if forward_days is None:
677
+ forward_days = [3, 5, 10]
678
+ if signal_name not in SIGNAL_DEFINITIONS:
679
+ return {"error": f"Unknown signal: {signal_name}. Available: {list(SIGNAL_DEFINITIONS.keys())}"}
680
+
681
+ checker = SIGNAL_DEFINITIONS[signal_name]
682
+ end = datetime.now().strftime("%Y-%m-%d")
683
+ start = (datetime.now() - timedelta(days=int(lookback * 1.5))).strftime("%Y-%m-%d")
684
+ df = fetch_kline(symbol, start, end)
685
+ if len(df) < 30:
686
+ return {"error": f"Insufficient data: {len(df)} rows"}
687
+
688
+ max_fwd = max(forward_days)
689
+ occurrences = []
690
+ for i in range(20, len(df) - max_fwd):
691
+ try:
692
+ if checker(df, i):
693
+ entry_price = float(df["close"].iloc[i])
694
+ date_str = (
695
+ str(df["date"].iloc[i].date()) if hasattr(df["date"].iloc[i], "date") else str(df["date"].iloc[i])
696
+ )
697
+ fwd_returns = {}
698
+ for fd in forward_days:
699
+ if i + fd < len(df):
700
+ fwd_price = float(df["close"].iloc[i + fd])
701
+ fwd_returns[f"return_{fd}d"] = round((fwd_price - entry_price) / entry_price * 100, 2)
702
+ occurrences.append({"date": date_str, "price": round(entry_price, 2), **fwd_returns})
703
+ except Exception:
704
+ continue
705
+
706
+ if not occurrences:
707
+ return {"signal": signal_name, "symbol": symbol, "occurrences": 0, "note": "No signal found in period"}
708
+
709
+ result = {"signal": signal_name, "symbol": symbol, "occurrences": len(occurrences)}
710
+ for fd in forward_days:
711
+ key = f"return_{fd}d"
712
+ vals = [o[key] for o in occurrences if key in o]
713
+ if vals:
714
+ result[f"avg_return_{fd}d"] = round(np.mean(vals), 2)
715
+ result[f"win_rate_{fd}d"] = round(sum(1 for v in vals if v > 0) / len(vals), 4)
716
+ result["samples"] = occurrences[-10:]
717
+ return result
718
+
719
+
720
+ def main():
721
+ parser = argparse.ArgumentParser(description="AlphaEvo strategy backtester")
722
+ sub = parser.add_subparsers(dest="command")
723
+
724
+ p_run = sub.add_parser("run")
725
+ p_run.add_argument("strategy", help="Path to strategy YAML file")
726
+ p_run.add_argument("symbol", help="Stock symbol")
727
+ p_run.add_argument("--start", help="Start date (YYYY-MM-DD)")
728
+ p_run.add_argument("--end", help="End date (YYYY-MM-DD)")
729
+ p_run.add_argument("--capital", type=float, default=1000000)
730
+
731
+ p_eval = sub.add_parser("evaluate")
732
+ p_eval.add_argument("result", help="Path to result JSON file")
733
+
734
+ p_sig = sub.add_parser("evaluate_signal")
735
+ p_sig.add_argument("symbol", help="Stock symbol")
736
+ p_sig.add_argument("signal", help="Signal name (e.g. macd_golden_cross)")
737
+ p_sig.add_argument("--forward", default="3,5,10", help="Comma-separated forward days")
738
+ p_sig.add_argument("--lookback", type=int, default=250)
739
+
740
+ args = parser.parse_args()
741
+ if not args.command:
742
+ parser.print_help()
743
+ sys.exit(1)
744
+
745
+ if args.command == "run":
746
+ result = run_backtest(args.strategy, args.symbol, args.start, args.end, args.capital)
747
+ elif args.command == "evaluate":
748
+ result = evaluate_result(args.result)
749
+ elif args.command == "evaluate_signal":
750
+ fwd = [int(x) for x in args.forward.split(",")]
751
+ result = evaluate_signal(args.symbol, args.signal, fwd, args.lookback)
752
+ else:
753
+ result = {"error": f"Unknown command: {args.command}"}
754
+
755
+ print(json.dumps(result, ensure_ascii=False, default=str))
756
+
757
+
758
+ if __name__ == "__main__":
759
+ # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
760
+ # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
761
+ for _s in (sys.stdout, sys.stderr):
762
+ if hasattr(_s, "reconfigure"):
763
+ _s.reconfigure(encoding="utf-8")
764
+ main()