Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(backtest): rebalance notes artifact + metrics (Portfolio Studio slice)

Yufeng Hea6a57b256279
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index a7bab9d70..512e4e98a 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -578,6 +578,22 @@ class BaseEngine(ABC):
m["by_symbol"] = by_symbol_stats(self.trades)
m["by_exit_reason"] = by_exit_reason_stats(self.trades)
+ # Portfolio Studio: per-rebalance weight-drift notes from the target
+ # positions. Optimizer-agnostic, so they land for the baseline too.
+ from backtest.rebalance_notes import (
+ compute_rebalance_notes,
+ render_rebalance_notes_markdown,
+ write_rebalance_notes,
+ )
+ rebalance_notes = compute_rebalance_notes(target_pos)
+ write_rebalance_notes(run_dir / "artifacts" / "rebalance_notes.json", rebalance_notes)
+ (run_dir / "artifacts" / "rebalance_notes.md").write_text(
+ render_rebalance_notes_markdown(rebalance_notes), encoding="utf-8"
+ )
+ m["rebalance_count"] = rebalance_notes["summary"]["rebalance_count"]
+ m["rebalance_turnover_mean"] = rebalance_notes["summary"]["turnover_mean"]
+ m["rebalance_turnover_max"] = rebalance_notes["summary"]["turnover_max"]
+
# 7. Validation (optional — triggered by config["validation"])
if config.get("validation"):
from backtest.validation import run_validation, write_validation_json
diff --git a/agent/backtest/rebalance_notes.py b/agent/backtest/rebalance_notes.py
new file mode 100644
index 000000000..972e235ca
--- /dev/null
+++ b/agent/backtest/rebalance_notes.py
@@ -0,0 +1,158 @@
+"""Rebalance notes: per-rebalance turnover and weight-drift detail.
+
+The Portfolio Studio epic (#456) asks for per-rebalance reporting as the
+last backend slice, alongside the shipped turnover-aware optimizer and the
+risk x-ray. The notes here are computed from the target position frame, so
+they work for every optimizer and for the no-optimizer baseline: a rebalance
+is any decision date whose target weight vector moved past ``epsilon`` from
+the previous one. Trade-derived turnover in ``metrics`` measures what the
+execution layer actually exchanged; these notes measure what the signal and
+optimizer asked for, which is where churn starts.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any, Dict, List
+
+import numpy as np
+import pandas as pd
+
+from backtest.validation import _json_safe
+
+
+def compute_rebalance_notes(
+ target_pos: pd.DataFrame,
+ *,
+ top_n: int = 5,
+ epsilon: float = 1e-6,
+) -> Dict[str, Any]:
+ """Summarize per-date weight changes in a target position frame.
+
+ Args:
+ target_pos: Target weights (dates x codes), e.g. the frame behind
+ ``artifacts/positions.csv``. NaN cells are treated as zero.
+ top_n: How many largest per-name moves to keep per rebalance.
+ epsilon: Turnover at or below this counts as "no rebalance".
+
+ Returns:
+ JSON-safe dict with ``rebalances`` (per date: turnover, entries,
+ exits, top moves by absolute weight change) and ``summary`` (count
+ plus turnover aggregates).
+ """
+ empty = {
+ "rebalances": [],
+ "summary": {
+ "rebalance_count": 0,
+ "turnover_total": 0.0,
+ "turnover_mean": 0.0,
+ "turnover_max": 0.0,
+ "largest_rebalance_date": None,
+ },
+ }
+ if target_pos.empty or len(target_pos) < 2:
+ return empty
+
+ codes = target_pos.columns.tolist()
+ values = target_pos.fillna(0.0).to_numpy(dtype=float)
+
+ rebalances: List[Dict[str, Any]] = []
+ prev = values[0]
+ for i in range(1, len(values)):
+ curr = values[i]
+ delta = curr - prev
+ turnover = 0.5 * float(np.abs(delta).sum())
+ if turnover > epsilon:
+ date = target_pos.index[i]
+ entries = [
+ {"code": codes[j], "weight": float(curr[j])}
+ for j in range(len(codes))
+ if abs(prev[j]) <= epsilon and abs(curr[j]) > epsilon
+ ]
+ exits = [
+ {"code": codes[j], "weight": float(prev[j])}
+ for j in range(len(codes))
+ if abs(curr[j]) <= epsilon and abs(prev[j]) > epsilon
+ ]
+ moves = sorted(
+ (
+ {
+ "code": codes[j],
+ "from": float(prev[j]),
+ "to": float(curr[j]),
+ "delta": float(delta[j]),
+ }
+ for j in range(len(codes))
+ if abs(delta[j]) > epsilon
+ ),
+ key=lambda move: -abs(move["delta"]),
+ )[:top_n]
+ rebalances.append(
+ {
+ "date": str(date.date()) if hasattr(date, "date") else str(date),
+ "turnover": turnover,
+ "entries": entries,
+ "exits": exits,
+ "top_moves": moves,
+ }
+ )
+ prev = curr
+
+ turnovers = [r["turnover"] for r in rebalances]
+ largest = max(range(len(rebalances)), key=lambda k: turnovers[k]) if rebalances else None
+ return {
+ "rebalances": rebalances,
+ "summary": {
+ "rebalance_count": len(rebalances),
+ "turnover_total": float(sum(turnovers)),
+ "turnover_mean": float(np.mean(turnovers)) if turnovers else 0.0,
+ "turnover_max": float(max(turnovers)) if turnovers else 0.0,
+ "largest_rebalance_date": rebalances[largest]["date"] if largest is not None else None,
+ },
+ }
+
+
+def render_rebalance_notes_markdown(notes: Dict[str, Any]) -> str:
+ """Render notes as a compact Markdown report."""
+ summary = notes["summary"]
+ lines = [
+ "# Rebalance Notes",
+ "",
+ f"- rebalances: {summary['rebalance_count']}",
+ f"- turnover total / mean / max: {summary['turnover_total']:.4f} / "
+ f"{summary['turnover_mean']:.4f} / {summary['turnover_max']:.4f}",
+ ]
+ if summary["largest_rebalance_date"] is not None:
+ lines.append(f"- largest rebalance: {summary['largest_rebalance_date']}")
+ lines.append("")
+
+ for rebalance in notes["rebalances"]:
+ lines.append(f"## {rebalance['date']} (turnover {rebalance['turnover']:.4f})")
+ if rebalance["entries"]:
+ joined = ", ".join(item["code"] for item in rebalance["entries"])
+ lines.append(f"- entries: {joined}")
+ if rebalance["exits"]:
+ joined = ", ".join(item["code"] for item in rebalance["exits"])
+ lines.append(f"- exits: {joined}")
+ for move in rebalance["top_moves"]:
+ lines.append(f"- {move['code']}: {move['from']:.4f} -> {move['to']:.4f} ({move['delta']:+.4f})")
+ lines.append("")
+ return "\n".join(lines)
+
+
+def write_rebalance_notes(path: Path, notes: Dict[str, Any]) -> Dict[str, Any]:
+ """Write notes to ``path`` as strict, RFC-8259 JSON.
+
+ Mirrors :func:`backtest.validation.write_validation_json`: sanitize with
+ ``_json_safe`` (non-finite -> null) and serialize with ``allow_nan=False``
+ so every strict parser accepts the artifact. Returns the sanitized
+ payload that was written.
+ """
+ safe_notes = _json_safe(notes)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ json.dumps(safe_notes, indent=2, ensure_ascii=False, allow_nan=False) + "\n",
+ encoding="utf-8",
+ )
+ return safe_notes
diff --git a/agent/tests/test_rebalance_notes.py b/agent/tests/test_rebalance_notes.py
new file mode 100644
index 000000000..88bd98700
--- /dev/null
+++ b/agent/tests/test_rebalance_notes.py
@@ -0,0 +1,113 @@
+"""Tests for the rebalance notes module."""
+
+from __future__ import annotations
+
+import json
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from backtest.rebalance_notes import (
+ compute_rebalance_notes,
+ render_rebalance_notes_markdown,
+ write_rebalance_notes,
+)
+
+
+def _frame(rows, codes=("A", "B")):
+ dates = pd.date_range("2025-01-01", periods=len(rows), freq="B")
+ return pd.DataFrame(rows, index=dates, columns=list(codes))
+
+
+def test_turnover_entries_exits_and_top_moves():
+ pos = _frame(
+ [
+ [0.5, 0.5],
+ [0.75, 0.25], # turnover 0.25, A up, B down
+ [0.0, 1.0], # turnover 0.75, A exits, B grows
+ ]
+ )
+
+ notes = compute_rebalance_notes(pos)
+
+ rebalances = notes["rebalances"]
+ assert len(rebalances) == 2
+ assert rebalances[0]["turnover"] == pytest.approx(0.25)
+ assert rebalances[0]["entries"] == []
+ assert rebalances[0]["exits"] == []
+ assert [m["code"] for m in rebalances[0]["top_moves"]] == ["A", "B"]
+ assert rebalances[0]["top_moves"][0]["delta"] == pytest.approx(0.25)
+
+ second = rebalances[1]
+ assert second["turnover"] == pytest.approx(0.75)
+ assert [e["code"] for e in second["exits"]] == ["A"]
+ assert second["exits"][0]["weight"] == pytest.approx(0.75)
+ assert second["top_moves"][0]["code"] == "A"
+
+
+def test_epsilon_skips_noop_dates():
+ pos = _frame(
+ [
+ [0.5, 0.5],
+ [0.5 + 1e-9, 0.5 - 1e-9], # drift far below epsilon
+ [0.9, 0.1],
+ ]
+ )
+
+ notes = compute_rebalance_notes(pos)
+
+ assert len(notes["rebalances"]) == 1
+ assert notes["rebalances"][0]["date"] == "2025-01-03"
+
+
+def test_summary_aggregates_and_largest_date():
+ pos = _frame(
+ [
+ [1.0, 0.0],
+ [0.5, 0.5], # turnover 0.5
+ [0.2, 0.8], # turnover 0.3
+ ]
+ )
+
+ summary = compute_rebalance_notes(pos)["summary"]
+
+ assert summary["rebalance_count"] == 2
+ assert summary["turnover_total"] == pytest.approx(0.8)
+ assert summary["turnover_mean"] == pytest.approx(0.4)
+ assert summary["turnover_max"] == pytest.approx(0.5)
+ assert summary["largest_rebalance_date"] == "2025-01-02"
+
+
+def test_short_and_long_only_frames():
+ pos = _frame([[0.0, 0.0], [0.4, 0.6]])
+ notes = compute_rebalance_notes(pos)
+ assert len(notes["rebalances"]) == 1
+ assert {e["code"] for e in notes["rebalances"][0]["entries"]} == {"A", "B"}
+
+ assert compute_rebalance_notes(pos.iloc[:1])["summary"]["rebalance_count"] == 0
+ assert compute_rebalance_notes(pos.iloc[0:0])["rebalances"] == []
+
+
+def test_nan_cells_treated_as_zero():
+ pos = _frame([[0.5, np.nan], [0.5, 0.5]])
+ notes = compute_rebalance_notes(pos)
+ assert notes["rebalances"][0]["entries"][0]["code"] == "B"
+
+
+def test_write_strict_json_and_markdown(tmp_path):
+ pos = _frame([[0.5, 0.5], [0.9, 0.1]])
+ notes = compute_rebalance_notes(pos)
+
+ out = tmp_path / "nested" / "rebalance_notes.json"
+ payload = write_rebalance_notes(out, notes)
+
+ parsed = json.loads(out.read_text(encoding="utf-8"))
+ assert parsed["summary"]["rebalance_count"] == 1
+ assert parsed["rebalances"][0]["turnover"] == pytest.approx(0.4)
+ assert payload == parsed
+
+ md = render_rebalance_notes_markdown(notes)
+ assert "2025-01-02" in md
+ assert "turnover 0.4000" in md
+ assert "A: 0.5000 -> 0.9000 (+0.4000)" in md