"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): make the buy-and-hold return path sign-safe
Haozhe Wu452653c81c7a
diff --git a/agent/backtest/benchmark.py b/agent/backtest/benchmark.pyindex c9ed08815..0b5a68bad 100644--- a/agent/backtest/benchmark.py+++ b/agent/backtest/benchmark.py@@ -12,6 +12,7 @@ from typing import Any, Optionalimport pandas as pdfrom backtest.loaders.yfinance_loader import DataLoader as YfinanceLoader+from backtest.metrics import bar_returns, buy_and_hold_return# -------------------------------------------------------------------@@ -89,10 +90,15 @@ def resolve_benchmark(if len(close) < 2:return None- ret_series = close.pct_change().fillna(0.0)- total_ret = float((1 + ret_series).prod() - 1)+ ret_series = bar_returns(close, label=f"benchmark {ticker}")+ # Price relative, not the compounded product: identical while prices are+ # positive, and it is the only one of the two that stays honest once they+ # are not (#872).+ total = buy_and_hold_return(close)+ if total is None:+ return None- return BenchmarkResult(ticker=ticker, ret_series=ret_series, total_ret=total_ret)+ return BenchmarkResult(ticker=ticker, ret_series=ret_series, total_ret=total)# -------------------------------------------------------------------diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.pyindex 7e424872a..eefe99174 100644--- a/agent/backtest/engines/base.py+++ b/agent/backtest/engines/base.py@@ -35,6 +35,7 @@ from backtest.loaders.tushare_fundamentals import (enrich_price_frames_with_fundamentals,)from backtest.metrics import (+ bar_returns,by_exit_reason_stats,by_symbol_stats,calc_metrics,@@ -219,7 +220,7 @@ def _align(# Construct DataFrames for returnclose = pd.DataFrame(close_arr, index=dates, columns=codes)pos = pd.DataFrame(pos_arr, index=dates, columns=codes)- ret = close.pct_change().fillna(0.0)+ ret = bar_returns(close, label="engine per-symbol returns")if optimizer is not None:pos = optimizer(ret, pos, dates)diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.pyindex cc2caeec0..55712b976 100644--- a/agent/backtest/metrics.py+++ b/agent/backtest/metrics.py@@ -5,6 +5,7 @@ Provides annualisation helpers, trade statistics, and full metric calculation.from __future__ import annotations+import loggingfrom typing import Any, Dict, List, Optionalimport numpy as np@@ -70,6 +71,81 @@ def calc_bars_per_year(interval: str = "1D", source: str = "tushare") -> int:return trading_days * bars_per_day+# ─── Sign-safe returns ───++_log = logging.getLogger(__name__)+++def bar_returns(close: Any, *, label: str = "") -> Any:+ """Per-bar simple returns, defined only where the prior price is positive.++ ``close.pct_change()`` silently assumes ``price[t-1] > 0``. That holds for+ equities but not for instruments that can print zero or negative prices,+ such as European day-ahead power. As the divisor approaches zero an+ ordinary absolute move reads as an enormous *percentage* move, so a+ compounded aggregate explodes; at exactly zero the next bar is ``inf``,+ which ``fillna`` does not neutralise (it fills ``NaN``) and which collapses+ ``(1 + r).prod()`` to ``nan`` (#872).++ A return is therefore defined only when the previous price is finite and+ strictly positive. Otherwise it is undefined and reported as ``0.0``,+ never ``inf`` or ``nan``. For an all-positive series this is identical to+ ``pct_change().fillna(0.0)``, so ordinary equity/crypto runs are unchanged.++ Args:+ close: Raw price ``Series`` or per-symbol ``DataFrame``.+ label: Optional name used when warning about undefined bars.++ Returns:+ Returns aligned to ``close``, with the first bar ``0.0``.+ """+ prev = close.shift(1)+ positive_prev = prev.where(prev > 0)++ undefined = int((prev.notna() & ~(prev > 0)).to_numpy().sum())+ if undefined:+ # Silence is the actual hazard here: a wrong return is a wrong reported+ # number, not a crash, so the run has to say it defaulted.+ _log.warning(+ "%s: %d bar(s) follow a non-positive price; their return is "+ "undefined and reported as 0.0 (issue #872)",+ label or "returns",+ undefined,+ )++ # ``close / prev - 1`` is exactly the expression ``pct_change`` uses, kept+ # verbatim so results for positive series are bit-identical, not merely+ # equal to within floating-point error.+ ret = close / positive_prev - 1+ return ret.replace([np.inf, -np.inf], np.nan).fillna(0.0)+++def buy_and_hold_return(close: Any) -> Optional[float]:+ """Total buy-and-hold return as a price relative, not a compounded product.++ ``(1 + close.pct_change()).prod() - 1`` telescopes to ``P_end / P_start - 1``+ only while every price is positive; once a near-zero price enters the+ series the product diverges from what a held position actually earned. On+ the reproduction in #872 it reported ``+39,560%`` where the price relative+ gives ``-42.7%``. This computes the price relative directly, so the two+ agree exactly for ordinary series and it stays honest for the rest.++ Args:+ close: Raw price series, already ``dropna()``-ed.++ Returns:+ Total return, or ``None`` when the entry price is not strictly+ positive and no honest percentage exists.+ """+ if len(close) < 2:+ return None+ first = float(close.iloc[0])+ last = float(close.iloc[-1])+ if not (first > 0) or not np.isfinite(last):+ return None+ return last / first - 1.0++def win_rate_and_stats(trades: List[TradeRecord]) -> Dict[str, float]:"""Win rate and P&L statistics from completed trades.diff --git a/agent/tests/test_nonpositive_prices.py b/agent/tests/test_nonpositive_prices.pyindex 85c8ea012..69ff67264 100644--- a/agent/tests/test_nonpositive_prices.py+++ b/agent/tests/test_nonpositive_prices.py@@ -62,17 +62,21 @@ def test_allow_keeps_negatives_rejects_exact_zero() -> None:def test_why_loader_drops_exact_zero_inf_downstream() -> None:"""Pins *why* an exact-zero close is dropped at the loader, not kept.- Both the benchmark (``benchmark.py``) and the position simulation- (``engines/base.py``) compute per-bar returns as- ``close.pct_change().fillna(0.0)`` over a *raw* close series. If a ``0.00``- clear survived into that series, the bar *after* it divides by zero and- yields ``inf`` — and ``fillna(0.0)`` does not neutralize it (it fills NaN,- not inf), so the benchmark's ``(1 + r).prod()`` collapses to ``nan``.-- Negatives divide cleanly (engine sizing uses ``abs(price)``), so they are- kept; exact zero is genuinely undefined and is therefore rejected at the- loader *and* the engine. This test encodes that contract so the asymmetry- is not silently "fixed" by later relaxing the loader. See #571.+ A raw ``close.pct_change()`` over a series containing ``0.00`` yields+ ``inf`` on the *next* bar — ``fillna(0.0)`` fills NaN, not inf — so any+ compounded aggregate collapses to ``nan``. That is what this test+ demonstrates, and it is why #816 stopped at negatives.++ The production return path no longer has this hazard: #872 moved+ ``benchmark.py`` and ``engines/base.py`` onto+ :func:`backtest.metrics.bar_returns`, which defines a return only where the+ prior price is strictly positive and yields ``0.0`` otherwise. See+ ``test_nonpositive_returns.py`` for that contract.++ Exact zero is still rejected at the loader, but now for the one reason that+ survives: position sizing is ``target_notional / abs(price)``+ (``engines/base.py:478``), which is undefined at zero. Negatives divide+ cleanly and are therefore kept. See #571, #816, #872."""idx = pd.to_datetime(["2025-10-24", "2025-10-25", "2025-10-26", "2025-10-27"])diff --git a/agent/tests/test_nonpositive_returns.py b/agent/tests/test_nonpositive_returns.pynew file mode 100644index 000000000..4d4de761c--- /dev/null+++ b/agent/tests/test_nonpositive_returns.py@@ -0,0 +1,172 @@+"""Sign-safe returns: the buy-and-hold path must not assume positive prices.++Issue #872. ``close.pct_change()`` assumes ``price[t-1] > 0``. As the divisor+approaches zero an ordinary absolute move reads as an enormous percentage move,+so the compounded benchmark explodes (+39,560% on a real power-price run); at+exactly zero the next bar is ``inf``, which ``fillna(0.0)`` does not neutralise+and which collapses ``(1 + r).prod()`` to ``nan``.++Contract pinned here:++1. A return is defined only when the previous price is finite and strictly+ positive; otherwise it is ``0.0``, never ``inf``/``nan``.+2. Buy-and-hold total return is the price relative ``P_end / P_start - 1``,+ which is bit-identical to the old compounded product while prices are+ positive, and is ``None`` when the entry price is not positive.+3. Undefined bars are logged, not silently swallowed.+"""++from __future__ import annotations++import logging+from pathlib import Path++import numpy as np+import pandas as pd+import pytest++from backtest.metrics import bar_returns, buy_and_hold_return++FIXTURE = Path(__file__).parent / "fixtures" / "negative_close_bars.csv"+++def delu() -> pd.Series:+ """The four DE-LU non-positive closes from the #816 fixture."""+ df = pd.read_csv(FIXTURE, comment="#")+ return (+ df[df.code == "POWER-DA-DELU"]+ .sort_values("trade_date")+ .set_index("trade_date")["close"]+ )+++# ---------------------------------------------------------------------------+# No behaviour change for ordinary, strictly positive series+# ---------------------------------------------------------------------------++[email protected]("n", [2, 5, 50, 500])+def test_positive_series_are_bit_identical_to_pct_change(n: int) -> None:+ """Equities and crypto must be untouched — not close, identical."""+ prices = pd.Series(np.random.default_rng(7).uniform(1.0, 400.0, n))++ assert (+ bar_returns(prices).to_numpy() == prices.pct_change().fillna(0.0).to_numpy()+ ).all()+++def test_positive_frames_are_bit_identical_to_pct_change() -> None:+ prices = pd.DataFrame(+ np.random.default_rng(11).uniform(1.0, 400.0, (200, 4)), columns=list("ABCD")+ )++ assert (+ bar_returns(prices).to_numpy() == prices.pct_change().fillna(0.0).to_numpy()+ ).all()+++def test_buy_and_hold_equals_the_compounded_product_when_prices_are_positive() -> None:+ """The price relative is what the old product telescoped to all along."""+ prices = pd.Series(np.random.default_rng(3).uniform(1.0, 400.0, 300))++ compounded = float((1 + prices.pct_change().fillna(0.0)).prod() - 1)++ assert buy_and_hold_return(prices) == pytest.approx(compounded)+++# ---------------------------------------------------------------------------+# Symptom A — a near-zero divisor exploded the percentage return+# ---------------------------------------------------------------------------+++def test_near_zero_prior_close_no_longer_explodes(delu: pd.Series) -> None:+ """-0.02 -> -1.03 read as +5050% purely because the divisor was near zero."""+ assert delu.pct_change().fillna(0.0).loc["2025-10-04"] == pytest.approx(50.5)++ assert bar_returns(delu).loc["2025-10-04"] == 0.0+++def test_compounded_aggregate_no_longer_explodes(delu: pd.Series) -> None:+ pre_zero = delu.iloc[:-1]+ assert float((1 + pre_zero.pct_change().fillna(0.0)).prod() - 1) == pytest.approx(+ 10.444, rel=1e-3+ )++ assert (bar_returns(pre_zero) == 0.0).all()+++# ---------------------------------------------------------------------------+# Symptom B — an exact-zero close produced inf, then nan+# ---------------------------------------------------------------------------+++def test_bar_after_an_exact_zero_is_finite(delu: pd.Series) -> None:+ series = pd.concat([delu, pd.Series({"2025-10-27": 42.0})])++ assert np.isinf(series.pct_change().fillna(0.0).iloc[-1])++ result = bar_returns(series)+ assert result.iloc[-1] == 0.0+ assert np.isfinite(result.to_numpy()).all()+++def test_compounded_aggregate_stays_finite_through_zero(delu: pd.Series) -> None:+ series = pd.concat([delu, pd.Series({"2025-10-27": 42.0})])+ with np.errstate(invalid="ignore"):+ assert not np.isfinite(float((1 + series.pct_change().fillna(0.0)).prod()))++ assert np.isfinite(float((1 + bar_returns(series)).prod()))+++def test_zero_prices_do_not_leak_through_a_frame() -> None:+ """The engine's per-symbol matrix feeds optimizers and correlation math."""+ frame = pd.DataFrame({"A": [10.0, 0.0, 42.0], "B": [1.0, 2.0, 4.0]})++ result = bar_returns(frame)++ assert np.isfinite(result.to_numpy()).all()+ assert result["A"].tolist() == [0.0, -1.0, 0.0]+ # An unaffected symbol keeps its ordinary returns.+ assert result["B"].tolist() == [0.0, 1.0, 1.0]+++# ---------------------------------------------------------------------------+# buy_and_hold_return contract+# ---------------------------------------------------------------------------+++def test_buy_and_hold_is_none_without_a_positive_entry_price(delu: pd.Series) -> None:+ """No honest percentage exists, so report nothing rather than a number."""+ assert buy_and_hold_return(delu) is None+++def test_buy_and_hold_is_none_for_a_series_too_short_to_move() -> None:+ assert buy_and_hold_return(pd.Series([42.0])) is None+++def test_buy_and_hold_survives_a_negative_bar_mid_series() -> None:+ """Entry and exit are positive, so the held position has a real return."""+ prices = pd.Series([100.0, -5.0, 0.0, 80.0])++ assert buy_and_hold_return(prices) == pytest.approx(-0.2)+++# ---------------------------------------------------------------------------+# Undefined bars must be loud+# ---------------------------------------------------------------------------+++def test_undefined_bars_are_logged(delu: pd.Series, caplog) -> None:+ with caplog.at_level(logging.WARNING, logger="backtest.metrics"):+ bar_returns(delu, label="DE-LU")++ assert "DE-LU" in caplog.text+ assert "3 bar(s) follow a non-positive price" in caplog.text+++def test_clean_series_log_nothing(caplog) -> None:+ with caplog.at_level(logging.WARNING, logger="backtest.metrics"):+ bar_returns(pd.Series([1.0, 2.0, 3.0]), label="SPY")++ assert caplog.text == ""