Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(backtest): emit risk x-ray artifacts in portfolio runs (Portfolio Studio slice) (#900)

Yufeng He59fa3181b0e3
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index eefe99174..eb26405e6 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -623,6 +623,33 @@ class BaseEngine(ABC):
m["rebalance_turnover_mean"] = rebalance_notes["summary"]["turnover_mean"]
m["rebalance_turnover_max"] = rebalance_notes["summary"]["turnover_max"]
+ # Portfolio Studio: risk x-ray over the strategy's average basket.
+ # Short runs and never-invested strategies raise ValueError in the
+ # derivation and simply get no x-ray artifact.
+ from backtest.risk_xray import (
+ average_invested_weights,
+ compute_risk_xray,
+ render_risk_xray_markdown,
+ write_risk_xray,
+ )
+ try:
+ basket_weights, avg_invested = average_invested_weights(target_pos)
+ risk_xray = compute_risk_xray(
+ close_df, basket_weights, periods_per_year=bars_per_year,
+ )
+ except ValueError:
+ pass
+ else:
+ write_risk_xray(run_dir / "artifacts" / "risk_xray.json", risk_xray)
+ (run_dir / "artifacts" / "risk_xray.md").write_text(
+ render_risk_xray_markdown(risk_xray), encoding="utf-8"
+ )
+ m["risk_xray_hhi"] = risk_xray["concentration"]["hhi"]
+ m["risk_xray_effective_n"] = risk_xray["concentration"]["effective_n"]
+ m["risk_xray_annualized_vol"] = risk_xray["volatility"]["annualized_vol"]
+ m["risk_xray_max_drawdown"] = risk_xray["drawdown"]["max_drawdown"]
+ m["risk_xray_avg_invested"] = avg_invested
+
# 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/risk_xray.py b/agent/backtest/risk_xray.py
index c45cf29a6..e9f91bfe4 100644
--- a/agent/backtest/risk_xray.py
+++ b/agent/backtest/risk_xray.py
@@ -18,12 +18,16 @@ Conventions:
from __future__ import annotations
+import json
import math
+from pathlib import Path
from typing import Any, Mapping, Sequence
import numpy as np
import pandas as pd
+from backtest.validation import _json_safe
+
MIN_HISTORY_DAYS = 30
PERIODS_PER_YEAR = 252
VAR_LEVELS = (0.95, 0.99)
@@ -275,3 +279,84 @@ def _correlation(returns: pd.DataFrame, port: pd.Series) -> dict[str, Any]:
"max_pair": max_pair,
"beta_to_equal_weight": _finite(beta),
}
+
+
+def average_invested_weights(target_pos: pd.DataFrame) -> tuple[dict[str, float], float]:
+ """Derive the run's average basket from the target position frame.
+
+ Returns ``(weights, avg_invested)``: the mean target weight per symbol
+ restricted to symbols the strategy actually held on average, and the mean
+ row sum (how much of the book was invested at all). The final row alone
+ would be the wrong object here, since many strategies end flat.
+
+ Raises:
+ ValueError: when the frame is empty, the strategy never held
+ anything on average, or any symbol's average exposure is net
+ short — ``compute_risk_xray`` is long-only, and silently
+ x-raying just the long half of a long-short book would present
+ a partial basket as the whole strategy.
+ """
+ if target_pos is None or target_pos.empty:
+ raise ValueError("target position frame is empty")
+ means = target_pos.mean(axis=0)
+ short_book = [str(sym) for sym, w in means.items() if float(w) < 0]
+ if short_book:
+ raise ValueError(
+ "long-only x-ray cannot describe net short average exposure "
+ f"in {', '.join(short_book)}"
+ )
+ weights = {str(sym): float(w) for sym, w in means.items() if float(w) > 0}
+ avg_invested = float(target_pos.sum(axis=1).mean())
+ if not weights:
+ raise ValueError("strategy held no average exposure")
+ return weights, avg_invested
+
+
+def render_risk_xray_markdown(report: dict[str, Any]) -> str:
+ """Render an x-ray report as a compact Markdown summary."""
+ inputs = report["inputs"]
+ conc = report["concentration"]
+ vol = report["volatility"]
+ dd = report["drawdown"]
+ tail = report["tail_risk"]
+ lines = [
+ "# Portfolio Risk X-Ray",
+ "",
+ f"- basket: {', '.join(inputs['symbols'])}",
+ f"- window: {inputs['first_date']} .. {inputs['last_date']} "
+ f"({inputs['aligned_days']} aligned days)",
+ ]
+ if conc.get("hhi") is not None:
+ lines.append(
+ f"- concentration: hhi {conc['hhi']:.4f}, "
+ f"effective n {conc['effective_n']:.2f}, "
+ f"top1 {conc['top1_weight']:.2%}, top3 {conc['top3_weight']:.2%}"
+ )
+ if vol.get("annualized_vol") is not None:
+ lines.append(f"- annualized vol: {vol['annualized_vol']:.2%}")
+ if dd.get("max_drawdown") is not None:
+ lines.append(f"- max drawdown: {dd['max_drawdown']:.2%}")
+ if tail.get("var_95") is not None:
+ lines.append(
+ f"- tail (historical): VaR95 {tail['var_95']:.2%}, ES95 {tail['expected_shortfall_95']:.2%}"
+ )
+ if report["skipped"]:
+ joined = ", ".join(item["symbol"] for item in report["skipped"])
+ lines.append(f"- skipped: {joined}")
+ lines.append("")
+ return "\n".join(lines)
+
+
+def write_risk_xray(path: Path, report: dict[str, Any]) -> dict[str, Any]:
+ """Write the report to ``path`` as strict, RFC-8259 JSON.
+
+ Same contract as ``write_rebalance_notes``: sanitize with ``_json_safe``
+ and serialize with ``allow_nan=False``. Returns the sanitized payload.
+ """
+ safe_report = _json_safe(report)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ json.dumps(safe_report, indent=2, ensure_ascii=False, allow_nan=False) + "\n",
+ encoding="utf-8",
+ )
+ return safe_report
diff --git a/agent/tests/test_risk_xray.py b/agent/tests/test_risk_xray.py
index 2fe625cbc..cd809f851 100644
--- a/agent/tests/test_risk_xray.py
+++ b/agent/tests/test_risk_xray.py
@@ -8,7 +8,12 @@ import numpy as np
import pandas as pd
import pytest
-from backtest.risk_xray import compute_risk_xray
+from backtest.risk_xray import (
+ average_invested_weights,
+ compute_risk_xray,
+ render_risk_xray_markdown,
+ write_risk_xray,
+)
from src.tools.portfolio_risk_tool import PortfolioRiskXrayTool
@@ -242,3 +247,116 @@ def test_tool_survives_records_without_dates():
tool = PortfolioRiskXrayTool(data_fetcher=fetch)
payload = json.loads(tool.execute(symbols=["AAA", "BBB"]))
assert payload["status"] == "ok"
+
+
+# ---------------------------------------------------------------------------
+# average_invested_weights / artifact writers (run emission slice)
+
+
+def test_average_invested_weights_basic():
+ idx = pd.date_range("2026-01-01", periods=4, freq="D")
+ target_pos = pd.DataFrame(
+ {"AAA": [0.5, 0.5, 0.25, 0.0], "BBB": [0.25, 0.25, 0.25, 0.0], "CCC": [0.0] * 4},
+ index=idx,
+ )
+ weights, avg_invested = average_invested_weights(target_pos)
+ assert weights == {"AAA": pytest.approx(0.3125), "BBB": pytest.approx(0.1875)}
+ assert avg_invested == pytest.approx(0.5)
+
+
+def test_average_invested_weights_rejects_flat_strategy():
+ idx = pd.date_range("2026-01-01", periods=3, freq="D")
+ target_pos = pd.DataFrame({"AAA": [0.0, 0.0, 0.0]}, index=idx)
+ with pytest.raises(ValueError, match="no average exposure"):
+ average_invested_weights(target_pos)
+ with pytest.raises(ValueError, match="empty"):
+ average_invested_weights(pd.DataFrame())
+
+
+def test_average_invested_weights_rejects_long_short_book():
+ # A net-short leg must refuse the x-ray outright, not silently shrink the
+ # basket to the long half and present it as the whole strategy.
+ idx = pd.date_range("2026-01-01", periods=4, freq="D")
+ target_pos = pd.DataFrame(
+ {"AAA": [0.5, 0.5, 0.5, 0.5], "BBB": [-0.25, -0.25, -0.25, -0.25]},
+ index=idx,
+ )
+ with pytest.raises(ValueError, match="long-only .* BBB"):
+ average_invested_weights(target_pos)
+
+
+def test_write_risk_xray_strict_json_and_markdown(tmp_path):
+ closes = _closes({"AAA": list(range(100, 140)), "BBB": [50.0 + 0.1 * i for i in range(40)]})
+ report = compute_risk_xray(closes, {"AAA": 0.6, "BBB": 0.4})
+
+ out = tmp_path / "risk_xray.json"
+ safe = write_risk_xray(out, report)
+ on_disk = json.loads(out.read_text(encoding="utf-8"))
+ assert on_disk == safe
+ _assert_strict_json(on_disk)
+ assert on_disk["concentration"]["hhi"] == pytest.approx(0.52)
+
+ md = render_risk_xray_markdown(report)
+ assert "# Portfolio Risk X-Ray" in md
+ assert "AAA" in md and "BBB" in md
+ assert "annualized vol" in md
+
+
+def test_run_backtest_emits_risk_xray_artifacts(tmp_path):
+ from backtest.engines.base import BaseEngine
+
+ class _FlatEngine(BaseEngine):
+ def can_execute(self, symbol, direction, bar):
+ return True
+
+ def round_size(self, raw_size, price):
+ return float(raw_size)
+
+ def calc_commission(self, size, price, direction, is_open):
+ return 0.0
+
+ def apply_slippage(self, price, direction):
+ return price
+
+ dates = pd.bdate_range("2026-01-05", periods=40)
+ data_map = {
+ "AAA": pd.DataFrame(
+ {"open": [100.0 + i for i in range(40)], "close": [100.0 + i for i in range(40)]},
+ index=dates,
+ ),
+ "BBB": pd.DataFrame(
+ {"open": [50.0 + 0.2 * i for i in range(40)], "close": [50.0 + 0.2 * i for i in range(40)]},
+ index=dates,
+ ),
+ }
+
+ class _Loader:
+ def fetch(self, codes, start_date, end_date, fields=None, interval="1D"):
+ return data_map
+
+ class _Signals:
+ def generate(self, data):
+ return {code: pd.Series(1.0, index=frame.index) for code, frame in data.items()}
+
+ engine = _FlatEngine({"initial_cash": 100_000.0})
+ metrics = engine.run_backtest(
+ {"codes": ["AAA", "BBB"], "start_date": "2026-01-05", "end_date": "2026-03-01"},
+ _Loader(),
+ _Signals(),
+ tmp_path,
+ )
+
+ out_json = tmp_path / "artifacts" / "risk_xray.json"
+ out_md = tmp_path / "artifacts" / "risk_xray.md"
+ assert out_json.exists() and out_md.exists()
+ payload = json.loads(out_json.read_text(encoding="utf-8"))
+ _assert_strict_json(payload)
+ # constant 1.0 signals normalize to an even two-name basket
+ assert payload["concentration"]["hhi"] == pytest.approx(0.5)
+ assert set(payload["inputs"]["symbols"]) == {"AAA", "BBB"}
+ assert "# Portfolio Risk X-Ray" in out_md.read_text(encoding="utf-8")
+
+ assert metrics["risk_xray_hhi"] == pytest.approx(0.5)
+ assert metrics["risk_xray_effective_n"] == pytest.approx(2.0)
+ assert metrics["risk_xray_annualized_vol"] is not None
+ assert metrics["risk_xray_avg_invested"] == pytest.approx(39 / 40, abs=1e-6)