From b4a79cf3aaf2bcccccd4052ce11d270e2e386fb4 Mon Sep 17 00:00:00 2001 From: moshferatu Date: Fri, 2 Feb 2024 13:15:33 -0800 Subject: [PATCH] Prevent lookahead bias when determining the best performing entry times by not including the date being requested --- backtesting/best_entry_times.py | 2 ++ test/best_entry_times_test.py | 3 +++ 2 files changed, 5 insertions(+) diff --git a/backtesting/best_entry_times.py b/backtesting/best_entry_times.py index 1d6f51e..ce587ec 100644 --- a/backtesting/best_entry_times.py +++ b/backtesting/best_entry_times.py @@ -3,9 +3,11 @@ from datetime import datetime, timedelta def best_entry_times(date: datetime = datetime.now(), days_to_look_back: int = 10): end_date = date.replace(hour = 0, minute = 0, second = 0, microsecond = 0) + end_date -= timedelta(days = 1) # Subtract one day in order to prevent lookahead bias. start_date = end_date - timedelta(days = days_to_look_back) backtest = backtest_results('SPX', '10 Delta Iron Condor', start_date = start_date, end_date = end_date) + print(backtest) backtest['Entry Time'] = backtest['Entry Time'].dt.time profit_by_entry_time = backtest.groupby('Entry Time')['Profit'].sum().reset_index() diff --git a/test/best_entry_times_test.py b/test/best_entry_times_test.py index 1d3d784..6a4e708 100644 --- a/test/best_entry_times_test.py +++ b/test/best_entry_times_test.py @@ -1,5 +1,8 @@ from backtesting import best_entry_times +from datetime import datetime print(best_entry_times()) +print(best_entry_times(datetime(2024, 1, 31))) + print(best_entry_times(days_to_look_back = 30)) # Days. \ No newline at end of file