alphasift 0.3.1__py3-none-any.whl

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 (86) hide show
  1. alphasift/__init__.py +52 -0
  2. alphasift/__main__.py +7 -0
  3. alphasift/audit.py +191 -0
  4. alphasift/candidate_context.py +738 -0
  5. alphasift/cli.py +2797 -0
  6. alphasift/config.py +705 -0
  7. alphasift/context.py +672 -0
  8. alphasift/daily.py +1256 -0
  9. alphasift/daily_brief.py +593 -0
  10. alphasift/daily_report.py +1115 -0
  11. alphasift/daily_report_html.py +1257 -0
  12. alphasift/doctor.py +1123 -0
  13. alphasift/dsa.py +302 -0
  14. alphasift/dsa_adapter.py +178 -0
  15. alphasift/dsa_provider.py +192 -0
  16. alphasift/evaluate.py +2418 -0
  17. alphasift/filter.py +517 -0
  18. alphasift/hotspot.py +1713 -0
  19. alphasift/industry.py +959 -0
  20. alphasift/llm_client.py +349 -0
  21. alphasift/market_digest.py +284 -0
  22. alphasift/market_news.py +446 -0
  23. alphasift/market_regime.py +578 -0
  24. alphasift/markets.py +160 -0
  25. alphasift/mcp.py +720 -0
  26. alphasift/models.py +315 -0
  27. alphasift/normalize.py +113 -0
  28. alphasift/notify.py +2608 -0
  29. alphasift/overview.py +225 -0
  30. alphasift/pack.py +1470 -0
  31. alphasift/pack_features.py +431 -0
  32. alphasift/pattern_replay.py +1449 -0
  33. alphasift/patterns/bottom_volume_yang.yaml +32 -0
  34. alphasift/patterns/box_breakout.yaml +36 -0
  35. alphasift/patterns/double_bottom_breakout.yaml +38 -0
  36. alphasift/patterns/ma20_shrink_pullback.yaml +37 -0
  37. alphasift/patterns/shooting_star_confirm.yaml +49 -0
  38. alphasift/patterns/single_yang_hold.yaml +44 -0
  39. alphasift/patterns/steady_trend_breakout.yaml +39 -0
  40. alphasift/patterns/three_white_soldiers.yaml +72 -0
  41. alphasift/patterns/three_white_soldiers_pullback.yaml +91 -0
  42. alphasift/patterns.py +1233 -0
  43. alphasift/performance_history.py +297 -0
  44. alphasift/pipeline.py +1010 -0
  45. alphasift/post_analysis.py +337 -0
  46. alphasift/ranker.py +990 -0
  47. alphasift/report.py +379 -0
  48. alphasift/result_schema.py +179 -0
  49. alphasift/risk.py +452 -0
  50. alphasift/run_history.py +164 -0
  51. alphasift/scorer.py +597 -0
  52. alphasift/server.py +680 -0
  53. alphasift/snapshot.py +1025 -0
  54. alphasift/snapshot_us.py +280 -0
  55. alphasift/snapshot_yahoo.py +358 -0
  56. alphasift/source_guard.py +70 -0
  57. alphasift/source_history.py +306 -0
  58. alphasift/store.py +294 -0
  59. alphasift/strategies/balanced_alpha.yaml +76 -0
  60. alphasift/strategies/blue_chip_income.yaml +87 -0
  61. alphasift/strategies/capital_heat.yaml +74 -0
  62. alphasift/strategies/dual_low.yaml +80 -0
  63. alphasift/strategies/global_value.yaml +65 -0
  64. alphasift/strategies/low_volatility_quality.yaml +95 -0
  65. alphasift/strategies/momentum_quality.yaml +81 -0
  66. alphasift/strategies/oversold_reversal.yaml +75 -0
  67. alphasift/strategies/quality_value.yaml +80 -0
  68. alphasift/strategies/shrink_pullback.yaml +77 -0
  69. alphasift/strategies/us_momentum_quality.yaml +74 -0
  70. alphasift/strategies/volume_breakout.yaml +78 -0
  71. alphasift/strategy.py +1090 -0
  72. alphasift/strategy_cards.py +424 -0
  73. alphasift/strategy_templates.py +291 -0
  74. alphasift/timeutil.py +38 -0
  75. alphasift/valuation_kr.py +149 -0
  76. alphasift/workbench_ui.py +1051 -0
  77. alphasift-0.3.1.data/data/.env.example +151 -0
  78. alphasift-0.3.1.data/data/LICENSE +184 -0
  79. alphasift-0.3.1.data/data/SKILL.md +190 -0
  80. alphasift-0.3.1.data/data/agents/openai.yaml +7 -0
  81. alphasift-0.3.1.dist-info/METADATA +312 -0
  82. alphasift-0.3.1.dist-info/RECORD +86 -0
  83. alphasift-0.3.1.dist-info/WHEEL +5 -0
  84. alphasift-0.3.1.dist-info/entry_points.txt +2 -0
  85. alphasift-0.3.1.dist-info/licenses/LICENSE +184 -0
  86. alphasift-0.3.1.dist-info/top_level.txt +1 -0
