@weaxs/openclaw-stock-analysis 0.1.3

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 (71) hide show
  1. package/README.md +70 -0
  2. package/index.ts +761 -0
  3. package/openclaw.plugin.json +47 -0
  4. package/package.json +46 -0
  5. package/schemas/report_schema.json +131 -0
  6. package/scripts/setup-python.mjs +52 -0
  7. package/skills/bottom-volume/SKILL.md +63 -0
  8. package/skills/bottom-volume/scripts/gather.py +15 -0
  9. package/skills/box-oscillation/SKILL.md +72 -0
  10. package/skills/box-oscillation/scripts/gather.py +15 -0
  11. package/skills/bull-trend/SKILL.md +60 -0
  12. package/skills/bull-trend/scripts/gather.py +15 -0
  13. package/skills/chan-theory/SKILL.md +71 -0
  14. package/skills/chan-theory/scripts/gather.py +15 -0
  15. package/skills/dragon-head/SKILL.md +69 -0
  16. package/skills/dragon-head/scripts/gather.py +15 -0
  17. package/skills/emotion-cycle/SKILL.md +65 -0
  18. package/skills/emotion-cycle/scripts/gather.py +15 -0
  19. package/skills/event-driven/SKILL.md +73 -0
  20. package/skills/event-driven/scripts/gather.py +15 -0
  21. package/skills/expectation-repricing/SKILL.md +72 -0
  22. package/skills/expectation-repricing/scripts/gather.py +15 -0
  23. package/skills/growth-quality/SKILL.md +74 -0
  24. package/skills/growth-quality/scripts/gather.py +15 -0
  25. package/skills/hot-theme/SKILL.md +74 -0
  26. package/skills/hot-theme/scripts/gather.py +15 -0
  27. package/skills/ma-crossover/SKILL.md +63 -0
  28. package/skills/ma-crossover/scripts/gather.py +15 -0
  29. package/skills/market-review/SKILL.md +70 -0
  30. package/skills/market-review/scripts/gather.py +16 -0
  31. package/skills/one-yang-three-yin/SKILL.md +74 -0
  32. package/skills/one-yang-three-yin/scripts/gather.py +15 -0
  33. package/skills/shrink-pullback/SKILL.md +59 -0
  34. package/skills/shrink-pullback/scripts/gather.py +15 -0
  35. package/skills/stock-analysis/SKILL.md +134 -0
  36. package/skills/stock-analysis/scripts/gather.py +15 -0
  37. package/skills/stock-screener/SKILL.md +68 -0
  38. package/skills/stock-screener/scripts/gather.py +15 -0
  39. package/skills/strategy-backtest/SKILL.md +129 -0
  40. package/skills/strategy-backtest/scripts/gather.py +16 -0
  41. package/skills/volume-breakout/SKILL.md +58 -0
  42. package/skills/volume-breakout/scripts/gather.py +15 -0
  43. package/skills/wave-theory/SKILL.md +67 -0
  44. package/skills/wave-theory/scripts/gather.py +15 -0
  45. package/skills/wisburg-research/SKILL.md +119 -0
  46. package/strategies/examples/bottom_volume.yaml +47 -0
  47. package/strategies/examples/box_oscillation.yaml +41 -0
  48. package/strategies/examples/bull_trend.yaml +42 -0
  49. package/strategies/examples/dragon_head.yaml +45 -0
  50. package/strategies/examples/emotion_cycle.yaml +43 -0
  51. package/strategies/examples/ma_crossover.yaml +34 -0
  52. package/strategies/examples/rsi_oversold.yaml +35 -0
  53. package/strategies/examples/shrink_pullback.yaml +45 -0
  54. package/strategies/examples/volume_breakout.yaml +42 -0
  55. package/tools/__init__.py +0 -0
  56. package/tools/anomaly_detect.py +570 -0
  57. package/tools/backtest.py +643 -0
  58. package/tools/gather.py +152 -0
  59. package/tools/market_regime.py +247 -0
  60. package/tools/market_review.py +150 -0
  61. package/tools/name_resolver.py +131 -0
  62. package/tools/pattern.py +509 -0
  63. package/tools/requirements.txt +13 -0
  64. package/tools/risk_screening.py +318 -0
  65. package/tools/screener.py +213 -0
  66. package/tools/search_intel.py +455 -0
  67. package/tools/stock_data.py +1649 -0
  68. package/tools/technical.py +636 -0
  69. package/tools/trading_calendar.py +198 -0
  70. package/tools/volume_analysis.py +172 -0
  71. package/tools/watchlist.py +61 -0
