From 38b157adee08bea41e53f442b32128daed9093b6 Mon Sep 17 00:00:00 2001 From: moshferatu Date: Wed, 17 Jan 2024 11:39:18 -0800 Subject: [PATCH] Add script to perform backtest and insert results into database --- run_backtest.py | 62 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 run_backtest.py diff --git a/run_backtest.py b/run_backtest.py new file mode 100644 index 0000000..62af2df --- /dev/null +++ b/run_backtest.py @@ -0,0 +1,62 @@ +from backtesting import backtest_iron_condor +from backtesting.delta_target_strategy import DeltaTargetStrategy +from backtesting.option_type import OptionType +from database.backtest import insert +from datetime import datetime, timedelta + +entry_time_format = '%H:%M:%S' + +def entry_times(): + start = datetime.strptime('09:35:00', entry_time_format) + end = datetime.strptime('15:55:00', entry_time_format) + + current_time = start + entry_times = [] + + while current_time <= end: + entry_times.append(current_time.strftime(entry_time_format)) + current_time += timedelta(minutes = 5) + + return entry_times + +def create_strategies(entry_time: str): + call_spread_strat = DeltaTargetStrategy( + delta_upper_bound = 0.11, + delta_lower_bound = 0.10, + option_type = OptionType.CALL, + number_of_contracts = 1, + spread_width = 50, + stop_loss_multiple = 1.00, + trade_entry_time = entry_time + ) + put_spread_strat = DeltaTargetStrategy( + delta_upper_bound = 0.11, + delta_lower_bound = 0.10, + option_type = OptionType.PUT, + number_of_contracts = 1, + spread_width = 50, + stop_loss_multiple = 1.00, + trade_entry_time = entry_time + ) + return call_spread_strat, put_spread_strat + +def run_backtest(): + # TODO: Start date = yesterday. + start_date = datetime(2024, 1, 1) + end_date = datetime.now() + for entry_time in entry_times(): + call_spread_strategy, put_spread_strategy = create_strategies(entry_time) + backtest_results = backtest_iron_condor( + f'10 Delta Iron Condor @ {call_spread_strategy.trade_entry_time}', + call_spread_strategy, + put_spread_strategy, + start_date, + end_date + ) + # TODO: Think of a better way to handle this. + backtest_results.drop('Cumulative Profit', axis=1, inplace=True) + print(backtest_results) + insert(backtest_results) + +if __name__ == '__main__': + run_backtest() \ No newline at end of file