"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(runner): check the declared interval against the served bars before annualising
chiww2cb8bcd554f0
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex 9ee68e82d..52a059921 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -1281,13 +1281,14 @@ def main(run_dir: Path) -> None:# Annualization barseffective_source = _detect_primary_source(codes, source)- from backtest.metrics import calc_bars_per_year# Cross-market: use calendar-day annualization (bars_per_year=None)market_types = {_detect_market(c) for c in codes}if len(market_types) > 1:bars_per_year = Noneelse:- bars_per_year = calc_bars_per_year(interval, effective_source)+ bars_per_year = _annualisation_bars(+ interval, effective_source, data_map, codes+ )# Every source has already been fetched, sanitized, and enriched above.# Reuse that exact snapshot so provider costs and run-card provenance stay@@ -1302,6 +1303,70 @@ 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+++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.++ ``interval`` is what the caller asked for, not a fact about what arrived. A+ loader may legitimately serve coarser bars than requested -- the local+ loader cannot upsample a daily file to ``1H`` and says so only in a log+ 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.++ 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.++ Returns:+ The declared count, or the observed one when the two disagree by at+ least :data:`_ANNUALISATION_MISMATCH_RATIO`.+ """+ from backtest.metrics import calc_bars_per_year, effective_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:+ return declared+ index = max(indexes, key=len)+ observed = effective_bars_per_year(index, default=declared)+ if observed <= 0:+ return declared+ ratio = max(declared, observed) / min(declared, observed)+ if ratio < _ANNUALISATION_MISMATCH_RATIO:+ 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,+ )+ return observed++def _create_market_engine(source: str, config: dict, codes: List[str]):"""Create the appropriate market engine based on data source and market type.diff --git a/agent/tests/test_cross_market_annualization.py b/agent/tests/test_cross_market_annualization.pyindex b6940d0ca..b64fcf5db 100644--- a/agent/tests/test_cross_market_annualization.py+++ b/agent/tests/test_cross_market_annualization.py@@ -19,7 +19,7 @@ import pandas as pdimport pytestfrom backtest.engines.options_portfolio import _calc_options_metrics-from backtest.metrics import calc_metrics, effective_bars_per_year+from backtest.metrics import calc_bars_per_year, calc_metrics, effective_bars_per_yearfrom backtest.risk_xray import compute_risk_xrayfrom backtest.validation import _sharpe, run_validation@@ -110,3 +110,68 @@ class TestConsumersShareTheConvention:assert metrics["annual_return"] == pytest.approx(growth ** (self.expected_bpy / 120) - 1, rel=1e-6)+++class TestSingleMarketAnnualisationChecksTheServedData:+ """The declared interval is a request, not a fact about what arrived.++ A loader may legitimately serve coarser bars than asked for — the local+ 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.+ """++ @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 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)."""+ from backtest.runner import _annualisation_bars++ assert _annualisation_bars("1D", "tushare", self._daily(), ["600519.SH"]) == 252++ def test_declared_intraday_against_daily_bars_uses_the_observed_count(self):+ from backtest.runner import _annualisation_bars++ declared = calc_bars_per_year("1H", "tushare")+ resolved = _annualisation_bars("1H", "tushare", self._daily(), ["600519.SH"])++ 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)++ def test_crypto_daily_is_not_tripped_by_the_check(self):+ """365-day markets measure close to their declared count."""+ 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)}+ assert _annualisation_bars("1D", "okx", data, ["BTC-USDT"]) == 365++ @pytest.mark.parametrize("data", [{}, {"600519.SH": pd.DataFrame({"close": []})}])+ def test_unmeasurable_data_falls_back_to_the_declaration(self, data):+ from backtest.runner import _annualisation_bars++ assert _annualisation_bars("1D", "tushare", data, ["600519.SH"]) == 252++ def test_only_price_frames_are_measured(self):+ """Injected fundamental panels must not decide the annualisation."""+ from backtest.runner import _annualisation_bars++ data = self._daily()+ 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_mismatch_is_logged(self, caplog):+ from backtest.runner import _annualisation_bars++ with caplog.at_level("WARNING", logger="backtest.runner"):+ _annualisation_bars("1H", "tushare", self._daily(), ["600519.SH"])++ assert any("1H" in r.getMessage() for r in caplog.records)