Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(backtest): portfolio risk x-ray core + agent tool (Portfolio Studio slice)

Yufeng He9889a74320e9
diff --git a/agent/backtest/risk_xray.py b/agent/backtest/risk_xray.py
new file mode 100644
index 000000000..c45cf29a6
--- /dev/null
+++ b/agent/backtest/risk_xray.py
@@ -0,0 +1,277 @@
+"""Portfolio risk x-ray: concentration, volatility, drawdown, tail risk, and
+co-movement for a weighted basket, computed from close-price panels.
+
+This is the Portfolio Studio risk-x-ray backend (roadmap slice). Everything
+here is a pure function of prices and weights — no I/O, no network, no
+loader imports — so the same computation serves the agent tool, the API,
+and tests. Data fetching lives in the caller.
+
+Conventions:
+- Long-only v1: negative weights are rejected up front rather than silently
+ mis-computing concentration (a short leg is a different feature).
+- Non-finite inputs are never trusted and non-finite outputs are never
+ emitted: every reported float passes through ``_finite`` so the result
+ survives ``json.dumps(..., allow_nan=False)``.
+- Look-ahead is structurally impossible: all statistics are computed over
+ trailing returns only.
+"""
+
+from __future__ import annotations
+
+import math
+from typing import Any, Mapping, Sequence
+
+import numpy as np
+import pandas as pd
+
+MIN_HISTORY_DAYS = 30
+PERIODS_PER_YEAR = 252
+VAR_LEVELS = (0.95, 0.99)
+
+
+def _finite(value: float | None) -> float | None:
+ """Return ``value`` when finite, else ``None`` (strict-JSON safe)."""
+ if value is None:
+ return None
+ try:
+ out = float(value)
+ except (TypeError, ValueError):
+ return None
+ return out if math.isfinite(out) else None
+
+
+def _validate_weights(
+ closes: pd.DataFrame, weights: Mapping[str, float]
+) -> tuple[dict[str, float], list[str]]:
+ """Normalize weights to sum 1; reject unknown symbols and bad values.
+
+ Returns the cleaned weight map (restricted to available columns) and any
+ warnings worth surfacing to the caller.
+ """
+ warnings: list[str] = []
+ if not weights:
+ raise ValueError("weights must name at least one symbol")
+
+ unknown = [sym for sym in weights if sym not in closes.columns]
+ if unknown:
+ raise ValueError(f"weights reference symbols with no price data: {sorted(unknown)}")
+
+ cleaned: dict[str, float] = {}
+ for sym, raw in weights.items():
+ try:
+ value = float(raw)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"weight for {sym!r} is not a number: {raw!r}") from exc
+ if not math.isfinite(value):
+ raise ValueError(f"weight for {sym!r} is not finite: {raw!r}")
+ if value < 0:
+ raise ValueError(
+ f"weight for {sym!r} is negative ({value}); the risk x-ray is long-only for now"
+ )
+ cleaned[sym] = value
+
+ total = sum(cleaned.values())
+ if total <= 0:
+ raise ValueError("weights must sum to a positive value")
+ if abs(total - 1.0) > 1e-6:
+ warnings.append(f"weights summed to {total:.6f}; renormalized to 1.0")
+ cleaned = {sym: value / total for sym, value in cleaned.items()}
+ return cleaned, warnings
+
+
+def compute_risk_xray(
+ closes: pd.DataFrame,
+ weights: Mapping[str, float],
+ *,
+ periods_per_year: int = PERIODS_PER_YEAR,
+ var_levels: Sequence[float] = VAR_LEVELS,
+ min_history: int = MIN_HISTORY_DAYS,
+) -> dict[str, Any]:
+ """Compute the risk x-ray for a weighted basket.
+
+ Args:
+ closes: Close-price panel, one column per symbol, sorted by date.
+ weights: Symbol → weight. Renormalized to 1.0 with a warning when the
+ sum differs; must be long-only and reference existing columns.
+ periods_per_year: Annualization factor for the bar interval.
+ var_levels: Tail levels for historical VaR / expected shortfall.
+ min_history: Minimum valid bars a symbol must have to be included.
+
+ Returns:
+ A strict-JSON-safe dict (``json.dumps(..., allow_nan=False)`` must
+ never fail on it) with concentration, volatility, drawdown, tail
+ risk, diversification, and correlation sections, plus ``skipped``
+ and ``warnings`` bookkeeping.
+
+ Raises:
+ ValueError: On unusable input (empty panel, bad weights, or nothing
+ left after the history filter / calendar alignment).
+ """
+ if closes is None or closes.empty:
+ raise ValueError("price panel is empty")
+ frame = closes.dropna(axis=1, how="all")
+ if frame.empty:
+ raise ValueError("price panel has no non-NaN closes")
+
+ weights, warnings = _validate_weights(frame, weights)
+
+ # History filter: thin symbols are excluded rather than allowed to skew
+ # the whole x-ray on a handful of bars.
+ kept: list[str] = []
+ skipped: list[dict[str, str]] = []
+ for sym in weights:
+ valid = int(frame[sym].count())
+ if valid < min_history:
+ skipped.append({"symbol": sym, "reason": f"only {valid} valid bars (min {min_history})"})
+ else:
+ kept.append(sym)
+ if not kept:
+ raise ValueError(f"no symbol has at least {min_history} valid bars")
+ if skipped:
+ # Renormalize over the survivors so the x-ray still describes a
+ # fully invested basket, and say so.
+ kept_weights = {sym: weights[sym] for sym in kept}
+ total = sum(kept_weights.values())
+ weights = {sym: value / total for sym, value in kept_weights.items()}
+ warnings.append("weights renormalized over symbols that survived the history filter")
+
+ aligned = frame[kept].dropna(axis=0, how="any")
+ if len(aligned) < 2:
+ raise ValueError(
+ "fewer than 2 shared trading days after aligning calendars across symbols"
+ )
+
+ returns = aligned.pct_change(fill_method=None).dropna(how="any")
+ if returns.empty:
+ raise ValueError("no overlapping return observations across symbols")
+
+ w = np.array([weights[sym] for sym in kept], dtype=float)
+ port = returns.to_numpy(dtype=float) @ w
+ port_returns = pd.Series(port, index=returns.index)
+
+ result: dict[str, Any] = {
+ "inputs": {
+ "symbols": kept,
+ "weights": {sym: round(float(weights[sym]), 8) for sym in kept},
+ "aligned_days": int(len(aligned)),
+ "return_observations": int(len(returns)),
+ "first_date": str(aligned.index[0]),
+ "last_date": str(aligned.index[-1]),
+ },
+ "concentration": _concentration(w),
+ "volatility": _volatility(port_returns, periods_per_year),
+ "drawdown": _drawdown(port_returns),
+ "tail_risk": _tail_risk(port_returns, var_levels),
+ "diversification": _diversification(returns, w, port_returns, periods_per_year),
+ "correlation": _correlation(returns, port_returns),
+ "skipped": skipped,
+ "warnings": warnings,
+ }
+ return result
+
+
+def _concentration(w: np.ndarray) -> dict[str, Any]:
+ hhi = float(np.sum(w**2))
+ order = np.argsort(w)[::-1]
+ return {
+ "hhi": _finite(hhi),
+ "effective_n": _finite(1.0 / hhi) if hhi > 0 else None,
+ "top1_weight": _finite(float(w[order[0]])) if len(order) else None,
+ "top3_weight": _finite(float(w[order[:3]].sum())) if len(order) else None,
+ }
+
+
+def _volatility(port: pd.Series, ppy: int) -> dict[str, Any]:
+ vol = float(port.std(ddof=1)) if len(port) > 1 else None
+ downside = port[port < 0]
+ downside_dev = float(downside.std(ddof=1)) if len(downside) > 1 else None
+ return {
+ "daily_vol": _finite(vol),
+ "annualized_vol": _finite(vol * math.sqrt(ppy)) if vol is not None else None,
+ "downside_deviation_annualized": (
+ _finite(downside_dev * math.sqrt(ppy)) if downside_dev is not None else None
+ ),
+ }
+
+
+def _drawdown(port: pd.Series) -> dict[str, Any]:
+ if port.empty:
+ return {"max_drawdown": None, "max_drawdown_start": None, "max_drawdown_trough": None}
+ equity = (1.0 + port).cumprod()
+ peak = equity.cummax()
+ dd = equity / peak - 1.0
+ trough_idx = dd.idxmin()
+ start_idx = equity.loc[:trough_idx].idxmax()
+ return {
+ "max_drawdown": _finite(float(dd.loc[trough_idx])),
+ "max_drawdown_start": str(start_idx),
+ "max_drawdown_trough": str(trough_idx),
+ }
+
+
+def _tail_risk(port: pd.Series, levels: Sequence[float]) -> dict[str, Any]:
+ out: dict[str, Any] = {}
+ losses = -port.to_numpy(dtype=float)
+ for level in levels:
+ if len(losses) < 2:
+ var = es = None
+ else:
+ var = float(np.quantile(losses, level))
+ tail = losses[losses >= var]
+ es = float(tail.mean()) if len(tail) else None
+ key = f"{int(round(level * 100))}"
+ out[f"var_{key}"] = _finite(var)
+ out[f"expected_shortfall_{key}"] = _finite(es)
+ out["method"] = "historical simulation (non-parametric)"
+ return out
+
+
+def _diversification(
+ returns: pd.DataFrame, w: np.ndarray, port: pd.Series, ppy: int
+) -> dict[str, Any]:
+ if returns.shape[1] < 2:
+ return {"diversification_ratio": None, "note": "needs at least 2 assets"}
+ asset_vols = returns.std(ddof=1).to_numpy(dtype=float)
+ port_vol = float(port.std(ddof=1)) if len(port) > 1 else 0.0
+ if port_vol <= 0 or not math.isfinite(port_vol):
+ return {"diversification_ratio": None, "note": "portfolio variance is zero"}
+ ratio = float(np.dot(w, asset_vols) / port_vol)
+ return {"diversification_ratio": _finite(ratio)}
+
+
+def _correlation(returns: pd.DataFrame, port: pd.Series) -> dict[str, Any]:
+ if returns.shape[1] < 2:
+ return {
+ "avg_pairwise_abs": None,
+ "max_pair": None,
+ "beta_to_equal_weight": None,
+ "note": "needs at least 2 assets",
+ }
+ corr = returns.corr().to_numpy(dtype=float)
+ n = corr.shape[0]
+ off_diag = [abs(corr[i, j]) for i in range(n) for j in range(i + 1, n)]
+ avg_pairwise = float(np.mean(off_diag)) if off_diag else None
+
+ max_pair = None
+ if off_diag:
+ i, j = max(
+ ((i, j) for i in range(n) for j in range(i + 1, n)),
+ key=lambda pair: abs(corr[pair[0], pair[1]]),
+ )
+ max_pair = {
+ "symbols": [str(returns.columns[i]), str(returns.columns[j])],
+ "corr": _finite(float(corr[i, j])),
+ }
+
+ market = returns.mean(axis=1)
+ market_var = float(market.var(ddof=1)) if len(market) > 1 else 0.0
+ if market_var > 0 and math.isfinite(market_var):
+ beta = float(port.cov(market) / market_var)
+ else:
+ beta = None
+
+ return {
+ "avg_pairwise_abs": _finite(avg_pairwise),
+ "max_pair": max_pair,
+ "beta_to_equal_weight": _finite(beta),
+ }
diff --git a/agent/src/tools/portfolio_risk_tool.py b/agent/src/tools/portfolio_risk_tool.py
new file mode 100644
index 000000000..c978a4bca
--- /dev/null
+++ b/agent/src/tools/portfolio_risk_tool.py
@@ -0,0 +1,194 @@
+"""Agent tool: portfolio risk x-ray (Portfolio Studio slice).
+
+Wraps ``backtest.risk_xray.compute_risk_xray`` with data fetching through the
+standard loader fallback chain (``src.market_data.fetch_market_data``), so the
+agent can ask "how risky is this basket" without caring which source serves
+the prices. The computation itself is pure and unit-tested directly; this
+file only does argument handling, panel shaping, and the JSON envelope.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from datetime import datetime, timedelta, timezone
+from typing import Any, Callable, Mapping
+
+import pandas as pd
+
+from backtest.risk_xray import compute_risk_xray
+from src.agent.tools import BaseTool
+from src.market_data import fetch_market_data
+
+logger = logging.getLogger(__name__)
+
+_DEFAULT_LOOKBACK_DAYS = 365
+_MAX_SYMBOLS = 50
+
+# Candidate record keys that may carry the bar's date/timestamp after
+# ``DataFrame.reset_index().to_dict("records")`` — loaders name the index
+# differently ("date", "datetime", "trade_date", ...).
+_DATE_KEYS = ("date", "datetime", "trade_date", "time", "timestamp")
+
+
+class PortfolioRiskXrayTool(BaseTool):
+ """Compute concentration, volatility, drawdown, tail risk, and
+ co-movement for a weighted basket of symbols."""
+
+ name = "portfolio_risk_xray"
+ description = (
+ "Portfolio risk x-ray: given symbols (and optional weights), fetch "
+ "recent daily closes through the data fallback chain and compute "
+ "concentration (HHI/effective N), annualized volatility, max drawdown, "
+ "historical VaR/expected shortfall, diversification ratio, and "
+ "correlation/beta. Long-only; weights are renormalized when they do "
+ "not sum to 1."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "symbols": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Symbols in the basket, e.g. [\"AAPL\", \"MSFT\", \"SPY\"].",
+ },
+ "weights": {
+ "type": "object",
+ "additionalProperties": {"type": "number"},
+ "description": "Optional symbol → weight map. Equal weights when omitted.",
+ },
+ "start_date": {
+ "type": "string",
+ "description": "YYYY-MM-DD. Defaults to one year before end_date.",
+ },
+ "end_date": {
+ "type": "string",
+ "description": "YYYY-MM-DD. Defaults to today (UTC).",
+ },
+ "source": {
+ "type": "string",
+ "description": "Data source preference; 'auto' (default) walks the fallback chain.",
+ },
+ "interval": {
+ "type": "string",
+ "description": "Bar interval passed to the loaders; defaults to '1D'.",
+ },
+ },
+ "required": ["symbols"],
+ }
+
+ def __init__(self, data_fetcher: Callable[..., dict[str, Any]] | None = None) -> None:
+ # Injectable for tests; production uses the real fallback chain.
+ self._fetch = data_fetcher or fetch_market_data
+
+ def execute(self, **kwargs: Any) -> str:
+ try:
+ return self._run(**kwargs)
+ except Exception as exc: # noqa: BLE001 — tool must always return JSON
+ logger.warning("portfolio_risk_xray failed: %s", exc)
+ return json.dumps(
+ {"status": "error", "error": str(exc)}, ensure_ascii=False, allow_nan=False
+ )
+
+ # ------------------------------------------------------------------
+ def _run(self, **kwargs: Any) -> str:
+ symbols = kwargs.get("symbols")
+ if not isinstance(symbols, list) or not symbols or not all(
+ isinstance(s, str) and s.strip() for s in symbols
+ ):
+ raise ValueError("symbols must be a non-empty list of strings")
+ symbols = [s.strip() for s in symbols]
+ if len(symbols) > _MAX_SYMBOLS:
+ raise ValueError(f"too many symbols ({len(symbols)}); cap is {_MAX_SYMBOLS}")
+
+ weights = self._parse_weights(kwargs.get("weights"), symbols)
+ start_date, end_date = self._parse_dates(kwargs.get("start_date"), kwargs.get("end_date"))
+ source = str(kwargs.get("source") or "auto")
+ interval = str(kwargs.get("interval") or "1D")
+
+ raw = self._fetch(
+ codes=symbols,
+ start_date=start_date,
+ end_date=end_date,
+ source=source,
+ interval=interval,
+ )
+ closes = self._closes_frame(raw, symbols)
+ unresolved = raw.get("_unresolved") if isinstance(raw, Mapping) else None
+
+ report = compute_risk_xray(closes, weights)
+ envelope = {
+ "status": "ok",
+ "data": report,
+ "meta": {
+ "start_date": start_date,
+ "end_date": end_date,
+ "interval": interval,
+ "source": source,
+ "unresolved_symbols": list(unresolved or []),
+ },
+ }
+ return json.dumps(envelope, ensure_ascii=False, indent=2, allow_nan=False)
+
+ # ------------------------------------------------------------------
+ @staticmethod
+ def _parse_weights(raw: Any, symbols: list[str]) -> dict[str, float]:
+ if raw is None:
+ return {sym: 1.0 / len(symbols) for sym in symbols}
+ if not isinstance(raw, Mapping):
+ raise ValueError("weights must be an object mapping symbol → number")
+ unknown = [sym for sym in raw if sym not in symbols]
+ if unknown:
+ raise ValueError(f"weights name symbols not in the basket: {sorted(unknown)}")
+ missing = [sym for sym in symbols if sym not in raw]
+ if missing:
+ raise ValueError(f"weights missing basket symbols: {sorted(missing)}")
+ return {sym: raw[sym] for sym in symbols}
+
+ @staticmethod
+ def _parse_dates(start_raw: Any, end_raw: Any) -> tuple[str, str]:
+ end = (
+ datetime.strptime(end_raw, "%Y-%m-%d").date()
+ if isinstance(end_raw, str) and end_raw
+ else datetime.now(timezone.utc).date()
+ )
+ start = (
+ datetime.strptime(start_raw, "%Y-%m-%d").date()
+ if isinstance(start_raw, str) and start_raw
+ else end - timedelta(days=_DEFAULT_LOOKBACK_DAYS)
+ )
+ if start >= end:
+ raise ValueError(f"start_date {start} must be before end_date {end}")
+ return start.isoformat(), end.isoformat()
+
+ @staticmethod
+ def _closes_frame(raw: Mapping[str, Any], symbols: list[str]) -> pd.DataFrame:
+ """Shape the fetch envelope into a date-indexed close-price panel."""
+ series: dict[str, pd.Series] = {}
+ for sym in symbols:
+ records = raw.get(sym)
+ if not records:
+ continue
+ times: list[Any] = []
+ prices: list[float] = []
+ for record in records:
+ if not isinstance(record, Mapping) or "close" not in record:
+ continue
+ when = next((record[k] for k in _DATE_KEYS if k in record), None)
+ try:
+ price = float(record["close"])
+ except (TypeError, ValueError):
+ continue
+ times.append(when)
+ prices.append(price)
+ if not prices:
+ continue
+ # Mixed typed/untyped timestamps can't be sorted together; when any
+ # bar lacks a date, trust loader order (chronological) instead.
+ if any(when is None for when in times):
+ series[sym] = pd.Series(prices, name=sym)
+ else:
+ series[sym] = pd.Series(prices, index=times, name=sym).sort_index()
+ if not series:
+ raise ValueError("no close prices returned for any requested symbol")
+ return pd.DataFrame(series)
diff --git a/agent/tests/test_risk_xray.py b/agent/tests/test_risk_xray.py
new file mode 100644
index 000000000..2fe625cbc
--- /dev/null
+++ b/agent/tests/test_risk_xray.py
@@ -0,0 +1,244 @@
+"""Tests for the portfolio risk x-ray core and its agent tool."""
+
+from __future__ import annotations
+
+import json
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from backtest.risk_xray import compute_risk_xray
+from src.tools.portfolio_risk_tool import PortfolioRiskXrayTool
+
+
+def _closes(series_map: dict[str, list[float]], start: str = "2026-01-01") -> pd.DataFrame:
+ n = max(len(v) for v in series_map.values())
+ idx = pd.date_range(start, periods=n, freq="D")
+ return pd.DataFrame({k: pd.Series(v, index=idx[: len(v)]) for k, v in series_map.items()})
+
+
+def _assert_strict_json(payload: dict) -> None:
+ json.dumps(payload, allow_nan=False)
+
+
+# ---------------------------------------------------------------------------
+# weights handling
+# ---------------------------------------------------------------------------
+
+
+def test_weights_are_renormalized_with_warning():
+ closes = _closes({"AAA": list(range(100, 160)), "BBB": list(range(50, 110))})
+ result = compute_risk_xray(closes, {"AAA": 2.0, "BBB": 2.0}, min_history=10)
+ assert result["inputs"]["weights"] == {"AAA": 0.5, "BBB": 0.5}
+ assert any("renormalized" in w for w in result["warnings"])
+ _assert_strict_json(result)
+
+
+def test_negative_weight_rejected():
+ closes = _closes({"AAA": list(range(100, 160)), "BBB": list(range(50, 110))})
+ with pytest.raises(ValueError, match="long-only"):
+ compute_risk_xray(closes, {"AAA": 1.5, "BBB": -0.5})
+
+
+def test_unknown_symbol_rejected():
+ closes = _closes({"AAA": list(range(100, 160))})
+ with pytest.raises(ValueError, match="no price data"):
+ compute_risk_xray(closes, {"AAA": 0.5, "MISSING": 0.5})
+
+
+def test_empty_panel_rejected():
+ with pytest.raises(ValueError, match="empty"):
+ compute_risk_xray(pd.DataFrame(), {"AAA": 1.0})
+
+
+# ---------------------------------------------------------------------------
+# concentration
+# ---------------------------------------------------------------------------
+
+
+def test_concentration_math():
+ closes = _closes(
+ {
+ "AAA": list(range(100, 160)),
+ "BBB": list(range(50, 110)),
+ "CCC": list(range(200, 260)),
+ }
+ )
+ result = compute_risk_xray(closes, {"AAA": 0.5, "BBB": 0.25, "CCC": 0.25}, min_history=10)
+ conc = result["concentration"]
+ assert conc["hhi"] == pytest.approx(0.375)
+ assert conc["effective_n"] == pytest.approx(1 / 0.375)
+ assert conc["top1_weight"] == pytest.approx(0.5)
+ assert conc["top3_weight"] == pytest.approx(1.0)
+ _assert_strict_json(result)
+
+
+# ---------------------------------------------------------------------------
+# history filter and calendar alignment
+# ---------------------------------------------------------------------------
+
+
+def test_thin_symbol_skipped_and_weights_renormalized():
+ closes = _closes(
+ {
+ "AAA": list(range(100, 160)),
+ "BBB": list(range(50, 110)),
+ "THIN": [10.0] * 5,
+ }
+ )
+ result = compute_risk_xray(
+ closes, {"AAA": 0.34, "BBB": 0.33, "THIN": 0.33}, min_history=30
+ )
+ assert [s["symbol"] for s in result["skipped"]] == ["THIN"]
+ assert result["inputs"]["symbols"] == ["AAA", "BBB"]
+ assert result["inputs"]["weights"] == pytest.approx({"AAA": 0.34 / 0.67, "BBB": 0.33 / 0.67})
+ _assert_strict_json(result)
+
+
+def test_all_thin_rejected():
+ closes = _closes({"AAA": [1.0, 2.0, 3.0]})
+ with pytest.raises(ValueError, match="valid bars"):
+ compute_risk_xray(closes, {"AAA": 1.0}, min_history=30)
+
+
+# ---------------------------------------------------------------------------
+# drawdown / tail risk
+# ---------------------------------------------------------------------------
+
+
+def test_max_drawdown_on_hand_built_curve():
+ closes = _closes({"AAA": [100.0, 120.0, 60.0, 90.0]})
+ result = compute_risk_xray(closes, {"AAA": 1.0}, min_history=2)
+ assert result["drawdown"]["max_drawdown"] == pytest.approx(-0.5)
+ _assert_strict_json(result)
+
+
+def test_expected_shortfall_on_known_tail():
+ returns_closes = [100.0]
+ for ret in [0.01] * 19 + [-0.10]:
+ returns_closes.append(returns_closes[-1] * (1 + ret))
+ closes = _closes({"AAA": returns_closes})
+ result = compute_risk_xray(closes, {"AAA": 1.0}, min_history=2)
+ tail = result["tail_risk"]
+ assert tail["expected_shortfall_95"] == pytest.approx(0.10)
+ assert tail["var_95"] is not None
+ _assert_strict_json(result)
+
+
+# ---------------------------------------------------------------------------
+# correlation / beta / diversification
+# ---------------------------------------------------------------------------
+
+
+def test_equal_weight_beta_is_one_against_equal_weight_proxy():
+ rng = np.random.default_rng(7)
+ a = rng.normal(0.001, 0.01, 80)
+ b = rng.normal(0.0005, 0.02, 80)
+ closes = _closes(
+ {
+ "AAA": 100 * np.cumprod(1 + a),
+ "BBB": 80 * np.cumprod(1 + b),
+ }
+ )
+ result = compute_risk_xray(closes, {"AAA": 0.5, "BBB": 0.5}, min_history=10)
+ assert result["correlation"]["beta_to_equal_weight"] == pytest.approx(1.0)
+ _assert_strict_json(result)
+
+
+def test_identical_series_have_unit_diversification_ratio():
+ base = 100 * np.cumprod(1 + np.random.default_rng(3).normal(0, 0.01, 80))
+ closes = _closes({"AAA": base, "BBB": base.copy()})
+ result = compute_risk_xray(closes, {"AAA": 0.5, "BBB": 0.5}, min_history=10)
+ assert result["diversification"]["diversification_ratio"] == pytest.approx(1.0)
+ assert result["correlation"]["avg_pairwise_abs"] == pytest.approx(1.0)
+ _assert_strict_json(result)
+
+
+def test_single_asset_correlation_section_is_null():
+ closes = _closes({"AAA": list(range(100, 180))})
+ result = compute_risk_xray(closes, {"AAA": 1.0}, min_history=10)
+ corr = result["correlation"]
+ assert corr["avg_pairwise_abs"] is None
+ assert corr["beta_to_equal_weight"] is None
+ assert corr["note"]
+ _assert_strict_json(result)
+
+
+def test_constant_prices_never_emit_nan():
+ closes = _closes({"AAA": [10.0] * 60, "BBB": [20.0] * 60})
+ result = compute_risk_xray(closes, {"AAA": 0.5, "BBB": 0.5}, min_history=10)
+ _assert_strict_json(result)
+
+
+# ---------------------------------------------------------------------------
+# agent tool
+# ---------------------------------------------------------------------------
+
+
+def _stub_fetcher(closes_map: dict[str, list[float]]):
+ def fetch(*, codes, start_date, end_date, source, interval, **kwargs):
+ out: dict[str, object] = {}
+ idx = pd.date_range("2026-01-01", periods=max(len(v) for v in closes_map.values()), freq="D")
+ for code in codes:
+ values = closes_map.get(code)
+ if values is None:
+ continue
+ out[code] = [
+ {"date": str(idx[i].date()), "close": price} for i, price in enumerate(values)
+ ]
+ out["_unresolved"] = [c for c in codes if c not in out]
+ return out
+
+ return fetch
+
+
+def test_tool_happy_path_equal_weights():
+ tool = PortfolioRiskXrayTool(
+ data_fetcher=_stub_fetcher(
+ {"AAA": list(range(100, 160)), "BBB": list(range(50, 110))}
+ )
+ )
+ payload = json.loads(
+ tool.execute(symbols=["AAA", "BBB"], start_date="2026-01-01", end_date="2026-03-01")
+ )
+ assert payload["status"] == "ok"
+ assert payload["data"]["concentration"]["hhi"] == pytest.approx(0.5)
+ assert payload["data"]["concentration"]["effective_n"] == pytest.approx(2.0)
+ assert payload["meta"]["unresolved_symbols"] == []
+
+
+def test_tool_reports_unresolved_symbols():
+ tool = PortfolioRiskXrayTool(data_fetcher=_stub_fetcher({"AAA": list(range(100, 160))}))
+ payload = json.loads(tool.execute(symbols=["AAA", "NOPE"]))
+ # NOPE has no data → weights reference it → error envelope, still strict JSON
+ assert payload["status"] == "error"
+ assert "NOPE" in payload["error"]
+
+
+def test_tool_rejects_bad_arguments():
+ tool = PortfolioRiskXrayTool(data_fetcher=_stub_fetcher({}))
+ payload = json.loads(tool.execute(symbols=[]))
+ assert payload["status"] == "error"
+ payload = json.loads(tool.execute(symbols=["AAA"], weights={"AAA": 0.5, "ZZZ": 0.5}))
+ assert payload["status"] == "error"
+ payload = json.loads(
+ tool.execute(symbols=["AAA"], start_date="2026-03-01", end_date="2026-01-01")
+ )
+ assert payload["status"] == "error"
+
+
+def test_tool_survives_records_without_dates():
+ def fetch(*, codes, start_date, end_date, source, interval, **kwargs):
+ return {
+ "AAA": [{"close": 100 + i} for i in range(40)], # no date fields at all
+ # partially dated → whole series falls back to loader order
+ "BBB": (
+ [{"date": "2026-02-01", "close": 50.0}]
+ + [{"close": 50 + i} for i in range(1, 40)]
+ ),
+ }
+
+ tool = PortfolioRiskXrayTool(data_fetcher=fetch)
+ payload = json.loads(tool.execute(symbols=["AAA", "BBB"]))
+ assert payload["status"] == "ok"