From e02e8312885390658f1239baf96b61d27613409b Mon Sep 17 00:00:00 2001 From: moshferatu Date: Tue, 6 Feb 2024 07:50:28 -0800 Subject: [PATCH] Add the ability to filter out days to trade by providing a list of backtest filters --- backtesting/backtest_iron_condor.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/backtesting/backtest_iron_condor.py b/backtesting/backtest_iron_condor.py index 9dd9812..500a2c2 100644 --- a/backtesting/backtest_iron_condor.py +++ b/backtesting/backtest_iron_condor.py @@ -5,10 +5,12 @@ import pandas as pd from concurrent.futures import ProcessPoolExecutor from datetime import datetime from dotenv import load_dotenv +from typing import List from .backtest_result import BacktestResult from .credit_targeting import CreditTargetStrategy from .delta_targeting import DeltaTargetStrategy +from .filter import BacktestFilter, VolatilityRegimeFilter from .option_spread_strategy import OptionSpreadStrategy from .option_type import OptionType @@ -272,7 +274,8 @@ def backtest_iron_condor( call_spread_strategy: OptionSpreadStrategy, put_spread_strategy: OptionSpreadStrategy, start_date: datetime, - end_date: datetime + end_date: datetime, + filters: List[BacktestFilter] = [] ) -> pd.DataFrame: total_premium_received = 0.0 @@ -292,18 +295,22 @@ def backtest_iron_condor( continue # Assuming file format 'YYYY-MM-DD.csv'. - file_date_str = os.path.splitext(file)[0] - file_date = datetime.strptime(file_date_str, '%Y-%m-%d') + current_date = datetime.strptime(os.path.splitext(file)[0], '%Y-%m-%d') # TODO: This doesn't work as expected when the start date is not set to midnight. - if file_date < start_date or file_date > end_date: + if current_date < start_date or current_date > end_date: continue logging.info('Processing File: %s', historical_data_file) - future = executor.submit(_backtest_iron_condor, - historical_data_file, call_spread_strategy, put_spread_strategy) - futures.append(future) + if (not filters) or all(filter.trade_allowed(current_date) for filter in filters): + future = executor.submit( + _backtest_iron_condor, + historical_data_file, + call_spread_strategy, + put_spread_strategy + ) + futures.append(future) backtest_results = [] for future in futures: