Add the ability to filter out days to trade by providing a list of backtest filters

This commit is contained in:
moshferatu 2024-02-06 07:50:28 -08:00
parent 4214ed5165
commit e02e831288

View File

@ -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,17 +295,21 @@ 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)
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 = []