Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat: factor research panel in Run Detail — IC series, IC stats, quantile equity, IC correlation

shadowinlifeb4f7e98341af
diff --git a/agent/src/api/models.py b/agent/src/api/models.py
index 831e56d56..2d0638620 100644
--- a/agent/src/api/models.py
+++ b/agent/src/api/models.py
@@ -68,6 +68,7 @@ class RunResponse(BaseModel):
metrics: Optional[BacktestMetrics] = Field(None, description="Backtest metrics")
artifacts: List[Artifact] = Field(default_factory=list, description="Run artifacts")
+ has_factor_artifacts: bool = Field(False, description="Whether the run produced factor-analysis artifacts")
run_card: Optional[Dict[str, Any]] = Field(None, description="Trust Layer run card payload")
llm_usage: Optional[Dict[str, Any]] = Field(None, description="Provider-reported AgentLoop usage summary")
diff --git a/agent/src/api/runs_routes.py b/agent/src/api/runs_routes.py
index ab1de81b4..be94281a2 100644
--- a/agent/src/api/runs_routes.py
+++ b/agent/src/api/runs_routes.py
@@ -7,9 +7,10 @@ from __future__ import annotations
import csv
import json
+import statistics
from datetime import datetime
from pathlib import Path
-from typing import Any, Awaitable, Callable, Dict, List, Optional
+from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple
from fastapi import Depends, FastAPI, HTTPException, Query, status
from fastapi.responses import JSONResponse
@@ -44,6 +45,193 @@ def _load_csv_to_dict(path: Path, limit: Optional[int] = None) -> List[Dict[str,
return []
+def _load_ic_series_csv(path: Path) -> List[Dict[str, Any]]:
+ """Load an ``ic_series.csv`` file into ``{"date", "ic"}`` rows.
+
+ The first CSV column is treated as the date column regardless of its
+ header name (the factor tool writes it with an empty or varying index
+ label). Rows whose IC value does not parse as a float are skipped.
+
+ Args:
+ path: Path to the ic_series.csv file.
+
+ Returns:
+ List of rows with raw string dates and float IC values.
+ """
+ try:
+ if not path.exists():
+ return []
+ with path.open("r", encoding="utf-8", newline="") as handle:
+ reader = csv.DictReader(handle)
+ fieldnames = reader.fieldnames
+ if not fieldnames or fieldnames[0] is None:
+ return []
+ date_col = fieldnames[0]
+ rows: List[Dict[str, Any]] = []
+ for row in reader:
+ date_value = row.get(date_col)
+ if date_value is None:
+ continue
+ try:
+ ic_value = float(row.get("IC"))
+ except (TypeError, ValueError):
+ continue
+ rows.append({"date": date_value, "ic": ic_value})
+ return rows
+ except Exception:
+ return []
+
+
+def _load_group_equity_csv(path: Path) -> Tuple[List[Dict[str, Any]], List[str]]:
+ """Load a ``group_equity.csv`` file into dated rows of float group values.
+
+ The first column is the date; every remaining column is kept in file
+ order and parsed as float. Cells that fail to parse are dropped.
+
+ Args:
+ path: Path to the group_equity.csv file.
+
+ Returns:
+ Tuple of (rows, value column names in file order).
+ """
+ try:
+ if not path.exists():
+ return [], []
+ with path.open("r", encoding="utf-8", newline="") as handle:
+ reader = csv.DictReader(handle)
+ fieldnames = reader.fieldnames
+ if not fieldnames or fieldnames[0] is None or len(fieldnames) < 2:
+ return [], []
+ date_col = fieldnames[0]
+ value_cols = [col for col in fieldnames[1:] if col]
+ rows: List[Dict[str, Any]] = []
+ for row in reader:
+ date_value = row.get(date_col)
+ if date_value is None:
+ continue
+ parsed: Dict[str, Any] = {"date": date_value}
+ for col in value_cols:
+ try:
+ parsed[col] = float(row.get(col))
+ except (TypeError, ValueError):
+ continue
+ rows.append(parsed)
+ return rows, value_cols
+ except Exception:
+ return [], []
+
+
+def _scan_factor_results(run_dir: Path, limit: int = 20) -> List[Dict[str, Any]]:
+ """Scan a run directory for factor-analysis artifact bundles.
+
+ A factor result is any directory under ``run_dir/artifacts`` (recursive)
+ that contains an ``ic_series.csv`` file. A bundle sitting directly in
+ ``artifacts/`` is named ``factor_analysis``; otherwise the containing
+ directory name is used. Paths with ``..`` or hidden components are
+ skipped, and results are capped to bound recursion over hostile layouts.
+
+ Args:
+ run_dir: Root directory of the run.
+ limit: Maximum number of factor results to return.
+
+ Returns:
+ Factor result dicts sorted by name ascending.
+ """
+ artifacts_dir = run_dir / "artifacts"
+ if not artifacts_dir.is_dir():
+ return []
+ try:
+ candidates = list(artifacts_dir.rglob("ic_series.csv"))
+ except OSError:
+ return []
+ results: List[Dict[str, Any]] = []
+ for csv_path in candidates:
+ try:
+ relative_dir = csv_path.parent.relative_to(run_dir)
+ except ValueError:
+ continue
+ if any(part == ".." or part.startswith(".") for part in relative_dir.parts):
+ continue
+ directory = csv_path.parent
+ name = "factor_analysis" if directory == artifacts_dir else directory.name
+ equity_rows, equity_cols = _load_group_equity_csv(directory / "group_equity.csv")
+ group_cols = [col for col in equity_cols if col.startswith("Group_")]
+ spread_cols = group_cols or equity_cols
+ long_short_spread: Optional[float] = None
+ group_final_equity: Dict[str, Any] = {}
+ if equity_rows and spread_cols:
+ last_row = equity_rows[-1]
+ first_value = last_row.get(spread_cols[0])
+ last_value = last_row.get(spread_cols[-1])
+ if first_value is not None and last_value is not None:
+ long_short_spread = round(last_value - first_value, 6)
+ group_final_equity = {col: last_row[col] for col in equity_cols if col in last_row}
+ entry: Dict[str, Any] = {
+ "name": name,
+ "path": relative_dir.as_posix(),
+ "ic_series": _load_ic_series_csv(csv_path),
+ }
+ summary = _load_json_file(directory / "ic_summary.json")
+ if isinstance(summary, dict):
+ entry["ic_stats"] = summary
+ entry["group_equity"] = equity_rows
+ entry["n_groups"] = len(group_cols)
+ entry["long_short_spread"] = long_short_spread
+ entry["group_final_equity"] = group_final_equity
+ results.append(entry)
+ results.sort(key=lambda item: str(item["name"]))
+ return results[:limit]
+
+
+def _pearson_correlation(x_values: List[float], y_values: List[float]) -> float:
+ """Compute Pearson correlation, degrading to 0.0 for degenerate input.
+
+ Args:
+ x_values: First series of values.
+ y_values: Second series of values (same length).
+
+ Returns:
+ Pearson correlation in [-1, 1], or 0.0 when a variance is zero.
+ """
+ try:
+ return statistics.correlation(x_values, y_values)
+ except (statistics.StatisticsError, ValueError):
+ return 0.0
+
+
+def _factor_ic_correlation(factors: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
+ """Build the pairwise IC correlation matrix across factor results.
+
+ Args:
+ factors: Factor result dicts from ``_scan_factor_results``.
+
+ Returns:
+ Labels plus a symmetric Pearson correlation matrix rounded to four
+ decimals, or ``None`` when fewer than two factors exist or any pair
+ shares fewer than 10 dates.
+ """
+ if len(factors) < 2:
+ return None
+ series: List[Dict[str, float]] = []
+ for factor in factors:
+ series.append({str(row["date"]): float(row["ic"]) for row in factor.get("ic_series") or []})
+ for i in range(len(series)):
+ for j in range(i + 1, len(series)):
+ if len(series[i].keys() & series[j].keys()) < 10:
+ return None
+ size = len(series)
+ matrix: List[List[float]] = [[1.0 if i == j else 0.0 for j in range(size)] for i in range(size)]
+ for i in range(size):
+ for j in range(i + 1, size):
+ common_dates = sorted(series[i].keys() & series[j].keys())
+ x_values = [series[i][date] for date in common_dates]
+ y_values = [series[j][date] for date in common_dates]
+ correlation = round(_pearson_correlation(x_values, y_values), 4)
+ matrix[i][j] = correlation
+ matrix[j][i] = correlation
+ return {"labels": [str(factor["name"]) for factor in factors], "matrix": matrix}
+
+
def _run_response_payload(response: Any) -> Dict[str, Any]:
"""Return a JSON-ready payload for opt-in run response variants."""
return response.model_dump(mode="json")
@@ -142,6 +330,8 @@ def _build_response_from_run_dir(
)
)
+ response.has_factor_artifacts = bool(_scan_factor_results(run_dir, limit=1))
+
equity_path = run_dir / "artifacts" / "equity.csv"
if equity_path.exists():
response.artifacts_equity_csv = _load_csv_to_dict(equity_path)
@@ -310,6 +500,33 @@ def register_runs_routes(
"content": pine_path.read_text(encoding="utf-8"),
}
+ @app.get("/runs/{run_id}/factor", dependencies=[Depends(require_auth)])
+ async def get_run_factor(run_id: str):
+ """Return factor-analysis artifacts for a run.
+
+ Args:
+ run_id: Run identifier.
+
+ Returns:
+ Object with exists flag, factor results sorted by name, and the
+ pairwise IC correlation matrix (null when not computable).
+ """
+ _host_validate_path_param(run_id, "run_id")
+ run_dir = _host_RUNS_DIR() / run_id
+ if not run_dir.exists():
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Run {run_id} not found"
+ )
+ factors = _scan_factor_results(run_dir)
+ if not factors:
+ return {"exists": False, "factors": [], "ic_correlation": None}
+ return {
+ "exists": True,
+ "factors": factors,
+ "ic_correlation": _factor_ic_correlation(factors),
+ }
+
@app.get("/runs/{run_id}", response_model=RunResponse, dependencies=[Depends(require_auth)])
async def get_run_result(
run_id: str,
diff --git a/agent/src/skills/factor-research/SKILL.md b/agent/src/skills/factor-research/SKILL.md
index 7365b2f83..4e786fa0c 100644
--- a/agent/src/skills/factor-research/SKILL.md
+++ b/agent/src/skills/factor-research/SKILL.md
@@ -154,3 +154,7 @@ factor_panel.to_csv("factor_alpha101_001.csv") # ready for factor
For combining several validated alphas into one composite signal, see the `multi-factor` skill's `ZooSignalEngine` (it z-scores, weights, and ranks alphas for you, with per-alpha skip isolation). For browsing the catalogue and inspecting individual `__alpha_meta__` records, see the `alpha-zoo` skill.
+## Artifact Placement
+
+When `factor_analysis` runs inside a backtest or swarm run, set `output_dir` to `<run_dir>/artifacts/factor/<factor_name>/` so the Run Detail Factor tab can render the results. Use one subdirectory per factor (for example `artifacts/factor/momentum_20d/`), and keep the three standard output files (`ic_series.csv`, `ic_summary.json`, `group_equity.csv`) together inside it. Artifacts written elsewhere under `artifacts/` are still discovered by the recursive scan, but the canonical layout keeps runs comparable.
+
diff --git a/agent/tests/test_factor_api.py b/agent/tests/test_factor_api.py
new file mode 100644
index 000000000..5b39e7e21
--- /dev/null
+++ b/agent/tests/test_factor_api.py
@@ -0,0 +1,185 @@
+"""API regressions for the run factor-analysis artifact endpoint."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from fastapi.testclient import TestClient
+
+import api_server
+
+
+def _client(tmp_path: Path, monkeypatch) -> TestClient:
+ monkeypatch.setattr(api_server, "RUNS_DIR", tmp_path / "runs")
+ return TestClient(api_server.app, client=("127.0.0.1", 50000))
+
+
+def _write_factor_bundle(
+ run_dir: Path,
+ name: str,
+ ic_csv: str,
+ summary: dict | None,
+ group_equity_csv: str | None = None,
+) -> Path:
+ bundle = run_dir / "artifacts" / "factor" / name
+ bundle.mkdir(parents=True, exist_ok=True)
+ (bundle / "ic_series.csv").write_text(ic_csv, encoding="utf-8")
+ if summary is not None:
+ (bundle / "ic_summary.json").write_text(json.dumps(summary), encoding="utf-8")
+ if group_equity_csv is not None:
+ (bundle / "group_equity.csv").write_text(group_equity_csv, encoding="utf-8")
+ return bundle
+
+
+def _ic_csv(rows: list[tuple[str, float]]) -> str:
+ lines = ["date,IC"]
+ lines.extend(f"{date},{value}" for date, value in rows)
+ lines.append("2024-01-30,not-a-number") # malformed row must be skipped
+ return "\n".join(lines) + "\n"
+
+
+def _summary(ic_count: int) -> dict:
+ return {
+ "ic_mean": 0.031,
+ "ic_std": 0.12,
+ "ir": 0.258,
+ "ic_positive_ratio": 0.56,
+ "ic_count": ic_count,
+ }
+
+
+def test_factor_endpoint_single_factor_happy_path(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ run_dir = tmp_path / "runs" / "run_20240102_093000"
+ summary = _summary(730)
+ _write_factor_bundle(
+ run_dir,
+ "momentum_20d",
+ "date,IC\n2024-01-02,0.0432\n2024-01-03,not-a-number\n2024-01-04,0.0211\n",
+ summary,
+ "date,Group_1,Group_2,Group_3,Group_4,Group_5\n"
+ "2024-01-02,1.0,1.001,1.002,1.003,1.004\n"
+ "2024-01-03,0.99,1.002,1.005,1.007,1.01\n"
+ "2024-01-04,0.95,1.0,1.03,1.05,1.07\n",
+ )
+
+ response = client.get("/runs/run_20240102_093000/factor")
+
+ assert response.status_code == 200
+ payload = response.json()
+ assert payload["exists"] is True
+ assert payload["ic_correlation"] is None
+ assert len(payload["factors"]) == 1
+ factor = payload["factors"][0]
+ assert factor["name"] == "momentum_20d"
+ assert factor["path"] == "artifacts/factor/momentum_20d"
+ assert factor["ic_series"] == [
+ {"date": "2024-01-02", "ic": 0.0432},
+ {"date": "2024-01-04", "ic": 0.0211},
+ ]
+ assert factor["ic_stats"] == summary
+ assert factor["n_groups"] == 5
+ assert factor["long_short_spread"] == round(1.07 - 0.95, 6)
+ assert factor["group_final_equity"] == {
+ "Group_1": 0.95,
+ "Group_2": 1.0,
+ "Group_3": 1.03,
+ "Group_4": 1.05,
+ "Group_5": 1.07,
+ }
+ assert factor["group_equity"][-1] == {
+ "date": "2024-01-04",
+ "Group_1": 0.95,
+ "Group_2": 1.0,
+ "Group_3": 1.03,
+ "Group_4": 1.05,
+ "Group_5": 1.07,
+ }
+
+
+def test_factor_endpoint_two_factors_ic_correlation(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ run_dir = tmp_path / "runs" / "run_20240102_093100"
+ dates = [f"2024-01-{day:02d}" for day in range(2, 14)] # 12 common dates
+ momentum_rows = [(date, round(0.01 * (index + 1), 4)) for index, date in enumerate(dates)]
+ reversal_rows = [(date, round(-0.01 * (index + 1), 4)) for index, date in enumerate(dates)]
+ _write_factor_bundle(run_dir, "momentum_20d", _ic_csv(momentum_rows), _summary(len(dates)))
+ _write_factor_bundle(run_dir, "reversal_5d", _ic_csv(reversal_rows), _summary(len(dates)))
+
+ response = client.get("/runs/run_20240102_093100/factor")
+
+ assert response.status_code == 200
+ payload = response.json()
+ assert payload["exists"] is True
+ assert [factor["name"] for factor in payload["factors"]] == ["momentum_20d", "reversal_5d"]
+ correlation = payload["ic_correlation"]
+ assert correlation["labels"] == ["momentum_20d", "reversal_5d"]
+ matrix = correlation["matrix"]
+ assert len(matrix) == 2 and all(len(row) == 2 for row in matrix)
+ assert matrix[0][0] == 1.0 and matrix[1][1] == 1.0
+ assert matrix[0][1] == matrix[1][0]
+ assert -1.0 <= matrix[0][1] <= 1.0
+ assert matrix[0][1] == -1.0 # perfectly opposed IC series
+
+
+def test_factor_endpoint_run_without_artifacts(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ (tmp_path / "runs" / "run_empty").mkdir(parents=True)
+
+ response = client.get("/runs/run_empty/factor")
+
+ assert response.status_code == 200
+ assert response.json() == {"exists": False, "factors": [], "ic_correlation": None}
+
+
+def test_factor_endpoint_unknown_run_returns_404(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+
+ response = client.get("/runs/missing_run/factor")
+
+ assert response.status_code == 404
+ assert response.json()["detail"] == "Run missing_run not found"
+
+
+def test_factor_endpoint_traversal_run_id_returns_400(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+
+ response = client.get("/runs/foo.bar/factor")
+
+ assert response.status_code == 400
+ assert response.json()["detail"] == "invalid run_id"
+
+
+def test_factor_endpoint_missing_ic_summary_omits_ic_stats(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ run_dir = tmp_path / "runs" / "run_no_summary"
+ _write_factor_bundle(run_dir, "value_factor", "date,IC\n2024-01-02,0.01\n", None)
+
+ response = client.get("/runs/run_no_summary/factor")
+
+ assert response.status_code == 200
+ payload = response.json()
+ assert payload["exists"] is True
+ factor = payload["factors"][0]
+ assert factor["name"] == "value_factor"
+ assert "ic_stats" not in factor
+ assert factor["group_equity"] == []
+ assert factor["n_groups"] == 0
+ assert factor["long_short_spread"] is None
+ assert factor["group_final_equity"] == {}
+
+
+def test_run_detail_has_factor_artifacts_flag(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ with_factor = tmp_path / "runs" / "run_with_factor"
+ _write_factor_bundle(with_factor, "momentum_20d", "date,IC\n2024-01-02,0.02\n", _summary(1))
+ (tmp_path / "runs" / "run_without_factor").mkdir(parents=True)
+
+ response_with = client.get("/runs/run_with_factor")
+ assert response_with.status_code == 200
+ assert response_with.json()["has_factor_artifacts"] is True
+
+ response_without = client.get("/runs/run_without_factor")
+ assert response_without.status_code == 200
+ assert response_without.json()["has_factor_artifacts"] is False
diff --git a/frontend/src/components/charts/CorrelationMatrix.tsx b/frontend/src/components/charts/CorrelationMatrix.tsx
index 0eb29455e..ade4e5d84 100644
--- a/frontend/src/components/charts/CorrelationMatrix.tsx
+++ b/frontend/src/components/charts/CorrelationMatrix.tsx
@@ -10,6 +10,23 @@ interface Props {
height?: number;
}
+const RDBU_STOPS = ["#2166ac", "#4393c3", "#92c5de", "#d1e5f0", "#f7f7f7", "#fddbc7", "#f4a582", "#d6604d", "#b2182b"];
+
+function hexToRgb(hex: string): [number, number, number] {
+ const n = parseInt(hex.slice(1), 16);
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
+}
+
+function cellTextColor(value: number): string {
+ const pos = Math.min(1, Math.max(0, (value + 1) / 2)) * (RDBU_STOPS.length - 1);
+ const idx = Math.min(RDBU_STOPS.length - 2, Math.floor(pos));
+ const frac = pos - idx;
+ const [r1, g1, b1] = hexToRgb(RDBU_STOPS[idx]);
+ const [r2, g2, b2] = hexToRgb(RDBU_STOPS[idx + 1]);
+ const luminance = (0.299 * (r1 + (r2 - r1) * frac) + 0.587 * (g1 + (g2 - g1) * frac) + 0.114 * (b1 + (b2 - b1) * frac)) / 255;
+ return luminance > 0.55 ? "#1f2937" : "#ffffff";
+}
+
export function CorrelationMatrix({ labels, matrix, height = 500 }: Props) {
const ref = useRef<HTMLDivElement>(null);
const dark = useThemeDark();
@@ -20,12 +37,12 @@ export function CorrelationMatrix({ labels, matrix, height = 500 }: Props) {
const t = getChartTheme();
const chart = echarts.init(ref.current);
- // Build heatmap data: [xIdx, yIdx, value]
- const data: [number, number, number][] = [];
+ // Build heatmap data: [xIdx, yIdx, value] with per-cell label color for readability on saturated cells
+ const data: { value: [number, number, number]; label: { color: string } }[] = [];
for (let i = 0; i < labels.length; i++) {
for (let j = 0; j < labels.length; j++) {
- const val = matrix[i]?.[j] ?? 0;
- data.push([j, i, parseFloat(val.toFixed(4))]);
+ const val = parseFloat((matrix[i]?.[j] ?? 0).toFixed(4));
+ data.push({ value: [j, i, val], label: { color: cellTextColor(val) } });
}
}
@@ -40,8 +57,8 @@ export function CorrelationMatrix({ labels, matrix, height = 500 }: Props) {
borderColor: t.tooltipBorder,
textStyle: { color: t.tooltipText, fontSize: 12 },
formatter: (params: unknown) => {
- const p = params as { data: [number, number, number] };
- const [x, y, v] = p.data;
+ const p = params as { data: { value: [number, number, number] } };
+ const [x, y, v] = p.data.value;
return `<b>${labels[x]}</b> vs <b>${labels[y]}</b><br/>r = <b>${v.toFixed(4)}</b>`;
},
},
@@ -75,7 +92,7 @@ export function CorrelationMatrix({ labels, matrix, height = 500 }: Props) {
top: "center",
textStyle: { color: t.textColor, fontSize: 11 },
inRange: {
- color: ["#2166ac", "#4393c3", "#92c5de", "#d1e5f0", "#f7f7f7", "#fddbc7", "#f4a582", "#d6604d", "#b2182b"],
+ color: RDBU_STOPS,
},
},
series: [
@@ -86,7 +103,6 @@ export function CorrelationMatrix({ labels, matrix, height = 500 }: Props) {
label: {
show: labels.length <= 8,
fontSize: 10,
- color: t.textColor,
formatter: (params: unknown) => {
const p = params as { value: [number, number, number] };
return p.value[2].toFixed(2);
diff --git a/frontend/src/components/charts/FactorResearchPanel.tsx b/frontend/src/components/charts/FactorResearchPanel.tsx
new file mode 100644
index 000000000..9c04e2404
--- /dev/null
+++ b/frontend/src/components/charts/FactorResearchPanel.tsx
@@ -0,0 +1,269 @@
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { BarChart3, Grid3x3, LineChart, Sigma } from "lucide-react";
+import { echarts } from "@/lib/echarts";
+import { getChartTheme } from "@/lib/chart-theme";
+import { useThemeDark } from "@/lib/theme-store";
+import { cn } from "@/lib/utils";
+import type { FactorReportPayload, FactorResult } from "@/lib/api";
+import { RunCardPanel, RunCardStat } from "@/pages/RunDetail";
+import { CorrelationMatrix } from "./CorrelationMatrix";
+
+const SLATE = "#8f98a6";
+const IC_MA_WINDOW = 20;
+const MAX_CHART_POINTS = 500;
+
+function num(value: unknown): number | null {
+ if (value === null || value === undefined || value === "") return null;
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : null;
+}
+
+function fixed(value: unknown, digits = 4): string {
+ const parsed = num(value);
+ return parsed == null ? "—" : parsed.toFixed(digits);
+}
+
+function pct(value: unknown, digits = 2): string {
+ const parsed = num(value);
+ return parsed == null ? "—" : `${(parsed * 100).toFixed(digits)}%`;
+}
+
+/** Stride-sample long series for rendering, keeping the LAST point pinned. */
+function downsample<T>(rows: T[], maxPoints = MAX_CHART_POINTS): T[] {
+ if (rows.length <= maxPoints) return rows;
+ const stride = Math.floor(rows.length / maxPoints);
+ const sampled: T[] = [];
+ for (let i = 0; i < rows.length; i += stride) sampled.push(rows[i]);
+ if (sampled[sampled.length - 1] !== rows[rows.length - 1]) {
+ sampled.push(rows[rows.length - 1]);
+ }
+ return sampled;
+}
+
+/** Simple moving average; the first window-1 points are null (skipped). */
+function movingAverage(values: number[], window = IC_MA_WINDOW): Array<number | null> {
+ return values.map((_, index) => {
+ if (index + 1 < window) return null;
+ let sum = 0;
+ for (let i = index + 1 - window; i <= index; i += 1) sum += values[i];
+ return sum / window;
+ });
+}
+
+type IcRow = { date: string; ic: number; ma: number | null };
+
+function groupColumnsOf(factor: FactorResult, rows: FactorResult["group_equity"]): string[] {
+ const present = new Set<string>();
+ for (const row of rows) {
+ for (const key of Object.keys(row)) {
+ if (key !== "date") present.add(key);
+ }
+ }
+ const declared = Array.from({ length: Math.max(0, factor.n_groups || 0) }, (_, i) => `Group_${i + 1}`)
+ .filter((col) => present.has(col));
+ if (declared.length > 0) return declared;
+ return [...present].sort((a, b) => {
+ const suffixA = Number(a.split("_")[1] || 0);
+ const suffixB = Number(b.split("_")[1] || 0);
+ return suffixA - suffixB;
+ });
+}
+
+export function FactorResearchPanel({ report }: { report: FactorReportPayload }) {
+ const { t } = useTranslation();
+ const icRef = useRef<HTMLDivElement>(null);
+ const equityRef = useRef<HTMLDivElement>(null);
+ const dark = useThemeDark();
+
+ const factors = report.factors;
+ const [selectedName, setSelectedName] = useState(factors[0]?.name ?? "");
+ const selected = useMemo(
+ () => factors.find((factor) => factor.name === selectedName) || factors[0] || null,
+ [factors, selectedName],
+ );
+
+ const icRows = useMemo<IcRow[]>(() => {
+ if (!selected || !selected.ic_series?.length) return [];
+ const series = selected.ic_series;
+ const ma = movingAverage(series.map((point) => point.ic));
+ const rows = series.map((point, index) => ({ date: point.date, ic: point.ic, ma: ma[index] }));
+ return downsample(rows);
+ }, [selected]);
+
+ const equityData = useMemo(() => {
+ if (!selected || !selected.group_equity?.length) {
+ return { rows: [] as FactorResult["group_equity"], columns: [] as string[] };
+ }
+ const rows = downsample(selected.group_equity);
+ return { rows, columns: groupColumnsOf(selected, rows) };
+ }, [selected]);
+
+ useEffect(() => {
+ const theme = getChartTheme();
+ const axis = {
+ axisLine: { lineStyle: { color: theme.axisColor } },
+ axisLabel: { color: theme.textColor, fontSize: 10 },
+ splitLine: { lineStyle: { color: theme.gridColor } },
+ };
+ const charts: ReturnType<typeof echarts.init>[] = [];
+ const nodes: HTMLDivElement[] = [];
+
+ if (icRef.current && icRows.length > 0) {
+ const icChart = echarts.init(icRef.current);
+ icChart.setOption({
+ backgroundColor: "transparent",
+ tooltip: { trigger: "axis", axisPointer: { type: "shadow" } },
+ legend: { top: 0, right: 4, textStyle: { color: theme.textColor, fontSize: 10 } },
+ grid: { left: 18, right: 22, top: 32, bottom: 18, containLabel: true },
+ xAxis: { ...axis, type: "category", data: icRows.map((row) => row.date) },
+ yAxis: { ...axis, type: "value" },
+ series: [
+ {
+ name: t("factor.icSeries"),
+ type: "bar",
+ barMaxWidth: 8,
+ // Neutral series color drives the legend swatch; per-point itemStyle below keeps sign coloring.
+ color: SLATE,
+ data: icRows.map((row) => ({
+ value: row.ic,
+ itemStyle: { color: row.ic >= 0 ? theme.upColor : theme.downColor },
+ })),
+ markLine: {
+ symbol: "none",
+ silent: true,
+ label: { show: false },
+ lineStyle: { color: theme.axisColor, type: "dashed" },
+ data: [{ yAxis: 0 }],
+ },
+ },
+ {
+ name: t("factor.icMa"),
+ type: "line",
+ showSymbol: false,
+ connectNulls: false,
+ data: icRows.map((row) => row.ma),
+ lineStyle: { color: theme.infoColor, width: 1.5 },
+ itemStyle: { color: theme.infoColor },
+ },
+ ],
+ });
+ charts.push(icChart);
+ nodes.push(icRef.current);
+ }
+
+ if (equityRef.current && equityData.rows.length > 0 && equityData.columns.length > 0) {
+ const equityChart = echarts.init(equityRef.current);
+ equityChart.setOption({
+ backgroundColor: "transparent",
+ tooltip: { trigger: "axis" },
+ legend: { top: 0, right: 4, textStyle: { color: theme.textColor, fontSize: 10 } },
+ grid: { left: 18, right: 22, top: 32, bottom: 18, containLabel: true },
+ xAxis: { ...axis, type: "category", data: equityData.rows.map((row) => row.date), boundaryGap: false },
+ yAxis: { ...axis, type: "value", scale: true },
+ series: equityData.columns.map((col, index) => {
+ const isTop = index === equityData.columns.length - 1;
+ const isBottom = index === 0 && equityData.columns.length > 1;
+ const color = isTop ? theme.upColor : isBottom ? theme.downColor : SLATE;
+ return {
+ name: col,
+ type: "line",
+ showSymbol: false,
+ data: equityData.rows.map((row) => num(row[col])),
+ lineStyle: { color, width: isTop || isBottom ? 2 : 1.2 },
+ itemStyle: { color },
+ };
+ }),
+ });
+ charts.push(equityChart);
+ nodes.push(equityRef.current);
+ }
+
+ if (charts.length === 0) return;
+
+ let frame: number | null = null;
+ const observer = new ResizeObserver(() => {
+ if (frame != null) cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(() => charts.forEach((chart) => chart.resize()));
+ });
+ nodes.forEach((node) => observer.observe(node));
+ return () => {
+ observer.disconnect();
+ if (frame != null) cancelAnimationFrame(frame);
+ charts.forEach((chart) => chart.dispose());
+ };
+ }, [dark, icRows, equityData, t]);
+
+ if (factors.length === 0 || !selected) {
+ return <div className="p-8 text-center text-sm text-muted-foreground">{t("factor.noFactorData")}</div>;
+ }
+
+ const stats = selected.ic_stats;
+ const correlation = report.ic_correlation;
+
+ return (
+ <div className="space-y-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="min-w-0">
+ <h2 className="text-lg font-semibold tracking-tight">{t("factor.title")}</h2>
+ <p data-testid="factor-selected" className="mt-0.5 truncate font-mono text-xs text-muted-foreground">{selected.name}</p>
+ </div>
+ {factors.length >= 2 && (
+ <div className="flex flex-wrap items-center gap-1">
+ <span className="mr-1 text-xs text-muted-foreground">{t("factor.selectFactor")}</span>
+ {factors.map((factor) => (
+ <button
+ key={factor.name}
+ type="button"
+ onClick={() => setSelectedName(factor.name)}
+ className={cn(
+ "flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm transition-colors",
+ selected.name === factor.name
+ ? "bg-primary/10 font-medium text-primary"
+ : "text-muted-foreground hover:bg-muted/60",
+ )}
+ >
+ {factor.name}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+
+ <RunCardPanel title={t("factor.icStats")} icon={Sigma}>
+ <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
+ <RunCardStat label={t("factor.icMean")} value={fixed(stats?.ic_mean)} />
+ <RunCardStat label={t("factor.icStd")} value={fixed(stats?.ic_std)} />
+ <RunCardStat label={t("factor.ir")} value={fixed(stats?.ir)} />
+ <RunCardStat label={t("factor.icPositiveRatio")} value={pct(stats?.ic_positive_ratio)} />
+ <RunCardStat label={t("factor.icCount")} value={stats ? String(stats.ic_count) : "—"} />
+ <RunCardStat label={t("factor.longShortSpread")} value={fixed(selected.long_short_spread)} />
+ <RunCardStat label={t("factor.nGroups")} value={selected.n_groups ? String(selected.n_groups) : "—"} />
+ </div>
+ </RunCardPanel>
+
+ {icRows.length > 0 && (
+ <RunCardPanel title={t("factor.icSeries")} icon={BarChart3}>
+ <div ref={icRef} className="h-[320px]" />
+ </RunCardPanel>
+ )}
+
+ {equityData.rows.length > 0 && equityData.columns.length > 0 && (
+ <RunCardPanel title={t("factor.quantileEquity")} icon={LineChart}>
+ <div ref={equityRef} className="h-[360px]" />
+ <p className="mt-2 text-xs text-muted-foreground">{t("factor.quantileEquityNote")}</p>
+ </RunCardPanel>
+ )}
+
+ {correlation && (
+ <RunCardPanel title={t("factor.correlation")} icon={Grid3x3}>
+ <CorrelationMatrix labels={correlation.labels} matrix={correlation.matrix} height={420} />
+ <p className="mt-2 text-xs text-muted-foreground">{t("factor.correlationNote")}</p>
+ </RunCardPanel>
+ )}
+ {!correlation && factors.length >= 2 && (
+ <p className="text-xs text-muted-foreground">{t("factor.insufficientOverlap")}</p>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/components/charts/__tests__/FactorResearchPanel.test.tsx b/frontend/src/components/charts/__tests__/FactorResearchPanel.test.tsx
new file mode 100644
index 000000000..65b0d7d84
--- /dev/null
+++ b/frontend/src/components/charts/__tests__/FactorResearchPanel.test.tsx
@@ -0,0 +1,126 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { FactorResearchPanel } from "../FactorResearchPanel";
+import type { FactorReportPayload, FactorResult } from "@/lib/api";
+
+// No canvas in jsdom: stub the echarts instance contract so chart init is a
+// no-op and only the DOM around the charts is asserted here.
+vi.mock("@/lib/echarts", () => ({
+ CHART_GROUP: "quant-charts",
+ connectCharts: vi.fn(),
+ echarts: {
+ init: vi.fn(() => ({ setOption: vi.fn(), resize: vi.fn(), dispose: vi.fn(), group: "" })),
+ },
+}));
+
+vi.mock("../CorrelationMatrix", () => ({
+ CorrelationMatrix: ({ labels, matrix }: { labels: string[]; matrix: number[][] }) => (
+ <div
+ data-testid="factor-correlation-matrix"
+ data-labels={labels.join(",")}
+ data-size={String(matrix.length)}
+ />
+ ),
+}));
+
+function makeFactor(overrides: Partial<FactorResult> = {}): FactorResult {
+ return {
+ name: "momentum_20d",
+ path: "artifacts/factor_momentum_20d",
+ ic_series: [
+ { date: "2024-01-02", ic: 0.031 },
+ { date: "2024-01-03", ic: -0.018 },
+ { date: "2024-01-04", ic: 0.042 },
+ ],
+ ic_stats: { ic_mean: 0.0521, ic_std: 0.0287, ir: 0.8734, ic_positive_ratio: 0.625, ic_count: 128 },
+ group_equity: [
+ { date: "2024-01-02", Group_1: 1.0, Group_2: 1.004, Group_3: 1.011 },
+ { date: "2024-01-03", Group_1: 1.002, Group_2: 1.009, Group_3: 1.02 },
+ ],
+ n_groups: 3,
+ long_short_spread: 0.021,
+ group_final_equity: { Group_1: 1.002, Group_2: 1.009, Group_3: 1.02 },
+ ...overrides,
+ };
+}
+
+function makeReport(overrides: Partial<FactorReportPayload> = {}): FactorReportPayload {
+ return {
+ exists: true,
+ factors: [makeFactor()],
+ ic_correlation: null,
+ ...overrides,
+ };
+}
+
+describe("FactorResearchPanel", () => {
+ it("shows the IC statistics cards for the selected factor", () => {
+ render(<FactorResearchPanel report={makeReport()} />);
+
+ expect(screen.getByText("IC Statistics")).toBeInTheDocument();
+ expect(screen.getByText("0.0521")).toBeInTheDocument(); // ic_mean, 4 decimals
+ expect(screen.getByText("0.8734")).toBeInTheDocument(); // ir
+ expect(screen.getByText("62.50%")).toBeInTheDocument(); // ic_positive_ratio
+ expect(screen.getByText("128")).toBeInTheDocument(); // ic_count
+ expect(screen.getByText("0.0210")).toBeInTheDocument(); // long_short_spread
+ });
+
+ it("renders the factor selector only with multiple factors and switches the selection", () => {
+ const { rerender } = render(<FactorResearchPanel report={makeReport()} />);
+ expect(screen.queryByText("Select factor")).not.toBeInTheDocument();
+
+ const second = makeFactor({
+ name: "value_pe",
+ ic_stats: { ic_mean: -0.0113, ic_std: 0.0301, ir: -0.3754, ic_positive_ratio: 0.44, ic_count: 96 },
+ long_short_spread: -0.012,
+ });
+ rerender(<FactorResearchPanel report={makeReport({ factors: [makeFactor(), second] })} />);
+
+ expect(screen.getByText("Select factor")).toBeInTheDocument();
+ expect(screen.getByTestId("factor-selected")).toHaveTextContent("momentum_20d");
+
+ fireEvent.click(screen.getByRole("button", { name: "value_pe" }));
+
+ expect(screen.getByTestId("factor-selected")).toHaveTextContent("value_pe");
+ expect(screen.getByText("-0.0113")).toBeInTheDocument();
+ expect(screen.queryByText("0.0521")).not.toBeInTheDocument();
+ });
+
+ it("renders the IC correlation heatmap only when the report provides it", () => {
+ const twoFactors = [makeFactor(), makeFactor({ name: "value_pe" })];
+ const overlapNote =
+ "IC correlation is unavailable because the factor IC series do not overlap enough on common dates.";
+
+ const { rerender } = render(<FactorResearchPanel report={makeReport()} />);
+ expect(screen.queryByTestId("factor-correlation-matrix")).not.toBeInTheDocument();
+ expect(screen.queryByText(overlapNote)).not.toBeInTheDocument();
+
+ rerender(<FactorResearchPanel report={makeReport({ factors: twoFactors })} />);
+ expect(screen.queryByTestId("factor-correlation-matrix")).not.toBeInTheDocument();
+ expect(screen.getByText(overlapNote)).toBeInTheDocument();
+
+ rerender(
+ <FactorResearchPanel
+ report={makeReport({
+ factors: twoFactors,
+ ic_correlation: {
+ labels: ["momentum_20d", "value_pe"],
+ matrix: [
+ [1, 0.42],
+ [0.42, 1],
+ ],
+ },
+ })}
+ />,
+ );
+ expect(screen.queryByText(overlapNote)).not.toBeInTheDocument();
+ expect(screen.getByTestId("factor-correlation-matrix")).toHaveAttribute(
+ "data-labels",
+ "momentum_20d,value_pe",
+ );
+ });
+
+ it("shows the empty state when the report has no factors", () => {
+ render(<FactorResearchPanel report={{ exists: false, factors: [], ic_correlation: null }} />);
+ expect(screen.getByText("No factor analysis results are available for this run.")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index 528934c2d..47b1df14d 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -544,6 +544,7 @@
"goBack": "رجوع",
"chart": "الرسم البياني",
"trades": "التداولات",
+ "factor": "تحليل العوامل",
"studio": "استوديو المحفظة",
"riskXray": "الأشعة السينية للمخاطر",
"rebalanceNotes": "ملاحظات إعادة التوازن",
@@ -1299,5 +1300,27 @@
"colQty": "الكمية",
"colPnl": "الربح/الخسارة",
"colReason": "السبب"
+ },
+ "factor": {
+ "title": "تحليل العوامل",
+ "selectFactor": "اختيار العامل",
+ "icSeries": "IC اليومي",
+ "icMa": "متوسط متحرك لـ 20 فترة",
+ "icStats": "إحصاءات IC",
+ "icMean": "متوسط IC",
+ "icStd": "الانحراف المعياري لـ IC",
+ "ir": "نسبة المعلومات",
+ "icPositiveRatio": "نسبة IC>0",
+ "icCount": "عدد ملاحظات IC",
+ "longShortSpread": "فارق الشراء/البيع",
+ "nGroups": "عدد الشرائح",
+ "quantileEquity": "أصول الشرائح الكمية",
+ "quantileEquityNote": "تمثل Group_1 أدنى قيم العامل وتمثل Group_N أعلاها؛ ويقيس الفارق بين أعلى شريحة وأدناها قوة الاختيار.",
+ "correlation": "ارتباط IC",
+ "correlationNote": "الارتباط الزوجي بين السلاسل الزمنية اليومية لـ IC عبر العوامل؛ العوامل شديدة الارتباط تحمل معلومات متداخلة.",
+ "insufficientOverlap": "لا يمكن حساب ارتباط IC لعدم كفاية التداخل في التواريخ المشتركة بين سلاسل IC للعوامل.",
+ "loading": "جارٍ تحميل نتائج تحليل العوامل…",
+ "error": "تعذّر تحميل نتائج تحليل العوامل",
+ "noFactorData": "لا تتوفر نتائج تحليل عوامل لهذا التشغيل."
}
}
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index d66a41ddd..e2be81a00 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -549,6 +549,7 @@
"goBack": "Go back",
"chart": "Chart",
"trades": "Trades",
+ "factor": "Factor Research",
"studio": "Portfolio Studio",
"riskXray": "Risk X-Ray",
"rebalanceNotes": "Rebalance Notes",
@@ -1299,5 +1300,27 @@
"colQty": "Qty",
"colPnl": "PnL",
"colReason": "Reason"
+ },
+ "factor": {
+ "title": "Factor Research",
+ "selectFactor": "Select factor",
+ "icSeries": "Daily IC",
+ "icMa": "20-period MA",
+ "icStats": "IC Statistics",
+ "icMean": "IC Mean",
+ "icStd": "IC Std",
+ "ir": "IR",
+ "icPositiveRatio": "IC > 0 Ratio",
+ "icCount": "IC Observations",
+ "longShortSpread": "Long-Short Spread",
+ "nGroups": "Quantile Groups",
+ "quantileEquity": "Quantile Group Equity",
+ "quantileEquityNote": "Group_1 holds the lowest factor values and Group_N the highest; the gap between the top and bottom quantiles measures selection power.",
+ "correlation": "IC Correlation",
+ "correlationNote": "Pairwise correlation of the daily IC time series across factors; highly correlated factors carry overlapping information.",
+ "insufficientOverlap": "IC correlation is unavailable because the factor IC series do not overlap enough on common dates.",
+ "loading": "Loading factor results…",
+ "error": "Failed to load factor results",
+ "noFactorData": "No factor analysis results are available for this run."
}
}
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index 77f3679cf..b3ad58e71 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -549,6 +549,7 @@
"goBack": "Volver",
"chart": "Gráfico",
"trades": "Operaciones",
+ "factor": "Investigación de factores",
"studio": "Estudio de portafolio",
"riskXray": "Radiografía de riesgo",
"rebalanceNotes": "Notas de rebalanceo",
@@ -1299,5 +1300,27 @@
"colQty": "Cantidad",
"colPnl": "P&L",
"colReason": "Motivo"
+ },
+ "factor": {
+ "title": "Investigación de factores",
+ "selectFactor": "Seleccionar factor",
+ "icSeries": "IC diario",
+ "icMa": "Media móvil de 20 períodos",
+ "icStats": "Estadísticas de IC",
+ "icMean": "Media de IC",
+ "icStd": "Desviación de IC",
+ "ir": "IR",
+ "icPositiveRatio": "Ratio IC>0",
+ "icCount": "Observaciones de IC",
+ "longShortSpread": "Diferencial largo-corto",
+ "nGroups": "Grupos de cuantiles",
+ "quantileEquity": "Capital de grupos de cuantiles",
+ "quantileEquityNote": "Group_1 contiene los valores más bajos del factor y Group_N los más altos; la brecha entre el cuantil superior y el inferior mide el poder de selección.",
+ "correlation": "Correlación de IC",
+ "correlationNote": "Correlación por pares de las series diarias de IC entre factores; los factores muy correlacionados aportan información superpuesta.",
+ "insufficientOverlap": "La correlación de IC no está disponible porque las series de IC no se solapan suficiente en fechas comunes.",
+ "loading": "Cargando resultados de factores…",
+ "error": "Error al cargar los resultados de factores",
+ "noFactorData": "No hay resultados de análisis de factores disponibles para esta ejecución."
}
}
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index de72586a8..f9f48ab1b 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -544,6 +544,7 @@
"goBack": "戻る",
"chart": "チャート",
"trades": "トレード",
+ "factor": "ファクター分析",
"studio": "ポートフォリオスタジオ",
"riskXray": "リスクエックス線",
"rebalanceNotes": "リバランスノート",
@@ -1299,5 +1300,27 @@
"colQty": "数量",
"colPnl": "損益",
"colReason": "理由"
+ },
+ "factor": {
+ "title": "ファクター分析",
+ "selectFactor": "ファクターを選択",
+ "icSeries": "日次 IC",
+ "icMa": "20期間移動平均",
+ "icStats": "IC 統計",
+ "icMean": "IC 平均",
+ "icStd": "IC 標準偏差",
+ "ir": "IR",
+ "icPositiveRatio": "IC>0 比率",
+ "icCount": "IC サンプル数",
+ "longShortSpread": "ロング・ショート差",
+ "nGroups": "分位グループ数",
+ "quantileEquity": "分位グループ純資産",
+ "quantileEquityNote": "Group_1 はファクター値が最も低いグループ、Group_N は最も高いグループです。上位と下位の分位グループ間の差が選別力を示します。",
+ "correlation": "IC 相関",
+ "correlationNote": "各ファクターの日次 IC 時系列のペアワイズ相関。相関が高いファクターは重複した情報を持ちます。",
+ "insufficientOverlap": "ファクター IC シリーズの共通日付の重複が不十分なため、IC 相関を計算できません。",
+ "loading": "ファクター分析結果を読み込み中…",
+ "error": "ファクター分析結果の読み込みに失敗しました",
+ "noFactorData": "この実行には利用可能なファクター分析結果がありません。"
}
}
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 8d9551cf9..e00f8ace1 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -544,6 +544,7 @@
"goBack": "뒤로",
"chart": "차트",
"trades": "거래",
+ "factor": "팩터 분석",
"studio": "포트폴리오 스튜디오",
"riskXray": "리스크 엑스레이",
"rebalanceNotes": "리밸런스 노트",
@@ -1299,5 +1300,27 @@
"colQty": "수량",
"colPnl": "손익",
"colReason": "사유"
+ },
+ "factor": {
+ "title": "팩터 분석",
+ "selectFactor": "팩터 선택",
+ "icSeries": "일별 IC",
+ "icMa": "20기간 이동평균",
+ "icStats": "IC 통계",
+ "icMean": "IC 평균",
+ "icStd": "IC 표준편차",
+ "ir": "IR",
+ "icPositiveRatio": "IC>0 비율",
+ "icCount": "IC 관측치",
+ "longShortSpread": "롱-숏 스프레드",
+ "nGroups": "분위 그룹 수",
+ "quantileEquity": "분위 그룹 자산",
+ "quantileEquityNote": "Group_1은 팩터 값이 가장 낮은 그룹이고 Group_N은 가장 높은 그룹입니다. 최상위와 최하위 분위의 차이는 종목 선정력을 나타냅니다.",
+ "correlation": "IC 상관관계",
+ "correlationNote": "팩터 간 일별 IC 시계열의 쌍별 상관관계입니다. 상관계수가 높은 팩터는 중복된 정보를 담고 있습니다.",
+ "insufficientOverlap": "팩터 IC 시계열의 공통 날짜 중복이 부족하여 IC 상관관계를 계산할 수 없습니다.",
+ "loading": "팩터 분석 결과를 불러오는 중…",
+ "error": "팩터 분석 결과를 불러오지 못했습니다",
+ "noFactorData": "이 실행에는 사용 가능한 팩터 분석 결과가 없습니다."
}
}
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index 679170192..ffa85fa8d 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -544,6 +544,7 @@
"goBack": "返回",
"chart": "图表",
"trades": "交易",
+ "factor": "因子研究",
"studio": "组合工作室",
"riskXray": "风险透视",
"rebalanceNotes": "调仓笔记",
@@ -1299,5 +1300,27 @@
"colQty": "数量",
"colPnl": "盈亏",
"colReason": "原因"
+ },
+ "factor": {
+ "title": "因子研究",
+ "selectFactor": "选择因子",
+ "icSeries": "日度 IC",
+ "icMa": "20 期均线",
+ "icStats": "IC 统计",
+ "icMean": "IC 均值",
+ "icStd": "IC 标准差",
+ "ir": "IR",
+ "icPositiveRatio": "IC>0 占比",
+ "icCount": "IC 样本数",
+ "longShortSpread": "多空收益差",
+ "nGroups": "分组数",
+ "quantileEquity": "分位数组合净值",
+ "quantileEquityNote": "Group_1 为因子值最低组,Group_N 为因子值最高组;首尾分位组的净值差距衡量因子的选股能力。",
+ "correlation": "IC 相关性",
+ "correlationNote": "各因子日度 IC 时间序列两两之间的相关系数;高度相关的因子携带的信息高度重叠。",
+ "insufficientOverlap": "各因子 IC 序列的共同日期重叠不足,无法计算 IC 相关性。",
+ "loading": "正在加载因子分析结果…",
+ "error": "加载因子分析结果失败",
+ "noFactorData": "本次运行没有可用的因子分析结果。"
}
}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 286baf21c..c33510326 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -146,6 +146,7 @@ export const api = {
return request<RunData>(`/runs/${id}${qs ? `?${qs}` : ""}`);
},
getRunCode: (id: string) => request<Record<string, string>>(`/runs/${id}/code`),
+ getRunFactor: (id: string) => request<FactorReportPayload>(`/runs/${id}/factor`),
getRunPine: (id: string) => request<PineScriptResult>(`/runs/${id}/pine`),
listSessions: () => request<SessionItem[]>("/sessions"),
createSession: (title?: string) => request<SessionItem>("/sessions", { method: "POST", body: JSON.stringify({ title: title || "" }) }),
@@ -611,6 +612,31 @@ export interface RebalanceNotesPayload {
};
}
+export interface FactorIcStats {
+ ic_mean: number;
+ ic_std: number;
+ ir: number;
+ ic_positive_ratio: number;
+ ic_count: number;
+}
+
+export interface FactorResult {
+ name: string;
+ path: string;
+ ic_series: Array<{ date: string; ic: number }>;
+ ic_stats?: FactorIcStats;
+ group_equity: Array<{ date: string } & Record<string, number | string>>;
+ n_groups: number;
+ long_short_spread: number | null;
+ group_final_equity: Record<string, number>;
+}
+
+export interface FactorReportPayload {
+ exists: boolean;
+ factors: FactorResult[];
+ ic_correlation: { labels: string[]; matrix: number[][] } | null;
+}
+
export interface RunData {
status: string;
run_id: string;
@@ -626,6 +652,7 @@ export interface RunData {
risk_xray?: RiskXRayPayload;
rebalance_notes?: RebalanceNotesPayload;
validation?: ValidationData;
+ has_factor_artifacts?: boolean;
chart_symbols?: string[];
price_series?: Record<string, PriceBar[]>;
diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsx
index 1d718f47a..6fda80347 100644
--- a/frontend/src/pages/RunDetail.tsx
+++ b/frontend/src/pages/RunDetail.tsx
@@ -20,12 +20,13 @@ import {
LayoutDashboard,
Loader2,
ShieldCheck,
+ Sigma,
XCircle,
CircleSlash,
} from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
-import { api, type BacktestMetrics, type EquityPoint, type RebalanceNotesPayload, type RiskXRayPayload, type RunCard, type RunData, type ValidationData } from "@/lib/api";
+import { api, type BacktestMetrics, type EquityPoint, type FactorReportPayload, type RebalanceNotesPayload, type RiskXRayPayload, type RunCard, type RunData, type ValidationData } from "@/lib/api";
import {
computeAnnualReturns,
computeMonthlyReturns,
@@ -45,10 +46,11 @@ import { ValidationPanel } from "@/components/charts/ValidationPanel";
import { Skeleton, SkeletonMetrics, SkeletonChart } from "@/components/common/Skeleton";
import { ErrorBoundary } from "@/components/common/ErrorBoundary";
import { getStrategyReportIdentity, StrategyResearchDashboard } from "@/components/charts/StrategyResearchDashboard";
+import { FactorResearchPanel } from "@/components/charts/FactorResearchPanel";
const rehypePlugins = [rehypeHighlight];
-type Tab = "dashboard" | "chart" | "tearsheet" | "trades" | "runCard" | "code" | "validation" | "studio";
+type Tab = "dashboard" | "chart" | "tearsheet" | "trades" | "runCard" | "code" | "validation" | "studio" | "factor";
type ChartPayload = Pick<RunData, "price_series" | "indicator_series" | "trade_markers">;
type ChartCache = Record<string, ChartPayload>;
type ChartLoadProgress = { done: number; total: number };
@@ -133,11 +135,13 @@ export function RunDetail() {
const hasRunCard = !!run?.run_card;
const hasStudio = !!run?.risk_xray || !!run?.rebalance_notes;
const hasTearsheet = (run?.artifacts_equity_csv?.length ?? 0) > 0 || (run?.equity_curve?.length ?? 0) > 0;
+ const hasFactor = !!run?.has_factor_artifacts;
const TABS: { id: Tab; label: string; icon: typeof BarChart3; hidden?: boolean }[] = [
{ id: "dashboard", label: i18n.t("runDetail.dashboard"), icon: LayoutDashboard },
{ id: "chart", label: i18n.t("runDetail.chart"), icon: BarChart3 },
{ id: "tearsheet", label: i18n.t("runDetail.tearsheet"), icon: CalendarRange, hidden: !hasTearsheet },
{ id: "trades", label: i18n.t("runDetail.trades"), icon: List },
+ { id: "factor", label: i18n.t("runDetail.factor"), icon: Sigma, hidden: !hasFactor },
{ id: "studio", label: i18n.t("runDetail.studio"), icon: Gauge, hidden: !hasStudio },
{ id: "validation", label: i18n.t("runDetail.validation"), icon: ShieldCheck, hidden: !hasValidation },
{ id: "runCard", label: i18n.t("runDetail.runCard"), icon: FileCheck2, hidden: !hasRunCard },
@@ -408,6 +412,7 @@ export function RunDetail() {
)}
{tab === "tearsheet" && hasTearsheet && <TearsheetTab run={run} />}
{tab === "trades" && <TradesTab run={run} />}
+ {tab === "factor" && run.has_factor_artifacts && runId && <FactorTab runId={runId} />}
{tab === "validation" && run.validation && <ValidationPanel data={run.validation} />}
{tab === "studio" && hasStudio && (
<StudioTab xray={run.risk_xray} notes={run.rebalance_notes} />
@@ -636,7 +641,64 @@ function TearsheetTab({ run }: { run: RunData }) {
);
}
-function RunCardStat({ label, value, tone = "normal" }: { label: string; value: string; tone?: "normal" | "warning" }) {
+function FactorTab({ runId }: { runId: string }) {
+ const [data, setData] = useState<FactorReportPayload | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState("");
+ const generationRef = useRef(0);
+
+ useEffect(() => {
+ const generation = ++generationRef.current;
+ setLoading(true);
+ setError("");
+ setData(null);
+ api.getRunFactor(runId)
+ .then((payload) => {
+ if (generationRef.current !== generation) return;
+ setData(payload);
+ })
+ .catch((err: unknown) => {
+ if (generationRef.current !== generation) return;
+ setError(err instanceof Error ? err.message : String(err));
+ })
+ .finally(() => {
+ if (generationRef.current === generation) setLoading(false);
+ });
+ return () => {
+ if (generationRef.current === generation) generationRef.current += 1;
+ };
+ }, [runId]);
+
+ if (loading) {
+ return (
+ <div className="p-4 space-y-4">
+ <Skeleton className="h-6 w-48" />
+ <p className="text-xs text-muted-foreground">{i18n.t("factor.loading")}</p>
+ <SkeletonMetrics />
+ <SkeletonChart height={320} />
+ <SkeletonChart height={320} />
+ </div>
+ );
+ }
+ if (error) {
+ return (
+ <div className="p-8 space-y-1">
+ <p className="text-sm font-medium text-danger">{i18n.t("factor.error")}</p>
+ <p className="text-xs text-muted-foreground">{error}</p>
+ </div>
+ );
+ }
+ if (!data || !data.exists || data.factors.length === 0) {
+ return <div className="p-8 text-muted-foreground text-sm">{i18n.t("factor.noFactorData")}</div>;
+ }
+ return (
+ <div className="p-4">
+ <FactorResearchPanel report={data} />
+ </div>
+ );
+}
+
+export function RunCardStat({ label, value, tone = "normal" }: { label: string; value: string; tone?: "normal" | "warning" }) {
return (
<div className="rounded-xl border border-border/60 bg-card p-4 shadow-sm">
<div className="text-xs text-muted-foreground">{label}</div>
@@ -645,7 +707,7 @@ function RunCardStat({ label, value, tone = "normal" }: { label: string; value:
);
}
-function RunCardPanel({ title, icon: Icon, children }: { title: string; icon: typeof FileCheck2; children: ReactNode }) {
+export function RunCardPanel({ title, icon: Icon, children }: { title: string; icon: typeof FileCheck2; children: ReactNode }) {
return (
<section className="rounded-xl border border-border/60 bg-card p-4 shadow-sm">
<div className="mb-3 flex items-center gap-2 text-sm font-semibold">
diff --git a/frontend/src/pages/__tests__/RunDetail.test.tsx b/frontend/src/pages/__tests__/RunDetail.test.tsx
index c48f9ffab..4bd4e5e14 100644
--- a/frontend/src/pages/__tests__/RunDetail.test.tsx
+++ b/frontend/src/pages/__tests__/RunDetail.test.tsx
@@ -6,9 +6,13 @@ import type { RunData } from "@/lib/api";
const apiMock = vi.hoisted(() => ({
getRun: vi.fn(),
getRunCode: vi.fn(),
+ getRunFactor: vi.fn(),
}));
vi.mock("@/lib/api", () => ({ api: apiMock }));
+vi.mock("@/components/charts/FactorResearchPanel", () => ({
+ FactorResearchPanel: () => <div data-testid="factor-panel" />,
+}));
vi.mock("@/components/charts/CandlestickChart", () => ({
CandlestickChart: () => <div data-testid="candlestick-chart" />,
}));
@@ -44,6 +48,7 @@ describe("RunDetail page", () => {
beforeEach(() => {
apiMock.getRun.mockReset();
apiMock.getRunCode.mockReset();
+ apiMock.getRunFactor.mockReset();
});
it("presents a readable strategy title instead of promoting the run id", async () => {
@@ -235,6 +240,57 @@ describe("RunDetail page", () => {
expect(screen.getByRole("columnheader", { name: "Path" })).toHaveClass("ps-4");
expect(screen.getByText("artifacts/result.json")).toHaveClass("ps-4");
});
+
+ it("renders the Factor Research tab from has_factor_artifacts and lazy-loads the report", async () => {
+ apiMock.getRun.mockResolvedValue({
+ status: "success",
+ run_id: "factor-run",
+ prompt: "Factor run",
+ has_factor_artifacts: true,
+ });
+ apiMock.getRunCode.mockResolvedValue({});
+ apiMock.getRunFactor.mockResolvedValue({
+ exists: true,
+ factors: [{
+ name: "momentum_20d",
+ path: "artifacts/factor_momentum_20d",
+ ic_series: [{ date: "2024-01-02", ic: 0.03 }],
+ ic_stats: { ic_mean: 0.03, ic_std: 0.02, ir: 1.5, ic_positive_ratio: 0.6, ic_count: 1 },
+ group_equity: [{ date: "2024-01-02", Group_1: 1, Group_2: 1.01 }],
+ n_groups: 2,
+ long_short_spread: 0.01,
+ group_final_equity: { Group_1: 1, Group_2: 1.01 },
+ }],
+ ic_correlation: null,
+ });
+
+ renderRunDetail("/runs/factor-run");
+
+ await screen.findByText("Factor run");
+ // The factor report is fetched lazily on tab open, never with the main run payload.
+ expect(apiMock.getRunFactor).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole("tab", { name: "Factor Research" }));
+
+ expect(await screen.findByTestId("factor-panel")).toBeInTheDocument();
+ expect(apiMock.getRunFactor).toHaveBeenCalledWith("factor-run");
+ });
+
+ it("hides the Factor Research tab when the run has no factor artifacts", async () => {
+ apiMock.getRun.mockResolvedValue({
+ status: "success",
+ run_id: "no-factor-run",
+ prompt: "No factor run",
+ trade_log: [],
+ });
+ apiMock.getRunCode.mockResolvedValue({});
+
+ renderRunDetail("/runs/no-factor-run");
+
+ await screen.findByText("No factor run");
+ expect(screen.queryByRole("tab", { name: "Factor Research" })).not.toBeInTheDocument();
+ expect(apiMock.getRunFactor).not.toHaveBeenCalled();
+ });
});
it("renders the Portfolio Studio tab from risk_xray and rebalance_notes payloads", async () => {