Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): seed per-bar returns with initial cash (#1843)

Yufeng He74410a9331df
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index ab850a198..3260f88d3 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -44,6 +44,7 @@ from backtest.metrics import (
by_symbol_stats,
calc_fill_turnover_series,
calc_metrics,
+ period_returns,
)
from backtest.models import EquitySnapshot, FillRecord, Position, TradeRecord
from backtest.rebalance_mask import (
@@ -2276,8 +2277,9 @@ class BaseEngine(ABC):
for code, df in data_map.items():
df.to_csv(out / f"ohlcv_{code}.csv")
- # Equity curve
- port_ret = equity_series.pct_change().fillna(0.0)
+ # Equity curve. Same cash-seeded returns as calc_metrics, so the ret
+ # column compounds back to total_return and agrees with drawdown.
+ port_ret = period_returns(equity_series, self.initial_capital).fillna(0.0)
# Same high-water mark as calc_metrics: the account holds initial_capital
# before the first recorded bar, so a loss on that bar is a drawdown too.
peak = equity_series.cummax().clip(lower=float(self.initial_capital))
diff --git a/agent/backtest/engines/options_portfolio.py b/agent/backtest/engines/options_portfolio.py
index f016c872a..a29f9c69c 100644
--- a/agent/backtest/engines/options_portfolio.py
+++ b/agent/backtest/engines/options_portfolio.py
@@ -29,7 +29,7 @@ import numpy as np
import pandas as pd
from backtest.engines.base import evaluation_start_index
-from backtest.metrics import effective_bars_per_year
+from backtest.metrics import effective_bars_per_year, period_returns
from src.quantlib.options import bs_greeks, bs_price, normalise_option_type
@@ -781,7 +781,10 @@ def _calc_options_metrics(
returns: pd.Series | None = None
if n >= 2 and path_is_finite:
- candidate_returns = equity_vals.pct_change(fill_method=None).iloc[1:]
+ # Seeded with the pre-first-bar cash mark, same convention as
+ # calc_metrics: the drawdown path below already counts that bar's
+ # loss, so the risk ratios must see it too.
+ candidate_returns = period_returns(equity_vals, initial_cash)
if np.isfinite(candidate_returns.to_numpy()).all():
returns = candidate_returns
else:
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.py
index d05b5d64c..d5e50cad2 100644
--- a/agent/backtest/metrics.py
+++ b/agent/backtest/metrics.py
@@ -535,6 +535,22 @@ def calc_fill_turnover_series(
return (traded_margin / denominator).replace([np.inf, -np.inf], np.nan).fillna(0.0)
+def period_returns(equity_curve: pd.Series, initial_cash: float) -> pd.Series:
+ """Per-bar returns seeded with the pre-first-bar cash mark.
+
+ The account holds ``initial_cash`` before the first recorded bar, so the
+ first return measures that bar's fill from cash rather than starting the
+ series at a hard zero. ``prod(1 + r) - 1`` then reproduces
+ ``equity[-1] / initial_cash - 1`` exactly, which is what ``total_return``
+ and the drawdown path already assume. When the first bar carries no fill
+ (equity == cash) the seed is 0 and the series matches a plain pct_change.
+ """
+ ret = equity_curve.pct_change(fill_method=None)
+ if len(ret) and np.isfinite(initial_cash) and initial_cash > 0:
+ ret.iloc[0] = equity_curve.iloc[0] / float(initial_cash) - 1.0
+ return ret
+
+
def calc_metrics(
equity_curve: pd.Series,
trades: List[TradeRecord],
@@ -572,7 +588,7 @@ def calc_metrics(
else:
bpy = bars_per_year
- port_ret = equity_curve.pct_change().fillna(0.0)
+ port_ret = period_returns(equity_curve, initial_cash).fillna(0.0)
# Equity that touches zero then recovers (100 → 0 → 50) yields non-finite
# pct_change values; options metrics already skip risk ratios in that case.
returns_finite = bool(np.isfinite(port_ret.to_numpy(dtype=float, copy=False)).all())
diff --git a/agent/backtest/validation.py b/agent/backtest/validation.py
index 79b1aa034..6151dc6f3 100644
--- a/agent/backtest/validation.py
+++ b/agent/backtest/validation.py
@@ -20,7 +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.metrics import effective_bars_per_year, period_returns
from backtest.models import TradeRecord
@@ -147,6 +147,7 @@ def bootstrap_sharpe_ci(
confidence: float = 0.95,
bars_per_year: int = 252,
seed: int = 42,
+ initial_capital: float | None = None,
) -> Dict[str, Any]:
"""Resample daily returns to estimate Sharpe confidence interval.
@@ -156,6 +157,11 @@ def bootstrap_sharpe_ci(
confidence: Confidence level (e.g. 0.95 for 95% CI).
bars_per_year: Annualisation factor.
seed: Random seed.
+ initial_capital: Starting capital. When given, the first return is
+ measured from this cash mark (the calc_metrics convention), so
+ ``observed_sharpe`` agrees with the report's own Sharpe on paths
+ whose first recorded bar carries real PnL. None keeps the legacy
+ adjacent-pair series.
Returns:
Dict with observed_sharpe, ci_lower, ci_upper, median_sharpe,
@@ -173,9 +179,13 @@ def bootstrap_sharpe_ci(
if isinstance(seed, bool) or not isinstance(seed, Integral) or seed < 0:
return {"error": f"seed must be >= 0, got {seed}"}
+ if initial_capital is not None:
+ series = period_returns(equity_curve, initial_capital)
+ else:
+ series = equity_curve.pct_change(fill_method=None)
# Missing equity is not a flat observation or a one-period recovery return.
returns = (
- equity_curve.pct_change(fill_method=None)
+ series
.replace([np.inf, -np.inf], 0.0)
.dropna()
.values
@@ -364,6 +374,7 @@ def run_validation(
n_bootstrap=bs_cfg.get("n_bootstrap", 1000),
confidence=bs_cfg.get("confidence", 0.95),
seed=bs_cfg.get("seed", 42),
+ initial_capital=initial_capital,
)
if "walk_forward" in v_cfg:
diff --git a/agent/tests/test_cross_market_annualization.py b/agent/tests/test_cross_market_annualization.py
index 4c117eb57..c5cdd2be6 100644
--- a/agent/tests/test_cross_market_annualization.py
+++ b/agent/tests/test_cross_market_annualization.py
@@ -19,7 +19,7 @@ import pandas as pd
import pytest
from backtest.engines.options_portfolio import _calc_options_metrics
-from backtest.metrics import calc_bars_per_year, calc_metrics, effective_bars_per_year
+from backtest.metrics import calc_bars_per_year, calc_metrics, effective_bars_per_year, period_returns
from backtest.risk_xray import compute_risk_xray
from backtest.validation import _sharpe, run_validation
@@ -81,7 +81,7 @@ class TestConsumersShareTheConvention:
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:]
+ returns = period_returns(equity, 100_000.0)
# 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
@@ -97,7 +97,7 @@ class TestConsumersShareTheConvention:
bars_per_year=None,
)
- returns = equity.pct_change().dropna().to_numpy()
+ returns = period_returns(equity, 100_000.0).to_numpy()
assert result["bootstrap"]["observed_sharpe"] == pytest.approx(
round(_sharpe(returns, self.expected_bpy), 4)
)
diff --git a/agent/tests/test_equity_artifact_drawdown.py b/agent/tests/test_equity_artifact_drawdown.py
index 905287245..9a9deb533 100644
--- a/agent/tests/test_equity_artifact_drawdown.py
+++ b/agent/tests/test_equity_artifact_drawdown.py
@@ -74,3 +74,33 @@ def test_equity_csv_drawdown_counts_a_loss_on_the_first_bar(tmp_path: Path) -> N
assert metrics["max_drawdown"] == pytest.approx(-0.10)
assert equity["drawdown"].tolist() == pytest.approx([-0.10, -0.05, 0.0])
assert equity["drawdown"].min() == pytest.approx(metrics["max_drawdown"])
+
+
+def test_equity_csv_ret_column_is_seeded_with_initial_cash(tmp_path: Path) -> None:
+ dates = pd.bdate_range("2025-01-06", periods=5)
+ # Same fill pattern as the drawdown test: the first evaluated bar loses 10%.
+ frame = pd.DataFrame(
+ {
+ "open": [100.0, 100.0, 100.0, 95.0, 100.0],
+ "close": [100.0, 100.0, 90.0, 95.0, 100.0],
+ },
+ index=dates,
+ )
+ metrics = _Engine({"initial_cash": 100_000.0}).run_backtest(
+ {
+ "codes": ["AAA"],
+ "start_date": str(dates[0].date()),
+ "end_date": str(dates[-1].date()),
+ "warmup_bars": 2,
+ },
+ _Loader({"AAA": frame}),
+ _AlwaysLong(),
+ tmp_path,
+ )
+ equity = pd.read_csv(tmp_path / "artifacts" / "equity.csv", index_col="timestamp")
+
+ # Row by row the ret column must agree with the drawdown column, and the
+ # series must compound back to the reported total return.
+ assert equity["ret"].iloc[0] == pytest.approx(-0.10)
+ compounded = float((1 + equity["ret"]).prod() - 1)
+ assert compounded == pytest.approx(metrics["total_return"])
diff --git a/agent/tests/test_options_portfolio_correctness.py b/agent/tests/test_options_portfolio_correctness.py
index 3659be1d5..b0664a9c0 100644
--- a/agent/tests/test_options_portfolio_correctness.py
+++ b/agent/tests/test_options_portfolio_correctness.py
@@ -195,11 +195,11 @@ def test_profit_loss_ratio_zero_without_closed_trades() -> None:
@pytest.mark.parametrize(
"values,mean_return,downside_mean_square",
[
- ([100.0, 99.0, 98.01, 100.9503], 0.01 / 3, 0.0002 / 3),
- ([100.0, 99.0, 101.97], 0.01, 0.0001 / 2),
- ([100.0, 99.0, 97.02, 102.8412], 0.01, 0.0005 / 3),
- ([100.0, 99.0, 98.01], -0.01, 0.0001),
- ([100.0, 99.0], -0.01, 0.0001),
+ ([100.0, 99.0, 98.01, 100.9503], 0.01 / 4, 0.0002 / 4),
+ ([100.0, 99.0, 101.97], 0.02 / 3, 0.0001 / 3),
+ ([100.0, 99.0, 97.02, 102.8412], 0.03 / 4, 0.0005 / 4),
+ ([100.0, 99.0, 98.01], -0.02 / 3, 0.0002 / 3),
+ ([100.0, 99.0], -0.01 / 2, 0.0001 / 2),
],
ids=["equal-losses", "single-loss", "unequal-losses", "all-losses", "one-period"],
)
@@ -214,8 +214,9 @@ def test_sortino_uses_full_sample_downside_deviation(
)
metrics = _calc_options_metrics(equity, 100.0, [], bars_per_year=bars_per_year)
- # Hand-derived moments use observed period returns, with no initial zero.
- # For daily observations the existing span convention counts all equity bars.
+ # Hand-derived moments use the cash-seeded period returns. equity[0] equals
+ # initial_cash in every case here, so the seed contributes one 0.0
+ # observation: every legacy denominator grows by one.
annualization = bars_per_year
if annualization is None:
annualization = int(len(values) * 365.25 / (len(values) - 1))
diff --git a/agent/tests/test_period_returns.py b/agent/tests/test_period_returns.py
new file mode 100644
index 000000000..80c2ba918
--- /dev/null
+++ b/agent/tests/test_period_returns.py
@@ -0,0 +1,106 @@
+"""Per-bar returns are seeded with the pre-first-bar cash mark.
+
+The account holds ``initial_cash`` before the first recorded bar, and the
+drawdown path already measures from that mark (#1750, #1818). The return
+series behind the risk ratios and the ``ret`` column in equity.csv used to
+start at a hard zero instead, so a first-bar loss never reached Sharpe or
+Sortino and ``prod(1 + ret) - 1`` disagreed with ``total_return``.
+"""
+
+from __future__ import annotations
+
+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, period_returns
+from backtest.validation import _sharpe, bootstrap_sharpe_ci
+
+
+def _curve(values):
+ return pd.Series(
+ values,
+ index=pd.bdate_range("2025-01-06", periods=len(values)),
+ dtype=float,
+ )
+
+
+def test_first_bar_loss_is_the_first_return() -> None:
+ # Bought at the first bar's open, marked 10% down, then recovered.
+ ret = period_returns(_curve([90_000.0, 95_000.0, 100_000.0]), 100_000.0)
+ assert ret.iloc[0] == pytest.approx(-0.10)
+ assert ret.iloc[1] == pytest.approx(95_000.0 / 90_000.0 - 1)
+ assert ret.iloc[2] == pytest.approx(100_000.0 / 95_000.0 - 1)
+
+
+def test_seeded_returns_compound_back_to_total_return() -> None:
+ equity = _curve([90_000.0, 95_000.0, 100_000.0, 97_000.0, 103_000.0])
+ ret = period_returns(equity, 100_000.0)
+ assert float((1 + ret).prod() - 1) == pytest.approx(0.03)
+ metrics = calc_metrics(equity, [], 100_000.0, bars_per_year=252)
+ assert metrics["total_return"] == pytest.approx(0.03)
+
+
+def test_first_bar_loss_reaches_the_risk_ratios() -> None:
+ equity = _curve([90_000.0, 95_000.0, 100_000.0])
+ metrics = calc_metrics(equity, [], 100_000.0, bars_per_year=252)
+ # Before the seed this path reported sharpe ~18 and sortino ~3e9 because
+ # the only losing move was missing from the series.
+ assert metrics["sharpe"] == pytest.approx(0.48, abs=0.01)
+ assert 0.0 < metrics["sortino"] < 5.0
+
+
+def test_no_fill_first_bar_matches_the_legacy_series() -> None:
+ equity = _curve([100_000.0, 95_000.0, 100_000.0])
+ seeded = period_returns(equity, 100_000.0)
+ legacy = equity.pct_change().fillna(0.0)
+ pd.testing.assert_series_equal(seeded, legacy)
+
+
+def test_nonpositive_initial_cash_leaves_the_first_return_unseeded() -> None:
+ equity = _curve([90_000.0, 95_000.0])
+ ret = period_returns(equity, 0.0)
+ # No seed without a positive cash mark; callers decide how to treat the
+ # unseeded first observation (calc_metrics fills 0.0, bootstrap drops it).
+ assert pd.isna(ret.iloc[0])
+ assert ret.iloc[1] == pytest.approx(95_000.0 / 90_000.0 - 1)
+
+
+def test_options_metrics_see_the_first_bar_loss() -> None:
+ metrics = _calc_options_metrics(
+ _curve([90_000.0, 95_000.0, 100_000.0]), 100_000.0, [], bars_per_year=252
+ )
+ # Legacy: returns were [.0556, .0526], all positive, so Sortino came back
+ # undefined and Sharpe was ~404. With the seed both are small and finite.
+ assert metrics["sharpe"] is not None and metrics["sharpe"] < 1.0
+ assert metrics["sortino"] is not None and metrics["sortino"] < 5.0
+
+
+def test_bootstrap_observed_sharpe_uses_the_seeded_series() -> None:
+ equity = _curve([90_000.0, 95_000.0, 100_000.0, 97_000.0, 103_000.0])
+ result = bootstrap_sharpe_ci(
+ equity, n_bootstrap=50, initial_capital=100_000.0
+ )
+ expected = _sharpe(period_returns(equity, 100_000.0).to_numpy(), 252)
+ assert result["observed_sharpe"] == pytest.approx(expected, abs=1e-4)
+
+
+def test_bootstrap_without_capital_keeps_the_legacy_contract() -> None:
+ equity = _curve([90_000.0, 95_000.0, 100_000.0, 97_000.0, 103_000.0])
+ # Five equity points give four adjacent returns, below the minimum.
+ legacy = bootstrap_sharpe_ci(equity, n_bootstrap=50)
+ assert legacy == {"error": "need at least 5 return observations"}
+ # The cash seed makes the first bar a real observation, so it qualifies.
+ seeded = bootstrap_sharpe_ci(equity, n_bootstrap=50, initial_capital=100_000.0)
+ assert "observed_sharpe" in seeded
+
+
+def test_seeded_returns_stay_finite_after_equity_touches_zero() -> None:
+ equity = _curve([100_000.0, 0.0, 50_000.0])
+ ret = period_returns(equity, 100_000.0)
+ assert ret.iloc[0] == pytest.approx(0.0)
+ assert ret.iloc[1] == pytest.approx(-1.0)
+ # 0 -> 50k is an infinite recovery return; the calc_metrics isfinite guard
+ # owns that case, period_returns must not mask it.
+ assert np.isinf(ret.iloc[2])
diff --git a/agent/tests/test_validation_cli_settings.py b/agent/tests/test_validation_cli_settings.py
index dfac48c77..10b436959 100644
--- a/agent/tests/test_validation_cli_settings.py
+++ b/agent/tests/test_validation_cli_settings.py
@@ -92,7 +92,11 @@ def test_missing_settings_keep_standalone_defaults(
"monte_carlo": validation.monte_carlo_test(
validation._load_trades(tmp_path), 1_000_000
),
- "bootstrap": validation.bootstrap_sharpe_ci(validation._load_equity(tmp_path)),
+ # The CLI seeds bootstrap returns with its initial_cash fallback
+ # (1_000_000 when the config carries none), same as run_validation.
+ "bootstrap": validation.bootstrap_sharpe_ci(
+ validation._load_equity(tmp_path), initial_capital=1_000_000
+ ),
"walk_forward": validation.walk_forward_analysis(
validation._load_equity(tmp_path), validation._load_trades(tmp_path)
),
diff --git a/agent/tests/test_validation_missing_equity.py b/agent/tests/test_validation_missing_equity.py
index f568575fd..021daf613 100644
--- a/agent/tests/test_validation_missing_equity.py
+++ b/agent/tests/test_validation_missing_equity.py
@@ -67,9 +67,12 @@ def test_complete_equity_retains_sharpe_calculation() -> None:
def test_loaded_equity_gap_reaches_validation_sample_guard(tmp_path) -> None:
artifacts = tmp_path / "artifacts"
artifacts.mkdir()
+ # Six rows with one interior gap: the cash seed adds the observed first
+ # bar (equity[0] == initial cash), the gap removes its two adjacent
+ # pairs, and four observed returns remain, below the bootstrap minimum.
(artifacts / "equity.csv").write_text(
"date,equity\n2026-01-01,100\n2026-01-02,110\n2026-01-03,\n"
- "2026-01-04,121\n2026-01-05,120\n2026-01-06,122\n2026-01-07,123\n",
+ "2026-01-04,121\n2026-01-05,120\n2026-01-06,122\n",
encoding="utf-8",
)
equity = _load_equity(tmp_path)