@@ -0,0 +1,643 @@
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
+ )
72
+ data = json.loads(r.stdout)
73
+ if isinstance(data, dict) and "error" in data:
74
+ raise RuntimeError(data["error"])
75
+
76
+ df = pd.DataFrame(data)
77
+ for c in ["open", "high", "low", "close", "volume"]:
78
+ if c in df.columns:
79
+ df[c] = pd.to_numeric(df[c], errors="coerce")
80
+ df["date"] = pd.to_datetime(df["date"], errors="coerce")
81
+ df = df.sort_values("date").reset_index(drop=True)
82
+
83
+ if start:
84
+ df = df[df["date"] >= start]
85
+ if end:
86
+ df = df[df["date"] <= end]
87
+ return df.reset_index(drop=True)
88
+
89
+
90
+ # --------------- Indicators (inline) ---------------
91
+
92
+
93
+ def compute_rsi(close: pd.Series, period: int = 14) -> pd.Series:
94
+ delta = close.diff()
95
+ gain = delta.where(delta > 0, 0.0).rolling(period).mean()
96
+ loss = (-delta.where(delta < 0, 0.0)).rolling(period).mean()
97
+ rs = gain / loss.replace(0, np.nan)
98
+ return (100 - 100 / (1 + rs)).fillna(50)
99
+
100
+
101
+ def compute_ma(close: pd.Series, period: int) -> pd.Series:
102
+ return close.rolling(period).mean()
103
+
104
+
105
+ def compute_ema(close: pd.Series, period: int) -> pd.Series:
106
+ return close.ewm(span=period, adjust=False).mean()
107
+
108
+
109
+ def compute_macd_dif(close: pd.Series) -> pd.Series:
110
+ return compute_ema(close, 12) - compute_ema(close, 26)
111
+
112
+
113
+ def compute_macd_dea(close: pd.Series) -> pd.Series:
114
+ return compute_macd_dif(close).ewm(span=9, adjust=False).mean()
115
+
116
+
117
+ def compute_macd_hist(close: pd.Series) -> pd.Series:
118
+ return 2 * (compute_macd_dif(close) - compute_macd_dea(close))
119
+
120
+
121
+ def compute_volume_ratio(volume: pd.Series, period: int = 5) -> pd.Series:
122
+ ma = volume.rolling(period).mean()
123
+ return (volume / ma.replace(0, np.nan)).fillna(1)
124
+
125
+
126
+ def compute_price_change(close: pd.Series) -> pd.Series:
127
+ return close.pct_change() * 100
128
+
129
+
130
+ def compute_bollinger_position(close: pd.Series, period: int = 20) -> pd.Series:
131
+ mid = close.rolling(period).mean()
132
+ std = close.rolling(period).std()
133
+ upper = mid + 2 * std
134
+ lower = mid - 2 * std
135
+ width = (upper - lower).replace(0, np.nan)
136
+ return ((close - lower) / width).fillna(0.5)
137
+
138
+
139
+ def compute_ma_diff(close: pd.Series, period: int | None = None) -> pd.Series:
140
+ """Difference between two MAs. Period encodes both: e.g. 510 = MA5 - MA10, 1020 = MA10 - MA20."""
141
+ if period and period >= 100:
142
+ fast = period // 100
143
+ slow = period % 100
144
+ if slow == 0:
145
+ slow = fast * 4
146
+ else:
147
+ fast = 5
148
+ slow = 20
149
+ return compute_ma(close, fast) - compute_ma(close, slow)
150
+
151
+
152
+ def compute_ema_diff(close: pd.Series, period: int | None = None) -> pd.Series:
153
+ if period and period >= 100:
154
+ fast = period // 100
155
+ slow = period % 100
156
+ if slow == 0:
157
+ slow = fast * 4
158
+ else:
159
+ fast = 12
160
+ slow = 26
161
+ return compute_ema(close, fast) - compute_ema(close, slow)
162
+
163
+
164
+ def get_indicator(df: pd.DataFrame, name: str, period: int | None = None) -> pd.Series:
165
+ close = df["close"]
166
+ dispatch = {
167
+ "rsi": lambda: compute_rsi(close, period or 14),
168
+ "ma": lambda: compute_ma(close, period or 20),
169
+ "ema": lambda: compute_ema(close, period or 20),
170
+ "macd_dif": lambda: compute_macd_dif(close),
171
+ "macd_dea": lambda: compute_macd_dea(close),
172
+ "macd": lambda: compute_macd_hist(close),
173
+ "ma_diff": lambda: compute_ma_diff(close, period),
174
+ "ema_diff": lambda: compute_ema_diff(close, period),
175
+ "volume_ratio": lambda: compute_volume_ratio(df["volume"], period or 5),
176
+ "price_change": lambda: compute_price_change(close),
177
+ "bollinger_position": lambda: compute_bollinger_position(close, period or 20),
178
+ "close": lambda: close,
179
+ "volume": lambda: df["volume"].astype(float),
180
+ }
181
+ fn = dispatch.get(name.lower())
182
+ if fn is None:
183
+ raise ValueError(f"Unknown indicator: {name}")
184
+ return fn()
185
+
186
+
187
+ # --------------- Condition Evaluation ---------------
188
+
189
+
190
+ def check_condition(series: pd.Series, operator: str, value: float, idx: int) -> bool:
191
+ if idx < 1 or idx >= len(series):
192
+ return False
193
+ cur = float(series.iloc[idx])
194
+ ops = {
195
+ ">": cur > value,
196
+ "<": cur < value,
197
+ ">=": cur >= value,
198
+ "<=": cur <= value,
199
+ "==": abs(cur - value) < 1e-6,
200
+ }
201
+ if operator in ops:
202
+ return ops[operator]
203
+ prev = float(series.iloc[idx - 1])
204
+ if operator == "cross_above":
205
+ return prev <= value and cur > value
206
+ if operator == "cross_below":
207
+ return prev >= value and cur < value
208
+ return False
209
+
210
+
211
+ def evaluate_conditions(df: pd.DataFrame, conditions: list, logic: str, idx: int, cache: dict) -> tuple[bool, str]:
212
+ results = []
213
+ reasons = []
214
+ for cond in conditions:
215
+ ind_name = cond["indicator"]
216
+ period = cond.get("period")
217
+ if isinstance(period, str):
218
+ try:
219
+ period = int(float(period))
220
+ except (ValueError, TypeError):
221
+ period = None
222
+
223
+ cache_key = f"{ind_name}_{period}"
224
+ if cache_key not in cache:
225
+ cache[cache_key] = get_indicator(df, ind_name, period)
226
+ series = cache[cache_key]
227
+
228
+ op = cond["operator"]
229
+ val = float(cond["value"])
230
+ hit = check_condition(series, op, val, idx)
231
+ results.append(hit)
232
+ if hit:
233
+ cur_val = round(float(series.iloc[idx]), 2)
234
+ label = f"{ind_name}({period})" if period else ind_name
235
+ reasons.append(f"{label} = {cur_val} {op} {val}")
236
+
237
+ if logic == "all":
238
+ return all(results), "; ".join(reasons)
239
+ return any(results), "; ".join(reasons)
240
+
241
+
242
+ # --------------- Simulation ---------------
243
+
244
+
245
+ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> dict:
246
+ market = "A" if re.match(r"^\d{6}$", symbol) else "OTHER"
247
+ lot_size = 100 if market == "A" else 1
248
+ sim_cfg = strategy.get("simulation", {})
249
+ slippage = float(sim_cfg.get("slippage", 0.001))
250
+ commission = float(sim_cfg.get("commission", 0.0015))
251
+
252
+ entry = strategy.get("entry", {})
253
+ exit_ = strategy.get("exit", {})
254
+ position_cfg = strategy.get("position", {})
255
+ size_frac = float(position_cfg.get("size", 1.0))
256
+ stop_loss = float(exit_.get("stop_loss", -0.10))
257
+ take_profit = float(exit_.get("take_profit", 0.50))
258
+
259
+ entry_conditions = entry.get("conditions", [])
260
+ entry_logic = entry.get("logic", "all")
261
+ exit_conditions = exit_.get("conditions", [])
262
+ exit_logic = exit_.get("logic", "any")
263
+
264
+ cache: dict = {}
265
+ trades = []
266
+ equity_curve = []
267
+ holding = None
268
+ cash = capital
269
+ trade_id = 0
270
+
271
+ for i in range(1, len(df)):
272
+ row = df.iloc[i]
273
+ date_str = str(row["date"].date()) if hasattr(row["date"], "date") else str(row["date"])
274
+ price = float(row["close"])
275
+
276
+ if holding is None:
277
+ hit, reason = evaluate_conditions(df, entry_conditions, entry_logic, i, cache)
278
+ if hit:
279
+ buy_price = price * (1 + slippage)
280
+ buy_amount = cash * size_frac
281
+ shares = int(buy_amount / buy_price / lot_size) * lot_size
282
+ if shares <= 0:
283
+ continue
284
+ cost = shares * buy_price * (1 + commission)
285
+ cash -= cost
286
+ trade_id += 1
287
+ holding = {
288
+ "id": trade_id,
289
+ "buy_date": date_str,
290
+ "buy_price": round(buy_price, 4),
291
+ "shares": shares,
292
+ "cost": cost,
293
+ }
294
+ trades.append(
295
+ {
296
+ "id": trade_id,
297
+ "type": "buy",
298
+ "date": date_str,
299
+ "price": round(buy_price, 2),
300
+ "shares": shares,
301
+ "amount": round(cost, 2),
302
+ "reason": reason,
303
+ }
304
+ )
305
+ else:
306
+ pnl_pct = (price - holding["buy_price"]) / holding["buy_price"]
307
+ sell = False
308
+ reason = ""
309
+
310
+ if pnl_pct <= stop_loss:
311
+ sell, reason = True, f"止损触发 ({round(pnl_pct * 100, 1)}% <= {round(stop_loss * 100, 1)}%)"
312
+ elif pnl_pct >= take_profit:
313
+ sell, reason = True, f"止盈触发 ({round(pnl_pct * 100, 1)}% >= {round(take_profit * 100, 1)}%)"
314
+ elif exit_conditions:
315
+ sell, reason = evaluate_conditions(df, exit_conditions, exit_logic, i, cache)
316
+
317
+ if sell:
318
+ sell_price = price * (1 - slippage)
319
+ proceeds = holding["shares"] * sell_price * (1 - commission)
320
+ cash += proceeds
321
+ pnl = proceeds - holding["cost"]
322
+ days = 0
323
+ try:
324
+ d0 = datetime.strptime(holding["buy_date"], "%Y-%m-%d")
325
+ d1 = datetime.strptime(date_str, "%Y-%m-%d")
326
+ days = (d1 - d0).days
327
+ except ValueError:
328
+ pass
329
+ trade_id_sell = holding["id"]
330
+ trades.append(
331
+ {
332
+ "id": trade_id_sell,
333
+ "type": "sell",
334
+ "date": date_str,
335
+ "price": round(sell_price, 2),
336
+ "shares": holding["shares"],
337
+ "amount": round(proceeds, 2),
338
+ "reason": reason,
339
+ "pnl": round(pnl, 2),
340
+ "pnl_pct": round(pnl / holding["cost"], 4),
341
+ "holding_days": days,
342
+ }
343
+ )
344
+ holding = None
345
+
346
+ equity = cash
347
+ if holding:
348
+ equity += holding["shares"] * price
349
+ equity_curve.append({"date": date_str, "equity": round(equity, 2)})
350
+
351
+ if holding:
352
+ last_price = float(df["close"].iloc[-1])
353
+ equity = cash + holding["shares"] * last_price
354
+ equity_curve[-1]["equity"] = round(equity, 2)
355
+
356
+ return {
357
+ "trades": trades,
358
+ "equity_curve": equity_curve,
359
+ "final_equity": equity_curve[-1]["equity"] if equity_curve else capital,
360
+ }
361
+
362
+
363
+ # --------------- Metrics ---------------
364
+
365
+
366
+ def compute_metrics(trades: list, equity_curve: list, initial: float, final: float, start: str, end: str) -> dict:
367
+ sell_trades = [t for t in trades if t["type"] == "sell"]
368
+ total_trades = len(sell_trades)
369
+ winning = [t for t in sell_trades if t.get("pnl", 0) > 0]
370
+ losing = [t for t in sell_trades if t.get("pnl", 0) <= 0]
371
+
372
+ total_return = (final - initial) / initial if initial else 0
373
+ try:
374
+ d0 = datetime.strptime(start, "%Y-%m-%d")
375
+ d1 = datetime.strptime(end, "%Y-%m-%d")
376
+ years = (d1 - d0).days / 365.25
377
+ except (ValueError, TypeError):
378
+ years = 1
379
+ annual_return = (1 + total_return) ** (1 / max(years, 0.01)) - 1 if total_return > -1 else total_return
380
+
381
+ equities = pd.Series([e["equity"] for e in equity_curve], dtype=float)
382
+ peak = equities.cummax()
383
+ dd = (equities - peak) / peak
384
+ max_drawdown = float(dd.min()) if len(dd) > 0 else 0
385
+
386
+ daily_returns = equities.pct_change().dropna()
387
+ if len(daily_returns) > 1 and daily_returns.std() > 0:
388
+ sharpe = (daily_returns.mean() - 0.03 / 252) / daily_returns.std() * math.sqrt(252)
389
+ else:
390
+ sharpe = 0
391
+
392
+ win_rate = len(winning) / total_trades if total_trades else 0
393
+ avg_win = np.mean([t["pnl"] for t in winning]) if winning else 0
394
+ avg_loss = abs(np.mean([t["pnl"] for t in losing])) if losing else 1
395
+ pl_ratio = avg_win / avg_loss if avg_loss > 0 else float("inf")
396
+
397
+ avg_days = np.mean([t.get("holding_days", 0) for t in sell_trades]) if sell_trades else 0
398
+
399
+ max_cw = max_cl = cw = cl = 0
400
+ for t in sell_trades:
401
+ if t.get("pnl", 0) > 0:
402
+ cw += 1
403
+ cl = 0
404
+ else:
405
+ cl += 1
406
+ cw = 0
407
+ max_cw = max(max_cw, cw)
408
+ max_cl = max(max_cl, cl)
409
+
410
+ return {
411
+ "total_return": round(total_return, 4),
412
+ "annual_return": round(annual_return, 4),
413
+ "max_drawdown": round(max_drawdown, 4),
414
+ "sharpe_ratio": round(sharpe, 2),
415
+ "win_rate": round(win_rate, 4),
416
+ "profit_loss_ratio": round(pl_ratio, 2),
417
+ "total_trades": total_trades,
418
+ "winning_trades": len(winning),
419
+ "losing_trades": len(losing),
420
+ "avg_holding_days": round(avg_days, 1),
421
+ "max_consecutive_wins": max_cw,
422
+ "max_consecutive_losses": max_cl,
423
+ }
424
+
425
+
426
+ def diagnose(metrics: dict) -> dict:
427
+ strengths, weaknesses, suggestions = [], [], []
428
+ wr = metrics["win_rate"]
429
+ if wr >= 0.6:
430
+ strengths.append(f"胜率较高 ({round(wr * 100, 1)}%)")
431
+ elif wr < 0.4:
432
+ weaknesses.append(f"胜率偏低 ({round(wr * 100, 1)}%)")
433
+
434
+ plr = metrics["profit_loss_ratio"]
435
+ if plr >= 2:
436
+ strengths.append(f"盈亏比优秀 ({plr}:1)")
437
+ elif plr < 1:
438
+ weaknesses.append(f"盈亏比不足 ({plr}:1)")
439
+ suggestions.append("考虑提高止盈目标或收紧止损")
440
+
441
+ mdd = abs(metrics["max_drawdown"])
442
+ if mdd > 0.2:
443
+ weaknesses.append(f"最大回撤较大 ({round(mdd * 100, 1)}%)")
444
+ suggestions.append("建议增加止损保护或减小仓位比例")
445
+ elif mdd < 0.1:
446
+ strengths.append(f"回撤控制良好 ({round(mdd * 100, 1)}%)")
447
+
448
+ sr = metrics["sharpe_ratio"]
449
+ if sr > 1.5:
450
+ strengths.append(f"夏普比率优秀 ({sr})")
451
+ elif sr < 0.5:
452
+ weaknesses.append(f"风险调整收益较低(夏普={sr})")
453
+
454
+ if metrics["total_trades"] < 5:
455
+ weaknesses.append("交易次数过少,统计意义有限")
456
+ suggestions.append("考虑放宽入场条件或延长回测周期")
457
+
458
+ return {"strengths": strengths, "weaknesses": weaknesses, "suggestions": suggestions}
459
+
460
+
461
+ def sample_curve(curve: list, max_points: int = 200) -> list:
462
+ if len(curve) <= max_points:
463
+ return curve
464
+ step = len(curve) / max_points
465
+ indices = [int(i * step) for i in range(max_points)]
466
+ if indices[-1] != len(curve) - 1:
467
+ indices.append(len(curve) - 1)
468
+ return [curve[i] for i in indices]
469
+
470
+
471
+ # --------------- Entry Points ---------------
472
+
473
+
474
+ def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str | None, capital: float) -> dict:
475
+ strategy = load_strategy(strategy_path)
476
+
477
+ if not end:
478
+ end = datetime.now().strftime("%Y-%m-%d")
479
+ if not start:
480
+ start = (datetime.now() - timedelta(days=365)).strftime("%Y-%m-%d")
481
+
482
+ df = fetch_kline(symbol, start, end)
483
+ if len(df) < 30:
484
+ return {"error": f"Insufficient data: {len(df)} rows (need at least 30)"}
485
+
486
+ sim = simulate(df, strategy, capital, symbol)
487
+ final = sim["final_equity"]
488
+ metrics = compute_metrics(sim["trades"], sim["equity_curve"], capital, final, start, end)
489
+
490
+ return {
491
+ "strategy": strategy.get("name", "unnamed"),
492
+ "symbol": symbol,
493
+ "period": f"{start} to {end}",
494
+ "initial_capital": capital,
495
+ "final_capital": final,
496
+ "metrics": metrics,
497
+ "trades": sim["trades"],
498
+ "equity_curve": sample_curve(sim["equity_curve"]),
499
+ "diagnosis": diagnose(metrics),
500
+ }
501
+
502
+
503
+ def evaluate_result(path: str) -> dict:
504
+ with open(path, encoding="utf-8") as f:
505
+ data = json.load(f)
506
+ trades = data.get("trades", [])
507
+ curve = data.get("equity_curve", [])
508
+ initial = data.get("initial_capital", 1000000)
509
+ final = data.get("final_capital", initial)
510
+ period = data.get("period", "unknown")
511
+ parts = period.split(" to ") if " to " in period else [period, period]
512
+ metrics = compute_metrics(trades, curve, initial, final, parts[0], parts[1])
513
+ data["metrics"] = metrics
514
+ data["diagnosis"] = diagnose(metrics)
515
+ return data
516
+
517
+
518
+ # --------------- Signal Evaluation ---------------
519
+
520
+ SIGNAL_DEFINITIONS = {
521
+ "macd_golden_cross": lambda df, i: (
522
+ i >= 1
523
+ and float(compute_macd_dif(df["close"]).iloc[i]) > float(compute_macd_dea(df["close"]).iloc[i])
524
+ and float(compute_macd_dif(df["close"]).iloc[i - 1]) <= float(compute_macd_dea(df["close"]).iloc[i - 1])
525
+ ),
526
+ "macd_death_cross": lambda df, i: (
527
+ i >= 1
528
+ and float(compute_macd_dif(df["close"]).iloc[i]) < float(compute_macd_dea(df["close"]).iloc[i])
529
+ and float(compute_macd_dif(df["close"]).iloc[i - 1]) >= float(compute_macd_dea(df["close"]).iloc[i - 1])
530
+ ),
531
+ "rsi_oversold": lambda df, i: float(compute_rsi(df["close"], 14).iloc[i]) < 30,
532
+ "rsi_overbought": lambda df, i: float(compute_rsi(df["close"], 14).iloc[i]) > 70,
533
+ "breakout_20d": lambda df, i: (
534
+ i >= 20
535
+ and float(df["close"].iloc[i]) > float(df["high"].iloc[i - 20 : i].max())
536
+ and float(df["close"].iloc[i - 1]) <= float(df["high"].iloc[i - 20 : i].max())
537
+ ),
538
+ "breakdown_20d": lambda df, i: (
539
+ i >= 20
540
+ and float(df["close"].iloc[i]) < float(df["low"].iloc[i - 20 : i].min())
541
+ and float(df["close"].iloc[i - 1]) >= float(df["low"].iloc[i - 20 : i].min())
542
+ ),
543
+ "volume_surge": lambda df, i: (
544
+ i >= 20 and float(df["volume"].iloc[i]) > 2.0 * float(df["volume"].iloc[i - 20 : i].mean())
545
+ ),
546
+ "ma_golden_cross": lambda df, i: (
547
+ i >= 20
548
+ and float(compute_ma(df["close"], 5).iloc[i]) > float(compute_ma(df["close"], 20).iloc[i])
549
+ and float(compute_ma(df["close"], 5).iloc[i - 1]) <= float(compute_ma(df["close"], 20).iloc[i - 1])
550
+ ),
551
+ "ma_death_cross": lambda df, i: (
552
+ i >= 20
553
+ and float(compute_ma(df["close"], 5).iloc[i]) < float(compute_ma(df["close"], 20).iloc[i])
554
+ and float(compute_ma(df["close"], 5).iloc[i - 1]) >= float(compute_ma(df["close"], 20).iloc[i - 1])
555
+ ),
556
+ }
557
+
558
+
559
+ def evaluate_signal(symbol: str, signal_name: str, forward_days: list[int] = None, lookback: int = 250) -> dict:
560
+ if forward_days is None:
561
+ forward_days = [3, 5, 10]
562
+ if signal_name not in SIGNAL_DEFINITIONS:
563
+ return {"error": f"Unknown signal: {signal_name}. Available: {list(SIGNAL_DEFINITIONS.keys())}"}
564
+
565
+ checker = SIGNAL_DEFINITIONS[signal_name]
566
+ end = datetime.now().strftime("%Y-%m-%d")
567
+ start = (datetime.now() - timedelta(days=int(lookback * 1.5))).strftime("%Y-%m-%d")
568
+ df = fetch_kline(symbol, start, end)
569
+ if len(df) < 30:
570
+ return {"error": f"Insufficient data: {len(df)} rows"}
571
+
572
+ max_fwd = max(forward_days)
573
+ occurrences = []
574
+ for i in range(20, len(df) - max_fwd):
575
+ try:
576
+ if checker(df, i):
577
+ entry_price = float(df["close"].iloc[i])
578
+ date_str = (
579
+ str(df["date"].iloc[i].date()) if hasattr(df["date"].iloc[i], "date") else str(df["date"].iloc[i])
580
+ )
581
+ fwd_returns = {}
582
+ for fd in forward_days:
583
+ if i + fd < len(df):
584
+ fwd_price = float(df["close"].iloc[i + fd])
585
+ fwd_returns[f"return_{fd}d"] = round((fwd_price - entry_price) / entry_price * 100, 2)
586
+ occurrences.append({"date": date_str, "price": round(entry_price, 2), **fwd_returns})
587
+ except Exception:
588
+ continue
589
+
590
+ if not occurrences:
591
+ return {"signal": signal_name, "symbol": symbol, "occurrences": 0, "note": "No signal found in period"}
592
+
593
+ result = {"signal": signal_name, "symbol": symbol, "occurrences": len(occurrences)}
594
+ for fd in forward_days:
595
+ key = f"return_{fd}d"
596
+ vals = [o[key] for o in occurrences if key in o]
597
+ if vals:
598
+ result[f"avg_return_{fd}d"] = round(np.mean(vals), 2)
599
+ result[f"win_rate_{fd}d"] = round(sum(1 for v in vals if v > 0) / len(vals), 4)
600
+ result["samples"] = occurrences[-10:]
601
+ return result
602
+
603
+
604
+ def main():
605
+ parser = argparse.ArgumentParser(description="AlphaEvo strategy backtester")
606
+ sub = parser.add_subparsers(dest="command")
607
+
608
+ p_run = sub.add_parser("run")
609
+ p_run.add_argument("strategy", help="Path to strategy YAML file")
610
+ p_run.add_argument("symbol", help="Stock symbol")
611
+ p_run.add_argument("--start", help="Start date (YYYY-MM-DD)")
612
+ p_run.add_argument("--end", help="End date (YYYY-MM-DD)")
613
+ p_run.add_argument("--capital", type=float, default=1000000)
614
+
615
+ p_eval = sub.add_parser("evaluate")
616
+ p_eval.add_argument("result", help="Path to result JSON file")
617
+
618
+ p_sig = sub.add_parser("evaluate_signal")
619
+ p_sig.add_argument("symbol", help="Stock symbol")
620
+ p_sig.add_argument("signal", help="Signal name (e.g. macd_golden_cross)")
621
+ p_sig.add_argument("--forward", default="3,5,10", help="Comma-separated forward days")
622
+ p_sig.add_argument("--lookback", type=int, default=250)
623
+
624
+ args = parser.parse_args()
625
+ if not args.command:
626
+ parser.print_help()
627
+ sys.exit(1)
628
+
629
+ if args.command == "run":
630
+ result = run_backtest(args.strategy, args.symbol, args.start, args.end, args.capital)
631
+ elif args.command == "evaluate":
632
+ result = evaluate_result(args.result)
633
+ elif args.command == "evaluate_signal":
634
+ fwd = [int(x) for x in args.forward.split(",")]
635
+ result = evaluate_signal(args.symbol, args.signal, fwd, args.lookback)
636
+ else:
637
+ result = {"error": f"Unknown command: {args.command}"}
638
+
639
+ print(json.dumps(result, ensure_ascii=False, default=str))
640
+
641
+
642
+ if __name__ == "__main__":
643
+ main()