jesse: semi-endless loop around add_candle call

Describe the bug Until this week I’d been running 0.44 w/o any problems, but 0.48 added some welcome changes, so I switched my backtesting to 0.48 and encountered a very long loop around https://github.com/jesse-ai/jesse/blob/master/jesse/store/state_candles.py#L102 call, which sometimes causes a backtest to hang for 10-15 minutes. This happens sporadically, maybe one out of 100-200 backtests run, but it effectively it blocks the whole pipeline until problematic test is finished with this loop.

This happens on all symbols and tfs.

When I say ‘around’ it means impossible to track down exact line that hangs, but what I could gather via py-spy is:

  %Own   %Total  OwnTime  TotalTime  Function (filename)
 48.00% 100.00%   627.62s    652.15s   add_candle (jesse/store/state_candles.py)
 52.00%  52.00%   624.50s    624.50s   __getitem__ (jesse/libs/dynamic_numpy_array/__init__.py)
  0.00%   0.00%   0.310s    0.320s   _var (numpy/core/_methods.py)
  0.00%   0.00%   0.070s    0.180s   mean (numpy/core/fromnumeric.py)
  0.00%   0.00%   0.070s    0.110s   _mean (numpy/core/_methods.py)
  0.00%   0.00%   0.070s    0.390s   _std (numpy/core/_methods.py)
  0.00%   0.00%   0.060s    0.060s   timeframe_to_one_minutes (jesse/helpers.py)
  0.00%   0.00%   0.050s    0.050s   _count_reduce_items (numpy/core/_methods.py)
  0.00% 100.00%   0.040s    53.00s   _step_simulator (jesse/modes/backtest_mode.py)
  0.00%   0.00%   0.030s    0.630s   peaks (jesse-bot/custom_indicators/peaks.py)
  0.00%  52.00%   0.020s    25.74s   _simulate_price_change_effect (jesse/modes/backtest_mode.py)
  0.00%   0.00%   0.020s    0.020s   stochrsi (tulipy/__init__.py)
  0.00%   0.00%   0.020s    0.020s   is_collecting_data (jesse/helpers.py)
  0.00%   0.00%   0.020s    0.020s   wrapper (talib/__init__.py)
  0.00%   0.00%   0.010s    0.190s   mean (<__array_function__ internals>)
  0.00%   0.00%   0.010s    0.010s   _sum (numpy/core/_methods.py)
  0.00%   0.00%   0.010s    0.010s   is_live (jesse/helpers.py)
  0.00%   0.00%   0.010s    0.400s   std (numpy/core/fromnumeric.py)
  0.00%   0.00%   0.010s    0.010s   get_candles (jesse/store/state_candles.py)
  0.00%   0.00%   0.010s    0.010s   get_candle_source (jesse/helpers.py)
  0.00%   0.00%   0.010s    0.410s   std (<__array_function__ internals>)
  0.00%   0.00%   0.010s    0.010s   is_debuggable (jesse/helpers.py)
  0.00%   0.00%   0.010s    0.010s   _get_fixed_jumped_candle (jesse/modes/backtest_mode.py)
  0.00%   0.00%   0.010s    0.700s   _check (jesse/strategies/Strategy.py)
  0.00% 100.00%   0.000s    53.00s   backtest_rungs (jesse-bot/backtest_new.py)
  0.00% 100.00%   0.000s    53.00s   _resume_span (ray/util/tracing/tracing_helper.py)
  0.00%   0.00%   0.000s    0.690s   decorated (jesse/services/cache.py)

I’ve added some logging:

    def get_storage(self, exchange: str, symbol: str, timeframe: str) -> DynamicNumpyArray:
        key = jh.key(exchange, symbol, timeframe)
        print(key) <----
