Skip to content

Fix trailing ATR look-ahead bias#1368

Open
Jaco-Ren wants to merge 1 commit into
kernc:masterfrom
Jaco-Ren:fix-trailing-atr-lookahead
Open

Fix trailing ATR look-ahead bias#1368
Jaco-Ren wants to merge 1 commit into
kernc:masterfrom
Jaco-Ren:fix-trailing-atr-lookahead

Conversation

@Jaco-Ren

Copy link
Copy Markdown

Summary

  • stop backfilling TrailingStrategy ATR values, which used future volatility during the rolling warmup window
  • skip trailing stop updates until ATR is finite instead of setting a stop from unavailable data
  • keep set_trailing_pct() stable by averaging only finite close/ATR ratios
  • add a regression test proving a trade opened before ATR warmup does not receive a future-derived stop loss

Motivation and Context

Fixes #963.

TrailingStrategy.set_atr_periods() previously used .bfill() after the rolling ATR calculation. That filled the warmup bars with ATR values computed from later bars, so strategies could open early trades whose trailing stop used future information.

With this change, early ATR entries remain NaN. TrailingStrategy.next() ignores those bars for stop updates and starts applying trailing stops once the rolling ATR window is actually available.

Testing

  • python -m pytest backtesting/test/_test.py -q
  • git diff --check
  • python -m py_compile backtesting\lib.py backtesting\test\_test.py

@Jaco-Ren Jaco-Ren marked this pull request as ready for review July 12, 2026 03:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ATR introduces look-ahead bias

1 participant