Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat: add attribution panel and apply cross-panel audit fixes

shadowinlife9da94eef2af2
diff --git a/agent/api_server.py b/agent/api_server.py
index 8d82263fc..9200f2233 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -193,6 +193,8 @@ from src.api.runs_routes import ( # noqa: F401, E402
_load_csv_to_dict,
_build_response_from_run_dir,
)
+from src.api.attribution_routes import register_attribution_routes # noqa: E402
+register_attribution_routes(app)
# --- Sessions ---
from src.api.sessions_routes import register_sessions_routes # noqa: E402
diff --git a/agent/src/api/attribution_core.py b/agent/src/api/attribution_core.py
new file mode 100644
index 000000000..518115c04
--- /dev/null
+++ b/agent/src/api/attribution_core.py
@@ -0,0 +1,783 @@
+"""Pure computation core for the run attribution endpoint.
+
+Builds the ``GET /runs/{run_id}/attribution`` payload exclusively from a run's
+persisted artifacts (``equity.csv``, ``positions.csv``, ``ohlcv_<SYMBOL>.csv``,
+``config.json``, ``metrics.csv``) — no market data is re-fetched. Every section
+degrades independently: a missing artifact nulls its section and appends an
+explanatory note instead of failing the request.
+
+Mounted by ``attribution_routes.py``; kept in its own module so the route file
+stays a thin registration slice.
+"""
+
+from __future__ import annotations
+
+import csv
+import json
+import math
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple
+
+# ---------------------------------------------------------------------------
+# Module constants (no magic numbers in the computation paths below)
+# ---------------------------------------------------------------------------
+
+#: Decimals every response float is rounded to, recursively.
+_ATTRIBUTION_FLOAT_DECIMALS = 6
+#: Maximum points per returned series; longer series are even-stride
+#: downsampled with the last point always pinned.
+_ATTRIBUTION_MAX_SERIES_POINTS = 500
+#: Trailing window length (in bars) for rolling beta/alpha.
+_ATTRIBUTION_ROLLING_WINDOW = 60
+#: Minimum valid observations inside a rolling window for it to emit a point.
+_ATTRIBUTION_MIN_ROLLING_OBS = 40
+#: Minimum aligned observations for the full-sample factor regression.
+_ATTRIBUTION_MIN_FACTOR_OBS = 10
+#: Benchmark return variance below which the series is treated as constant.
+_ATTRIBUTION_BENCHMARK_VARIANCE_FLOOR = 1e-16
+#: Smallest positive cash weight reported as a Brinson cash row.
+_ATTRIBUTION_CASH_WEIGHT_TOLERANCE = 1e-6
+#: Smallest invested weight still reported in the invested/cash fallback.
+_ATTRIBUTION_MIN_INVESTED_WEIGHT = 1e-9
+#: Annualization factor used when the run's interval is unknown.
+_ATTRIBUTION_DEFAULT_BARS_PER_YEAR = 252
+
+#: Bars per year by normalized (lower-cased) interval label.
+_ATTRIBUTION_BARS_PER_YEAR_BY_INTERVAL = {
+ "1d": 252,
+ "d": 252,
+ "daily": 252,
+ "1wk": 52,
+ "w": 52,
+ "weekly": 52,
+ "1mo": 12,
+ "mo": 12,
+ "monthly": 12,
+ "1h": 1638,
+ "30m": 3276,
+ "15m": 6552,
+ "5m": 19656,
+ "1m": 98280,
+}
+
+
+# ---------------------------------------------------------------------------
+# Small shared helpers
+# ---------------------------------------------------------------------------
+
+
+def _attribution_finite_float(value: Any) -> Optional[float]:
+ """Parse a finite float, returning ``None`` for invalid values."""
+ try:
+ parsed = float(value)
+ except (TypeError, ValueError, OverflowError):
+ return None
+ return parsed if math.isfinite(parsed) else None
+
+
+def _attribution_iso_dates(values: List[Any]) -> List[str]:
+ """Normalize timestamp cells to ``YYYY-MM-DD`` date-part strings."""
+ dates: List[str] = []
+ for value in values:
+ text = str(value or "").strip()
+ for separator in ("T", " "):
+ if separator in text:
+ text = text.split(separator, 1)[0]
+ dates.append(text)
+ return dates
+
+
+def _attribution_bars_per_year(interval: Any) -> int:
+ """Infer the annualization factor from the run's bar interval label."""
+ if not interval:
+ return _ATTRIBUTION_DEFAULT_BARS_PER_YEAR
+ return _ATTRIBUTION_BARS_PER_YEAR_BY_INTERVAL.get(
+ str(interval).strip().lower(), _ATTRIBUTION_DEFAULT_BARS_PER_YEAR
+ )
+
+
+def _attribution_downsample(
+ rows: List[Dict[str, Any]], max_points: int = _ATTRIBUTION_MAX_SERIES_POINTS
+) -> List[Dict[str, Any]]:
+ """Even-stride downsample a series, always pinning the last point.
+
+ Args:
+ rows: Series points in chronological order.
+ max_points: Maximum number of points to keep.
+
+ Returns:
+ The original list when within budget, otherwise every ``step``-th row
+ with the final row replacing the last sampled index when needed.
+ """
+ count = len(rows)
+ if count <= max_points or max_points <= 0:
+ return rows
+ step = -(-count // max_points) # ceil division
+ indices = list(range(0, count, step))
+ if indices[-1] != count - 1:
+ indices[-1] = count - 1
+ return [rows[index] for index in indices]
+
+
+def _attribution_round_values(value: Any, decimals: int = _ATTRIBUTION_FLOAT_DECIMALS) -> Any:
+ """Recursively round every float in a JSON-ready structure."""
+ if isinstance(value, float):
+ return round(value, decimals)
+ if isinstance(value, dict):
+ return {key: _attribution_round_values(item, decimals) for key, item in value.items()}
+ if isinstance(value, list):
+ return [_attribution_round_values(item, decimals) for item in value]
+ return value
+
+
+def _attribution_read_csv(path: Path) -> Tuple[Optional[List[str]], List[Dict[str, str]]]:
+ """Read a CSV into ``(fieldnames, rows)``, refusing symlinks.
+
+ Returns ``(None, [])`` when the file is missing, a symlink, or unreadable.
+ """
+ try:
+ if path.is_symlink() or not path.is_file():
+ return None, []
+ with path.open("r", encoding="utf-8", newline="") as handle:
+ reader = csv.DictReader(handle)
+ fieldnames = list(reader.fieldnames or [])
+ rows = [dict(row) for row in reader]
+ return fieldnames, rows
+ except (OSError, UnicodeError, csv.Error):
+ return None, []
+
+
+def _attribution_load_json(path: Path) -> Optional[Dict[str, Any]]:
+ """Load a JSON object from disk if present, not a symlink, and dict-shaped."""
+ try:
+ if path.is_symlink() or not path.is_file():
+ return None
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ return payload if isinstance(payload, dict) else None
+ except (OSError, UnicodeError, ValueError):
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Artifact loading
+# ---------------------------------------------------------------------------
+
+
+def _attribution_load_equity(
+ run_dir: Path,
+) -> Tuple[Optional[List[str]], Optional[List[float]], Optional[List[float]], str]:
+ """Load dates, portfolio returns, and benchmark equity from ``equity.csv``.
+
+ Args:
+ run_dir: Root directory of the run.
+
+ Returns:
+ ``(dates, portfolio_returns, benchmark_equity, benchmark_state)`` where
+ ``benchmark_state`` is ``"ok"``, ``"missing"``, or ``"non_finite"``.
+ Dates and returns are ``None`` when equity.csv itself is unreadable.
+ """
+ fieldnames, rows = _attribution_read_csv(run_dir / "artifacts" / "equity.csv")
+ if fieldnames is None or not rows or "ret" not in fieldnames or "timestamp" not in fieldnames:
+ return None, None, None, "missing"
+
+ dates: List[str] = []
+ portfolio_returns: List[float] = []
+ benchmark_equity: List[float] = []
+ has_benchmark_column = "benchmark_equity" in fieldnames
+ benchmark_all_blank = True
+ for row in rows:
+ ret = _attribution_finite_float(row.get("ret"))
+ if ret is None:
+ continue
+ dates.append(str(row.get("timestamp") or ""))
+ portfolio_returns.append(ret)
+ if has_benchmark_column:
+ benchmark_value = _attribution_finite_float(row.get("benchmark_equity"))
+ if benchmark_value is not None:
+ benchmark_all_blank = False
+ benchmark_equity.append(benchmark_value)
+ else:
+ benchmark_equity.append(float("nan"))
+
+ if not portfolio_returns:
+ return None, None, None, "missing"
+
+ if not has_benchmark_column or benchmark_all_blank:
+ return _attribution_iso_dates(dates), portfolio_returns, None, "missing"
+ if any(math.isnan(value) for value in benchmark_equity):
+ return _attribution_iso_dates(dates), portfolio_returns, None, "non_finite"
+ return _attribution_iso_dates(dates), portfolio_returns, benchmark_equity, "ok"
+
+
+def _attribution_benchmark_returns_from_equity(benchmark_equity: List[float]) -> Optional[List[float]]:
+ """Convert a benchmark equity curve into daily returns.
+
+ The first bar's return is defined as 0.0 (the curve's first value is the
+ first observation, matching the ``pct_change().fillna(0)`` convention).
+ """
+ if len(benchmark_equity) < 2:
+ return None
+ returns = [0.0]
+ for previous, current in zip(benchmark_equity[:-1], benchmark_equity[1:]):
+ if previous <= 0.0:
+ return None
+ returns.append(current / previous - 1.0)
+ return returns
+
+
+def _attribution_symbol_cumulative_return(run_dir: Path, symbol: str) -> Optional[float]:
+ """Buy-and-hold close-to-close return for one symbol from its OHLCV artifact.
+
+ Returns ``last_close / first_close - 1`` over the date-sorted rows, or
+ ``None`` when the artifact is missing, too short, or starts non-positive.
+ """
+ fieldnames, rows = _attribution_read_csv(run_dir / "artifacts" / f"ohlcv_{symbol}.csv")
+ if fieldnames is None or "close" not in fieldnames or not rows:
+ return None
+ dated: List[Tuple[str, float]] = []
+ for row in rows:
+ close = _attribution_finite_float(row.get("close"))
+ if close is not None:
+ dated.append((str(row.get("trade_date") or ""), close))
+ if len(dated) < 2:
+ return None
+ dated.sort(key=lambda item: item[0])
+ first_close = dated[0][1]
+ last_close = dated[-1][1]
+ if first_close <= 0.0:
+ return None
+ return last_close / first_close - 1.0
+
+
+def _attribution_equal_weight_returns(
+ run_dir: Path, codes: List[str], dates: List[str]
+) -> Optional[List[float]]:
+ """Equal-weight daily mean of the configured codes' close-to-close returns.
+
+ Used as the auto-benchmark series when ``equity.csv`` carries no
+ ``benchmark_equity`` column. A symbol's first observed date contributes
+ 0.0. Returns ``None`` when any date lacks symbol coverage.
+ """
+ if not codes or not dates:
+ return None
+ per_symbol: List[Dict[str, float]] = []
+ for symbol in codes:
+ fieldnames, rows = _attribution_read_csv(run_dir / "artifacts" / f"ohlcv_{symbol}.csv")
+ if fieldnames is None or "close" not in fieldnames or not rows:
+ continue
+ closes: List[Tuple[str, float]] = []
+ for row in rows:
+ close = _attribution_finite_float(row.get("close"))
+ if close is not None:
+ closes.append((str(row.get("trade_date") or ""), close))
+ if not closes:
+ continue
+ closes.sort(key=lambda item: item[0])
+ returns_by_date: Dict[str, float] = {closes[0][0]: 0.0}
+ for index in range(1, len(closes)):
+ previous_close = closes[index - 1][1]
+ if previous_close > 0.0:
+ returns_by_date[closes[index][0]] = closes[index][1] / previous_close - 1.0
+ per_symbol.append(returns_by_date)
+ if not per_symbol:
+ return None
+ series: List[float] = []
+ for day in dates:
+ values = [table[day] for table in per_symbol if day in table and math.isfinite(table[day])]
+ if not values:
+ return None
+ series.append(math.fsum(values) / len(values))
+ return series
+
+
+# ---------------------------------------------------------------------------
+# Factor section
+# ---------------------------------------------------------------------------
+
+
+def _attribution_ols(x_values: List[float], y_values: List[float]) -> Optional[Dict[str, float]]:
+ """Ordinary least squares of ``y`` on ``x`` with an intercept.
+
+ Returns ``{"alpha", "beta", "r_squared", "alpha_t_stat"}`` where
+ ``alpha_t_stat`` is the t-statistic of the intercept, or ``None`` when the
+ regressor variance is below ``_ATTRIBUTION_BENCHMARK_VARIANCE_FLOOR``.
+ """
+ n = len(x_values)
+ if n < 2 or n != len(y_values):
+ return None
+ mean_x = math.fsum(x_values) / n
+ mean_y = math.fsum(y_values) / n
+ sxx = math.fsum((x - mean_x) ** 2 for x in x_values)
+ if sxx / n < _ATTRIBUTION_BENCHMARK_VARIANCE_FLOOR:
+ return None
+ sxy = math.fsum((x - mean_x) * (y - mean_y) for x, y in zip(x_values, y_values))
+ beta = sxy / sxx
+ alpha = mean_y - beta * mean_x
+ ssr = math.fsum((y - alpha - beta * x) ** 2 for x, y in zip(x_values, y_values))
+ sst = math.fsum((y - mean_y) ** 2 for y in y_values)
+ if sst <= 0.0:
+ r_squared = 1.0 if ssr <= 0.0 else 0.0
+ else:
+ r_squared = max(0.0, min(1.0, 1.0 - ssr / sst))
+ alpha_t_stat = 0.0
+ if n > 2:
+ sigma_squared = ssr / (n - 2)
+ variance_alpha = sigma_squared * (1.0 / n + mean_x * mean_x / sxx)
+ if variance_alpha > 0.0:
+ alpha_t_stat = alpha / math.sqrt(variance_alpha)
+ return {"alpha": alpha, "beta": beta, "r_squared": r_squared, "alpha_t_stat": alpha_t_stat}
+
+
+def _attribution_factor_section(
+ dates: List[str],
+ portfolio_returns: List[float],
+ benchmark_returns: Optional[List[float]],
+ bars_per_year: int,
+ notes: List[str],
+) -> Optional[Dict[str, Any]]:
+ """Build the factor section: full-sample OLS plus rolling and cumulative series.
+
+ Args:
+ dates: Equity-curve dates aligned with ``portfolio_returns``.
+ portfolio_returns: Portfolio daily returns from ``equity.csv``.
+ benchmark_returns: Benchmark daily returns, or ``None`` when no usable
+ benchmark series exists.
+ bars_per_year: Annualization factor for the run interval.
+ notes: Note accumulator; skip reasons are appended here.
+
+ Returns:
+ The factor section dict, or ``None`` with an explanatory note.
+ """
+ if benchmark_returns is None:
+ notes.append("factor attribution skipped: no benchmark_equity series in equity.csv")
+ return None
+
+ count = min(len(dates), len(portfolio_returns), len(benchmark_returns))
+ aligned: List[Tuple[str, float, float]] = []
+ for index in range(count):
+ portfolio_value = portfolio_returns[index]
+ benchmark_value = benchmark_returns[index]
+ if math.isfinite(portfolio_value) and math.isfinite(benchmark_value):
+ aligned.append((dates[index], portfolio_value, benchmark_value))
+
+ if not aligned:
+ notes.append("factor attribution skipped: benchmark return series is missing or constant")
+ return None
+ if len(aligned) < _ATTRIBUTION_MIN_FACTOR_OBS:
+ notes.append(
+ "factor attribution skipped: only "
+ f"{len(aligned)} observations available (need at least {_ATTRIBUTION_MIN_FACTOR_OBS})"
+ )
+ return None
+
+ x_values = [row[2] for row in aligned]
+ y_values = [row[1] for row in aligned]
+ fit = _attribution_ols(x_values, y_values)
+ if fit is None:
+ notes.append("factor attribution skipped: benchmark return series is missing or constant")
+ return None
+
+ rolling: Optional[List[Dict[str, Any]]] = None
+ if len(aligned) >= _ATTRIBUTION_ROLLING_WINDOW:
+ points: List[Dict[str, Any]] = []
+ for end in range(_ATTRIBUTION_ROLLING_WINDOW, len(aligned) + 1):
+ window = aligned[end - _ATTRIBUTION_ROLLING_WINDOW : end]
+ window_fit = _attribution_ols([row[2] for row in window], [row[1] for row in window])
+ if window_fit is None:
+ continue
+ points.append(
+ {
+ "date": window[-1][0],
+ "beta": window_fit["beta"],
+ "alpha_annualized": window_fit["alpha"] * bars_per_year,
+ }
+ )
+ rolling = points or None
+
+ cumulative: List[Dict[str, Any]] = []
+ portfolio_wealth = 1.0
+ benchmark_wealth = 1.0
+ for day, portfolio_value, benchmark_value in aligned:
+ portfolio_wealth *= 1.0 + portfolio_value
+ benchmark_wealth *= 1.0 + benchmark_value
+ cumulative.append(
+ {
+ "date": day,
+ "portfolio": portfolio_wealth - 1.0,
+ "benchmark": benchmark_wealth - 1.0,
+ "active": portfolio_wealth - benchmark_wealth,
+ }
+ )
+
+ return {
+ "beta": fit["beta"],
+ "alpha_per_period": fit["alpha"],
+ "alpha_annualized": fit["alpha"] * bars_per_year,
+ "alpha_t_stat": fit["alpha_t_stat"],
+ "r_squared": fit["r_squared"],
+ "n_obs": len(aligned),
+ "rolling_window": _ATTRIBUTION_ROLLING_WINDOW,
+ "rolling": _attribution_downsample(rolling) if rolling is not None else None,
+ "cumulative": _attribution_downsample(cumulative),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Brinson section
+# ---------------------------------------------------------------------------
+
+
+def _attribution_run_brinson(
+ mode: str,
+ portfolio_weights: Dict[str, float],
+ benchmark_weights: Dict[str, float],
+ portfolio_returns: Dict[str, float],
+ benchmark_returns: Dict[str, float],
+ notes: List[str],
+) -> Optional[Dict[str, Any]]:
+ """Run ``brinson_fachler`` and serialize the result into the response shape.
+
+ Args:
+ mode: One of ``"symbol"``, ``"asset_class"``, ``"invested_cash"``.
+ portfolio_weights: Sector label to portfolio weight.
+ benchmark_weights: Sector label to benchmark weight.
+ portfolio_returns: Sector label to portfolio sector return.
+ benchmark_returns: Sector label to benchmark sector return.
+ notes: Note accumulator; skip reasons are appended here.
+
+ Returns:
+ The serialized Brinson section, or ``None`` with an explanatory note.
+ """
+ if not portfolio_weights or not benchmark_weights or math.fsum(benchmark_weights.values()) == 0.0:
+ notes.append("brinson attribution skipped: benchmark weight vector sums to zero")
+ return None
+ try:
+ from src.quantlib.attribution import brinson_fachler
+
+ result = brinson_fachler(
+ portfolio_weights, benchmark_weights, portfolio_returns, benchmark_returns
+ )
+ except ValueError as exc:
+ notes.append(f"brinson attribution skipped: {exc}")
+ return None
+ return {
+ "mode": mode,
+ "portfolio_return": result.portfolio_return,
+ "benchmark_return": result.benchmark_return,
+ "active_return": result.active_return,
+ "allocation": result.allocation,
+ "selection": result.selection,
+ "interaction": result.interaction,
+ "sectors": [
+ {
+ "sector": sector.sector,
+ "portfolio_weight": sector.portfolio_weight,
+ "benchmark_weight": sector.benchmark_weight,
+ "portfolio_return": sector.portfolio_return,
+ "benchmark_return": sector.benchmark_return,
+ "allocation": sector.allocation,
+ "selection": sector.selection,
+ "interaction": sector.interaction,
+ "total": sector.total,
+ }
+ for sector in result.sectors
+ ],
+ }
+
+
+def _attribution_load_position_weights(run_dir: Path, notes: List[str]) -> Optional[Dict[str, float]]:
+ """Read the last row of ``positions.csv`` as per-symbol weights.
+
+ Returns ``None`` (with a skip note) when the artifact is missing or cannot
+ be parsed into at least one weighted symbol column.
+ """
+ path = run_dir / "artifacts" / "positions.csv"
+ try:
+ if path.is_symlink() or not path.is_file():
+ notes.append("brinson attribution skipped: positions.csv not found")
+ return None
+ except OSError:
+ notes.append("brinson attribution skipped: positions.csv not found")
+ return None
+ fieldnames, rows = _attribution_read_csv(path)
+ if fieldnames is None or len(fieldnames) < 2 or not rows:
+ notes.append("brinson attribution skipped: positions.csv could not be parsed")
+ return None
+ symbols = [name.strip() for name in fieldnames[1:] if name and name.strip()]
+ if not symbols:
+ notes.append("brinson attribution skipped: positions.csv could not be parsed")
+ return None
+ last_row = rows[-1]
+ weights: Dict[str, float] = {}
+ for symbol in symbols:
+ weight = _attribution_finite_float(last_row.get(symbol))
+ weights[symbol] = weight if weight is not None else 0.0
+ return weights
+
+
+def _attribution_brinson_section(
+ run_dir: Path,
+ codes: List[str],
+ benchmark_ticker: Optional[str],
+ portfolio_returns: List[float],
+ benchmark_equity_state: str,
+ benchmark_equity: Optional[List[float]],
+ notes: List[str],
+) -> Optional[Dict[str, Any]]:
+ """Build the Brinson-Fachler section in symbol, asset_class, or fallback mode.
+
+ Args:
+ run_dir: Root directory of the run.
+ codes: Configured symbols from ``config.json``.
+ benchmark_ticker: Explicit benchmark ticker, or ``None`` in auto mode.
+ portfolio_returns: Portfolio daily returns from ``equity.csv``.
+ benchmark_equity_state: ``"ok"``, ``"missing"``, or ``"non_finite"``.
+ benchmark_equity: Finite benchmark equity values when state is ``"ok"``.
+ notes: Note accumulator; skip reasons are appended here.
+
+ Returns:
+ The Brinson section dict, or ``None`` with an explanatory note.
+ """
+ weights = _attribution_load_position_weights(run_dir, notes)
+ if weights is None:
+ return None
+ if all(abs(weight) <= 0.0 for weight in weights.values()):
+ notes.append("brinson attribution skipped: all position weights are zero")
+ return None
+
+ if benchmark_ticker is None:
+ return _attribution_brinson_symbol_mode(run_dir, codes, weights, notes)
+ return _attribution_brinson_asset_class_mode(
+ run_dir, benchmark_ticker, weights, portfolio_returns,
+ benchmark_equity_state, benchmark_equity, notes,
+ )
+
+
+def _attribution_brinson_symbol_mode(
+ run_dir: Path,
+ codes: List[str],
+ weights: Dict[str, float],
+ notes: List[str],
+) -> Optional[Dict[str, Any]]:
+ """Symbol-mode Brinson: each configured symbol is its own sector.
+
+ Portfolio weights come from the last ``positions.csv`` row; benchmark
+ weights are equal weight; both sides share the same buy-and-hold per-symbol
+ returns, so selection and interaction vanish by construction.
+ """
+ candidates = codes or list(weights)
+ symbols = [symbol for symbol in candidates if symbol in weights] or list(weights)
+ returns: Dict[str, float] = {}
+ for symbol in symbols:
+ symbol_return = _attribution_symbol_cumulative_return(run_dir, symbol)
+ if symbol_return is not None:
+ returns[symbol] = symbol_return
+ included = [symbol for symbol in symbols if symbol in returns]
+ if not included:
+ notes.append("brinson attribution skipped: positions.csv could not be parsed")
+ return None
+
+ portfolio_weights = {symbol: weights.get(symbol, 0.0) for symbol in included}
+ portfolio_returns_map = dict(returns)
+ benchmark_weights = {symbol: 1.0 / len(included) for symbol in included}
+ cash_weight = 1.0 - math.fsum(portfolio_weights.values())
+ if cash_weight > _ATTRIBUTION_CASH_WEIGHT_TOLERANCE:
+ portfolio_weights["Cash"] = cash_weight
+ portfolio_returns_map["Cash"] = 0.0
+
+ notes.append(
+ "brinson attribution computed in symbol-mode: buy-and-hold per-symbol returns, "
+ "portfolio weights vs equal-weight benchmark"
+ )
+ return _attribution_run_brinson(
+ "symbol", portfolio_weights, benchmark_weights, portfolio_returns_map, dict(returns), notes
+ )
+
+
+def _attribution_brinson_asset_class_mode(
+ run_dir: Path,
+ benchmark_ticker: str,
+ weights: Dict[str, float],
+ portfolio_returns: List[float],
+ benchmark_equity_state: str,
+ benchmark_equity: Optional[List[float]],
+ notes: List[str],
+) -> Optional[Dict[str, Any]]:
+ """Asset-class Brinson against an explicit benchmark.
+
+ Symbols are grouped by asset class; the benchmark is 100% in the benchmark
+ ticker's own class, whose return is the cumulative ``benchmark_equity``
+ return. Degrades to an invested/cash decomposition when class returns
+ cannot be resolved.
+ """
+ from backtest.engines._market_hooks import _detect_market
+
+ if benchmark_equity_state == "non_finite":
+ notes.append("brinson attribution skipped: benchmark_equity contains non-finite values")
+ return None
+ if benchmark_equity_state != "ok" or not benchmark_equity:
+ notes.append("brinson attribution skipped: no benchmark_equity series in equity.csv")
+ return None
+ benchmark_cumulative = benchmark_equity[-1] / benchmark_equity[0] - 1.0
+ benchmark_class = str(_detect_market(benchmark_ticker))
+
+ class_weights: Dict[str, float] = {}
+ class_return_sums: Dict[str, float] = {}
+ for symbol, weight in weights.items():
+ if abs(weight) <= 0.0:
+ continue
+ asset_class = str(_detect_market(symbol))
+ class_weights[asset_class] = class_weights.get(asset_class, 0.0) + weight
+ symbol_return = _attribution_symbol_cumulative_return(run_dir, symbol)
+ if symbol_return is not None:
+ class_return_sums[asset_class] = class_return_sums.get(asset_class, 0.0) + weight * symbol_return
+
+ portfolio_weights: Dict[str, float] = {}
+ portfolio_returns_by_class: Dict[str, float] = {}
+ degraded = False
+ for asset_class, class_weight in class_weights.items():
+ if asset_class not in class_return_sums:
+ degraded = True
+ break
+ portfolio_weights[asset_class] = class_weight
+ portfolio_returns_by_class[asset_class] = class_return_sums[asset_class] / class_weight
+
+ if degraded:
+ return _attribution_brinson_invested_cash_mode(
+ benchmark_class, benchmark_cumulative, weights, portfolio_returns, notes
+ )
+
+ cash_weight = 1.0 - math.fsum(portfolio_weights.values())
+ if cash_weight > _ATTRIBUTION_CASH_WEIGHT_TOLERANCE:
+ portfolio_weights["Cash"] = cash_weight
+ portfolio_returns_by_class["Cash"] = 0.0
+
+ notes.append(
+ "brinson attribution in asset_class mode uses a buy-and-hold approximation "
+ "for portfolio sector returns"
+ )
+ return _attribution_run_brinson(
+ "asset_class",
+ portfolio_weights,
+ {benchmark_class: 1.0},
+ portfolio_returns_by_class,
+ {benchmark_class: benchmark_cumulative},
+ notes,
+ )
+
+
+def _attribution_brinson_invested_cash_mode(
+ benchmark_class: str,
+ benchmark_cumulative: float,
+ weights: Dict[str, float],
+ portfolio_returns: List[float],
+ notes: List[str],
+) -> Optional[Dict[str, Any]]:
+ """Invested/cash fallback Brinson when class-level returns are unavailable."""
+ invested_weight = math.fsum(abs(weight) for weight in weights.values())
+ if invested_weight < _ATTRIBUTION_MIN_INVESTED_WEIGHT:
+ notes.append("brinson attribution skipped: all position weights are zero")
+ return None
+ portfolio_wealth = 1.0
+ for value in portfolio_returns:
+ if math.isfinite(value):
+ portfolio_wealth *= 1.0 + value
+ invested_return = portfolio_wealth - 1.0
+
+ notes.append("brinson attribution degraded to invested/cash decomposition")
+ return _attribution_run_brinson(
+ "invested_cash",
+ {"invested": invested_weight, "Cash": 1.0 - invested_weight},
+ {benchmark_class: 1.0},
+ {"invested": invested_return, "Cash": 0.0},
+ {benchmark_class: benchmark_cumulative},
+ notes,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Payload assembly
+# ---------------------------------------------------------------------------
+
+
+def _build_attribution_payload(run_dir: Path) -> Dict[str, Any]:
+ """Assemble the full attribution payload from a run's artifacts.
+
+ Args:
+ run_dir: Root directory of the run.
+
+ Returns:
+ The response contract dict ``{"exists", "benchmark", "factor",
+ "brinson", "notes"}`` with unrounded floats; the route rounds it.
+ """
+ notes: List[str] = []
+ payload: Dict[str, Any] = {
+ "exists": False,
+ "benchmark": None,
+ "factor": None,
+ "brinson": None,
+ "notes": notes,
+ }
+
+ config = _attribution_load_json(run_dir / "config.json") or {}
+ raw_codes = config.get("codes")
+ codes: List[str] = []
+ if isinstance(raw_codes, list):
+ codes = [str(code) for code in raw_codes if str(code).strip()]
+ bars_per_year = _attribution_bars_per_year(config.get("interval"))
+
+ # Mirror the factor scan's symlink rejection: a symlinked artifacts dir is
+ # treated as having no readable artifacts rather than followed.
+ artifacts_dir = run_dir / "artifacts"
+ try:
+ artifacts_usable = artifacts_dir.is_dir() and not artifacts_dir.is_symlink()
+ except OSError:
+ artifacts_usable = False
+
+ if artifacts_usable:
+ dates, portfolio_returns, benchmark_equity, benchmark_state = _attribution_load_equity(run_dir)
+ else:
+ dates, portfolio_returns, benchmark_equity, benchmark_state = None, None, None, "missing"
+
+ if dates is None or portfolio_returns is None:
+ notes.append("attribution skipped: equity.csv is missing or unreadable")
+ return payload
+ payload["exists"] = True
+
+ benchmark_ticker: Optional[str] = None
+ config_benchmark = config.get("benchmark")
+ if isinstance(config_benchmark, dict):
+ config_benchmark = config_benchmark.get("ticker") or config_benchmark.get("code")
+ if config_benchmark is not None and str(config_benchmark).strip():
+ benchmark_ticker = str(config_benchmark).strip()
+ if benchmark_ticker is None:
+ _metrics_fields, metrics_rows = _attribution_read_csv(run_dir / "artifacts" / "metrics.csv")
+ if metrics_rows:
+ candidate = metrics_rows[0].get("benchmark_ticker")
+ if candidate is not None and str(candidate).strip():
+ benchmark_ticker = str(candidate).strip()
+
+ if benchmark_ticker is not None:
+ payload["benchmark"] = {"ticker": benchmark_ticker, "mode": "explicit"}
+ else:
+ payload["benchmark"] = {"ticker": None, "mode": "auto_equal_weight"}
+
+ benchmark_returns: Optional[List[float]] = None
+ if benchmark_state == "ok" and benchmark_equity is not None:
+ benchmark_returns = _attribution_benchmark_returns_from_equity(benchmark_equity)
+ if benchmark_returns is None and benchmark_ticker is None:
+ benchmark_returns = _attribution_equal_weight_returns(run_dir, codes, dates)
+
+ payload["factor"] = _attribution_factor_section(
+ dates, portfolio_returns, benchmark_returns, bars_per_year, notes
+ )
+ payload["brinson"] = _attribution_brinson_section(
+ run_dir,
+ codes,
+ benchmark_ticker,
+ portfolio_returns,
+ benchmark_state,
+ benchmark_equity,
+ notes,
+ )
+ return payload
diff --git a/agent/src/api/attribution_routes.py b/agent/src/api/attribution_routes.py
new file mode 100644
index 000000000..e1adc24ff
--- /dev/null
+++ b/agent/src/api/attribution_routes.py
@@ -0,0 +1,100 @@
+"""Run attribution HTTP routes for the Web UI.
+
+Mounted by ``agent/api_server.py`` via ``register_attribution_routes(app, ...)``.
+
+Routes (auth via the caller-supplied ``require_auth`` dependency):
+
+- ``GET /runs/{run_id}/attribution`` — factor attribution (portfolio vs
+ benchmark OLS: beta / alpha / rolling / cumulative) plus a single-period
+ Brinson-Fachler decomposition, computed exclusively from the run's persisted
+ artifacts. No market data is re-fetched.
+
+The computation lives in ``attribution_core.py`` so this module stays a thin
+registration slice.
+"""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import Any, Awaitable, Callable
+
+from fastapi import Depends, FastAPI, HTTPException, status
+from fastapi.concurrency import run_in_threadpool
+
+from src.api.attribution_core import _attribution_round_values, _build_attribution_payload
+
+logger = logging.getLogger(__name__)
+
+# ---------------------------------------------------------------------------
+# Registration
+# ---------------------------------------------------------------------------
+
+AuthDep = Callable[..., Awaitable[Any] | Any]
+
+
+def register_attribution_routes(
+ app: FastAPI,
+ require_auth: AuthDep | None = None,
+) -> None:
+ """Mount the attribution route onto ``app``.
+
+ Resolves ``require_auth`` from the host ``api_server`` module via
+ ``sys.modules`` when not passed explicitly.
+
+ Args:
+ app: The host FastAPI app.
+ require_auth: Header-auth dependency for the endpoint.
+
+ Raises:
+ RuntimeError: When the host module is absent from ``sys.modules`` and
+ no explicit dependency was passed.
+ """
+ import sys as _sys
+
+ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ if host is None:
+ raise RuntimeError(
+ "register_attribution_routes: api_server module not in sys.modules; "
+ "ensure api_server is imported before calling this function"
+ )
+
+ if require_auth is None:
+ require_auth = host.require_auth
+
+ # Late-access closures for shared host symbols (monkeypatch-safe)
+ def _host_validate_path_param(value: str, kind: str) -> None:
+ h = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ return h._validate_path_param(value, kind)
+
+ def _host_RUNS_DIR() -> Path:
+ h = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ return h.RUNS_DIR
+
+ @app.get("/runs/{run_id}/attribution", dependencies=[Depends(require_auth)])
+ async def get_run_attribution(run_id: str):
+ """Return factor + Brinson attribution for one run.
+
+ All inputs come from the run's persisted artifacts; nothing is
+ re-fetched. Blocking file work runs in the FastAPI threadpool.
+
+ Args:
+ run_id: Run identifier.
+
+ Returns:
+ The attribution envelope ``{"exists", "benchmark", "factor",
+ "brinson", "notes"}`` with floats rounded to six decimals.
+
+ Raises:
+ HTTPException: 400 on a traversal-shaped ``run_id``, 404 when the
+ run directory does not exist.
+ """
+ _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",
+ )
+ payload = await run_in_threadpool(_build_attribution_payload, run_dir)
+ return _attribution_round_values(payload)
diff --git a/agent/src/api/options_routes.py b/agent/src/api/options_routes.py
index 2b307ae96..8e7372325 100644
--- a/agent/src/api/options_routes.py
+++ b/agent/src/api/options_routes.py
@@ -23,6 +23,7 @@ Error surface:
- Payoff: pydantic request validation → 422 (FastAPI default). A tool-level
error envelope (``{"status": "error", ...}``) → 400 with that same body.
+ An unexpected exception inside the tool call → 502 with a generic envelope.
- Chain: missing/blank ticker → 400 ``{"ok": false, "error": "ticker is
required"}``; a tool failure envelope (``ok: false``) → 502 with the tool's
body; an unexpected exception inside the tool call → 502 with a generic
@@ -194,8 +195,15 @@ def register_options_routes(
"""Tool-identical payoff analysis plus portfolio Greeks at entry."""
params = _tool_params(payload)
tool = OptionsPayoffTool()
- raw = await asyncio.to_thread(tool.execute, **params)
- envelope = json.loads(raw)
+ try:
+ raw = await asyncio.to_thread(tool.execute, **params)
+ envelope = json.loads(raw)
+ except Exception: # noqa: BLE001 — never leak a stack frame to clients
+ logger.exception("options payoff tool call failed")
+ return JSONResponse(
+ status_code=502,
+ content={"ok": False, "error": "payoff computation failed"},
+ )
if envelope.get("status") != "ok":
# Curated tool error envelope (bad bounds, bad scenarios, ...) —
# surface it verbatim as a client error.
diff --git a/agent/src/api/runs_routes.py b/agent/src/api/runs_routes.py
index 6e729627b..7991cba07 100644
--- a/agent/src/api/runs_routes.py
+++ b/agent/src/api/runs_routes.py
@@ -10,6 +10,7 @@ import json
import math
import os
import statistics
+import threading
from collections import deque
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone
@@ -464,11 +465,35 @@ def _factor_ic_correlation(factors: List[Dict[str, Any]]) -> Optional[Dict[str,
# Bounded contract for /runs/{run_id}/positions/sectors: at most
# _POSITIONS_SECTOR_MAX_SYMBOLS symbols get a network industry lookup (excess
-# symbols degrade to asset-class-only grouping), lookups run on at most
-# _POSITIONS_SECTOR_WORKERS threads, and each HTTP call carries the shared
-# Eastmoney client's 15-second socket timeout.
+# symbols degrade to asset-class-only grouping), lookups run on ONE shared
+# module-level executor with _POSITIONS_SECTOR_WORKERS threads (created lazily
+# on first use and never shut down — process-lifetime — so concurrent requests
+# share a single bounded pool instead of spawning one per request), and each
+# HTTP call carries the shared Eastmoney client's 15-second socket timeout.
_POSITIONS_SECTOR_MAX_SYMBOLS = 200
_POSITIONS_SECTOR_WORKERS = 4
+_POSITIONS_SECTOR_EXECUTOR: Optional[ThreadPoolExecutor] = None
+_POSITIONS_SECTOR_EXECUTOR_LOCK = threading.Lock()
+
+
+def _get_positions_sector_executor() -> ThreadPoolExecutor:
+ """Return the shared, process-lifetime industry-lookup executor.
+
+ Created lazily on first use with ``_POSITIONS_SECTOR_WORKERS`` workers and
+ never shut down, so every request fans out onto the same bounded pool.
+
+ Returns:
+ The shared executor instance.
+ """
+ global _POSITIONS_SECTOR_EXECUTOR
+ if _POSITIONS_SECTOR_EXECUTOR is None:
+ with _POSITIONS_SECTOR_EXECUTOR_LOCK:
+ if _POSITIONS_SECTOR_EXECUTOR is None:
+ _POSITIONS_SECTOR_EXECUTOR = ThreadPoolExecutor(
+ max_workers=_POSITIONS_SECTOR_WORKERS,
+ thread_name_prefix="positions-sector",
+ )
+ return _POSITIONS_SECTOR_EXECUTOR
def _read_positions_symbols(path: Path) -> List[str]:
@@ -507,14 +532,14 @@ def _resolve_industries_concurrent(symbols: List[str]) -> Dict[str, Optional[str
from src.tools.sector_tool import resolve_industry_board
results: Dict[str, Optional[str]] = {}
- with ThreadPoolExecutor(max_workers=_POSITIONS_SECTOR_WORKERS) as pool:
- futures = {pool.submit(resolve_industry_board, symbol): symbol for symbol in symbols}
- for future in as_completed(futures):
- symbol = futures[future]
- try:
- results[symbol] = future.result()
- except Exception: # noqa: BLE001 - one failure must not abort the batch
- results[symbol] = None
+ pool = _get_positions_sector_executor()
+ futures = {pool.submit(resolve_industry_board, symbol): symbol for symbol in symbols}
+ for future in as_completed(futures):
+ symbol = futures[future]
+ try:
+ results[symbol] = future.result()
+ except Exception: # noqa: BLE001 - one failure must not abort the batch
+ results[symbol] = None
return results
@@ -544,6 +569,16 @@ def _build_positions_sector_map(run_dir: Path, run_id: str, *, refresh: bool) ->
"""
from backtest.engines._market_hooks import _detect_market
+ artifacts_dir = run_dir / "artifacts"
+ try:
+ artifacts_symlinked = artifacts_dir.is_symlink()
+ except OSError:
+ artifacts_symlinked = False
+ if artifacts_symlinked:
+ # Mirror the factor scan's symlink rejection: a symlinked artifacts dir
+ # is treated as having no positions artifact rather than followed.
+ return {"ok": True, "run_id": run_id, "symbols": {}, "note": "no positions artifact"}
+
cache_path = run_dir / "artifacts" / "sector_map.json"
if not refresh:
cached = _load_json_file(cache_path)
@@ -884,7 +919,7 @@ def register_runs_routes(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Run {run_id} not found"
)
- factors = _scan_factor_results(run_dir)
+ factors = await run_in_threadpool(_scan_factor_results, run_dir)
if not factors:
return {"exists": False, "factors": [], "ic_correlation": None}
return {
diff --git a/agent/tests/api/test_positions_sectors.py b/agent/tests/api/test_positions_sectors.py
index afdb55067..688b6037d 100644
--- a/agent/tests/api/test_positions_sectors.py
+++ b/agent/tests/api/test_positions_sectors.py
@@ -15,6 +15,7 @@ from unittest.mock import patch
from fastapi.testclient import TestClient
import api_server
+from src.api import runs_routes
from src.tools.sector_tool import resolve_industry_board
RUN_ID = "run_20260801_120000"
@@ -250,6 +251,34 @@ def test_unknown_run_id_returns_404(tmp_path: Path, monkeypatch) -> None:
assert response.json()["detail"] == "Run no-such-run not found"
+def test_symlinked_artifacts_dir_returns_no_positions_note(tmp_path: Path, monkeypatch) -> None:
+ """A symlinked artifacts dir is rejected, mirroring the factor scan."""
+ real_artifacts = tmp_path / "real_artifacts"
+ real_artifacts.mkdir()
+ (real_artifacts / "positions.csv").write_text(
+ "timestamp,600519.SH\n2026-08-01T00:00:00,1.0\n", encoding="utf-8"
+ )
+ run_dir = tmp_path / "runs" / RUN_ID
+ run_dir.mkdir(parents=True)
+ (run_dir / "artifacts").symlink_to(real_artifacts)
+ client = _client(tmp_path, monkeypatch)
+
+ with patch("src.tools.sector_tool.resolve_secid") as resolve, patch(
+ "src.tools.sector_tool.get_json"
+ ) as get:
+ response = client.get(f"/runs/{RUN_ID}/positions/sectors")
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "ok": True,
+ "run_id": RUN_ID,
+ "symbols": {},
+ "note": "no positions artifact",
+ }
+ resolve.assert_not_called()
+ get.assert_not_called()
+
+
# ============================================================================
# Endpoint: bounded contract for large books
# ============================================================================
@@ -299,6 +328,69 @@ def test_large_symbol_list_caps_network_lookups(tmp_path: Path, monkeypatch) ->
assert payload["unresolved"] == symbols[200:]
+def test_shared_executor_created_once_and_bounded(tmp_path: Path, monkeypatch) -> None:
+ """One process-lifetime executor serves every request; the 200 cap holds.
+
+ Regression for the per-request ``ThreadPoolExecutor`` replacement: the
+ shared pool must be created lazily exactly once, carry
+ ``_POSITIONS_SECTOR_WORKERS`` workers, stay un-shutdown across requests,
+ and still cap network lookups at ``_POSITIONS_SECTOR_MAX_SYMBOLS``.
+ """
+ total = 250
+ symbols = [f"6{i:05d}.SH" for i in range(total)]
+ _make_run(
+ tmp_path,
+ "timestamp," + ",".join(symbols),
+ ["2026-08-01T00:00:00," + ",".join(["0.004"] * total)],
+ )
+ client = _client(tmp_path, monkeypatch)
+
+ monkeypatch.setattr(runs_routes, "_POSITIONS_SECTOR_EXECUTOR", None)
+ created: list[dict] = []
+ real_executor = runs_routes.ThreadPoolExecutor
+
+ def counting_executor(*args, **kwargs):
+ created.append(kwargs)
+ return real_executor(*args, **kwargs)
+
+ monkeypatch.setattr(runs_routes, "ThreadPoolExecutor", counting_executor)
+
+ def any_secid(symbol: str) -> str | None:
+ return f"1.{symbol.split('.')[0]}"
+
+ def any_get_json(url: str, *, params: dict) -> dict:
+ code = params["secid"].split(".")[1]
+ return {
+ "data": {
+ "diff": {
+ "0": {"f12": code, "f13": 1, "f14": "S"},
+ "1": {"f12": "BK0001", "f13": 90, "f14": "银行Ⅱ"},
+ }
+ }
+ }
+
+ with patch(
+ "src.tools.sector_tool.resolve_secid", side_effect=any_secid
+ ), patch("src.tools.sector_tool.get_json", side_effect=any_get_json) as get:
+ first = client.get(f"/runs/{RUN_ID}/positions/sectors")
+ second = client.get(f"/runs/{RUN_ID}/positions/sectors?refresh=1")
+
+ assert first.status_code == 200
+ assert second.status_code == 200
+ # The shared executor still caps lookups at 200 on every request.
+ assert get.call_count == 2 * runs_routes._POSITIONS_SECTOR_MAX_SYMBOLS
+ assert first.json()["symbol_limit"] == runs_routes._POSITIONS_SECTOR_MAX_SYMBOLS
+ # Exactly one executor was created across both requests, bounded by
+ # _POSITIONS_SECTOR_WORKERS, and never shut down (process-lifetime).
+ assert len(created) == 1
+ assert created[0]["max_workers"] == runs_routes._POSITIONS_SECTOR_WORKERS
+ executor = runs_routes._POSITIONS_SECTOR_EXECUTOR
+ assert executor is not None
+ assert runs_routes._get_positions_sector_executor() is executor
+ assert executor._max_workers == runs_routes._POSITIONS_SECTOR_WORKERS
+ assert not executor._shutdown
+
+
# ============================================================================
# resolve_industry_board helper
# ============================================================================
diff --git a/agent/tests/test_attribution_api.py b/agent/tests/test_attribution_api.py
new file mode 100644
index 000000000..65b5eb11e
--- /dev/null
+++ b/agent/tests/test_attribution_api.py
@@ -0,0 +1,303 @@
+"""API tests for GET /runs/{run_id}/attribution.
+
+Synthetic run directories are built under a temporary RUNS_ROOT following the
+artifact layout of real runs: equity.csv (timestamp, ret, equity, drawdown,
+benchmark_equity, active_ret), positions.csv (timestamp + per-symbol weights),
+ohlcv_<SYMBOL>.csv (trade_date, open, high, low, close, volume), metrics.csv
+(single wide row), and config.json.
+"""
+
+from __future__ import annotations
+
+import csv
+import json
+from pathlib import Path
+from typing import Any, Dict, List
+
+import numpy as np
+import pytest
+from fastapi.testclient import TestClient
+
+import api_server
+
+SYMBOL_A = "SYMA.US"
+SYMBOL_B = "SYMB.US"
+N_BARS = 120
+
+
+def _client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ monkeypatch.setattr(api_server, "RUNS_DIR", tmp_path / "runs")
+ return TestClient(api_server.app, client=("127.0.0.1", 50000))
+
+
+def _write_csv(path: Path, header: List[str], rows: List[List[Any]]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("w", encoding="utf-8", newline="") as handle:
+ writer = csv.writer(handle)
+ writer.writerow(header)
+ writer.writerows(rows)
+
+
+def _trading_dates(count: int, start: str = "2024-01-01") -> List[str]:
+ import pandas as pd
+
+ return [day.strftime("%Y-%m-%d") for day in pd.bdate_range(start, periods=count)]
+
+
+def _write_ohlcv(run_dir: Path, symbol: str, dates: List[str], first_close: float, last_close: float) -> None:
+ span = len(dates) - 1
+ rows = []
+ for index, day in enumerate(dates):
+ close = first_close + (last_close - first_close) * index / span
+ rows.append([day, f"{close:.4f}", f"{close + 1:.4f}", f"{close - 1:.4f}", f"{close:.4f}", "1000"])
+ _write_csv(run_dir / "artifacts" / f"ohlcv_{symbol}.csv", ["trade_date", "open", "high", "low", "close", "volume"], rows)
+
+
+def _write_equity(run_dir: Path, dates: List[str], portfolio_returns: np.ndarray, benchmark_returns: np.ndarray) -> None:
+ rows = []
+ equity = 1_000_000.0
+ benchmark_equity = 1_000_000.0
+ for index, day in enumerate(dates):
+ equity *= 1.0 + portfolio_returns[index]
+ benchmark_equity *= 1.0 + benchmark_returns[index]
+ rows.append(
+ [
+ day,
+ f"{portfolio_returns[index]:.12f}",
+ f"{equity:.6f}",
+ "0.0",
+ f"{benchmark_equity:.12f}",
+ f"{portfolio_returns[index] - benchmark_returns[index]:.12f}",
+ ]
+ )
+ _write_csv(
+ run_dir / "artifacts" / "equity.csv",
+ ["timestamp", "ret", "equity", "drawdown", "benchmark_equity", "active_ret"],
+ rows,
+ )
+
+
+def _write_config(run_dir: Path, codes: List[str], benchmark: Any = None) -> None:
+ config: Dict[str, Any] = {
+ "codes": codes,
+ "interval": "1D",
+ "source": "yfinance",
+ "start_date": "2024-01-01",
+ "end_date": "2024-12-31",
+ }
+ if benchmark is not None:
+ config["benchmark"] = benchmark
+ run_dir.mkdir(parents=True, exist_ok=True)
+ (run_dir / "config.json").write_text(json.dumps(config), encoding="utf-8")
+
+
+def _write_metrics(run_dir: Path, extra: Dict[str, str] | None = None) -> None:
+ header = ["total_return", "sharpe", "benchmark_return", "excess_return"]
+ values = ["0.1", "1.0", "0.05", "0.05"]
+ if extra:
+ header.extend(extra.keys())
+ values.extend(extra.values())
+ _write_csv(run_dir / "artifacts" / "metrics.csv", header, [values])
+
+
+def _build_auto_run(tmp_path: Path, run_id: str, n_bars: int = N_BARS) -> Path:
+ """Auto-benchmark run: portfolio ret = 0.001 + 1.2 * benchmark ret exactly."""
+ run_dir = tmp_path / "runs" / run_id
+ rng = np.random.default_rng(7)
+ benchmark = rng.normal(0.0005, 0.01, n_bars)
+ benchmark[0] = 0.0
+ portfolio = 0.001 + 1.2 * benchmark
+ dates = _trading_dates(n_bars)
+
+ _write_equity(run_dir, dates, portfolio, benchmark)
+ _write_csv(
+ run_dir / "artifacts" / "positions.csv",
+ ["timestamp", SYMBOL_A, SYMBOL_B],
+ [[day, "0.7", "0.3"] for day in dates],
+ )
+ # Exact cumulative returns: SYMA +10%, SYMB +5%, so the symbol-mode Brinson
+ # numbers are clean decimals that survive 6-decimal response rounding.
+ _write_ohlcv(run_dir, SYMBOL_A, dates, 100.0, 110.0)
+ _write_ohlcv(run_dir, SYMBOL_B, dates, 100.0, 105.0)
+ _write_config(run_dir, [SYMBOL_A, SYMBOL_B])
+ _write_metrics(run_dir)
+ return run_dir
+
+
+def _build_explicit_run(tmp_path: Path, run_id: str) -> Path:
+ """Explicit-benchmark run across two asset classes with weights < 1 (cash)."""
+ run_dir = tmp_path / "runs" / run_id
+ benchmark = np.array([0.001 if i % 2 else -0.001 for i in range(N_BARS)])
+ benchmark[0] = 0.0
+ portfolio = 0.0005 + 0.8 * benchmark
+ dates = _trading_dates(N_BARS)
+
+ _write_equity(run_dir, dates, portfolio, benchmark)
+ _write_csv(
+ run_dir / "artifacts" / "positions.csv",
+ ["timestamp", "600519.SH", "AAPL.US"],
+ [[day, "0.4", "0.3"] for day in dates],
+ )
+ _write_ohlcv(run_dir, "600519.SH", dates, 100.0, 120.0)
+ _write_ohlcv(run_dir, "AAPL.US", dates, 100.0, 90.0)
+ _write_config(run_dir, ["600519.SH", "AAPL.US"], benchmark="000300.SH")
+ _write_metrics(run_dir, extra={"benchmark_ticker": "000300.SH"})
+ return run_dir
+
+
+def test_attribution_auto_mode_factor_and_symbol_brinson(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ _build_auto_run(tmp_path, "attr-auto")
+
+ response = client.get("/runs/attr-auto/attribution")
+
+ assert response.status_code == 200
+ data = response.json()
+ assert data["exists"] is True
+ assert data["benchmark"] == {"ticker": None, "mode": "auto_equal_weight"}
+
+ factor = data["factor"]
+ assert factor is not None
+ assert factor["beta"] == pytest.approx(1.2, abs=1e-8)
+ assert factor["alpha_per_period"] == pytest.approx(0.001, abs=1e-8)
+ assert factor["alpha_annualized"] == pytest.approx(0.001 * 252, abs=1e-6)
+ assert factor["r_squared"] == pytest.approx(1.0, abs=1e-9)
+ assert factor["n_obs"] == N_BARS
+ assert factor["rolling_window"] == 60
+ assert factor["rolling"] is not None
+ assert len(factor["rolling"]) == N_BARS - 60 + 1
+ assert len(factor["cumulative"]) == N_BARS
+ assert factor["cumulative"][-1]["date"] == _trading_dates(N_BARS)[-1]
+
+ brinson = data["brinson"]
+ assert brinson is not None
+ assert brinson["mode"] == "symbol"
+ assert brinson["portfolio_return"] == pytest.approx(0.085, abs=1e-9)
+ assert brinson["benchmark_return"] == pytest.approx(0.075, abs=1e-9)
+ assert brinson["active_return"] == pytest.approx(0.01, abs=1e-9)
+ assert brinson["allocation"] == pytest.approx(0.01, abs=1e-9)
+ # Symbol mode: per-symbol portfolio and benchmark sector returns coincide,
+ # so selection and interaction vanish by construction.
+ assert brinson["selection"] == pytest.approx(0.0, abs=1e-12)
+ assert brinson["interaction"] == pytest.approx(0.0, abs=1e-12)
+ assert abs(brinson["allocation"] + brinson["selection"] + brinson["interaction"] - brinson["active_return"]) < 1e-9
+ sectors = {sector["sector"]: sector for sector in brinson["sectors"]}
+ assert set(sectors) == {SYMBOL_A, SYMBOL_B}
+ assert sectors[SYMBOL_A]["portfolio_weight"] == pytest.approx(0.7, abs=1e-9)
+ assert sectors[SYMBOL_A]["benchmark_weight"] == pytest.approx(0.5, abs=1e-9)
+ assert sectors[SYMBOL_A]["portfolio_return"] == pytest.approx(0.10, abs=1e-9)
+ assert all(sector["selection"] == pytest.approx(0.0, abs=1e-12) for sector in brinson["sectors"])
+ assert any("symbol-mode" in note for note in data["notes"])
+
+
+def test_attribution_explicit_mode_asset_class_with_cash(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ _build_explicit_run(tmp_path, "attr-explicit")
+
+ response = client.get("/runs/attr-explicit/attribution")
+
+ assert response.status_code == 200
+ data = response.json()
+ assert data["exists"] is True
+ assert data["benchmark"] == {"ticker": "000300.SH", "mode": "explicit"}
+ assert data["factor"] is not None
+ assert data["factor"]["beta"] == pytest.approx(0.8, abs=1e-6)
+
+ brinson = data["brinson"]
+ assert brinson is not None
+ assert brinson["mode"] == "asset_class"
+ sectors = {sector["sector"]: sector for sector in brinson["sectors"]}
+ assert "Cash" in sectors
+ assert sectors["Cash"]["portfolio_weight"] == pytest.approx(0.3, abs=1e-9)
+ assert sectors["Cash"]["benchmark_weight"] == pytest.approx(0.0, abs=1e-9)
+ assert sectors["a_share"]["benchmark_weight"] == pytest.approx(1.0, abs=1e-9)
+ assert sectors["a_share"]["portfolio_return"] == pytest.approx(0.20, abs=1e-9)
+ assert sectors["us_equity"]["portfolio_return"] == pytest.approx(-0.10, abs=1e-9)
+ # Response floats are rounded to 6 decimals, so the exact tie-out identity
+ # holds here within combined rounding error rather than machine epsilon.
+ assert (
+ abs(brinson["allocation"] + brinson["selection"] + brinson["interaction"] - brinson["active_return"]) < 1e-5
+ )
+ assert any("buy-and-hold approximation" in note for note in data["notes"])
+
+
+def test_attribution_exists_false_without_equity(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ run_dir = tmp_path / "runs" / "attr-no-equity"
+ _write_config(run_dir, [SYMBOL_A])
+
+ response = client.get("/runs/attr-no-equity/attribution")
+
+ assert response.status_code == 200
+ data = response.json()
+ assert data["exists"] is False
+ assert data["benchmark"] is None
+ assert data["factor"] is None
+ assert data["brinson"] is None
+ assert any("equity.csv" in note for note in data["notes"])
+
+
+def test_attribution_unknown_run_returns_404(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ (tmp_path / "runs").mkdir(parents=True, exist_ok=True)
+
+ response = client.get("/runs/does-not-exist/attribution")
+
+ assert response.status_code == 404
+
+
+def test_attribution_traversal_run_id_returns_400(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+
+ response = client.get("/runs/foo.bar/attribution")
+
+ assert response.status_code == 400
+ assert response.json()["detail"] == "invalid run_id"
+
+
+def test_attribution_degrades_without_positions(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ run_dir = tmp_path / "runs" / "attr-no-positions"
+ rng = np.random.default_rng(11)
+ benchmark = rng.normal(0.0004, 0.008, N_BARS)
+ benchmark[0] = 0.0
+ portfolio = 0.0002 + 0.9 * benchmark
+ dates = _trading_dates(N_BARS)
+ _write_equity(run_dir, dates, portfolio, benchmark)
+ _write_config(run_dir, [SYMBOL_A])
+ _write_metrics(run_dir)
+
+ response = client.get("/runs/attr-no-positions/attribution")
+
+ assert response.status_code == 200
+ data = response.json()
+ assert data["exists"] is True
+ assert data["factor"] is not None
+ assert data["factor"]["beta"] == pytest.approx(0.9, abs=1e-6)
+ assert data["brinson"] is None
+ assert any("positions.csv" in note for note in data["notes"])
+
+
+def test_attribution_long_series_downsampled_with_last_point_pinned(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ client = _client(tmp_path, monkeypatch)
+ long_bars = 900
+ _build_auto_run(tmp_path, "attr-long", n_bars=long_bars)
+
+ response = client.get("/runs/attr-long/attribution")
+
+ assert response.status_code == 200
+ factor = response.json()["factor"]
+ assert factor is not None
+ assert factor["n_obs"] == long_bars
+ assert len(factor["rolling"]) <= 500
+ assert len(factor["cumulative"]) <= 500
+ last_date = _trading_dates(long_bars)[-1]
+ assert factor["rolling"][-1]["date"] == last_date
+ assert factor["cumulative"][-1]["date"] == last_date
+ rng = np.random.default_rng(7)
+ benchmark = rng.normal(0.0005, 0.01, long_bars)
+ benchmark[0] = 0.0
+ expected_total = float(np.prod(1.0 + (0.001 + 1.2 * benchmark)) - 1.0)
+ assert factor["cumulative"][-1]["portfolio"] == pytest.approx(expected_total, abs=1e-6)
diff --git a/agent/tests/test_factor_api.py b/agent/tests/test_factor_api.py
index 9b1130633..3e55d59b9 100644
--- a/agent/tests/test_factor_api.py
+++ b/agent/tests/test_factor_api.py
@@ -152,6 +152,27 @@ def test_factor_endpoint_traversal_run_id_returns_400(tmp_path: Path, monkeypatc
assert response.json()["detail"] == "invalid run_id"
+def test_factor_endpoint_offloads_scan_to_threadpool(tmp_path: Path, monkeypatch) -> None:
+ """The blocking factor scan must run off the event loop via the threadpool."""
+ client = _client(tmp_path, monkeypatch)
+ run_dir = tmp_path / "runs" / "run_offload"
+ _write_factor_bundle(run_dir, "momentum_20d", "date,IC\n2024-01-02,0.02\n", _summary(1))
+
+ offloaded: list = []
+
+ async def fake_run_in_threadpool(func, *args, **kwargs):
+ offloaded.append(func)
+ return func(*args, **kwargs)
+
+ monkeypatch.setattr(runs_routes, "run_in_threadpool", fake_run_in_threadpool)
+
+ response = client.get("/runs/run_offload/factor")
+
+ assert response.status_code == 200
+ assert response.json()["exists"] is True
+ assert runs_routes._scan_factor_results in offloaded
+
+
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"
diff --git a/agent/tests/test_options_routes.py b/agent/tests/test_options_routes.py
index 4b400c1dd..de6d8d55d 100644
--- a/agent/tests/test_options_routes.py
+++ b/agent/tests/test_options_routes.py
@@ -165,6 +165,18 @@ def test_payoff_tool_error_maps_to_400() -> None:
assert "spot_max" in payload["error"]
+def test_payoff_unexpected_tool_exception_maps_to_502(monkeypatch: pytest.MonkeyPatch) -> None:
+ def explode(self: Any, **kwargs: Any) -> str:
+ raise RuntimeError("payoff engine exploded")
+
+ monkeypatch.setattr("src.api.options_routes.OptionsPayoffTool.execute", explode)
+
+ r = _client().post("/options/payoff", json=_long_call_body())
+
+ assert r.status_code == 502
+ assert r.json() == {"ok": False, "error": "payoff computation failed"}
+
+
# ── GET /options/chain ───────────────────────────────────────────────────────
_OK_CHAIN = json.dumps(
diff --git a/frontend/src/components/charts/AnnualReturnsChart.tsx b/frontend/src/components/charts/AnnualReturnsChart.tsx
index 92277c4a0..2f77aa9a5 100644
--- a/frontend/src/components/charts/AnnualReturnsChart.tsx
+++ b/frontend/src/components/charts/AnnualReturnsChart.tsx
@@ -1,9 +1,8 @@
-import { useEffect, useRef } from "react";
+import { useRef } from "react";
import i18n from "@/i18n";
import type { AnnualReturn } from "@/lib/tearsheet";
import { getChartTheme } from "@/lib/chart-theme";
-import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";
-import { useThemeDark } from "@/lib/theme-store";
+import { useChartLifecycle } from "@/hooks/useChartLifecycle";
interface Props {
data: AnnualReturn[];
@@ -12,18 +11,13 @@ interface Props {
export function AnnualReturnsChart({ data, height = 260 }: Props) {
const ref = useRef<HTMLDivElement>(null);
- const dark = useThemeDark();
- useEffect(() => {
- if (!ref.current || data.length === 0) return;
+ useChartLifecycle(ref, () => {
const t = getChartTheme();
- const chart = echarts.init(ref.current);
- chart.group = CHART_GROUP;
- connectCharts();
const seriesName = i18n.t("runDetail.annualReturns");
- chart.setOption({
+ return {
backgroundColor: "transparent",
tooltip: {
trigger: "axis",
@@ -77,23 +71,8 @@ export function AnnualReturnsChart({ data, height = 260 }: Props) {
},
},
],
- });
-
- let resizeFrame: number | null = null;
- const ro = new ResizeObserver(() => {
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- resizeFrame = requestAnimationFrame(() => {
- resizeFrame = null;
- chart.resize();
- });
- });
- ro.observe(ref.current!);
- return () => {
- ro.disconnect();
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- chart.dispose();
};
- }, [data, dark]);
+ }, [data]);
if (data.length === 0) {
return <div className="text-muted-foreground text-sm p-4">{i18n.t("runDetail.noTearsheetData")}</div>;
diff --git a/frontend/src/components/charts/AttributionCumulativeChart.tsx b/frontend/src/components/charts/AttributionCumulativeChart.tsx
new file mode 100644
index 000000000..1c0660dfe
--- /dev/null
+++ b/frontend/src/components/charts/AttributionCumulativeChart.tsx
@@ -0,0 +1,128 @@
+import { useEffect, useRef } from "react";
+import i18n from "@/i18n";
+import type { AttributionCumulativePoint } from "@/lib/api";
+import { getChartTheme } from "@/lib/chart-theme";
+import { getPnlColors } from "@/lib/pnl-colors";
+import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";
+import { escapeHtml } from "@/lib/escapeHtml";
+import { useThemeDark } from "@/lib/theme-store";
+
+interface Props {
+ data: AttributionCumulativePoint[];
+ height?: number;
+}
+
+export function AttributionCumulativeChart({ data, height = 300 }: Props) {
+ const ref = useRef<HTMLDivElement>(null);
+ const dark = useThemeDark();
+
+ useEffect(() => {
+ if (!ref.current || data.length === 0) return;
+ const t = getChartTheme();
+ const pnl = getPnlColors();
+ const chart = echarts.init(ref.current);
+ chart.group = CHART_GROUP;
+ connectCharts();
+
+ const portfolioLabel = i18n.t("runDetail.attrPortfolio");
+ const benchmarkLabel = i18n.t("runDetail.attrBenchmark");
+ const activeLabel = i18n.t("runDetail.attrActive");
+ const dates = data.map((d) => d.date);
+
+ chart.setOption({
+ backgroundColor: "transparent",
+ tooltip: {
+ trigger: "axis",
+ axisPointer: { type: "cross" },
+ backgroundColor: t.tooltipBg,
+ borderColor: t.tooltipBorder,
+ textStyle: { color: t.tooltipText, fontSize: 11 },
+ formatter: (raw: unknown) => {
+ const params = raw as Array<{ dataIndex?: number }>;
+ if (!Array.isArray(params) || !params.length) return "";
+ const point = data[params[0].dataIndex ?? 0];
+ if (!point) return "";
+ const pct = (v: number) => `${v > 0 ? "+" : ""}${(v * 100).toFixed(2)}%`;
+ return `<b>${escapeHtml(point.date)}</b>`
+ + `<br/>${portfolioLabel}: <b>${pct(point.portfolio)}</b>`
+ + `<br/>${benchmarkLabel}: <b>${pct(point.benchmark)}</b>`
+ + `<br/>${activeLabel}: <b>${pct(point.active)}</b>`;
+ },
+ },
+ legend: {
+ data: [portfolioLabel, benchmarkLabel, activeLabel],
+ textStyle: { color: t.textColor, fontSize: 11 },
+ right: 60,
+ top: 4,
+ },
+ toolbox: {
+ feature: {
+ saveAsImage: { title: "Save" },
+ restore: { title: "Reset" },
+ },
+ right: 8,
+ top: 0,
+ iconStyle: { borderColor: t.textColor },
+ },
+ grid: { left: 8, right: 8, top: 36, bottom: 8, containLabel: true },
+ xAxis: {
+ type: "category",
+ data: dates,
+ axisLine: { lineStyle: { color: t.axisColor } },
+ axisLabel: { color: t.textColor, fontSize: 10 },
+ },
+ yAxis: {
+ type: "value",
+ splitLine: { lineStyle: { color: t.gridColor } },
+ axisLabel: { color: t.textColor, fontSize: 10, formatter: "{value}%" },
+ },
+ dataZoom: [{ type: "inside" }],
+ series: [
+ {
+ name: portfolioLabel,
+ type: "line",
+ data: data.map((d) => +(d.portfolio * 100).toFixed(4)),
+ smooth: false,
+ symbol: "none",
+ lineStyle: { color: t.infoColor, width: 2 },
+ },
+ {
+ name: benchmarkLabel,
+ type: "line",
+ data: data.map((d) => +(d.benchmark * 100).toFixed(4)),
+ smooth: false,
+ symbol: "none",
+ lineStyle: { color: t.textColor, width: 1.5 },
+ },
+ {
+ name: activeLabel,
+ type: "line",
+ data: data.map((d) => +(d.active * 100).toFixed(4)),
+ smooth: false,
+ symbol: "none",
+ lineStyle: { color: pnl.profit, width: 1.5, type: "dashed" },
+ },
+ ],
+ });
+
+ let resizeFrame: number | null = null;
+ const ro = new ResizeObserver(() => {
+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
+ resizeFrame = requestAnimationFrame(() => {
+ resizeFrame = null;
+ chart.resize();
+ });
+ });
+ ro.observe(ref.current!);
+ return () => {
+ ro.disconnect();
+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
+ chart.dispose();
+ };
+ }, [data, dark]);
+
+ if (data.length === 0) {
+ return <div className="text-muted-foreground text-sm p-4">{i18n.t("runDetail.attrNoFactor")}</div>;
+ }
+ return <div ref={ref} style={{ height }} />;
+}
diff --git a/frontend/src/components/charts/AttributionTab.tsx b/frontend/src/components/charts/AttributionTab.tsx
new file mode 100644
index 000000000..4f88f8353
--- /dev/null
+++ b/frontend/src/components/charts/AttributionTab.tsx
@@ -0,0 +1,275 @@
+import { useEffect, useState } from "react";
+import type { ReactNode } from "react";
+import i18n from "@/i18n";
+import { Activity, AlertTriangle, BarChart3, Loader2, TrendingUp } from "lucide-react";
+import { cn } from "@/lib/utils";
+import { api } from "@/lib/api";
+import type {
+ AttributionBenchmarkInfo,
+ AttributionBrinson,
+ AttributionFactor,
+ AttributionResponse,
+ RunData,
+} from "@/lib/api";
+import { AttributionCumulativeChart } from "./AttributionCumulativeChart";
+import { AttributionWaterfallChart } from "./AttributionWaterfallChart";
+import { RollingBetaAlphaChart } from "./RollingBetaAlphaChart";
+
+type AttrState =
+ | { status: "loading" }
+ | { status: "error"; message: string }
+ | { status: "ready"; data: AttributionResponse };
+
+function fmtPct(v: number, digits = 2): string {
+ return `${(v * 100).toFixed(digits)}%`;
+}
+
+function fmtSignedPct(v: number, digits = 2): string {
+ return `${v > 0 ? "+" : ""}${(v * 100).toFixed(digits)}%`;
+}
+
+function signedTone(v: number): "positive" | "negative" | "neutral" {
+ if (v > 0) return "positive";
+ if (v < 0) return "negative";
+ return "neutral";
+}
+
+function signedNumberClass(value: number): string {
+ if (value === 0) return "text-muted-foreground";
+ return value > 0 ? "text-success" : "text-danger";
+}
+
+function benchmarkCaption(benchmark: AttributionBenchmarkInfo | null): string {
+ if (!benchmark) return i18n.t("runDetail.attrNoBenchmark");
+ const label = i18n.t("runDetail.attrBenchmark");
+ if (benchmark.mode === "auto_equal_weight") {
+ const auto = i18n.t("runDetail.attrAutoEqualWeight");
+ return benchmark.ticker ? `${label}: ${benchmark.ticker} · ${auto}` : `${label}: ${auto}`;
+ }
+ if (benchmark.ticker) return `${label}: ${benchmark.ticker}`;
+ return i18n.t("runDetail.attrNoBenchmark");
+}
+
+function modeCaption(mode: AttributionBrinson["mode"]): string {
+ if (mode === "asset_class") return i18n.t("runDetail.attrModeAssetClass");
+ if (mode === "invested_cash") return i18n.t("runDetail.attrModeInvestedCash");
+ return i18n.t("runDetail.attrModeSymbol");
+}
+
+function AttrStat({ label, value, sub, tone = "neutral" }: {
+ label: string;
+ value: string;
+ sub?: string;
+ tone?: "positive" | "negative" | "neutral";
+}) {
+ return (
+ <div className="rounded-xl border border-border/60 bg-card p-4 shadow-sm">
+ <div className="text-xs text-muted-foreground">{label}</div>
+ <div className={cn(
+ "mt-1 truncate text-sm font-medium tabular-nums",
+ tone === "positive" && "text-success",
+ tone === "negative" && "text-danger",
+ )}>
+ {value}
+ </div>
+ {sub && <div className="mt-0.5 text-[11px] text-muted-foreground">{sub}</div>}
+ </div>
+ );
+}
+
+function AttrPanel({ title, icon: Icon, children }: {
+ title: string;
+ icon: typeof BarChart3;
+ 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">
+ <Icon className="h-4 w-4 text-muted-foreground" />
+ {title}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+function BrinsonTable({ brinson }: { brinson: AttributionBrinson }) {
+ const sectors = brinson.sectors;
+ const weightTotal = (pick: "portfolio_weight" | "benchmark_weight") =>
+ sectors.reduce((sum, s) => sum + s[pick], 0);
+
+ return (
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b bg-muted/40 text-left text-[11px] uppercase tracking-wide text-muted-foreground [&_th]:font-medium">
+ <th className="py-2 ps-4 pr-4">{i18n.t("runDetail.attrSector")}</th>
+ <th className="py-2 pr-4 text-right">{i18n.t("runDetail.attrPortfolioWeight")}</th>
+ <th className="py-2 pr-4 text-right">{i18n.t("runDetail.attrBenchmarkWeight")}</th>
+ <th className="py-2 pr-4 text-right">{i18n.t("runDetail.attrPortfolioReturn")}</th>
+ <th className="py-2 pr-4 text-right">{i18n.t("runDetail.attrBenchmarkReturn")}</th>
+ <th className="py-2 pr-4 text-right">{i18n.t("runDetail.attrAllocation")}</th>
+ <th className="py-2 pr-4 text-right">{i18n.t("runDetail.attrSelection")}</th>
+ <th className="py-2 pr-4 text-right">{i18n.t("runDetail.attrInteraction")}</th>
+ <th className="py-2 text-right">{i18n.t("runDetail.attrTotal")}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {sectors.map((s) => (
+ <tr key={s.sector} className="border-b last:border-0 hover:bg-muted/40">
+ <td className="py-2 ps-4 pr-4 font-mono text-xs">{s.sector}</td>
+ <td className="py-2 pr-4 text-right font-mono tabular-nums">{fmtPct(s.portfolio_weight)}</td>
+ <td className="py-2 pr-4 text-right font-mono tabular-nums">{fmtPct(s.benchmark_weight)}</td>
+ <td className="py-2 pr-4 text-right font-mono tabular-nums">{fmtSignedPct(s.portfolio_return)}</td>
+ <td className="py-2 pr-4 text-right font-mono tabular-nums">{fmtSignedPct(s.benchmark_return)}</td>
+ <td className={cn("py-2 pr-4 text-right font-mono tabular-nums", signedNumberClass(s.allocation))}>{fmtSignedPct(s.allocation)}</td>
+ <td className={cn("py-2 pr-4 text-right font-mono tabular-nums", signedNumberClass(s.selection))}>{fmtSignedPct(s.selection)}</td>
+ <td className={cn("py-2 pr-4 text-right font-mono tabular-nums", signedNumberClass(s.interaction))}>{fmtSignedPct(s.interaction)}</td>
+ <td className={cn("py-2 text-right font-mono tabular-nums", signedNumberClass(s.total))}>{fmtSignedPct(s.total)}</td>
+ </tr>
+ ))}
+ <tr className="border-t bg-muted/40 font-semibold">
+ <td className="py-2 ps-4 pr-4">{i18n.t("runDetail.attrTotal")}</td>
+ <td className="py-2 pr-4 text-right font-mono tabular-nums">{fmtPct(weightTotal("portfolio_weight"))}</td>
+ <td className="py-2 pr-4 text-right font-mono tabular-nums">{fmtPct(weightTotal("benchmark_weight"))}</td>
+ <td className="py-2 pr-4 text-right font-mono tabular-nums">{fmtSignedPct(brinson.portfolio_return)}</td>
+ <td className="py-2 pr-4 text-right font-mono tabular-nums">{fmtSignedPct(brinson.benchmark_return)}</td>
+ <td className={cn("py-2 pr-4 text-right font-mono tabular-nums", signedNumberClass(brinson.allocation))}>{fmtSignedPct(brinson.allocation)}</td>
+ <td className={cn("py-2 pr-4 text-right font-mono tabular-nums", signedNumberClass(brinson.selection))}>{fmtSignedPct(brinson.selection)}</td>
+ <td className={cn("py-2 pr-4 text-right font-mono tabular-nums", signedNumberClass(brinson.interaction))}>{fmtSignedPct(brinson.interaction)}</td>
+ <td className={cn("py-2 text-right font-mono tabular-nums", signedNumberClass(brinson.active_return))}>{fmtSignedPct(brinson.active_return)}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ );
+}
+
+function FactorStatCards({ factor, metrics }: { factor: AttributionFactor | null; metrics: RunData["metrics"] }) {
+ const informationRatio = metrics?.information_ratio;
+ const trackingError = metrics?.tracking_error;
+ const hasFactor = factor !== null;
+ if (!hasFactor && informationRatio === undefined && trackingError === undefined) return null;
+
+ return (
+ <div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-5">
+ {hasFactor && (
+ <>
+ <AttrStat
+ label={i18n.t("runDetail.attrAlpha")}
+ value={fmtSignedPct(factor.alpha_annualized)}
+ sub={i18n.t("runDetail.attrTStat", { value: factor.alpha_t_stat.toFixed(2) })}
+ tone={signedTone(factor.alpha_annualized)}
+ />
+ <AttrStat label={i18n.t("runDetail.attrBeta")} value={factor.beta.toFixed(2)} />
+ <AttrStat label={i18n.t("runDetail.attrRSquared")} value={factor.r_squared.toFixed(2)} />
+ </>
+ )}
+ {informationRatio !== undefined && (
+ <AttrStat
+ label={i18n.t("runDetail.attrInformationRatio")}
+ value={`${informationRatio > 0 ? "+" : ""}${informationRatio.toFixed(2)}`}
+ tone={signedTone(informationRatio)}
+ />
+ )}
+ {trackingError !== undefined && (
+ <AttrStat label={i18n.t("runDetail.attrTrackingError")} value={fmtPct(trackingError)} />
+ )}
+ </div>
+ );
+}
+
+export function AttributionTab({ runId, run }: { runId: string; run: RunData }) {
+ const [state, setState] = useState<AttrState>({ status: "loading" });
+
+ useEffect(() => {
+ let cancelled = false;
+ setState({ status: "loading" });
+ api.getRunAttribution(runId)
+ .then((data) => {
+ if (!cancelled) setState({ status: "ready", data });
+ })
+ .catch((error: unknown) => {
+ if (!cancelled) {
+ setState({ status: "error", message: error instanceof Error ? error.message : String(error) });
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [runId]);
+
+ if (state.status === "loading") {
+ return (
+ <div className="flex items-center gap-2 p-8 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
+ {i18n.t("runDetail.attrLoading")}
+ </div>
+ );
+ }
+
+ if (state.status === "error") {
+ return (
+ <div className="flex items-center gap-2 p-8 text-sm text-danger">
+ <AlertTriangle className="h-4 w-4" aria-hidden="true" />
+ <span>{i18n.t("runDetail.attrError")}</span>
+ <span className="text-muted-foreground">{state.message}</span>
+ </div>
+ );
+ }
+
+ const { data } = state;
+ const factor = data.factor;
+ const brinson = data.brinson;
+
+ if (!data.exists || (!factor && !brinson)) {
+ return <div className="p-8 text-muted-foreground text-sm">{i18n.t("runDetail.attrNoData")}</div>;
+ }
+
+ return (
+ <div className="p-4 space-y-4">
+ <FactorStatCards factor={factor} metrics={run.metrics} />
+
+ {brinson ? (
+ <>
+ <AttrPanel title={i18n.t("runDetail.attrBrinsonTitle")} icon={BarChart3}>
+ <BrinsonTable brinson={brinson} />
+ <p className="mt-2 text-xs text-muted-foreground">{modeCaption(brinson.mode)}</p>
+ {data.notes.length > 0 && (
+ <ul className="mt-1 space-y-0.5 text-xs text-muted-foreground">
+ {data.notes.map((note, index) => <li key={index}>{note}</li>)}
+ </ul>
+ )}
+ </AttrPanel>
+ <AttrPanel title={i18n.t("runDetail.attrWaterfallTitle")} icon={BarChart3}>
+ <AttributionWaterfallChart brinson={brinson} height={300} />
+ </AttrPanel>
+ </>
+ ) : (
+ <p className="text-xs text-muted-foreground">{i18n.t("runDetail.attrNoBrinson")}</p>
+ )}
+
+ {factor ? (
+ <>
+ {factor.rolling && factor.rolling.length > 0 && (
+ <AttrPanel title={i18n.t("runDetail.attrRollingTitle")} icon={Activity}>
+ <p className="mb-2 text-xs text-muted-foreground">
+ {i18n.t("runDetail.attrRollingWindow", { count: factor.rolling_window })}
+ </p>
+ <RollingBetaAlphaChart data={factor.rolling} height={280} />
+ </AttrPanel>
+ )}
+ {factor.cumulative.length > 0 && (
+ <AttrPanel title={i18n.t("runDetail.attrCumulativeTitle")} icon={TrendingUp}>
+ <AttributionCumulativeChart data={factor.cumulative} height={300} />
+ </AttrPanel>
+ )}
+ </>
+ ) : (
+ <p className="text-xs text-muted-foreground">{i18n.t("runDetail.attrNoFactor")}</p>
+ )}
+
+ <p className="text-xs text-muted-foreground">{benchmarkCaption(data.benchmark)}</p>
+ </div>
+ );
+}
diff --git a/frontend/src/components/charts/AttributionWaterfallChart.tsx b/frontend/src/components/charts/AttributionWaterfallChart.tsx
new file mode 100644
index 000000000..2fc1b9706
--- /dev/null
+++ b/frontend/src/components/charts/AttributionWaterfallChart.tsx
@@ -0,0 +1,147 @@
+import { useEffect, useRef } from "react";
+import i18n from "@/i18n";
+import type { AttributionBrinson } from "@/lib/api";
+import { getChartTheme } from "@/lib/chart-theme";
+import { getPnlColors } from "@/lib/pnl-colors";
+import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";
+import { useThemeDark } from "@/lib/theme-store";
+
+export interface WaterfallBar {
+ base: number;
+ value: number;
+ kind: "level" | "effect";
+}
+
+// Waterfall identity: benchmark + allocation + selection + interaction equals
+// portfolio, so each effect bar starts where the previous bar ended.
+export function buildWaterfallBars(
+ brinson: Pick<AttributionBrinson, "benchmark_return" | "allocation" | "selection" | "interaction">,
+): WaterfallBar[] {
+ const b = brinson.benchmark_return;
+ const a = brinson.allocation;
+ const s = brinson.selection;
+ const x = brinson.interaction;
+ return [
+ { base: 0, value: b, kind: "level" },
+ { base: b, value: a, kind: "effect" },
+ { base: b + a, value: s, kind: "effect" },
+ { base: b + a + s, value: x, kind: "effect" },
+ { base: 0, value: b + a + s + x, kind: "level" },
+ ];
+}
+
+function fmtSignedPct(v: number): string {
+ return `${v > 0 ? "+" : ""}${(v * 100).toFixed(2)}%`;
+}
+
+interface Props {
+ brinson: AttributionBrinson;
+ height?: number;
+}
+
+export function AttributionWaterfallChart({ brinson, height = 300 }: Props) {
+ const ref = useRef<HTMLDivElement>(null);
+ const dark = useThemeDark();
+
+ useEffect(() => {
+ if (!ref.current) return;
+ const t = getChartTheme();
+ const pnl = getPnlColors();
+ const chart = echarts.init(ref.current);
+ chart.group = CHART_GROUP;
+ connectCharts();
+
+ const bars = buildWaterfallBars(brinson);
+ const categories = [
+ i18n.t("runDetail.attrBenchmark"),
+ i18n.t("runDetail.attrAllocation"),
+ i18n.t("runDetail.attrSelection"),
+ i18n.t("runDetail.attrInteraction"),
+ i18n.t("runDetail.attrPortfolio"),
+ ];
+ const valueLabel = i18n.t("runDetail.returnPct");
+
+ const placeholders = bars.map((bar) => +(Math.min(bar.base, bar.base + bar.value) * 100).toFixed(4));
+ const values = bars.map((bar) => ({
+ value: +(Math.abs(bar.value) * 100).toFixed(4),
+ itemStyle: {
+ color: bar.kind === "level" ? t.infoColor : bar.value >= 0 ? pnl.profit : pnl.loss,
+ borderRadius: 2,
+ },
+ label: {
+ show: true,
+ position: bar.value >= 0 ? "top" : "bottom",
+ formatter: fmtSignedPct(bar.value),
+ fontSize: 10,
+ color: bar.kind === "level" ? t.textColor : bar.value >= 0 ? pnl.profit : pnl.loss,
+ },
+ }));
+
+ chart.setOption({
+ backgroundColor: "transparent",
+ tooltip: {
+ trigger: "axis",
+ axisPointer: { type: "shadow" },
+ backgroundColor: t.tooltipBg,
+ borderColor: t.tooltipBorder,
+ textStyle: { color: t.tooltipText, fontSize: 11 },
+ formatter: (raw: unknown) => {
+ const params = raw as Array<{ dataIndex?: number }>;
+ if (!Array.isArray(params) || !params.length) return "";
+ const idx = params[0].dataIndex ?? 0;
+ const bar = bars[idx];
+ if (!bar) return "";
+ return `<b>${categories[idx]}</b><br/>${valueLabel}: <b>${fmtSignedPct(bar.value)}</b>`;
+ },
+ },
+ grid: { left: 8, right: 8, top: 28, bottom: 8, containLabel: true },
+ xAxis: {
+ type: "category",
+ data: categories,
+ axisLine: { lineStyle: { color: t.axisColor } },
+ axisLabel: { color: t.textColor, fontSize: 10 },
+ },
+ yAxis: {
+ type: "value",
+ splitLine: { lineStyle: { color: t.gridColor } },
+ axisLabel: { color: t.textColor, fontSize: 10, formatter: "{value}%" },
+ },
+ series: [
+ {
+ name: "placeholder",
+ type: "bar",
+ stack: "waterfall",
+ data: placeholders,
+ silent: true,
+ itemStyle: { color: "transparent" },
+ emphasis: { itemStyle: { color: "transparent" } },
+ tooltip: { show: false },
+ },
+ {
+ name: valueLabel,
+ type: "bar",
+ stack: "waterfall",
+ data: values,
+ barWidth: "45%",
+ },
+ ],
+ });
+
+ let resizeFrame: number | null = null;
+ const ro = new ResizeObserver(() => {
+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
+ resizeFrame = requestAnimationFrame(() => {
+ resizeFrame = null;
+ chart.resize();
+ });
+ });
+ ro.observe(ref.current!);
+ return () => {
+ ro.disconnect();
+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
+ chart.dispose();
+ };
+ }, [brinson, dark]);
+
+ return <div ref={ref} style={{ height }} />;
+}
diff --git a/frontend/src/components/charts/CorrelationMatrix.tsx b/frontend/src/components/charts/CorrelationMatrix.tsx
index ade4e5d84..6ecd7a997 100644
--- a/frontend/src/components/charts/CorrelationMatrix.tsx
+++ b/frontend/src/components/charts/CorrelationMatrix.tsx
@@ -1,8 +1,8 @@
-import { useEffect, useRef } from "react";
+import { useRef } from "react";
import i18n from "@/i18n";
-import { echarts } from "@/lib/echarts";
import { getChartTheme } from "@/lib/chart-theme";
-import { useThemeDark } from "@/lib/theme-store";
+import { escapeHtml } from "@/lib/escapeHtml";
+import { useChartLifecycle } from "@/hooks/useChartLifecycle";
interface Props {
labels: string[];
@@ -29,13 +29,9 @@ function cellTextColor(value: number): string {
export function CorrelationMatrix({ labels, matrix, height = 500 }: Props) {
const ref = useRef<HTMLDivElement>(null);
- const dark = useThemeDark();
-
- useEffect(() => {
- if (!ref.current || labels.length === 0 || matrix.length === 0) return;
+ useChartLifecycle(ref, () => {
const t = getChartTheme();
- const chart = echarts.init(ref.current);
// 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 } }[] = [];
@@ -49,7 +45,7 @@ export function CorrelationMatrix({ labels, matrix, height = 500 }: Props) {
const minVal = -1;
const maxVal = 1;
- chart.setOption({
+ return {
backgroundColor: "transparent",
tooltip: {
position: "top",
@@ -59,7 +55,7 @@ export function CorrelationMatrix({ labels, matrix, height = 500 }: Props) {
formatter: (params: unknown) => {
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>`;
+ return `<b>${escapeHtml(labels[x] ?? "")}</b> vs <b>${escapeHtml(labels[y] ?? "")}</b><br/>r = <b>${v.toFixed(4)}</b>`;
},
},
grid: { left: "3%", right: "8%", top: "8%", bottom: "12%", containLabel: true },
@@ -113,25 +109,10 @@ export function CorrelationMatrix({ labels, matrix, height = 500 }: Props) {
},
},
],
- });
-
- let resizeFrame: number | null = null;
- const ro = new ResizeObserver(() => {
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- resizeFrame = requestAnimationFrame(() => {
- resizeFrame = null;
- chart.resize();
- });
- });
- ro.observe(ref.current!);
- return () => {
- ro.disconnect();
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- chart.dispose();
};
- }, [labels, matrix, dark]);
+ }, [labels, matrix]);
- if (labels.length === 0) {
+ if (labels.length === 0 || matrix.length === 0) {
return <div className="text-muted-foreground text-sm p-4">{i18n.t("charts.noCorrelationData")}</div>;
}
return <div ref={ref} style={{ height }} />;
diff --git a/frontend/src/components/charts/EquityChart.tsx b/frontend/src/components/charts/EquityChart.tsx
index 4cf5a5bc8..3582b0265 100644
--- a/frontend/src/components/charts/EquityChart.tsx
+++ b/frontend/src/components/charts/EquityChart.tsx
@@ -1,10 +1,10 @@
-import { useEffect, useRef } from "react";
+import { useRef } from "react";
import i18n from "@/i18n";
import type { EquityPoint } from "@/lib/api";
import { getChartTheme } from "@/lib/chart-theme";
import { abbreviateNum } from "@/lib/formatters";
-import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";
-import { useThemeDark } from "@/lib/theme-store";
+import { escapeHtml } from "@/lib/escapeHtml";
+import { useChartLifecycle } from "@/hooks/useChartLifecycle";
import type { DrawdownZone } from "@/lib/tearsheet";
interface Props {
@@ -15,14 +15,9 @@ interface Props {
export function EquityChart({ data, height = 300, drawdownZones }: Props) {
const ref = useRef<HTMLDivElement>(null);
- const dark = useThemeDark();
- useEffect(() => {
- if (!ref.current || data.length === 0) return;
+ useChartLifecycle(ref, () => {
const t = getChartTheme();
- const chart = echarts.init(ref.current);
- chart.group = CHART_GROUP;
- connectCharts();
const zones = drawdownZones ?? [];
const dates = data.map((d) => d.time);
@@ -30,7 +25,7 @@ export function EquityChart({ data, height = 300, drawdownZones }: Props) {
const drawdown = data.map((d) => (Number(d.drawdown) * 100).toFixed(2));
const minDD = Math.min(...drawdown.map(Number));
- chart.setOption({
+ return {
backgroundColor: "transparent",
tooltip: {
trigger: "axis",
@@ -41,7 +36,7 @@ export function EquityChart({ data, height = 300, drawdownZones }: Props) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
formatter: (params: any) => {
if (!Array.isArray(params) || !params.length) return "";
- let html = `<b>${params[0].axisValue}</b>`;
+ let html = `<b>${escapeHtml(String(params[0].axisValue))}</b>`;
for (const p of params) {
const val = p.seriesName === "Drawdown%"
? `${p.value}%`
@@ -115,23 +110,8 @@ export function EquityChart({ data, height = 300, drawdownZones }: Props) {
},
},
],
- });
-
- let resizeFrame: number | null = null;
- const ro = new ResizeObserver(() => {
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- resizeFrame = requestAnimationFrame(() => {
- resizeFrame = null;
- chart.resize();
- });
- });
- ro.observe(ref.current!);
- return () => {
- ro.disconnect();
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- chart.dispose();
};
- }, [data, drawdownZones, dark]);
+ }, [data, drawdownZones]);
if (data.length === 0) {
return <div className="text-muted-foreground text-sm p-4">{i18n.t("charts.noEquityData")}</div>;
diff --git a/frontend/src/components/charts/FactorResearchPanel.tsx b/frontend/src/components/charts/FactorResearchPanel.tsx
index 977e5735e..b6c7b58fa 100644
--- a/frontend/src/components/charts/FactorResearchPanel.tsx
+++ b/frontend/src/components/charts/FactorResearchPanel.tsx
@@ -6,7 +6,7 @@ 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 { RunCardPanel, RunCardStat } from "@/components/run/RunCard";
import { CorrelationMatrix } from "./CorrelationMatrix";
const SLATE = "#8f98a6";
diff --git a/frontend/src/components/charts/MonthlyReturnsHeatmap.tsx b/frontend/src/components/charts/MonthlyReturnsHeatmap.tsx
index bc90f47b8..2c2c89a6f 100644
--- a/frontend/src/components/charts/MonthlyReturnsHeatmap.tsx
+++ b/frontend/src/components/charts/MonthlyReturnsHeatmap.tsx
@@ -1,9 +1,8 @@
-import { useEffect, useRef } from "react";
+import { useRef } from "react";
import i18n from "@/i18n";
import type { AnnualReturn, MonthlyReturn } from "@/lib/tearsheet";
import { getChartTheme } from "@/lib/chart-theme";
-import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";
-import { useThemeDark } from "@/lib/theme-store";
+import { useChartLifecycle } from "@/hooks/useChartLifecycle";
interface Props {
data: MonthlyReturn[];
@@ -17,14 +16,9 @@ function fmtSignedPct(v: number, digits = 1): string {
export function MonthlyReturnsHeatmap({ data, annual, height = 300 }: Props) {
const ref = useRef<HTMLDivElement>(null);
- const dark = useThemeDark();
- useEffect(() => {
- if (!ref.current || data.length === 0) return;
+ useChartLifecycle(ref, () => {
const t = getChartTheme();
- const chart = echarts.init(ref.current);
- chart.group = CHART_GROUP;
- connectCharts();
const monthFmt = new Intl.DateTimeFormat(i18n.language || "en", { month: "short" });
const monthLabels = Array.from({ length: 12 }, (_, i) => monthFmt.format(new Date(2024, i, 15)));
@@ -53,7 +47,7 @@ export function MonthlyReturnsHeatmap({ data, annual, height = 300 }: Props) {
const returnLabel = i18n.t("runDetail.returnPct");
- chart.setOption({
+ return {
backgroundColor: "transparent",
tooltip: {
trigger: "item",
@@ -115,23 +109,8 @@ export function MonthlyReturnsHeatmap({ data, annual, height = 300 }: Props) {
emphasis: { itemStyle: { borderColor: t.axisColor, borderWidth: 1 } },
},
],
- });
-
- let resizeFrame: number | null = null;
- const ro = new ResizeObserver(() => {
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- resizeFrame = requestAnimationFrame(() => {
- resizeFrame = null;
- chart.resize();
- });
- });
- ro.observe(ref.current!);
- return () => {
- ro.disconnect();
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- chart.dispose();
};
- }, [data, annual, dark]);
+ }, [data, annual]);
if (data.length === 0) {
return <div className="text-muted-foreground text-sm p-4">{i18n.t("runDetail.noTearsheetData")}</div>;
diff --git a/frontend/src/components/charts/OptionsPayoffChart.tsx b/frontend/src/components/charts/OptionsPayoffChart.tsx
index 987d05642..8b499d95f 100644
--- a/frontend/src/components/charts/OptionsPayoffChart.tsx
+++ b/frontend/src/components/charts/OptionsPayoffChart.tsx
@@ -1,11 +1,10 @@
-import { useEffect, useRef } from "react";
+import { useRef } from "react";
import i18n from "@/i18n";
import type { ExpiryCurve } from "@/lib/options";
import { getChartTheme } from "@/lib/chart-theme";
import { getPnlColors } from "@/lib/pnl-colors";
import { abbreviateNum } from "@/lib/formatters";
-import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";
-import { useThemeDark } from "@/lib/theme-store";
+import { useChartLifecycle } from "@/hooks/useChartLifecycle";
interface Props {
curve: ExpiryCurve;
@@ -16,15 +15,10 @@ interface Props {
export function OptionsPayoffChart({ curve, entrySpot, breakevens, height = 340 }: Props) {
const ref = useRef<HTMLDivElement>(null);
- const dark = useThemeDark();
- useEffect(() => {
- if (!ref.current || curve.spot.length === 0 || curve.pnl.length === 0) return;
+ useChartLifecycle(ref, () => {
const t = getChartTheme();
const pnlC = getPnlColors();
- const chart = echarts.init(ref.current);
- chart.group = CHART_GROUP;
- connectCharts();
const pnlLabel = i18n.t("options.payoff.pnl");
const spotLabel = i18n.t("options.payoff.entrySpot");
@@ -34,7 +28,7 @@ export function OptionsPayoffChart({ curve, entrySpot, breakevens, height = 340
const profitData = pairs.map(([s, v]) => [s, v >= 0 ? v : null]);
const lossData = pairs.map(([s, v]) => [s, v <= 0 ? v : null]);
- chart.setOption({
+ return {
backgroundColor: "transparent",
tooltip: {
trigger: "axis",
@@ -150,23 +144,8 @@ export function OptionsPayoffChart({ curve, entrySpot, breakevens, height = 340
tooltip: { show: false },
},
],
- });
-
- let resizeFrame: number | null = null;
- const ro = new ResizeObserver(() => {
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- resizeFrame = requestAnimationFrame(() => {
- resizeFrame = null;
- chart.resize();
- });
- });
- ro.observe(ref.current!);
- return () => {
- ro.disconnect();
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- chart.dispose();
};
- }, [curve, entrySpot, breakevens, dark]);
+ }, [curve, entrySpot, breakevens]);
if (curve.spot.length === 0 || curve.pnl.length === 0) {
return <div className="text-muted-foreground text-sm p-4">{i18n.t("options.payoff.noData")}</div>;
diff --git a/frontend/src/components/charts/OptionsScenarioMatrix.tsx b/frontend/src/components/charts/OptionsScenarioMatrix.tsx
index cad408aa3..7222cc133 100644
--- a/frontend/src/components/charts/OptionsScenarioMatrix.tsx
+++ b/frontend/src/components/charts/OptionsScenarioMatrix.tsx
@@ -1,10 +1,9 @@
-import { useEffect, useRef } from "react";
+import { useRef } from "react";
import i18n from "@/i18n";
import { downsampleIndices, ivLabel, type ScenarioGrid } from "@/lib/options";
import { getChartTheme } from "@/lib/chart-theme";
import { getPnlColors } from "@/lib/pnl-colors";
-import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";
-import { useThemeDark } from "@/lib/theme-store";
+import { useChartLifecycle } from "@/hooks/useChartLifecycle";
const MAX_DISPLAY_COLUMNS = 61;
@@ -15,18 +14,13 @@ interface Props {
export function OptionsScenarioMatrix({ grid, height = 380 }: Props) {
const ref = useRef<HTMLDivElement>(null);
- const dark = useThemeDark();
const hasData =
grid.iv_values.length > 0 && grid.spot.length > 0 && grid.pnl.length > 0;
- useEffect(() => {
- if (!ref.current || !hasData) return;
+ useChartLifecycle(ref, () => {
const t = getChartTheme();
const pnlC = getPnlColors();
- const chart = echarts.init(ref.current);
- chart.group = CHART_GROUP;
- connectCharts();
// Downsample the spot axis for display only; cell values keep reading the
// original grid at the retained indices, so labels stay honest.
@@ -49,7 +43,7 @@ export function OptionsScenarioMatrix({ grid, height = 380 }: Props) {
}
const bound = Math.max(Math.abs(minVal), Math.abs(maxVal), 1e-9);
- chart.setOption({
+ return {
backgroundColor: "transparent",
tooltip: {
position: "top",
@@ -117,23 +111,8 @@ export function OptionsScenarioMatrix({ grid, height = 380 }: Props) {
},
},
],
- });
-
- let resizeFrame: number | null = null;
- const ro = new ResizeObserver(() => {
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- resizeFrame = requestAnimationFrame(() => {
- resizeFrame = null;
- chart.resize();
- });
- });
- ro.observe(ref.current!);
- return () => {
- ro.disconnect();
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- chart.dispose();
};
- }, [grid, hasData, dark]);
+ }, [grid, hasData]);
if (!hasData) {
return <div className="text-muted-foreground text-sm p-4">{i18n.t("options.scenario.noData")}</div>;
diff --git a/frontend/src/components/charts/RollingBetaAlphaChart.tsx b/frontend/src/components/charts/RollingBetaAlphaChart.tsx
new file mode 100644
index 000000000..bd308914c
--- /dev/null
+++ b/frontend/src/components/charts/RollingBetaAlphaChart.tsx
@@ -0,0 +1,130 @@
+import { useEffect, useRef } from "react";
+import i18n from "@/i18n";
+import type { AttributionRollingPoint } from "@/lib/api";
+import { getChartTheme } from "@/lib/chart-theme";
+import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";
+import { escapeHtml } from "@/lib/escapeHtml";
+import { useThemeDark } from "@/lib/theme-store";
+
+interface Props {
+ data: AttributionRollingPoint[];
+ height?: number;
+}
+
+export function RollingBetaAlphaChart({ data, height = 280 }: Props) {
+ const ref = useRef<HTMLDivElement>(null);
+ const dark = useThemeDark();
+
+ useEffect(() => {
+ if (!ref.current || data.length === 0) return;
+ const t = getChartTheme();
+ const chart = echarts.init(ref.current);
+ chart.group = CHART_GROUP;
+ connectCharts();
+
+ const betaLabel = i18n.t("runDetail.attrBeta");
+ const alphaLabel = i18n.t("runDetail.attrAlpha");
+ const dates = data.map((d) => d.date);
+ const betas = data.map((d) => +d.beta.toFixed(4));
+ const alphas = data.map((d) => +(d.alpha_annualized * 100).toFixed(4));
+
+ chart.setOption({
+ backgroundColor: "transparent",
+ tooltip: {
+ trigger: "axis",
+ axisPointer: { type: "cross" },
+ backgroundColor: t.tooltipBg,
+ borderColor: t.tooltipBorder,
+ textStyle: { color: t.tooltipText, fontSize: 11 },
+ formatter: (raw: unknown) => {
+ const params = raw as Array<{ dataIndex?: number }>;
+ if (!Array.isArray(params) || !params.length) return "";
+ const point = data[params[0].dataIndex ?? 0];
+ if (!point) return "";
+ return `<b>${escapeHtml(point.date)}</b>`
+ + `<br/>${betaLabel}: <b>${point.beta.toFixed(2)}</b>`
+ + `<br/>${alphaLabel}: <b>${(point.alpha_annualized * 100).toFixed(2)}%</b>`;
+ },
+ },
+ legend: {
+ data: [betaLabel, alphaLabel],
+ textStyle: { color: t.textColor, fontSize: 11 },
+ right: 60,
+ top: 4,
+ },
+ toolbox: {
+ feature: {
+ saveAsImage: { title: "Save" },
+ restore: { title: "Reset" },
+ },
+ right: 8,
+ top: 0,
+ iconStyle: { borderColor: t.textColor },
+ },
+ grid: { left: 8, right: 8, top: 36, bottom: 8, containLabel: true },
+ xAxis: {
+ type: "category",
+ data: dates,
+ axisLine: { lineStyle: { color: t.axisColor } },
+ axisLabel: { color: t.textColor, fontSize: 10 },
+ },
+ yAxis: [
+ {
+ type: "value",
+ name: betaLabel,
+ nameTextStyle: { color: t.textColor, fontSize: 10 },
+ splitLine: { lineStyle: { color: t.gridColor } },
+ axisLabel: { color: t.textColor, fontSize: 10 },
+ },
+ {
+ type: "value",
+ name: alphaLabel,
+ nameTextStyle: { color: t.textColor, fontSize: 10 },
+ splitLine: { show: false },
+ axisLabel: { color: t.textColor, fontSize: 10, formatter: "{value}%" },
+ },
+ ],
+ dataZoom: [{ type: "inside" }],
+ series: [
+ {
+ name: betaLabel,
+ type: "line",
+ yAxisIndex: 0,
+ data: betas,
+ smooth: false,
+ symbol: "none",
+ lineStyle: { color: t.infoColor, width: 2 },
+ },
+ {
+ name: alphaLabel,
+ type: "line",
+ yAxisIndex: 1,
+ data: alphas,
+ smooth: false,
+ symbol: "none",
+ lineStyle: { color: t.warningColor, width: 1.5 },
+ },
+ ],
+ });
+
+ let resizeFrame: number | null = null;
+ const ro = new ResizeObserver(() => {
+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
+ resizeFrame = requestAnimationFrame(() => {
+ resizeFrame = null;
+ chart.resize();
+ });
+ });
+ ro.observe(ref.current!);
+ return () => {
+ ro.disconnect();
+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
+ chart.dispose();
+ };
+ }, [data, dark]);
+
+ if (data.length === 0) {
+ return <div className="text-muted-foreground text-sm p-4">{i18n.t("runDetail.attrNoFactor")}</div>;
+ }
+ return <div ref={ref} style={{ height }} />;
+}
diff --git a/frontend/src/components/charts/__tests__/AttributionTab.test.tsx b/frontend/src/components/charts/__tests__/AttributionTab.test.tsx
new file mode 100644
index 000000000..55f7af11b
--- /dev/null
+++ b/frontend/src/components/charts/__tests__/AttributionTab.test.tsx
@@ -0,0 +1,153 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { api } from "@/lib/api";
+import type { AttributionResponse, RunData } from "@/lib/api";
+import { AttributionTab } from "../AttributionTab";
+
+vi.mock("@/lib/echarts", () => ({
+ echarts: { init: vi.fn() },
+ CHART_GROUP: "quant-charts",
+ connectCharts: vi.fn(),
+}));
+
+import { echarts } from "@/lib/echarts";
+
+function makeRun(): RunData {
+ return {
+ status: "success",
+ run_id: "run-attr",
+ metrics: {
+ final_value: 1_100_000,
+ total_return: 0.1,
+ annual_return: 0.08,
+ max_drawdown: -0.05,
+ sharpe: 1.2,
+ win_rate: 0.55,
+ trade_count: 42,
+ information_ratio: 0.8,
+ tracking_error: 0.02,
+ },
+ };
+}
+
+const fullPayload: AttributionResponse = {
+ exists: true,
+ benchmark: { ticker: "SPY", mode: "explicit" },
+ factor: {
+ beta: 1.2,
+ alpha_per_period: 0.0002,
+ alpha_annualized: 0.05,
+ alpha_t_stat: 2.1,
+ r_squared: 0.85,
+ n_obs: 120,
+ rolling_window: 60,
+ rolling: [
+ { date: "2024-01-01", beta: 1.1, alpha_annualized: 0.04 },
+ { date: "2024-01-02", beta: 1.2, alpha_annualized: 0.05 },
+ ],
+ cumulative: [
+ { date: "2024-01-01", portfolio: 0.01, benchmark: 0.008, active: 0.002 },
+ { date: "2024-01-02", portfolio: 0.02, benchmark: 0.015, active: 0.005 },
+ ],
+ },
+ brinson: {
+ mode: "asset_class",
+ portfolio_return: 0.08,
+ benchmark_return: 0.06,
+ active_return: 0.02,
+ allocation: 0.01,
+ selection: 0.008,
+ interaction: 0.002,
+ sectors: [
+ {
+ sector: "Technology",
+ portfolio_weight: 0.5,
+ benchmark_weight: 0.4,
+ portfolio_return: 0.1,
+ benchmark_return: 0.08,
+ allocation: 0.005,
+ selection: 0.004,
+ interaction: 0.001,
+ total: 0.01,
+ },
+ ],
+ },
+ notes: [],
+};
+
+describe("AttributionTab", () => {
+ beforeEach(() => {
+ vi.mocked(echarts.init).mockImplementation((() => ({
+ setOption: vi.fn(),
+ resize: vi.fn(),
+ dispose: vi.fn(),
+ group: "",
+ })) as unknown as typeof echarts.init);
+ });
+
+ it("shows a loading state while the attribution payload is fetched", () => {
+ vi.spyOn(api, "getRunAttribution").mockReturnValue(new Promise<AttributionResponse>(() => {}));
+
+ render(<AttributionTab runId="run-attr" run={makeRun()} />);
+
+ expect(screen.getByText("Loading attribution…")).toBeInTheDocument();
+ });
+
+ it("shows an error state when the request fails", async () => {
+ vi.spyOn(api, "getRunAttribution").mockRejectedValue(new Error("boom"));
+
+ render(<AttributionTab runId="run-attr" run={makeRun()} />);
+
+ expect(await screen.findByText("Failed to load attribution.")).toBeInTheDocument();
+ expect(screen.getByText("boom")).toBeInTheDocument();
+ });
+
+ it("shows the empty note when the response has no attribution", async () => {
+ vi.spyOn(api, "getRunAttribution").mockResolvedValue({
+ exists: false,
+ benchmark: null,
+ factor: null,
+ brinson: null,
+ notes: ["equity.csv missing"],
+ });
+
+ render(<AttributionTab runId="run-attr" run={makeRun()} />);
+
+ expect(
+ await screen.findByText("No attribution data is available for this run."),
+ ).toBeInTheDocument();
+ });
+
+ it("renders the Brinson table and factor stat cards for a full payload", async () => {
+ vi.spyOn(api, "getRunAttribution").mockResolvedValue(fullPayload);
+
+ render(<AttributionTab runId="run-attr" run={makeRun()} />);
+
+ expect(await screen.findByText("Technology")).toBeInTheDocument();
+ expect(screen.getByText("Brinson Attribution")).toBeInTheDocument();
+ expect(screen.getByText("1.20")).toBeInTheDocument(); // beta
+ expect(screen.getByText("+5.00%")).toBeInTheDocument(); // annualized alpha
+ });
+
+ it("shows the benchmark caption for an explicit benchmark", async () => {
+ vi.spyOn(api, "getRunAttribution").mockResolvedValue(fullPayload);
+
+ render(<AttributionTab runId="run-attr" run={makeRun()} />);
+
+ expect(await screen.findByText(/Benchmark: SPY/)).toBeInTheDocument();
+ });
+
+ it("shows the factor empty note when only Brinson attribution exists", async () => {
+ vi.spyOn(api, "getRunAttribution").mockResolvedValue({
+ ...fullPayload,
+ factor: null,
+ });
+
+ render(<AttributionTab runId="run-attr" run={makeRun()} />);
+
+ expect(
+ await screen.findByText("Factor attribution is not available for this run."),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Technology")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/components/charts/__tests__/FactorResearchPanel.test.tsx b/frontend/src/components/charts/__tests__/FactorResearchPanel.test.tsx
index 65b0d7d84..9be5414b9 100644
--- a/frontend/src/components/charts/__tests__/FactorResearchPanel.test.tsx
+++ b/frontend/src/components/charts/__tests__/FactorResearchPanel.test.tsx
@@ -124,3 +124,12 @@ describe("FactorResearchPanel", () => {
expect(screen.getByText("No factor analysis results are available for this run.")).toBeInTheDocument();
});
});
+
+describe("FactorResearchPanel circular-import safety", () => {
+ it("loads standalone via dynamic import without importing RunDetail first", async () => {
+ // RunCardPanel/RunCardStat now live in components/run/RunCard, so this module
+ // no longer imports pages/RunDetail (which imports this module back).
+ const mod = await import("@/components/charts/FactorResearchPanel");
+ expect(mod.FactorResearchPanel).toBeTypeOf("function");
+ });
+});
diff --git a/frontend/src/components/run/PositionsTab.tsx b/frontend/src/components/run/PositionsTab.tsx
index 617ed7566..cdebc6164 100644
--- a/frontend/src/components/run/PositionsTab.tsx
+++ b/frontend/src/components/run/PositionsTab.tsx
@@ -1,12 +1,11 @@
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useMemo, useRef, useState } from "react";
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Loader2 } from "lucide-react";
-import type { EChartsCoreOption } from "echarts/core";
import { fetchRunSectorMap, type RunData, type SectorMapResponse } from "@/lib/api";
import { getChartTheme } from "@/lib/chart-theme";
-import { echarts } from "@/lib/echarts";
-import { useThemeDark } from "@/lib/theme-store";
+import { escapeHtml } from "@/lib/escapeHtml";
+import { useChartLifecycle } from "@/hooks/useChartLifecycle";
import { cn } from "@/lib/utils";
import {
CASH_SYMBOL,
@@ -100,7 +99,13 @@ export function PositionsTab({ run }: { run: RunData }) {
);
const latestDate = useMemo(() => latestHoldingDate(panel), [panel]);
const hasAShare = useMemo(
- () => panel.symbols.some((symbol) => classifyAssetClass(symbol) === "a_share"),
+ () => panel.symbols.some((symbol) => {
+ const assetClass = classifyAssetClass(symbol);
+ // The backend sector-map `_detect_market` defaults UNKNOWN symbols to
+ // a_share, so symbols the frontend classifier buckets as "other" are
+ // still resolvable — include them in the gate.
+ return assetClass === "a_share" || assetClass === "other";
+ }),
[panel.symbols],
);
@@ -349,35 +354,6 @@ function PositionsPanelCard({
);
}
-function useChartLifecycle(
- ref: React.RefObject<HTMLDivElement | null>,
- buildOption: () => EChartsCoreOption,
- deps: unknown[],
-) {
- const dark = useThemeDark();
- useEffect(() => {
- if (!ref.current) return;
- const chart = echarts.init(ref.current);
- chart.setOption(buildOption());
-
- let resizeFrame: number | null = null;
- const ro = new ResizeObserver(() => {
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- resizeFrame = requestAnimationFrame(() => {
- resizeFrame = null;
- chart.resize();
- });
- });
- ro.observe(ref.current);
- return () => {
- ro.disconnect();
- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
- chart.dispose();
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [...deps, dark]);
-}
-
function WeightDistributionChart({
items,
mode,
@@ -416,7 +392,7 @@ function WeightDistributionChart({
const p = params as { name: string; value: number; data?: { assetClassLabel?: string; weight?: number } };
const label = p.data?.assetClassLabel ?? "";
const signed = p.data?.weight ?? p.value;
- return `<b>${p.name}</b><br/>${label}: <b>${formatPercent(signed, 2)}</b>`;
+ return `<b>${escapeHtml(p.name)}</b><br/>${label}: <b>${formatPercent(signed, 2)}</b>`;
},
};
@@ -499,7 +475,7 @@ function SectorDistributionChart({ items, cashLabel }: { items: GroupedItem[]; c
const list = params as Array<{ name: string; value: number }>;
if (!Array.isArray(list) || list.length === 0) return "";
const p = list[0];
- return `<b>${p.name}</b>: <b>${formatPercent(p.value, 2)}</b>`;
+ return `<b>${escapeHtml(p.name)}</b>: <b>${formatPercent(p.value, 2)}</b>`;
},
},
grid: { left: 8, right: 40, top: 8, bottom: 8, containLabel: true },
@@ -572,9 +548,9 @@ function WeightEvolutionChart({ dates, series }: { dates: string[]; series: Evol
if (!Array.isArray(list) || list.length === 0) return "";
const rows = [...list]
.sort((a, b) => b.value - a.value)
- .map((p) => `${p.marker} ${p.seriesName}: <b>${formatPercent(p.value, 2)}</b>`)
+ .map((p) => `${p.marker} ${escapeHtml(p.seriesName)}: <b>${formatPercent(p.value, 2)}</b>`)
.join("<br/>");
- return `<b>${list[0] && (list[0] as { axisValue?: string }).axisValue}</b><br/>${rows}`;
+ return `<b>${escapeHtml(String((list[0] as { axisValue?: string }).axisValue ?? ""))}</b><br/>${rows}`;
},
},
legend: {
diff --git a/frontend/src/components/run/RunCard.tsx b/frontend/src/components/run/RunCard.tsx
new file mode 100644
index 000000000..f66c529d6
--- /dev/null
+++ b/frontend/src/components/run/RunCard.tsx
@@ -0,0 +1,36 @@
+import type { ReactNode } from "react";
+import type { LucideIcon } from "lucide-react";
+import { cn } from "@/lib/utils";
+
+/**
+ * Shared Run-Card building blocks. Extracted from pages/RunDetail.tsx so that
+ * FactorResearchPanel can reuse them without importing the page module (which
+ * imports FactorResearchPanel back, creating a circular import).
+ */
+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>
+ <div className={cn("mt-1 truncate text-sm font-medium", tone === "warning" ? "text-warning" : "")}>{value}</div>
+ </div>
+ );
+}
+
+export function RunCardPanel({ title, icon: Icon, children }: { title: string; icon: LucideIcon; 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">
+ <Icon className="h-4 w-4 text-muted-foreground" />
+ {title}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+export function formatRunCardValue(value: unknown): string {
+ if (Array.isArray(value)) return value.join(", ");
+ if (typeof value === "number") return Number.isInteger(value) ? String(value) : value.toFixed(4);
+ if (typeof value === "object" && value !== null) return JSON.stringify(value);
+ return String(value ?? "");
+}
diff --git a/frontend/src/components/run/__tests__/PositionsTab.test.tsx b/frontend/src/components/run/__tests__/PositionsTab.test.tsx
index 397355ef4..a07697fab 100644
--- a/frontend/src/components/run/__tests__/PositionsTab.test.tsx
+++ b/frontend/src/components/run/__tests__/PositionsTab.test.tsx
@@ -180,6 +180,19 @@ describe("PositionsTab", () => {
expect(screen.queryByText("Resolve industries")).not.toBeInTheDocument();
});
+ it("shows the resolve button for a symbol the frontend classifier cannot place", () => {
+ // "BTCUSDT" has no exchange suffix / quote pair the frontend recognises, so
+ // it classifies as "other"; the backend defaults unknowns to a_share, so the
+ // button must still be offered.
+ const unknownRows = [
+ { timestamp: "2024-01-01", BTCUSDT: "0.6" },
+ { timestamp: "2024-01-02", BTCUSDT: "0.5" },
+ ];
+ render(<PositionsTab run={makeRun(unknownRows)} />);
+
+ expect(screen.getByRole("button", { name: "Resolve industries" })).toBeInTheDocument();
+ });
+
it("shows the empty-state note and no charts for an all-zero payload", () => {
const zeroRows = [
{ timestamp: "2024-01-01", "159913.SZ": "0.0" },
diff --git a/frontend/src/hooks/useChartLifecycle.ts b/frontend/src/hooks/useChartLifecycle.ts
new file mode 100644
index 000000000..d8d0cda70
--- /dev/null
+++ b/frontend/src/hooks/useChartLifecycle.ts
@@ -0,0 +1,47 @@
+import { useEffect } from "react";
+import type { RefObject } from "react";
+import type { EChartsCoreOption } from "echarts/core";
+import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";
+import { useThemeDark } from "@/lib/theme-store";
+
+/**
+ * Shared ECharts lifecycle: init on mount, rebuild the option whenever `deps`
+ * (or the dark theme) change, keep the canvas sized with a ResizeObserver +
+ * requestAnimationFrame, and dispose on teardown. Instances join CHART_GROUP
+ * so axis pointers stay connected across the charts rendered together.
+ *
+ * `deps` are the data props the built option depends on; `buildOption` itself
+ * is re-evaluated from the current closure on every effect run, so callers pass
+ * the same dependency list they would have given the inline effect (minus the
+ * manual dark handling this hook already provides).
+ */
+export function useChartLifecycle(
+ ref: RefObject<HTMLDivElement | null>,
+ buildOption: () => EChartsCoreOption,
+ deps: readonly unknown[],
+): void {
+ const dark = useThemeDark();
+ useEffect(() => {
+ if (!ref.current) return;
+ const chart = echarts.init(ref.current);
+ chart.group = CHART_GROUP;
+ connectCharts();
+ chart.setOption(buildOption());
+
+ let resizeFrame: number | null = null;
+ const ro = new ResizeObserver(() => {
+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
+ resizeFrame = requestAnimationFrame(() => {
+ resizeFrame = null;
+ chart.resize();
+ });
+ });
+ ro.observe(ref.current);
+ return () => {
+ ro.disconnect();
+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);
+ chart.dispose();
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [...deps, dark]);
+}
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index a9cf6c59f..888f1618d 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -668,7 +668,41 @@
"forex": "عملات أجنبية",
"other": "أخرى"
}
- }
+ },
+ "attribution": "تحليل الإسناد",
+ "attrBenchmark": "المؤشر المرجعي",
+ "attrPortfolio": "المحفظة",
+ "attrActive": "النشط",
+ "attrAutoEqualWeight": "أوزان متساوية تلقائيًا",
+ "attrNoBenchmark": "لم يتم تكوين مؤشر مرجعي",
+ "attrModeSymbol": "وضع Brinson: حسب الرمز",
+ "attrModeAssetClass": "وضع Brinson: حسب فئة الأصول",
+ "attrModeInvestedCash": "وضع Brinson: مقابل النقد المستثمر",
+ "attrSector": "القطاع",
+ "attrPortfolioWeight": "وزن المحفظة",
+ "attrBenchmarkWeight": "وزن المؤشر",
+ "attrPortfolioReturn": "عائد المحفظة",
+ "attrBenchmarkReturn": "عائد المؤشر",
+ "attrAllocation": "التخصيص",
+ "attrSelection": "الاختيار",
+ "attrInteraction": "التفاعل",
+ "attrTotal": "الإجمالي",
+ "attrBrinsonTitle": "إسناد Brinson",
+ "attrWaterfallTitle": "شلال العوائد",
+ "attrNoBrinson": "إسناد Brinson غير متاح لهذا التشغيل.",
+ "attrAlpha": "ألفا (سنوي)",
+ "attrBeta": "بيتا",
+ "attrTStat": "قيمة t: {{value}}",
+ "attrRSquared": "R²",
+ "attrInformationRatio": "نسبة المعلومات",
+ "attrTrackingError": "خطأ التتبع",
+ "attrNoFactor": "إسناد العوامل غير متاح لهذا التشغيل.",
+ "attrRollingTitle": "بيتا وألفا المتحركة",
+ "attrRollingWindow": "نافذة متحركة {{count}} فترة",
+ "attrCumulativeTitle": "العوائد التراكمية",
+ "attrLoading": "جارٍ تحميل الإسناد…",
+ "attrError": "فشل تحميل الإسناد.",
+ "attrNoData": "لا تتوفر بيانات إسناد لهذا التشغيل."
},
"compare": {
"title": "مقارنة الاستراتيجيات",
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 4c6a66a29..1b7de32d2 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -673,7 +673,41 @@
"forex": "Forex",
"other": "Other"
}
- }
+ },
+ "attribution": "Attribution",
+ "attrBenchmark": "Benchmark",
+ "attrPortfolio": "Portfolio",
+ "attrActive": "Active",
+ "attrAutoEqualWeight": "auto equal-weight",
+ "attrNoBenchmark": "No benchmark configured",
+ "attrModeSymbol": "Brinson mode: symbol",
+ "attrModeAssetClass": "Brinson mode: asset class",
+ "attrModeInvestedCash": "Brinson mode: invested cash",
+ "attrSector": "Sector",
+ "attrPortfolioWeight": "Portfolio Weight",
+ "attrBenchmarkWeight": "Benchmark Weight",
+ "attrPortfolioReturn": "Portfolio Return",
+ "attrBenchmarkReturn": "Benchmark Return",
+ "attrAllocation": "Allocation",
+ "attrSelection": "Selection",
+ "attrInteraction": "Interaction",
+ "attrTotal": "Total",
+ "attrBrinsonTitle": "Brinson Attribution",
+ "attrWaterfallTitle": "Return Waterfall",
+ "attrNoBrinson": "Brinson attribution is not available for this run.",
+ "attrAlpha": "Alpha (ann.)",
+ "attrBeta": "Beta",
+ "attrTStat": "t-stat: {{value}}",
+ "attrRSquared": "R²",
+ "attrInformationRatio": "Information Ratio",
+ "attrTrackingError": "Tracking Error",
+ "attrNoFactor": "Factor attribution is not available for this run.",
+ "attrRollingTitle": "Rolling Beta & Alpha",
+ "attrRollingWindow": "{{count}}-bar rolling window",
+ "attrCumulativeTitle": "Cumulative Returns",
+ "attrLoading": "Loading attribution…",
+ "attrError": "Failed to load attribution.",
+ "attrNoData": "No attribution data is available for this run."
},
"compare": {
"title": "Strategy Comparison",
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index 0bdb07f4e..916e0cf5a 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -673,7 +673,41 @@
"forex": "Divisas",
"other": "Otros"
}
- }
+ },
+ "attribution": "Atribución",
+ "attrBenchmark": "Índice de referencia",
+ "attrPortfolio": "Cartera",
+ "attrActive": "Activo",
+ "attrAutoEqualWeight": "ponderación equitativa automática",
+ "attrNoBenchmark": "Sin índice de referencia configurado",
+ "attrModeSymbol": "Modo Brinson: por símbolo",
+ "attrModeAssetClass": "Modo Brinson: por clase de activo",
+ "attrModeInvestedCash": "Modo Brinson: frente a caja invertida",
+ "attrSector": "Sector",
+ "attrPortfolioWeight": "Peso de la cartera",
+ "attrBenchmarkWeight": "Peso del índice",
+ "attrPortfolioReturn": "Retorno de la cartera",
+ "attrBenchmarkReturn": "Retorno del índice",
+ "attrAllocation": "Asignación",
+ "attrSelection": "Selección",
+ "attrInteraction": "Interacción",
+ "attrTotal": "Total",
+ "attrBrinsonTitle": "Atribución de Brinson",
+ "attrWaterfallTitle": "Cascada de retornos",
+ "attrNoBrinson": "La atribución de Brinson no está disponible para esta ejecución.",
+ "attrAlpha": "Alfa (anual.)",
+ "attrBeta": "Beta",
+ "attrTStat": "t-estadístico: {{value}}",
+ "attrRSquared": "R²",
+ "attrInformationRatio": "Ratio de información",
+ "attrTrackingError": "Error de seguimiento",
+ "attrNoFactor": "La atribución por factores no está disponible para esta ejecución.",
+ "attrRollingTitle": "Beta y alfa móviles",
+ "attrRollingWindow": "Ventana móvil de {{count}} barras",
+ "attrCumulativeTitle": "Retornos acumulados",
+ "attrLoading": "Cargando atribución…",
+ "attrError": "Error al cargar la atribución.",
+ "attrNoData": "No hay datos de atribución disponibles para esta ejecución."
},
"compare": {
"title": "Comparación de estrategias",
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index 33a9fbbb5..dcba2c0fe 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -668,7 +668,41 @@
"forex": "外国為替",
"other": "その他"
}
- }
+ },
+ "attribution": "アトリビューション",
+ "attrBenchmark": "ベンチマーク",
+ "attrPortfolio": "ポートフォリオ",
+ "attrActive": "アクティブ",
+ "attrAutoEqualWeight": "自動等ウェイト",
+ "attrNoBenchmark": "ベンチマーク未設定",
+ "attrModeSymbol": "Brinson モード:銘柄別",
+ "attrModeAssetClass": "Brinson モード:資産クラス別",
+ "attrModeInvestedCash": "Brinson モード:投資現金基準",
+ "attrSector": "セクター",
+ "attrPortfolioWeight": "ポートフォリオ・ウェイト",
+ "attrBenchmarkWeight": "ベンチマーク・ウェイト",
+ "attrPortfolioReturn": "ポートフォリオ収益",
+ "attrBenchmarkReturn": "ベンチマーク収益",
+ "attrAllocation": "配分効果",
+ "attrSelection": "選択効果",
+ "attrInteraction": "交互効果",
+ "attrTotal": "合計",
+ "attrBrinsonTitle": "Brinson アトリビューション",
+ "attrWaterfallTitle": "収益ウォーターフォール",
+ "attrNoBrinson": "この実行には Brinson アトリビューションがありません。",
+ "attrAlpha": "アルファ(年率)",
+ "attrBeta": "ベータ",
+ "attrTStat": "t値: {{value}}",
+ "attrRSquared": "R²",
+ "attrInformationRatio": "情報比率",
+ "attrTrackingError": "トラッキングエラー",
+ "attrNoFactor": "この実行にはファクター・アトリビューションがありません。",
+ "attrRollingTitle": "ローリング Beta と Alpha",
+ "attrRollingWindow": "{{count}} 期間ローリングウィンドウ",
+ "attrCumulativeTitle": "累積収益",
+ "attrLoading": "アトリビューションを読み込み中…",
+ "attrError": "アトリビューションの読み込みに失敗しました。",
+ "attrNoData": "この実行にはアトリビューションデータがありません。"
},
"compare": {
"title": "戦略比較",
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 22e05fa2f..20c551b41 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -668,7 +668,41 @@
"forex": "외환",
"other": "기타"
}
- }
+ },
+ "attribution": "귀인 분석",
+ "attrBenchmark": "벤치마크",
+ "attrPortfolio": "포트폴리오",
+ "attrActive": "액티브",
+ "attrAutoEqualWeight": "자동 동일가중",
+ "attrNoBenchmark": "벤치마크 미설정",
+ "attrModeSymbol": "Brinson 모드: 종목별",
+ "attrModeAssetClass": "Brinson 모드: 자산군별",
+ "attrModeInvestedCash": "Brinson 모드: 투자 현금 기준",
+ "attrSector": "섹터",
+ "attrPortfolioWeight": "포트폴리오 비중",
+ "attrBenchmarkWeight": "벤치마크 비중",
+ "attrPortfolioReturn": "포트폴리오 수익률",
+ "attrBenchmarkReturn": "벤치마크 수익률",
+ "attrAllocation": "배분 효과",
+ "attrSelection": "선택 효과",
+ "attrInteraction": "상호작용 효과",
+ "attrTotal": "합계",
+ "attrBrinsonTitle": "Brinson 귀인",
+ "attrWaterfallTitle": "수익 워터폴",
+ "attrNoBrinson": "이 실행에는 Brinson 귀인 데이터가 없습니다.",
+ "attrAlpha": "알파(연율)",
+ "attrBeta": "베타",
+ "attrTStat": "t-통계량: {{value}}",
+ "attrRSquared": "R²",
+ "attrInformationRatio": "정보비율",
+ "attrTrackingError": "추적 오차",
+ "attrNoFactor": "이 실행에는 팩터 귀인 데이터가 없습니다.",
+ "attrRollingTitle": "롤링 Beta와 Alpha",
+ "attrRollingWindow": "{{count}}기간 롤링 윈도우",
+ "attrCumulativeTitle": "누적 수익률",
+ "attrLoading": "귀인 데이터 로드 중…",
+ "attrError": "귀인 데이터를 로드하지 못했습니다.",
+ "attrNoData": "이 실행에는 귀인 데이터가 없습니다."
},
"compare": {
"title": "전략 비교",
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index 84fc6f761..605fdf57c 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -668,7 +668,41 @@
"forex": "外汇",
"other": "其他"
}
- }
+ },
+ "attribution": "归因分析",
+ "attrBenchmark": "基准",
+ "attrPortfolio": "组合",
+ "attrActive": "超额",
+ "attrAutoEqualWeight": "自动等权",
+ "attrNoBenchmark": "未配置基准",
+ "attrModeSymbol": "Brinson 模式:按标的",
+ "attrModeAssetClass": "Brinson 模式:按资产类别",
+ "attrModeInvestedCash": "Brinson 模式:按已投资现金",
+ "attrSector": "板块",
+ "attrPortfolioWeight": "组合权重",
+ "attrBenchmarkWeight": "基准权重",
+ "attrPortfolioReturn": "组合收益",
+ "attrBenchmarkReturn": "基准收益",
+ "attrAllocation": "配置效应",
+ "attrSelection": "选择效应",
+ "attrInteraction": "交互效应",
+ "attrTotal": "合计",
+ "attrBrinsonTitle": "Brinson 归因",
+ "attrWaterfallTitle": "收益瀑布图",
+ "attrNoBrinson": "本次运行无 Brinson 归因数据。",
+ "attrAlpha": "年化 Alpha",
+ "attrBeta": "Beta",
+ "attrTStat": "t 统计量:{{value}}",
+ "attrRSquared": "R²",
+ "attrInformationRatio": "信息比率",
+ "attrTrackingError": "跟踪误差",
+ "attrNoFactor": "本次运行无因子归因数据。",
+ "attrRollingTitle": "滚动 Beta 与 Alpha",
+ "attrRollingWindow": "{{count}} 期滚动窗口",
+ "attrCumulativeTitle": "累计收益",
+ "attrLoading": "加载归因数据…",
+ "attrError": "加载归因数据失败。",
+ "attrNoData": "本次运行无归因数据。"
},
"compare": {
"title": "策略对比",
diff --git a/frontend/src/lib/__tests__/escapeHtml.test.ts b/frontend/src/lib/__tests__/escapeHtml.test.ts
new file mode 100644
index 000000000..8d903a423
--- /dev/null
+++ b/frontend/src/lib/__tests__/escapeHtml.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+import { escapeHtml } from "../escapeHtml";
+
+describe("escapeHtml", () => {
+ it("escapes ampersand", () => {
+ expect(escapeHtml("a & b")).toBe("a &amp; b");
+ });
+
+ it("escapes less-than", () => {
+ expect(escapeHtml("a < b")).toBe("a &lt; b");
+ });
+
+ it("escapes greater-than", () => {
+ expect(escapeHtml("a > b")).toBe("a &gt; b");
+ });
+
+ it("escapes double quote", () => {
+ expect(escapeHtml('a " b')).toBe("a &quot; b");
+ });
+
+ it("escapes single quote", () => {
+ expect(escapeHtml("a ' b")).toBe("a &#39; b");
+ });
+
+ it("escapes all five characters in one pass without double-escaping", () => {
+ expect(escapeHtml(`<img src="x" onerror='alert(&)'>`)).toBe(
+ "&lt;img src=&quot;x&quot; onerror=&#39;alert(&amp;)&#39;&gt;",
+ );
+ });
+
+ it("passes already-safe strings through unchanged", () => {
+ expect(escapeHtml("plain text 123")).toBe("plain text 123");
+ expect(escapeHtml("2024-01-02")).toBe("2024-01-02");
+ expect(escapeHtml("600519.SH")).toBe("600519.SH");
+ expect(escapeHtml("")).toBe("");
+ });
+});
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index f66d6c3f9..5783ca4b6 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -147,6 +147,7 @@ export const api = {
},
getRunCode: (id: string) => request<Record<string, string>>(`/runs/${id}/code`),
getRunFactor: (id: string) => request<FactorReportPayload>(`/runs/${id}/factor`),
+ getRunAttribution: (id: string) => request<AttributionResponse>(`/runs/${encodeURIComponent(id)}/attribution`),
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 || "" }) }),
@@ -643,6 +644,70 @@ export interface FactorReportPayload {
ic_correlation: { labels: string[]; matrix: number[][] } | null;
}
+// --- Attribution types (GET /runs/{runId}/attribution) ---
+
+export interface AttributionBenchmarkInfo {
+ ticker: string | null;
+ mode: "auto_equal_weight" | "explicit";
+}
+
+export interface AttributionRollingPoint {
+ date: string;
+ beta: number;
+ alpha_annualized: number;
+}
+
+export interface AttributionCumulativePoint {
+ date: string;
+ portfolio: number;
+ benchmark: number;
+ /** Portfolio-minus-benchmark cumulative return; plotted as the active line. */
+ active: number;
+}
+
+export interface AttributionFactor {
+ beta: number;
+ alpha_per_period: number;
+ alpha_annualized: number;
+ alpha_t_stat: number;
+ r_squared: number;
+ n_obs: number;
+ rolling_window: number;
+ rolling: AttributionRollingPoint[] | null;
+ cumulative: AttributionCumulativePoint[];
+}
+
+export interface AttributionSectorEntry {
+ sector: string;
+ portfolio_weight: number;
+ benchmark_weight: number;
+ portfolio_return: number;
+ benchmark_return: number;
+ allocation: number;
+ selection: number;
+ interaction: number;
+ total: number;
+}
+
+export interface AttributionBrinson {
+ mode: "symbol" | "asset_class" | "invested_cash";
+ portfolio_return: number;
+ benchmark_return: number;
+ active_return: number;
+ allocation: number;
+ selection: number;
+ interaction: number;
+ sectors: AttributionSectorEntry[];
+}
+
+export interface AttributionResponse {
+ exists: boolean;
+ benchmark: AttributionBenchmarkInfo | null;
+ factor: AttributionFactor | null;
+ brinson: AttributionBrinson | null;
+ notes: string[];
+}
+
export interface RunData {
status: string;
run_id: string;
diff --git a/frontend/src/lib/escapeHtml.ts b/frontend/src/lib/escapeHtml.ts
new file mode 100644
index 000000000..561c8eaa6
--- /dev/null
+++ b/frontend/src/lib/escapeHtml.ts
@@ -0,0 +1,23 @@
+/**
+ * Escape a string for safe interpolation into an HTML context.
+ *
+ * ECharts injects the string returned by a custom tooltip `formatter` via
+ * `innerHTML` WITHOUT escaping (the default tooltip renderer escapes via
+ * `encodeHTML`, but custom formatter return values are injected verbatim).
+ * Artifact-derived strings — positions.csv column headers, date cells, factor
+ * directory names, equity timestamps — are attacker-influenceable via crafted
+ * run directories, and the API key lives in localStorage, so an XSS in a chart
+ * tooltip escalates to full API control. Every such value interpolated into a
+ * tooltip/label formatter must pass through this helper first.
+ *
+ * `&` MUST be replaced first, otherwise the entities introduced by the later
+ * replacements would be double-escaped.
+ */
+export function escapeHtml(value: string): string {
+ return value
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;")
+ .replace(/'/g, "&#39;");
+}
diff --git a/frontend/src/lib/positions.ts b/frontend/src/lib/positions.ts
index 7112f14a3..1cbc9a013 100644
--- a/frontend/src/lib/positions.ts
+++ b/frontend/src/lib/positions.ts
@@ -25,6 +25,15 @@ export const CASH_SYMBOL = "__cash__";
const DATE_COLUMNS = new Set(["timestamp", "date", "time"]);
+/**
+ * True when a positions.csv column key is a date/time column rather than a
+ * symbol weight column. Shared by the parser and the RunDetail `hasPositions`
+ * gate so both treat timestamp/date/time identically.
+ */
+export function isDateColumn(key: string): boolean {
+ return DATE_COLUMNS.has(key.toLowerCase());
+}
+
const EQUITY_SUFFIX_MAP: Record<string, AssetClass> = {
SH: "a_share",
SZ: "a_share",
@@ -62,7 +71,7 @@ export function parsePositionsPanel(rows: Array<Record<string, string>>): Positi
for (const row of rows) {
let date = "";
for (const [key, value] of Object.entries(row)) {
- if (DATE_COLUMNS.has(key.toLowerCase())) {
+ if (isDateColumn(key)) {
date = value ?? "";
break;
}
@@ -71,7 +80,7 @@ export function parsePositionsPanel(rows: Array<Record<string, string>>): Positi
if (!weightByDate.has(date)) dates.push(date);
const weights: Record<string, number> = weightByDate.get(date) ?? {};
for (const [key, raw] of Object.entries(row)) {
- if (DATE_COLUMNS.has(key.toLowerCase())) continue;
+ if (isDateColumn(key)) continue;
if (!seenSymbols.has(key)) {
seenSymbols.add(key);
symbols.push(key);
diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsx
index 1e332223b..4da56c830 100644
--- a/frontend/src/pages/RunDetail.tsx
+++ b/frontend/src/pages/RunDetail.tsx
@@ -1,11 +1,11 @@
import i18n from '@/i18n';
import { useEffect, useMemo, useRef, useState } from "react";
-import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { useParams, useNavigate, useSearchParams } from "react-router";
import {
AlertTriangle,
ArrowLeft,
+ ArrowLeftRight,
BarChart3,
CalendarRange,
CheckCircle2,
@@ -48,11 +48,14 @@ import { Skeleton, SkeletonMetrics, SkeletonChart } from "@/components/common/Sk
import { ErrorBoundary } from "@/components/common/ErrorBoundary";
import { getStrategyReportIdentity, StrategyResearchDashboard } from "@/components/charts/StrategyResearchDashboard";
import { FactorResearchPanel } from "@/components/charts/FactorResearchPanel";
+import { AttributionTab } from "@/components/charts/AttributionTab";
import { PositionsTab } from "@/components/run/PositionsTab";
+import { RunCardPanel, RunCardStat, formatRunCardValue } from "@/components/run/RunCard";
+import { isDateColumn } from "@/lib/positions";
const rehypePlugins = [rehypeHighlight];
-type Tab = "dashboard" | "chart" | "tearsheet" | "trades" | "positions" | "runCard" | "code" | "validation" | "studio" | "factor";
+type Tab = "dashboard" | "chart" | "tearsheet" | "trades" | "positions" | "attribution" | "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 };
@@ -138,8 +141,9 @@ export function RunDetail() {
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 hasAttribution = (run?.artifacts_equity_csv?.length ?? 0) > 0;
const hasPositions = !!run?.artifacts_positions_csv?.some(
- (row) => Object.keys(row).some((key) => key.toLowerCase() !== "timestamp" && key.toLowerCase() !== "date"),
+ (row) => Object.keys(row).some((key) => !isDateColumn(key)),
);
const TABS: { id: Tab; label: string; icon: typeof BarChart3; hidden?: boolean }[] = [
{ id: "dashboard", label: i18n.t("runDetail.dashboard"), icon: LayoutDashboard },
@@ -147,6 +151,7 @@ export function RunDetail() {
{ id: "tearsheet", label: i18n.t("runDetail.tearsheet"), icon: CalendarRange, hidden: !hasTearsheet },
{ id: "trades", label: i18n.t("runDetail.trades"), icon: List },
{ id: "positions", label: i18n.t("runDetail.positions.tab"), icon: PieChart, hidden: !hasPositions },
+ { id: "attribution", label: i18n.t("runDetail.attribution"), icon: ArrowLeftRight, hidden: !hasAttribution },
{ 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 },
@@ -419,6 +424,7 @@ export function RunDetail() {
{tab === "tearsheet" && hasTearsheet && <TearsheetTab run={run} />}
{tab === "trades" && <TradesTab run={run} />}
{tab === "positions" && hasPositions && <PositionsTab run={run} />}
+ {tab === "attribution" && hasAttribution && runId && <AttributionTab runId={runId} run={run} />}
{tab === "factor" && run.has_factor_artifacts && runId && <FactorTab runId={runId} />}
{tab === "validation" && run.validation && <ValidationPanel data={run.validation} />}
{tab === "studio" && hasStudio && (
@@ -619,12 +625,15 @@ function TearsheetTab({ run }: { run: RunData }) {
const lastTime = equityPoints.length > 0 ? equityPoints[equityPoints.length - 1].time : "";
return toDrawdownZones(drawdowns, lastTime);
}, [drawdowns, equityPoints]);
+ const chartData = useMemo<EquityPoint[]>(
+ () => equityPoints.map((p) => ({ time: p.time, equity: p.equity, drawdown: p.drawdown })),
+ [equityPoints],
+ );
if (equityPoints.length < 2) {
return <div className="p-8 text-muted-foreground text-sm">{i18n.t("runDetail.noTearsheetData")}</div>;
}
- const chartData: EquityPoint[] = equityPoints.map((p) => ({ time: p.time, equity: p.equity, drawdown: p.drawdown }));
const yearCount = new Set(monthly.map((m) => m.year)).size;
const heatmapHeight = Math.min(420, Math.max(200, 40 + 34 * yearCount));
@@ -705,27 +714,6 @@ function FactorTab({ runId }: { runId: string }) {
);
}
-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>
- <div className={cn("mt-1 truncate text-sm font-medium", tone === "warning" ? "text-warning" : "")}>{value}</div>
- </div>
- );
-}
-
-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">
- <Icon className="h-4 w-4 text-muted-foreground" />
- {title}
- </div>
- {children}
- </section>
- );
-}
-
function KeyValueTable({ data, empty, monospaceValues = false }: { data: Record<string, unknown>; empty: string; monospaceValues?: boolean }) {
const entries = Object.entries(data).filter(([, value]) => value !== undefined && value !== null && value !== "");
if (entries.length === 0) {
@@ -753,13 +741,6 @@ function hasStructuredValidation(value: unknown): boolean {
return Boolean(v.monte_carlo || v.bootstrap || v.walk_forward);
}
-function formatRunCardValue(value: unknown): string {
- if (Array.isArray(value)) return value.join(", ");
- if (typeof value === "number") return Number.isInteger(value) ? String(value) : value.toFixed(4);
- if (typeof value === "object" && value !== null) return JSON.stringify(value);
- return String(value ?? "");
-}
-
function formatBytes(value: number): string {
if (!Number.isFinite(value)) return "-";
if (value < 1024) return `${value} B`;