[...]


    def add_candle(
        [...]
        print('getting arr') <---
        arr: DynamicNumpyArray = self.get_storage(exchange, symbol, timeframe)
        print('got arr', len(arr)) <---

And from these prints we can see this method is called millions of times by a single backtest process: image

Eventually number of calls falls: image

Which makes me think there’s loop inside loop somewhere.

I could not instantly pinpoint recent changes responsible for this. Will roll back to 0.44 for now and slowly work my way to 0.48, maybe I can find where regression first appeared.

Any help from those familiar with recent changes is appreciated @yakir4123

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 27 (26 by maintainers)

Most upvoted comments

Okay, I think I found the culprit, it was a mistake in my code (thanks to Python’s archaic scoping rules) when migrating to updated backtest function, but finding this mistake was so hard due to difference between backtest() function handling of warmup_candles argument when fast_mode set to True or False.

Consider the following generic backtest:


import importlib
from datetime import datetime

import jesse.helpers as jh
from jesse.research import backtest, import_candles, get_candles
from jesse.utils import anchor_timeframe

exchange = 'Binance Perpetual Futures'
symbol = 'ACH-USDT'
tf = '1h'
strategy_name = 'DUAL_THRUST'
strategy = getattr(importlib.import_module(f"strategies.{strategy_name}"), f"{strategy_name}")
timeframes = [tf]
config = {
    'starting_balance': 1000,
    'fee': 0.001,
    'type': 'futures',
    'futures_leverage': 1,
    'futures_leverage_mode': 'cross',
    'exchange': exchange,
    'warm_up_candles': 255,
}

tests_start_date = '2024-01-01'
tests_end_date = '2024-08-30'

import_candles(exchange, symbol, tests_start_date, show_progressbar=False)
warmup_candles, candles = get_candles(exchange, symbol, tf, int((datetime.strptime(tests_start_date, '%Y-%m-%d')).timestamp() * 1000), int((datetime.strptime(tests_end_date, '%Y-%m-%d')).timestamp() * 1000), warmup_candles_num=config["warm_up_candles"], caching=True, is_for_jesse=True)

wrong_tests_start_date = '2024-05-01' # !!! IMPORTING WRONG CANDLES !!!
wrong_warmup_candles, wrong_candles = get_candles(exchange, symbol, tf, int((datetime.strptime(wrong_tests_start_date, '%Y-%m-%d')).timestamp() * 1000), int((datetime.strptime(tests_end_date, '%Y-%m-%d')).timestamp() * 1000), warmup_candles_num=config["warm_up_candles"], caching=True, is_for_jesse=True)

params={'stop_loss_atr_rate': 0.8, 'down_length': 30, 'up_length': 24, 'down_coeff': 1.8000000000000003, 'up_coeff': 0.5, 'tp_pc': 5.0, 'sl_pc': 0.5, 'trailing_profit': 5.0}

result = backtest(config, 
        [ {'exchange': exchange, 'strategy': strategy, 'symbol': symbol, 'timeframe': tf} ], 
        [ {'exchange': exchange, 'strategy': strategy, 'symbol': symbol, 'timeframe': anchor_timeframe(tf)} ],
        candles = {
            jh.key(exchange, symbol): {
                'exchange': exchange,
                'symbol': symbol,
                'candles': candles,
            }
        },  
        warmup_candles = {
            jh.key(exchange, symbol): {
                'exchange': exchange,
                'symbol': symbol,
                'candles': wrong_warmup_candles, # !!! USING WRONG CANDLES !!!
            }
        }, 
        generate_csv=False,
        generate_json=True,
        hyperparameters=params,
        fast_mode=False
        ) 

print(result)

As you can see, here I deliberately offer wrong_warmup_candles to backtest() call, and with fast_mode=False the test will SILENTLY run, although very slowly, but in many cases it will finish the run successfully (!).

With fast_mode=True however, backtest fails with:

  File "/home/ubuntu/.local/lib/python3.11/site-packages/jesse/modes/backtest_mode.py", line 681, in _skip_simulator
    _simulate_new_candles(candles, i, candles_step)
  File "/home/ubuntu/.local/lib/python3.11/site-packages/jesse/modes/backtest_mode.py", line 754, in _simulate_new_candles
    _simulate_price_change_effect_multiple_candles(
  File "/home/ubuntu/.local/lib/python3.11/site-packages/jesse/modes/backtest_mode.py", line 856, in _simulate_price_change_effect_multiple_candles
    store.candles.add_multiple_1m_candles(
  File "/home/ubuntu/.local/lib/python3.11/site-packages/jesse/store/state_candles.py", line 429, in add_multiple_1m_candles
    raise IndexError(f"Could not find the candle with timestamp {jh.timestamp_to_time(candles[0, 0])} in the storage. Last candle's timestamp: {jh.timestamp_to_time(arr[-1][0])}. exchange: {exchange}, symbol: {symbol}")
IndexError: Could not find the candle with timestamp 2023-12-31T00:00:00+00:00 in the storage. Last candle's timestamp: 2024-04-29T23:59:00+00:00. exchange: Binance Perpetual Futures, symbol: ACH-USDT

This error message is expected with wrong_warmup_candles but is somewhat misleading. A better error would be Could not find the candle [...] First candle's timestamp [...]. Make sure your warmup_candles are imported properly!

I believe, this difference in handling of warmup_candles can lead us to some interesting discoveries of how fast_mode works. It is really fast, I can confirm, but I will run further tests to see whether results match “slow mode” with complex exit strategies.

@movy I updated the branch 1 hour ago, if you fetch the last update before that please give another try. I do something very similar to you and now it workings for me really fast

0.45 is the final version working w/o hanging, 0.46 introduced this bug

@movy Cool I didnt know that v0.46 didnt has this problem

please try this PR I did some fixes on these cases exactly!

https://github.com/jesse-ai/jesse/pull/450