From f14d8d3b41d17f46eda9c328af5165636fa95dde Mon Sep 17 00:00:00 2001 From: Charles Dai Date: Wed, 18 Nov 2026 00:26:35 -0500 Subject: [PATCH 1/2] Check truncated price histories for calendar look-ahead --- docs/DESIGN.md | 2 +- src/quantkit/backtest/engine.py | 17 ++++++++++++++--- tests/test_backtest_engine.py | 26 ++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 7b4fbab..ccaa491 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -190,7 +190,7 @@ for the last trade day `s ≤ t`, computed for all days with a forward fill. The - The built-in strategies use trailing windows only (`rolling`, `shift` with positive lags). - **Calendar look-ahead:** rebalancing on the *last* trading day of each month looks innocent but is not causal, because on a given day you cannot know it is the last trading day without tomorrow's date. `rebalance_days` flags the *first* trading day of each period, which needs only today's and yesterday's dates. - **Tests:** for every strategy and several cutoffs `t`, prices after `t` are multiplied by random factors and the backtest is re-run; the weights in effect on days `0..t+1`, and equity and turnover through day `t`, must be identical. A deliberately cheating strategy (buying whatever rises tomorrow) is a negative control: it fails the same check, and its equity explodes. -- `check_no_lookahead(strategy, prices)` exposes the strategy-level check for custom strategies. +- `check_no_lookahead(strategy, prices)` samples historical cutoffs for custom strategies. It changes later prices and also removes later dates: a month-end rule that reads the next trading date can pass a price shock but changes its decision on a shorter history. ### Metrics (`metrics.py`) diff --git a/src/quantkit/backtest/engine.py b/src/quantkit/backtest/engine.py index 027f86d..0da51aa 100644 --- a/src/quantkit/backtest/engine.py +++ b/src/quantkit/backtest/engine.py @@ -204,9 +204,10 @@ def check_no_lookahead( ) -> None: """Raise if ``strategy``'s weight for some day depends on later prices. - For several cutoff days ``t`` the prices after ``t`` are scrambled (multiplied - by random factors) and the strategy is re-run. A causal strategy produces - identical target weights for days ``0..t``. + For sampled cutoff days, first scramble the later prices, then rerun on a + truncated price history to also check for dependence on future trading + dates. Each run must reproduce the original weights over the shared prefix. + Truncated histories use at least two dates, the minimum supported price table. Args: strategy: The strategy to check. @@ -232,3 +233,13 @@ def check_no_lookahead( f"look-ahead detected: target weights up to {day} changed when only " "later prices were modified" ) + # Keep at least two dates, as required by the public price-table contract. + stop = max(2, cutoff + 1) + if stop < len(prices): + prefix_weights = strategy(prices.iloc[:stop]).to_numpy() + if not np.array_equal(baseline[:stop], prefix_weights, equal_nan=True): + day = pd.Timestamp(prices.index[stop - 1]).date() + raise InvalidParameterError( + f"look-ahead detected: target weights up to {day} changed when " + "later trading dates were removed" + ) diff --git a/tests/test_backtest_engine.py b/tests/test_backtest_engine.py index 539001f..d1de1bd 100644 --- a/tests/test_backtest_engine.py +++ b/tests/test_backtest_engine.py @@ -198,6 +198,32 @@ def test_built_in_strategies_pass_the_lookahead_checker( check_no_lookahead(strategy, prices, cutoffs=10) +def test_lookahead_checker_detects_a_rebalance_using_future_trading_dates() -> None: + prices = pd.DataFrame( + {"X": [100.0, 101.0, 99.0, 102.0]}, index=pd.bdate_range("2024-01-08", periods=4) + ) + + def last_close_of_month(history: pd.DataFrame) -> pd.DataFrame: + dates = pd.DatetimeIndex(history.index) + # The final observed session of each month is known only in hindsight. + flags = ~dates.to_period("M").duplicated(keep="last") + return pd.DataFrame({"X": flags.astype(float)}, index=dates) + + with pytest.raises(InvalidParameterError, match="look-ahead"): + check_no_lookahead(last_close_of_month, prices, cutoffs=len(prices) - 1) + + +def test_lookahead_checker_uses_supported_histories_for_short_samples( + prices: pd.DataFrame, +) -> None: + def strategy(history: pd.DataFrame) -> pd.DataFrame: + assert len(history) >= 2 + return BuyAndHold()(history) + + check_no_lookahead(strategy, prices.iloc[:2]) + check_no_lookahead(strategy, prices.iloc[:4], cutoffs=3) + + def peeking_strategy(prices: pd.DataFrame) -> pd.DataFrame: """Deliberately broken: buys whatever will rise tomorrow (uses shift(-1)).""" rises_tomorrow = prices.shift(-1) > prices From 51e950c078a4d68f2f374b4fb2657505bdb2300c Mon Sep 17 00:00:00 2001 From: Charles Dai Date: Wed, 18 Nov 2026 00:27:24 -0500 Subject: [PATCH 2/2] Hold existing shares when inverse-volatility targets are undefined --- src/quantkit/backtest/strategies.py | 11 ++++++--- tests/test_strategies.py | 37 +++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/quantkit/backtest/strategies.py b/src/quantkit/backtest/strategies.py index 27feebc..9aca8c9 100644 --- a/src/quantkit/backtest/strategies.py +++ b/src/quantkit/backtest/strategies.py @@ -184,6 +184,9 @@ class InverseVolatility: Volatility is the standard deviation of the last ``window`` daily returns. Assets that have been calmer get more capital, so each contributes roughly similar risk when correlations are similar (a simple cousin of risk parity). + A rebalance requires positive volatility for every asset. During warm-up or + when an asset has zero trailing volatility, keep the existing shares (or + initial cash) until a scheduled rebalance has defined weights. Attributes: window: Trailing window for volatility, in trading days. @@ -199,8 +202,10 @@ def __post_init__(self) -> None: def __call__(self, prices: pd.DataFrame) -> pd.DataFrame: """Target weights proportional to inverse volatility on rebalance days.""" - inverse_vol = 1.0 / prices.pct_change().rolling(self.window).std() - # Rows are NaN until a full window of returns exists, so no trade happens - # (the portfolio stays in cash) during the warm-up. + volatility = prices.pct_change().rolling(self.window).std() + # An undefined reciprocal invalidates the whole rebalance. An all-NaN + # target row is the engine's instruction to keep the existing shares. + defined = volatility.gt(0.0).all(axis=1) + inverse_vol = 1.0 / volatility.where(defined, axis=0) targets = inverse_vol.div(inverse_vol.sum(axis=1), axis=0) return _trade_only_on(targets, rebalance_days(_dates(prices), self.rebalance)) diff --git a/tests/test_strategies.py b/tests/test_strategies.py index 881462a..c5beb82 100644 --- a/tests/test_strategies.py +++ b/tests/test_strategies.py @@ -107,6 +107,43 @@ def test_inverse_volatility_weights_are_inversely_proportional_to_volatility() - np.testing.assert_allclose(targets["WILD"], 0.25) +@pytest.mark.parametrize( + "second", [[80.0] * 5, [80.0, 85.0, 82.0, 85.0, 80.0]], ids=["all-flat", "one-flat"] +) +def test_inverse_volatility_stays_in_cash_when_a_weight_is_undefined(second: list[float]) -> None: + prices = frame({"A": [100.0] * 5, "B": second}) + strategy = InverseVolatility(window=2, rebalance="D") + assert strategy(prices).isna().all().all() + result = run_backtest(prices, strategy, cost_bps=25.0, initial_capital=1000.0) + np.testing.assert_array_equal(result.equity, 1000.0) + np.testing.assert_array_equal(result.costs, 0.0) + np.testing.assert_array_equal(result.turnover, 0.0) + + +def test_inverse_volatility_holds_its_shares_through_flat_windows_and_resumes() -> None: + prices = frame( + { + "A": [100.0, 120.0, 100.0, 100.0, 100.0, 100.0, 100.0, 90.0, 99.0], + "B": [100.0, 85.0, 105.0, 110.0, 120.0, 120.0, 120.0, 132.0, 115.0], + } + ) + strategy = InverseVolatility(window=2, rebalance="D") + targets = strategy(prices) + assert targets.iloc[4:7].isna().all().all() # A alone, then both, have zero volatility. + result = run_backtest(prices, strategy, cost_bps=25.0, initial_capital=1000.0) + shares = result.equity.iloc[3] * targets.iloc[3] / prices.iloc[3] + np.testing.assert_allclose(result.equity.iloc[4:7], prices.iloc[4:7] @ shares) + np.testing.assert_array_equal(result.turnover.iloc[4:7], 0.0) + np.testing.assert_array_equal(result.costs.iloc[4:7], 0.0) + assert targets.iloc[7].sum() == pytest.approx(1.0) + np.testing.assert_allclose(result.weights.iloc[8], targets.iloc[7]) + pre_trade = shares * prices.iloc[7] + turnover = (targets.iloc[7] - pre_trade / pre_trade.sum()).abs().sum() + assert turnover > 0.0 + assert result.turnover.iloc[7] == pytest.approx(turnover) + assert result.equity.iloc[7] == pytest.approx(pre_trade.sum() * (1.0 - 0.0025 * turnover)) + + def test_calendar_strategies_need_a_datetime_index() -> None: prices = pd.DataFrame({"X": [1.0, 2.0, 3.0]}) with pytest.raises(InvalidParameterError, match="DatetimeIndex"):