alphasift/evaluate.py ADDED
@@ -0,0 +1,2418 @@
1
+ # -*- coding: utf-8 -*-
2
+ """T+N evaluation for saved screening runs."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from collections import Counter
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from datetime import date, datetime, time, timedelta, timezone
9
+ from decimal import ROUND_HALF_UP, Decimal
10
+ from math import isclose, isfinite
11
+ from pathlib import Path
12
+ import time as _time
13
+ from typing import Any
14
+ from zoneinfo import ZoneInfo
15
+
16
+ import pandas as pd
17
+
18
+ from alphasift.config import Config
19
+ from alphasift.daily import fetch_daily_history
20
+ from alphasift.markets import get_market
21
+ from alphasift.models import EvaluationResult, PickEvaluation, ScreenResult
22
+ from alphasift.normalize import normalize_code
23
+ from alphasift.snapshot import fetch_snapshot_with_fallback
24
+ from alphasift.snapshot_yahoo import fetch_yahoo_quotes
25
+ from alphasift.store import list_saved_runs, load_screen_result
26
+ from alphasift.timeutil import now_iso, parse_timestamp
27
+
28
+
29
+ def _normalize_code(value: object) -> str:
30
+ # Stored picks and snapshot code columns are structured fields, so
31
+ # US tickers may pass through (see normalize_code docstring).
32
+ return normalize_code(value, allow_ticker=True)
33
+
34
+
35
+ def evaluate_saved_run(
36
+ run_ref: str | Path,
37
+ *,
38
+ config: Config | None = None,
39
+ current_snapshot: pd.DataFrame | None = None,
40
+ cost_bps: float | None = None,
41
+ follow_through_pct: float | None = None,
42
+ failed_breakout_pct: float | None = None,
43
+ price_paths: dict[str, pd.DataFrame] | None = None,
44
+ with_price_path: bool | None = None,
45
+ price_path_lookback_days: int | None = None,
46
+ horizon_days: int | None = None,
47
+ benchmark_paths: dict[str, pd.DataFrame] | None = None,
48
+ entry_mode: str = "close",
49
+ ) -> EvaluationResult:
50
+ """Evaluate saved picks.
51
+
52
+ By default each pick's return is measured to the latest snapshot price.
53
+ With ``horizon_days``, both modes target the close of the Nth available
54
+ stock bar strictly after ``entry_cutoff_date``. Close mode enters at the
55
+ latest close on or before the cutoff. Next-open mode enters at the first
56
+ post-cutoff bar's open and counts that bar as T+1, including its high and
57
+ low in the path. Missing stock sessions are skipped. CN one-price
58
+ limit-ups at entry are excluded, and one-price limit-downs at exit defer
59
+ the exit to a later bar.
60
+ Incomplete windows are pending. Next-open excess uses the benchmark open
61
+ and close on the pick's actual entry and exit dates, respectively.
62
+ ``benchmark_paths`` caches benchmark history by market across runs.
63
+ """
64
+ _validate_entry_mode(entry_mode, horizon_days)
65
+ if config is None:
66
+ config = Config.from_env()
67
+
68
+ run = load_screen_result(run_ref, data_dir=config.data_dir)
69
+ if current_snapshot is None:
70
+ # Must fetch the snapshot for the run's own market — a CN-default
71
+ # snapshot can't resolve US tickers (or vice versa), which silently
72
+ # marks every pick "missing" instead of evaluating it.
73
+ current_snapshot = _fetch_current_snapshot(
74
+ config, run.market, optional=horizon_days is not None
75
+ )
76
+ current_snapshot = _fill_missing_quotes(
77
+ current_snapshot, run.market, [pick.code for pick in run.picks]
78
+ )
79
+ if cost_bps is None:
80
+ cost_bps = config.evaluation_cost_bps
81
+ if follow_through_pct is None:
82
+ follow_through_pct = config.evaluation_follow_through_pct
83
+ if failed_breakout_pct is None:
84
+ failed_breakout_pct = config.evaluation_failed_breakout_pct
85
+ if with_price_path is None:
86
+ with_price_path = config.evaluation_price_path_enabled
87
+ if price_path_lookback_days is None:
88
+ price_path_lookback_days = config.evaluation_price_path_lookback_days
89
+ if horizon_days is not None:
90
+ horizon_days = max(int(horizon_days), 1)
91
+ with_price_path = True
92
+ # Cover entry -> today; the window is cut from the post-entry bars.
93
+ elapsed = _elapsed_days(run) or 0
94
+ price_path_lookback_days = max(int(price_path_lookback_days), elapsed + 10)
95
+
96
+ snapshot_source = str(current_snapshot.attrs.get("snapshot_source", ""))
97
+ source_errors = [str(item) for item in current_snapshot.attrs.get("source_errors", [])]
98
+ by_code = _snapshot_by_code(current_snapshot)
99
+ evaluations: list[PickEvaluation] = []
100
+ returns: list[float] = []
101
+ missing_codes: list[str] = []
102
+ path_errors: list[str] = []
103
+ effective_price_paths = _normalize_price_path_mapping(price_paths)
104
+ if with_price_path:
105
+ # Same market-aware default as pipeline.py: config.daily_source's
106
+ # "auto" chain is CN-only and cannot resolve Yahoo symbols.
107
+ effective_daily_source = (
108
+ "yfinance" if run.market != "cn" and config.daily_source in ("auto", "")
109
+ else config.daily_source
110
+ )
111
+ fetched_paths, path_errors = _fetch_price_paths(
112
+ run,
113
+ existing=effective_price_paths,
114
+ lookback_days=price_path_lookback_days,
115
+ source=effective_daily_source,
116
+ retries=config.daily_fetch_retries,
117
+ max_workers=config.daily_fetch_max_workers,
118
+ cache_dir=_daily_history_cache_dir(config),
119
+ cache_ttl_seconds=_daily_history_cache_ttl_seconds(config),
120
+ )
121
+ effective_price_paths.update(fetched_paths)
122
+
123
+ excess_returns: list[float] = []
124
+ pending_count = 0
125
+ untradable_count = 0
126
+ benchmark_errors: list[str] = []
127
+ benchmark_label = ""
128
+ benchmark_return_pct: float | None = None
129
+ benchmark_curve: pd.Series | None = None
130
+ benchmark_bars: pd.DataFrame | None = None
131
+ if horizon_days is not None and entry_mode == "next_open":
132
+ benchmark_return_pct, benchmark_label, benchmark_errors, benchmark_bars = _next_open_benchmark(
133
+ run,
134
+ horizon_days=horizon_days,
135
+ lookback_days=int(price_path_lookback_days),
136
+ cache=benchmark_paths,
137
+ )
138
+ elif horizon_days is not None:
139
+ benchmark_return_pct, benchmark_label, benchmark_errors, benchmark_curve = _benchmark_return(
140
+ run,
141
+ horizon_days=horizon_days,
142
+ lookback_days=int(price_path_lookback_days),
143
+ cache=benchmark_paths,
144
+ )
145
+
146
+ for pick in run.picks:
147
+ code = _normalize_code(pick.code)
148
+ current_price = by_code.get(code)
149
+ path_metrics = _price_path_metrics(
150
+ effective_price_paths.get(code),
151
+ entry_price=pick.price,
152
+ created_at=run.created_at,
153
+ cost_bps=float(cost_bps),
154
+ market=run.market,
155
+ horizon_days=horizon_days,
156
+ entry_mode=entry_mode,
157
+ pick_code=code,
158
+ pick_name=pick.name,
159
+ )
160
+ path_status = path_metrics["path_status"]
161
+ entry_open = path_metrics.get("entry_open")
162
+ entry_date = path_metrics.get("entry_date")
163
+ exit_date = path_metrics.get("path_end_date")
164
+ tradability_flags = path_metrics.get("tradability_flags", [])
165
+ if (
166
+ entry_open is not None
167
+ and benchmark_bars is not None
168
+ and not benchmark_bars.empty
169
+ and benchmark_bars.index[0] < entry_date
170
+ ):
171
+ tradability_flags.append("entry_delayed_missing_bar")
172
+ status = "ok"
173
+ return_pct = None
174
+ excess_return_pct = None
175
+ pick_benchmark_pct = None
176
+ if horizon_days is not None:
177
+ if entry_mode == "close" and pick.price <= 0:
178
+ status = "bad_entry_price"
179
+ elif path_status == "ok":
180
+ return_pct = path_metrics["path_end_return_pct"]
181
+ returns.append(float(return_pct))
182
+ if benchmark_bars is not None:
183
+ pick_benchmark_pct, error = _benchmark_open_return(
184
+ benchmark_bars, entry_date, exit_date.normalize(), benchmark_label
185
+ )
186
+ if error and error not in benchmark_errors:
187
+ benchmark_errors.append(error)
188
+ else:
189
+ pick_benchmark_pct = _benchmark_return_through(benchmark_curve, exit_date)
190
+ if pick_benchmark_pct is not None:
191
+ excess_return_pct = _safe_round(float(return_pct) - pick_benchmark_pct)
192
+ excess_returns.append(float(excess_return_pct))
193
+ elif path_status == "pending":
194
+ status = "pending"
195
+ pending_count += 1
196
+ elif path_status == "untradable_limit_up":
197
+ status = "untradable_limit_up"
198
+ untradable_count += 1
199
+ else:
200
+ status = "missing"
201
+ missing_codes.append(pick.code)
202
+ elif current_price is None:
203
+ status = "missing"
204
+ missing_codes.append(pick.code)
205
+ elif pick.price <= 0:
206
+ status = "bad_entry_price"
207
+ else:
208
+ return_pct = (current_price / pick.price - 1.0) * 100
209
+ return_pct -= float(cost_bps) / 100.0
210
+ returns.append(return_pct)
211
+ shape_status, shape_tags = _classify_shape_status(
212
+ pick,
213
+ return_pct,
214
+ follow_through_pct=float(follow_through_pct),
215
+ failed_breakout_pct=float(failed_breakout_pct),
216
+ )
217
+ evaluations.append(PickEvaluation(
218
+ code=pick.code,
219
+ name=pick.name,
220
+ rank=pick.rank,
221
+ entry_price=pick.price,
222
+ current_price=current_price,
223
+ return_pct=None if return_pct is None else round(return_pct, 4),
224
+ final_score=pick.final_score,
225
+ status=status,
226
+ llm_sector=pick.llm_sector or pick.industry,
227
+ llm_theme=pick.llm_theme,
228
+ llm_tags=list(pick.llm_tags),
229
+ llm_catalysts=list(pick.llm_catalysts),
230
+ llm_risks=list(pick.llm_risks),
231
+ post_analysis_tags=list(pick.post_analysis_tags),
232
+ risk_level=pick.risk_level,
233
+ risk_flags=list(pick.risk_flags),
234
+ portfolio_flags=list(pick.portfolio_flags),
235
+ shape_status=shape_status,
236
+ shape_tags=shape_tags,
237
+ path_status=path_status,
238
+ path_days=path_metrics["path_days"],
239
+ path_end_return_pct=path_metrics["path_end_return_pct"],
240
+ max_drawdown_pct=path_metrics["max_drawdown_pct"],
241
+ max_runup_pct=path_metrics["max_runup_pct"],
242
+ horizon_days=horizon_days,
243
+ benchmark_return_pct=pick_benchmark_pct,
244
+ excess_return_pct=excess_return_pct,
245
+ entry_mode=entry_mode,
246
+ entry_open=entry_open,
247
+ entry_date=entry_date.date().isoformat() if entry_date is not None else None,
248
+ exit_date=exit_date.date().isoformat() if entry_mode == "next_open" and exit_date is not None else None,
249
+ tradability_flags=tradability_flags,
250
+ ))
251
+
252
+ run_daily_sources, run_daily_flags = _extract_run_daily_quality_counts(run)
253
+ return EvaluationResult(
254
+ run_id=run.run_id,
255
+ strategy=run.strategy,
256
+ market=run.market,
257
+ created_at=run.created_at,
258
+ elapsed_days=_elapsed_days(run),
259
+ snapshot_source=snapshot_source,
260
+ source_errors=source_errors,
261
+ picks=evaluations,
262
+ average_return_pct=_safe_round(sum(returns) / len(returns)) if returns else None,
263
+ median_return_pct=_safe_round(float(pd.Series(returns).median())) if returns else None,
264
+ win_rate=_safe_round(sum(1 for item in returns if item > 0) / len(returns) * 100) if returns else None,
265
+ missing_codes=missing_codes,
266
+ degradation=[
267
+ *[
268
+ (f"Missing T+{horizon_days} price path for {code}" if horizon_days else f"Missing current quote for {code}")
269
+ for code in missing_codes
270
+ ],
271
+ *path_errors,
272
+ *benchmark_errors,
273
+ ],
274
+ horizon_days=horizon_days,
275
+ benchmark=benchmark_label,
276
+ benchmark_return_pct=benchmark_return_pct if horizon_days is not None else None,
277
+ average_excess_return_pct=(
278
+ _safe_round(sum(excess_returns) / len(excess_returns)) if excess_returns else None
279
+ ),
280
+ pending_count=pending_count,
281
+ entry_mode=entry_mode,
282
+ untradable_count=untradable_count,
283
+ untradable_share_pct=_untradable_share_pct(untradable_count, len(evaluations)),
284
+ run_snapshot_source=run.snapshot_source,
285
+ run_source_errors=list(run.source_errors),
286
+ run_degradation=list(run.degradation),
287
+ daily_source_counts=run_daily_sources,
288
+ daily_quality_flag_counts=run_daily_flags,
289
+ )
290
+
291
+
292
+ def evaluate_result_against_snapshot(
293
+ run: ScreenResult,
294
+ snapshot: pd.DataFrame,
295
+ *,
296
+ cost_bps: float = 0.0,
297
+ follow_through_pct: float = 3.0,
298
+ failed_breakout_pct: float = -3.0,
299
+ price_paths: dict[str, pd.DataFrame] | None = None,
300
+ ) -> EvaluationResult:
301
+ """Convenience helper for tests and custom integrations."""
302
+ by_code = _snapshot_by_code(snapshot)
303
+ picks = []
304
+ returns = []
305
+ missing = []
306
+ effective_price_paths = _normalize_price_path_mapping(price_paths)
307
+ for pick in run.picks:
308
+ code = _normalize_code(pick.code)
309
+ current_price = by_code.get(code)
310
+ return_pct = None
311
+ status = "missing"
312
+ if current_price is not None and pick.price > 0:
313
+ return_pct = (current_price / pick.price - 1.0) * 100
314
+ return_pct -= float(cost_bps) / 100.0
315
+ returns.append(return_pct)
316
+ status = "ok"
317
+ elif current_price is not None:
318
+ status = "bad_entry_price"
319
+ else:
320
+ missing.append(pick.code)
321
+ shape_status, shape_tags = _classify_shape_status(
322
+ pick,
323
+ return_pct,
324
+ follow_through_pct=follow_through_pct,
325
+ failed_breakout_pct=failed_breakout_pct,
326
+ )
327
+ path_metrics = _price_path_metrics(
328
+ effective_price_paths.get(code),
329
+ entry_price=pick.price,
330
+ created_at=run.created_at,
331
+ cost_bps=float(cost_bps),
332
+ market=run.market,
333
+ )
334
+ picks.append(PickEvaluation(
335
+ code=pick.code,
336
+ name=pick.name,
337
+ rank=pick.rank,
338
+ entry_price=pick.price,
339
+ current_price=current_price,
340
+ return_pct=None if return_pct is None else round(return_pct, 4),
341
+ final_score=pick.final_score,
342
+ status=status,
343
+ llm_sector=pick.llm_sector or pick.industry,
344
+ llm_theme=pick.llm_theme,
345
+ llm_tags=list(pick.llm_tags),
346
+ llm_catalysts=list(pick.llm_catalysts),
347
+ llm_risks=list(pick.llm_risks),
348
+ post_analysis_tags=list(pick.post_analysis_tags),
349
+ risk_level=pick.risk_level,
350
+ risk_flags=list(pick.risk_flags),
351
+ portfolio_flags=list(pick.portfolio_flags),
352
+ shape_status=shape_status,
353
+ shape_tags=shape_tags,
354
+ path_status=path_metrics["path_status"],
355
+ path_days=path_metrics["path_days"],
356
+ path_end_return_pct=path_metrics["path_end_return_pct"],
357
+ max_drawdown_pct=path_metrics["max_drawdown_pct"],
358
+ max_runup_pct=path_metrics["max_runup_pct"],
359
+ ))
360
+ run_daily_sources, run_daily_flags = _extract_run_daily_quality_counts(run)
361
+ return EvaluationResult(
362
+ run_id=run.run_id,
363
+ strategy=run.strategy,
364
+ market=run.market,
365
+ created_at=run.created_at,
366
+ elapsed_days=_elapsed_days(run),
367
+ snapshot_source=str(snapshot.attrs.get("snapshot_source", "")),
368
+ source_errors=[str(item) for item in snapshot.attrs.get("source_errors", [])],
369
+ picks=picks,
370
+ average_return_pct=_safe_round(sum(returns) / len(returns)) if returns else None,
371
+ median_return_pct=_safe_round(float(pd.Series(returns).median())) if returns else None,
372
+ win_rate=_safe_round(sum(1 for item in returns if item > 0) / len(returns) * 100) if returns else None,
373
+ missing_codes=missing,
374
+ degradation=[f"Missing current quote for {code}" for code in missing],
375
+ run_snapshot_source=run.snapshot_source,
376
+ run_source_errors=list(run.source_errors),
377
+ run_degradation=list(run.degradation),
378
+ daily_source_counts=run_daily_sources,
379
+ daily_quality_flag_counts=run_daily_flags,
380
+ )
381
+
382
+
383
+ def evaluate_saved_runs(
384
+ *,
385
+ config: Config | None = None,
386
+ current_snapshot: pd.DataFrame | None = None,
387
+ limit: int = 20,
388
+ strategy: str | None = None,
389
+ market: str = "cn",
390
+ cost_bps: float | None = None,
391
+ follow_through_pct: float | None = None,
392
+ failed_breakout_pct: float | None = None,
393
+ with_price_path: bool | None = None,
394
+ price_path_lookback_days: int | None = None,
395
+ failure_sample_limit: int = 5,
396
+ horizon_days: int | None = None,
397
+ benchmark_paths: dict[str, pd.DataFrame] | None = None,
398
+ entry_mode: str = "close",
399
+ ) -> dict[str, object]:
400
+ """Evaluate multiple saved runs with one current snapshot and aggregate stats.
401
+
402
+ A batch evaluates runs from a single market at a time: all runs share one
403
+ freshly-fetched snapshot, and a CN snapshot can't resolve US tickers (or
404
+ vice versa), so mixed-market batches would silently mark every pick from
405
+ the other market "missing". Runs are filtered to `market` accordingly.
406
+ """
407
+ _validate_entry_mode(entry_mode, horizon_days)
408
+ if config is None:
409
+ config = Config.from_env()
410
+ market = get_market(market).id # saved runs store the lowercase id
411
+ fetched_snapshot = current_snapshot is None
412
+ if current_snapshot is None:
413
+ current_snapshot = _fetch_current_snapshot(config, market, optional=horizon_days is not None)
414
+ if cost_bps is None:
415
+ cost_bps = config.evaluation_cost_bps
416
+ if follow_through_pct is None:
417
+ follow_through_pct = config.evaluation_follow_through_pct
418
+ if failed_breakout_pct is None:
419
+ failed_breakout_pct = config.evaluation_failed_breakout_pct
420
+ if with_price_path is None:
421
+ with_price_path = config.evaluation_price_path_enabled
422
+ if price_path_lookback_days is None:
423
+ price_path_lookback_days = config.evaluation_price_path_lookback_days
424
+
425
+ run_items = list_saved_runs(
426
+ data_dir=config.data_dir,
427
+ limit=max(int(limit), 1),
428
+ strategy=strategy,
429
+ market=market,
430
+ )
431
+ if fetched_snapshot:
432
+ current_snapshot = _fill_missing_quotes(
433
+ current_snapshot, market, _saved_pick_codes(run_items, config)
434
+ )
435
+
436
+ shared_benchmark_paths = benchmark_paths if benchmark_paths is not None else {}
437
+ evaluations: list[EvaluationResult] = []
438
+ for item in run_items:
439
+ try:
440
+ evaluations.append(
441
+ evaluate_saved_run(
442
+ str(item["path"]),
443
+ config=config,
444
+ current_snapshot=current_snapshot,
445
+ cost_bps=cost_bps,
446
+ follow_through_pct=follow_through_pct,
447
+ failed_breakout_pct=failed_breakout_pct,
448
+ with_price_path=with_price_path,
449
+ price_path_lookback_days=price_path_lookback_days,
450
+ horizon_days=horizon_days,
451
+ benchmark_paths=shared_benchmark_paths,
452
+ entry_mode=entry_mode,
453
+ )
454
+ )
455
+ except Exception as exc:
456
+ evaluations.append(EvaluationResult(
457
+ run_id=str(item.get("run_id", "")),
458
+ strategy=str(item.get("strategy", "")),
459
+ market=str(item.get("market", "")),
460
+ created_at=str(item.get("created_at", "")),
461
+ snapshot_source=str(current_snapshot.attrs.get("snapshot_source", "")),
462
+ source_errors=[str(err) for err in current_snapshot.attrs.get("source_errors", [])],
463
+ degradation=[f"Failed to evaluate run: {exc}"],
464
+ entry_mode=entry_mode,
465
+ run_snapshot_source=str(item.get("snapshot_source", "") or ""),
466
+ run_source_errors=[str(err) for err in (item.get("source_errors") or [])],
467
+ run_degradation=[str(deg) for deg in (item.get("degradation") or [])],
468
+ daily_source_counts=dict(item.get("daily_source_counts") or {}),
469
+ daily_quality_flag_counts=dict(item.get("daily_quality_flag_counts") or {}),
470
+ ))
471
+
472
+ summary = _aggregate_evaluations(evaluations)
473
+ portfolio_summary = _aggregate_portfolios(evaluations)
474
+ by_strategy = {
475
+ name: _aggregate_evaluations(items)
476
+ for name, items in _group_by_strategy(evaluations).items()
477
+ }
478
+ portfolio_by_strategy = {
479
+ name: _aggregate_portfolios(items)
480
+ for name, items in _group_by_strategy(evaluations).items()
481
+ }
482
+ strategy_summaries = _strategy_summaries(evaluations)
483
+ dimensions = {
484
+ "by_sector": _aggregate_by_pick_label(evaluations, "llm_sector"),
485
+ "by_theme": _aggregate_by_pick_label(evaluations, "llm_theme"),
486
+ "by_tag": _aggregate_by_pick_multi_label(evaluations, "llm_tags"),
487
+ "by_llm_catalyst": _aggregate_by_pick_multi_label(evaluations, "llm_catalysts"),
488
+ "by_llm_risk": _aggregate_by_pick_multi_label(evaluations, "llm_risks"),
489
+ "by_post_analysis_tag": _aggregate_by_pick_multi_label(evaluations, "post_analysis_tags"),
490
+ "by_risk_flag": _aggregate_by_pick_multi_label(evaluations, "risk_flags"),
491
+ "by_portfolio_flag": _aggregate_by_pick_multi_label(evaluations, "portfolio_flags"),
492
+ "by_holding_period": _aggregate_by_holding_period(evaluations),
493
+ "by_shape_status": _aggregate_by_pick_label(evaluations, "shape_status"),
494
+ "by_shape_tag": _aggregate_by_pick_multi_label(evaluations, "shape_tags"),
495
+ "by_path_status": _aggregate_by_pick_label(evaluations, "path_status"),
496
+ }
497
+ return {
498
+ "evaluated_at": now_iso(),
499
+ "snapshot_source": str(current_snapshot.attrs.get("snapshot_source", "")),
500
+ "source_errors": [str(item) for item in current_snapshot.attrs.get("source_errors", [])],
501
+ "limit": limit,
502
+ "strategy_filter": strategy or "",
503
+ "cost_bps": float(cost_bps),
504
+ "follow_through_pct": float(follow_through_pct),
505
+ "failed_breakout_pct": float(failed_breakout_pct),
506
+ "with_price_path": bool(with_price_path),
507
+ "price_path_lookback_days": int(price_path_lookback_days),
508
+ "horizon_days": horizon_days,
509
+ "entry_mode": entry_mode,
510
+ "summary": summary,
511
+ "portfolio_summary": portfolio_summary,
512
+ "by_strategy": by_strategy,
513
+ "portfolio_by_strategy": portfolio_by_strategy,
514
+ "strategy_summaries": strategy_summaries,
515
+ "dimensions": dimensions,
516
+ "data_quality_review": _data_quality_review(evaluations),
517
+ "event_signal_review": _event_signal_review(evaluations),
518
+ "failure_review": _failure_review(
519
+ evaluations,
520
+ sample_limit=failure_sample_limit,
521
+ ),
522
+ "runs": [_evaluation_brief(item) for item in evaluations],
523
+ }
524
+
525
+
526
+
527
+ def _validate_entry_mode(entry_mode: str, horizon_days: int | None) -> None:
528
+ if entry_mode not in ("close", "next_open"):
529
+ raise ValueError("entry_mode must be 'close' or 'next_open'")
530
+ if entry_mode == "next_open" and horizon_days is None:
531
+ raise ValueError("next_open requires a T+N window")
532
+
533
+
534
+ def _normalize_price_windows(windows: list[int]) -> list[int]:
535
+ unique: list[int] = []
536
+ seen: set[int] = set()
537
+ for window in windows:
538
+ value = int(window)
539
+ if value <= 0:
540
+ continue
541
+ if value in seen:
542
+ continue
543
+ seen.add(value)
544
+ unique.append(value)
545
+ return sorted(unique)
546
+
547
+
548
+ def evaluate_saved_runs_by_windows(
549
+ *,
550
+ windows: list[int],
551
+ config: Config | None = None,
552
+ current_snapshot: pd.DataFrame | None = None,
553
+ limit: int = 20,
554
+ strategy: str | None = None,
555
+ market: str = "cn",
556
+ cost_bps: float | None = None,
557
+ follow_through_pct: float | None = None,
558
+ failed_breakout_pct: float | None = None,
559
+ failure_sample_limit: int = 5,
560
+ entry_mode: str = "close",
561
+ ) -> dict[str, Any]:
562
+ """Evaluate fixed T+N windows using the entry rules of ``evaluate_saved_run``."""
563
+ normalized_windows = _normalize_price_windows(windows)
564
+ if not normalized_windows:
565
+ normalized_windows = [30]
566
+ _validate_entry_mode(entry_mode, normalized_windows[0])
567
+
568
+ if config is None:
569
+ config = Config.from_env()
570
+
571
+ if current_snapshot is None:
572
+ # One live snapshot for every window instead of one per window.
573
+ current_snapshot = _fetch_current_snapshot(config, get_market(market).id, optional=True)
574
+ window_results: list[dict[str, Any]] = []
575
+ benchmark_paths: dict[str, pd.DataFrame] = {}
576
+ for window_days in normalized_windows:
577
+ window_results.append(
578
+ evaluate_saved_runs(
579
+ config=config,
580
+ current_snapshot=current_snapshot,
581
+ limit=limit,
582
+ strategy=strategy,
583
+ market=market,
584
+ cost_bps=cost_bps,
585
+ follow_through_pct=follow_through_pct,
586
+ failed_breakout_pct=failed_breakout_pct,
587
+ with_price_path=True,
588
+ horizon_days=window_days,
589
+ benchmark_paths=benchmark_paths,
590
+ failure_sample_limit=failure_sample_limit,
591
+ entry_mode=entry_mode,
592
+ )
593
+ )
594
+
595
+ merged: dict[str, list[dict[str, Any]]] = {}
596
+ for index, window_days in enumerate(normalized_windows):
597
+ for summary in window_results[index].get("strategy_summaries", []):
598
+ if not isinstance(summary, dict):
599
+ continue
600
+ strategy_name = str(summary.get("strategy", "unknown")) or "unknown"
601
+ merged.setdefault(strategy_name, []).append(
602
+ {
603
+ "window_days": window_days,
604
+ "average_return_pct": summary.get("average_return_pct"),
605
+ "win_rate": summary.get("win_rate"),
606
+ "average_max_drawdown_pct": summary.get("average_max_drawdown_pct"),
607
+ "average_max_runup_pct": summary.get("average_max_runup_pct"),
608
+ "evaluated_pick_count": summary.get("evaluated_pick_count", 0),
609
+ "pending_count": summary.get("pending_count", 0),
610
+ "untradable_count": summary.get("untradable_count", 0),
611
+ "untradable_share_pct": summary.get("untradable_share_pct"),
612
+ "tradability_flag_counts": summary.get("tradability_flag_counts", {}),
613
+ "benchmark": summary.get("benchmark", ""),
614
+ "benchmark_pick_count": summary.get("benchmark_pick_count", 0),
615
+ "average_matched_return_pct": summary.get("average_matched_return_pct"),
616
+ "average_benchmark_return_pct": summary.get("average_benchmark_return_pct"),
617
+ "average_excess_return_pct": summary.get("average_excess_return_pct"),
618
+ "beat_benchmark_rate": summary.get("beat_benchmark_rate"),
619
+ "benchmark_errors": summary.get("benchmark_errors", []),
620
+ "failed_breakout_count": (summary.get("shape_status_counts", {}) or {}).get("failed_breakout", 0),
621
+ "breakout_follow_through_count": (summary.get("shape_status_counts", {}) or {}).get("breakout_follow_through", 0),
622
+ "missing_count": summary.get("missing_count", 0),
623
+ "shape_status_counts": summary.get("shape_status_counts", {}),
624
+ "pick_status_counts": summary.get("pick_status_counts", {}),
625
+ }
626
+ )
627
+
628
+ summary_by_strategy: list[dict[str, Any]] = []
629
+ for strategy_name, window_summaries in sorted(merged.items(), key=lambda item: item[0]):
630
+ window_summaries.sort(key=lambda item: int(item.get("window_days", 0)))
631
+ summary_by_strategy.append(
632
+ {
633
+ "strategy": strategy_name,
634
+ "window_count": len(window_summaries),
635
+ "window_summaries": window_summaries,
636
+ }
637
+ )
638
+
639
+ # Failures and event signals differ by horizon: a pick that is fine at T+5
640
+ # can be a loser at T+20. Each window keeps its own reviews.
641
+ window_reviews = [
642
+ {
643
+ "window_days": window_days,
644
+ "data_quality_review": window_results[index].get("data_quality_review", {}),
645
+ "event_signal_review": window_results[index].get("event_signal_review", {}),
646
+ "failure_review": window_results[index].get("failure_review", {}),
647
+ }
648
+ for index, window_days in enumerate(normalized_windows)
649
+ ]
650
+ base_payload = window_results[0]
651
+ return {
652
+ **{k: base_payload[k] for k in base_payload if k != "strategy_summaries"},
653
+ "strategy_summaries": summary_by_strategy,
654
+ "price_path_window_days": normalized_windows,
655
+ # Top-level summary, dimensions and reviews are those of the shortest window.
656
+ "review_window_days": normalized_windows[0],
657
+ "window_reviews": window_reviews,
658
+ "with_price_path": True,
659
+ }
660
+
661
+
662
+ def _fetch_current_snapshot(config: Config, market: str, *, optional: bool) -> pd.DataFrame:
663
+ """Live snapshot for current prices.
664
+
665
+ T+N returns come from historical closes; the current price is only shown
666
+ alongside. With ``optional`` a snapshot outage leaves it empty instead
667
+ of failing an evaluation whose windows have already completed.
668
+ """
669
+ try:
670
+ return fetch_snapshot_with_fallback(
671
+ config.snapshot_source_priority,
672
+ fallback_snapshot_path=config.fallback_snapshot_path,
673
+ fallback_max_age_hours=config.snapshot_fallback_max_age_hours,
674
+ source_health_path=config.source_health_path,
675
+ market=market,
676
+ )
677
+ except Exception as exc:
678
+ if not optional:
679
+ raise
680
+ empty = pd.DataFrame(columns=["code", "price"])
681
+ empty.attrs["snapshot_source"] = ""
682
+ empty.attrs["source_errors"] = [f"current snapshot unavailable (T+N uses historical closes): {exc}"]
683
+ return empty
684
+
685
+
686
+ def _fill_missing_quotes(
687
+ snapshot: pd.DataFrame,
688
+ market: str,
689
+ codes: list[str],
690
+ ) -> pd.DataFrame:
691
+ """Add prices for saved non-CN picks that fell out of the screener universe.
692
+
693
+ The Yahoo screener only returns names above the market's universe floor,
694
+ so a pick that dropped below it would be marked missing and silently
695
+ left out of returns. CN snapshots cover the whole market already.
696
+ """
697
+ if get_market(market).cn_rules:
698
+ return snapshot
699
+ have = set(_snapshot_by_code(snapshot))
700
+ missing = [
701
+ code for code in dict.fromkeys(_normalize_code(item) for item in codes)
702
+ if code and code not in have
703
+ ]
704
+ if not missing:
705
+ return snapshot
706
+ attrs = dict(snapshot.attrs)
707
+ errors = [str(item) for item in attrs.get("source_errors", [])]
708
+ try:
709
+ quotes = fetch_yahoo_quotes(missing)
710
+ except Exception as exc: # noqa: BLE001 - leave the picks missing, but say why
711
+ errors.append(f"yahoo_quotes for {len(missing)} saved picks: {exc}")
712
+ quotes = pd.DataFrame(columns=["code", "price"])
713
+ unresolved = sorted(set(missing) - set(quotes["code"]))
714
+ if unresolved:
715
+ errors.append(f"yahoo_quotes: no price for {','.join(unresolved[:10])}")
716
+ combined = pd.concat([snapshot, quotes], ignore_index=True) if not quotes.empty else snapshot.copy()
717
+ combined.attrs = {**attrs, "source_errors": errors}
718
+ return combined
719
+
720
+
721
+ def _saved_pick_codes(run_items: list[dict[str, Any]], config: Config) -> list[str]:
722
+ codes: list[str] = []
723
+ for item in run_items:
724
+ try:
725
+ run = load_screen_result(str(item["path"]), data_dir=config.data_dir)
726
+ except Exception: # noqa: BLE001 - the per-run loop reports load errors
727
+ continue
728
+ codes.extend(pick.code for pick in run.picks)
729
+ return codes
730
+
731
+
732
+ def _snapshot_by_code(snapshot: pd.DataFrame) -> dict[str, float]:
733
+ if snapshot.empty or "code" not in snapshot.columns or "price" not in snapshot.columns:
734
+ return {}
735
+ result = {}
736
+ for _, row in snapshot.iterrows():
737
+ price = pd.to_numeric(row.get("price"), errors="coerce")
738
+ if pd.notna(price) and isfinite(float(price)):
739
+ code = _normalize_code(row.get("code", ""))
740
+ if code:
741
+ result[code] = float(price)
742
+ return result
743
+
744
+
745
+ def _normalize_price_path_mapping(
746
+ price_paths: dict[str, pd.DataFrame] | None,
747
+ ) -> dict[str, pd.DataFrame]:
748
+ if not price_paths:
749
+ return {}
750
+ return {
751
+ _normalize_code(code): path
752
+ for code, path in price_paths.items()
753
+ if _normalize_code(code) and isinstance(path, pd.DataFrame)
754
+ }
755
+
756
+
757
+ def _fetch_price_paths(
758
+ run: ScreenResult,
759
+ *,
760
+ existing: dict[str, pd.DataFrame],
761
+ lookback_days: int,
762
+ source: str,
763
+ retries: int,
764
+ max_workers: int = 1,
765
+ cache_dir: str | Path | None = None,
766
+ cache_ttl_seconds: float | None = None,
767
+ ) -> tuple[dict[str, pd.DataFrame], list[str]]:
768
+ paths: dict[str, pd.DataFrame] = {}
769
+ errors: list[str] = []
770
+ fetch_codes: list[str] = []
771
+ seen_codes = set(existing)
772
+ for pick in run.picks:
773
+ code = _normalize_code(pick.code)
774
+ if not code or code in seen_codes:
775
+ continue
776
+ seen_codes.add(code)
777
+ fetch_codes.append(code)
778
+
779
+ def fetch_one(code: str) -> tuple[str, pd.DataFrame | None, str | None]:
780
+ try:
781
+ return code, fetch_daily_history(
782
+ code,
783
+ lookback_days=lookback_days,
784
+ source=source,
785
+ retries=retries,
786
+ cache_dir=cache_dir,
787
+ cache_ttl_seconds=cache_ttl_seconds,
788
+ ), None
789
+ except Exception as exc:
790
+ return code, None, f"Price path fetch failed for {code}: {exc}"
791
+
792
+ if len(fetch_codes) <= 1:
793
+ fetched_rows = [fetch_one(code) for code in fetch_codes]
794
+ else:
795
+ worker_limit = min(max(1, int(max_workers)), len(fetch_codes))
796
+ with ThreadPoolExecutor(max_workers=worker_limit) as executor:
797
+ fetched_rows = list(executor.map(fetch_one, fetch_codes))
798
+
799
+ for code, path, error in fetched_rows:
800
+ if error:
801
+ errors.append(error)
802
+ elif path is not None:
803
+ paths[code] = path
804
+ return paths, errors
805
+
806
+
807
+ def _daily_history_cache_dir(config: Config) -> Path | None:
808
+ configured = getattr(config, "daily_history_cache_dir", None)
809
+ if configured is not None:
810
+ return Path(configured)
811
+ return Path(config.data_dir) / "daily_history"
812
+
813
+
814
+ def _daily_history_cache_ttl_seconds(config: Config) -> float:
815
+ hours = getattr(config, "daily_history_cache_ttl_hours", 24)
816
+ return max(0.0, float(hours)) * 60 * 60
817
+
818
+
819
+ _EMPTY_PATH_METRICS = {
820
+ "path_status": "",
821
+ "path_days": None,
822
+ "path_end_return_pct": None,
823
+ "max_drawdown_pct": None,
824
+ "max_runup_pct": None,
825
+ "path_end_date": None,
826
+ }
827
+
828
+
829
+ def _price_path_metrics(
830
+ path: pd.DataFrame | None,
831
+ *,
832
+ entry_price: float,
833
+ created_at: str,
834
+ cost_bps: float,
835
+ market: str = "cn",
836
+ horizon_days: int | None = None,
837
+ now: datetime | None = None,
838
+ entry_mode: str = "close",
839
+ pick_code: str = "",
840
+ pick_name: str = "",
841
+ ) -> dict[str, object]:
842
+ """Measure the first N completed post-cutoff bars for a fixed horizon.
843
+
844
+ Next-open entry is on bar one, including that bar in the path. A CN
845
+ limit-down exit can extend the path beyond N. Without a horizon, measure
846
+ the path from the saved entry price to the latest available close.
847
+ """
848
+ empty = _EMPTY_PATH_METRICS
849
+ if path is None:
850
+ return empty.copy()
851
+ if entry_mode == "next_open" and horizon_days is not None:
852
+ return _next_open_path_metrics(
853
+ path,
854
+ created_at=created_at,
855
+ cost_bps=cost_bps,
856
+ market=market,
857
+ horizon_days=horizon_days,
858
+ as_of=now or _history_fetched_at(path),
859
+ pick_code=pick_code,
860
+ pick_name=pick_name,
861
+ )
862
+ if entry_price <= 0:
863
+ return {**empty, "path_status": "bad_entry_price"}
864
+ as_of = now or _history_fetched_at(path)
865
+ df = _normalize_price_path(path)
866
+ if df.empty:
867
+ return {**empty, "path_status": "no_path"}
868
+ cutoff = entry_cutoff_date(created_at, market)
869
+ if horizon_days:
870
+ # T+N is close-to-close within one history. Without the entry
871
+ # session's close the saved pick price (intraday, unadjusted) would
872
+ # be compared with adjusted closes, so report it instead of guessing.
873
+ entry_bars = (
874
+ df[df["date"].dt.normalize() <= pd.Timestamp(cutoff)]
875
+ if cutoff is not None and "date" in df.columns
876
+ else df.iloc[0:0]
877
+ )
878
+ if entry_bars.empty or not float(entry_bars["close"].iloc[-1]) > 0:
879
+ return {**empty, "path_status": "no_entry_close"}
880
+ entry_price = float(entry_bars["close"].iloc[-1])
881
+ df = _filter_path_after_entry(df, cutoff)
882
+ # Only sessions that had closed when the history was fetched count; a bar
883
+ # cached mid-session is not a close even after the session ends.
884
+ df = _completed_sessions(df, market, now=as_of)
885
+ if horizon_days:
886
+ if len(df) < horizon_days:
887
+ return {**empty, "path_status": "pending", "path_days": int(len(df))}
888
+ df = df.head(int(horizon_days))
889
+ if df.empty:
890
+ return {**empty, "path_status": "no_path_after_entry"}
891
+
892
+ return _summarize_price_path(df, entry_price, cost_bps)
893
+
894
+
895
+ def _summarize_price_path(df: pd.DataFrame, entry_price: float, cost_bps: float) -> dict[str, object]:
896
+ close = pd.to_numeric(df["close"], errors="coerce").dropna()
897
+ high = pd.to_numeric(df["high"], errors="coerce").dropna()
898
+ low = pd.to_numeric(df["low"], errors="coerce").dropna()
899
+ if close.empty:
900
+ return {**_EMPTY_PATH_METRICS, "path_status": "no_close"}
901
+
902
+ end_return = (float(close.iloc[-1]) / entry_price - 1.0) * 100 - cost_bps / 100.0
903
+ max_runup = (float(high.max()) / entry_price - 1.0) * 100 if not high.empty else None
904
+ max_drawdown = (float(low.min()) / entry_price - 1.0) * 100 if not low.empty else None
905
+ return {
906
+ "path_status": "ok",
907
+ "path_end_date": df["date"].iloc[-1] if "date" in df.columns else None,
908
+ "path_days": int(len(close)),
909
+ "path_end_return_pct": _safe_round(end_return),
910
+ "max_drawdown_pct": _safe_round(min(max_drawdown, 0.0)) if max_drawdown is not None else None,
911
+ "max_runup_pct": _safe_round(max(max_runup, 0.0)) if max_runup is not None else None,
912
+ }
913
+
914
+
915
+ def _next_open_path_metrics(
916
+ path: pd.DataFrame,
917
+ *,
918
+ created_at: str,
919
+ cost_bps: float,
920
+ market: str,
921
+ horizon_days: int,
922
+ as_of: datetime | None,
923
+ pick_code: str,
924
+ pick_name: str,
925
+ ) -> dict[str, object]:
926
+ df = _normalize_price_path(path, fill_missing_extremes=False)
927
+ cutoff = entry_cutoff_date(created_at, market)
928
+ empty = _EMPTY_PATH_METRICS
929
+ if df.empty or cutoff is None or "date" not in df.columns:
930
+ return {**empty, "path_status": "no_path"}
931
+
932
+ limit_pct = _cn_price_limit(pick_code, pick_name) if get_market(market or "cn").cn_rules else None
933
+ volume = df.get("volume", df.get("成交量"))
934
+ if limit_pct is not None and volume is not None:
935
+ # Some histories retain a zero-volume bar while the stock is suspended.
936
+ suspended = pd.to_numeric(volume, errors="coerce").eq(0).fillna(False)
937
+ df = df.loc[~suspended].copy()
938
+ df["previous_close"] = df["close"].shift()
939
+ if "raw_pre_close" in df.columns:
940
+ prev_raw = df["raw_close"].shift() if "raw_close" in df.columns else pd.Series(float("nan"), index=df.index)
941
+ df["raw_previous_close"] = df["raw_pre_close"].where(df["raw_pre_close"].gt(0), prev_raw)
942
+ elif "raw_close" in df.columns:
943
+ df["raw_previous_close"] = df["raw_close"].shift()
944
+ bars = _completed_sessions(_filter_path_after_entry(df, cutoff), market, now=as_of)
945
+ if bars.empty:
946
+ return {**empty, "path_status": "pending", "path_days": 0}
947
+
948
+ entry = bars.iloc[0]
949
+ opening = entry.get("open")
950
+ flags: list[str] = []
951
+ details: dict[str, object] = {"entry_date": entry["date"].normalize(), "tradability_flags": flags}
952
+ if pd.isna(opening) or opening <= 0:
953
+ return {**empty, **details, "path_status": "no_entry_open"}
954
+ opening = float(opening)
955
+ details["entry_open"] = opening
956
+
957
+ if limit_pct is not None and _one_price_limit(entry, limit_pct, "low"):
958
+ return {**empty, **details, "path_status": "untradable_limit_up"}
959
+
960
+ exit_index = horizon_days - 1
961
+ if limit_pct is not None and exit_index < len(bars):
962
+ while exit_index < len(bars) and _one_price_limit(bars.iloc[exit_index], -limit_pct, "high"):
963
+ exit_index += 1
964
+ if exit_index >= horizon_days:
965
+ flags.append("exit_delayed_limit_down")
966
+ if exit_index >= len(bars):
967
+ return {**empty, **details, "path_status": "pending", "path_days": len(bars)}
968
+ return {**_summarize_price_path(bars.iloc[:exit_index + 1], opening, cost_bps), **details}
969
+
970
+
971
+ def _cn_price_limit(code: str, name: str) -> float:
972
+ # ChiNext, STAR and Beijing keep their board limit for ST names; only main-board ST is 5%.
973
+ if code.startswith(("300", "301", "688", "689")):
974
+ return 0.20
975
+ if code.startswith(("4", "8", "920")):
976
+ return 0.30
977
+ # The saved label approximates ST status at entry and exit.
978
+ if (name or "").strip().upper().startswith(("ST", "*ST", "SST", "S*ST")):
979
+ return 0.05
980
+ return 0.10
981
+
982
+
983
+ def _one_price_limit(bar: pd.Series, change: float, extreme: str) -> bool:
984
+ raw_edge_col = f"raw_{extreme}"
985
+ if (
986
+ "raw_open" in bar
987
+ and "raw_previous_close" in bar
988
+ and raw_edge_col in bar
989
+ and pd.notna(bar["raw_open"])
990
+ and pd.notna(bar["raw_previous_close"])
991
+ and pd.notna(bar[raw_edge_col])
992
+ and float(bar["raw_open"]) > 0
993
+ and float(bar["raw_previous_close"]) > 0
994
+ ):
995
+ opening = float(bar["raw_open"])
996
+ previous_close = float(bar["raw_previous_close"])
997
+ edge = float(bar[raw_edge_col])
998
+ else:
999
+ opening, previous_close, edge = bar["open"], bar["previous_close"], bar[extreme]
1000
+ if pd.isna(opening) or pd.isna(previous_close) or pd.isna(edge):
1001
+ return False
1002
+ # Round half up before comparing so a quote one tick below the limit
1003
+ # cannot qualify when the theoretical limit falls exactly between ticks.
1004
+ limit = Decimal(str(previous_close)) * (1 + Decimal(str(change)))
1005
+ rounded_limit = float(limit.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
1006
+ return (
1007
+ opening > 0
1008
+ and isclose(opening, rounded_limit, rel_tol=0, abs_tol=0.00500001)
1009
+ and isclose(opening, edge, rel_tol=0, abs_tol=1e-8)
1010
+ )
1011
+
1012
+
1013
+ def entry_cutoff_date(created_at: str, market: str = "cn") -> date | None:
1014
+ """Return the last session date whose bar is at least partly pre-entry.
1015
+
1016
+ ``created_at`` carries its UTC offset (older runs hold a naive local
1017
+ time, read as this machine's local time). It is converted to the
1018
+ exchange's timezone: a run created before the session open was priced off
1019
+ the previous close, so that day's bar is entirely post-entry; a run
1020
+ created during or after the session saw part of that day's bar, which must
1021
+ not count toward post-entry run-up or drawdown.
1022
+ """
1023
+ created = parse_timestamp(created_at)
1024
+ if created is None:
1025
+ return None
1026
+ try:
1027
+ spec = get_market(market or "cn")
1028
+ except ValueError:
1029
+ spec = get_market("cn")
1030
+ local = created.astimezone(ZoneInfo(spec.timezone))
1031
+ hour, minute = (int(part) for part in spec.session_open.split(":"))
1032
+ if local.time() < time(hour, minute):
1033
+ return local.date() - timedelta(days=1)
1034
+ return local.date()
1035
+
1036
+
1037
+ def _completed_sessions(
1038
+ df: pd.DataFrame,
1039
+ market: str,
1040
+ *,
1041
+ now: datetime | None = None,
1042
+ ) -> pd.DataFrame:
1043
+ """Keep bars whose session had closed at ``now`` (default: the current time).
1044
+
1045
+ Pass the history's fetch time as ``now`` so a bar captured mid-session is
1046
+ never treated as that session's close.
1047
+ """
1048
+ if "date" not in df.columns or df["date"].dropna().empty:
1049
+ return df
1050
+ try:
1051
+ spec = get_market(market or "cn")
1052
+ except ValueError:
1053
+ spec = get_market("cn")
1054
+ tz = ZoneInfo(spec.timezone)
1055
+ local_now = (now or datetime.now(tz)).astimezone(tz)
1056
+ hour, minute = (int(part) for part in spec.session_close.split(":"))
1057
+ dates = df["date"].dt.normalize()
1058
+ last_closed = pd.Timestamp(local_now.date())
1059
+ if local_now.time() < time(hour, minute):
1060
+ last_closed -= pd.Timedelta(days=1)
1061
+ return df[dates <= last_closed].copy()
1062
+
1063
+
1064
+ def _history_fetched_at(path: pd.DataFrame) -> datetime | None:
1065
+ raw = getattr(path, "attrs", {}).get("fetched_at")
1066
+ if isinstance(raw, datetime):
1067
+ return raw
1068
+ try:
1069
+ return datetime.fromisoformat(str(raw)) if raw else None
1070
+ except ValueError:
1071
+ return None
1072
+
1073
+
1074
+ def _filter_path_after_entry(df: pd.DataFrame, cutoff: date | None) -> pd.DataFrame:
1075
+ if cutoff is None or "date" not in df.columns or df["date"].dropna().empty:
1076
+ return df
1077
+ dates = df["date"]
1078
+ if getattr(dates.dt, "tz", None) is not None:
1079
+ dates = dates.dt.tz_localize(None)
1080
+ return df[dates.dt.normalize() > pd.Timestamp(cutoff)].copy()
1081
+
1082
+
1083
+ def _load_benchmark_path(
1084
+ run: ScreenResult,
1085
+ *,
1086
+ lookback_days: int,
1087
+ cache: dict[str, pd.DataFrame] | None,
1088
+ ) -> tuple[pd.DataFrame | None, str, list[str]]:
1089
+ try:
1090
+ spec = get_market(run.market or "cn")
1091
+ except ValueError:
1092
+ return None, "", [f"Benchmark skipped: unsupported market {run.market!r}"]
1093
+ label = spec.benchmark_name or spec.benchmark
1094
+ if not spec.benchmark:
1095
+ return None, label, []
1096
+ cutoff = entry_cutoff_date(run.created_at, spec.id)
1097
+ path = cache.get(spec.id) if cache is not None else None
1098
+ if path is not None and not _path_reaches(path, cutoff):
1099
+ # Cached for a newer run with a shorter lookback; batches list runs
1100
+ # newest first, so older runs need a longer history.
1101
+ path = None
1102
+ if path is None:
1103
+ try:
1104
+ path = _fetch_benchmark_path(spec.id, lookback_days=lookback_days)
1105
+ except Exception as exc:
1106
+ return None, label, [f"Benchmark {label} fetch failed: {exc}"]
1107
+ if cache is not None:
1108
+ cache[spec.id] = path
1109
+ return path, label, []
1110
+
1111
+
1112
+ def _benchmark_return(
1113
+ run: ScreenResult,
1114
+ *,
1115
+ horizon_days: int,
1116
+ lookback_days: int,
1117
+ cache: dict[str, pd.DataFrame] | None,
1118
+ ) -> tuple[float | None, str, list[str], pd.Series | None]:
1119
+ """Return the benchmark's close-based T+N return and post-cutoff return curve."""
1120
+ path, label, errors = _load_benchmark_path(run, lookback_days=lookback_days, cache=cache)
1121
+ if path is None:
1122
+ return None, label, errors, None
1123
+ market = run.market or "cn"
1124
+ cutoff = entry_cutoff_date(run.created_at, market)
1125
+ # Entry level = the benchmark close on the entry cutoff session, so the
1126
+ # benchmark and the picks share the same start and the same N bars.
1127
+ df = _normalize_price_path(path)
1128
+ if df.empty or cutoff is None or "date" not in df.columns:
1129
+ return None, label, [f"Benchmark {label} has no usable history"], None
1130
+ dates = df["date"].dt.normalize()
1131
+ before = df[dates <= pd.Timestamp(cutoff)]
1132
+ if before.empty:
1133
+ return None, label, [f"Benchmark {label} history does not reach the entry date"], None
1134
+ entry_level = float(before["close"].iloc[-1])
1135
+ metrics = _price_path_metrics(
1136
+ path,
1137
+ entry_price=entry_level,
1138
+ created_at=run.created_at,
1139
+ cost_bps=0.0,
1140
+ market=market,
1141
+ horizon_days=horizon_days,
1142
+ )
1143
+ after = _completed_sessions(
1144
+ _filter_path_after_entry(df, cutoff), market, now=_history_fetched_at(path)
1145
+ )
1146
+ curve = pd.Series(
1147
+ (after["close"].to_numpy(dtype=float) / entry_level - 1.0) * 100,
1148
+ index=after["date"].dt.normalize(),
1149
+ )
1150
+ return metrics["path_end_return_pct"], label, [], curve
1151
+
1152
+
1153
+ def _benchmark_return_through(curve: pd.Series | None, end_date) -> float | None:
1154
+ """Benchmark return from the entry close to the last close on or before ``end_date``."""
1155
+ if curve is None or curve.empty or end_date is None:
1156
+ return None
1157
+ upto = curve[curve.index <= pd.Timestamp(end_date).normalize()]
1158
+ return _safe_round(float(upto.iloc[-1])) if not upto.empty else None
1159
+
1160
+
1161
+ def _next_open_benchmark(
1162
+ run: ScreenResult,
1163
+ *,
1164
+ horizon_days: int,
1165
+ lookback_days: int,
1166
+ cache: dict[str, pd.DataFrame] | None,
1167
+ ) -> tuple[float | None, str, list[str], pd.DataFrame | None]:
1168
+ path, label, errors = _load_benchmark_path(run, lookback_days=lookback_days, cache=cache)
1169
+ if path is None:
1170
+ return None, label, errors, None
1171
+ bars = _normalize_price_path(path)
1172
+ cutoff = entry_cutoff_date(run.created_at, run.market)
1173
+ if bars.empty or cutoff is None or "date" not in bars.columns:
1174
+ return None, label, [f"Benchmark {label} has no usable history"], None
1175
+ bars = _completed_sessions(
1176
+ _filter_path_after_entry(bars, cutoff), run.market, now=_history_fetched_at(path)
1177
+ )
1178
+ bars["date"] = bars["date"].dt.normalize()
1179
+ bars = bars.drop_duplicates("date", keep="last").set_index("date")
1180
+ if "open" not in bars:
1181
+ return None, label, [f"Benchmark {label} history has no open column"], bars
1182
+ if len(bars) < horizon_days:
1183
+ return None, label, [], bars
1184
+ benchmark_return, error = _benchmark_open_return(
1185
+ bars, bars.index[0], bars.index[horizon_days - 1], label
1186
+ )
1187
+ return benchmark_return, label, [error] if error else [], bars
1188
+
1189
+
1190
+ def _benchmark_open_return(
1191
+ bars: pd.DataFrame, entry_date: pd.Timestamp, exit_date: pd.Timestamp, label: str
1192
+ ) -> tuple[float | None, str]:
1193
+ """Match both endpoints of a pick's open-to-close window by date."""
1194
+ if "open" not in bars:
1195
+ return None, f"Benchmark {label} history has no open column"
1196
+ if entry_date not in bars.index or exit_date not in bars.index:
1197
+ return None, f"Benchmark {label} history lacks a matching entry or exit session"
1198
+ opening = bars.at[entry_date, "open"]
1199
+ if pd.isna(opening) or opening <= 0:
1200
+ return None, f"Benchmark {label} has no usable open on {entry_date.date().isoformat()}"
1201
+ return _safe_round((float(bars.at[exit_date, "close"]) / float(opening) - 1.0) * 100), ""
1202
+
1203
+
1204
+ def _path_reaches(path: pd.DataFrame, cutoff: date | None) -> bool:
1205
+ """True when the history has a bar on or before the entry cutoff session."""
1206
+ if cutoff is None:
1207
+ return True
1208
+ df = _normalize_price_path(path)
1209
+ if df.empty or "date" not in df.columns:
1210
+ return False
1211
+ return bool((df["date"].dt.normalize() <= pd.Timestamp(cutoff)).any())
1212
+
1213
+
1214
+ def _fetch_benchmark_path(market: str, *, lookback_days: int) -> pd.DataFrame:
1215
+ spec = get_market(market or "cn")
1216
+ if not spec.benchmark:
1217
+ raise RuntimeError(f"no benchmark configured for market {spec.id}")
1218
+ fetched_at = datetime.now().astimezone()
1219
+ if spec.id == "cn":
1220
+ from alphasift.daily import _fetch_daily_sina, _fetch_daily_tencent
1221
+
1222
+ sources = (
1223
+ ("tencent", _fetch_daily_tencent),
1224
+ ("sina", _fetch_daily_sina),
1225
+ )
1226
+ else:
1227
+ from alphasift.snapshot_us import fetch_daily_history_yfinance
1228
+
1229
+ sources = (("yfinance", fetch_daily_history_yfinance),)
1230
+
1231
+ errors: list[str] = []
1232
+ path: pd.DataFrame | None = None
1233
+ for name, fetcher in sources:
1234
+ for attempt in range(2):
1235
+ try:
1236
+ candidate = fetcher(spec.benchmark, lookback_days=lookback_days)
1237
+ if candidate is None or candidate.empty:
1238
+ raise RuntimeError(f"{name} benchmark history empty for {spec.benchmark}")
1239
+ norm = _normalize_price_path(candidate)
1240
+ if norm.empty or "date" not in norm.columns:
1241
+ raise RuntimeError(
1242
+ f"{name} benchmark history has no valid dated closes for {spec.benchmark}"
1243
+ )
1244
+ path = norm
1245
+ break
1246
+ except Exception as exc: # noqa: BLE001 - retry / fall through to backup benchmark source
1247
+ errors.append(f"{name}[{attempt + 1}]: {exc}")
1248
+ if attempt == 0:
1249
+ _time.sleep(0.4)
1250
+ if path is not None:
1251
+ break
1252
+
1253
+ if path is None:
1254
+ raise RuntimeError("; ".join(errors))
1255
+ path.attrs["fetched_at"] = fetched_at.isoformat()
1256
+ return path
1257
+
1258
+
1259
+ def _normalize_price_path(path: pd.DataFrame, *, fill_missing_extremes: bool = True) -> pd.DataFrame:
1260
+ rename_map = {
1261
+ "日期": "date",
1262
+ "收盘": "close",
1263
+ "开盘": "open",
1264
+ "最高": "high",
1265
+ "最低": "low",
1266
+ }
1267
+ df = path.rename(columns=rename_map).copy()
1268
+ if "close" not in df.columns:
1269
+ return pd.DataFrame()
1270
+ price_columns = ("close", "high", "low", "open") if "open" in df.columns else ("close", "high", "low")
1271
+ for column in price_columns:
1272
+ if column not in df.columns:
1273
+ df[column] = df["close"] if fill_missing_extremes else float("nan")
1274
+ df[column] = pd.to_numeric(df[column], errors="coerce").replace(
1275
+ [float("inf"), float("-inf")], float("nan")
1276
+ )
1277
+ for raw_col in ("raw_open", "raw_high", "raw_low", "raw_close", "raw_pre_close"):
1278
+ if raw_col in df.columns:
1279
+ df[raw_col] = pd.to_numeric(df[raw_col], errors="coerce").replace(
1280
+ [float("inf"), float("-inf")], float("nan")
1281
+ )
1282
+ valid = df["close"].notna() & (df["close"] > 0)
1283
+ if "date" in df.columns:
1284
+ try:
1285
+ parsed_dates = pd.to_datetime(df["date"], format="mixed", errors="coerce")
1286
+ except (TypeError, ValueError):
1287
+ parsed_dates = pd.to_datetime(df["date"], errors="coerce")
1288
+ if not pd.api.types.is_datetime64_any_dtype(parsed_dates):
1289
+ parsed_dates = pd.to_datetime(
1290
+ df["date"], errors="coerce", utc=True
1291
+ ).dt.tz_localize(None)
1292
+ elif getattr(parsed_dates.dt, "tz", None) is not None:
1293
+ parsed_dates = parsed_dates.dt.tz_localize(None)
1294
+ df["date"] = parsed_dates
1295
+ valid &= df["date"].notna()
1296
+ df = df.loc[valid].sort_values("date")
1297
+ else:
1298
+ df = df.loc[valid]
1299
+ return df.copy()
1300
+
1301
+
1302
+ def _classify_shape_status(
1303
+ pick,
1304
+ return_pct: float | None,
1305
+ *,
1306
+ follow_through_pct: float,
1307
+ failed_breakout_pct: float,
1308
+ ) -> tuple[str, list[str]]:
1309
+ tags: list[str] = []
1310
+ status = ""
1311
+
1312
+ if pick.breakout_20d_pct is not None and pick.breakout_20d_pct >= -1.5:
1313
+ tags.append("breakout_setup")
1314
+ if return_pct is None:
1315
+ status = "breakout_pending"
1316
+ elif return_pct >= follow_through_pct:
1317
+ status = "breakout_follow_through"
1318
+ elif return_pct <= failed_breakout_pct:
1319
+ status = "failed_breakout"
1320
+ else:
1321
+ status = "breakout_unconfirmed"
1322
+
1323
+ if pick.pullback_to_ma20_pct is not None and -3.0 <= pick.pullback_to_ma20_pct <= 6.0:
1324
+ tags.append("ma20_pullback_setup")
1325
+ if not status:
1326
+ if return_pct is None:
1327
+ status = "pullback_pending"
1328
+ elif return_pct > 0:
1329
+ status = "pullback_rebound"
1330
+ else:
1331
+ status = "pullback_failed"
1332
+
1333
+ if pick.consolidation_days_20d is not None and pick.consolidation_days_20d >= 8:
1334
+ tags.append("consolidation_setup")
1335
+
1336
+ return status, tags
1337
+
1338
+
1339
+ def _aggregate_evaluations(evaluations: list[EvaluationResult]) -> dict[str, object]:
1340
+ returns = [
1341
+ float(pick.return_pct)
1342
+ for evaluation in evaluations
1343
+ for pick in evaluation.picks
1344
+ if pick.return_pct is not None
1345
+ ]
1346
+ drawdowns = [
1347
+ float(pick.max_drawdown_pct)
1348
+ for evaluation in evaluations
1349
+ for pick in evaluation.picks
1350
+ if pick.max_drawdown_pct is not None
1351
+ ]
1352
+ runups = [
1353
+ float(pick.max_runup_pct)
1354
+ for evaluation in evaluations
1355
+ for pick in evaluation.picks
1356
+ if pick.max_runup_pct is not None
1357
+ ]
1358
+ excess = [
1359
+ float(pick.excess_return_pct)
1360
+ for evaluation in evaluations
1361
+ for pick in evaluation.picks
1362
+ if pick.excess_return_pct is not None
1363
+ ]
1364
+ # Benchmark and excess cover only picks with benchmark data for their own
1365
+ # window. The matched return average is over the same picks, so
1366
+ # matched_return - bench == excess even when coverage is partial; the
1367
+ # all-pick average_return_pct can differ from it.
1368
+ matched = [
1369
+ (float(pick.return_pct), float(pick.benchmark_return_pct))
1370
+ for evaluation in evaluations
1371
+ for pick in evaluation.picks
1372
+ if pick.excess_return_pct is not None
1373
+ and pick.benchmark_return_pct is not None
1374
+ and pick.return_pct is not None
1375
+ ]
1376
+ benchmark_returns = [bench for _, bench in matched]
1377
+ benchmarks = sorted({evaluation.benchmark for evaluation in evaluations if evaluation.benchmark})
1378
+ benchmark_errors = _dedupe_strings(
1379
+ item
1380
+ for evaluation in evaluations
1381
+ for item in evaluation.degradation
1382
+ if str(item).startswith("Benchmark ")
1383
+ )
1384
+ pick_count = sum(len(evaluation.picks) for evaluation in evaluations)
1385
+ missing_count = sum(len(evaluation.missing_codes) for evaluation in evaluations)
1386
+ untradable_count = sum(evaluation.untradable_count for evaluation in evaluations)
1387
+ tradability_flag_counts = Counter(
1388
+ flag for evaluation in evaluations for pick in evaluation.picks for flag in pick.tradability_flags
1389
+ )
1390
+ return {
1391
+ "run_count": len(evaluations),
1392
+ "pick_count": pick_count,
1393
+ "evaluated_pick_count": len(returns),
1394
+ "missing_count": missing_count,
1395
+ "average_return_pct": _safe_round(sum(returns) / len(returns)) if returns else None,
1396
+ "median_return_pct": _safe_round(float(pd.Series(returns).median())) if returns else None,
1397
+ "win_rate": _safe_round(sum(1 for value in returns if value > 0) / len(returns) * 100)
1398
+ if returns else None,
1399
+ "path_pick_count": len(drawdowns),
1400
+ "average_max_drawdown_pct": _safe_round(sum(drawdowns) / len(drawdowns)) if drawdowns else None,
1401
+ "median_max_drawdown_pct": _safe_round(float(pd.Series(drawdowns).median())) if drawdowns else None,
1402
+ "average_max_runup_pct": _safe_round(sum(runups) / len(runups)) if runups else None,
1403
+ "median_max_runup_pct": _safe_round(float(pd.Series(runups).median())) if runups else None,
1404
+ "pending_count": sum(evaluation.pending_count for evaluation in evaluations),
1405
+ "untradable_count": untradable_count,
1406
+ "untradable_share_pct": _untradable_share_pct(untradable_count, pick_count),
1407
+ "tradability_flag_counts": dict(sorted(tradability_flag_counts.items())),
1408
+ "benchmark": ",".join(benchmarks),
1409
+ # Why bench/excess are empty when they are: fetch failures, short history.
1410
+ "benchmark_errors": benchmark_errors,
1411
+ "benchmark_pick_count": len(matched),
1412
+ "average_matched_return_pct": (
1413
+ _safe_round(sum(ret for ret, _ in matched) / len(matched)) if matched else None
1414
+ ),
1415
+ "average_benchmark_return_pct": (
1416
+ _safe_round(sum(benchmark_returns) / len(benchmark_returns)) if benchmark_returns else None
1417
+ ),
1418
+ "average_excess_return_pct": _safe_round(sum(excess) / len(excess)) if excess else None,
1419
+ "beat_benchmark_rate": (
1420
+ _safe_round(sum(1 for value in excess if value > 0) / len(excess) * 100) if excess else None
1421
+ ),
1422
+ }
1423
+
1424
+
1425
+ def _aggregate_portfolios(evaluations: list[EvaluationResult]) -> dict[str, object]:
1426
+ returns: list[float] = []
1427
+ drawdowns: list[float] = []
1428
+ runups: list[float] = []
1429
+ evaluated_runs = 0
1430
+ for evaluation in evaluations:
1431
+ pick_returns = [
1432
+ float(pick.return_pct)
1433
+ for pick in evaluation.picks
1434
+ if pick.return_pct is not None
1435
+ ]
1436
+ if pick_returns:
1437
+ evaluated_runs += 1
1438
+ returns.append(sum(pick_returns) / len(pick_returns))
1439
+ pick_drawdowns = [
1440
+ float(pick.max_drawdown_pct)
1441
+ for pick in evaluation.picks
1442
+ if pick.max_drawdown_pct is not None
1443
+ ]
1444
+ if pick_drawdowns:
1445
+ drawdowns.append(sum(pick_drawdowns) / len(pick_drawdowns))
1446
+ pick_runups = [
1447
+ float(pick.max_runup_pct)
1448
+ for pick in evaluation.picks
1449
+ if pick.max_runup_pct is not None
1450
+ ]
1451
+ if pick_runups:
1452
+ runups.append(sum(pick_runups) / len(pick_runups))
1453
+ return {
1454
+ "run_count": len(evaluations),
1455
+ "evaluated_run_count": evaluated_runs,
1456
+ "average_portfolio_return_pct": _safe_round(sum(returns) / len(returns)) if returns else None,
1457
+ "median_portfolio_return_pct": _safe_round(float(pd.Series(returns).median())) if returns else None,
1458
+ "portfolio_win_rate": _safe_round(sum(1 for value in returns if value > 0) / len(returns) * 100)
1459
+ if returns else None,
1460
+ "path_run_count": len(drawdowns),
1461
+ "average_portfolio_max_drawdown_pct": _safe_round(sum(drawdowns) / len(drawdowns)) if drawdowns else None,
1462
+ "median_portfolio_max_drawdown_pct": _safe_round(float(pd.Series(drawdowns).median()))
1463
+ if drawdowns else None,
1464
+ "average_portfolio_max_runup_pct": _safe_round(sum(runups) / len(runups)) if runups else None,
1465
+ "median_portfolio_max_runup_pct": _safe_round(float(pd.Series(runups).median()))
1466
+ if runups else None,
1467
+ }
1468
+
1469
+
1470
+ def _group_by_strategy(evaluations: list[EvaluationResult]) -> dict[str, list[EvaluationResult]]:
1471
+ result: dict[str, list[EvaluationResult]] = {}
1472
+ for item in evaluations:
1473
+ result.setdefault(item.strategy or "unknown", []).append(item)
1474
+ return result
1475
+
1476
+
1477
+ def _strategy_summaries(evaluations: list[EvaluationResult]) -> list[dict[str, object]]:
1478
+ """Return stable per-strategy evaluation summaries for reports/UI."""
1479
+ summaries: list[dict[str, object]] = []
1480
+ for strategy, items in _group_by_strategy(evaluations).items():
1481
+ aggregate = _aggregate_evaluations(items)
1482
+ portfolio = _aggregate_portfolios(items)
1483
+ shape_counts: dict[str, int] = {}
1484
+ status_counts: dict[str, int] = {}
1485
+ for evaluation in items:
1486
+ for pick in evaluation.picks:
1487
+ shape = str(pick.shape_status or "unknown")
1488
+ shape_counts[shape] = shape_counts.get(shape, 0) + 1
1489
+ status = str(pick.status or "unknown")
1490
+ status_counts[status] = status_counts.get(status, 0) + 1
1491
+ summaries.append({
1492
+ "strategy": strategy,
1493
+ "run_count": aggregate["run_count"],
1494
+ "pick_count": aggregate["pick_count"],
1495
+ "evaluated_pick_count": aggregate["evaluated_pick_count"],
1496
+ "missing_count": aggregate["missing_count"],
1497
+ "average_return_pct": aggregate["average_return_pct"],
1498
+ "median_return_pct": aggregate["median_return_pct"],
1499
+ "win_rate": aggregate["win_rate"],
1500
+ "average_max_drawdown_pct": aggregate["average_max_drawdown_pct"],
1501
+ "average_max_runup_pct": aggregate["average_max_runup_pct"],
1502
+ "pending_count": aggregate["pending_count"],
1503
+ "untradable_count": aggregate["untradable_count"],
1504
+ "untradable_share_pct": aggregate["untradable_share_pct"],
1505
+ "tradability_flag_counts": aggregate["tradability_flag_counts"],
1506
+ "benchmark": aggregate["benchmark"],
1507
+ "benchmark_pick_count": aggregate["benchmark_pick_count"],
1508
+ "average_matched_return_pct": aggregate["average_matched_return_pct"],
1509
+ "average_benchmark_return_pct": aggregate["average_benchmark_return_pct"],
1510
+ "average_excess_return_pct": aggregate["average_excess_return_pct"],
1511
+ "benchmark_errors": aggregate["benchmark_errors"],
1512
+ "beat_benchmark_rate": aggregate["beat_benchmark_rate"],
1513
+ "average_portfolio_return_pct": portfolio["average_portfolio_return_pct"],
1514
+ "portfolio_win_rate": portfolio["portfolio_win_rate"],
1515
+ "shape_status_counts": dict(sorted(shape_counts.items())),
1516
+ "pick_status_counts": dict(sorted(status_counts.items())),
1517
+ "outcome": _strategy_outcome(aggregate),
1518
+ })
1519
+ return sorted(
1520
+ summaries,
1521
+ key=lambda item: (
1522
+ item["average_return_pct"] is None,
1523
+ -(float(item["average_return_pct"]) if item["average_return_pct"] is not None else -999999.0),
1524
+ str(item["strategy"]),
1525
+ ),
1526
+ )
1527
+
1528
+
1529
+ def _strategy_outcome(summary: dict[str, object]) -> str:
1530
+ avg = summary.get("average_return_pct")
1531
+ win_rate = summary.get("win_rate")
1532
+ if avg is None or win_rate is None:
1533
+ return "insufficient_data"
1534
+ avg_f = float(avg)
1535
+ win_f = float(win_rate)
1536
+ if avg_f > 0 and win_f >= 50:
1537
+ return "positive"
1538
+ if avg_f < 0 and win_f < 50:
1539
+ return "negative"
1540
+ return "mixed"
1541
+
1542
+
1543
+ def _failure_review(
1544
+ evaluations: list[EvaluationResult],
1545
+ *,
1546
+ sample_limit: int = 5,
1547
+ ) -> dict[str, object]:
1548
+ samples = _failure_samples(evaluations)
1549
+ shown_samples = samples[:max(0, int(sample_limit))]
1550
+ dimensions = {
1551
+ "by_strategy": _aggregate_failure_dimension(samples, "strategy"),
1552
+ "by_sector": _aggregate_failure_dimension(samples, "llm_sector"),
1553
+ "by_theme": _aggregate_failure_dimension(samples, "llm_theme"),
1554
+ "by_risk_flag": _aggregate_failure_dimension(samples, "risk_flags", multi=True),
1555
+ "by_portfolio_flag": _aggregate_failure_dimension(samples, "portfolio_flags", multi=True),
1556
+ "by_shape_status": _aggregate_failure_dimension(samples, "shape_status"),
1557
+ "by_shape_tag": _aggregate_failure_dimension(samples, "shape_tags", multi=True),
1558
+ "by_llm_tag": _aggregate_failure_dimension(samples, "llm_tags", multi=True),
1559
+ "by_llm_catalyst": _aggregate_failure_dimension(samples, "llm_catalysts", multi=True),
1560
+ "by_llm_risk": _aggregate_failure_dimension(samples, "llm_risks", multi=True),
1561
+ "by_post_analysis_tag": _aggregate_failure_dimension(samples, "post_analysis_tags", multi=True),
1562
+ "by_event_signal": _aggregate_failure_dimension(samples, "event_signals", multi=True),
1563
+ "by_failure_reason": _aggregate_failure_dimension(samples, "failure_reasons", multi=True),
1564
+ }
1565
+ returns = [
1566
+ float(item["return_pct"])
1567
+ for item in samples
1568
+ if item.get("return_pct") is not None
1569
+ ]
1570
+ negative_returns = [value for value in returns if value < 0]
1571
+ summary = {
1572
+ "failure_count": len(samples),
1573
+ "shown_failure_count": len(shown_samples),
1574
+ "negative_pick_count": sum(1 for item in samples if _is_negative_sample(item)),
1575
+ "missing_count": sum(1 for item in samples if item.get("status") != "ok"),
1576
+ "failed_breakout_count": sum(
1577
+ 1 for item in samples if item.get("shape_status") == "failed_breakout"
1578
+ ),
1579
+ "severe_drawdown_count": sum(
1580
+ 1
1581
+ for item in samples
1582
+ if item.get("max_drawdown_pct") is not None
1583
+ and float(item["max_drawdown_pct"]) <= -8.0
1584
+ ),
1585
+ "average_negative_return_pct": (
1586
+ _safe_round(sum(negative_returns) / len(negative_returns)) if negative_returns else None
1587
+ ),
1588
+ "worst_return_pct": _safe_round(min(returns)) if returns else None,
1589
+ }
1590
+ return {
1591
+ "summary": summary,
1592
+ "failure_samples": shown_samples,
1593
+ "dimensions": dimensions,
1594
+ "recommendations": _failure_recommendations(summary, dimensions),
1595
+ }
1596
+
1597
+
1598
+ def _event_signal_review(evaluations: list[EvaluationResult]) -> dict[str, object]:
1599
+ groups: dict[str, list[tuple[EvaluationResult, PickEvaluation]]] = {}
1600
+ signal_occurrences = 0
1601
+ for evaluation in evaluations:
1602
+ for pick in evaluation.picks:
1603
+ if pick.status in ("pending", "untradable_limit_up"):
1604
+ continue
1605
+ signals = [signal for signal in _event_signals(pick) if signal != "none"]
1606
+ for signal in signals:
1607
+ signal_occurrences += 1
1608
+ groups.setdefault(signal, []).append((evaluation, pick))
1609
+
1610
+ signals = [
1611
+ _event_signal_stats(signal, items)
1612
+ for signal, items in groups.items()
1613
+ ]
1614
+ signals.sort(
1615
+ key=lambda item: (
1616
+ _event_signal_action_rank(str(item.get("action", ""))),
1617
+ item.get("average_return_pct") is None,
1618
+ -(
1619
+ float(item["average_return_pct"])
1620
+ if item.get("average_return_pct") is not None
1621
+ else -999999.0
1622
+ ),
1623
+ -int(item.get("pick_count", 0) or 0),
1624
+ str(item.get("signal", "")),
1625
+ )
1626
+ )
1627
+ summary = {
1628
+ "signal_count": len(signals),
1629
+ "signal_occurrence_count": signal_occurrences,
1630
+ "positive_signal_count": sum(1 for item in signals if item.get("action") == "prefer"),
1631
+ "negative_signal_count": sum(1 for item in signals if item.get("action") == "avoid"),
1632
+ "mixed_signal_count": sum(1 for item in signals if item.get("action") == "watch"),
1633
+ }
1634
+ patch_suggestions = _event_signal_strategy_patch_suggestions(evaluations)
1635
+ summary["patch_suggestion_count"] = len(patch_suggestions)
1636
+ return {
1637
+ "summary": summary,
1638
+ "signals": signals,
1639
+ "strategy_patch_suggestions": patch_suggestions,
1640
+ "recommendations": _event_signal_recommendations(signals),
1641
+ }
1642
+
1643
+
1644
+ def _event_signal_stats(
1645
+ signal: str,
1646
+ items: list[tuple[EvaluationResult, PickEvaluation]],
1647
+ ) -> dict[str, object]:
1648
+ returns = [
1649
+ float(pick.return_pct)
1650
+ for _, pick in items
1651
+ if pick.return_pct is not None
1652
+ ]
1653
+ failures = [
1654
+ pick
1655
+ for _, pick in items
1656
+ if _failure_reasons(pick)
1657
+ ]
1658
+ strategies = _dedupe_strings(evaluation.strategy for evaluation, _ in items)
1659
+ sample_codes = _dedupe_strings(
1660
+ pick.code
1661
+ for _, pick in sorted(
1662
+ items,
1663
+ key=lambda item: (
1664
+ item[1].return_pct is None,
1665
+ float(item[1].return_pct or 0),
1666
+ item[0].strategy,
1667
+ item[1].rank,
1668
+ ),
1669
+ )
1670
+ )[:5]
1671
+ win_rate = (
1672
+ _safe_round(sum(1 for value in returns if value > 0) / len(returns) * 100)
1673
+ if returns
1674
+ else None
1675
+ )
1676
+ average = _safe_round(sum(returns) / len(returns)) if returns else None
1677
+ action = _event_signal_action(average, win_rate, len(failures), len(items))
1678
+ return {
1679
+ "signal": signal,
1680
+ "pick_count": len(items),
1681
+ "evaluated_pick_count": len(returns),
1682
+ "failure_count": len(failures),
1683
+ "failure_rate": _safe_round(len(failures) / len(items) * 100) if items else None,
1684
+ "average_return_pct": average,
1685
+ "median_return_pct": _safe_round(float(pd.Series(returns).median())) if returns else None,
1686
+ "win_rate": win_rate,
1687
+ "best_return_pct": _safe_round(max(returns)) if returns else None,
1688
+ "worst_return_pct": _safe_round(min(returns)) if returns else None,
1689
+ "strategies": strategies,
1690
+ "sample_codes": sample_codes,
1691
+ "action": action,
1692
+ "recommendation": _event_signal_action_text(signal, action),
1693
+ }
1694
+
1695
+
1696
+ def _event_signal_action(
1697
+ average_return_pct: float | None,
1698
+ win_rate: float | None,
1699
+ failure_count: int,
1700
+ pick_count: int,
1701
+ ) -> str:
1702
+ if average_return_pct is None or win_rate is None:
1703
+ return "insufficient_data"
1704
+ failure_rate = failure_count / pick_count * 100 if pick_count else 0.0
1705
+ if average_return_pct > 0 and win_rate >= 50 and failure_rate < 50:
1706
+ return "prefer"
1707
+ if average_return_pct < 0 or win_rate < 50 or failure_rate >= 50:
1708
+ return "avoid"
1709
+ return "watch"
1710
+
1711
+
1712
+ def _event_signal_action_text(signal: str, action: str) -> str:
1713
+ if action == "prefer":
1714
+ return f"Signal `{signal}` has positive follow-through; consider using it as a preferred event tag."
1715
+ if action == "avoid":
1716
+ return f"Signal `{signal}` has weak or negative follow-through; consider adding it to avoided_event_tags or risk penalties."
1717
+ if action == "watch":
1718
+ return f"Signal `{signal}` is mixed; keep collecting samples before changing strategy weights."
1719
+ return f"Signal `{signal}` has insufficient evaluated samples."
1720
+
1721
+
1722
+ def _event_signal_action_rank(action: str) -> int:
1723
+ return {
1724
+ "avoid": 0,
1725
+ "prefer": 1,
1726
+ "watch": 2,
1727
+ "insufficient_data": 3,
1728
+ }.get(action, 4)
1729
+
1730
+
1731
+ def _event_signal_recommendations(signals: list[dict[str, object]]) -> list[str]:
1732
+ recommendations: list[str] = []
1733
+ avoid = [item for item in signals if item.get("action") == "avoid"]
1734
+ prefer = [item for item in signals if item.get("action") == "prefer"]
1735
+ if avoid:
1736
+ labels = ", ".join(str(item.get("signal")) for item in avoid[:3])
1737
+ recommendations.append(f"Review avoided-event candidates first: {labels}.")
1738
+ if prefer:
1739
+ labels = ", ".join(str(item.get("signal")) for item in prefer[:3])
1740
+ recommendations.append(f"Preferred-event candidates with positive follow-through: {labels}.")
1741
+ if not recommendations:
1742
+ recommendations.append("No strong event-signal lessons yet; keep collecting saved runs and evaluations.")
1743
+ return recommendations
1744
+
1745
+
1746
+ def _event_signal_strategy_patch_suggestions(
1747
+ evaluations: list[EvaluationResult],
1748
+ ) -> list[dict[str, object]]:
1749
+ groups: dict[tuple[str, str], list[tuple[EvaluationResult, PickEvaluation]]] = {}
1750
+ for evaluation in evaluations:
1751
+ strategy = evaluation.strategy or "unknown"
1752
+ for pick in evaluation.picks:
1753
+ if pick.status in ("pending", "untradable_limit_up"):
1754
+ continue
1755
+ for signal in _event_signals(pick):
1756
+ if signal == "none":
1757
+ continue
1758
+ groups.setdefault((strategy, signal), []).append((evaluation, pick))
1759
+
1760
+ by_strategy: dict[str, list[dict[str, object]]] = {}
1761
+ for (strategy, signal), items in groups.items():
1762
+ stats = _event_signal_stats(signal, items)
1763
+ if stats.get("action") not in {"prefer", "avoid"}:
1764
+ continue
1765
+ if not stats.get("evaluated_pick_count"):
1766
+ continue
1767
+ by_strategy.setdefault(strategy, []).append(stats)
1768
+
1769
+ suggestions: list[dict[str, object]] = []
1770
+ for strategy, signals in by_strategy.items():
1771
+ signals.sort(
1772
+ key=lambda item: (
1773
+ _event_signal_action_rank(str(item.get("action", ""))),
1774
+ item.get("average_return_pct") is None,
1775
+ -(
1776
+ float(item["average_return_pct"])
1777
+ if item.get("average_return_pct") is not None
1778
+ else -999999.0
1779
+ ),
1780
+ str(item.get("signal", "")),
1781
+ )
1782
+ )
1783
+ preferred = _event_signal_patch_values(
1784
+ [item for item in signals if item.get("action") == "prefer"]
1785
+ )
1786
+ avoided = _event_signal_patch_values(
1787
+ [item for item in signals if item.get("action") == "avoid"]
1788
+ )
1789
+ if not preferred and not avoided:
1790
+ continue
1791
+ field_changes = _event_signal_field_changes(preferred=preferred, avoided=avoided)
1792
+ suggestions.append({
1793
+ "strategy": strategy,
1794
+ "preferred_event_tags": preferred,
1795
+ "avoided_event_tags": avoided,
1796
+ "field_changes": field_changes,
1797
+ "evidence": [_event_signal_patch_evidence(item) for item in signals],
1798
+ "yaml_patch": _event_signal_yaml_patch(preferred=preferred, avoided=avoided),
1799
+ "recommendation": _event_signal_patch_recommendation(
1800
+ strategy,
1801
+ preferred=preferred,
1802
+ avoided=avoided,
1803
+ ),
1804
+ })
1805
+
1806
+ suggestions.sort(
1807
+ key=lambda item: (
1808
+ -len(item.get("avoided_event_tags", []) or []),
1809
+ -len(item.get("preferred_event_tags", []) or []),
1810
+ str(item.get("strategy", "")),
1811
+ )
1812
+ )
1813
+ return suggestions
1814
+
1815
+
1816
+ def _event_signal_patch_values(signals: list[dict[str, object]]) -> list[str]:
1817
+ return _dedupe_strings(
1818
+ _event_signal_patch_value(str(item.get("signal", "")))
1819
+ for item in signals
1820
+ )
1821
+
1822
+
1823
+ def _event_signal_patch_value(signal: str) -> str:
1824
+ prefix, separator, label = signal.partition(":")
1825
+ if not separator:
1826
+ return signal
1827
+ label = label.strip()
1828
+ if prefix == "risk":
1829
+ return f"风险:{label}"
1830
+ if prefix == "catalyst":
1831
+ return f"催化:{label}"
1832
+ if prefix == "post":
1833
+ return f"后验:{label}"
1834
+ return label
1835
+
1836
+
1837
+ def _event_signal_field_changes(
1838
+ *,
1839
+ preferred: list[str],
1840
+ avoided: list[str],
1841
+ ) -> list[dict[str, object]]:
1842
+ changes: list[dict[str, object]] = []
1843
+ if preferred:
1844
+ changes.append({
1845
+ "path": "screening.event_profile.preferred_event_tags",
1846
+ "operation": "append_unique",
1847
+ "add": preferred,
1848
+ })
1849
+ if avoided:
1850
+ changes.append({
1851
+ "path": "screening.event_profile.avoided_event_tags",
1852
+ "operation": "append_unique",
1853
+ "add": avoided,
1854
+ })
1855
+ return changes
1856
+
1857
+
1858
+ def _event_signal_patch_evidence(item: dict[str, object]) -> dict[str, object]:
1859
+ return {
1860
+ "signal": item.get("signal"),
1861
+ "action": item.get("action"),
1862
+ "pick_count": item.get("pick_count"),
1863
+ "evaluated_pick_count": item.get("evaluated_pick_count"),
1864
+ "average_return_pct": item.get("average_return_pct"),
1865
+ "win_rate": item.get("win_rate"),
1866
+ "failure_count": item.get("failure_count"),
1867
+ "failure_rate": item.get("failure_rate"),
1868
+ "sample_codes": item.get("sample_codes", []),
1869
+ }
1870
+
1871
+
1872
+ def _event_signal_yaml_patch(
1873
+ *,
1874
+ preferred: list[str],
1875
+ avoided: list[str],
1876
+ ) -> str:
1877
+ lines = [
1878
+ "screening:",
1879
+ " event_profile:",
1880
+ ]
1881
+ if preferred:
1882
+ lines.append(" preferred_event_tags:")
1883
+ lines.extend(f" - {value}" for value in preferred)
1884
+ if avoided:
1885
+ lines.append(" avoided_event_tags:")
1886
+ lines.extend(f" - {value}" for value in avoided)
1887
+ return "\n".join(lines)
1888
+
1889
+
1890
+ def _event_signal_patch_recommendation(
1891
+ strategy: str,
1892
+ *,
1893
+ preferred: list[str],
1894
+ avoided: list[str],
1895
+ ) -> str:
1896
+ parts: list[str] = []
1897
+ if preferred:
1898
+ parts.append("prefer " + ", ".join(preferred[:3]))
1899
+ if avoided:
1900
+ parts.append("avoid " + ", ".join(avoided[:3]))
1901
+ return f"Review strategy `{strategy}` event_profile patch: {'; '.join(parts)}."
1902
+
1903
+
1904
+ def _failure_samples(evaluations: list[EvaluationResult]) -> list[dict[str, object]]:
1905
+ samples: list[dict[str, object]] = []
1906
+ for evaluation in evaluations:
1907
+ for pick in evaluation.picks:
1908
+ reasons = _failure_reasons(pick)
1909
+ if not reasons:
1910
+ continue
1911
+ samples.append({
1912
+ "run_id": evaluation.run_id,
1913
+ "strategy": evaluation.strategy,
1914
+ "created_at": evaluation.created_at,
1915
+ "elapsed_days": evaluation.elapsed_days,
1916
+ "code": pick.code,
1917
+ "name": pick.name,
1918
+ "rank": pick.rank,
1919
+ "entry_price": pick.entry_price,
1920
+ "current_price": pick.current_price,
1921
+ "return_pct": pick.return_pct,
1922
+ "final_score": pick.final_score,
1923
+ "status": pick.status,
1924
+ "llm_sector": pick.llm_sector,
1925
+ "llm_theme": pick.llm_theme,
1926
+ "llm_tags": list(pick.llm_tags),
1927
+ "llm_catalysts": list(pick.llm_catalysts),
1928
+ "llm_risks": list(pick.llm_risks),
1929
+ "post_analysis_tags": list(pick.post_analysis_tags),
1930
+ "event_signals": _event_signals(pick),
1931
+ "risk_level": pick.risk_level,
1932
+ "risk_flags": list(pick.risk_flags),
1933
+ "portfolio_flags": list(pick.portfolio_flags),
1934
+ "shape_status": pick.shape_status,
1935
+ "shape_tags": list(pick.shape_tags),
1936
+ "path_status": pick.path_status,
1937
+ "max_drawdown_pct": pick.max_drawdown_pct,
1938
+ "max_runup_pct": pick.max_runup_pct,
1939
+ "failure_reasons": reasons,
1940
+ })
1941
+ return sorted(samples, key=_failure_sample_sort_key)
1942
+
1943
+
1944
+ def _failure_reasons(pick: PickEvaluation) -> list[str]:
1945
+ if pick.status in ("pending", "untradable_limit_up"):
1946
+ return []
1947
+ reasons: list[str] = []
1948
+ if pick.status != "ok":
1949
+ reasons.append(f"quote_status:{pick.status}")
1950
+ if pick.return_pct is not None and pick.return_pct < 0:
1951
+ reasons.append("negative_return")
1952
+ if pick.return_pct <= -5:
1953
+ reasons.append("large_loss")
1954
+ if pick.shape_status in {"failed_breakout", "pullback_failed"}:
1955
+ reasons.append(f"shape_status:{pick.shape_status}")
1956
+ elif pick.shape_status in {"breakout_unconfirmed"}:
1957
+ reasons.append("shape_status:breakout_unconfirmed")
1958
+ if pick.max_drawdown_pct is not None and pick.max_drawdown_pct <= -8:
1959
+ reasons.append("path_drawdown_breach")
1960
+ if pick.path_status and pick.path_status != "ok":
1961
+ reasons.append(f"path_status:{pick.path_status}")
1962
+ if not reasons:
1963
+ return []
1964
+ for flag in pick.risk_flags:
1965
+ reasons.append(f"risk_flag:{flag}")
1966
+ for flag in pick.portfolio_flags:
1967
+ reasons.append(f"portfolio_flag:{flag}")
1968
+ for risk in pick.llm_risks:
1969
+ reasons.append(f"llm_risk:{risk}")
1970
+ return _dedupe_strings(reasons)
1971
+
1972
+
1973
+ def _failure_sample_sort_key(item: dict[str, object]) -> tuple[object, ...]:
1974
+ return_pct = item.get("return_pct")
1975
+ if return_pct is not None:
1976
+ return (0, float(return_pct), str(item.get("strategy", "")), int(item.get("rank", 0) or 0))
1977
+ return (1, str(item.get("status", "")), str(item.get("strategy", "")), int(item.get("rank", 0) or 0))
1978
+
1979
+
1980
+ def _aggregate_failure_dimension(
1981
+ samples: list[dict[str, object]],
1982
+ field: str,
1983
+ *,
1984
+ multi: bool = False,
1985
+ ) -> dict[str, dict[str, object]]:
1986
+ groups: dict[str, list[dict[str, object]]] = {}
1987
+ for sample in samples:
1988
+ labels = _sample_labels(sample.get(field), multi=multi)
1989
+ for label in labels:
1990
+ groups.setdefault(label, []).append(sample)
1991
+ result: dict[str, dict[str, object]] = {}
1992
+ for label, items in groups.items():
1993
+ returns = [
1994
+ float(item["return_pct"])
1995
+ for item in items
1996
+ if item.get("return_pct") is not None
1997
+ ]
1998
+ result[label] = {
1999
+ "failure_count": len(items),
2000
+ "evaluated_failure_count": len(returns),
2001
+ "average_return_pct": _safe_round(sum(returns) / len(returns)) if returns else None,
2002
+ "worst_return_pct": _safe_round(min(returns)) if returns else None,
2003
+ "sample_codes": _dedupe_strings(
2004
+ str(item.get("code", ""))
2005
+ for item in sorted(items, key=_failure_sample_sort_key)
2006
+ if item.get("code")
2007
+ )[:3],
2008
+ }
2009
+ return dict(
2010
+ sorted(
2011
+ result.items(),
2012
+ key=lambda item: (
2013
+ -int(item[1]["failure_count"]),
2014
+ item[1]["worst_return_pct"] is None,
2015
+ float(item[1]["worst_return_pct"] or 0),
2016
+ item[0],
2017
+ ),
2018
+ )
2019
+ )
2020
+
2021
+
2022
+ def _sample_labels(value: object, *, multi: bool) -> list[str]:
2023
+ if multi:
2024
+ return _normalize_labels(value or ["none"])
2025
+ text = str(value or "unknown").strip()
2026
+ return [text or "unknown"]
2027
+
2028
+
2029
+ def _failure_recommendations(
2030
+ summary: dict[str, object],
2031
+ dimensions: dict[str, dict[str, dict[str, object]]],
2032
+ ) -> list[str]:
2033
+ if int(summary.get("failure_count", 0) or 0) == 0:
2034
+ return ["No evaluated failure samples yet; keep collecting saved runs before tuning strategy thresholds."]
2035
+ recommendations: list[str] = []
2036
+ if int(summary.get("missing_count", 0) or 0) > 0:
2037
+ recommendations.append(
2038
+ "Missing or bad current quotes appeared in failure samples; check snapshot source coverage before tuning strategy logic."
2039
+ )
2040
+ if int(summary.get("failed_breakout_count", 0) or 0) > 0:
2041
+ recommendations.append(
2042
+ "Failed breakout samples appeared; review breakout filters such as volume confirmation, MA20 position, and consolidation quality."
2043
+ )
2044
+ if int(summary.get("severe_drawdown_count", 0) or 0) > 0:
2045
+ recommendations.append(
2046
+ "Price-path drawdown breaches appeared; review stop-loss assumptions or tighten volatility and drawdown filters."
2047
+ )
2048
+ risk_item = _top_dimension_label(dimensions.get("by_risk_flag", {}), exclude={"none"})
2049
+ if risk_item:
2050
+ recommendations.append(
2051
+ f"Risk flag `{risk_item}` repeats in failure samples; consider adjusting risk_profile thresholds or penalties."
2052
+ )
2053
+ portfolio_item = _top_dimension_label(dimensions.get("by_portfolio_flag", {}), exclude={"none"})
2054
+ if portfolio_item:
2055
+ recommendations.append(
2056
+ f"Portfolio flag `{portfolio_item}` repeats in failure samples; review portfolio_profile concentration rules."
2057
+ )
2058
+ llm_risk_item = _top_dimension_label(dimensions.get("by_llm_risk", {}), exclude={"none"})
2059
+ if llm_risk_item:
2060
+ recommendations.append(
2061
+ f"LLM risk `{llm_risk_item}` repeats in failure samples; consider adding it to avoided_event_tags or risk_profile penalties."
2062
+ )
2063
+ event_item = _top_dimension_label(dimensions.get("by_event_signal", {}), exclude={"none"})
2064
+ if event_item:
2065
+ recommendations.append(
2066
+ f"Event signal `{event_item}` repeats in failure samples; compare its win/loss history before using it as a positive catalyst."
2067
+ )
2068
+ shape_item = _top_dimension_label(dimensions.get("by_shape_status", {}), exclude={"unknown", ""})
2069
+ if shape_item:
2070
+ recommendations.append(
2071
+ f"Shape outcome `{shape_item}` is a recurring failure bucket; compare it against strategy intent before raising exposure."
2072
+ )
2073
+ return _dedupe_strings(recommendations)
2074
+
2075
+
2076
+ def _top_dimension_label(
2077
+ items: dict[str, dict[str, object]],
2078
+ *,
2079
+ exclude: set[str],
2080
+ ) -> str:
2081
+ for label, stats in items.items():
2082
+ if label in exclude:
2083
+ continue
2084
+ if int(stats.get("failure_count", 0) or 0) <= 0:
2085
+ continue
2086
+ return label
2087
+ return ""
2088
+
2089
+
2090
+ def _is_negative_sample(item: dict[str, object]) -> bool:
2091
+ return item.get("return_pct") is not None and float(item["return_pct"]) < 0
2092
+
2093
+
2094
+ def _event_signals(pick: PickEvaluation) -> list[str]:
2095
+ return _dedupe_strings([
2096
+ *[f"tag:{item}" for item in pick.llm_tags],
2097
+ *[f"catalyst:{item}" for item in pick.llm_catalysts],
2098
+ *[f"risk:{item}" for item in pick.llm_risks],
2099
+ *[f"post:{item}" for item in pick.post_analysis_tags],
2100
+ ]) or ["none"]
2101
+
2102
+
2103
+ def _dedupe_strings(values) -> list[str]:
2104
+ result: list[str] = []
2105
+ seen: set[str] = set()
2106
+ for value in values:
2107
+ text = str(value or "").strip()
2108
+ if not text or text in seen:
2109
+ continue
2110
+ seen.add(text)
2111
+ result.append(text)
2112
+ return result
2113
+
2114
+
2115
+ def _safe_finite_float(value: object) -> float | None:
2116
+ if value is None or isinstance(value, bool):
2117
+ return None
2118
+ try:
2119
+ parsed = float(value) # type: ignore[arg-type]
2120
+ except (TypeError, ValueError, OverflowError):
2121
+ return None
2122
+ return parsed if isfinite(parsed) else None
2123
+
2124
+
2125
+ def _safe_positive_int(value: object) -> int:
2126
+ if isinstance(value, bool):
2127
+ return 0
2128
+ if isinstance(value, float) and not isfinite(value):
2129
+ return 0
2130
+ try:
2131
+ parsed = int(value) # type: ignore[arg-type]
2132
+ except (TypeError, ValueError, OverflowError):
2133
+ return 0
2134
+ return parsed if parsed > 0 else 0
2135
+
2136
+
2137
+ def _extract_run_daily_quality_counts(run: ScreenResult) -> tuple[dict[str, int], dict[str, int]]:
2138
+ """Return persisted or pick-derived daily source and quality flag counts."""
2139
+ sources: dict[str, int] = {}
2140
+ if isinstance(run.daily_source_counts, dict) and run.daily_source_counts:
2141
+ for key, count in run.daily_source_counts.items():
2142
+ name = str(key or "").strip()
2143
+ parsed = _safe_positive_int(count)
2144
+ if name and parsed > 0:
2145
+ sources[name] = parsed
2146
+ else:
2147
+ for pick in run.picks:
2148
+ src = str(pick.daily_source or "").strip()
2149
+ if src:
2150
+ sources[src] = sources.get(src, 0) + 1
2151
+
2152
+ flags: dict[str, int] = {}
2153
+ if isinstance(run.daily_quality_flag_counts, dict) and run.daily_quality_flag_counts:
2154
+ for key, count in run.daily_quality_flag_counts.items():
2155
+ name = str(key or "").strip()
2156
+ parsed = _safe_positive_int(count)
2157
+ if name and parsed > 0:
2158
+ flags[name] = parsed
2159
+ else:
2160
+ for pick in run.picks:
2161
+ raw = str(pick.daily_quality_flags or "")
2162
+ for part in raw.replace(";", ",").replace("|", ",").replace("/", ",").split(","):
2163
+ flag = part.strip()
2164
+ if flag and flag not in {"none", "ok"}:
2165
+ flags[flag] = flags.get(flag, 0) + 1
2166
+
2167
+ return dict(sorted(sources.items())), dict(sorted(flags.items()))
2168
+
2169
+
2170
+ def _data_quality_review(evaluations: list[EvaluationResult]) -> dict[str, object]:
2171
+ """Aggregate saved-run source/quality metadata and correlate clean vs degraded returns."""
2172
+ snapshot_source_counts: dict[str, int] = {}
2173
+ daily_source_counts: dict[str, int] = {}
2174
+ daily_quality_flag_counts: dict[str, int] = {}
2175
+ degraded_reason_counts: dict[str, int] = {}
2176
+ clean_runs = 0
2177
+ degraded_runs = 0
2178
+ clean_returns: list[float] = []
2179
+ degraded_returns: list[float] = []
2180
+
2181
+ for evaluation in evaluations:
2182
+ snap_src = str(evaluation.run_snapshot_source or "").strip()
2183
+ if snap_src:
2184
+ snapshot_source_counts[snap_src] = snapshot_source_counts.get(snap_src, 0) + 1
2185
+ src_map = evaluation.daily_source_counts if isinstance(evaluation.daily_source_counts, dict) else {}
2186
+ for src, cnt in src_map.items():
2187
+ src_name = str(src or "").strip()
2188
+ cnt_val = _safe_positive_int(cnt)
2189
+ if src_name and cnt_val > 0:
2190
+ daily_source_counts[src_name] = daily_source_counts.get(src_name, 0) + cnt_val
2191
+ flags = evaluation.daily_quality_flag_counts if isinstance(evaluation.daily_quality_flag_counts, dict) else {}
2192
+ for flag, cnt in flags.items():
2193
+ flag_name = str(flag or "").strip()
2194
+ cnt_val = _safe_positive_int(cnt)
2195
+ if flag_name and cnt_val > 0:
2196
+ daily_quality_flag_counts[flag_name] = daily_quality_flag_counts.get(flag_name, 0) + cnt_val
2197
+
2198
+ reasons: set[str] = set()
2199
+ for flag, cnt in flags.items():
2200
+ flag_name = str(flag or "").strip()
2201
+ if not flag_name or _safe_positive_int(cnt) <= 0:
2202
+ continue
2203
+ if flag_name == "stale_cache":
2204
+ reasons.add("stale_cache")
2205
+ elif flag_name in {"fetch_failed", "fallback_errors"}:
2206
+ reasons.add("fetch_failed")
2207
+ elif flag_name in {"invalid_ohlc", "missing_in_pack"}:
2208
+ reasons.add(flag_name)
2209
+ else:
2210
+ reasons.add("daily_quality_flags")
2211
+ run_src = snap_src.lower()
2212
+ raw_run_deg = evaluation.run_degradation if isinstance(evaluation.run_degradation, (list, tuple)) else []
2213
+ run_deg = " | ".join(str(x) for x in raw_run_deg).lower()
2214
+ if "stale" in run_src or "stale" in run_deg:
2215
+ reasons.add("stale_cache")
2216
+ if "fetch_failed" in run_deg or "enrichment skipped" in run_deg or "row errors" in run_deg:
2217
+ reasons.add("fetch_failed")
2218
+ if "fallback" in run_src or "cache" in run_src or "fallback" in run_deg:
2219
+ reasons.add("fallback_source")
2220
+ raw_run_errs = evaluation.run_source_errors if isinstance(evaluation.run_source_errors, (list, tuple)) else []
2221
+ if raw_run_errs:
2222
+ reasons.add("source_errors")
2223
+ raw_eval_deg = evaluation.degradation if isinstance(evaluation.degradation, (list, tuple)) else []
2224
+ if any(str(deg).startswith("Failed to evaluate run:") for deg in raw_eval_deg):
2225
+ reasons.add("evaluation_error")
2226
+
2227
+ pick_returns = [
2228
+ ret
2229
+ for p in (evaluation.picks or [])
2230
+ if (ret := _safe_finite_float(p.return_pct)) is not None
2231
+ ]
2232
+ if reasons:
2233
+ degraded_runs += 1
2234
+ degraded_returns.extend(pick_returns)
2235
+ for reason in reasons:
2236
+ degraded_reason_counts[reason] = degraded_reason_counts.get(reason, 0) + 1
2237
+ else:
2238
+ clean_runs += 1
2239
+ clean_returns.extend(pick_returns)
2240
+
2241
+ clean_stats = _return_stats(clean_returns)
2242
+ degraded_stats = _return_stats(degraded_returns)
2243
+ clean_avg = clean_stats.get("average_return_pct")
2244
+ degraded_avg = degraded_stats.get("average_return_pct")
2245
+ gap = (
2246
+ _safe_round(float(degraded_avg) - float(clean_avg))
2247
+ if clean_avg is not None and degraded_avg is not None
2248
+ else None
2249
+ )
2250
+
2251
+ hints: list[str] = []
2252
+ if not evaluations:
2253
+ hints.append("No saved runs evaluated yet.")
2254
+ elif degraded_runs == 0:
2255
+ hints.append(
2256
+ "No degraded saved runs detected in this sample; strategy differences reflect rule/universe behavior rather than cached or failed feeds."
2257
+ )
2258
+ else:
2259
+ reasons_text = ", ".join(f"{k}={v}" for k, v in sorted(degraded_reason_counts.items()))
2260
+ if gap is not None and float(gap) < 0:
2261
+ hints.append(
2262
+ f"Degraded saved runs ({degraded_runs}/{len(evaluations)}; {reasons_text}) "
2263
+ f"underperformed clean runs by {abs(float(gap)):.2f}% avg return; inspect feed/cache degradation before retuning rules."
2264
+ )
2265
+ elif clean_avg is not None and float(clean_avg) < 0 and (degraded_avg is None or float(clean_avg) <= float(degraded_avg)):
2266
+ hints.append(
2267
+ f"Clean runs also averaged {float(clean_avg):.2f}% despite {degraded_runs} degraded run(s) ({reasons_text}); negative return reflects strategy/market conditions rather than feed degradation alone."
2268
+ )
2269
+ else:
2270
+ hints.append(
2271
+ f"{degraded_runs}/{len(evaluations)} evaluated runs had data-quality degradation ({reasons_text}); compare clean vs degraded subsets before concluding."
2272
+ )
2273
+
2274
+ return {
2275
+ "run_count": len(evaluations),
2276
+ "clean_run_count": clean_runs,
2277
+ "degraded_run_count": degraded_runs,
2278
+ "snapshot_source_counts": dict(sorted(snapshot_source_counts.items())),
2279
+ "daily_source_counts": dict(sorted(daily_source_counts.items())),
2280
+ "daily_quality_flag_counts": dict(sorted(daily_quality_flag_counts.items())),
2281
+ "degraded_reason_counts": dict(sorted(degraded_reason_counts.items())),
2282
+ "clean_vs_degraded": {
2283
+ "clean": {"run_count": clean_runs, **clean_stats},
2284
+ "degraded": {"run_count": degraded_runs, **degraded_stats},
2285
+ "return_gap_pct": gap,
2286
+ },
2287
+ "hints": hints,
2288
+ }
2289
+
2290
+
2291
+ def _aggregate_by_pick_label(
2292
+ evaluations: list[EvaluationResult],
2293
+ field: str,
2294
+ ) -> dict[str, dict[str, object]]:
2295
+ groups: dict[str, list[float]] = {}
2296
+ for evaluation in evaluations:
2297
+ for pick in evaluation.picks:
2298
+ value = str(getattr(pick, field, "") or "unknown").strip() or "unknown"
2299
+ if pick.return_pct is not None:
2300
+ groups.setdefault(value, []).append(float(pick.return_pct))
2301
+ else:
2302
+ groups.setdefault(value, [])
2303
+ return {
2304
+ label: _return_stats(values)
2305
+ for label, values in sorted(groups.items())
2306
+ }
2307
+
2308
+
2309
+ def _aggregate_by_pick_multi_label(
2310
+ evaluations: list[EvaluationResult],
2311
+ field: str,
2312
+ ) -> dict[str, dict[str, object]]:
2313
+ groups: dict[str, list[float]] = {}
2314
+ for evaluation in evaluations:
2315
+ for pick in evaluation.picks:
2316
+ labels = _normalize_labels(getattr(pick, field, []) or ["none"])
2317
+ for label in labels:
2318
+ key = str(label or "none").strip() or "none"
2319
+ if pick.return_pct is not None:
2320
+ groups.setdefault(key, []).append(float(pick.return_pct))
2321
+ else:
2322
+ groups.setdefault(key, [])
2323
+ return {
2324
+ label: _return_stats(values)
2325
+ for label, values in sorted(groups.items())
2326
+ }
2327
+
2328
+
2329
+ def _normalize_labels(value: object) -> list[str]:
2330
+ if isinstance(value, str):
2331
+ return [item.strip() for item in value.split(",") if item.strip()] or ["none"]
2332
+ if isinstance(value, list):
2333
+ return [str(item).strip() for item in value if str(item).strip()] or ["none"]
2334
+ return ["none"]
2335
+
2336
+
2337
+ def _aggregate_by_holding_period(evaluations: list[EvaluationResult]) -> dict[str, dict[str, object]]:
2338
+ groups: dict[str, list[float]] = {}
2339
+ for evaluation in evaluations:
2340
+ bucket = _holding_period_bucket(evaluation.elapsed_days)
2341
+ for pick in evaluation.picks:
2342
+ if pick.return_pct is not None:
2343
+ groups.setdefault(bucket, []).append(float(pick.return_pct))
2344
+ else:
2345
+ groups.setdefault(bucket, [])
2346
+ return {
2347
+ label: _return_stats(values)
2348
+ for label, values in sorted(groups.items())
2349
+ }
2350
+
2351
+
2352
+ def _return_stats(values: list[float]) -> dict[str, object]:
2353
+ return {
2354
+ "pick_count": len(values),
2355
+ "average_return_pct": _safe_round(sum(values) / len(values)) if values else None,
2356
+ "median_return_pct": _safe_round(float(pd.Series(values).median())) if values else None,
2357
+ "win_rate": _safe_round(sum(1 for value in values if value > 0) / len(values) * 100)
2358
+ if values else None,
2359
+ }
2360
+
2361
+
2362
+ def _holding_period_bucket(days: int | None) -> str:
2363
+ if days is None:
2364
+ return "unknown"
2365
+ if days <= 1:
2366
+ return "T+0_1"
2367
+ if days <= 5:
2368
+ return "T+2_5"
2369
+ if days <= 20:
2370
+ return "T+6_20"
2371
+ return "T+20_plus"
2372
+
2373
+
2374
+ def _evaluation_brief(evaluation: EvaluationResult) -> dict[str, object]:
2375
+ return {
2376
+ "run_id": evaluation.run_id,
2377
+ "strategy": evaluation.strategy,
2378
+ "created_at": evaluation.created_at,
2379
+ "elapsed_days": evaluation.elapsed_days,
2380
+ "pick_count": len(evaluation.picks),
2381
+ "average_return_pct": evaluation.average_return_pct,
2382
+ "median_return_pct": evaluation.median_return_pct,
2383
+ "win_rate": evaluation.win_rate,
2384
+ "portfolio_return_pct": evaluation.average_return_pct,
2385
+ "path_pick_count": sum(1 for pick in evaluation.picks if pick.path_status == "ok"),
2386
+ "average_max_drawdown_pct": _safe_round(
2387
+ sum(float(pick.max_drawdown_pct) for pick in evaluation.picks if pick.max_drawdown_pct is not None)
2388
+ / sum(1 for pick in evaluation.picks if pick.max_drawdown_pct is not None)
2389
+ ) if any(pick.max_drawdown_pct is not None for pick in evaluation.picks) else None,
2390
+ "missing_count": len(evaluation.missing_codes),
2391
+ "horizon_days": evaluation.horizon_days,
2392
+ "entry_mode": evaluation.entry_mode,
2393
+ "pending_count": evaluation.pending_count,
2394
+ "untradable_count": evaluation.untradable_count,
2395
+ "untradable_share_pct": evaluation.untradable_share_pct,
2396
+ "benchmark": evaluation.benchmark,
2397
+ "benchmark_return_pct": evaluation.benchmark_return_pct,
2398
+ "average_excess_return_pct": evaluation.average_excess_return_pct,
2399
+ "degradation": evaluation.degradation,
2400
+ }
2401
+
2402
+
2403
+ def _elapsed_days(run: ScreenResult) -> int | None:
2404
+ created = parse_timestamp(run.created_at)
2405
+ if created is None:
2406
+ return None
2407
+ return (datetime.now(timezone.utc) - created).days
2408
+
2409
+
2410
+ def _untradable_share_pct(count: int, pick_count: int) -> float | None:
2411
+ return _safe_round(count / pick_count * 100) if pick_count else None
2412
+
2413
+
2414
+ def _safe_round(value: float | None) -> float | None:
2415
+ finite = _safe_finite_float(value)
2416
+ if finite is None:
2417
+ return None
2418
+ return round(finite, 4)