Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(attribution): keep benchmark returns aligned

Wu Shuwen887d4114eeba
diff --git a/agent/src/api/attribution_core.py b/agent/src/api/attribution_core.py
index 68fe5982b..e37ff9380 100644
--- a/agent/src/api/attribution_core.py
+++ b/agent/src/api/attribution_core.py
@@ -193,11 +193,13 @@ def _attribution_load_equity(
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
+ # Keep one entry per equity row. Dropping only an invalid portfolio
+ # return would make adjacent benchmark equity values span a longer
+ # interval, then pair that multi-bar benchmark return with one bar of
+ # portfolio return below.
dates.append(str(row.get("timestamp") or ""))
- portfolio_returns.append(ret)
+ ret = _attribution_finite_float(row.get("ret"))
+ portfolio_returns.append(ret if ret is not None else float("nan"))
if has_benchmark_column:
benchmark_value = _attribution_finite_float(row.get("benchmark_equity"))
if benchmark_value is not None:
@@ -206,7 +208,7 @@ def _attribution_load_equity(
else:
benchmark_equity.append(float("nan"))
- if not portfolio_returns:
+ if not any(math.isfinite(value) for value in portfolio_returns):
return None, None, None, "missing"
if not has_benchmark_column or benchmark_all_blank:
diff --git a/agent/tests/test_attribution_api.py b/agent/tests/test_attribution_api.py
index 57851c651..322371707 100644
--- a/agent/tests/test_attribution_api.py
+++ b/agent/tests/test_attribution_api.py
@@ -422,3 +422,29 @@ def test_attribution_artifact_symbol_path_traversal_is_contained(
assert brinson["mode"] == "symbol"
sectors = {sector["sector"]: sector for sector in brinson["sectors"]}
assert set(sectors) == {SYMBOL_A, "Cash"}
+
+
+def test_attribution_skips_invalid_portfolio_rows_without_shifting_benchmark_returns(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ client = _client(tmp_path, monkeypatch)
+ run_dir = tmp_path / "runs" / "attr-invalid-return"
+ rng = np.random.default_rng(23)
+ benchmark = rng.normal(0.0005, 0.01, N_BARS)
+ benchmark[0] = 0.0
+ portfolio = 0.001 + 1.2 * benchmark
+ portfolio[5] = np.nan
+ 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-invalid-return/attribution")
+
+ assert response.status_code == 200
+ factor = response.json()["factor"]
+ assert factor is not None
+ assert factor["n_obs"] == N_BARS - 1
+ assert factor["beta"] == pytest.approx(1.2, abs=1e-8)
+ assert factor["alpha_per_period"] == pytest.approx(0.001, abs=1e-8)