Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(factors): add alpha compare across CLI, REST, Web UI and agent tool

Haozhe Wub110bdc3b250
diff --git a/agent/src/api/alpha_routes.py b/agent/src/api/alpha_routes.py
index be5e5ffac..0f3f938c1 100644
--- a/agent/src/api/alpha_routes.py
+++ b/agent/src/api/alpha_routes.py
@@ -10,6 +10,8 @@ Routes (auth via the caller-supplied ``require_auth`` /
- ``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
+- ``POST /alpha/compare`` — kick off a head-to-head of >= 2 alphas (job_id)
+- ``GET /alpha/compare/{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
@@ -49,6 +51,7 @@ logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
ALPHA_BENCH_JOBS: dict[str, dict[str, Any]] = {}
+ALPHA_COMPARE_JOBS: dict[str, dict[str, Any]] = {}
_JOBS_LOCK = threading.Lock()
# Live background bench tasks. Holding strong refs prevents the asyncio GC from
@@ -67,6 +70,12 @@ MAX_CONCURRENT_BENCHES = 2
_BENCH_SEMAPHORE: asyncio.Semaphore | None = None
_BENCH_SEMAPHORE_LOCK = threading.Lock()
+# Compare is lighter than a full zoo bench (a handful of named alphas) but still
+# loads the universe panel, so it gets its own modest concurrency cap.
+MAX_CONCURRENT_COMPARES = 2
+_COMPARE_SEMAPHORE: asyncio.Semaphore | None = None
+_COMPARE_SEMAPHORE_LOCK = threading.Lock()
+
def _get_bench_semaphore() -> asyncio.Semaphore:
"""Return the process-wide bench semaphore, building it on first call."""
@@ -77,6 +86,15 @@ def _get_bench_semaphore() -> asyncio.Semaphore:
return _BENCH_SEMAPHORE
+def _get_compare_semaphore() -> asyncio.Semaphore:
+ """Return the process-wide compare semaphore, building it on first call."""
+ global _COMPARE_SEMAPHORE
+ with _COMPARE_SEMAPHORE_LOCK:
+ if _COMPARE_SEMAPHORE is None:
+ _COMPARE_SEMAPHORE = asyncio.Semaphore(MAX_CONCURRENT_COMPARES)
+ return _COMPARE_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}$")
@@ -89,6 +107,10 @@ _VALID_THEMES = {
"liquidity", "microstructure", "sentiment", "growth", "leverage",
}
_VALID_UNIVERSES = {"equity_us", "equity_cn", "equity_hk", "crypto", "futures"}
+# Ranking metrics for /alpha/compare — keep in sync with
+# ``src.factors.compare_runner.SORT_KEYS`` (kept local to avoid a heavy import).
+_VALID_SORTS = {"ir", "ic_mean", "ic_positive_ratio", "ic_count"}
+_BENCH_UNIVERSES = {"csi300", "sp500", "btc-usdt"}
def _now_iso() -> str:
@@ -106,16 +128,17 @@ def _safe_error(exc: BaseException) -> str:
def _prune_old_jobs() -> None:
- """Drop completed/errored jobs older than ``_JOB_TTL_SECONDS``."""
+ """Drop completed/errored bench + compare 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)
+ for store in (ALPHA_BENCH_JOBS, ALPHA_COMPARE_JOBS):
+ stale = [
+ jid for jid, job in store.items()
+ if job.get("status") in ("done", "error")
+ and job.get("_finished_at", 0) < cutoff
+ ]
+ for jid in stale:
+ store.pop(jid, None)
# ---------------------------------------------------------------------------
@@ -143,25 +166,67 @@ class BenchRequest(BaseModel):
@field_validator("universe")
@classmethod
def _universe_known(cls, v: str) -> str:
- allowed = {"csi300", "sp500", "btc-usdt"}
- if v not in allowed:
+ if v not in _BENCH_UNIVERSES:
+ raise ValueError(
+ f"unknown universe {v!r}; expected one of {sorted(_BENCH_UNIVERSES)}"
+ )
+ return v
+
+
+class CompareRequest(BaseModel):
+ """POST /alpha/compare body — a head-to-head of >= 2 named alphas."""
+
+ alpha_ids: list[str] = Field(..., min_length=2, max_length=50)
+ universe: str = Field(..., min_length=1, max_length=64)
+ period: str = Field(..., min_length=4, max_length=32)
+ sort: str = Field("ir", min_length=1, max_length=32)
+
+ @field_validator("alpha_ids")
+ @classmethod
+ def _ids_well_formed(cls, v: list[str]) -> list[str]:
+ # De-duplicate (preserve order) and validate each id shape.
+ seen: set[str] = set()
+ out: list[str] = []
+ for aid in v:
+ if not _ALPHA_ID_RE.fullmatch(aid or ""):
+ raise ValueError(f"invalid alpha_id {aid!r}")
+ if aid not in seen:
+ seen.add(aid)
+ out.append(aid)
+ if len(out) < 2:
+ raise ValueError("need at least 2 distinct alpha_ids to compare")
+ return out
+
+ @field_validator("universe")
+ @classmethod
+ def _universe_known(cls, v: str) -> str:
+ if v not in _BENCH_UNIVERSES:
raise ValueError(
- f"unknown universe {v!r}; expected one of {sorted(allowed)}"
+ f"unknown universe {v!r}; expected one of {sorted(_BENCH_UNIVERSES)}"
)
return v
+ @field_validator("sort")
+ @classmethod
+ def _sort_known(cls, v: str) -> str:
+ if v not in _VALID_SORTS:
+ raise ValueError(f"unknown sort {v!r}; expected one of {sorted(_VALID_SORTS)}")
+ return v
+
# ---------------------------------------------------------------------------
# Bench worker (runs in a thread; LLM-free, pandas-heavy)
# ---------------------------------------------------------------------------
-def _make_progress_cb(job_id: str) -> Callable[[int, int, str], None]:
+def _make_progress_cb(
+ job_id: str, jobs: dict[str, dict[str, Any]] = ALPHA_BENCH_JOBS
+) -> 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)
+ job = jobs.get(job_id)
if job is None:
return
job["progress"] = {
@@ -223,6 +288,54 @@ def _run_bench_blocking(job_id: str, zoo: str, universe: str, period: str, top:
job["_finished_at"] = time.time()
+def _run_compare_blocking(
+ job_id: str, alpha_ids: list[str], universe: str, period: str, sort: str
+) -> None:
+ """Synchronous compare worker (called via ``asyncio.to_thread``).
+
+ Unlike bench, the comparison's product IS the per-alpha ranking, so the full
+ (already-slim) envelope is stored as the job result.
+ """
+ from src.factors.compare_runner import compare_alphas # local import: heavy deps
+
+ with _JOBS_LOCK:
+ job = ALPHA_COMPARE_JOBS.get(job_id)
+ if job is not None:
+ job["status"] = "running"
+
+ try:
+ result = compare_alphas(
+ alpha_ids,
+ universe,
+ period,
+ sort=sort,
+ on_progress=_make_progress_cb(job_id, ALPHA_COMPARE_JOBS),
+ )
+ except Exception as exc: # noqa: BLE001 — worker must never crash the loop
+ logger.exception("alpha compare worker crashed (job=%s)", job_id)
+ with _JOBS_LOCK:
+ job = ALPHA_COMPARE_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_COMPARE_JOBS.get(job_id)
+ if job is None:
+ return
+ if result.get("status") != "ok":
+ job["status"] = "error"
+ # compare_alphas' error string is curated (too few ids, nothing
+ # evaluable, bubbled bench error) — safe to surface.
+ job["error"] = result.get("error", "unknown")
+ else:
+ job["status"] = "done"
+ job["result"] = result
+ job["_finished_at"] = time.time()
+
+
# ---------------------------------------------------------------------------
# Registration
# ---------------------------------------------------------------------------
@@ -457,69 +570,177 @@ def register_alpha_routes(
"""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")
+ return _job_event_stream(ALPHA_BENCH_JOBS, job_id, request, _result_for_wire)
- async def event_stream():
- last_n_done = -1
- last_emit = time.monotonic()
- while True:
- if await request.is_disconnected():
- return
+ # -----------------------------------------------------------------------
+ # POST /alpha/compare
+ # -----------------------------------------------------------------------
+
+ @app.post(
+ "/alpha/compare",
+ status_code=202,
+ dependencies=[Depends(require_auth)],
+ )
+ async def kick_off_compare(payload: CompareRequest) -> dict[str, Any]:
+ """Queue a background head-to-head comparison and return a job_id."""
+ 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}")
+
+ sem = _get_compare_semaphore()
+ if sem.locked() or getattr(sem, "_value", MAX_CONCURRENT_COMPARES) <= 0:
+ raise HTTPException(
+ status_code=429,
+ detail="too many running comparisons; wait for one to finish",
+ )
- 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"),
- },
+ _prune_old_jobs()
+
+ job_id = uuid.uuid4().hex
+ with _JOBS_LOCK:
+ ALPHA_COMPARE_JOBS[job_id] = {
+ "job_id": job_id,
+ "status": "queued",
+ "alpha_ids": payload.alpha_ids,
+ "universe": payload.universe,
+ "period": payload.period,
+ "sort": payload.sort,
+ "created_at": _now_iso(),
+ "progress": {"n_done": 0, "n_total": len(payload.alpha_ids), "current_alpha_id": None},
+ "result": None,
+ "error": None,
+ }
+
+ async def _runner() -> None:
+ async with sem:
+ try:
+ await asyncio.to_thread(
+ _run_compare_blocking,
+ job_id,
+ payload.alpha_ids,
+ payload.universe,
+ payload.period,
+ payload.sort,
)
- return
- if status == "error":
- yield _sse("error", {"message": error or "unknown error"})
+ except Exception: # noqa: BLE001 — never escape the loop
+ logger.exception("compare runner outer task crashed (job=%s)", job_id)
+ with _JOBS_LOCK:
+ job = ALPHA_COMPARE_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/compare/{job_id}/stream
+ # -----------------------------------------------------------------------
+
+ @app.get(
+ "/alpha/compare/{job_id}/stream",
+ dependencies=[Depends(require_event_stream_auth)],
+ )
+ async def stream_compare(job_id: str, request: Request) -> StreamingResponse:
+ """SSE: progress / result / done / error until the comparison 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_COMPARE_JOBS:
+ raise HTTPException(status_code=404, detail=f"job {job_id} not found")
+ return _job_event_stream(ALPHA_COMPARE_JOBS, job_id, request, _compare_result_for_wire)
+
+
+# ---------------------------------------------------------------------------
+# Streaming helpers (shared bench + compare SSE loop)
+# ---------------------------------------------------------------------------
+
+
+def _job_event_stream(
+ jobs: dict[str, dict[str, Any]],
+ job_id: str,
+ request: Request,
+ project_result: Callable[[dict[str, Any]], dict[str, Any]],
+) -> StreamingResponse:
+ """Shared SSE loop for bench + compare jobs.
+
+ Emits ``progress`` whenever ``n_done`` advances, then a single ``result``
+ (projected onto the wire contract via ``project_result``) followed by
+ ``done`` on success, or ``error`` + ``done`` on failure. A heartbeat comment
+ frame every ~15s keeps idle proxies from dropping the connection.
+ """
+
+ async def event_stream():
+ last_n_done = -1
+ last_emit = time.monotonic()
+ while True:
+ if await request.is_disconnected():
+ return
+
+ with _JOBS_LOCK:
+ job = 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")
+
+ 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", project_result(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",
- },
- )
+ 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",
+ },
+ )
+
+
+def _compare_result_for_wire(result: dict[str, Any]) -> dict[str, Any]:
+ """Project the compare envelope onto the `result` event.
+
+ The comparison envelope is already slim (a small ranking of user-selected
+ alphas + skipped list), so we forward it whole minus the redundant top-level
+ ``status`` (the SSE event type already conveys success).
+ """
+ return {k: v for k, v in result.items() if k != "status"}
# ---------------------------------------------------------------------------
diff --git a/agent/src/factors/bench_runner.py b/agent/src/factors/bench_runner.py
index 394a36950..c957f4927 100644
--- a/agent/src/factors/bench_runner.py
+++ b/agent/src/factors/bench_runner.py
@@ -18,7 +18,7 @@ from __future__ import annotations
import logging
import math
import time
-from typing import Any, Callable
+from typing import Any, Callable, Iterable
from src.factors.factor_analysis_core import compute_ic_series
from src.factors.registry import (
@@ -77,6 +77,7 @@ def run_bench(
top: int = 20,
on_progress: ProgressCb | None = None,
registry: Registry | None = None,
+ only: Iterable[str] | None = None,
) -> dict[str, Any]:
"""Run a bench end-to-end and return the API-shaped summary.
@@ -91,6 +92,10 @@ def run_bench(
(success or skip). Signature: ``(n_done, n_total, alpha_id)``.
registry: Optional pre-built registry (test injection); defaults to a
fresh ``Registry()``.
+ only: Optional subset of alpha ids to evaluate. When provided, the zoo's
+ alpha list is restricted to this set — used by ``alpha compare`` to
+ bench just a handful of named alphas instead of the whole zoo. Ids
+ not registered under ``zoo`` are silently dropped from the subset.
Returns:
Dict with keys: ``status``, ``zoo``, ``universe``, ``period``,
@@ -114,6 +119,15 @@ def run_bench(
entry["wall_seconds"] = round(time.monotonic() - start, 2)
return entry
+ if only is not None:
+ only_set = {str(aid) for aid in only}
+ alpha_ids = [aid for aid in alpha_ids if aid in only_set]
+ if not alpha_ids:
+ entry["status"] = "error"
+ entry["error"] = f"none of the requested alphas are registered under zoo={zoo!r}"
+ entry["wall_seconds"] = round(time.monotonic() - start, 2)
+ return entry
+
try:
panel = _load_universe_panel(universe, period)
except (ValueError, NotImplementedError, RuntimeError) as exc:
diff --git a/agent/src/factors/cli_handlers.py b/agent/src/factors/cli_handlers.py
index 926b49fbc..7ae72adaf 100644
--- a/agent/src/factors/cli_handlers.py
+++ b/agent/src/factors/cli_handlers.py
@@ -64,6 +64,7 @@ except Exception: # pragma: no cover — rich is a project dep, fallback only
TextColumn = None # type: ignore[assignment]
TimeElapsedColumn = None # type: ignore[assignment]
+from src.factors.compare_runner import SORT_KEYS as _COMPARE_SORT_KEYS, compare_alphas
from src.factors.registry import Registry, RegistryError
@@ -696,13 +697,43 @@ def cmd_alpha_bench(args: argparse.Namespace) -> int:
return _handle_exception(args, "alpha bench failed", exc)
+def _render_compare_table(ranking: list[dict[str, Any]], sort_key: str) -> None:
+ """Print a head-to-head ranking table to stderr (nice-to-have, never fatal)."""
+ if _stderr_console is None or Table is None:
+ return
+ delta_key = f"delta_{sort_key}_vs_best"
+ table = Table(title=f"alpha compare — ranked by {sort_key}")
+ for col, justify in (
+ ("#", "right"), ("alpha", "left"), ("zoo", "left"), ("IC mean", "right"),
+ ("IC std", "right"), ("IR", "right"), ("IC>0", "right"), ("n", "right"),
+ (f"Δ {sort_key}", "right"),
+ ):
+ table.add_column(col, justify=justify)
+ for r in ranking:
+ table.add_row(
+ str(r["rank"]),
+ str(r["id"]),
+ str(r.get("zoo") or ""),
+ f"{r.get('ic_mean', 0.0):.4f}",
+ f"{r.get('ic_std', 0.0):.4f}",
+ f"{r.get('ir', 0.0):.4f}",
+ f"{r.get('ic_positive_ratio', 0.0):.3f}",
+ str(r.get("ic_count", 0)),
+ f"{r.get(delta_key, 0.0):+.4f}",
+ )
+ _stderr_console.print(table)
+
+
def cmd_alpha_compare(args: argparse.Namespace) -> int:
- """``vibe-trading alpha compare <id1> [<id2> ...] | --all | --zoo X``.
+ """``vibe-trading alpha compare <id1> <id2> ... | --all | --zoo X``.
- Stub for W4; reports validated targets so callers can wire scripts.
+ Bench a hand-picked set of alphas head-to-head and print a ranked
+ comparison (IC mean/std, IR, IC>0 ratio, sample count) plus a JSON
+ envelope. Only the named alphas are evaluated — the zoo-wide loop is
+ restricted via ``run_bench(only=...)`` — so comparing three alphas does
+ not bench all 191 in their zoo.
"""
try:
- targets: list[str]
reg = Registry()
if getattr(args, "compare_all", False):
targets = reg.list()
@@ -711,20 +742,45 @@ def cmd_alpha_compare(args: argparse.Namespace) -> int:
else:
targets = list(args.alpha_ids or [])
+ # De-duplicate, preserving first-seen order.
+ seen: set[str] = set()
+ targets = [t for t in targets if not (t in seen or seen.add(t))]
+
if not targets:
_err(
"alpha compare: no targets supplied "
"(pass alpha ids, or --all for every alpha, or --zoo X to filter)"
)
return 1
+ if len(targets) < 2:
+ _err(
+ f"alpha compare: need at least 2 alphas to compare "
+ f"(got {len(targets)}: {', '.join(targets)})"
+ )
+ 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)"
+ sort_key = getattr(args, "sort", "ir") or "ir"
+ envelope = compare_alphas(
+ targets, args.universe, args.period, sort=sort_key, registry=reg
+ )
+ print(json.dumps(envelope, indent=2, default=str))
+
+ if envelope.get("status") != "ok":
+ _err(f"alpha compare: {envelope.get('error', 'comparison failed')}")
+ return 1
+
+ ranking = envelope["ranking"]
+ _render_compare_table(ranking, sort_key)
+ summary = (
+ f"✓ Compared {envelope['n_compared']} alphas — winner: {envelope['winner']} "
+ f"({sort_key}={ranking[0].get(sort_key, 0.0):.4f})"
)
- print(json.dumps({"status": "stub", "targets": targets, "reason": "W4 not implemented"}, indent=2))
+ if envelope["n_skipped"]:
+ summary += f"; {envelope['n_skipped']} skipped"
+ 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 compare failed", exc)
@@ -868,8 +924,8 @@ def add_subparser(subparsers: Any) -> argparse.ArgumentParser:
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 = alpha_sub.add_parser("compare", help="Compare alphas head-to-head")
+ p_compare.add_argument("alpha_ids", nargs="*", help="Alpha ids to compare (>= 2)")
p_compare.add_argument(
"--all",
dest="compare_all",
@@ -881,6 +937,23 @@ def add_subparser(subparsers: Any) -> argparse.ArgumentParser:
default=None,
help="Filter comparison to one zoo (e.g. alpha101)",
)
+ p_compare.add_argument(
+ "--universe",
+ default="csi300",
+ choices=_UNIVERSE_CHOICES,
+ help=f"Universe (default: csi300; one of {', '.join(_UNIVERSE_CHOICES)})",
+ )
+ p_compare.add_argument(
+ "--period",
+ default="2020-2025",
+ help="Period spec: YYYY-YYYY or YYYY-MM-DD/YYYY-MM-DD (e.g. 2020-2025)",
+ )
+ p_compare.add_argument(
+ "--sort",
+ default="ir",
+ choices=list(_COMPARE_SORT_KEYS),
+ help=f"Rank by which metric (default: ir; one of {', '.join(_COMPARE_SORT_KEYS)})",
+ )
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")
diff --git a/agent/src/factors/compare_runner.py b/agent/src/factors/compare_runner.py
new file mode 100644
index 000000000..e6f2a3ff0
--- /dev/null
+++ b/agent/src/factors/compare_runner.py
@@ -0,0 +1,209 @@
+"""Head-to-head comparison of hand-picked alphas.
+
+Shared core behind the three ``alpha compare`` surfaces:
+
+* ``vibe-trading alpha compare`` (CLI — ``factors/cli_handlers.py``)
+* ``POST /alpha/compare`` (Web UI — ``api/alpha_routes.py``)
+* the ``alpha_compare`` agent tool (``tools/alpha_compare_tool.py``)
+
+All three resolve a list of alpha ids and delegate the actual work here so the
+grouping / bench / ranking logic lives in exactly one place. The core groups the
+requested ids by their owning zoo, benches only those ids via
+``run_bench(only=...)`` (so comparing three alphas does not bench all 191 in a
+zoo), merges the per-alpha IC rows, and ranks them by a chosen metric with a
+``delta_<metric>_vs_best`` column.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Callable, Iterable
+
+from src.factors import bench_runner
+from src.factors.registry import Registry
+
+logger = logging.getLogger(__name__)
+
+#: Metrics a comparison can be ranked by (descending — higher is "better").
+SORT_KEYS: tuple[str, ...] = ("ir", "ic_mean", "ic_positive_ratio", "ic_count")
+
+#: Progress callback shape, identical to ``bench_runner.ProgressCb``:
+#: ``(n_done, n_total, alpha_id) -> None``, reported across the whole comparison
+#: (not per-zoo) so a UI sees one monotonic 0..N bar.
+ProgressCb = Callable[[int, int, str], None]
+
+
+def _sort_value(row: dict[str, Any], key: str) -> float:
+ """Numeric sort value for a bench row; missing/garbage coerces to 0.0."""
+ try:
+ return float(row.get(key, 0.0) or 0.0)
+ except (TypeError, ValueError):
+ return 0.0
+
+
+def _normalise_skip(skip: dict[str, Any]) -> dict[str, Any]:
+ """Shape a bench-skipped entry for the compare envelope."""
+ return {"id": skip.get("id") or skip.get("alpha_id"), "reason": skip.get("reason", "")}
+
+
+def _zoo_of(reg: Registry, alpha_id: str) -> str:
+ """Look up an alpha's owning zoo (best-effort; '' when unknown)."""
+ try:
+ return reg.get(alpha_id).zoo
+ except Exception: # noqa: BLE001 — unknown id is a normal "skipped" outcome
+ return ""
+
+
+def _zoo_progress_cb(on_progress: ProgressCb | None, base: int, total: int) -> bench_runner.ProgressCb | None:
+ """Wrap a global progress callback so a per-zoo bench reports global counts."""
+ if on_progress is None:
+ return None
+
+ def _cb(n_done: int, _n_total: int, alpha_id: str) -> None:
+ try:
+ on_progress(base + n_done, total, alpha_id)
+ except Exception: # noqa: BLE001 — progress must never break the loop
+ logger.exception("compare on_progress callback raised; ignoring")
+
+ return _cb
+
+
+def _error_envelope(
+ *, error: str, universe: str, period: str, sort: str, skipped: list[dict[str, Any]]
+) -> dict[str, Any]:
+ """Build the ``status="error"`` envelope with the standard key set."""
+ return {
+ "status": "error",
+ "error": error,
+ "universe": universe,
+ "period": period,
+ "sort": sort,
+ "n_compared": 0,
+ "n_skipped": len(skipped),
+ "ranking": [],
+ "skipped": skipped,
+ }
+
+
+def compare_alphas(
+ alpha_ids: Iterable[str],
+ universe: str,
+ period: str,
+ *,
+ sort: str = "ir",
+ registry: Registry | None = None,
+ on_progress: ProgressCb | None = None,
+) -> dict[str, Any]:
+ """Bench a hand-picked set of alphas head-to-head and rank them.
+
+ Args:
+ alpha_ids: The alpha ids to compare (>= 2 after de-duplication). Ids not
+ found in the registry are reported under ``skipped``, not raised.
+ universe: Universe key (``csi300`` / ``sp500`` / ``btc-usdt``).
+ period: ``YYYY-YYYY`` or ``YYYY-MM-DD/YYYY-MM-DD`` window.
+ sort: Ranking metric — one of :data:`SORT_KEYS` (default ``"ir"``).
+ An unrecognised value falls back to ``"ir"``.
+ registry: Optional pre-built registry (test injection); defaults to a
+ fresh :class:`Registry`.
+ on_progress: Optional ``(n_done, n_total, alpha_id)`` callback fired once
+ per evaluated alpha, counting across the whole comparison.
+
+ Returns:
+ On success, ``status="ok"`` with ``universe``, ``period``, ``sort``,
+ ``n_compared``, ``n_skipped``, ``winner``, ``ranking`` (list of
+ ``{rank, id, zoo, ic_mean, ic_std, ir, ic_positive_ratio, ic_count,
+ delta_<sort>_vs_best}`` sorted best-first) and ``skipped``. On failure
+ (fewer than two resolvable ids, or no alpha could be evaluated),
+ ``status="error"`` with an ``error`` message and the same key set.
+ """
+ reg = registry if registry is not None else Registry()
+ if sort not in SORT_KEYS:
+ sort = "ir"
+
+ # De-duplicate, preserving first-seen order.
+ seen: set[str] = set()
+ ids = [a for a in alpha_ids if not (a in seen or seen.add(a))]
+
+ if len(ids) < 2:
+ return _error_envelope(
+ error=f"need at least 2 alphas to compare (got {len(ids)})",
+ universe=universe,
+ period=period,
+ sort=sort,
+ skipped=[],
+ )
+
+ # Group requested ids by owning zoo; flag unknown ids as skipped.
+ by_zoo: dict[str, list[str]] = {}
+ skipped: list[dict[str, Any]] = []
+ for aid in ids:
+ zoo = _zoo_of(reg, aid)
+ if zoo:
+ by_zoo.setdefault(zoo, []).append(aid)
+ else:
+ skipped.append({"id": aid, "reason": "unknown alpha id (not in registry)"})
+
+ total = sum(len(v) for v in by_zoo.values())
+ rows: list[dict[str, Any]] = []
+ base = 0
+ for zoo, zids in sorted(by_zoo.items()):
+ sub = bench_runner.run_bench(
+ zoo=zoo,
+ universe=universe,
+ period=period,
+ top=len(zids),
+ only=zids,
+ registry=reg,
+ on_progress=_zoo_progress_cb(on_progress, base, total),
+ )
+ if sub.get("status") == "ok":
+ for raw in sub.get("rows", []) or []:
+ row = dict(raw)
+ row.setdefault("zoo", zoo)
+ rows.append(row)
+ skipped.extend(sub.get("skipped", []) or [])
+ else:
+ reason = sub.get("error", "bench failed")
+ skipped.extend({"id": aid, "reason": reason} for aid in zids)
+ base += len(zids)
+
+ skipped = [_normalise_skip(s) for s in skipped]
+
+ if not rows:
+ return _error_envelope(
+ error="no requested alphas could be evaluated",
+ universe=universe,
+ period=period,
+ sort=sort,
+ skipped=skipped,
+ )
+
+ rows_sorted = sorted(rows, key=lambda r: _sort_value(r, sort), reverse=True)
+ best = _sort_value(rows_sorted[0], sort)
+ delta_key = f"delta_{sort}_vs_best"
+ ranking = [
+ {
+ "rank": rank,
+ "id": row.get("id"),
+ "zoo": row.get("zoo"),
+ "ic_mean": row.get("ic_mean", 0.0),
+ "ic_std": row.get("ic_std", 0.0),
+ "ir": row.get("ir", 0.0),
+ "ic_positive_ratio": row.get("ic_positive_ratio", 0.0),
+ "ic_count": row.get("ic_count", 0),
+ delta_key: round(_sort_value(row, sort) - best, 6),
+ }
+ for rank, row in enumerate(rows_sorted, start=1)
+ ]
+
+ return {
+ "status": "ok",
+ "universe": universe,
+ "period": period,
+ "sort": sort,
+ "n_compared": len(ranking),
+ "n_skipped": len(skipped),
+ "winner": ranking[0]["id"],
+ "ranking": ranking,
+ "skipped": skipped,
+ }
diff --git a/agent/src/tools/alpha_compare_tool.py b/agent/src/tools/alpha_compare_tool.py
new file mode 100644
index 000000000..1e9d1ecb3
--- /dev/null
+++ b/agent/src/tools/alpha_compare_tool.py
@@ -0,0 +1,113 @@
+"""Agent tool: head-to-head comparison of hand-picked Alpha Zoo alphas.
+
+Thin wrapper over :func:`src.factors.compare_runner.compare_alphas` — the same
+core behind ``vibe-trading alpha compare`` (CLI) and ``POST /alpha/compare``
+(Web UI). Auto-discovered and registered via ``BaseTool.__subclasses__()``.
+
+Read-only: it computes IC/IR for the named alphas and ranks them; it writes no
+files and places no orders.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Any
+
+from src.agent.tools import BaseTool
+from src.factors.compare_runner import SORT_KEYS, compare_alphas
+
+
+def _coerce_ids(raw: Any) -> list[str]:
+ """Normalise the ``alpha_ids`` argument to a clean list of ids.
+
+ Accepts a list (the contract) or a comma/space-separated string (LLMs
+ occasionally inline the list), de-duplicating while preserving order.
+
+ Args:
+ raw: The ``alpha_ids`` value as supplied by the caller.
+
+ Returns:
+ Ordered, de-duplicated list of non-empty id strings.
+ """
+ items = re.split(r"[\s,]+", raw) if isinstance(raw, str) else (raw or [])
+ seen: set[str] = set()
+ out: list[str] = []
+ for item in items:
+ aid = str(item).strip()
+ if aid and aid not in seen:
+ seen.add(aid)
+ out.append(aid)
+ return out
+
+
+class AlphaCompareTool(BaseTool):
+ """Compare >= 2 named alphas head-to-head and rank them by an IC metric."""
+
+ name = "alpha_compare"
+ description = (
+ "Compare a hand-picked set of Alpha Zoo alphas (alpha_ids, >= 2) "
+ "head-to-head on a universe over a period. Benches only the named "
+ "alphas — not the whole zoo — then ranks them by IC mean/std, IR, "
+ "IC-positive ratio and sample count, with each alpha's gap to the "
+ "leader. Returns the ranking + a winner; no per-stock per-date payloads."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "alpha_ids": {
+ "type": "array",
+ "items": {"type": "string"},
+ "minItems": 2,
+ "description": "Alpha ids to compare, e.g. ['alpha101_1', 'gtja191_5'].",
+ },
+ "universe": {
+ "type": "string",
+ "description": "csi300 | sp500 | btc-usdt.",
+ },
+ "period": {
+ "type": "string",
+ "description": "YYYY-YYYY or YYYY-MM-DD/YYYY-MM-DD.",
+ },
+ "sort": {
+ "type": "string",
+ "enum": list(SORT_KEYS),
+ "default": "ir",
+ "description": "Ranking metric (default ir).",
+ },
+ },
+ "required": ["alpha_ids", "universe", "period"],
+ }
+ repeatable = True
+ is_readonly = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Run the comparison and return the JSON envelope.
+
+ Args:
+ **kwargs: ``alpha_ids`` (list[str]), ``universe`` (str),
+ ``period`` (str), optional ``sort`` (str).
+
+ Returns:
+ JSON string — on success ``status="ok"`` with a ranking + winner;
+ on failure ``status="error"`` with a message.
+ """
+ alpha_ids = _coerce_ids(kwargs.get("alpha_ids"))
+ universe = str(kwargs.get("universe", "")).strip()
+ period = str(kwargs.get("period", "")).strip()
+ sort = str(kwargs.get("sort") or "ir").strip()
+
+ if not universe or not period:
+ return json.dumps(
+ {"status": "error", "error": "universe and period are required"},
+ ensure_ascii=False,
+ )
+
+ try:
+ envelope = compare_alphas(alpha_ids, universe, period, sort=sort)
+ except Exception as exc: # noqa: BLE001 — surface a clean tool error
+ return json.dumps(
+ {"status": "error", "error": f"alpha compare failed: {exc}"},
+ ensure_ascii=False,
+ )
+ return json.dumps(envelope, ensure_ascii=False, default=str)
diff --git a/agent/tests/factors/test_alpha_compare.py b/agent/tests/factors/test_alpha_compare.py
new file mode 100644
index 000000000..e5e916f49
--- /dev/null
+++ b/agent/tests/factors/test_alpha_compare.py
@@ -0,0 +1,352 @@
+"""Unit + integration tests for ``vibe-trading alpha compare``.
+
+Two layers are covered:
+
+1. **``run_bench(only=...)`` filter** — the small backward-compatible rail that
+ restricts a zoo's IC loop to a named subset, so ``compare`` benches just the
+ handful of alphas asked for. Exercised with a registry-injected, panel-stubbed
+ integration test (no network — factors tests run socket-disabled).
+2. **``cmd_alpha_compare`` handler** — target resolution (ids / ``--all`` /
+ ``--zoo``), de-duplication, the ``<2`` guard, cross-zoo grouping, ranking +
+ ``delta_*_vs_best`` math, alternate ``--sort`` keys, unknown-id skipping, and
+ the all-skipped error envelope. ``run_bench`` and ``Registry`` are stubbed so
+ the handler logic is tested in isolation from the bench math.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from typing import Any
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from src.factors import cli_handlers, compare_runner
+from src.factors.bench_runner import run_bench
+
+
+# ── run_bench(only=...) integration ─────────────────────────────────────────
+
+
+class _ThreeAlphaRegistry:
+ """Registry stub exposing the slice ``run_bench`` uses, with 3 alphas."""
+
+ def __init__(self) -> None:
+ self._ids = ["a_one", "a_two", "a_three"]
+
+ def list(self, *, zoo: str) -> list[str]: # noqa: ARG002
+ return list(self._ids)
+
+ def get(self, aid: str) -> Any:
+ class _Handle:
+ meta = {"theme": ["test"], "formula_latex": f"stub_{aid}"}
+
+ return _Handle()
+
+ def compute(self, aid: str, panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
+ # Distinct deterministic frame per alpha so IC series are non-empty.
+ close = panel["close"]
+ seed = self._ids.index(aid)
+ return pd.DataFrame(
+ np.random.default_rng(seed).normal(size=close.shape),
+ index=close.index,
+ columns=close.columns,
+ )
+
+
+def _stub_panel(monkeypatch: pytest.MonkeyPatch, n_rows: int = 80, n_cols: int = 8) -> None:
+ rng = np.random.default_rng(0)
+ idx = pd.date_range("2024-01-01", periods=n_rows, freq="D")
+ cols = [f"S{i}" for i in range(n_cols)]
+ close = pd.DataFrame(
+ 100.0 + np.cumsum(rng.normal(size=(n_rows, n_cols)), axis=0),
+ index=idx,
+ columns=cols,
+ )
+ panel = {
+ "close": close, "high": close * 1.01, "low": close * 0.99,
+ "open": close, "volume": close * 0 + 1_000_000,
+ "vwap": close, "amount": close * 1_000_000,
+ }
+ monkeypatch.setattr(
+ "src.factors.bench_runner._load_universe_panel",
+ lambda universe, period: panel, # noqa: ARG005
+ )
+ monkeypatch.setattr(
+ "src.factors.bench_runner._compute_forward_returns",
+ lambda panel_in: panel_in["close"].pct_change().shift(-1),
+ )
+
+
+def test_run_bench_only_restricts_to_subset(monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_panel(monkeypatch)
+ result = run_bench(
+ zoo="z", universe="csi300", period="2024-2024",
+ only=["a_two", "a_three"], registry=_ThreeAlphaRegistry(),
+ )
+ assert result["status"] == "ok"
+ benched = {r["id"] for r in result["rows"]}
+ assert benched == {"a_two", "a_three"}
+ assert "a_one" not in benched
+
+
+def test_run_bench_only_none_benches_everything(monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_panel(monkeypatch)
+ result = run_bench(
+ zoo="z", universe="csi300", period="2024-2024",
+ only=None, registry=_ThreeAlphaRegistry(),
+ )
+ assert {r["id"] for r in result["rows"]} == {"a_one", "a_two", "a_three"}
+
+
+def test_run_bench_only_unknown_ids_errors(monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_panel(monkeypatch)
+ result = run_bench(
+ zoo="z", universe="csi300", period="2024-2024",
+ only=["does_not_exist"], registry=_ThreeAlphaRegistry(),
+ )
+ assert result["status"] == "error"
+ assert "requested alphas" in result["error"]
+
+
+# ── cmd_alpha_compare handler ───────────────────────────────────────────────
+
+
+class _FakeRegistry:
+ """Maps alpha id → zoo; ``get`` raises for unknown ids (like the real one)."""
+
+ def __init__(self, id_to_zoo: dict[str, str]) -> None:
+ self._id_to_zoo = id_to_zoo
+
+ def list(self, zoo: str | None = None, **_kw: Any) -> list[str]:
+ ids = sorted(self._id_to_zoo)
+ if zoo is not None:
+ ids = [i for i in ids if self._id_to_zoo[i] == zoo]
+ return ids
+
+ def get(self, aid: str) -> Any:
+ if aid not in self._id_to_zoo:
+ raise KeyError(aid)
+ handle = argparse.Namespace()
+ handle.zoo = self._id_to_zoo[aid]
+ return handle
+
+
+def _fake_run_bench(metrics: dict[str, dict[str, Any]], *, status_by_zoo: dict[str, str] | None = None):
+ """Build a ``run_bench`` double returning canned rows for the ``only`` ids."""
+
+ def _fake(*, zoo: str, universe: str, period: str, top: int, only: list[str], registry: Any, on_progress: Any = None) -> dict[str, Any]: # noqa: ARG001
+ if status_by_zoo and zoo in status_by_zoo:
+ return {"status": "error", "error": status_by_zoo[zoo]}
+ rows, skipped = [], []
+ for aid in only:
+ if aid in metrics:
+ rows.append({"id": aid, **metrics[aid]})
+ else:
+ skipped.append({"id": aid, "reason": "empty IC series"})
+ return {"status": "ok", "zoo": zoo, "rows": rows, "skipped": skipped}
+
+ return _fake
+
+
+def _metrics(ic_mean: float, ic_std: float, ir: float, pos: float = 0.5, n: int = 200) -> dict[str, Any]:
+ return {"ic_mean": ic_mean, "ic_std": ic_std, "ir": ir, "ic_positive_ratio": pos, "ic_count": n}
+
+
+def _args(**kw: Any) -> argparse.Namespace:
+ base = {
+ "alpha_ids": [], "compare_all": False, "zoo": None,
+ "universe": "csi300", "period": "2020-2025", "sort": "ir", "verbose": False,
+ }
+ base.update(kw)
+ return argparse.Namespace(**base)
+
+
+def _wire(monkeypatch: pytest.MonkeyPatch, id_to_zoo: dict[str, str], fake_bench: Any) -> None:
+ monkeypatch.setattr(cli_handlers, "Registry", lambda: _FakeRegistry(id_to_zoo))
+ monkeypatch.setattr("src.factors.bench_runner.run_bench", fake_bench)
+
+
+def _run(capsys: pytest.CaptureFixture[str], args: argparse.Namespace) -> tuple[int, dict[str, Any]]:
+ rc = cli_handlers.cmd_alpha_compare(args)
+ out = capsys.readouterr().out
+ return rc, json.loads(out)
+
+
+def test_compare_ranks_by_ir_descending(monkeypatch, capsys) -> None:
+ id_to_zoo = {"alpha101_1": "alpha101", "alpha101_2": "alpha101", "alpha101_3": "alpha101"}
+ metrics = {
+ "alpha101_1": _metrics(0.01, 0.05, 0.20),
+ "alpha101_2": _metrics(0.03, 0.05, 0.60), # best IR
+ "alpha101_3": _metrics(0.02, 0.05, 0.40),
+ }
+ _wire(monkeypatch, id_to_zoo, _fake_run_bench(metrics))
+ rc, env = _run(capsys, _args(alpha_ids=["alpha101_1", "alpha101_2", "alpha101_3"]))
+
+ assert rc == 0
+ assert env["status"] == "ok"
+ assert env["sort"] == "ir"
+ assert [r["id"] for r in env["ranking"]] == ["alpha101_2", "alpha101_3", "alpha101_1"]
+ assert env["winner"] == "alpha101_2"
+ assert env["ranking"][0]["delta_ir_vs_best"] == 0.0
+ assert env["ranking"][1]["delta_ir_vs_best"] == pytest.approx(-0.20)
+ assert env["ranking"][2]["delta_ir_vs_best"] == pytest.approx(-0.40)
+ assert env["n_compared"] == 3
+ assert env["n_skipped"] == 0
+
+
+def test_compare_alternate_sort_key_reorders(monkeypatch, capsys) -> None:
+ id_to_zoo = {"a": "alpha101", "b": "alpha101"}
+ # b wins on IR but a wins on ic_mean — sorting by ic_mean flips the winner.
+ metrics = {"a": _metrics(0.09, 0.05, 0.20), "b": _metrics(0.04, 0.05, 0.80)}
+ _wire(monkeypatch, id_to_zoo, _fake_run_bench(metrics))
+ rc, env = _run(capsys, _args(alpha_ids=["a", "b"], sort="ic_mean"))
+
+ assert rc == 0
+ assert env["sort"] == "ic_mean"
+ assert env["winner"] == "a"
+ assert "delta_ic_mean_vs_best" in env["ranking"][0]
+ assert env["ranking"][1]["delta_ic_mean_vs_best"] == pytest.approx(-0.05)
+
+
+def test_compare_groups_across_zoos(monkeypatch, capsys) -> None:
+ id_to_zoo = {"alpha101_1": "alpha101", "gtja191_5": "gtja191"}
+ metrics = {"alpha101_1": _metrics(0.02, 0.05, 0.40), "gtja191_5": _metrics(0.03, 0.05, 0.60)}
+
+ calls: list[tuple[str, tuple[str, ...]]] = []
+
+ fake = _fake_run_bench(metrics)
+
+ def _tracking(*, zoo, universe, period, top, only, registry, on_progress=None): # noqa: ANN001, ARG001
+ calls.append((zoo, tuple(only)))
+ return fake(
+ zoo=zoo, universe=universe, period=period, top=top, only=only,
+ registry=registry, on_progress=on_progress,
+ )
+
+ _wire(monkeypatch, id_to_zoo, _tracking)
+ rc, env = _run(capsys, _args(alpha_ids=["alpha101_1", "gtja191_5"]))
+
+ assert rc == 0
+ # One run_bench call per zoo, each scoped to its own ids.
+ assert sorted(calls) == [("alpha101", ("alpha101_1",)), ("gtja191", ("gtja191_5",))]
+ assert {r["id"] for r in env["ranking"]} == {"alpha101_1", "gtja191_5"}
+ assert env["winner"] == "gtja191_5"
+
+
+def test_compare_unknown_id_is_skipped(monkeypatch, capsys) -> None:
+ id_to_zoo = {"known_1": "alpha101", "known_2": "alpha101"}
+ metrics = {"known_1": _metrics(0.02, 0.05, 0.40), "known_2": _metrics(0.03, 0.05, 0.60)}
+ _wire(monkeypatch, id_to_zoo, _fake_run_bench(metrics))
+ rc, env = _run(capsys, _args(alpha_ids=["known_1", "known_2", "ghost_9"]))
+
+ assert rc == 0
+ assert {r["id"] for r in env["ranking"]} == {"known_1", "known_2"}
+ skipped_ids = {s["id"] for s in env["skipped"]}
+ assert "ghost_9" in skipped_ids
+ assert env["n_skipped"] == 1
+
+
+def test_compare_dedupes_repeated_ids(monkeypatch, capsys) -> None:
+ id_to_zoo = {"a": "alpha101", "b": "alpha101"}
+ metrics = {"a": _metrics(0.02, 0.05, 0.40), "b": _metrics(0.03, 0.05, 0.60)}
+ _wire(monkeypatch, id_to_zoo, _fake_run_bench(metrics))
+ rc, env = _run(capsys, _args(alpha_ids=["a", "b", "a", "b"]))
+
+ assert rc == 0
+ assert env["n_compared"] == 2
+
+
+def test_compare_requires_at_least_two(monkeypatch, capsys) -> None:
+ _wire(monkeypatch, {"solo": "alpha101"}, _fake_run_bench({"solo": _metrics(0.02, 0.05, 0.40)}))
+ rc = cli_handlers.cmd_alpha_compare(_args(alpha_ids=["solo"]))
+ assert rc == 1
+
+
+def test_compare_no_targets_errors(monkeypatch, capsys) -> None:
+ _wire(monkeypatch, {}, _fake_run_bench({}))
+ rc = cli_handlers.cmd_alpha_compare(_args(alpha_ids=[]))
+ assert rc == 1
+
+
+def test_compare_all_evaluations_skipped_errors(monkeypatch, capsys) -> None:
+ id_to_zoo = {"a": "alpha101", "b": "alpha101"}
+ # Bench fails for the whole zoo → both ids end up skipped, no rows.
+ fake = _fake_run_bench({}, status_by_zoo={"alpha101": "universe load failed: no token"})
+ _wire(monkeypatch, id_to_zoo, fake)
+ rc, env = _run(capsys, _args(alpha_ids=["a", "b"]))
+
+ assert rc == 1
+ assert env["status"] == "error"
+ assert env["n_skipped"] if "n_skipped" in env else True
+ assert {s["id"] for s in env["skipped"]} == {"a", "b"}
+
+
+def test_compare_all_flag_resolves_every_alpha(monkeypatch, capsys) -> None:
+ id_to_zoo = {"a": "alpha101", "b": "gtja191"}
+ metrics = {"a": _metrics(0.02, 0.05, 0.40), "b": _metrics(0.03, 0.05, 0.60)}
+ _wire(monkeypatch, id_to_zoo, _fake_run_bench(metrics))
+ rc, env = _run(capsys, _args(compare_all=True))
+
+ assert rc == 0
+ assert env["n_compared"] == 2
+
+
+def test_compare_zoo_flag_filters_targets(monkeypatch, capsys) -> None:
+ id_to_zoo = {"a": "alpha101", "b": "alpha101", "c": "gtja191"}
+ metrics = {k: _metrics(0.02, 0.05, 0.40 + i * 0.1) for i, k in enumerate(["a", "b", "c"])}
+ _wire(monkeypatch, id_to_zoo, _fake_run_bench(metrics))
+ rc, env = _run(capsys, _args(zoo="alpha101"))
+
+ assert rc == 0
+ assert {r["id"] for r in env["ranking"]} == {"a", "b"} # c (gtja191) excluded
+
+
+# ── compare_runner.compare_alphas core (direct) ─────────────────────────────
+
+
+def test_core_progress_counts_globally_across_zoos(monkeypatch) -> None:
+ id_to_zoo = {"a": "alpha101", "b": "alpha101", "c": "gtja191"}
+ metrics = {k: _metrics(0.02, 0.05, 0.40) for k in id_to_zoo}
+
+ def _fake(*, zoo, universe, period, top, only, registry, on_progress=None): # noqa: ANN001, ARG001
+ rows = []
+ for i, aid in enumerate(only, start=1):
+ rows.append({"id": aid, **metrics[aid]})
+ if on_progress is not None:
+ on_progress(i, len(only), aid) # per-zoo local count
+ return {"status": "ok", "zoo": zoo, "rows": rows, "skipped": []}
+
+ monkeypatch.setattr("src.factors.bench_runner.run_bench", _fake)
+ seen: list[tuple[int, int, str]] = []
+ env = compare_runner.compare_alphas(
+ ["a", "b", "c"], "csi300", "2020-2025", sort="ir",
+ registry=_FakeRegistry(id_to_zoo),
+ on_progress=lambda nd, nt, aid: seen.append((nd, nt, aid)),
+ )
+ assert env["status"] == "ok"
+ # alpha101 (a,b) base 0 → 1,2 ; gtja191 (c) base 2 → 3 — global & monotonic.
+ assert [nd for nd, _, _ in seen] == [1, 2, 3]
+ assert {nt for _, nt, _ in seen} == {3} # total is the whole comparison, not per-zoo
+
+
+def test_core_below_two_returns_error(monkeypatch) -> None:
+ env = compare_runner.compare_alphas(
+ ["solo"], "csi300", "2020-2025", registry=_FakeRegistry({"solo": "alpha101"}),
+ )
+ assert env["status"] == "error"
+ assert "at least 2" in env["error"]
+ assert env["ranking"] == []
+
+
+def test_core_invalid_sort_falls_back_to_ir(monkeypatch) -> None:
+ id_to_zoo = {"a": "alpha101", "b": "alpha101"}
+ metrics = {"a": _metrics(0.01, 0.05, 0.20), "b": _metrics(0.03, 0.05, 0.60)}
+ monkeypatch.setattr("src.factors.bench_runner.run_bench", _fake_run_bench(metrics))
+ env = compare_runner.compare_alphas(
+ ["a", "b"], "csi300", "2020-2025", sort="bogus", registry=_FakeRegistry(id_to_zoo),
+ )
+ assert env["sort"] == "ir"
+ assert env["winner"] == "b"
diff --git a/agent/tests/test_alpha_compare_api.py b/agent/tests/test_alpha_compare_api.py
new file mode 100644
index 000000000..b84c12ffd
--- /dev/null
+++ b/agent/tests/test_alpha_compare_api.py
@@ -0,0 +1,195 @@
+"""API tests for ``POST /alpha/compare`` + its SSE stream.
+
+Deterministic by construction — no network, no flaky background-timing:
+
+* **validation** runs through the real ``CompareRequest`` pydantic model via
+ ``TestClient.post`` (rejection happens before any worker spawns);
+* the **worker** (``_run_compare_blocking``) is called directly with
+ ``compare_alphas`` stubbed, asserting job-state transitions and that an
+ unexpected exception is sanitised (no path/message leak);
+* the **stream** is exercised over a pre-seeded ``done`` job so the SSE
+ generator emits ``result`` + ``done`` on the first pass and returns.
+
+Loopback ``TestClient`` (127.0.0.1) bypasses dev-mode auth, matching the
+convention in ``test_goal_api.py`` / ``test_security_auth_api.py``.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from fastapi.testclient import TestClient
+
+import api_server
+from src.api import alpha_routes
+
+
+def _client() -> TestClient:
+ return TestClient(api_server.app, client=("127.0.0.1", 50000))
+
+
[email protected](autouse=True)
+def _clear_compare_jobs():
+ alpha_routes.ALPHA_COMPARE_JOBS.clear()
+ yield
+ alpha_routes.ALPHA_COMPARE_JOBS.clear()
+
+
+_OK_ENVELOPE: dict[str, Any] = {
+ "status": "ok",
+ "universe": "csi300",
+ "period": "2020-2025",
+ "sort": "ir",
+ "n_compared": 2,
+ "n_skipped": 0,
+ "winner": "alpha101_2",
+ "ranking": [
+ {"rank": 1, "id": "alpha101_2", "zoo": "alpha101", "ic_mean": 0.03,
+ "ic_std": 0.05, "ir": 0.6, "ic_positive_ratio": 0.55, "ic_count": 200,
+ "delta_ir_vs_best": 0.0},
+ {"rank": 2, "id": "alpha101_1", "zoo": "alpha101", "ic_mean": 0.01,
+ "ic_std": 0.05, "ir": 0.2, "ic_positive_ratio": 0.5, "ic_count": 200,
+ "delta_ir_vs_best": -0.4},
+ ],
+ "skipped": [],
+}
+
+
+def _valid_body(**kw: Any) -> dict[str, Any]:
+ body = {
+ "alpha_ids": ["alpha101_1", "alpha101_2"],
+ "universe": "csi300",
+ "period": "2020-2025",
+ "sort": "ir",
+ }
+ body.update(kw)
+ return body
+
+
+def _seed_job(job_id: str, **over: Any) -> dict[str, Any]:
+ job = {
+ "job_id": job_id, "status": "queued",
+ "progress": {"n_done": 0, "n_total": 2, "current_alpha_id": None},
+ "result": None, "error": None,
+ }
+ job.update(over)
+ alpha_routes.ALPHA_COMPARE_JOBS[job_id] = job
+ return job
+
+
+# ── validation (pydantic, pre-worker) ───────────────────────────────────────
+
+
+def test_compare_requires_two_ids() -> None:
+ r = _client().post("/alpha/compare", json=_valid_body(alpha_ids=["alpha101_1"]))
+ assert r.status_code == 422
+
+
+def test_compare_dedupes_below_two_is_rejected() -> None:
+ r = _client().post("/alpha/compare", json=_valid_body(alpha_ids=["alpha101_1", "alpha101_1"]))
+ assert r.status_code == 422
+
+
+def test_compare_rejects_unknown_universe() -> None:
+ r = _client().post("/alpha/compare", json=_valid_body(universe="nasdaq"))
+ assert r.status_code == 422
+
+
+def test_compare_rejects_unknown_sort() -> None:
+ r = _client().post("/alpha/compare", json=_valid_body(sort="sharpe"))
+ assert r.status_code == 422
+
+
+def test_compare_rejects_malformed_alpha_id() -> None:
+ r = _client().post("/alpha/compare", json=_valid_body(alpha_ids=["alpha101_1", "BAD ID!"]))
+ assert r.status_code == 422
+
+
+# ── POST accepted ───────────────────────────────────────────────────────────
+
+
+def test_compare_post_accepts_and_registers_job(monkeypatch) -> None:
+ monkeypatch.setattr("src.factors.compare_runner.compare_alphas", lambda *a, **k: dict(_OK_ENVELOPE))
+ r = _client().post("/alpha/compare", json=_valid_body())
+ assert r.status_code == 202
+ body = r.json()
+ assert body["status"] == "ok"
+ assert body["job_id"] in alpha_routes.ALPHA_COMPARE_JOBS
+
+
+# ── worker (_run_compare_blocking) ──────────────────────────────────────────
+
+
+def test_worker_stores_ok_envelope(monkeypatch) -> None:
+ monkeypatch.setattr("src.factors.compare_runner.compare_alphas", lambda *a, **k: dict(_OK_ENVELOPE))
+ _seed_job("aaaa1111")
+ alpha_routes._run_compare_blocking("aaaa1111", ["alpha101_1", "alpha101_2"], "csi300", "2020-2025", "ir")
+ job = alpha_routes.ALPHA_COMPARE_JOBS["aaaa1111"]
+ assert job["status"] == "done"
+ assert job["result"]["winner"] == "alpha101_2"
+ assert job["result"]["ranking"][0]["id"] == "alpha101_2"
+
+
+def test_worker_marks_error_envelope(monkeypatch) -> None:
+ err = {"status": "error", "error": "no requested alphas could be evaluated",
+ "ranking": [], "skipped": [{"id": "x", "reason": "unknown"}]}
+ monkeypatch.setattr("src.factors.compare_runner.compare_alphas", lambda *a, **k: err)
+ _seed_job("bbbb2222")
+ alpha_routes._run_compare_blocking("bbbb2222", ["x", "y"], "csi300", "2020-2025", "ir")
+ job = alpha_routes.ALPHA_COMPARE_JOBS["bbbb2222"]
+ assert job["status"] == "error"
+ assert "evaluated" in job["error"]
+
+
+def test_worker_sanitises_unexpected_exception(monkeypatch) -> None:
+ def _boom(*_a: Any, **_k: Any) -> dict[str, Any]:
+ raise RuntimeError("leak: /etc/secret/path token=abc123")
+
+ monkeypatch.setattr("src.factors.compare_runner.compare_alphas", _boom)
+ _seed_job("cccc3333")
+ alpha_routes._run_compare_blocking("cccc3333", ["x", "y"], "csi300", "2020-2025", "ir")
+ job = alpha_routes.ALPHA_COMPARE_JOBS["cccc3333"]
+ assert job["status"] == "error"
+ # No raw message / path leaks to the client-facing error string.
+ assert job["error"] == "internal error; see server logs"
+
+
+# ── result projector ────────────────────────────────────────────────────────
+
+
+def test_result_projector_drops_status_keeps_ranking() -> None:
+ wire = alpha_routes._compare_result_for_wire(dict(_OK_ENVELOPE))
+ assert "status" not in wire
+ assert wire["winner"] == "alpha101_2"
+ assert wire["ranking"][0]["id"] == "alpha101_2"
+
+
+# ── SSE stream ──────────────────────────────────────────────────────────────
+
+
+def test_stream_emits_result_then_done() -> None:
+ _seed_job(
+ "dddd4444",
+ status="done",
+ progress={"n_done": 2, "n_total": 2, "current_alpha_id": "alpha101_2"},
+ result=dict(_OK_ENVELOPE),
+ )
+ with _client() as client:
+ r = client.get("/alpha/compare/dddd4444/stream")
+ assert r.status_code == 200
+ text = r.text
+ assert "event: result" in text
+ assert "event: done" in text
+ assert "ranking" in text
+ assert "alpha101_2" in text
+
+
+def test_stream_unknown_job_is_404() -> None:
+ r = _client().get("/alpha/compare/abcdef123456/stream")
+ assert r.status_code == 404
+
+
+def test_stream_invalid_job_id_is_400() -> None:
+ r = _client().get("/alpha/compare/bad@id/stream")
+ assert r.status_code == 400
diff --git a/agent/tests/test_alpha_compare_tool.py b/agent/tests/test_alpha_compare_tool.py
new file mode 100644
index 000000000..f43e31ed8
--- /dev/null
+++ b/agent/tests/test_alpha_compare_tool.py
@@ -0,0 +1,128 @@
+"""Tests for the ``alpha_compare`` agent tool.
+
+Covers id coercion, the tool's JSON-Schema contract, ``execute`` happy/error
+paths (with ``compare_alphas`` stubbed so no bench/network runs), and that the
+tool is auto-discovered into the default registry.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import pytest
+
+from src.tools import build_registry
+from src.tools.alpha_compare_tool import AlphaCompareTool, _coerce_ids
+
+
+# ── _coerce_ids ─────────────────────────────────────────────────────────────
+
+
+def test_coerce_ids_passes_through_list() -> None:
+ assert _coerce_ids(["a", "b", "c"]) == ["a", "b", "c"]
+
+
+def test_coerce_ids_splits_string_on_commas_and_spaces() -> None:
+ assert _coerce_ids("a, b c,d") == ["a", "b", "c", "d"]
+
+
+def test_coerce_ids_dedupes_preserving_order() -> None:
+ assert _coerce_ids(["a", "b", "a", "c", "b"]) == ["a", "b", "c"]
+
+
+def test_coerce_ids_handles_none_and_blanks() -> None:
+ assert _coerce_ids(None) == []
+ assert _coerce_ids(["", " ", "x"]) == ["x"]
+
+
+# ── tool contract ───────────────────────────────────────────────────────────
+
+
+def test_tool_metadata() -> None:
+ tool = AlphaCompareTool()
+ assert tool.name == "alpha_compare"
+ assert tool.is_readonly is True
+ assert tool.repeatable is True
+ assert tool.parameters["required"] == ["alpha_ids", "universe", "period"]
+ assert tool.parameters["properties"]["sort"]["enum"] == [
+ "ir", "ic_mean", "ic_positive_ratio", "ic_count",
+ ]
+
+
+def test_tool_is_auto_discovered() -> None:
+ registry = build_registry()
+ assert "alpha_compare" in registry.tool_names
+
+
+# ── execute ─────────────────────────────────────────────────────────────────
+
+
+def _ok_envelope() -> dict[str, Any]:
+ return {
+ "status": "ok", "universe": "csi300", "period": "2020-2025", "sort": "ir",
+ "n_compared": 2, "n_skipped": 0, "winner": "alpha101_2",
+ "ranking": [
+ {"rank": 1, "id": "alpha101_2", "zoo": "alpha101", "ir": 0.6, "delta_ir_vs_best": 0.0},
+ {"rank": 2, "id": "alpha101_1", "zoo": "alpha101", "ir": 0.2, "delta_ir_vs_best": -0.4},
+ ],
+ "skipped": [],
+ }
+
+
+def test_execute_happy_path(monkeypatch) -> None:
+ captured: dict[str, Any] = {}
+
+ def _fake(alpha_ids, universe, period, *, sort="ir", **_kw): # noqa: ANN001
+ captured.update(alpha_ids=alpha_ids, universe=universe, period=period, sort=sort)
+ return _ok_envelope()
+
+ monkeypatch.setattr("src.tools.alpha_compare_tool.compare_alphas", _fake)
+ out = AlphaCompareTool().execute(
+ alpha_ids=["alpha101_1", "alpha101_2", "alpha101_1"], # dup collapses
+ universe="csi300", period="2020-2025", sort="ir",
+ )
+ env = json.loads(out)
+ assert env["status"] == "ok"
+ assert env["winner"] == "alpha101_2"
+ # ids were coerced/deduped before reaching the core.
+ assert captured["alpha_ids"] == ["alpha101_1", "alpha101_2"]
+ assert captured["sort"] == "ir"
+
+
+def test_execute_accepts_inline_string_ids(monkeypatch) -> None:
+ monkeypatch.setattr(
+ "src.tools.alpha_compare_tool.compare_alphas",
+ lambda alpha_ids, *a, **k: {"status": "ok", "n_compared": len(alpha_ids),
+ "winner": alpha_ids[0], "ranking": [], "skipped": []},
+ )
+ env = json.loads(AlphaCompareTool().execute(
+ alpha_ids="alpha101_1, alpha101_2", universe="csi300", period="2020-2025",
+ ))
+ assert env["status"] == "ok"
+ assert env["n_compared"] == 2
+
+
+def test_execute_missing_universe_is_error(monkeypatch) -> None:
+ # compare_alphas must not even be called when required args are absent.
+ monkeypatch.setattr(
+ "src.tools.alpha_compare_tool.compare_alphas",
+ lambda *a, **k: pytest.fail("compare_alphas should not run without universe"),
+ )
+ env = json.loads(AlphaCompareTool().execute(
+ alpha_ids=["a", "b"], universe="", period="2020-2025",
+ ))
+ assert env["status"] == "error"
+ assert "universe and period" in env["error"]
+
+
+def test_execute_wraps_unexpected_exception(monkeypatch) -> None:
+ def _boom(*_a: Any, **_k: Any):
+ raise RuntimeError("kaboom")
+
+ monkeypatch.setattr("src.tools.alpha_compare_tool.compare_alphas", _boom)
+ env = json.loads(AlphaCompareTool().execute(
+ alpha_ids=["a", "b"], universe="csi300", period="2020-2025",
+ ))
+ assert env["status"] == "error"
+ assert "alpha compare failed" in env["error"]
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 24568fedd..cc7919522 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -157,6 +157,13 @@ export const api = {
}),
alphaBenchStreamUrl: (jobId: string) =>
withAuthQuery(`${BASE}/alpha/bench/${encodeURIComponent(jobId)}/stream`),
+ createAlphaCompare: (body: AlphaCompareRequest) =>
+ request<{ status: string; job_id: string }>("/alpha/compare", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+ alphaCompareStreamUrl: (jobId: string) =>
+ withAuthQuery(`${BASE}/alpha/compare/${encodeURIComponent(jobId)}/stream`),
// Connector runtime channel — privileged surface actions (NOT agent tools).
// commit is the ONLY action that writes a mandate; halt trips the kill switch.
@@ -679,6 +686,43 @@ export interface AlphaBenchResult {
by_theme: Record<string, { alive: number; reversed: number; dead: number }>;
}
+export interface AlphaCompareRequest {
+ alpha_ids: string[];
+ universe: string;
+ period: string;
+ /** One of: ir | ic_mean | ic_positive_ratio | ic_count (default ir). */
+ sort?: string;
+}
+
+export interface AlphaCompareRow {
+ rank: number;
+ id: string;
+ zoo: string;
+ ic_mean: number;
+ ic_std: number;
+ ir: number;
+ ic_positive_ratio: number;
+ ic_count: number;
+ /** `delta_<sort>_vs_best` — gap to the top-ranked alpha on the active metric. */
+ [deltaKey: string]: number | string;
+}
+
+export interface AlphaCompareSkip {
+ id: string;
+ reason: string;
+}
+
+export interface AlphaCompareResult {
+ universe: string;
+ period: string;
+ sort: string;
+ n_compared: number;
+ n_skipped: number;
+ winner: string;
+ ranking: AlphaCompareRow[];
+ skipped: AlphaCompareSkip[];
+}
+
// --- Connector runtime channel types ---
/** One mandate profile inside a `mandate.proposal` event (SPEC Consent §1). */
diff --git a/frontend/src/pages/AlphaZoo.tsx b/frontend/src/pages/AlphaZoo.tsx
index f051c261a..8555bef51 100644
--- a/frontend/src/pages/AlphaZoo.tsx
+++ b/frontend/src/pages/AlphaZoo.tsx
@@ -20,6 +20,7 @@ import {
Search,
Play,
ArrowLeft,
+ ArrowLeftRight,
Loader2,
CheckCircle2,
AlertTriangle,
@@ -34,6 +35,7 @@ import {
type AlphaDetailResponse,
type AlphaBenchResult,
type AlphaBenchTopRow,
+ type AlphaCompareResult,
} from "@/lib/api";
import { echarts } from "@/lib/echarts";
import { getChartTheme } from "@/lib/chart-theme";
@@ -119,6 +121,9 @@ export function AlphaZoo() {
if (pathname === "/alpha-zoo/bench") {
return <BenchView />;
}
+ if (pathname === "/alpha-zoo/compare") {
+ return <CompareView />;
+ }
if (params.alphaId) {
return <DetailView alphaId={params.alphaId} />;
}
@@ -136,6 +141,21 @@ function BrowseView() {
const [search, setSearch] = useState("");
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
const [total, setTotal] = useState<number>(0);
+ // Alphas ticked for a head-to-head compare; handed to CompareView via the URL.
+ const [selected, setSelected] = useState<Set<string>>(() => new Set());
+
+ const toggleSelected = (id: string) =>
+ setSelected((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+
+ const compareHref =
+ selected.size >= 2
+ ? `/alpha-zoo/compare?ids=${[...selected].map(encodeURIComponent).join(",")}`
+ : "/alpha-zoo/compare";
useEffect(() => {
let alive = true;
@@ -310,6 +330,14 @@ function BrowseView() {
))}
</select>
</div>
+ <Link
+ to={compareHref}
+ className="inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg border text-sm font-medium hover:bg-muted hover:text-foreground transition"
+ title="Tick 2+ alphas below, then compare them head-to-head"
+ >
+ <ArrowLeftRight className="h-3.5 w-3.5" aria-hidden="true" /> Compare
+ {selected.size >= 2 ? ` (${selected.size})` : ""}
+ </Link>
<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"
@@ -326,6 +354,9 @@ function BrowseView() {
<caption className="sr-only">Alpha catalogue</caption>
<thead>
<tr className="border-b bg-muted/40">
+ <th className="w-10 px-3 py-2.5">
+ <span className="sr-only">Select for compare</span>
+ </th>
<th className="text-left px-4 py-2.5 text-muted-foreground">
ID
</th>
@@ -346,14 +377,14 @@ function BrowseView() {
<tbody>
{loading ? (
<tr>
- <td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
+ <td colSpan={6} 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">
+ <td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">
No alphas match the current filters.
</td>
</tr>
@@ -361,8 +392,20 @@ function BrowseView() {
visible.map((a) => (
<tr
key={`${a.zoo}:${a.id}`}
- className="border-b last:border-0 hover:bg-muted/20"
+ className={cn(
+ "border-b last:border-0 hover:bg-muted/20",
+ selected.has(a.id) && "bg-primary/5",
+ )}
>
+ <td className="px-3 py-2">
+ <input
+ type="checkbox"
+ checked={selected.has(a.id)}
+ onChange={() => toggleSelected(a.id)}
+ aria-label={`Select ${a.id} for compare`}
+ className="h-4 w-4 rounded border-input accent-primary cursor-pointer"
+ />
+ </td>
<td className="px-4 py-2 font-mono text-xs">
<Link
to={`/alpha-zoo/${encodeURIComponent(a.id)}`}
@@ -1021,3 +1064,346 @@ function CategoryBadge({ category }: { category: AlphaBenchTopRow["category"] })
</span>
);
}
+
+/* ---------- Compare view ---------- */
+
+const SORT_OPTIONS = [
+ { value: "ir", label: "IR (information ratio)" },
+ { value: "ic_mean", label: "IC mean" },
+ { value: "ic_positive_ratio", label: "IC > 0 ratio" },
+ { value: "ic_count", label: "Sample count" },
+];
+
+/** Split a free-text id list on commas / whitespace; dedupe, preserve order. */
+function parseAlphaIds(text: string): string[] {
+ const seen = new Set<string>();
+ const out: string[] = [];
+ for (const raw of text.split(/[\s,]+/)) {
+ const id = raw.trim();
+ if (id && !seen.has(id)) {
+ seen.add(id);
+ out.push(id);
+ }
+ }
+ return out;
+}
+
+/**
+ * Head-to-head comparison of a hand-picked set of alphas.
+ *
+ * Mirrors {@link BenchView}'s raw-EventSource lifecycle (the shared `useSSE`
+ * hook drops these event types). Ids are prefilled from `?ids=a,b,c` — set by
+ * the BrowseView multi-select — and remain editable as free text.
+ */
+function CompareView() {
+ const { search: locSearch } = useLocation();
+ const initialIds = useMemo(() => {
+ const q = new URLSearchParams(locSearch);
+ return parseAlphaIds(q.get("ids") || "").join(", ");
+ }, [locSearch]);
+
+ const [idsText, setIdsText] = useState(initialIds);
+ const [universe, setUniverse] = useState("csi300");
+ const [period, setPeriod] = useState("2020-2025");
+ const [sort, setSort] = useState("ir");
+
+ const [status, setStatus] = useState<BenchStatus>("idle");
+ const [jobId, setJobId] = useState<string | null>(null);
+ const [progress, setProgress] = useState<BenchProgress | null>(null);
+ const [result, setResult] = useState<AlphaCompareResult | null>(null);
+ const [formError, setFormError] = useState<string | null>(null);
+ const sourceRef = useRef<EventSource | null>(null);
+ const doneRef = useRef(false);
+
+ const ids = useMemo(() => parseAlphaIds(idsText), [idsText]);
+
+ useEffect(() => {
+ return () => {
+ sourceRef.current?.close();
+ sourceRef.current = null;
+ };
+ }, []);
+
+ const attachStream = (newJobId: string) => {
+ setStatus("streaming");
+ const source = new EventSource(api.alphaCompareStreamUrl(newJobId));
+ sourceRef.current = source;
+
+ source.addEventListener("progress", (e) => {
+ try {
+ setProgress(JSON.parse((e as MessageEvent).data) as BenchProgress);
+ } catch {
+ /* ignore */
+ }
+ });
+ source.addEventListener("result", (e) => {
+ try {
+ setResult(JSON.parse((e as MessageEvent).data) as AlphaCompareResult);
+ } 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 the close that follows `done`;
+ // the ref check (synchronous) is the only reliable race guard.
+ if (doneRef.current) {
+ source.close();
+ sourceRef.current = null;
+ return;
+ }
+ let msg = "Compare 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 startCompare = async (e: FormEvent) => {
+ e.preventDefault();
+ if (status === "submitting" || status === "streaming") return;
+ if (ids.length < 2) {
+ setFormError("Enter at least 2 distinct alpha ids to compare.");
+ return;
+ }
+ setStatus("submitting");
+ setProgress(null);
+ setResult(null);
+ setFormError(null);
+ doneRef.current = false;
+ sourceRef.current?.close();
+ try {
+ const res = await api.createAlphaCompare({
+ alpha_ids: ids,
+ universe,
+ period,
+ sort,
+ });
+ setJobId(res.job_id);
+ attachStream(res.job_id);
+ } catch (err: unknown) {
+ const msg =
+ err instanceof Error ? err.message : "Failed to start comparison";
+ toast.error(msg);
+ setStatus("error");
+ }
+ };
+
+ 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">
+ <ArrowLeftRight className="h-3.5 w-3.5" aria-hidden="true" /> Head-to-head compare
+ </div>
+ <h1 className="text-2xl md:text-3xl font-bold tracking-tight">
+ Compare alphas side by side
+ </h1>
+ <p className="text-sm text-muted-foreground max-w-2xl">
+ Benches just the alphas you pick on a universe and period, then ranks
+ them by IC / IR with the gap to the leader — far faster than benching a
+ whole zoo when you only care about a shortlist.
+ </p>
+ </div>
+
+ <form onSubmit={startCompare} className="border rounded-xl p-4 bg-card space-y-3">
+ <div>
+ <label htmlFor="compare-ids" className="text-xs text-muted-foreground block mb-1">
+ Alpha ids{ids.length > 0 ? ` (${ids.length} selected)` : ""}
+ </label>
+ <textarea
+ id="compare-ids"
+ value={idsText}
+ onChange={(e) => setIdsText(e.target.value)}
+ disabled={busy}
+ rows={2}
+ placeholder="alpha101_1, alpha101_2, gtja191_5"
+ className="w-full px-3 py-2 rounded-lg border bg-background text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary/30 disabled:opacity-50"
+ />
+ <p className="text-[11px] text-muted-foreground mt-1">
+ Separate ids with commas or spaces. Tip: tick alphas in the catalogue
+ and hit “Compare” to prefill this.
+ </p>
+ </div>
+
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
+ <div>
+ <label htmlFor="compare-universe" className="text-xs text-muted-foreground block mb-1">Universe</label>
+ <select
+ id="compare-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="compare-period" className="text-xs text-muted-foreground block mb-1">Period</label>
+ <input
+ id="compare-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="compare-sort" className="text-xs text-muted-foreground block mb-1">Rank by</label>
+ <select
+ id="compare-sort"
+ value={sort}
+ onChange={(e) => setSort(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"
+ >
+ {SORT_OPTIONS.map((s) => (
+ <option key={s.value} value={s.value}>
+ {s.label}
+ </option>
+ ))}
+ </select>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <button
+ type="submit"
+ disabled={busy || ids.length < 2}
+ 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…
+ </>
+ ) : (
+ <>
+ <ArrowLeftRight className="h-3.5 w-3.5" aria-hidden="true" /> Compare
+ </>
+ )}
+ </button>
+ {ids.length < 2 && (
+ <span className="text-xs text-muted-foreground">Pick at least 2 alphas.</span>
+ )}
+ </div>
+
+ {formError && (
+ <p className="text-xs text-red-600 dark:text-red-400" role="alert">
+ {formError}
+ </p>
+ )}
+ </form>
+
+ {(status === "submitting" || status === "streaming") && (
+ <ProgressPanel jobId={jobId} progress={progress} />
+ )}
+
+ {result && <CompareResultPanel result={result} />}
+ </div>
+ );
+}
+
+function CompareResultPanel({ result }: { result: AlphaCompareResult }) {
+ const deltaKey = `delta_${result.sort}_vs_best`;
+ return (
+ <div className="space-y-4">
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
+ <span className="inline-flex items-center gap-1.5 font-medium text-emerald-600 dark:text-emerald-400">
+ <CheckCircle2 className="h-4 w-4" aria-hidden="true" /> Winner:{" "}
+ <span className="font-mono">{result.winner}</span>
+ </span>
+ <span className="text-muted-foreground">
+ {result.n_compared} compared · ranked by {result.sort} · {result.universe} · {result.period}
+ </span>
+ {result.n_skipped > 0 && (
+ <span className="inline-flex items-center gap-1 text-amber-600 dark:text-amber-400">
+ <AlertTriangle className="h-3.5 w-3.5" aria-hidden="true" /> {result.n_skipped} skipped
+ </span>
+ )}
+ </div>
+
+ <div className="border rounded-xl overflow-hidden">
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm" aria-label="Alpha comparison ranking">
+ <thead>
+ <tr className="border-b bg-muted/40 text-muted-foreground text-xs">
+ <th className="text-right px-3 py-2">#</th>
+ <th className="text-left px-3 py-2">Alpha</th>
+ <th className="text-left px-3 py-2 hidden sm:table-cell">Zoo</th>
+ <th className="text-right px-3 py-2">IC mean</th>
+ <th className="text-right px-3 py-2 hidden md:table-cell">IC std</th>
+ <th className="text-right px-3 py-2">IR</th>
+ <th className="text-right px-3 py-2 hidden md:table-cell" title="Share of periods with positive IC">IC&gt;0</th>
+ <th className="text-right px-3 py-2 hidden lg:table-cell" title="IC sample count">n</th>
+ <th className="text-right px-3 py-2" title={`Gap to the leader on ${result.sort}`}>Δ {result.sort}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {result.ranking.map((r) => (
+ <tr
+ key={`${r.zoo}:${r.id}`}
+ className={cn(
+ "border-b last:border-0 hover:bg-muted/20",
+ r.rank === 1 && "bg-emerald-500/5",
+ )}
+ >
+ <td className="px-3 py-2 text-right font-mono tabular-nums">{r.rank}</td>
+ <td className="px-3 py-2 font-mono text-xs">
+ <Link
+ to={`/alpha-zoo/${encodeURIComponent(r.id)}`}
+ className="text-primary hover:underline"
+ >
+ {r.id}
+ </Link>
+ </td>
+ <td className="px-3 py-2 text-xs text-muted-foreground hidden sm:table-cell">{r.zoo}</td>
+ <td className="px-3 py-2 text-right font-mono tabular-nums">{fmtNum(r.ic_mean, 4)}</td>
+ <td className="px-3 py-2 text-right font-mono tabular-nums hidden md:table-cell">{fmtNum(r.ic_std, 4)}</td>
+ <td className="px-3 py-2 text-right font-mono tabular-nums">{fmtNum(r.ir, 3)}</td>
+ <td className="px-3 py-2 text-right font-mono tabular-nums hidden md:table-cell">{fmtNum(r.ic_positive_ratio, 3)}</td>
+ <td className="px-3 py-2 text-right font-mono tabular-nums hidden lg:table-cell">{r.ic_count}</td>
+ <td className="px-3 py-2 text-right font-mono tabular-nums text-muted-foreground">
+ {r.rank === 1 ? "—" : fmtNum(Number(r[deltaKey]), 4)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ {result.skipped.length > 0 && (
+ <p className="text-xs text-muted-foreground">
+ <span className="font-medium">Skipped:</span>{" "}
+ {result.skipped.map((s) => `${s.id} (${s.reason})`).join("; ")}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/router.tsx b/frontend/src/router.tsx
index 77ace6e55..ddd5170bd 100644
--- a/frontend/src/router.tsx
+++ b/frontend/src/router.tsx
@@ -48,6 +48,7 @@ export const router = createBrowserRouter([
{ path: "/correlation", element: wrap(Correlation) },
{ path: "/alpha-zoo", element: wrap(AlphaZoo) },
{ path: "/alpha-zoo/bench", element: wrap(AlphaZoo) },
+ { path: "/alpha-zoo/compare", element: wrap(AlphaZoo) },
{ path: "/alpha-zoo/:alphaId", element: wrap(AlphaZoo) },
],
},