"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(alpha-zoo): bench runner + CLI + Web UI + 4 REST routes
Haozhe Wud77c64e2ce44
diff --git a/agent/api_server.py b/agent/api_server.pyindex 61990622c..3a1b04fde 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -1717,6 +1717,14 @@ async def cancel_swarm_run(run_id: str):return {"status": "cancelled"}+# ============================================================================+# Alpha Zoo routes (Web UI) — defined in src/api/alpha_routes.py+# ============================================================================++from src.api.alpha_routes import register_alpha_routes # noqa: E402+register_alpha_routes(app)++# ============================================================================# Main Entry Point# ============================================================================diff --git a/agent/cli.py b/agent/cli.pyindex b4d5cd5aa..878f6ddb7 100644--- a/agent/cli.py+++ b/agent/cli.py@@ -2339,6 +2339,10 @@ def _build_parser() -> argparse.ArgumentParser:memory_forget_parser.add_argument("name", help="Memory title or filename stem")memory_forget_parser.add_argument("-y", "--yes", action="store_true", help="Skip confirmation prompt")+ # Alpha Zoo subcommands (registered via cli_handlers.add_subparser)+ from src.factors.cli_handlers import add_subparser as _add_alpha_subparser+ _add_alpha_subparser(subparsers)+return parser@@ -2814,6 +2818,9 @@ def main(argv: list[str] | None = None) -> int:return _coerce_exit_code(cmd_show(args.show))if args.command == "chat":return _coerce_exit_code(cmd_interactive(args.chat_max_iter))+ if args.command == "alpha":+ from src.factors.cli_handlers import dispatch as _alpha_dispatch+ return _coerce_exit_code(_alpha_dispatch(args))if args.command == "memory":if args.memory_command == "list":return _coerce_exit_code(cmd_memory_list(args.memory_type))diff --git a/agent/scripts/w4a_patch_blog.py b/agent/scripts/w4a_patch_blog.pynew file mode 100644index 000000000..eee7acca2--- /dev/null+++ b/agent/scripts/w4a_patch_blog.py@@ -0,0 +1,250 @@+"""W4.a blog patcher: fill TBD placeholders in alpha-191-in-2026.html.++Reads ~/.vibe-trading/reports/bench_summary.json (produced by w4a_run_benches.py)+and patches the HTML in place.++Substitutions performed:+- num-alive / num-reversed / num-dead spans in the two stat blocks+- Theme survival table rows (count + survival rate per theme)+- Top 5 alphas (id + formula + IC mean)+- 3 famously-dead alphas (replace invented IDs with worst-IC from gtja191)+- Section-level "bench failed" callouts where the corresponding bench errored++The patcher never fabricates a number: if the gtja191 bench is missing, every+TBD that depends on it becomes a "bench failed" note instead. The script is+idempotent — re-running with the same summary produces the same HTML.+"""++from __future__ import annotations++import html+import json+import re+import sys+from pathlib import Path+from typing import Any++REPO = Path(__file__).resolve().parents[2]+HTML_PATH = REPO / "wiki" / "research-lab" / "posts" / "alpha-191-in-2026.html"+SUMMARY_PATH = Path.home() / ".vibe-trading" / "reports" / "bench_summary.json"++GTJA_KEY = "gtja191_csi300"++# Themes shown in the table — these are the human labels in the HTML, mapped+# to the canonical theme tags in registry meta. "Volume-price interaction"+# requires *both* volume and reversal-or-momentum, so it gets a custom probe.+THEME_LABEL_TO_TAGS: dict[str, list[str]] = {+ "Volume-price interaction": ["volume"],+ "Short-horizon volatility": ["volatility"],+ "Reversal": ["reversal"],+ "Momentum": ["momentum"],+ "Turnover / liquidity": ["liquidity"],+ "Microstructure / range": ["microstructure"],+}+++def _load_summary() -> dict[str, Any]:+ if not SUMMARY_PATH.is_file():+ raise SystemExit(f"summary not found: {SUMMARY_PATH}")+ return json.loads(SUMMARY_PATH.read_text(encoding="utf-8"))+++def _gtja_entry(summary: dict[str, Any]) -> dict[str, Any] | None:+ entry = summary.get("zoos", {}).get(GTJA_KEY)+ if not entry or entry.get("status") != "ok":+ return None+ return entry+++def _patch_stats(text: str, entry: dict[str, Any]) -> str:+ for span_class, key in (+ ("num-alive", "alive"),+ ("num-reversed", "reversed"),+ ("num-dead", "dead"),+ ):+ value = entry.get(key)+ if value is None:+ continue+ pattern = re.compile(+ rf'(<span class="{span_class}">)\[TBD\](</span>)'+ )+ text = pattern.sub(rf"\g<1>{int(value)}\g<2>", text)+ return text+++def _theme_survival_rows(entry: dict[str, Any]) -> str:+ """Build the inner <tr> rows for the theme-survival table."""+ by_theme = entry.get("by_theme", {})+ rows: list[str] = []+ definitions = {+ "Volume-price interaction": "Correlation / covariance of volume with close, high-low range",+ "Short-horizon volatility": "Rolling std / range over 5-20 day windows",+ "Reversal": "Negative-sign return signals over 1-5 day horizons",+ "Momentum": "Positive-sign return signals over 10-60 day horizons",+ "Turnover / liquidity": "Volume ratios, turnover-rate transforms",+ "Microstructure / range": "Open-close-high-low decompositions, intraday range proxies",+ }+ for label, tags in THEME_LABEL_TO_TAGS.items():+ # Aggregate across all listed tags (most themes are single-tag).+ alive = dead = reversed_ = count = 0+ for tag in tags:+ bucket = by_theme.get(tag)+ if bucket is None:+ continue+ alive += bucket.get("alive", 0)+ dead += bucket.get("dead", 0)+ reversed_ += bucket.get("reversed", 0)+ count += bucket.get("count", 0)+ if count == 0:+ count_cell = "n/a"+ rate_cell = "n/a"+ else:+ count_cell = str(count)+ rate_cell = f"{alive / count * 100:.0f}% ({alive}/{count})"+ rows.append(+ " <tr>\n"+ f" <td>{html.escape(label)}</td>\n"+ f" <td>{html.escape(definitions[label])}</td>\n"+ f" <td>{count_cell}</td>\n"+ f" <td>{rate_cell}</td>\n"+ " </tr>"+ )+ return "\n".join(rows)+++def _patch_theme_table(text: str, entry: dict[str, Any]) -> str:+ new_rows = _theme_survival_rows(entry)+ pattern = re.compile(+ r'(<tbody>)(.*?)(</tbody>)',+ re.DOTALL,+ )+ # The HTML has exactly one <tbody> inside the theme-table; surgical replace.+ def _swap(match: re.Match[str]) -> str:+ body = match.group(2)+ if "Volume-price interaction" not in body:+ return match.group(0) # not the theme table+ return f"{match.group(1)}\n{new_rows}\n {match.group(3)}"++ return pattern.sub(_swap, text, count=1)+++def _formula_to_html(formula: str) -> str:+ return html.escape(formula)+++def _build_top5_cards(entry: dict[str, Any]) -> str:+ rows = entry.get("top5_by_ir", [])[:5]+ cards: list[str] = []+ for row in rows:+ aid = row["id"]+ formula = _formula_to_html(row.get("formula_latex", ""))+ ic = row.get("ic_mean", 0.0)+ ir = row.get("ir", 0.0)+ cards.append(+ " <article class=\"alpha-card\">\n"+ f" <span class=\"alpha-id\">{html.escape(aid)}</span>\n"+ f" <pre class=\"formula-block\"><code>{formula}</code></pre>\n"+ " <p class=\"alpha-note\">"+ f"Mean IC = {ic:.4f}, IR = {ir:.4f} over the CSI 300 / 2018–2025 window. "+ "Formula reproduced verbatim from the registry "+ f"(<code>__alpha_meta__[\"formula_latex\"]</code> of <code>{html.escape(aid)}</code>)."+ "</p>\n"+ " </article>"+ )+ return "\n".join(cards)+++def _build_dead_cards(entry: dict[str, Any]) -> str:+ rows = entry.get("dead_examples", [])[:3]+ cards: list[str] = []+ for row in rows:+ aid = row["id"]+ formula = _formula_to_html(row.get("formula_latex", ""))+ ic = row.get("ic_mean", 0.0)+ cat = row.get("category", "dead")+ ir = row.get("ir", 0.0)+ cards.append(+ " <article class=\"alpha-card\">\n"+ f" <span class=\"alpha-id\">{html.escape(aid)} ({html.escape(cat)})</span>\n"+ f" <pre class=\"formula-block\"><code>{formula}</code></pre>\n"+ " <p class=\"alpha-note\">"+ f"Mean IC = {ic:.4f}, IR = {ir:.4f}. Worst-performing slice of the gtja191 "+ "zoo on CSI 300 / 2018–2025 by raw IC."+ "</p>\n"+ " </article>"+ )+ return "\n".join(cards)+++def _patch_top5(text: str, entry: dict[str, Any]) -> str:+ cards = _build_top5_cards(entry)+ pattern = re.compile(+ r'(<h3>Top 5 surviving alphas</h3>.*?</p>\s*)' # heading + lead paragraph+ r'(?:<article class="alpha-card">.*?</article>\s*){5}',+ re.DOTALL,+ )+ return pattern.sub(rf"\g<1>{cards}\n\n ", text, count=1)+++def _patch_dead(text: str, entry: dict[str, Any]) -> str:+ cards = _build_dead_cards(entry)+ pattern = re.compile(+ r'(<h3>Three famously dead alphas</h3>.*?</p>\s*)'+ r'(?:<article class="alpha-card">.*?</article>\s*){3}',+ re.DOTALL,+ )+ return pattern.sub(rf"\g<1>{cards}\n\n ", text, count=1)+++def _patch_bench_failed_note(text: str) -> str:+ """Replace the W4-roadmap placeholder callout with a real timestamp note."""+ return text.replace(+ "Numbers will be filled in once the full bench finishes (Vibe-Trading\n roadmap W4.a). "+ "This post is published as a methodology preview — the structure, definitions\n and caveats are final.",+ "Numbers below are the live W4.a bench output on the bundled gtja191 zoo "+ "(CSI 300, 2018–2025) — reproducible via the CLI snippet at the end of the post.",+ )+++def main() -> int:+ summary = _load_summary()+ entry = _gtja_entry(summary)++ text = HTML_PATH.read_text(encoding="utf-8")++ if entry is None:+ # Surface the failure once at the top; leave all TBDs intact so the+ # reader sees we have not invented numbers.+ zoo_blob = summary.get("zoos", {}).get(GTJA_KEY, {})+ reason = zoo_blob.get("error", "bench did not run")+ note = (+ '<p class="bench-failed"><strong>Note:</strong> the gtja191 / CSI 300 bench '+ f"failed during W4.a (reason: {html.escape(str(reason))}). All TBD numbers below "+ "remain to be filled in 0.1.9 once the bench is re-run.</p>"+ )+ text = text.replace(+ 'roadmap W4.a). This post',+ f'roadmap W4.a). {note} This post'+ )+ HTML_PATH.write_text(text, encoding="utf-8")+ print(f"bench failed; left TBDs intact and added note. tbd count = "+ f"{text.count('[TBD]')}", file=sys.stderr)+ return 0++ text = _patch_stats(text, entry)+ text = _patch_theme_table(text, entry)+ text = _patch_top5(text, entry)+ text = _patch_dead(text, entry)+ text = _patch_bench_failed_note(text)++ # Mean IC ~ [TBD] placeholders inside the per-card paragraphs are no longer+ # needed (we rewrote the cards with real numbers). Sanity-check sweep.+ HTML_PATH.write_text(text, encoding="utf-8")++ remaining = text.count("[TBD]")+ print(f"patched {HTML_PATH}; remaining [TBD] = {remaining}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/agent/scripts/w4a_run_benches.py b/agent/scripts/w4a_run_benches.pynew file mode 100644index 000000000..f13273dad--- /dev/null+++ b/agent/scripts/w4a_run_benches.py@@ -0,0 +1,170 @@+"""W4.a bench driver: run 4 zoo×universe combinations and emit summary JSON.++Usage:+ cd agent && python scripts/w4a_run_benches.py++Output:+ ~/.vibe-trading/reports/alpha_bench_*.html — per-run HTML reports+ ~/.vibe-trading/reports/bench_<zoo>_<uni>.json — per-run raw results+ ~/.vibe-trading/reports/bench_summary.json — aggregate summary++Safe to re-run; each bench result is cached by ``_load_universe_panel`` so the+expensive Tushare/yfinance fetches only happen once per (universe, period).+"""++from __future__ import annotations++import json+import logging+import os+import sys+import time+from datetime import datetime, timezone+from pathlib import Path++from dotenv import load_dotenv++# Repo-relative imports+HERE = Path(__file__).resolve().parent+AGENT_DIR = HERE.parent+sys.path.insert(0, str(AGENT_DIR))++load_dotenv(AGENT_DIR / ".env")++# Configure logging early so universe loaders log their progress.+logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s | %(message)s",+)+logger = logging.getLogger("w4a")++from src.factors.bench_runner import run_bench # noqa: E402+from src.tools.alpha_bench_tool import run_alpha_bench # noqa: E402+++REPORTS_DIR = Path.home() / ".vibe-trading" / "reports"++BENCHES = [+ {"key": "gtja191_csi300", "zoo": "gtja191", "universe": "csi300", "period": "2018-2025"},+ {"key": "alpha101_sp500", "zoo": "alpha101", "universe": "sp500", "period": "2020-2025"},+ {"key": "qlib158_csi300", "zoo": "qlib158", "universe": "csi300", "period": "2020-2025"},+ {"key": "alpha101_btc", "zoo": "alpha101", "universe": "btc-usdt", "period": "2022-2025"},+]+++def _run_one(bench: dict) -> dict:+ """Run a single bench end-to-end. Returns a summary entry.++ Delegates the math to ``src.factors.bench_runner.run_bench``; this wrapper+ just adds the HTML report (via ``run_alpha_bench``) and persists the raw+ per-alpha rows for downstream tooling, both of which the CLI driver wants+ but the API route does not.+ """+ key = bench["key"]+ zoo = bench["zoo"]+ universe = bench["universe"]+ period = bench["period"]+ logger.info("=== bench %s: zoo=%s universe=%s period=%s ===", key, zoo, universe, period)+ start = time.monotonic()++ entry: dict = {+ "key": key,+ "zoo": zoo,+ "universe": universe,+ "period": period,+ "status": "pending",+ }++ # 1. HTML report (also exercises the universe loader so the panel is cached+ # on disk for the run_bench call below).+ try:+ envelope = run_alpha_bench(+ zoo=zoo, universe=universe, period=period, top=20+ )+ except Exception as exc: # noqa: BLE001 — never let one bench abort the suite+ logger.exception("bench %s crashed (run_alpha_bench)", key)+ entry["status"] = "error"+ entry["error"] = f"unexpected: {exc!s}"+ entry["wall_seconds"] = round(time.monotonic() - start, 2)+ return entry++ if envelope.get("status") != "ok":+ entry["status"] = "error"+ entry["error"] = envelope.get("error", "unknown")+ entry["wall_seconds"] = round(time.monotonic() - start, 2)+ return entry++ # 2. Full bench (per-alpha rows + categorisation).+ try:+ result = run_bench(zoo=zoo, universe=universe, period=period, top=20)+ except Exception as exc: # noqa: BLE001+ logger.exception("bench %s crashed (run_bench)", key)+ entry["status"] = "error"+ entry["error"] = f"unexpected: {exc!s}"+ entry["wall_seconds"] = round(time.monotonic() - start, 2)+ return entry++ if result.get("status") != "ok":+ entry["status"] = "error"+ entry["error"] = result.get("error", "unknown")+ entry["wall_seconds"] = round(time.monotonic() - start, 2)+ return entry++ rows = result.pop("rows", [])+ skipped = result.pop("skipped", [])++ entry.update(result)+ entry["report_path"] = envelope.get("report_path")+ entry["wall_seconds"] = round(time.monotonic() - start, 2)++ # Write per-bench raw rows for downstream tooling.+ raw_path = REPORTS_DIR / f"bench_{key}.json"+ raw_path.write_text(+ json.dumps(+ {"meta": {k: entry[k] for k in ("key", "zoo", "universe", "period", "status")},+ "rows": rows, "skipped": skipped},+ indent=2,+ default=str,+ ),+ encoding="utf-8",+ )++ logger.info(+ "bench %s done: tested=%d skipped=%d alive=%d reversed=%d dead=%d (%.1fs)",+ key, len(rows), len(skipped),+ entry["alive"], entry["reversed"], entry["dead"],+ entry["wall_seconds"],+ )+ return entry+++def main() -> int:+ REPORTS_DIR.mkdir(parents=True, exist_ok=True)+ summary: dict = {+ "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),+ "zoos": {},+ }++ tushare_ok = bool(os.getenv("TUSHARE_TOKEN", "").strip())+ if not tushare_ok:+ logger.warning("TUSHARE_TOKEN unset; csi300 benches will be skipped")++ for bench in BENCHES:+ if bench["universe"] == "csi300" and not tushare_ok:+ summary["zoos"][bench["key"]] = {+ **{k: bench[k] for k in ("zoo", "universe", "period")},+ "status": "skipped",+ "error": "TUSHARE_TOKEN not set",+ }+ continue+ entry = _run_one(bench)+ summary["zoos"][bench["key"]] = entry++ out = REPORTS_DIR / "bench_summary.json"+ out.write_text(json.dumps(summary, indent=2, default=str), encoding="utf-8")+ logger.info("wrote summary -> %s", out)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/agent/src/api/__init__.py b/agent/src/api/__init__.pynew file mode 100644index 000000000..79c384eb0--- /dev/null+++ b/agent/src/api/__init__.py@@ -0,0 +1 @@+"""HTTP route packages mounted onto the main FastAPI app in ``api_server.py``."""diff --git a/agent/src/api/alpha_routes.py b/agent/src/api/alpha_routes.pynew file mode 100644index 000000000..c1c5d40fd--- /dev/null+++ b/agent/src/api/alpha_routes.py@@ -0,0 +1,564 @@+"""Alpha Zoo HTTP routes for the Web UI.++Mounted by ``agent/api_server.py`` via ``register_alpha_routes(app, ...)``. Pulled+into its own module because ``api_server.py`` is already ~1800 lines.++Routes (auth via the caller-supplied ``require_auth`` /+``require_event_stream_auth`` dependencies):++- ``GET /alpha/list`` — list alphas with optional filters+- ``GET /alpha/{alpha_id}`` — single alpha meta + source+- ``POST /alpha/bench`` — kick off a background bench (returns job_id)+- ``GET /alpha/bench/{job_id}/stream`` — SSE: progress / result / done / error++Job state lives in the module-level ``ALPHA_BENCH_JOBS`` dict, guarded by+``_JOBS_LOCK``. No persistence — process restart wipes job state, which is+acceptable for v1 (a bench takes 5-10 min; users re-trigger).++Concurrency: at most ``MAX_CONCURRENT_BENCHES`` bench workers run at the same+time across the process. POST returns 429 when the cap is reached. Workers run+in a thread (``asyncio.to_thread``) and we hold task references in a module+set so the loop's garbage collector cannot cancel them mid-run.++Error surface: typed errors (``ValueError`` on bad period, ``KeyError`` on+unknown alpha_id) bubble out with their original message. Anything else is+logged with full traceback and reported to clients as ``"internal error; see+server logs"`` to avoid leaking stack frames / paths.+"""++from __future__ import annotations++import asyncio+import json+import logging+import re+import threading+import time+import uuid+from datetime import datetime, timezone+from typing import Any, Awaitable, Callable++from fastapi import Depends, FastAPI, HTTPException, Query, Request+from fastapi.responses import StreamingResponse+from pydantic import BaseModel, Field, field_validator++logger = logging.getLogger(__name__)++# ---------------------------------------------------------------------------+# Job store (in-memory, process-local)+# ---------------------------------------------------------------------------++ALPHA_BENCH_JOBS: dict[str, dict[str, Any]] = {}+_JOBS_LOCK = threading.Lock()++# Live background bench tasks. Holding strong refs prevents the asyncio GC from+# cancelling fire-and-forget tasks; ``add`` on create, ``discard`` on done.+_RUNNING_TASKS: set[asyncio.Task[Any]] = set()++_JOB_TTL_SECONDS = 60 * 60 # prune jobs older than 1 hour on each new POST+_POLL_INTERVAL_SECONDS = 0.5+_SSE_HEARTBEAT_SECONDS = 15.0++# Cap on simultaneous bench workers. A bench is pandas-heavy (5-10 min wall) so+# unbounded concurrency would DoS the server with two or three clicks. The+# semaphore is created lazily on the first request so we bind to the running+# event loop, not the import-time one.+MAX_CONCURRENT_BENCHES = 2+_BENCH_SEMAPHORE: asyncio.Semaphore | None = None+_BENCH_SEMAPHORE_LOCK = threading.Lock()+++def _get_bench_semaphore() -> asyncio.Semaphore:+ """Return the process-wide bench semaphore, building it on first call."""+ global _BENCH_SEMAPHORE+ with _BENCH_SEMAPHORE_LOCK:+ if _BENCH_SEMAPHORE is None:+ _BENCH_SEMAPHORE = asyncio.Semaphore(MAX_CONCURRENT_BENCHES)+ return _BENCH_SEMAPHORE+++# Tighter alpha_id pattern: ``<zoo>_<short>``. Zoo prefix is short (a-z + a-z0-9),+# short id is 1-64 of [a-z0-9_]. Caps avoid pathological lookups.+_ALPHA_ID_RE = re.compile(r"^[a-z][a-z0-9]+_[a-z0-9_]{1,64}$")+_JOB_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")++# Filter enums — keep in sync with src.factors.registry.Theme / Universe.+_VALID_ZOOS = {"alpha101", "gtja191", "qlib158", "academic"}+_VALID_THEMES = {+ "momentum", "reversal", "volume", "volatility", "quality", "value",+ "liquidity", "microstructure", "sentiment", "growth", "leverage",+}+_VALID_UNIVERSES = {"equity_us", "equity_cn", "equity_hk", "crypto", "futures"}+++def _now_iso() -> str:+ return datetime.now(timezone.utc).isoformat(timespec="seconds")+++def _safe_error(exc: BaseException) -> str:+ """Sanitised user-facing error string for unexpected exceptions.++ Always returns a fixed phrase — never echoes the exception message or+ type, both of which can include filesystem paths, credentials, or stack+ frame snippets. Callers should ``logger.exception`` BEFORE invoking this.+ """+ return "internal error; see server logs"+++def _prune_old_jobs() -> None:+ """Drop completed/errored jobs older than ``_JOB_TTL_SECONDS``."""+ cutoff = time.time() - _JOB_TTL_SECONDS+ with _JOBS_LOCK:+ stale = [+ jid for jid, job in ALPHA_BENCH_JOBS.items()+ if job.get("status") in ("done", "error")+ and job.get("_finished_at", 0) < cutoff+ ]+ for jid in stale:+ ALPHA_BENCH_JOBS.pop(jid, None)+++# ---------------------------------------------------------------------------+# Request/response schemas+# ---------------------------------------------------------------------------+++class BenchRequest(BaseModel):+ """POST /alpha/bench body."""++ zoo: str = Field(..., min_length=1, max_length=64)+ universe: str = Field(..., min_length=1, max_length=64)+ period: str = Field(..., min_length=4, max_length=32)+ top: int = Field(20, ge=1, le=500)++ @field_validator("zoo")+ @classmethod+ def _zoo_known(cls, v: str) -> str:+ if v not in _VALID_ZOOS:+ raise ValueError(+ f"unknown zoo {v!r}; expected one of {sorted(_VALID_ZOOS)}"+ )+ return v++ @field_validator("universe")+ @classmethod+ def _universe_known(cls, v: str) -> str:+ allowed = {"csi300", "sp500", "btc-usdt"}+ if v not in allowed:+ raise ValueError(+ f"unknown universe {v!r}; expected one of {sorted(allowed)}"+ )+ return v+++# ---------------------------------------------------------------------------+# Bench worker (runs in a thread; LLM-free, pandas-heavy)+# ---------------------------------------------------------------------------+++def _make_progress_cb(job_id: str) -> Callable[[int, int, str], None]:+ """Return an on_progress closure that updates the job entry in-place."""++ def _cb(n_done: int, n_total: int, alpha_id: str) -> None:+ with _JOBS_LOCK:+ job = ALPHA_BENCH_JOBS.get(job_id)+ if job is None:+ return+ job["progress"] = {+ "n_done": int(n_done),+ "n_total": int(n_total),+ "current_alpha_id": alpha_id,+ }+ if job["status"] == "queued":+ job["status"] = "running"++ return _cb+++def _run_bench_blocking(job_id: str, zoo: str, universe: str, period: str, top: int) -> None:+ """Synchronous bench worker (called via ``asyncio.to_thread``)."""+ from src.factors.bench_runner import run_bench # local import: heavy deps++ with _JOBS_LOCK:+ job = ALPHA_BENCH_JOBS.get(job_id)+ if job is not None:+ job["status"] = "running"++ try:+ result = run_bench(+ zoo=zoo,+ universe=universe,+ period=period,+ top=top,+ on_progress=_make_progress_cb(job_id),+ )+ except Exception as exc: # noqa: BLE001 — worker must never crash the loop+ logger.exception("alpha bench worker crashed (job=%s)", job_id)+ with _JOBS_LOCK:+ job = ALPHA_BENCH_JOBS.get(job_id)+ if job is not None:+ job["status"] = "error"+ job["error"] = _safe_error(exc)+ job["_finished_at"] = time.time()+ return++ with _JOBS_LOCK:+ job = ALPHA_BENCH_JOBS.get(job_id)+ if job is None:+ return+ if result.get("status") != "ok":+ job["status"] = "error"+ # bench_runner's own error string is curated (universe load failed,+ # forward returns failed, etc.) — safe to surface.+ job["error"] = result.get("error", "unknown")+ else:+ # Strip the bulky per-alpha lists — the API contract returns+ # summary-only on the result event. We keep ``n_skipped`` (the+ # count) which ``_result_for_wire`` reshapes into ``skipped``.+ slim = {+ k: v for k, v in result.items() if k not in ("rows", "skipped")+ }+ job["status"] = "done"+ job["result"] = slim+ job["_finished_at"] = time.time()+++# ---------------------------------------------------------------------------+# Registration+# ---------------------------------------------------------------------------++AuthDep = Callable[..., Awaitable[Any] | Any]+++def register_alpha_routes(+ app: FastAPI,+ require_auth: AuthDep | None = None,+ require_event_stream_auth: AuthDep | None = None,+) -> None:+ """Mount the alpha routes onto ``app``.++ Args:+ app: The host FastAPI app.+ require_auth: Header-auth dependency for JSON endpoints.+ require_event_stream_auth: Query-param-auth dependency for SSE endpoints.++ For backwards compatibility, when the dependency callables are not passed+ explicitly we resolve them from the host ``api_server`` module via+ ``sys.modules``. Prefer the explicit form in new call sites.+ """+ if require_auth is None or require_event_stream_auth is None:+ import sys as _sys++ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")+ if host is None: # pragma: no cover — only triggers on weird import setups+ raise RuntimeError(+ "register_alpha_routes: api_server module not in sys.modules; "+ "pass require_auth/require_event_stream_auth explicitly"+ )+ if require_auth is None:+ require_auth = host.require_auth+ if require_event_stream_auth is None:+ require_event_stream_auth = host.require_event_stream_auth++ # -----------------------------------------------------------------------+ # GET /alpha/list+ # -----------------------------------------------------------------------++ @app.get("/alpha/list", dependencies=[Depends(require_auth)])+ async def list_alphas(+ zoo: str | None = Query(None, max_length=64),+ theme: str | None = Query(None, max_length=64),+ universe: str | None = Query(None, max_length=64),+ limit: int = Query(100, ge=1, le=1000),+ ) -> dict[str, Any]:+ """List alphas, optionally filtered by zoo / theme / universe."""+ if zoo is not None and zoo not in _VALID_ZOOS:+ raise HTTPException(+ status_code=400,+ detail=f"unknown zoo {zoo!r}; expected one of {sorted(_VALID_ZOOS)}",+ )+ if theme is not None and theme not in _VALID_THEMES:+ raise HTTPException(+ status_code=400,+ detail=f"unknown theme {theme!r}; expected one of {sorted(_VALID_THEMES)}",+ )+ if universe is not None and universe not in _VALID_UNIVERSES:+ raise HTTPException(+ status_code=400,+ detail=f"unknown universe {universe!r}; expected one of {sorted(_VALID_UNIVERSES)}",+ )++ from src.factors.registry import get_default_registry++ registry = get_default_registry()+ try:+ ids = registry.list(zoo=zoo, theme=theme, universe=universe)+ except Exception as exc: # noqa: BLE001+ logger.exception("registry.list failed")+ raise HTTPException(status_code=500, detail=_safe_error(exc))++ total = len(ids)+ sliced = ids[:limit]+ alphas: list[dict[str, Any]] = []+ for aid in sliced:+ try:+ a = registry.get(aid)+ except KeyError:+ continue+ meta = a.meta or {}+ alphas.append(+ {+ "id": a.id,+ "zoo": a.zoo,+ "theme": meta.get("theme", []),+ "universe": meta.get("universe", []),+ "nickname": meta.get("nickname"),+ "decay_horizon": meta.get("decay_horizon"),+ "min_warmup_bars": meta.get("min_warmup_bars"),+ "requires_sector": bool(meta.get("requires_sector", False)),+ }+ )+ return {+ "status": "ok",+ "alphas": alphas,+ "total": total,+ "returned": len(alphas),+ "truncated": total > len(alphas),+ }++ # -----------------------------------------------------------------------+ # GET /alpha/{alpha_id}+ # -----------------------------------------------------------------------++ @app.get("/alpha/{alpha_id}", dependencies=[Depends(require_auth)])+ async def get_alpha(alpha_id: str) -> dict[str, Any]:+ """Return alpha metadata + the source code of its zoo .py file."""+ if not _ALPHA_ID_RE.fullmatch(alpha_id or ""):+ raise HTTPException(status_code=400, detail="invalid alpha_id")++ from src.factors.registry import RegistryError, get_default_registry++ registry = get_default_registry()+ try:+ alpha = registry.get(alpha_id)+ except KeyError:+ raise HTTPException(+ status_code=404,+ detail={"status": "error", "error": "alpha_id not found"},+ )++ try:+ source_code = registry.get_source(alpha_id)+ except RegistryError as exc:+ # Source-read failure is a degraded but recoverable case — log and+ # surface a short placeholder. The reason here is a typed registry+ # error (size cap or OS error from a known path), safe to expose.+ logger.warning("failed to read source for %s: %s", alpha_id, exc)+ source_code = f"# <source unavailable: {exc}>"++ return {+ "status": "ok",+ "alpha": {+ "id": alpha.id,+ "zoo": alpha.zoo,+ "module_path": alpha.module_path,+ "meta": alpha.meta,+ },+ "source_code": source_code,+ }++ # -----------------------------------------------------------------------+ # POST /alpha/bench+ # -----------------------------------------------------------------------++ @app.post(+ "/alpha/bench",+ status_code=202,+ dependencies=[Depends(require_auth)],+ )+ async def kick_off_bench(payload: BenchRequest) -> dict[str, Any]:+ """Queue a background bench job and return a job_id."""+ # Cheap period parse pre-check so we 400 here instead of letting the+ # worker fail asynchronously.+ from src.tools.alpha_bench_tool import _parse_period++ try:+ _parse_period(payload.period)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=f"invalid period: {exc}")++ # Concurrency cap. We peek at the semaphore counter rather than+ # ``acquire(block=False)`` so the actual acquire happens inside the+ # worker (after the 202 is returned). _value is a CPython+ # implementation detail but it's been stable since 3.0 and asyncio's+ # own ``locked()`` uses it.+ sem = _get_bench_semaphore()+ # ``locked()`` returns True iff the counter is 0; defensive check.+ if sem.locked() or getattr(sem, "_value", MAX_CONCURRENT_BENCHES) <= 0:+ raise HTTPException(+ status_code=429,+ detail="too many running benches; wait for one to finish",+ )++ _prune_old_jobs()++ job_id = uuid.uuid4().hex+ with _JOBS_LOCK:+ ALPHA_BENCH_JOBS[job_id] = {+ "job_id": job_id,+ "status": "queued",+ "zoo": payload.zoo,+ "universe": payload.universe,+ "period": payload.period,+ "top": payload.top,+ "created_at": _now_iso(),+ "progress": {"n_done": 0, "n_total": 0, "current_alpha_id": None},+ "result": None,+ "error": None,+ }++ async def _runner() -> None:+ async with sem:+ try:+ await asyncio.to_thread(+ _run_bench_blocking,+ job_id,+ payload.zoo,+ payload.universe,+ payload.period,+ payload.top,+ )+ except Exception: # noqa: BLE001 — never escape the loop+ logger.exception("bench runner outer task crashed (job=%s)", job_id)+ with _JOBS_LOCK:+ job = ALPHA_BENCH_JOBS.get(job_id)+ if job is not None and job["status"] not in ("done", "error"):+ job["status"] = "error"+ job["error"] = "internal error; see server logs"+ job["_finished_at"] = time.time()++ task = asyncio.create_task(_runner())+ _RUNNING_TASKS.add(task)+ task.add_done_callback(_RUNNING_TASKS.discard)+ return {"status": "ok", "job_id": job_id}++ # -----------------------------------------------------------------------+ # GET /alpha/bench/{job_id}/stream+ # -----------------------------------------------------------------------++ @app.get(+ "/alpha/bench/{job_id}/stream",+ dependencies=[Depends(require_event_stream_auth)],+ )+ async def stream_bench(job_id: str, request: Request) -> StreamingResponse:+ """SSE: progress / result / done / error until the job terminates."""+ if not _JOB_ID_RE.fullmatch(job_id or ""):+ raise HTTPException(status_code=400, detail="invalid job_id")++ with _JOBS_LOCK:+ if job_id not in ALPHA_BENCH_JOBS:+ raise HTTPException(status_code=404, detail=f"job {job_id} not found")++ async def event_stream():+ last_n_done = -1+ last_emit = time.monotonic()+ while True:+ if await request.is_disconnected():+ return++ with _JOBS_LOCK:+ job = ALPHA_BENCH_JOBS.get(job_id)+ if job is None:+ yield _sse("error", {"message": "job vanished"})+ yield _sse("done", {"job_id": job_id})+ return+ status = job["status"]+ progress = dict(job.get("progress") or {})+ result = job.get("result")+ error = job.get("error")++ # Emit progress whenever n_done advances.+ n_done = int(progress.get("n_done") or 0)+ if n_done != last_n_done:+ yield _sse("progress", progress)+ last_n_done = n_done+ last_emit = time.monotonic()++ if status == "done":+ if result is not None:+ yield _sse("result", _result_for_wire(result))+ yield _sse(+ "done",+ {+ "job_id": job_id,+ "wall_seconds": (result or {}).get("wall_seconds"),+ },+ )+ return+ if status == "error":+ yield _sse("error", {"message": error or "unknown error"})+ yield _sse("done", {"job_id": job_id})+ return++ # Heartbeat comment frame every ~15s — clients ignore comment+ # frames; proxies see traffic and don't kill the idle connection.+ if time.monotonic() - last_emit >= _SSE_HEARTBEAT_SECONDS:+ yield ": ping\n\n"+ last_emit = time.monotonic()++ await asyncio.sleep(_POLL_INTERVAL_SECONDS)++ return StreamingResponse(+ event_stream(),+ media_type="text/event-stream",+ headers={+ "Cache-Control": "no-cache",+ "Connection": "keep-alive",+ "X-Accel-Buffering": "no",+ },+ )+++# ---------------------------------------------------------------------------+# SSE helpers+# ---------------------------------------------------------------------------+++def _sse(event: str, data: dict[str, Any]) -> str:+ """Format a single SSE frame."""+ payload = json.dumps(data, ensure_ascii=False, default=str)+ return f"event: {event}\ndata: {payload}\n\n"+++def _result_for_wire(result: dict[str, Any]) -> dict[str, Any]:+ """Project the bench-runner result onto the API contract's `result` event.++ Keeps: alive / reversed / dead / skipped / n_alphas_tested / top5_by_ir /+ dead_examples / by_theme / meta. The frontend renders skipped count and+ surfaces universe meta (e.g. survivorship_bias) so users see degraded+ runs clearly.++ Drops anything internal (wall_seconds is reported on the `done` event;+ rows / per-alpha skipped[] are stripped server-side to keep payloads small).+ """+ wire: dict[str, Any] = {}+ keep = (+ "alive",+ "reversed",+ "dead",+ "top5_by_ir",+ "dead_examples",+ "by_theme",+ "n_alphas_tested",+ "meta",+ )+ for k in keep:+ if k in result:+ wire[k] = result[k]+ # bench_runner reports the skip count as ``n_skipped``; the wire contract+ # exposes it as ``skipped``. Surface both keys to stay backward-compatible+ # with any client that started reading ``n_skipped`` early.+ if "n_skipped" in result:+ wire["skipped"] = result["n_skipped"]+ wire["n_skipped"] = result["n_skipped"]+ return wirediff --git a/agent/src/factors/cli_handlers.py b/agent/src/factors/cli_handlers.pynew file mode 100644index 000000000..926b49fbc--- /dev/null+++ b/agent/src/factors/cli_handlers.py@@ -0,0 +1,909 @@+"""CLI handlers for ``vibe-trading alpha {list,show,bench,compare,export-manifest}``.++All logic lives here; ``agent/cli.py`` only wires this in via :func:`add_subparser`+and :func:`dispatch`. Handlers print to stdout (Rich when available, plain+``print`` fallback) and return an int exit code. Errors are reported as a+one-line stderr message; tracebacks are suppressed unless ``--verbose`` is set+on the namespace.++Security gates:+ * ``alpha show <id>`` validates ``id`` against ``Registry().list()`` before+ touching the filesystem.+ * ``alpha export-manifest --out PATH`` refuses to write outside the repo+ root (``Path(__file__).resolve().parents[3]``) unless ``--force``.+"""++from __future__ import annotations++import argparse+import json+import sys+import time+import traceback+import warnings+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Callable++# Silence the noisy ConstantInputWarning that scipy emits from spearmanr when+# the IC slice has zero variance (very common in alpha bench loops).+try:+ from scipy.stats import ConstantInputWarning # type: ignore[attr-defined]++ warnings.filterwarnings("ignore", category=ConstantInputWarning)+except Exception: # pragma: no cover — older scipy / unexpected layout+ try:+ from scipy.stats._warnings_errors import ( # type: ignore[attr-defined]+ ConstantInputWarning,+ )++ warnings.filterwarnings("ignore", category=ConstantInputWarning)+ except Exception:+ pass++try:+ from rich.console import Console+ from rich.progress import (+ BarColumn,+ Progress,+ SpinnerColumn,+ TextColumn,+ TimeElapsedColumn,+ )+ from rich.syntax import Syntax+ from rich.table import Table++ _console: Console | None = Console()+except Exception: # pragma: no cover — rich is a project dep, fallback only+ _console = None+ Syntax = None # type: ignore[assignment]+ Table = None # type: ignore[assignment]+ Progress = None # type: ignore[assignment]+ BarColumn = None # type: ignore[assignment]+ SpinnerColumn = None # type: ignore[assignment]+ TextColumn = None # type: ignore[assignment]+ TimeElapsedColumn = None # type: ignore[assignment]++from src.factors.registry import Registry, RegistryError+++# Resolve repo root once: this file lives at+# ``<repo>/agent/src/factors/cli_handlers.py``; parents[3] is the repo root.+# We treat ``<repo>`` (and any subdirectory thereof) as the write-allow root.+_REPO_ROOT = Path(__file__).resolve().parents[3]++_UNIVERSE_CHOICES = ["csi300", "sp500", "btc-usdt"]+++def _print(msg: str) -> None:+ if _console is not None:+ _console.print(msg)+ else:+ print(msg)+++def _err(msg: str) -> None:+ print(msg, file=sys.stderr)+++def _stdout_is_tty() -> bool:+ try:+ return sys.stdout.isatty()+ except Exception: # noqa: BLE001+ return False+++_stderr_console: Console | None = None+if _console is not None:+ try:+ _stderr_console = Console(stderr=True)+ except Exception: # noqa: BLE001+ _stderr_console = None+++def _hint(msg: str) -> None:+ """Print a next-step hint to stderr when stdout is a TTY.++ Goes to stderr so it does not pollute JSON / pipe-friendly stdout output.+ """+ if not _stdout_is_tty():+ return+ if _stderr_console is not None:+ _stderr_console.print(f"[dim]{msg}[/dim]")+ else:+ print(msg, file=sys.stderr)+++def _handle_exception(args: argparse.Namespace, prefix: str, exc: BaseException) -> int:+ """Print one-line error; emit traceback only when ``--verbose`` is set."""+ _err(f"{prefix}: {exc}")+ if getattr(args, "verbose", False):+ traceback.print_exception(type(exc), exc, exc.__traceback__)+ # Surface a helpful banner for the common TUSHARE_TOKEN error case.+ if "TUSHARE_TOKEN" in str(exc):+ _err("")+ _err("How to fix:")+ _err(" 1. Register for a free token at https://tushare.pro/register")+ _err(" 2. Add 'TUSHARE_TOKEN=<your_token>' to agent/.env (or ~/.vibe-trading/.env)")+ _err(" 3. Re-run this command")+ return 1+++# --------------------------------------------------------------------------- #+# Handlers #+# --------------------------------------------------------------------------- #+++def cmd_alpha_list(args: argparse.Namespace) -> int:+ """``vibe-trading alpha list [--zoo X] [--theme Y] [--universe Z]``.++ Supports ``--limit N`` (default 50) and ``--json`` for machine-readable+ output. ``--include-load-errors`` (alias: ``--show-failed``) appends a+ registry health block.+ """+ try:+ reg = Registry()+ ids = reg.list(zoo=args.zoo, theme=args.theme, universe=args.universe)++ limit = getattr(args, "limit", None)+ total = len(ids)+ truncated = False+ # limit > 0 => cap; limit == 0 / None => no cap.+ if isinstance(limit, int) and limit > 0 and total > limit:+ ids = ids[:limit]+ truncated = True++ # JSON mode: machine-readable, no Rich, no hints.+ if getattr(args, "json", False):+ records: list[dict[str, Any]] = []+ for alpha_id in ids:+ alpha = reg.get(alpha_id)+ meta = alpha.meta or {}+ records.append(+ {+ "id": alpha.id,+ "zoo": alpha.zoo,+ "theme": meta.get("theme", []) or [],+ "universe": meta.get("universe", []) or [],+ "decay_horizon": meta.get("decay_horizon"),+ }+ )+ print(json.dumps(records, indent=2, default=str))+ if _include_load_errors(args):+ _print_load_errors(reg)+ return 0++ if not ids:+ _print("[dim]no alphas matched the filters[/dim]" if _console else "no alphas matched the filters")+ elif _console is not None and Table is not None:+ title = f"Alpha Zoo ({len(ids)} of {total} alphas)" if truncated else f"Alpha Zoo ({total} alphas)"+ table = Table(title=title)+ table.add_column("id", style="cyan", no_wrap=True)+ table.add_column("zoo", style="magenta")+ table.add_column("theme")+ table.add_column("universe")+ table.add_column("nickname")+ for alpha_id in ids:+ alpha = reg.get(alpha_id)+ meta = alpha.meta+ table.add_row(+ alpha.id,+ alpha.zoo,+ ", ".join(meta.get("theme", []) or []),+ ", ".join(meta.get("universe", []) or []),+ meta.get("nickname") or "",+ )+ _console.print(table)+ if truncated:+ _print(f"[dim]Showing {len(ids)} of {total}. Pass --limit N (or --limit 0 for no cap).[/dim]")+ else:+ for alpha_id in ids:+ alpha = reg.get(alpha_id)+ meta = alpha.meta+ print(+ f"{alpha.id}\t{alpha.zoo}\t"+ f"{','.join(meta.get('theme', []) or [])}\t"+ f"{','.join(meta.get('universe', []) or [])}\t"+ f"{meta.get('nickname') or ''}"+ )+ if truncated:+ print(f"[showing {len(ids)} of {total}]")++ if _include_load_errors(args):+ _print_load_errors(reg)++ if ids:+ example_id = ids[0]+ example_zoo = reg.get(example_id).zoo+ _hint(+ f"Next: vibe-trading alpha show {example_id} | "+ f"Bench a zoo: vibe-trading alpha bench --zoo {example_zoo} "+ f"--universe csi300 --period 2020-2025"+ )+ return 0+ except Exception as exc: # noqa: BLE001+ return _handle_exception(args, "alpha list failed", exc)+++def _include_load_errors(args: argparse.Namespace) -> bool:+ """Honour both the new flag name and the deprecated alias."""+ return bool(getattr(args, "include_load_errors", False) or getattr(args, "show_failed", False))+++def _print_load_errors(reg: Registry) -> None:+ health = reg.health()+ errors = health.get("errors", [])+ if not errors:+ _print("[green]no load errors[/green]" if _console else "no load errors")+ return+ _print(+ f"[yellow]{len(errors)} load error(s):[/yellow]"+ if _console+ else f"{len(errors)} load error(s):"+ )+ for entry in errors:+ _print(f" - {entry.get('alpha_id')}: {entry.get('reason')}")+++def cmd_alpha_show(args: argparse.Namespace) -> int:+ """``vibe-trading alpha show <alpha_id> [--brief]`` — metadata + source."""+ try:+ reg = Registry()+ if args.alpha_id not in reg.list():+ _err(f"alpha id not found: {args.alpha_id}")+ return 1++ alpha = reg.get(args.alpha_id)+ meta = alpha.meta+ brief = bool(getattr(args, "brief", False))++ _print(f"[bold cyan]id[/bold cyan]: {alpha.id}" if _console else f"id: {alpha.id}")+ if not brief:+ _print(f"[bold]zoo[/bold]: {alpha.zoo}" if _console else f"zoo: {alpha.zoo}")+ _print(+ f"[bold]module_path[/bold]: {alpha.module_path}"+ if _console+ else f"module_path: {alpha.module_path}"+ )+ _print(+ f"[bold]nickname[/bold]: {meta.get('nickname') or '-'}"+ if _console+ else f"nickname: {meta.get('nickname') or '-'}"+ )+ _print(+ f"[bold]theme[/bold]: {', '.join(meta.get('theme', []) or [])}"+ if _console+ else f"theme: {', '.join(meta.get('theme', []) or [])}"+ )+ _print(+ f"[bold]universe[/bold]: {', '.join(meta.get('universe', []) or [])}"+ if _console+ else f"universe: {', '.join(meta.get('universe', []) or [])}"+ )+ if not brief:+ _print(+ f"[bold]columns_required[/bold]: {', '.join(meta.get('columns_required', []) or [])}"+ if _console+ else f"columns_required: {', '.join(meta.get('columns_required', []) or [])}"+ )+ _print(+ f"[bold]decay_horizon[/bold]: {meta.get('decay_horizon')}"+ if _console+ else f"decay_horizon: {meta.get('decay_horizon')}"+ )+ _print(+ f"[bold]formula_latex[/bold]: {meta.get('formula_latex', '')}"+ if _console+ else f"formula_latex: {meta.get('formula_latex', '')}"+ )+ notes = meta.get("notes") or ""+ if notes:+ _print(f"[bold]notes[/bold]: {notes}" if _console else f"notes: {notes}")++ if brief:+ _hint(+ f"Next: vibe-trading alpha bench --zoo {alpha.zoo} "+ f"--universe csi300 --period 2020-2025 --top 20"+ )+ return 0++ # Source code — read via the registry's _py_paths cache (semi-private but+ # accepted in the parcel contract; falls back to importlib.getsource).+ py_path: Path | None = reg._py_paths.get(alpha.id) # noqa: SLF001+ source: str | None = None+ if py_path is not None and py_path.is_file():+ try:+ source = py_path.read_text(encoding="utf-8")+ except OSError as exc:+ _err(f"warning: could not read source file {py_path}: {exc}")+ if source is None:+ try:+ import importlib+ import inspect++ module = importlib.import_module(alpha.module_path)+ source = inspect.getsource(module)+ except Exception as exc: # noqa: BLE001+ _err(f"warning: could not load source via importlib: {exc}")+ source = None++ if source:+ _print("[bold]source[/bold]:" if _console else "source:")+ if _console is not None and Syntax is not None:+ try:+ _console.print(+ Syntax(+ source,+ "python",+ line_numbers=True,+ theme="monokai",+ word_wrap=True,+ ),+ soft_wrap=True,+ )+ except Exception: # noqa: BLE001 — fall back to raw print+ print(source)+ else:+ print(source)++ _hint(+ f"Next: vibe-trading alpha bench --zoo {alpha.zoo} "+ f"--universe csi300 --period 2020-2025 --top 20"+ )+ return 0+ except Exception as exc: # noqa: BLE001+ return _handle_exception(args, "alpha show failed", exc)+++def _confirm_bench_all(n_total: int) -> bool:+ """Interactive y/N prompt before benching every alpha."""+ msg = f"About to bench {n_total} alphas (~10-15 min). Continue? [y/N] "+ try:+ reply = input(msg).strip().lower()+ except EOFError:+ return False+ return reply in {"y", "yes"}+++def _zoo_for_id(reg: Registry, alpha_id: str | None) -> str:+ """Lookup an alpha's zoo (best-effort, returns '' on failure)."""+ if not alpha_id:+ return ""+ try:+ return reg.get(alpha_id).zoo+ except Exception: # noqa: BLE001+ return ""+++def _run_single_zoo_with_progress(+ *,+ zoo: str,+ universe: str,+ period: str,+ top: int,+ n_target: int,+ reg: Registry,+ run_bench: Callable[..., dict[str, Any]],+) -> dict[str, Any]:+ """Run :func:`bench_runner.run_bench` for one zoo with a Rich progress bar."""+ if _console is None or Progress is None:+ return run_bench(+ zoo=zoo,+ universe=universe,+ period=period,+ top=top,+ registry=reg,+ )++ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ BarColumn(),+ TextColumn("{task.completed}/{task.total}"),+ TextColumn("[cyan]{task.fields[current]}[/cyan]"),+ TimeElapsedColumn(),+ console=_console,+ transient=False,+ ) as progress:+ task_id = progress.add_task(+ description="Benching",+ total=n_target,+ current="loading universe...",+ )++ def on_progress(n_done: int, n_total: int, aid: str) -> None:+ progress.update(task_id, completed=n_done, total=n_total, current=aid)++ return run_bench(+ zoo=zoo,+ universe=universe,+ period=period,+ top=top,+ on_progress=on_progress,+ registry=reg,+ )+++def _run_all_zoos_with_progress(+ *,+ target_ids: list[str],+ universe: str,+ period: str,+ top: int,+ start_ts: float,+ reg: Registry,+ run_bench: Callable[..., dict[str, Any]],+) -> dict[str, Any]:+ """Aggregate across every zoo for the ``--yes`` / no-``--zoo`` case."""+ zoos = sorted({reg.get(aid).zoo for aid in target_ids})+ total_alphas = sum(len(reg.list(zoo=z)) for z in zoos)+ all_rows: list[dict[str, Any]] = []+ all_skipped: list[dict[str, Any]] = []++ def _run_zoo(z: str, base: int, update: Callable[[int, str], None] | None) -> None:+ cb: Callable[[int, int, str], None] | None = None+ if update is not None:+ def cb(n_done: int, _n_total: int, aid: str) -> None:+ update(base + n_done, f"{z}:{aid}")+ sub = run_bench(+ zoo=z,+ universe=universe,+ period=period,+ top=top,+ on_progress=cb,+ registry=reg,+ )+ if sub.get("status") == "ok":+ all_rows.extend(sub.get("rows", []) or [])+ all_skipped.extend(sub.get("skipped", []) or [])+ else:+ all_skipped.append({"id": f"<zoo:{z}>", "reason": sub.get("error", "unknown")})++ if _console is not None and Progress is not None:+ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ BarColumn(),+ TextColumn("{task.completed}/{task.total}"),+ TextColumn("[cyan]{task.fields[current]}[/cyan]"),+ TimeElapsedColumn(),+ console=_console,+ transient=False,+ ) as progress:+ task_id = progress.add_task(+ description="Benching (all zoos)",+ total=total_alphas,+ current="starting...",+ )++ def update(done: int, current: str) -> None:+ progress.update(task_id, completed=done, current=current)++ seen = 0+ for z in zoos:+ _run_zoo(z, seen, update)+ seen += len(reg.list(zoo=z))+ else:+ for z in zoos:+ _run_zoo(z, 0, None)++ return {+ "status": "ok" if all_rows else "error",+ "zoo": "all",+ "universe": universe,+ "period": period,+ "rows": all_rows,+ "skipped": all_skipped,+ "n_alphas_tested": len(all_rows),+ "n_skipped": len(all_skipped),+ "wall_seconds": round(time.monotonic() - start_ts, 2),+ **({"error": "no alphas produced IC across any zoo"} if not all_rows else {}),+ }+++def cmd_alpha_bench(args: argparse.Namespace) -> int:+ """``vibe-trading alpha bench --zoo X --universe csi300 --period Y-Z [--top N]``.++ Calls :func:`src.factors.bench_runner.run_bench` for the IC loop so we can+ stream Rich progress, then renders the HTML report via helpers imported+ from ``src.tools.alpha_bench_tool`` (we do NOT modify that module).+ """+ try:+ try:+ from src.factors.bench_runner import run_bench+ except ImportError as exc:+ _err(f"alpha bench failed: bench_runner unavailable ({exc})")+ return 1++ # --- 1. Decide which zoo to run (handle no-args footgun) ----------- #+ zoo = args.zoo+ if zoo is None:+ reg = Registry()+ n_total = len(reg.list())+ if getattr(args, "yes", False):+ _print(+ f"[yellow]No --zoo passed; benching ALL {n_total} alphas "+ f"(confirmed via --yes).[/yellow]"+ if _console+ else f"No --zoo passed; benching ALL {n_total} alphas (--yes)."+ )+ else:+ _print(+ f"[yellow]Warning:[/yellow] no --zoo passed; this would bench "+ f"every registered alpha ({n_total} total)."+ if _console+ else f"Warning: no --zoo passed; this would bench every alpha ({n_total})."+ )+ if not _confirm_bench_all(n_total):+ _err("alpha bench: aborted (pass --zoo <id> or --yes to confirm).")+ return 1++ # --- 2. Pre-flight banner: counts + ETA ---------------------------- #+ reg = Registry()+ if zoo is not None:+ target_ids = reg.list(zoo=zoo)+ else:+ target_ids = reg.list()+ n_target = len(target_ids)+ if n_target == 0:+ _err(f"alpha bench failed: no alphas registered under zoo={zoo!r}")+ return 1++ _print(+ f"[bold]Bench:[/bold] {n_target} alphas x {args.universe} x {args.period}"+ if _console+ else f"Bench: {n_target} alphas x {args.universe} x {args.period}"+ )+ _print(+ "[dim]ETA: ~3-5 min (cache hit) / ~10-20 min (cold fetch)[/dim]"+ if _console+ else "ETA: ~3-5 min (cache hit) / ~10-20 min (cold fetch)"+ )++ # --- 3. Run the bench loop with a live progress bar --------------- #+ start_ts = time.monotonic()+ result: dict[str, Any]++ if zoo is not None:+ # Single-zoo path: one call to bench_runner.run_bench.+ result = _run_single_zoo_with_progress(+ zoo=zoo,+ universe=args.universe,+ period=args.period,+ top=args.top,+ n_target=n_target,+ reg=reg,+ run_bench=run_bench,+ )+ else:+ # Multi-zoo path: aggregate across every zoo (bench_runner requires+ # a non-empty zoo, so we loop per zoo and merge).+ result = _run_all_zoos_with_progress(+ target_ids=target_ids,+ universe=args.universe,+ period=args.period,+ top=args.top,+ start_ts=start_ts,+ reg=reg,+ run_bench=run_bench,+ )++ # --- 5. Handle bench-loop errors / propagate exit code ------------- #+ status = result.get("status")+ if status != "ok":+ err_msg = result.get("error", "unknown error")+ envelope = {+ "status": "error",+ "error": err_msg,+ "zoo": zoo,+ "universe": args.universe,+ "period": args.period,+ }+ print(json.dumps(envelope, indent=2, default=str))+ _err(f"alpha bench failed: {err_msg}")+ if "TUSHARE_TOKEN" in str(err_msg):+ _err("")+ _err("How to fix:")+ _err(" 1. Register for a free token at https://tushare.pro/register")+ _err(" 2. Add 'TUSHARE_TOKEN=<your_token>' to agent/.env (or ~/.vibe-trading/.env)")+ _err(" 3. Re-run this command")+ return 1++ # --- 6. Render HTML report (delegating to alpha_bench_tool helpers) -#+ rows = result.get("rows", []) or []+ skipped = result.get("skipped", []) or []+ top_n = max(1, int(args.top))+ rows_sorted = sorted(rows, key=lambda r: r.get("ir", 0.0), reverse=True)+ top_rows_raw = rows_sorted[:top_n]++ # Normalise rows + skipped for the report template (and for the JSON+ # envelope so consumers don't see the internal _category key).+ def _normalise_row(r: dict[str, Any]) -> dict[str, Any]:+ return {+ "id": r.get("id"),+ "zoo": r.get("zoo") or _zoo_for_id(reg, r.get("id")),+ "theme": r.get("theme") or [],+ "formula_latex": r.get("formula_latex", ""),+ "ic_mean": r.get("ic_mean", 0.0),+ "ic_std": r.get("ic_std", 0.0),+ "ir": r.get("ir", 0.0),+ "ic_positive_ratio": r.get("ic_positive_ratio", 0.0),+ "ic_count": r.get("ic_count", 0),+ "category": r.get("_category") or r.get("category"),+ }++ def _normalise_skipped(s: dict[str, Any]) -> dict[str, Any]:+ return {"alpha_id": s.get("id") or s.get("alpha_id"), "reason": s.get("reason", "")}++ top_rows = [_normalise_row(r) for r in top_rows_raw]+ failures_for_report = [_normalise_skipped(s) for s in skipped[:10]]++ report_path: Path | None = None+ try:+ from src.tools.alpha_bench_tool import ( # type: ignore[import-not-found]+ _CSP,+ _REPORT_CSS,+ _default_output_dir,+ _render_html,+ )++ output_dir = _default_output_dir()+ output_dir.mkdir(parents=True, exist_ok=True)+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")+ report_path = output_dir / f"alpha_bench_{ts}.html"+ context = {+ "csp": _CSP,+ "css": _REPORT_CSS,+ "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),+ "universe": args.universe,+ "period": args.period,+ "n_alphas_tested": len(rows),+ "n_skipped": len(skipped),+ "top": top_rows,+ "failures": failures_for_report,+ }+ report_path.write_text(_render_html(context), encoding="utf-8")+ except Exception as exc: # noqa: BLE001 — report is nice-to-have+ _err(f"warning: could not write HTML report: {exc}")+ report_path = None++ envelope: dict[str, Any] = {+ "status": "ok",+ "zoo": zoo,+ "universe": args.universe,+ "period": args.period,+ "n_alphas_tested": len(rows),+ "n_skipped": len(skipped),+ "top": top_rows,+ "wall_seconds": result.get("wall_seconds"),+ }+ if report_path is not None:+ envelope["report_path"] = str(report_path)+ print(json.dumps(envelope, indent=2, default=str))++ # Final stderr success line (M4).+ tested = len(rows)+ skipped_n = len(skipped)+ summary = f"✓ Bench complete. {tested} tested, {skipped_n} skipped."+ if report_path is not None:+ summary += f" Report: {report_path}"+ if _stderr_console is not None:+ _stderr_console.print(summary, style="green")+ else:+ print(summary, file=sys.stderr)+ return 0+ except Exception as exc: # noqa: BLE001+ return _handle_exception(args, "alpha bench failed", exc)+++def cmd_alpha_compare(args: argparse.Namespace) -> int:+ """``vibe-trading alpha compare <id1> [<id2> ...] | --all | --zoo X``.++ Stub for W4; reports validated targets so callers can wire scripts.+ """+ try:+ targets: list[str]+ reg = Registry()+ if getattr(args, "compare_all", False):+ targets = reg.list()+ elif args.zoo:+ targets = reg.list(zoo=args.zoo)+ else:+ targets = list(args.alpha_ids or [])++ if not targets:+ _err(+ "alpha compare: no targets supplied "+ "(pass alpha ids, or --all for every alpha, or --zoo X to filter)"+ )+ return 1++ _print(f"compare targets ({len(targets)}): {', '.join(targets)}")+ _print(+ "[yellow]alpha compare not yet implemented (W4)[/yellow]"+ if _console+ else "alpha compare not yet implemented (W4)"+ )+ print(json.dumps({"status": "stub", "targets": targets, "reason": "W4 not implemented"}, indent=2))+ return 0+ except Exception as exc: # noqa: BLE001+ return _handle_exception(args, "alpha compare failed", exc)+++def cmd_alpha_export_manifest(args: argparse.Namespace) -> int:+ """``vibe-trading alpha export-manifest --out PATH [--force]``."""+ try:+ out_path = Path(args.out).resolve()++ # Refuse to write outside the repo root unless --force.+ try:+ out_path.relative_to(_REPO_ROOT)+ inside_repo = True+ except ValueError:+ inside_repo = False+ if not inside_repo and not args.force:+ _err(+ f"alpha export-manifest: refusing to write outside repo root "+ f"({_REPO_ROOT}); pass --force to override. target={out_path}"+ )+ return 1++ parent = out_path.parent+ if not parent.exists():+ parent.mkdir(parents=True, exist_ok=True)++ reg = Registry()+ manifest = reg.export_manifest()+ out_path.write_text(json.dumps(manifest, indent=2, default=str), encoding="utf-8")+ _print(+ f"[green]wrote manifest[/green] ({manifest['health']['loaded']} alphas, "+ f"{manifest['health']['failed']} errors) -> {out_path}"+ if _console+ else f"wrote manifest ({manifest['health']['loaded']} alphas, "+ f"{manifest['health']['failed']} errors) -> {out_path}"+ )+ return 0+ except (RegistryError, OSError) as exc:+ return _handle_exception(args, "alpha export-manifest failed", exc)+ except Exception as exc: # noqa: BLE001+ return _handle_exception(args, "alpha export-manifest failed", exc)+++# --------------------------------------------------------------------------- #+# Subparser + dispatch wiring #+# --------------------------------------------------------------------------- #+++_DISPATCH: dict[str, Callable[[argparse.Namespace], int]] = {+ "list": cmd_alpha_list,+ "show": cmd_alpha_show,+ "bench": cmd_alpha_bench,+ "compare": cmd_alpha_compare,+ "export-manifest": cmd_alpha_export_manifest,+}+++# Module-level handle to the alpha parser so ``dispatch`` can print full help+# when no subcommand is supplied (M6).+_ALPHA_PARSER: argparse.ArgumentParser | None = None+++def add_subparser(subparsers: Any) -> argparse.ArgumentParser:+ """Register ``alpha`` and its five sub-sub-commands on the given subparsers.++ Args:+ subparsers: The object returned by ``ArgumentParser.add_subparsers(...)``.++ Returns:+ The ``alpha`` parser (mostly for test introspection).+ """+ global _ALPHA_PARSER++ alpha_parser = subparsers.add_parser(+ "alpha", help="Alpha Zoo: list / show / bench / compare / export-manifest"+ )+ alpha_parser.add_argument(+ "--verbose", action="store_true", help="Show full traceback on errors"+ )+ alpha_sub = alpha_parser.add_subparsers(dest="alpha_command")++ p_list = alpha_sub.add_parser("list", help="List registered alphas")+ p_list.add_argument("--zoo", default=None, help="Filter by zoo (e.g. alpha101)")+ p_list.add_argument("--theme", default=None, help="Filter by theme (e.g. momentum)")+ p_list.add_argument(+ "--universe",+ default=None,+ choices=_UNIVERSE_CHOICES,+ help=f"Filter by universe ({', '.join(_UNIVERSE_CHOICES)})",+ )+ p_list.add_argument(+ "--limit",+ type=int,+ default=50,+ help="Max alphas to print (default: 50; pass 0 for no cap)",+ )+ p_list.add_argument(+ "--json",+ action="store_true",+ help="Emit JSON array of {id, zoo, theme, universe, decay_horizon} instead of a table",+ )+ p_list.add_argument(+ "--include-load-errors",+ dest="include_load_errors",+ action="store_true",+ help="Also print load errors from registry.health()",+ )+ p_list.add_argument(+ "--show-failed",+ dest="show_failed",+ action="store_true",+ help="(deprecated) alias for --include-load-errors",+ )++ p_show = alpha_sub.add_parser("show", help="Show alpha metadata and source code")+ p_show.add_argument("alpha_id", help="Alpha id, e.g. alpha101_001")+ p_show.add_argument(+ "--brief",+ action="store_true",+ help="Print only id/theme/universe/formula_latex/notes — omit source code",+ )++ p_bench = alpha_sub.add_parser("bench", help="Benchmark alphas in a zoo")+ p_bench.add_argument("--zoo", default=None, help="Zoo to benchmark (required unless --yes is passed)")+ p_bench.add_argument(+ "--universe",+ default="csi300",+ choices=_UNIVERSE_CHOICES,+ help=f"Universe (default: csi300; one of {', '.join(_UNIVERSE_CHOICES)})",+ )+ p_bench.add_argument(+ "--period",+ default="2020-2025",+ help="Period spec: YYYY-YYYY or YYYY-MM-DD/YYYY-MM-DD (e.g. 2020-2025)",+ )+ p_bench.add_argument("--top", type=int, default=20, help="Top-N alphas to keep (default: 20)")+ p_bench.add_argument(+ "--yes",+ action="store_true",+ help="Skip the 'bench every alpha?' prompt when --zoo is omitted",+ )++ p_compare = alpha_sub.add_parser("compare", help="Compare alphas (W4 stub)")+ p_compare.add_argument("alpha_ids", nargs="*", help="Alpha ids to compare")+ p_compare.add_argument(+ "--all",+ dest="compare_all",+ action="store_true",+ help="Compare every alpha in the registry",+ )+ p_compare.add_argument(+ "--zoo",+ default=None,+ help="Filter comparison to one zoo (e.g. alpha101)",+ )++ p_export = alpha_sub.add_parser("export-manifest", help="Export registry manifest as JSON")+ p_export.add_argument("--out", required=True, help="Output JSON path")+ p_export.add_argument("--force", action="store_true", help="Allow writing outside the repo root")++ _ALPHA_PARSER = alpha_parser+ return alpha_parser+++def dispatch(args: argparse.Namespace) -> int:+ """Dispatch ``alpha <sub>`` to the matching handler.++ Returns the exit code; ``cli.py`` propagates it via ``_coerce_exit_code``.+ """+ sub = getattr(args, "alpha_command", None)+ if sub is None:+ if _ALPHA_PARSER is not None:+ _ALPHA_PARSER.print_help()+ else:+ _err("alpha requires a subcommand. Try: vibe-trading alpha list")+ return 1+ handler = _DISPATCH.get(sub)+ if handler is None:+ _err(f"alpha: unknown subcommand {sub!r}")+ return 1+ return handler(args)diff --git a/agent/src/tools/alpha_bench_tool.py b/agent/src/tools/alpha_bench_tool.pynew file mode 100644index 000000000..79f366bb2--- /dev/null+++ b/agent/src/tools/alpha_bench_tool.py@@ -0,0 +1,846 @@+"""Alpha bench orchestrator: registry → universe panel → IC/IR → HTML report.++W2 scaffold: implements the orchestration shape and HTML rendering. Universe+loaders that need network calls return a clean "not yet implemented" envelope —+the full universe wiring lands in W4. The HTML path is autoescaped via Jinja2,+with manual ``html.escape`` fallback when Jinja2 is absent, plus a strict CSP+``<meta>`` so the report cannot fetch or execute external resources.++Output contract — JSON envelope:+ {"status": "ok"|"error",+ "report_path": str | None,+ "n_alphas_tested": int,+ "n_skipped": int,+ "top": [{"id": ..., "ic_mean": ..., "ir": ..., ...}, ...]}++Cache integrity note: the universe panel cache lives in ``~/.vibe-trading/cache/``+as pickle blobs. Each pickle is paired with a ``<name>.sha256`` sidecar; on+load we recompute the digest and refuse the cache on mismatch. This guards+against accidental corruption (truncated writes, partial syncs) — it is NOT a+defence against an attacker with local write access (they can rewrite both+files). Cache files are user-local; if shared across machines they can be+tampered with and the sha256 sidecar is only an integrity check, not authenticity.+"""++from __future__ import annotations++import hashlib+import html+import json+import logging+import os+import re+from concurrent.futures import ThreadPoolExecutor, as_completed+from datetime import datetime, timezone+from pathlib import Path+from typing import Any++import numpy as np+import pandas as pd++from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Date the SP500 constituent list was sampled from Wikipedia (best-effort label+# for the survivorship-bias warning in the bench summary's ``meta`` block).+_SP500_CONSTITUENT_SOURCE_DATE = "2026-05-17"++# Concurrent Tushare ``pro.daily`` fetches when building CSI300. Free tier+# allows ~200 calls/min; 4 workers stays well under that with a 300-name list.+_CSI300_FETCH_WORKERS = 4+++# ---------------------------------------------------------------------------+# Universe + period parsing+# ---------------------------------------------------------------------------++_PERIOD_YEAR = re.compile(r"^(\d{4})-(\d{4})$")+_PERIOD_DATE = re.compile(r"^(\d{4}-\d{2}-\d{2})/(\d{4}-\d{2}-\d{2})$")++# Universe → (market_key, universe_meta_tag). Only the listed universes have a+# defined contract; everything else returns "not yet implemented".+_UNIVERSE_TAG = {+ "csi300": "equity_cn",+ "sp500": "equity_us",+ "btc-usdt": "crypto",+}+++def _parse_period(period: str) -> tuple[str, str]:+ """Return (start_date, end_date) as YYYY-MM-DD strings."""+ if not isinstance(period, str):+ raise ValueError(f"period must be string, got {type(period).__name__}")+ m = _PERIOD_DATE.match(period)+ if m:+ return m.group(1), m.group(2)+ m = _PERIOD_YEAR.match(period)+ if m:+ return f"{m.group(1)}-01-01", f"{m.group(2)}-12-31"+ raise ValueError(+ f"period {period!r} must be YYYY-YYYY or YYYY-MM-DD/YYYY-MM-DD"+ )+++def _load_universe_panel(+ universe: str, period: str, *, use_cache: bool = True+) -> dict[str, pd.DataFrame]:+ """Load OHLCV(+amount, +vwap) wide panel for the requested universe.++ Returns a dict keyed by panel column (open/high/low/close/volume/amount/vwap)+ where each value is a wide ``pd.DataFrame`` indexed by date (DatetimeIndex)+ with one column per instrument.++ Args:+ universe: ``csi300`` | ``sp500`` | ``btc-usdt``.+ period: ``YYYY-YYYY`` or ``YYYY-MM-DD/YYYY-MM-DD``.+ use_cache: When True (default) reuse a pickle in+ ``~/.vibe-trading/cache/`` if the same universe+period was fetched+ before. Set to False to force a re-fetch.++ Raises:+ ValueError: unknown universe or bad period.+ RuntimeError: ``TUSHARE_TOKEN`` unset when csi300 is requested.+ """+ if universe not in _UNIVERSE_TAG:+ raise ValueError(+ f"universe {universe!r} not recognized; expected one of {sorted(_UNIVERSE_TAG)}"+ )+ start, end = _parse_period(period)++ cache_dir = Path.home() / ".vibe-trading" / "cache"+ cache_path = cache_dir / f"{universe}_{start}_{end}.pkl"+ if use_cache and cache_path.is_file():+ cached = _read_pickle_cache(cache_path)+ if cached is not None:+ logger.info("universe %s: loaded from cache %s", universe, cache_path)+ return cached++ if universe == "csi300":+ panel = _load_csi300_panel(start, end)+ elif universe == "sp500":+ panel = _load_sp500_panel(start, end)+ elif universe == "btc-usdt":+ panel = _load_btc_panel(start, end)+ else: # pragma: no cover — guarded above+ raise ValueError(f"unhandled universe {universe!r}")++ if not panel or "close" not in panel or panel["close"].empty:+ raise RuntimeError(+ f"universe {universe!r} produced empty panel for {start}..{end}; "+ "check network / token / date range"+ )++ # btc-usdt loader returns a single-column close (one instrument). Cross-+ # sectional IC needs >= 2 instruments — short-circuit with a clean error+ # that propagates to API (400) and CLI.+ close_df = panel["close"]+ if universe == "btc-usdt" and close_df.shape[1] < 2:+ raise ValueError(+ "btc-usdt is single-asset; cross-sectional IC needs >=2 instruments. "+ "Use a multi-symbol crypto basket (e.g. multiple OKX pairs) for "+ "meaningful results."+ )++ if use_cache:+ _write_pickle_cache(cache_dir, cache_path, panel)++ return panel+++def _sha256_path(cache_path: Path) -> Path:+ return cache_path.with_suffix(cache_path.suffix + ".sha256")+++def _read_pickle_cache(cache_path: Path) -> dict[str, pd.DataFrame] | None:+ """Load a pickle cache, validating its sha256 sidecar. None on any failure."""+ import pickle++ sidecar = _sha256_path(cache_path)+ try:+ blob = cache_path.read_bytes()+ except OSError as exc:+ logger.warning("cache read failed (%s); refetching", exc)+ return None++ if not sidecar.is_file():+ logger.warning(+ "cache sidecar %s missing; refusing stale cache and refetching",+ sidecar.name,+ )+ return None+ try:+ expected = sidecar.read_text(encoding="utf-8").strip()+ except OSError as exc:+ logger.warning("cache sidecar read failed (%s); refetching", exc)+ return None+ actual = hashlib.sha256(blob).hexdigest()+ if not _hashes_equal(expected, actual):+ logger.warning(+ "cache integrity mismatch for %s (expected %s..., got %s...); refetching",+ cache_path.name, expected[:12], actual[:12],+ )+ return None++ try:+ cached = pickle.loads(blob) # noqa: S301 — local cache, integrity-checked above+ except Exception as exc: # noqa: BLE001 — degrade to fresh fetch+ logger.warning("cache unpickle failed (%s); refetching", exc)+ return None+ if not isinstance(cached, dict) or "close" not in cached:+ logger.warning("cache %s has unexpected shape; refetching", cache_path.name)+ return None+ return cached+++def _write_pickle_cache(+ cache_dir: Path, cache_path: Path, panel: dict[str, Any]+) -> None:+ """Pickle ``panel`` + write its sha256 sidecar. Failures are non-fatal."""+ import pickle++ try:+ cache_dir.mkdir(parents=True, exist_ok=True)+ blob = pickle.dumps(panel, protocol=pickle.HIGHEST_PROTOCOL)+ cache_path.write_bytes(blob)+ _sha256_path(cache_path).write_text(+ hashlib.sha256(blob).hexdigest(), encoding="utf-8"+ )+ except Exception as exc: # noqa: BLE001 — cache miss is non-fatal+ logger.warning("cache write failed: %s", exc)+++def _hashes_equal(a: str, b: str) -> bool:+ """Constant-time comparison of two hex digests."""+ import hmac++ return hmac.compare_digest(a.strip().lower(), b.strip().lower())+++# ---------------------------------------------------------------------------+# Universe loaders+# ---------------------------------------------------------------------------+++_CSI300_FALLBACK_CODES = [+ # Blue-chip A-share representatives — used only when index_weight fails.+ # Hand-picked across sectors so a degraded run still gives diverse signal.+ "600519.SH", "601318.SH", "600036.SH", "000333.SZ", "000858.SZ",+ "601166.SH", "600276.SH", "601398.SH", "601288.SH", "600030.SH",+ "600887.SH", "601012.SH", "601888.SH", "000651.SZ", "600028.SH",+ "601628.SH", "600000.SH", "601088.SH", "601857.SH", "600009.SH",+ "601899.SH", "002594.SZ", "600585.SH", "300750.SZ", "601658.SH",+ "600048.SH", "601138.SH", "601668.SH", "000001.SZ", "000002.SZ",+]+++# Hand-picked US large-cap representatives. Used when Wikipedia fetch fails.+_SP500_FALLBACK_CODES = [+ "AAPL", "MSFT", "NVDA", "GOOGL", "AMZN", "META", "TSLA", "BRK-B",+ "JPM", "JNJ", "V", "PG", "UNH", "MA", "HD", "XOM", "LLY", "MRK",+ "PEP", "KO", "ABBV", "AVGO", "CVX", "WMT", "COST", "ADBE", "MCD",+ "CRM", "ACN", "BAC", "TMO", "ORCL", "CSCO", "ABT", "WFC", "DHR",+ "VZ", "PFE", "INTC", "DIS", "CMCSA", "AMD", "TXN", "PM", "QCOM",+ "NEE", "RTX", "HON", "T", "IBM",+]+++def _load_csi300_panel(start: str, end: str) -> dict[str, pd.DataFrame]:+ """CSI 300 panel via Tushare. Includes ``amount`` (required by gtja191).++ Constituents are taken from the most recent ``index_weight`` snapshot in+ the requested window; if that call fails we degrade to a 30-name+ blue-chip fallback so the bench still runs.+ """+ token = os.getenv("TUSHARE_TOKEN", "").strip()+ if not token or token == "your-tushare-token":+ raise RuntimeError(+ "TUSHARE_TOKEN not in agent/.env or environment; required for csi300 universe"+ )++ try:+ import tushare as ts+ except ImportError as exc:+ raise RuntimeError(f"tushare not installed: {exc}") from exc++ pro = ts.pro_api(token)+ sd = start.replace("-", "")+ ed = end.replace("-", "")++ codes: list[str] = []+ try:+ weights = pro.index_weight(+ index_code="399300.SZ", start_date=sd, end_date=ed+ )+ if weights is not None and not weights.empty:+ latest_date = weights["trade_date"].max()+ codes = (+ weights[weights["trade_date"] == latest_date]["con_code"]+ .drop_duplicates()+ .tolist()+ )+ logger.info("csi300: %d constituents from index_weight @ %s", len(codes), latest_date)+ except Exception as exc: # noqa: BLE001+ logger.warning("csi300 index_weight failed (%s); using fallback list", exc)++ if not codes:+ codes = list(_CSI300_FALLBACK_CODES)+ logger.warning("csi300: using %d-name fallback (degraded run)", len(codes))++ # Fetch raw daily in parallel — we need ``amount`` which the standard+ # loader drops. Tushare's free tier permits ~200 calls/min so 4 concurrent+ # workers is comfortably under the rate limit even for a full 300-name list.+ def _fetch_one(code: str) -> tuple[str, pd.DataFrame | None]:+ df = _retry(lambda: pro.daily(ts_code=code, start_date=sd, end_date=ed))+ if df is None or df.empty:+ return code, None+ df = df.sort_values("trade_date").copy()+ df["trade_date"] = pd.to_datetime(df["trade_date"])+ df = df.set_index("trade_date")+ df = df.rename(columns={"vol": "volume"})+ for col in ("open", "high", "low", "close", "volume", "amount"):+ if col in df.columns:+ df[col] = pd.to_numeric(df[col], errors="coerce")+ keep = [c for c in ("open", "high", "low", "close", "volume", "amount") if c in df.columns]+ return code, df[keep].dropna(subset=["open", "high", "low", "close"])++ fetched: dict[str, pd.DataFrame] = {}+ with ThreadPoolExecutor(max_workers=_CSI300_FETCH_WORKERS) as pool:+ futures = [pool.submit(_fetch_one, code) for code in codes]+ for fut in as_completed(futures):+ try:+ code, frame = fut.result()+ except Exception as exc: # noqa: BLE001 — _retry already logged+ logger.warning("csi300 fetch worker raised: %s", exc)+ continue+ if frame is not None and not frame.empty:+ fetched[code] = frame++ panel = _wide_from_fetched(fetched, include_amount=True)+ # CN equity vwap: Tushare ``amount`` is in 千元, ``volume`` in 手. True VWAP+ # = (amount * 1000 CNY) / (volume * 100 shares). Matches+ # ``src.factors.base.vwap(EQUITY_CN)``.+ if "amount" in panel and "volume" in panel:+ from src.factors.base import safe_div++ panel["vwap"] = safe_div(+ panel["amount"] * 1000.0, panel["volume"] * 100.0 + 1.0+ )+ return panel+++def _load_sp500_panel(start: str, end: str) -> dict[str, pd.DataFrame]:+ """SP500 panel via yfinance. Adds vwap = (O+H+L+C)/4 fallback for alpha101.++ Survivorship-bias warning: ``_fetch_sp500_constituents`` returns Wikipedia's+ *current* member list, not a point-in-time snapshot. Names that dropped out+ of the index during ``start..end`` (delistings, mergers, downgrades) are+ silently excluded — so IC stats are biased upward. The caller (bench+ runner) surfaces this in the bench summary's ``meta`` block via the+ ``_meta`` panel key set below.+ """+ codes = _fetch_sp500_constituents()+ constituent_source = "wikipedia"+ if not codes:+ codes = list(_SP500_FALLBACK_CODES)+ constituent_source = "hand-picked fallback"+ logger.warning("sp500: using %d-name fallback (degraded run)", len(codes))++ logger.warning(+ "SP500 universe uses current constituents (%s @ %s) → survivorship-biased",+ constituent_source, _SP500_CONSTITUENT_SOURCE_DATE,+ )++ # yfinance loader expects project-style symbols (``AAPL.US``).+ project_codes = [f"{c}.US" for c in codes]+ from backtest.loaders.registry import resolve_loader++ loader = resolve_loader("us_equity")+ fetched = _retry(lambda: loader.fetch(project_codes, start, end)) or {}++ panel = _wide_from_fetched(fetched, include_amount=False)+ # Synthetic vwap for alpha101 alphas that require it on US universe+ if all(k in panel for k in ("open", "high", "low", "close")):+ panel["vwap"] = (panel["open"] + panel["high"] + panel["low"] + panel["close"]) / 4.0++ # Attach a non-DataFrame metadata blob. Registry.compute() only iterates+ # required column names, so this extra key is ignored by the compute path.+ panel["_meta"] = {+ "universe": "sp500",+ "survivorship_bias": True,+ "constituent_source": constituent_source,+ "constituent_source_date": _SP500_CONSTITUENT_SOURCE_DATE,+ "constituent_count": len(codes),+ }+ return panel+++def _fetch_sp500_constituents() -> list[str]:+ """Pull current S&P 500 tickers from Wikipedia. Returns [] on any failure."""+ url = "https://en.wikipedia.org/wiki/List_of_S%26P_500_companies"+ try:+ import io++ import requests++ resp = requests.get(+ url,+ headers={+ "User-Agent": (+ "Vibe-Trading/0.1 (research bench; "+ "https://github.com/HKUDS/Vibe-Trading)"+ )+ },+ timeout=20,+ )+ resp.raise_for_status()+ tables = pd.read_html(io.StringIO(resp.text))+ for tbl in tables:+ if "Symbol" in tbl.columns:+ tickers = tbl["Symbol"].astype(str).str.strip().tolist()+ # yfinance prefers ``BRK-B`` over ``BRK.B`` — normalise+ tickers = [t.replace(".", "-") for t in tickers if t and t != "nan"]+ logger.info("sp500: %d tickers from Wikipedia", len(tickers))+ return tickers+ except Exception as exc: # noqa: BLE001+ logger.warning("sp500 Wikipedia fetch failed: %s", exc)+ return []+++def _load_btc_panel(start: str, end: str) -> dict[str, pd.DataFrame]:+ """Single-instrument BTC-USDT panel via OKX. Adds vwap = typical price."""+ from backtest.loaders.registry import resolve_loader++ loader = resolve_loader("crypto")+ fetched = _retry(lambda: loader.fetch(["BTC-USDT"], start, end)) or {}+ panel = _wide_from_fetched(fetched, include_amount=False)+ if all(k in panel for k in ("open", "high", "low", "close")):+ panel["vwap"] = (panel["open"] + panel["high"] + panel["low"] + panel["close"]) / 4.0+ return panel+++def _wide_from_fetched(+ fetched: dict[str, pd.DataFrame], *, include_amount: bool+) -> dict[str, pd.DataFrame]:+ """Stack per-code OHLCV frames into wide panels keyed by field."""+ if not fetched:+ return {}+ all_dates = sorted(set().union(*(df.index for df in fetched.values())))+ if not all_dates:+ return {}+ all_codes = sorted(fetched.keys())+ date_index = pd.DatetimeIndex(all_dates)+ fields = ["open", "high", "low", "close", "volume"]+ if include_amount:+ fields.append("amount")++ panel: dict[str, pd.DataFrame] = {}+ for field in fields:+ present = {+ code: df[field] for code, df in fetched.items() if field in df.columns+ }+ if not present:+ continue+ # pd.concat over a dict of Series gives a wide frame with codes as+ # columns in one pass — avoids the per-code reindex+DataFrame build.+ wide = pd.concat(present, axis=1)+ wide = wide.reindex(index=date_index, columns=all_codes)+ panel[field] = wide.astype(float)+ return panel+++def _retry(fn, *, tries: int = 3, base_delay: float = 1.0):+ """Call ``fn`` up to ``tries`` times with exponential backoff."""+ import time++ last_exc: Exception | None = None+ for attempt in range(tries):+ try:+ return fn()+ except Exception as exc: # noqa: BLE001 — recoverable network errors+ last_exc = exc+ if attempt == tries - 1:+ break+ delay = base_delay * (2 ** attempt)+ logger.debug("retry %d/%d after %.1fs: %s", attempt + 1, tries, delay, exc)+ time.sleep(delay)+ if last_exc is not None:+ logger.warning("retry exhausted: %s", last_exc)+ return None+++# ---------------------------------------------------------------------------+# Per-alpha IC bench+# ---------------------------------------------------------------------------+++def _compute_forward_returns(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:+ """Next-bar forward simple returns from close, aligned to factor timestamp."""+ close = panel.get("close")+ if close is None:+ raise ValueError("panel missing 'close' — cannot derive forward returns")+ # Next-period return aligned to current row (use t+1 close, shift back).+ fwd = close.pct_change().shift(-1)+ return fwd+++def _bench_one_alpha(+ registry: Any,+ alpha_id: str,+ panel: dict[str, pd.DataFrame],+ return_df: pd.DataFrame,+) -> dict[str, Any]:+ """Compute IC stats for one alpha. Returns a dict, may raise SkipAlpha / RegistryError."""+ from src.factors.factor_analysis_core import compute_ic_series # local import++ factor_df = registry.compute(alpha_id, panel)+ ic_series = compute_ic_series(factor_df, return_df)+ if ic_series.empty:+ raise RuntimeError(+ f"{alpha_id}: IC series empty — insufficient overlap between factor and returns"+ )+ ic_mean = float(ic_series.mean())+ ic_std = float(ic_series.std())+ ir = ic_mean / ic_std if ic_std > 0 else 0.0+ ic_pos = float((ic_series > 0).mean())+ alpha = registry.get(alpha_id)+ meta = alpha.meta or {}+ return {+ "id": alpha_id,+ "zoo": alpha.zoo,+ "theme": meta.get("theme", []),+ "formula_latex": meta.get("formula_latex", ""),+ "ic_mean": round(ic_mean, 6),+ "ic_std": round(ic_std, 6),+ "ir": round(ir, 4),+ "ic_positive_ratio": round(ic_pos, 4),+ "ic_count": int(len(ic_series)),+ }+++def _select_alpha_ids(+ registry: Any, *, alpha_id: str | None, zoo: str | None+) -> list[str]:+ if alpha_id and zoo:+ raise ValueError("alpha_id and zoo are mutually exclusive")+ if alpha_id:+ registry.get(alpha_id) # raises KeyError if unknown+ return [alpha_id]+ if zoo:+ return registry.list(zoo=zoo)+ return registry.list()+++# ---------------------------------------------------------------------------+# HTML rendering+# ---------------------------------------------------------------------------++_CSP = (+ "<meta http-equiv=\"Content-Security-Policy\" "+ "content=\"default-src 'none'; style-src 'unsafe-inline'; script-src 'none'\">"+)++_REPORT_CSS = """+body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; margin: 2em;+ color: #222; background: #fafafa; }+h1, h2 { color: #111; }+table { border-collapse: collapse; width: 100%; background: #fff; }+th, td { padding: .5em .75em; border-bottom: 1px solid #e5e5e5; text-align: left; }+th { background: #f0f0f0; }+.meta { color: #666; font-size: .9em; margin-bottom: 1.5em; }+.formula { font-family: monospace; background: #f4f4f4; padding: .25em .5em; }+.skipped { color: #a33; font-size: .9em; }+"""++_JINJA_TEMPLATE = """<!doctype html>+<html lang="en"><head>+<meta charset="utf-8">+{{ csp | safe }}+<title>Alpha Bench Report</title>+<style>{{ css }}</style>+</head><body>+<h1>Alpha Bench Report</h1>+<div class="meta">+ Generated {{ generated_at }} · Universe {{ universe }} ·+ Period {{ period }} · {{ n_alphas_tested }} tested, {{ n_skipped }} skipped+</div>++<h2>Top {{ top|length }} by IR</h2>+<table>+<tr><th>#</th><th>Alpha ID</th><th>Zoo</th><th>Theme</th>+ <th>IC mean</th><th>IC std</th><th>IR</th><th>IC+ ratio</th><th>N</th></tr>+{% for row in top %}+<tr>+ <td>{{ loop.index }}</td>+ <td>{{ row.id }}</td>+ <td>{{ row.zoo }}</td>+ <td>{{ row.theme | join(", ") }}</td>+ <td>{{ "%.4f"|format(row.ic_mean) }}</td>+ <td>{{ "%.4f"|format(row.ic_std) }}</td>+ <td>{{ "%.4f"|format(row.ir) }}</td>+ <td>{{ "%.4f"|format(row.ic_positive_ratio) }}</td>+ <td>{{ row.ic_count }}</td>+</tr>+{% endfor %}+</table>++<h2>Formulas</h2>+<table>+<tr><th>Alpha ID</th><th>Formula (LaTeX source)</th></tr>+{% for row in top %}+<tr><td>{{ row.id }}</td><td class="formula">{{ row.formula_latex }}</td></tr>+{% endfor %}+</table>++{% if failures %}+<h2 class="skipped">Skipped / Failed ({{ failures|length }} shown)</h2>+<table>+<tr><th>Alpha ID</th><th>Reason</th></tr>+{% for f in failures %}+<tr><td>{{ f.alpha_id }}</td><td>{{ f.reason }}</td></tr>+{% endfor %}+</table>+{% endif %}+</body></html>+"""+++def _render_html(context: dict[str, Any]) -> str:+ """Render with Jinja2 autoescape if available; else manual ``html.escape``."""+ try:+ from jinja2 import Environment, select_autoescape++ env = Environment(autoescape=select_autoescape(["html", "xml"]))+ return env.from_string(_JINJA_TEMPLATE).render(**context)+ except ImportError:+ return _render_html_manual(context)+++def _esc(value: Any) -> str:+ return html.escape(str(value), quote=True)+++def _render_html_manual(ctx: dict[str, Any]) -> str:+ """Hand-rolled fallback. Every interpolated value goes through html.escape."""+ parts: list[str] = [+ "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">",+ _CSP,+ f"<title>Alpha Bench Report</title><style>{_REPORT_CSS}</style></head><body>",+ "<h1>Alpha Bench Report</h1>",+ "<div class=\"meta\">Generated ",+ _esc(ctx["generated_at"]),+ " · Universe ",+ _esc(ctx["universe"]),+ " · Period ",+ _esc(ctx["period"]),+ f" · {int(ctx['n_alphas_tested'])} tested, {int(ctx['n_skipped'])} skipped",+ "</div>",+ f"<h2>Top {len(ctx['top'])} by IR</h2><table>",+ "<tr><th>#</th><th>Alpha ID</th><th>Zoo</th><th>Theme</th>"+ "<th>IC mean</th><th>IC std</th><th>IR</th><th>IC+ ratio</th><th>N</th></tr>",+ ]+ for i, row in enumerate(ctx["top"], start=1):+ ic_mean = _esc(f"{row['ic_mean']:.4f}")+ ic_std = _esc(f"{row['ic_std']:.4f}")+ ir = _esc(f"{row['ir']:.4f}")+ ic_pos = _esc(f"{row['ic_positive_ratio']:.4f}")+ parts.append(+ f"<tr><td>{i}</td>"+ f"<td>{_esc(row['id'])}</td>"+ f"<td>{_esc(row['zoo'])}</td>"+ f"<td>{_esc(', '.join(row['theme']))}</td>"+ f"<td>{ic_mean}</td>"+ f"<td>{ic_std}</td>"+ f"<td>{ir}</td>"+ f"<td>{ic_pos}</td>"+ f"<td>{_esc(row['ic_count'])}</td></tr>"+ )+ parts.append("</table><h2>Formulas</h2><table>")+ parts.append("<tr><th>Alpha ID</th><th>Formula (LaTeX source)</th></tr>")+ for row in ctx["top"]:+ parts.append(+ f"<tr><td>{_esc(row['id'])}</td>"+ f"<td class=\"formula\">{_esc(row['formula_latex'])}</td></tr>"+ )+ parts.append("</table>")+ failures = ctx.get("failures") or []+ if failures:+ parts.append(+ f"<h2 class=\"skipped\">Skipped / Failed ({len(failures)} shown)</h2><table>"+ )+ parts.append("<tr><th>Alpha ID</th><th>Reason</th></tr>")+ for f in failures:+ parts.append(+ f"<tr><td>{_esc(f['alpha_id'])}</td><td>{_esc(f['reason'])}</td></tr>"+ )+ parts.append("</table>")+ parts.append("</body></html>")+ return "".join(parts)+++# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------+++def _default_output_dir() -> Path:+ return Path.home() / ".vibe-trading" / "reports"+++def run_alpha_bench(**kwargs: Any) -> dict[str, Any]:+ """Run the bench and return a parsed envelope (dict, not JSON string)."""+ universe = kwargs.get("universe")+ period = kwargs.get("period")+ if not universe or not isinstance(universe, str):+ return {"status": "error", "error": "universe is required (string)"}+ if not period or not isinstance(period, str):+ return {"status": "error", "error": "period is required (string)"}++ try:+ _parse_period(period)+ except ValueError as exc:+ return {"status": "error", "error": str(exc)}++ top_n = int(kwargs.get("top", 20) or 20)+ if top_n <= 0:+ return {"status": "error", "error": "top must be > 0"}++ output_dir_raw = kwargs.get("output_dir") or str(_default_output_dir())+ output_dir = Path(output_dir_raw).expanduser().resolve()++ try:+ from src.factors.registry import (+ RegistryError,+ SkipAlpha,+ get_default_registry,+ )+ except Exception as exc:+ return {"status": "error", "error": f"registry import failed: {exc}"}++ try:+ registry = get_default_registry()+ except Exception as exc:+ logger.exception("Registry construction failed")+ return {"status": "error", "error": f"registry init failed: {exc}"}++ try:+ alpha_ids = _select_alpha_ids(+ registry, alpha_id=kwargs.get("alpha_id"), zoo=kwargs.get("zoo")+ )+ except (KeyError, ValueError) as exc:+ return {"status": "error", "error": str(exc)}++ if not alpha_ids:+ return {+ "status": "error",+ "error": "no alphas matched the selection (registry empty or filters too narrow)",+ }++ # Load panel — W4 universe loader fetches constituents + OHLCV (+ amount, vwap).+ try:+ panel = _load_universe_panel(universe, period)+ except (ValueError, NotImplementedError, RuntimeError) as exc:+ return {+ "status": "error",+ "error": str(exc),+ "n_alphas_tested": 0,+ "n_skipped": 0,+ "selected_alphas": alpha_ids[:50],+ "selected_total": len(alpha_ids),+ }++ try:+ return_df = _compute_forward_returns(panel)+ except Exception as exc:+ return {"status": "error", "error": f"forward returns failed: {exc}"}++ results: list[dict[str, Any]] = []+ failures: list[dict[str, str]] = []+ for aid in alpha_ids:+ try:+ results.append(_bench_one_alpha(registry, aid, panel, return_df))+ except (SkipAlpha, RegistryError, RuntimeError, KeyError, ValueError) as exc:+ failures.append({"alpha_id": aid, "reason": str(exc)})+ except Exception as exc: # noqa: BLE001 — isolate per-alpha failure+ logger.exception("alpha_bench unexpected failure on %s", aid)+ failures.append({"alpha_id": aid, "reason": f"unexpected: {exc}"})++ results.sort(key=lambda r: r["ir"], reverse=True)+ top = results[:top_n]++ output_dir.mkdir(parents=True, exist_ok=True)+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")+ report_path = output_dir / f"alpha_bench_{ts}.html"++ context = {+ "csp": _CSP,+ "css": _REPORT_CSS,+ "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),+ "universe": universe,+ "period": period,+ "n_alphas_tested": len(results),+ "n_skipped": len(failures),+ "top": top,+ "failures": failures[:10],+ }++ try:+ report_path.write_text(_render_html(context), encoding="utf-8")+ except OSError as exc:+ return {"status": "error", "error": f"failed to write report: {exc}"}++ return {+ "status": "ok",+ "report_path": str(report_path),+ "n_alphas_tested": len(results),+ "n_skipped": len(failures),+ "top": top,+ }+++class AlphaBenchTool(BaseTool):+ """Bench one alpha or a whole zoo on a universe and emit an HTML IC report."""++ name = "alpha_bench"+ description = (+ "Bench a single alpha (alpha_id) or a whole zoo (zoo) on a universe over "+ "a period; computes IC mean/std/IR/positive-ratio per alpha and writes an "+ "HTML report. Returns aggregate stats only — no per-stock per-date payloads."+ )+ parameters = {+ "type": "object",+ "properties": {+ "alpha_id": {+ "type": "string",+ "description": "Bench a single alpha (mutually exclusive with zoo).",+ },+ "zoo": {+ "type": "string",+ "description": "Bench every alpha in a zoo (mutually exclusive with alpha_id).",+ },+ "universe": {+ "type": "string",+ "description": "csi300 | sp500 | btc-usdt (resolved via existing data tools).",+ },+ "period": {+ "type": "string",+ "description": "YYYY-YYYY or YYYY-MM-DD/YYYY-MM-DD.",+ },+ "top": {+ "type": "integer",+ "default": 20,+ "description": "Report the top-N alphas ranked by IR.",+ },+ "output_dir": {+ "type": "string",+ "description": "Where to write the HTML report; default ~/.vibe-trading/reports/.",+ },+ },+ "required": ["universe", "period"],+ }+ repeatable = True+ is_readonly = False++ def execute(self, **kwargs: Any) -> str:+ envelope = run_alpha_bench(**kwargs)+ return json.dumps(envelope, ensure_ascii=False)diff --git a/agent/src/tools/alpha_zoo_tool.py b/agent/src/tools/alpha_zoo_tool.pynew file mode 100644index 000000000..3a4242c29--- /dev/null+++ b/agent/src/tools/alpha_zoo_tool.py@@ -0,0 +1,195 @@+"""Alpha-Zoo browse tool: list / get / health on the frozen Registry contract.++A single agent-facing tool with an ``action`` discriminator (list_alphas /+get_alpha / health) rather than three separate tools — keeps the LLM tool+catalogue compact and avoids teaching three near-identical surfaces.++Source-code bodies of alphas are intentionally NOT exposed here: payloads+get large, and the CLI/inspection path handles that case. The agent gets+metadata only.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++_DEFAULT_LIMIT = 50+_MAX_LIMIT = 500++# Fields surfaced to the agent for get_alpha. Excludes raw source — caller+# uses a dedicated inspection path for that.+_META_FIELDS_EXPOSED = (+ "nickname",+ "theme",+ "formula_latex",+ "columns_required",+ "extras_required",+ "requires_sector",+ "universe",+ "frequency",+ "decay_horizon",+ "min_warmup_bars",+ "notes",+)+++def _err(msg: str) -> str:+ return json.dumps({"status": "error", "error": msg}, ensure_ascii=False)+++def _ok(result: Any) -> str:+ return json.dumps({"status": "ok", "result": result}, ensure_ascii=False)+++def _get_registry() -> Any:+ """Lazy-import Registry so this tool's import never triggers a zoo scan+ until the agent actually calls it."""+ from src.factors.registry import Registry # local import; intentional++ return Registry()+++def _alpha_summary(registry: Any, alpha_id: str) -> dict[str, Any]:+ alpha = registry.get(alpha_id)+ meta = alpha.meta or {}+ out: dict[str, Any] = {"id": alpha.id, "zoo": alpha.zoo}+ for field in _META_FIELDS_EXPOSED:+ if field in meta:+ out[field] = meta[field]+ return out+++def _action_list(+ registry: Any,+ *,+ zoo: str | None,+ theme: str | None,+ universe: str | None,+ limit: int,+) -> dict[str, Any]:+ all_ids = registry.list(zoo=zoo, theme=theme, universe=universe)+ total = len(all_ids)+ truncated = total > limit+ items = [_alpha_summary(registry, aid) for aid in all_ids[:limit]]+ return {+ "total": total,+ "returned": len(items),+ "truncated": truncated,+ "filters": {"zoo": zoo, "theme": theme, "universe": universe},+ "items": items,+ }+++def _action_get(registry: Any, alpha_id: str) -> dict[str, Any]:+ return _alpha_summary(registry, alpha_id)+++def _action_health(registry: Any) -> dict[str, Any]:+ return registry.health()+++def run_alpha_zoo(**kwargs: Any) -> dict[str, Any]:+ """Module-level entry returning a parsed envelope (dict, not JSON string).++ Mirrors ``run_alpha_bench`` so CLI handlers can call without round-trip.+ """+ action = kwargs.get("action")+ if action not in {"list_alphas", "get_alpha", "health"}:+ return {+ "status": "error",+ "error": f"action must be list_alphas|get_alpha|health, got {action!r}",+ }++ try:+ registry = _get_registry()+ except Exception as exc:+ logger.exception("Registry construction failed")+ return {"status": "error", "error": f"registry init failed: {exc}"}++ try:+ if action == "list_alphas":+ limit_raw = kwargs.get("limit", _DEFAULT_LIMIT)+ try:+ limit = int(limit_raw)+ except (TypeError, ValueError):+ return {"status": "error", "error": f"limit must be int, got {limit_raw!r}"}+ if limit <= 0:+ return {"status": "error", "error": "limit must be > 0"}+ limit = min(limit, _MAX_LIMIT)+ result = _action_list(+ registry,+ zoo=kwargs.get("zoo"),+ theme=kwargs.get("theme"),+ universe=kwargs.get("universe"),+ limit=limit,+ )+ elif action == "get_alpha":+ alpha_id = kwargs.get("alpha_id")+ if not alpha_id or not isinstance(alpha_id, str):+ return {"status": "error", "error": "get_alpha requires alpha_id (string)"}+ try:+ result = _action_get(registry, alpha_id)+ except KeyError as exc:+ return {"status": "error", "error": str(exc)}+ else: # health+ result = _action_health(registry)+ except Exception as exc:+ logger.exception("alpha_zoo action %s failed", action)+ return {"status": "error", "error": f"{action} failed: {exc}"}++ return {"status": "ok", "result": result}+++class AlphaZooTool(BaseTool):+ """Browse the bundled alpha zoo: list_alphas / get_alpha / health."""++ name = "alpha_zoo"+ description = (+ "Browse the bundled alpha zoo. action=list_alphas filters by zoo/theme/universe; "+ "action=get_alpha returns one alpha's metadata (no source body); "+ "action=health reports registry load status (loaded / failed / errors)."+ )+ parameters = {+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": ["list_alphas", "get_alpha", "health"],+ "description": "Which registry operation to run.",+ },+ "alpha_id": {+ "type": "string",+ "description": "Required when action=get_alpha.",+ },+ "zoo": {+ "type": "string",+ "description": "Optional zoo filter for list_alphas (e.g. gtja191, kakushadze101).",+ },+ "theme": {+ "type": "string",+ "description": "Optional theme filter (momentum, reversal, volume, ...).",+ },+ "universe": {+ "type": "string",+ "description": "Optional universe filter (equity_us, equity_cn, crypto, ...).",+ },+ "limit": {+ "type": "integer",+ "default": _DEFAULT_LIMIT,+ "description": f"Cap on returned items (default {_DEFAULT_LIMIT}, max {_MAX_LIMIT}).",+ },+ },+ "required": ["action"],+ }+ repeatable = True+ is_readonly = True++ def execute(self, **kwargs: Any) -> str:+ envelope = run_alpha_zoo(**kwargs)+ return json.dumps(envelope, ensure_ascii=False)diff --git a/frontend/src/components/layout/Layout.tsx b/frontend/src/components/layout/Layout.tsxindex cd1c57b94..7c7e304b1 100644--- a/frontend/src/components/layout/Layout.tsx+++ b/frontend/src/components/layout/Layout.tsx@@ -1,6 +1,6 @@import { useEffect, useState } from "react";import { Link, Outlet, useLocation, useSearchParams } from "react-router-dom";-import { BarChart3, Bot, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings } from "lucide-react";+import { BarChart3, Bot, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings, Layers } from "lucide-react";import { cn } from "@/lib/utils";import { useI18n } from "@/lib/i18n";import { useDarkMode } from "@/hooks/useDarkMode";@@ -8,11 +8,16 @@ import { api, type SessionItem } from "@/lib/api";import { useAgentStore } from "@/stores/agent";import { ConnectionBanner } from "@/components/layout/ConnectionBanner";+// Bump on each release; one place keeps the footer in sync with package.json.+const APP_VERSION = "v0.1.8";++// NAV entries: `key` looks up label in i18n; `label` overrides (used for "Alpha Zoo").const NAV = [- { to: "/", icon: BarChart3, key: "home" as const },- { to: "/agent", icon: Bot, key: "agent" as const },- { to: "/settings", icon: Settings, key: "settings" as const },- { to: "/correlation", icon: BarChart3, key: "correlation" as const },+ { to: "/", icon: BarChart3, key: "home" as const, label: null },+ { to: "/agent", icon: Bot, key: "agent" as const, label: null },+ { to: "/alpha-zoo", icon: Layers, key: "alphaZoo" as const, label: "Alpha Zoo" },+ { to: "/settings", icon: Settings, key: "settings" as const, label: null },+ { to: "/correlation", icon: BarChart3, key: "correlation" as const, label: null },];export function Layout() {@@ -82,23 +87,26 @@ export function Layout() {{/* Nav */}<nav className={cn("space-y-0.5", collapsed ? "p-1" : "p-2")}>- {NAV.map(({ to, icon: Icon, key }) => (- <Link- key={to}- to={to}- className={cn(- "flex items-center rounded-md text-sm transition-colors",- collapsed ? "justify-center p-2" : "gap-3 px-3 py-2",- (to === "/" ? pathname === "/" : pathname.startsWith(to))- ? "bg-primary/10 text-primary font-medium"- : "text-muted-foreground hover:bg-muted hover:text-foreground"- )}- title={collapsed ? t[key] : undefined}- >- <Icon className="h-4 w-4 shrink-0" />- {!collapsed && t[key]}- </Link>- ))}+ {NAV.map(({ to, icon: Icon, key, label }) => {+ const text = label ?? t[key];+ return (+ <Link+ key={to}+ to={to}+ className={cn(+ "flex items-center rounded-md text-sm transition-colors",+ collapsed ? "justify-center p-2" : "gap-3 px-3 py-2",+ (to === "/" ? pathname === "/" : pathname.startsWith(to))+ ? "bg-primary/10 text-primary font-medium"+ : "text-muted-foreground hover:bg-muted hover:text-foreground"+ )}+ title={collapsed ? text : undefined}+ >+ <Icon className="h-4 w-4 shrink-0" aria-hidden="true" />+ {!collapsed && text}+ </Link>+ );+ })}</nav>{/* Sessions — hidden when collapsed */}@@ -227,7 +235,7 @@ export function Layout() {</button></div></div>- <p className="text-xs text-muted-foreground/60">v0.1.7</p>+ <p className="text-xs text-muted-foreground/60">{APP_VERSION}</p></>)}</div>diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex d92673615..d4c238c6b 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -105,6 +105,26 @@ export const api = {method: "PUT",body: JSON.stringify(settings),}),++ // Alpha Zoo API+ listAlphas: (params: AlphaListParams = {}) => {+ const q = new URLSearchParams();+ if (params.zoo) q.set("zoo", params.zoo);+ if (params.theme) q.set("theme", params.theme);+ if (params.universe) q.set("universe", params.universe);+ if (params.limit !== undefined) q.set("limit", String(params.limit));+ const qs = q.toString();+ return request<AlphaListResponse>(`/alpha/list${qs ? `?${qs}` : ""}`);+ },+ getAlpha: (alphaId: string) =>+ request<AlphaDetailResponse>(`/alpha/${encodeURIComponent(alphaId)}`),+ createAlphaBench: (body: AlphaBenchRequest) =>+ request<{ status: string; job_id: string }>("/alpha/bench", {+ method: "POST",+ body: JSON.stringify(body),+ }),+ alphaBenchStreamUrl: (jobId: string) =>+ withAuthQuery(`${BASE}/alpha/bench/${encodeURIComponent(jobId)}/stream`),};// --- Swarm types ---@@ -349,6 +369,73 @@ export interface SessionItem {last_attempt_id?: string;}+// --- Alpha Zoo types ---++export interface AlphaListParams {+ zoo?: string;+ theme?: string;+ universe?: string;+ limit?: number;+}++export interface AlphaSummary {+ id: string;+ zoo: string;+ theme: string[];+ universe: string[];+ nickname?: string;+ decay_horizon?: number | null;+ min_warmup_bars?: number | null;+ requires_sector?: boolean;+}++export interface AlphaListResponse {+ status: string;+ alphas: AlphaSummary[];+ total: number;+ returned: number;+ truncated: boolean;+}++export interface AlphaDetail {+ id: string;+ zoo: string;+ module_path?: string;+ meta: Record<string, unknown>;+}++export interface AlphaDetailResponse {+ status: string;+ alpha: AlphaDetail;+ source_code: string;+}++export interface AlphaBenchRequest {+ zoo: string;+ universe: string;+ period: string;+ top?: number;+}++export interface AlphaBenchTopRow {+ id: string;+ ic_mean: number;+ ir: number;+ theme: string[];+ formula_latex: string;+ category: "alive" | "reversed" | "dead";+}++export interface AlphaBenchResult {+ alive: number;+ reversed: number;+ dead: number;+ skipped?: number;+ top5_by_ir: AlphaBenchTopRow[];+ dead_examples: AlphaBenchTopRow[];+ by_theme: Record<string, { alive: number; reversed: number; dead: number }>;+}+export interface MessageItem {message_id: string;session_id: string;diff --git a/frontend/src/lib/i18n.tsx b/frontend/src/lib/i18n.tsxindex 18a9cd1b9..2d000b066 100644--- a/frontend/src/lib/i18n.tsx+++ b/frontend/src/lib/i18n.tsx@@ -1,7 +1,7 @@import { createContext, useContext, type ReactNode } from "react";const messages = {- home: "Home", agent: "Agent", runs: "Runs", settings: "Settings",+ home: "Home", agent: "Agent", runs: "Runs", settings: "Settings", alphaZoo: "Alpha Zoo",settingsDesc: "Configure model credentials and market data source tokens for this local project.",localApiAccess: "Local API access",localApiAccessDesc: "For remote or private Web UI deployments, enter the server API key once in this browser. Localhost use can stay blank.",diff --git a/frontend/src/pages/AlphaZoo.tsx b/frontend/src/pages/AlphaZoo.tsxnew file mode 100644index 000000000..786433815--- /dev/null+++ b/frontend/src/pages/AlphaZoo.tsx@@ -0,0 +1,1023 @@+/**+ * Alpha Zoo — browse / detail / bench views.+ *+ * Routing model: a single page component, three URL shapes:+ * /alpha-zoo → browse view+ * /alpha-zoo/bench → bench runner+ * /alpha-zoo/:alphaId → alpha detail+ *+ * The bench view uses a raw EventSource rather than the shared `useSSE` hook+ * because that hook hard-codes the agent's known event types (text_delta,+ * tool_call, …) and would silently drop the alpha bench events+ * (`progress`, `result`, `done`, `error`). The swarm page uses the same+ * raw-EventSource pattern (frontend/src/pages/Agent.tsx).+ */++import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";+import { Link, useLocation, useNavigate, useParams } from "react-router-dom";+import {+ Layers,+ Search,+ Play,+ ArrowLeft,+ Loader2,+ CheckCircle2,+ AlertTriangle,+ XCircle,+ Library,+} from "lucide-react";+import { toast } from "sonner";+import { cn } from "@/lib/utils";+import {+ api,+ type AlphaSummary,+ type AlphaDetailResponse,+ type AlphaBenchResult,+ type AlphaBenchTopRow,+} from "@/lib/api";+import { echarts } from "@/lib/echarts";+import { getChartTheme } from "@/lib/chart-theme";+import { useDarkMode } from "@/hooks/useDarkMode";++/* ---------- Constants ---------- */++interface ZooCard {+ id: string;+ title: string;+ description: string;+ approxCount: number;+ accent: string;+}++// IMPORTANT: The Kakushadze 101 zoo must use the author's name as the label.+// The legacy / trademark name is forbidden by a CI grep gate — do not add it.+const ZOO_CARDS: ZooCard[] = [+ {+ id: "qlib158",+ title: "Qlib 158",+ description:+ "Microsoft Qlib's full 158-feature library covering momentum, volatility, volume and rolling statistical signals.",+ approxCount: 154,+ accent: "from-sky-500/20 to-sky-500/5",+ },+ {+ id: "alpha101",+ title: "Kakushadze 101 Formulaic Alphas",+ description:+ "The 101 formulaic alphas from Kakushadze (2015); short-horizon cross-sectional signals.",+ approxCount: 101,+ accent: "from-emerald-500/20 to-emerald-500/5",+ },+ {+ id: "gtja191",+ title: "GTJA 191",+ description:+ "Guotai Junan Securities' 191 alphas; technical and microstructure signals tuned to China A-share markets.",+ approxCount: 191,+ accent: "from-amber-500/20 to-amber-500/5",+ },+ {+ id: "academic",+ title: "Academic Anomalies",+ description:+ "Curated long-horizon anomalies from the academic literature (value, momentum, quality, low-vol, etc.).",+ approxCount: 6,+ accent: "from-violet-500/20 to-violet-500/5",+ },+];++const UNIVERSE_OPTIONS = [+ { value: "csi300", label: "CSI 300 (China A)" },+ { value: "sp500", label: "S&P 500 (US)" },+ { value: "btc-usdt", label: "BTC-USDT (Crypto)" },+];++const PAGE_SIZE = 50;++/* ---------- Helpers ---------- */++function fmtNum(v: unknown, digits = 3): string {+ const n = Number(v);+ if (!Number.isFinite(n)) return "—";+ return n.toFixed(digits);+}++function metaString(meta: Record<string, unknown>, key: string): string {+ const v = meta[key];+ if (v === undefined || v === null || v === "") return "—";+ if (Array.isArray(v)) return v.join(", ");+ return String(v);+}++/* ---------- Page entry ---------- */++export function AlphaZoo() {+ const params = useParams<{ alphaId?: string }>();+ const { pathname } = useLocation();++ // Internal view selection+ if (pathname === "/alpha-zoo/bench") {+ return <BenchView />;+ }+ if (params.alphaId) {+ return <DetailView alphaId={params.alphaId} />;+ }+ return <BrowseView />;+}++/* ---------- Browse view ---------- */++function BrowseView() {+ const [alphas, setAlphas] = useState<AlphaSummary[]>([]);+ const [loading, setLoading] = useState(true);+ const [zooFilter, setZooFilter] = useState<string>("");+ const [themeFilter, setThemeFilter] = useState<string>("");+ const [universeFilter, setUniverseFilter] = useState<string>("");+ const [search, setSearch] = useState("");+ const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);+ const [total, setTotal] = useState<number>(0);++ useEffect(() => {+ let alive = true;+ setLoading(true);+ api+ .listAlphas({+ zoo: zooFilter || undefined,+ theme: themeFilter || undefined,+ universe: universeFilter || undefined,+ limit: 1000,+ })+ .then((res) => {+ if (!alive) return;+ setAlphas(res.alphas);+ setTotal(res.total);+ setVisibleCount(PAGE_SIZE);+ })+ .catch((err: unknown) => {+ if (!alive) return;+ const msg = err instanceof Error ? err.message : "Failed to load alphas";+ toast.error(msg);+ setAlphas([]);+ setTotal(0);+ })+ .finally(() => {+ if (alive) setLoading(false);+ });+ return () => {+ alive = false;+ };+ }, [zooFilter, themeFilter, universeFilter]);++ const themeOptions = useMemo(() => {+ const set = new Set<string>();+ for (const a of alphas) for (const t of a.theme || []) set.add(t);+ return Array.from(set).sort();+ }, [alphas]);++ const filtered = useMemo(() => {+ const q = search.trim().toLowerCase();+ if (!q) return alphas;+ return alphas.filter(+ (a) =>+ a.id.toLowerCase().includes(q) ||+ (a.nickname || "").toLowerCase().includes(q),+ );+ }, [alphas, search]);++ const visible = filtered.slice(0, visibleCount);++ return (+ <div className="p-4 md:p-8 max-w-6xl mx-auto space-y-8">+ {/* Hero */}+ <div className="space-y-2">+ <div className="flex items-center gap-2 text-xs text-muted-foreground uppercase tracking-wide">+ <Layers className="h-3.5 w-3.5" aria-hidden="true" /> Alpha Zoo+ </div>+ <h1 className="text-2xl md:text-3xl font-bold tracking-tight">+ {total > 0 ? total : 452} pre-built quant alphas across 4 zoos+ </h1>+ <p className="text-sm text-muted-foreground max-w-2xl">+ Browse formula-driven cross-sectional signals from Qlib, the+ Kakushadze 101 set, GTJA 191, and the academic anomaly literature.+ Click any alpha to read its formula and source code, or run a bench+ to score the whole zoo on a universe and period.+ </p>+ </div>++ {/* Zoo cards */}+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">+ {ZOO_CARDS.map((z) => {+ const active = zooFilter === z.id;+ return (+ <button+ key={z.id}+ type="button"+ onClick={() => setZooFilter(active ? "" : z.id)}+ className={cn(+ "text-left border rounded-xl p-4 space-y-2 transition bg-gradient-to-br",+ z.accent,+ "hover:border-primary/50",+ active && "border-primary ring-1 ring-primary/30",+ )}+ >+ <div className="flex items-center justify-between">+ <Library className="h-5 w-5 text-primary" aria-hidden="true" />+ <span className="text-xs font-mono text-muted-foreground">+ {z.approxCount}+ </span>+ </div>+ <h3 className="font-semibold text-sm leading-tight">{z.title}</h3>+ <p className="text-xs text-muted-foreground line-clamp-3">+ {z.description}+ </p>+ </button>+ );+ })}+ </div>++ {/* Filter bar */}+ <div className="flex flex-col md:flex-row md:items-end gap-3 border rounded-xl p-4 bg-card">+ <div className="flex-1 min-w-0">+ <label htmlFor="alpha-search" className="text-xs text-muted-foreground block mb-1">+ Search+ </label>+ <div className="relative">+ <Search+ className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"+ aria-hidden="true"+ />+ <input+ id="alpha-search"+ value={search}+ onChange={(e) => {+ setSearch(e.target.value);+ setVisibleCount(PAGE_SIZE);+ }}+ placeholder="Filter by id or nickname…"+ className="w-full pl-9 pr-3 py-2 rounded-lg border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"+ />+ </div>+ </div>+ <div className="md:w-40">+ <label htmlFor="alpha-zoo-filter" className="text-xs text-muted-foreground block mb-1">Zoo</label>+ <select+ id="alpha-zoo-filter"+ value={zooFilter}+ onChange={(e) => setZooFilter(e.target.value)}+ className="w-full px-3 py-2 rounded-lg border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"+ >+ <option value="">All zoos</option>+ {ZOO_CARDS.map((z) => (+ <option key={z.id} value={z.id}>+ {z.title}+ </option>+ ))}+ </select>+ </div>+ <div className="md:w-40">+ <label htmlFor="alpha-theme-filter" className="text-xs text-muted-foreground block mb-1">+ Theme+ </label>+ <select+ id="alpha-theme-filter"+ value={themeFilter}+ onChange={(e) => setThemeFilter(e.target.value)}+ className="w-full px-3 py-2 rounded-lg border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"+ >+ <option value="">All themes</option>+ {themeOptions.map((tname) => (+ <option key={tname} value={tname}>+ {tname}+ </option>+ ))}+ </select>+ </div>+ <div className="md:w-44">+ <label htmlFor="alpha-universe-filter" className="text-xs text-muted-foreground block mb-1">+ Universe+ </label>+ <select+ id="alpha-universe-filter"+ value={universeFilter}+ onChange={(e) => setUniverseFilter(e.target.value)}+ className="w-full px-3 py-2 rounded-lg border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"+ >+ <option value="">All universes</option>+ {UNIVERSE_OPTIONS.map((u) => (+ <option key={u.value} value={u.value}>+ {u.label}+ </option>+ ))}+ </select>+ </div>+ <Link+ to="/alpha-zoo/bench"+ className="inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 transition"+ >+ <Play className="h-3.5 w-3.5" aria-hidden="true" /> Run bench+ </Link>+ </div>++ {/* Table */}+ {/* TODO(v0.2): switch to react-window if alpha count exceeds 5000 */}+ <div className="border rounded-xl overflow-hidden">+ <div className="overflow-x-auto">+ <table className="w-full text-sm" aria-label="Alpha catalogue">+ <caption className="sr-only">Alpha catalogue</caption>+ <thead>+ <tr className="border-b bg-muted/40">+ <th className="text-left px-4 py-2.5 text-muted-foreground">+ ID+ </th>+ <th className="text-left px-4 py-2.5 text-muted-foreground">+ Zoo+ </th>+ <th className="text-left px-4 py-2.5 text-muted-foreground">+ Theme+ </th>+ <th className="text-left px-4 py-2.5 text-muted-foreground hidden md:table-cell">+ Universe+ </th>+ <th className="text-right px-4 py-2.5 text-muted-foreground">+ Decay+ </th>+ </tr>+ </thead>+ <tbody>+ {loading ? (+ <tr>+ <td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin inline mr-2" aria-hidden="true" />+ Loading alphas…+ </td>+ </tr>+ ) : visible.length === 0 ? (+ <tr>+ <td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">+ No alphas match the current filters.+ </td>+ </tr>+ ) : (+ visible.map((a) => (+ <tr+ key={`${a.zoo}:${a.id}`}+ className="border-b last:border-0 hover:bg-muted/20"+ >+ <td className="px-4 py-2 font-mono text-xs">+ <Link+ to={`/alpha-zoo/${encodeURIComponent(a.id)}`}+ className="text-primary hover:underline"+ >+ {a.id}+ </Link>+ {a.nickname && (+ <span className="ml-2 text-muted-foreground font-sans">+ {a.nickname}+ </span>+ )}+ </td>+ <td className="px-4 py-2 text-xs">{a.zoo}</td>+ <td className="px-4 py-2 text-xs text-muted-foreground">+ {(a.theme || []).join(", ") || "—"}+ </td>+ <td className="px-4 py-2 text-xs text-muted-foreground hidden md:table-cell">+ {(a.universe || []).join(", ") || "—"}+ </td>+ <td className="px-4 py-2 text-right font-mono tabular-nums text-xs">+ {a.decay_horizon ?? "—"}+ </td>+ </tr>+ ))+ )}+ </tbody>+ </table>+ </div>+ {!loading && visible.length < filtered.length && (+ <div className="border-t p-3 flex items-center justify-between text-xs text-muted-foreground">+ <span>+ Showing {visible.length} of {filtered.length}+ </span>+ <button+ type="button"+ onClick={() => setVisibleCount((c) => c + PAGE_SIZE)}+ className="px-3 py-1 rounded-md border hover:bg-muted hover:text-foreground transition"+ >+ Load more+ </button>+ </div>+ )}+ </div>+ </div>+ );+}++/* ---------- Detail view ---------- */++interface DetailProps {+ alphaId: string;+}++function DetailView({ alphaId }: DetailProps) {+ const [detail, setDetail] = useState<AlphaDetailResponse | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const navigate = useNavigate();++ useEffect(() => {+ let alive = true;+ setLoading(true);+ setError(null);+ api+ .getAlpha(alphaId)+ .then((res) => {+ if (alive) setDetail(res);+ })+ .catch((err: unknown) => {+ if (!alive) return;+ const msg = err instanceof Error ? err.message : "Failed to load alpha";+ setError(msg);+ })+ .finally(() => {+ if (alive) setLoading(false);+ });+ return () => {+ alive = false;+ };+ }, [alphaId]);++ if (loading) {+ return (+ <div className="p-8 flex items-center justify-center text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin mr-2" aria-hidden="true" /> Loading {alphaId}…+ </div>+ );+ }++ if (error || !detail) {+ return (+ <div className="p-8 max-w-3xl mx-auto space-y-4">+ <Link to="/alpha-zoo" className="text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1">+ <ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" /> Back to Alpha Zoo+ </Link>+ <div className="border rounded-xl p-6 bg-card">+ <h2 className="font-semibold text-sm mb-1 flex items-center gap-2">+ <AlertTriangle className="h-4 w-4 text-warning" aria-hidden="true" /> Could not load alpha+ </h2>+ <p className="text-sm text-muted-foreground">{error || "Unknown error"}</p>+ </div>+ </div>+ );+ }++ const a = detail.alpha;+ const meta = a.meta || {};+ const formulaLatex = (meta["formula_latex"] as string | undefined) || "";+ const nickname = (meta["nickname"] as string | undefined) || "";+ const firstUniverse = ((meta["universe"] as string[] | undefined) || [])[0] || "";++ // Keep period in sync with the BenchView form default so the prefilled+ // form values match what users see if they click "Run bench" from here.+ const benchHref = firstUniverse+ ? `/alpha-zoo/bench?zoo=${encodeURIComponent(a.zoo)}&universe=${encodeURIComponent(firstUniverse)}&period=2020-2025`+ : `/alpha-zoo/bench?zoo=${encodeURIComponent(a.zoo)}&period=2020-2025`;++ return (+ <div className="p-4 md:p-8 max-w-4xl mx-auto space-y-6">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <Link+ to="/alpha-zoo"+ className="text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1"+ >+ <ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" /> Back to Alpha Zoo+ </Link>+ <button+ type="button"+ onClick={() => navigate(benchHref)}+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-md bg-primary text-primary-foreground text-xs font-medium hover:opacity-90 transition"+ >+ <Play className="h-3.5 w-3.5" aria-hidden="true" /> Run bench+ </button>+ </div>++ {/* Title */}+ <div className="space-y-1">+ <div className="flex items-center gap-2 flex-wrap">+ <h1 className="font-mono text-xl md:text-2xl font-bold tracking-tight">+ {a.id}+ </h1>+ <span className="text-xs px-2 py-0.5 rounded-full bg-primary/10 text-primary font-medium">+ {a.zoo}+ </span>+ </div>+ {nickname && (+ <p className="text-sm text-muted-foreground">{nickname}</p>+ )}+ </div>++ {/* Formula */}+ <section className="space-y-2">+ <h2 className="text-sm font-medium text-muted-foreground">Formula</h2>+ <pre className="border rounded-xl bg-muted/30 p-4 overflow-x-auto text-xs leading-relaxed">+ <code>{formulaLatex || "(no formula provided)"}</code>+ </pre>+ </section>++ {/* Metadata */}+ <section className="space-y-2">+ <h2 className="text-sm font-medium text-muted-foreground">Metadata</h2>+ <div className="border rounded-xl overflow-hidden">+ <table className="w-full text-sm">+ <tbody>+ <MetaRow label="Theme" value={metaString(meta, "theme")} />+ <MetaRow label="Universe" value={metaString(meta, "universe")} />+ <MetaRow label="Frequency" value={metaString(meta, "frequency")} />+ <MetaRow label="Decay horizon" value={metaString(meta, "decay_horizon")} />+ <MetaRow label="Min warm-up bars" value={metaString(meta, "min_warmup_bars")} />+ <MetaRow label="Requires sector" value={metaString(meta, "requires_sector")} />+ <MetaRow label="Module path" value={a.module_path || "—"} />+ <MetaRow label="Notes" value={metaString(meta, "notes")} last />+ </tbody>+ </table>+ </div>+ </section>++ {/* Source code */}+ <section className="space-y-2">+ <h2 className="text-sm font-medium text-muted-foreground">Source code</h2>+ <details className="border rounded-xl bg-card group">+ <summary className="cursor-pointer px-4 py-3 text-sm font-medium hover:bg-muted/40 select-none">+ View source ({(detail.source_code || "").split("\n").length} lines)+ </summary>+ <pre className="border-t bg-muted/30 p-4 overflow-x-auto text-xs leading-relaxed">+ <code>{detail.source_code || "(no source available)"}</code>+ </pre>+ </details>+ </section>+ </div>+ );+}++function MetaRow({ label, value, last }: { label: string; value: string; last?: boolean }) {+ return (+ <tr className={cn(!last && "border-b", "hover:bg-muted/20")}>+ <td className="px-4 py-2 text-xs text-muted-foreground w-1/3">{label}</td>+ <td className="px-4 py-2 text-xs font-mono break-all">{value}</td>+ </tr>+ );+}++/* ---------- Bench view ---------- */++type BenchStatus = "idle" | "submitting" | "streaming" | "done" | "error";++interface BenchProgress {+ n_done: number;+ n_total: number;+ current_alpha_id?: string;+}++function BenchView() {+ // Read prefill from query string (set by Detail "Run bench" button).+ const { search: locSearch } = useLocation();+ const initial = useMemo(() => {+ const q = new URLSearchParams(locSearch);+ return {+ zoo: q.get("zoo") || "alpha101",+ universe: q.get("universe") || "csi300",+ period: q.get("period") || "2020-2025",+ top: Number(q.get("top") || "20"),+ };+ }, [locSearch]);++ const [zoo, setZoo] = useState(initial.zoo);+ const [universe, setUniverse] = useState(initial.universe);+ const [period, setPeriod] = useState(initial.period);+ const [top, setTop] = useState<number>(initial.top);++ const [status, setStatus] = useState<BenchStatus>("idle");+ const [jobId, setJobId] = useState<string | null>(null);+ const [progress, setProgress] = useState<BenchProgress | null>(null);+ const [result, setResult] = useState<AlphaBenchResult | null>(null);+ const [formError, setFormError] = useState<string | null>(null);+ const sourceRef = useRef<EventSource | null>(null);+ // Track terminal `done` so the synthetic EventSource `error` fired on+ // close doesn't surface as a spurious toast (race between done + error).+ const doneRef = useRef(false);++ useEffect(() => {+ return () => {+ sourceRef.current?.close();+ sourceRef.current = null;+ };+ }, []);++ const startBench = async (e: FormEvent) => {+ e.preventDefault();+ if (status === "submitting" || status === "streaming") return;+ setStatus("submitting");+ setProgress(null);+ setResult(null);+ setFormError(null);+ doneRef.current = false;+ sourceRef.current?.close();+ const safeTop = Number.isFinite(top) && top > 0 ? top : 20;+ try {+ const res = await api.createAlphaBench({+ zoo,+ universe,+ period,+ top: safeTop,+ });+ setJobId(res.job_id);+ attachStream(res.job_id);+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : "Failed to start bench";+ // BTC-USDT is single-asset — surface inline rather than as a toast,+ // because the form is the action context and the message includes a+ // concrete suggestion for the user's next step.+ if (msg.toLowerCase().includes("single-asset")) {+ setFormError(+ `${msg} Try \`sp500\` or \`csi300\` for a meaningful cross-sectional IC.`,+ );+ } else {+ toast.error(msg);+ }+ setStatus("error");+ }+ };++ const attachStream = (newJobId: string) => {+ setStatus("streaming");+ const url = api.alphaBenchStreamUrl(newJobId);+ const source = new EventSource(url);+ sourceRef.current = source;++ source.addEventListener("progress", (e) => {+ try {+ const data = JSON.parse((e as MessageEvent).data) as BenchProgress;+ setProgress(data);+ } catch {+ /* ignore */+ }+ });++ source.addEventListener("result", (e) => {+ try {+ const data = JSON.parse((e as MessageEvent).data) as AlphaBenchResult;+ setResult(data);+ } catch {+ /* ignore */+ }+ });++ source.addEventListener("done", () => {+ doneRef.current = true;+ setStatus("done");+ source.close();+ sourceRef.current = null;+ });++ source.addEventListener("error", (e) => {+ // EventSource raises a synthetic error on every disconnect, including+ // the normal close that follows our `done` event. The ref check is+ // synchronous (state updates from `done` would be batched and not+ // visible here yet), so it's the only reliable race guard.+ if (doneRef.current) {+ source.close();+ sourceRef.current = null;+ return;+ }+ let msg = "Bench stream error";+ try {+ const data = JSON.parse((e as MessageEvent).data || "{}");+ if (typeof data.message === "string") msg = data.message;+ } catch {+ /* network-level error, no payload */+ }+ toast.error(msg);+ setStatus("error");+ source.close();+ sourceRef.current = null;+ });+ };++ const busy = status === "submitting" || status === "streaming";++ return (+ <div className="p-4 md:p-8 max-w-5xl mx-auto space-y-6">+ <Link+ to="/alpha-zoo"+ className="text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1"+ >+ <ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" /> Back to Alpha Zoo+ </Link>++ <div className="space-y-1">+ <div className="flex items-center gap-2 text-xs text-muted-foreground uppercase tracking-wide">+ <Play className="h-3.5 w-3.5" aria-hidden="true" /> Bench runner+ </div>+ <h1 className="text-2xl md:text-3xl font-bold tracking-tight">+ Score a zoo on a universe+ </h1>+ <p className="text-sm text-muted-foreground max-w-2xl">+ Computes IC / IR for every alpha in the selected zoo over the chosen+ universe and period, then bucketizes them as alive / reversed / dead.+ </p>+ </div>++ {/* Form */}+ <form+ onSubmit={startBench}+ className="border rounded-xl p-4 bg-card grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3 items-end"+ >+ <div>+ <label htmlFor="bench-zoo" className="text-xs text-muted-foreground block mb-1">Zoo</label>+ <select+ id="bench-zoo"+ value={zoo}+ onChange={(e) => setZoo(e.target.value)}+ disabled={busy}+ className="w-full px-3 py-2 rounded-lg border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 disabled:opacity-50"+ >+ {ZOO_CARDS.map((z) => (+ <option key={z.id} value={z.id}>+ {z.title}+ </option>+ ))}+ </select>+ </div>+ <div>+ <label htmlFor="bench-universe" className="text-xs text-muted-foreground block mb-1">Universe</label>+ <select+ id="bench-universe"+ value={universe}+ onChange={(e) => setUniverse(e.target.value)}+ disabled={busy}+ className="w-full px-3 py-2 rounded-lg border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 disabled:opacity-50"+ >+ {UNIVERSE_OPTIONS.map((u) => (+ <option key={u.value} value={u.value}>+ {u.label}+ </option>+ ))}+ </select>+ </div>+ <div>+ <label htmlFor="bench-period" className="text-xs text-muted-foreground block mb-1">Period</label>+ <input+ id="bench-period"+ value={period}+ onChange={(e) => setPeriod(e.target.value)}+ disabled={busy}+ placeholder="2020-2025"+ className="w-full px-3 py-2 rounded-lg border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 disabled:opacity-50"+ />+ </div>+ <div>+ <label htmlFor="bench-top" className="text-xs text-muted-foreground block mb-1">Top</label>+ <input+ id="bench-top"+ type="number"+ min={1}+ max={500}+ value={Number.isFinite(top) ? top : ""}+ onChange={(e) =>+ // Empty input → fall back to default; submit also clamps+ // to a safe value so NaN never reaches the API.+ setTop(e.target.value === "" ? 20 : Number(e.target.value))+ }+ disabled={busy}+ className="w-full px-3 py-2 rounded-lg border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 disabled:opacity-50"+ />+ </div>+ <div className="flex flex-col gap-1">+ <button+ type="submit"+ disabled={busy}+ className="inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 transition disabled:opacity-50"+ >+ {busy ? (+ <>+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" /> Running…+ </>+ ) : (+ <>+ <Play className="h-3.5 w-3.5" aria-hidden="true" /> Run bench+ </>+ )}+ </button>+ </div>+ {formError && (+ <p+ className="sm:col-span-2 lg:col-span-5 text-xs text-red-600 dark:text-red-400"+ role="alert"+ >+ {formError}+ </p>+ )}+ </form>++ {/* Progress */}+ {(status === "submitting" || status === "streaming") && (+ <ProgressPanel jobId={jobId} progress={progress} />+ )}++ {/* Result */}+ {result && <ResultPanel result={result} />}+ </div>+ );+}++function ProgressPanel({+ jobId,+ progress,+}: {+ jobId: string | null;+ progress: BenchProgress | null;+}) {+ const pct = progress && progress.n_total > 0+ ? Math.min(100, Math.round((progress.n_done / progress.n_total) * 100))+ : 0;+ return (+ <div className="border rounded-xl p-4 bg-card space-y-3">+ <div className="flex items-center justify-between text-xs text-muted-foreground">+ <span className="flex items-center gap-1.5">+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />+ {jobId ? `Job ${jobId.slice(0, 12)}…` : "Submitting…"}+ </span>+ {progress && (+ <span className="font-mono tabular-nums">+ {progress.n_done} / {progress.n_total}+ </span>+ )}+ </div>+ <div className="h-2 rounded-full bg-muted overflow-hidden">+ <div+ className="h-full bg-primary transition-all duration-300"+ style={{ width: `${pct}%` }}+ />+ </div>+ {progress?.current_alpha_id && (+ <p className="text-xs text-muted-foreground font-mono truncate">+ Computing: {progress.current_alpha_id}+ </p>+ )}+ </div>+ );+}++function ResultPanel({ result }: { result: AlphaBenchResult }) {+ const { dark } = useDarkMode();+ const chartRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (!chartRef.current) return;+ const theme = getChartTheme();+ const chart = echarts.init(chartRef.current);+ const themes = Object.keys(result.by_theme || {}).sort();+ const aliveSeries = themes.map((k) => result.by_theme[k].alive);+ const reversedSeries = themes.map((k) => result.by_theme[k].reversed);+ const deadSeries = themes.map((k) => result.by_theme[k].dead);++ chart.setOption({+ backgroundColor: "transparent",+ tooltip: { trigger: "axis", axisPointer: { type: "shadow" } },+ legend: {+ data: ["Alive", "Reversed", "Dead"],+ textStyle: { color: theme.textColor, fontSize: 11 },+ right: 8,+ top: 4,+ },+ grid: { left: 8, right: 8, top: 32, bottom: 8, containLabel: true },+ xAxis: {+ type: "category",+ data: themes,+ axisLine: { lineStyle: { color: theme.axisColor } },+ axisLabel: { color: theme.textColor, fontSize: 10, rotate: themes.length > 6 ? 30 : 0 },+ },+ yAxis: {+ type: "value",+ splitLine: { lineStyle: { color: theme.gridColor } },+ axisLabel: { color: theme.textColor, fontSize: 10 },+ },+ series: [+ { name: "Alive", type: "bar", stack: "n", data: aliveSeries, itemStyle: { color: theme.upColor } },+ { name: "Reversed", type: "bar", stack: "n", data: reversedSeries, itemStyle: { color: theme.warningColor } },+ { name: "Dead", type: "bar", stack: "n", data: deadSeries, itemStyle: { color: theme.downColor } },+ ],+ });++ const ro = new ResizeObserver(() => chart.resize());+ ro.observe(chartRef.current);+ return () => {+ ro.disconnect();+ chart.dispose();+ };+ }, [result, dark]);++ const totals = [+ { label: "Alive", value: result.alive, icon: CheckCircle2, tone: "text-green-600 dark:text-green-400" },+ { label: "Reversed", value: result.reversed, icon: AlertTriangle, tone: "text-amber-600 dark:text-amber-400" },+ { label: "Dead", value: result.dead, icon: XCircle, tone: "text-red-600 dark:text-red-400" },+ { label: "Skipped", value: result.skipped ?? 0, icon: Loader2, tone: "text-muted-foreground" },+ ];++ return (+ <div className="space-y-4">+ {/* Stat cards */}+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">+ {totals.map(({ label, value, icon: Icon, tone }) => (+ <div key={label} className="border rounded-xl p-4 bg-card flex items-center gap-3">+ <Icon className={cn("h-5 w-5 shrink-0", tone)} aria-hidden="true" />+ <div>+ <p className="text-xs text-muted-foreground">{label}</p>+ <p className="text-xl font-bold tabular-nums">{value}</p>+ </div>+ </div>+ ))}+ </div>++ {/* Top tables */}+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <TopTable title="Top 5 by IR" rows={result.top5_by_ir || []} />+ <TopTable title="Most reversed" rows={(result.dead_examples || []).slice(0, 3)} />+ </div>++ {/* By-theme breakdown */}+ {result.by_theme && Object.keys(result.by_theme).length > 0 && (+ <div className="border rounded-xl p-4 bg-card">+ <h3 className="text-sm font-medium text-muted-foreground mb-2">+ By theme+ </h3>+ <div ref={chartRef} style={{ height: 240 }} />+ </div>+ )}+ </div>+ );+}++function TopTable({ title, rows }: { title: string; rows: AlphaBenchTopRow[] }) {+ return (+ <div className="border rounded-xl overflow-hidden bg-card">+ <div className="px-4 py-2.5 border-b bg-muted/40">+ <h3 className="text-sm font-medium">{title}</h3>+ </div>+ {rows.length === 0 ? (+ <div className="px-4 py-6 text-xs text-muted-foreground text-center">+ No rows.+ </div>+ ) : (+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b">+ <th className="text-left px-4 py-2 text-xs text-muted-foreground font-medium">ID</th>+ <th className="text-right px-4 py-2 text-xs text-muted-foreground font-medium">Mean IC</th>+ <th className="text-right px-4 py-2 text-xs text-muted-foreground font-medium">IR</th>+ <th className="text-left px-4 py-2 text-xs text-muted-foreground font-medium">Theme</th>+ <th className="text-left px-4 py-2 text-xs text-muted-foreground font-medium">Category</th>+ </tr>+ </thead>+ <tbody>+ {rows.map((r) => (+ <tr key={r.id} className="border-b last:border-0 hover:bg-muted/20">+ <td className="px-4 py-2">+ <Link+ to={`/alpha-zoo/${encodeURIComponent(r.id)}`}+ className="text-primary hover:underline font-mono text-xs"+ >+ {r.id}+ </Link>+ </td>+ <td className="px-4 py-2 text-right font-mono tabular-nums text-xs">{fmtNum(r.ic_mean)}</td>+ <td className="px-4 py-2 text-right font-mono tabular-nums text-xs">{fmtNum(r.ir)}</td>+ <td className="px-4 py-2 text-xs text-muted-foreground">{(r.theme || []).join(", ") || "—"}</td>+ <td className="px-4 py-2 text-xs">+ <CategoryBadge category={r.category} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ );+}++/**+ * Render the alpha bench category as a colored badge so users can see whether+ * a row is alive / reversed / dead at a glance. The "Most reversed" panel+ * mixes reversed + dead rows; the badge keeps them distinguishable.+ */+function CategoryBadge({ category }: { category: AlphaBenchTopRow["category"] }) {+ const tone =+ category === "alive"+ ? "bg-green-500/10 text-green-700 dark:text-green-300"+ : category === "reversed"+ ? "bg-amber-500/10 text-amber-700 dark:text-amber-300"+ : "bg-red-500/10 text-red-700 dark:text-red-300";+ return (+ <span className={cn("inline-block px-2 py-0.5 rounded-full text-[10px] font-medium", tone)}>+ {category}+ </span>+ );+}diff --git a/frontend/src/router.tsx b/frontend/src/router.tsxindex ec3ee86f5..77ace6e55 100644--- a/frontend/src/router.tsx+++ b/frontend/src/router.tsx@@ -16,6 +16,9 @@ const Settings = lazy(() =>const Correlation = lazy(() =>import("@/pages/Correlation").then((m) => ({ default: m.Correlation })),);+const AlphaZoo = lazy(() =>+ import("@/pages/AlphaZoo").then((m) => ({ default: m.AlphaZoo })),+);function PageLoader() {return (@@ -43,6 +46,9 @@ export const router = createBrowserRouter([{ path: "/runs/:runId", element: wrap(RunDetail) },{ path: "/compare", element: wrap(Compare) },{ path: "/correlation", element: wrap(Correlation) },+ { path: "/alpha-zoo", element: wrap(AlphaZoo) },+ { path: "/alpha-zoo/bench", element: wrap(AlphaZoo) },+ { path: "/alpha-zoo/:alphaId", element: wrap(AlphaZoo) },],},]);