feat: extract backtest iteration into generator

This commit is contained in:
Matthias
2024-08-12 10:19:33 +02:00
parent 980b81f009
commit f01e101447
+23 -10
View File
@@ -1388,6 +1388,25 @@ class Backtesting:
self._process_exit_order(order, trade, current_time, row, pair) self._process_exit_order(order, trade, current_time, row, pair)
return open_trade_count_start return open_trade_count_start
def time_pair_generator(
self, start_date: datetime, end_date: datetime, increment: timedelta, pairs: List[str]
):
"""
Backtest time and pair generator
"""
current_time = start_date + increment
self.progress.init_step(
BacktestState.BACKTEST, int((end_date - start_date) / self.timeframe_td)
)
while current_time <= end_date:
is_first = True
for pair in pairs:
yield current_time, pair, is_first
is_first = False
self.progress.increment()
current_time += increment
def backtest(self, processed: Dict, start_date: datetime, end_date: datetime) -> Dict[str, Any]: def backtest(self, processed: Dict, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
""" """
Implement backtesting functionality Implement backtesting functionality
@@ -1411,19 +1430,17 @@ class Backtesting:
# Indexes per pair, so some pairs are allowed to have a missing start. # Indexes per pair, so some pairs are allowed to have a missing start.
indexes: Dict = defaultdict(int) indexes: Dict = defaultdict(int)
current_time = start_date + self.timeframe_td
self.progress.init_step(
BacktestState.BACKTEST, int((end_date - start_date) / self.timeframe_td)
)
# Loop timerange and get candle for each pair at that point in time # Loop timerange and get candle for each pair at that point in time
while current_time <= end_date: for current_time, pair, is_first in self.time_pair_generator(
start_date, end_date, self.timeframe_td, list(data.keys())
):
if is_first:
open_trade_count_start = LocalTrade.bt_open_open_trade_count open_trade_count_start = LocalTrade.bt_open_open_trade_count
self.check_abort() self.check_abort()
strategy_safe_wrapper(self.strategy.bot_loop_start, supress_error=True)( strategy_safe_wrapper(self.strategy.bot_loop_start, supress_error=True)(
current_time=current_time current_time=current_time
) )
for i, pair in enumerate(data):
row_index = indexes[pair] row_index = indexes[pair]
row = self.validate_row(data, pair, row_index, current_time) row = self.validate_row(data, pair, row_index, current_time)
if not row: if not row:
@@ -1484,10 +1501,6 @@ class Backtesting:
row, pair, current_time, end_date, open_trade_count_start, trade_dir row, pair, current_time, end_date, open_trade_count_start, trade_dir
) )
# Move time one configured time_interval ahead.
self.progress.increment()
current_time += self.timeframe_td
self.handle_left_open(LocalTrade.bt_trades_open_pp, data=data) self.handle_left_open(LocalTrade.bt_trades_open_pp, data=data)
self.wallets.update() self.wallets.update()