Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(runner): compare bar spacing, not bars per calendar year

chiwwe85e7c9416a6
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index 52a059921..18efc2b24 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -1303,18 +1303,60 @@ def main(run_dir: Path) -> None:
market_engine.run_backtest(config, loader, signal_engine, run_dir, bars_per_year=bars_per_year)
-#: How far the declared interval's bar count may sit from the count actually
-#: observed before the declaration is treated as wrong. Neighbouring intervals
-#: differ by at least 2x (``30m`` -> ``1H``), while the calendar-vs-trading-day
-#: spread inside one interval is a few percent (a business-daily series measures
-#: ~261 against a declared 252), so 1.5 separates the two cases cleanly.
-_ANNUALISATION_MISMATCH_RATIO = 1.5
+#: Bar spacing, in seconds, of every interval the runner accepts
+#: (:data:`_VALID_INTERVALS`). Seconds rather than ``Timedelta`` so the
+#: comparison below is a ratio of two numbers.
+_INTERVAL_SECONDS: dict[str, float] = {
+ "1m": 60.0,
+ "5m": 300.0,
+ "15m": 900.0,
+ "30m": 1_800.0,
+ "1H": 3_600.0,
+ "4H": 14_400.0,
+ "1D": 86_400.0,
+}
+
+#: How far the served bar spacing may sit from the declared interval's spacing
+#: before the declaration is treated as wrong. The closest pair of intervals
+#: differs by 2x (``30m`` -> ``1H``), while a correctly served series measures
+#: its own spacing exactly, so 1.5 separates the two cases with room to spare.
+_SPACING_MISMATCH_RATIO = 1.5
+
+#: Fewest bars whose median spacing is trustworthy. Sessions leave gaps -- a
+#: daily series jumps three days over a weekend -- and the median only absorbs
+#: them once they are outnumbered. Three differences survive one gap
+#: (``[1, 1, 3]`` -> 1 day); two do not (``[1, 3]`` -> 2 days).
+_MIN_BARS_FOR_SPACING = 4
+
+
+def _observed_spacing(data_map: dict, codes: List[str]) -> float | None:
+ """Median spacing of the served price bars in seconds, or None when
+ unmeasurable.
+
+ The median, not the span: a session index is mostly regular with occasional
+ gaps (weekends, overnight, a trading halt), and the median reports the
+ regular part. Only the instrument codes are measured, so an injected
+ fundamental panel cannot decide the annualisation.
+ """
+ indexes = [
+ data_map[code].index
+ for code in codes
+ if code in data_map and len(data_map[code]) >= _MIN_BARS_FOR_SPACING
+ ]
+ if not indexes:
+ return None
+ index = max(indexes, key=len)
+ spacing = pd.Series(index).diff().dropna().median()
+ if pd.isna(spacing):
+ return None
+ seconds = spacing.total_seconds()
+ return seconds if seconds > 0 else None
def _annualisation_bars(
interval: str, source: str, data_map: dict, codes: List[str]
) -> int:
- """Bars per year for a single-market run, checked against the served data.
+ """Bars per year for a single-market run, checked against the served bars.
``interval`` is what the caller asked for, not a fact about what arrived. A
loader may legitimately serve coarser bars than requested -- the local
@@ -1322,49 +1364,68 @@ def _annualisation_bars(
warning -- and annualising at the declared rate then scales CAGR, Sharpe and
the annualised volatility by the ratio between the two.
- Measuring the served index is the convention
- :func:`~backtest.metrics.effective_bars_per_year` already applies to
- cross-market runs. Here it is used as a *check* rather than a replacement,
- so a correctly served single-market run keeps the per-source trading-day
- table it has always had and no existing run card moves.
+ The comparison is on bar **spacing**, not on bars per calendar year. A
+ calendar-year count is a property of the window as much as of the data:
+ weekends and overnight gaps dominate a short span, so five daily bars
+ starting on a Monday measure 456 against a declared 252 while the same five
+ bars starting on a Tuesday measure 304 -- one trips a 1.5 gate and the other
+ does not, for the same correctly served series. Median spacing is one day
+ for a daily series whether the window holds five bars or five years, and one
+ hour for hourly bars regardless of session length or 24x7 trading.
+
+ On a mismatch the count still comes from
+ :func:`~backtest.metrics.calc_bars_per_year` -- looked up with the interval
+ the spacing actually matches -- so the per-source trading-day table keeps
+ producing the number and a run card never picks up a window-dependent one.
Args:
interval: Bar size the caller declared.
source: Primary source name, for the per-source trading-day table.
data_map: Fetched ``code -> frame`` map.
- codes: The instrument codes, so injected fundamental panels stay out
- of the measurement.
+ codes: The instrument codes.
Returns:
- The declared count, or the observed one when the two disagree by at
- least :data:`_ANNUALISATION_MISMATCH_RATIO`.
+ Bars per year for the declared interval, or for the interval the served
+ spacing matches when the two disagree.
"""
- from backtest.metrics import calc_bars_per_year, effective_bars_per_year
+ from backtest.metrics import _normalize_interval, calc_bars_per_year
declared = calc_bars_per_year(interval, source)
- indexes = [
- data_map[code].index
- for code in codes
- if code in data_map and len(data_map[code]) >= 2
- ]
- if not indexes:
+ declared_spacing = _INTERVAL_SECONDS.get(_normalize_interval(interval))
+ observed = _observed_spacing(data_map, codes)
+ if declared_spacing is None or observed is None:
return declared
- index = max(indexes, key=len)
- observed = effective_bars_per_year(index, default=declared)
- if observed <= 0:
+ if max(declared_spacing, observed) / min(declared_spacing, observed) < _SPACING_MISMATCH_RATIO:
return declared
- ratio = max(declared, observed) / min(declared, observed)
- if ratio < _ANNUALISATION_MISMATCH_RATIO:
+
+ matched = min(
+ _INTERVAL_SECONDS,
+ key=lambda name: max(_INTERVAL_SECONDS[name], observed)
+ / min(_INTERVAL_SECONDS[name], observed),
+ )
+ matched_spacing = _INTERVAL_SECONDS[matched]
+ if max(matched_spacing, observed) / min(matched_spacing, observed) >= _SPACING_MISMATCH_RATIO:
+ # Spacing that is no supported interval (a weekly file, say). Naming a
+ # bar count for it would be a guess, so the declaration stands and the
+ # mismatch is reported instead.
+ logger.warning(
+ "interval=%s declares bars spaced %.0fs but the served data is "
+ "spaced %.0fs, which matches no supported interval; annualising at "
+ "the declared rate. Check the earlier loader warning and re-run at "
+ "the granularity the source actually has.",
+ interval, declared_spacing, observed,
+ )
return declared
+
logger.warning(
- "interval=%s declares %d bars/year but the served data measures %d "
- "(%d bars over %d days); annualising on the served data. The loader "
- "returned bars coarser or finer than requested -- check the earlier "
- "loader warning, and set interval to the granularity the source "
- "actually has.",
- interval, declared, observed, len(index), (index[-1] - index[0]).days,
+ "interval=%s declares bars spaced %.0fs but the served data is spaced "
+ "%.0fs; annualising as %s (%d bars/year) instead of %d. The loader returned "
+ "bars coarser or finer than requested -- check the earlier loader "
+ "warning, and set interval to the granularity the source actually has.",
+ interval, declared_spacing, observed, matched,
+ calc_bars_per_year(matched, source), declared,
)
- return observed
+ return calc_bars_per_year(matched, source)
def _create_market_engine(source: str, config: dict, codes: List[str]):
diff --git a/agent/tests/test_cross_market_annualization.py b/agent/tests/test_cross_market_annualization.py
index b64fcf5db..d97a8be31 100644
--- a/agent/tests/test_cross_market_annualization.py
+++ b/agent/tests/test_cross_market_annualization.py
@@ -119,40 +119,123 @@ class TestSingleMarketAnnualisationChecksTheServedData:
loader cannot upsample a daily file to ``1H`` and only logs a warning —
and annualising at the declared rate then scales CAGR, Sharpe and the
annualised volatility by the ratio between the two.
+
+ The comparison is on bar *spacing*, not on bars per calendar year: a
+ calendar-year count is a property of the window as much as of the data,
+ so it flags correctly served short runs (see the window-length tests).
"""
@staticmethod
- def _daily(n: int = 654) -> dict:
- idx = pd.date_range("2024-01-02", periods=n, freq="B")
- return {"600519.SH": pd.DataFrame({"close": [10.0] * n}, index=idx)}
+ def _frame(index) -> dict:
+ return {"600519.SH": pd.DataFrame({"close": [10.0] * len(index)}, index=index)}
+
+ @staticmethod
+ def _session(days: int, per_day: int, freq: str, start: str = "2026-09-07") -> pd.DatetimeIndex:
+ """Intraday bars inside a trading session, so the index carries the
+ overnight gaps a real one does."""
+ stamps: list[pd.Timestamp] = []
+ for day in pd.bdate_range(start, periods=days):
+ stamps += list(
+ pd.date_range(day.replace(hour=9, minute=30), periods=per_day, freq=freq)
+ )
+ return pd.DatetimeIndex(stamps)
def test_matching_declaration_keeps_the_per_source_table(self):
- """A correctly served run must keep the trading-day table it always had,
- not drift to the measured count (252 declared vs ~261 measured)."""
+ """A correctly served run keeps the trading-day table it always had,
+ rather than drifting to a count measured off its own window."""
+ from backtest.runner import _annualisation_bars
+
+ data = self._frame(pd.date_range("2024-01-02", periods=654, freq="B"))
+ assert _annualisation_bars("1D", "tushare", data, ["600519.SH"]) == 252
+
+ def test_declared_intraday_against_daily_bars_uses_the_matched_interval(self):
+ """The corrected count still comes from the per-source table, looked up
+ with the interval the spacing actually matches."""
+ from backtest.runner import _annualisation_bars
+
+ data = self._frame(pd.date_range("2024-01-02", periods=654, freq="B"))
+ resolved = _annualisation_bars("1H", "tushare", data, ["600519.SH"])
+
+ assert calc_bars_per_year("1H", "tushare") > 1000 # the declaration is intraday
+ assert resolved == calc_bars_per_year("1D", "tushare") == 252
+
+ # --- window length must not decide the outcome (issue found in review) ---
+
+ def test_five_daily_bars_keep_the_declared_count(self):
+ """Five bars is a quick check, not a granularity change."""
from backtest.runner import _annualisation_bars
- assert _annualisation_bars("1D", "tushare", self._daily(), ["600519.SH"]) == 252
+ data = self._frame(pd.bdate_range("2026-09-08", periods=5))
+ assert _annualisation_bars("1D", "yahoo", data, ["600519.SH"]) == 252
- def test_declared_intraday_against_daily_bars_uses_the_observed_count(self):
+ def test_five_daily_bars_starting_monday_keep_the_declared_count(self):
+ """Calendar alignment must not change the verdict: a Monday-start week
+ spans four calendar days and a Tuesday-start week spans six, so a
+ bars-per-calendar-year measurement flags one and not the other."""
from backtest.runner import _annualisation_bars
- declared = calc_bars_per_year("1H", "tushare")
- resolved = _annualisation_bars("1H", "tushare", self._daily(), ["600519.SH"])
+ monday = pd.bdate_range("2026-09-07", periods=5)
+ assert monday[0].day_name() == "Monday"
+ assert (monday[-1] - monday[0]).days == 4
- assert declared > 1000 # the declaration is intraday
- assert resolved < 400 # the data is not
- assert resolved == effective_bars_per_year(self._daily()["600519.SH"].index)
+ data = self._frame(monday)
+ assert _annualisation_bars("1D", "yahoo", data, ["600519.SH"]) == 252
+
+ def test_one_week_of_hourly_bars_keeps_the_declared_count(self):
+ from backtest.runner import _annualisation_bars
+
+ data = self._frame(self._session(days=5, per_day=7, freq="1h"))
+ declared = calc_bars_per_year("1H", "yahoo")
+ assert _annualisation_bars("1H", "yahoo", data, ["600519.SH"]) == declared
+
+ def test_one_session_of_minute_bars_keeps_the_declared_count(self):
+ from backtest.runner import _annualisation_bars
+
+ data = self._frame(self._session(days=1, per_day=390, freq="1min"))
+ declared = calc_bars_per_year("1m", "yahoo")
+ assert _annualisation_bars("1m", "yahoo", data, ["600519.SH"]) == declared
+
+ # --- session shapes that a spacing measurement must tolerate ---
+
+ def test_a_share_four_hour_session_keeps_the_declared_count(self):
+ from backtest.runner import _annualisation_bars
+
+ data = self._frame(self._session(days=5, per_day=4, freq="1h"))
+ assert _annualisation_bars("1H", "tushare", data, ["600519.SH"]) == \
+ calc_bars_per_year("1H", "tushare")
+
+ def test_a_trading_halt_does_not_change_the_verdict(self):
+ """The median reports the regular spacing; one long gap cannot outvote it."""
+ from backtest.runner import _annualisation_bars
+
+ index = pd.bdate_range("2025-01-06", periods=60).append(
+ pd.bdate_range("2025-08-01", periods=60)
+ )
+ assert _annualisation_bars("1D", "tushare", self._frame(index), ["600519.SH"]) == 252
def test_crypto_daily_is_not_tripped_by_the_check(self):
- """365-day markets measure close to their declared count."""
+ """365-day markets keep their own table entry."""
from backtest.runner import _annualisation_bars
n = 700
- idx = pd.date_range("2024-01-02", periods=n, freq="D")
- data = {"BTC-USDT": pd.DataFrame({"close": [10.0] * n}, index=idx)}
+ data = {"BTC-USDT": pd.DataFrame(
+ {"close": [10.0] * n}, index=pd.date_range("2024-01-02", periods=n, freq="D")
+ )}
assert _annualisation_bars("1D", "okx", data, ["BTC-USDT"]) == 365
- @pytest.mark.parametrize("data", [{}, {"600519.SH": pd.DataFrame({"close": []})}])
+ # --- degenerate inputs ---
+
+ @pytest.mark.parametrize(
+ "data",
+ [
+ {},
+ {"600519.SH": pd.DataFrame({"close": []})},
+ # Too few bars for a median that survives a weekend gap.
+ {"600519.SH": pd.DataFrame(
+ {"close": [1.0, 2.0]}, index=pd.to_datetime(["2026-09-11", "2026-09-14"])
+ )},
+ ],
+ )
def test_unmeasurable_data_falls_back_to_the_declaration(self, data):
from backtest.runner import _annualisation_bars
@@ -162,16 +245,28 @@ class TestSingleMarketAnnualisationChecksTheServedData:
"""Injected fundamental panels must not decide the annualisation."""
from backtest.runner import _annualisation_bars
- data = self._daily()
+ data = self._frame(pd.date_range("2024-01-02", periods=654, freq="B"))
data["_fundamentals"] = pd.DataFrame(
{"pe": [1.0] * 5}, index=pd.date_range("2024-01-02", periods=5, freq="YE")
)
assert _annualisation_bars("1D", "tushare", data, ["600519.SH"]) == 252
+ def test_unsupported_spacing_keeps_the_declaration_and_says_so(self, caplog):
+ """Weekly bars match no supported interval; naming a count would guess."""
+ from backtest.runner import _annualisation_bars
+
+ data = self._frame(pd.date_range("2024-01-05", periods=60, freq="W-FRI"))
+ with caplog.at_level("WARNING", logger="backtest.runner"):
+ resolved = _annualisation_bars("1D", "tushare", data, ["600519.SH"])
+
+ assert resolved == 252
+ assert any("matches no supported interval" in r.getMessage() for r in caplog.records)
+
def test_mismatch_is_logged(self, caplog):
from backtest.runner import _annualisation_bars
+ data = self._frame(pd.date_range("2024-01-02", periods=654, freq="B"))
with caplog.at_level("WARNING", logger="backtest.runner"):
- _annualisation_bars("1H", "tushare", self._daily(), ["600519.SH"])
+ _annualisation_bars("1H", "tushare", data, ["600519.SH"])
assert any("1H" in r.getMessage() for r in caplog.records)