Skip to content

"Vibe-Trading: Your Personal Trading Agent"

refactor(metrics): one shared span-derived bars-per-year for cross-market runs

Haozhe Wue40b01b875c7
diff --git a/agent/backtest/engines/options_portfolio.py b/agent/backtest/engines/options_portfolio.py
index c53ed5012..4a4e5d942 100644
--- a/agent/backtest/engines/options_portfolio.py
+++ b/agent/backtest/engines/options_portfolio.py
@@ -26,6 +26,7 @@ from typing import Any, Dict, List, Optional
import numpy as np
import pandas as pd
+from backtest.metrics import effective_bars_per_year
from src.quantlib.options import bs_greeks, bs_price, normalise_option_type
@@ -573,19 +574,12 @@ def _calc_options_metrics(
equity_vals = pd.to_numeric(equity, errors="coerce").astype(float)
path_is_finite = bool(n and np.isfinite(equity_vals.to_numpy()).all())
- # Cross-market convention (runner.py passes bars_per_year=None): derive
- # the effective bars per year from the observed calendar span, mirroring
- # calc_metrics. Without this, every None comparison below (<= 0 / > 0)
- # raises TypeError instead of returning metrics.
+ # Cross-market convention (runner.py passes bars_per_year=None): resolve
+ # it through the shared span-derived factor. Without this, every None
+ # comparison below (<= 0 / > 0) raises TypeError instead of returning
+ # metrics.
if bars_per_year is None:
- if n >= 2:
- first, last = equity_vals.index[0], equity_vals.index[-1]
- diff = last - first
- calendar_days = diff.days if hasattr(diff, "days") else 0
- years = calendar_days / 365.25 if calendar_days > 0 else 1.0
- bars_per_year = int(n / years) if years > 0 else 252
- else:
- bars_per_year = 252
+ bars_per_year = effective_bars_per_year(equity_vals.index)
final_raw: float | None = None
final_value: float | None = None
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.py
index 3b2f2ddeb..602a4a7aa 100644
--- a/agent/backtest/metrics.py
+++ b/agent/backtest/metrics.py
@@ -170,6 +170,39 @@ def calc_bars_per_year(interval: str = "1D", source: str = "tushare") -> int:
return trading_days * bars_per_day
+def effective_bars_per_year(index: Any, default: int = 252) -> int:
+ """Bars per elapsed calendar year observed on ``index``.
+
+ The cross-market annualisation convention. A basket that spans markets has
+ no single per-market bar count — the runner signals that by passing
+ ``bars_per_year=None`` — so the factor is measured from the series itself
+ instead of assumed: bars observed divided by calendar years elapsed. Every
+ consumer of ``bars_per_year=None`` (portfolio metrics, risk x-ray, options
+ metrics, validation) resolves it through this one function, so the Sharpe,
+ the annualised volatility, and the validation Sharpe in a single run card
+ are annualised identically.
+
+ Args:
+ index: Datetime-like index of the series being annualised.
+ default: Returned when the span cannot be measured (empty index, or an
+ index whose difference carries no ``days``).
+
+ Returns:
+ Effective bars per year. A span shorter than one calendar day counts as
+ one year, matching how a single-bar curve annualises to its own return.
+ """
+ n = len(index)
+ if n == 0:
+ return default
+ try:
+ diff = index[-1] - index[0]
+ except (IndexError, TypeError):
+ return default
+ calendar_days = diff.days if hasattr(diff, "days") else 0
+ years = calendar_days / 365.25 if calendar_days > 0 else 1.0
+ return int(n / years) if years > 0 else default
+
+
# ─── Sign-safe returns ───
_log = logging.getLogger(__name__)
@@ -491,11 +524,7 @@ def calc_metrics(
# Calendar-day annualization for cross-market (bars_per_year=None)
if bars_per_year is None:
- first, last = equity_curve.index[0], equity_curve.index[-1]
- diff = last - first
- calendar_days = diff.days if hasattr(diff, "days") else 0
- years = calendar_days / 365.25 if calendar_days > 0 else 1.0
- bpy = int(n / years) if years > 0 else 252
+ bpy = effective_bars_per_year(equity_curve.index)
else:
bpy = bars_per_year
diff --git a/agent/backtest/risk_xray.py b/agent/backtest/risk_xray.py
index 9dc7c7c5d..be877f04c 100644
--- a/agent/backtest/risk_xray.py
+++ b/agent/backtest/risk_xray.py
@@ -26,6 +26,7 @@ from typing import Any, Mapping, Sequence
import numpy as np
import pandas as pd
+from backtest.metrics import effective_bars_per_year
from backtest.validation import _json_safe
MIN_HISTORY_DAYS = 30
@@ -203,29 +204,19 @@ def _volatility(port: pd.Series, ppy: int | None) -> dict[str, Any]:
}
-def _annualize_factor(ppy: int | None, index: Any = None) -> float:
+def _annualize_factor(ppy: int | None, index: Any) -> float:
"""Return the annualization factor ``sqrt(periods_per_year)``.
``ppy is None`` means the caller deliberately declined to specify a
per-market bar count — the runner's cross-market convention
- (``bars_per_year=None``). Follow the same span-derived convention as
- ``calc_metrics`` / ``run_validation`` / options metrics: effective bars
- per year = observed bars per elapsed calendar year, so the x-ray's
- annualized volatility agrees with the Sharpe metrics in the same run
- card (a fixed 365 would sit ~18% higher for a 252-trading-day daily
- series). Degenerate/empty indexes fall back to the default 252.
+ (``bars_per_year=None``). Resolving it through the shared
+ ``effective_bars_per_year`` is what keeps the x-ray's annualized
+ volatility on the same footing as the Sharpe in the same run card (a
+ fixed 365 would sit ~18% higher for a 252-trading-day daily series).
"""
if ppy is not None:
return math.sqrt(float(ppy))
- try:
- first, last = index[0], index[-1]
- diff = last - first
- calendar_days = diff.days if hasattr(diff, "days") else 0
- years = calendar_days / 365.25 if calendar_days > 0 else 1.0
- bpy = int(len(index) / years) if years > 0 else 252
- except (IndexError, TypeError):
- bpy = 252
- return math.sqrt(float(bpy))
+ return math.sqrt(float(effective_bars_per_year(index)))
def _drawdown(port: pd.Series) -> dict[str, Any]:
diff --git a/agent/backtest/validation.py b/agent/backtest/validation.py
index b17ec9ffa..729fd5728 100644
--- a/agent/backtest/validation.py
+++ b/agent/backtest/validation.py
@@ -20,6 +20,7 @@ from typing import Any, Dict, List
import numpy as np
import pandas as pd
+from backtest.metrics import effective_bars_per_year
from backtest.models import TradeRecord
@@ -285,27 +286,6 @@ def walk_forward_analysis(
}
-def _effective_bars_per_year(equity_curve: pd.Series) -> int:
- """Derive an effective bars-per-year from the equity span.
-
- Used when the runner declines to specify per-market bar counts
- (``bars_per_year=None``, the cross-market calendar-day convention):
- the observed number of bars per elapsed calendar year, falling back to
- the default 252 for degenerate spans (empty/single-bar curves).
- """
- n = len(equity_curve)
- if n < 2:
- return 252
- try:
- first, last = equity_curve.index[0], equity_curve.index[-1]
- diff = last - first
- calendar_days = diff.days if hasattr(diff, "days") else 0
- years = calendar_days / 365.25 if calendar_days > 0 else 1.0
- except (IndexError, TypeError):
- return 252
- return int(n / years) if years > 0 else 252
-
-
# ─── Runner integration ───
@@ -336,12 +316,12 @@ def run_validation(
v_cfg = config.get("validation", {})
results: Dict[str, Any] = {}
- # Cross-market convention (runner.py passes bars_per_year=None): derive
- # the effective bars per year from the observed calendar span, mirroring
- # calc_metrics — otherwise _sharpe's np.sqrt(bars_per_year) raises
- # TypeError for every validation-enabled cross-market run.
+ # Cross-market convention (runner.py passes bars_per_year=None): resolve
+ # it through the shared span-derived factor — otherwise _sharpe's
+ # np.sqrt(bars_per_year) raises TypeError for every validation-enabled
+ # cross-market run.
if bars_per_year is None:
- bars_per_year = _effective_bars_per_year(equity_curve)
+ bars_per_year = effective_bars_per_year(equity_curve.index)
if "monte_carlo" in v_cfg:
mc_cfg = v_cfg["monte_carlo"] if isinstance(v_cfg["monte_carlo"], dict) else {}
diff --git a/agent/tests/test_cross_market_annualization.py b/agent/tests/test_cross_market_annualization.py
new file mode 100644
index 000000000..b6940d0ca
--- /dev/null
+++ b/agent/tests/test_cross_market_annualization.py
@@ -0,0 +1,112 @@
+"""One annualisation convention for cross-market runs (issue #1237).
+
+A basket spanning markets has no single per-market bar count, so the runner
+passes ``bars_per_year=None`` (``runner.py``: *"Cross-market: use calendar-day
+annualization"*). Four consumers have to agree on what that means — portfolio
+metrics, the risk x-ray, options metrics, and validation — or one run card
+reports a Sharpe and an annualised volatility computed on different footings.
+
+These tests pin all four to ``metrics.effective_bars_per_year``. They fail if
+any consumer grows its own copy of the span derivation and drifts.
+"""
+
+from __future__ import annotations
+
+import math
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from backtest.engines.options_portfolio import _calc_options_metrics
+from backtest.metrics import calc_metrics, effective_bars_per_year
+from backtest.risk_xray import compute_risk_xray
+from backtest.validation import _sharpe, run_validation
+
+
+def _zigzag(n: int, base: float, step: float, period: int) -> list[float]:
+ """Prices with both up and down moves, so downside statistics exist."""
+ return [base + (i % period) * step - step * (period - 1) / 2 for i in range(n)]
+
+
+class TestEffectiveBarsPerYear:
+ def test_daily_bars_over_a_full_year(self):
+ idx = pd.date_range("2024-01-01", periods=253, freq="B")
+ span_years = (idx[-1] - idx[0]).days / 365.25
+ assert effective_bars_per_year(idx) == int(253 / span_years)
+
+ def test_span_shorter_than_a_day_counts_as_one_year(self):
+ # Two bars on the same calendar day: no measurable span, so the series
+ # annualises to itself rather than exploding on a near-zero divisor.
+ idx = pd.DatetimeIndex(["2024-01-01T09:30", "2024-01-01T15:00"])
+ assert effective_bars_per_year(idx) == 2
+
+ def test_empty_index_falls_back_to_default(self):
+ assert effective_bars_per_year(pd.DatetimeIndex([])) == 252
+ assert effective_bars_per_year(pd.DatetimeIndex([]), default=365) == 365
+
+ def test_non_datetime_index_has_no_measurable_span(self):
+ # An integer index carries no ``days``; the series annualises to its
+ # own length rather than raising.
+ assert effective_bars_per_year(pd.Index([0, 1, 2, 3])) == 4
+
+
+class TestConsumersShareTheConvention:
+ """Every ``bars_per_year=None`` consumer resolves the same factor."""
+
+ idx = pd.date_range("2024-01-01", periods=120, freq="B")
+
+ @property
+ def expected_bpy(self) -> int:
+ return effective_bars_per_year(self.idx)
+
+ def test_risk_xray(self):
+ closes = pd.DataFrame(
+ {
+ "AAA": _zigzag(120, 100.0, 2.0, 5),
+ "BBB": _zigzag(120, 50.0, 1.0, 7),
+ },
+ index=self.idx,
+ )
+ weights = {"AAA": 0.5, "BBB": 0.5}
+ result = compute_risk_xray(closes, weights, min_history=10, periods_per_year=None)
+
+ port = (closes.pct_change().dropna() * pd.Series(weights)).sum(axis=1)
+ expected = effective_bars_per_year(port.index)
+ assert result["volatility"]["annualized_vol"] == pytest.approx(
+ port.std(ddof=1) * math.sqrt(expected)
+ )
+
+ def test_options_metrics(self):
+ equity = pd.Series(_zigzag(120, 100_000.0, 500.0, 5), index=self.idx)
+ metrics = _calc_options_metrics(equity, 100_000.0, [], bars_per_year=None)
+
+ returns = equity.pct_change(fill_method=None).iloc[1:]
+ # Options metrics round their reported ratios to 4 decimals.
+ assert metrics["sharpe"] == pytest.approx(
+ returns.mean() / returns.std() * math.sqrt(self.expected_bpy), abs=5e-5
+ )
+
+ def test_validation(self):
+ equity = pd.Series(_zigzag(120, 100_000.0, 500.0, 5), index=self.idx)
+ result = run_validation(
+ {"validation": {"bootstrap": {"n_bootstrap": 10}}},
+ equity,
+ [],
+ 100_000.0,
+ bars_per_year=None,
+ )
+
+ returns = equity.pct_change().dropna().to_numpy()
+ assert result["bootstrap"]["observed_sharpe"] == pytest.approx(
+ round(_sharpe(returns, self.expected_bpy), 4)
+ )
+
+ def test_portfolio_metrics(self):
+ equity = pd.Series(np.linspace(100_000.0, 130_000.0, 120), index=self.idx)
+ metrics = calc_metrics(equity, [], 100_000.0, bars_per_year=None)
+
+ growth = 1.3
+ assert metrics["annual_return"] == pytest.approx(
+ growth ** (self.expected_bpy / 120) - 1, rel=1e-6
+ )