For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

Strategy.__init__() slows down the whole backtest after it’s first execution?

  • Hello together,

    I am new to backtrader and python and noticed something seeming weird to me. To get a feeling how long it takes to calculate an indicator really often, I added the following code to the --init-- method of the class testStrategy:

    startTime = time.time()
    for i in range(1, 100000):
        self.datas[0], period=self.params.maperiod)
    time2 = time.time()-startTime
    print("time needed " + str(time2))

    When running the program, it takes about 20 seconds to execute the --init-- method, what makes sense to me. However, afterwards it takes much longer to execute the rest of the program (the actual testing). As far as I have understood backtrader/python the --init--() method is only executed ones, right after the instantiation of the testStrategy object. But if I increase the number of loops from 100.000 to 1.000.000, the steps after executing the --init-- method the first time take ten times longer.
    Can anybody explain this behavior? Why is the rest of the program executed more slowly?
    My program equals the second last step of the quickstart guide.

    Thanks for any help in advance.

  • administrators

    You increase the number of objects you create.

    Why should things run at the same speed regardless of the number of objects? It would be an incredible feat.

    In your example you create one hundred thousand (100000) simple moving averages. Are you expecting that nothing happens with them during program execution?

  • Thanks a lot for the fast answer. That makes sense!

  • administrators

    What you probably miss is that

    @jburb said in Strategy.__init__() slows down the whole backtest after it’s first execution?:

        bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.maperiod)

    This is only a declaration. No actual calculation is taking place there. If it actually did, live data feeds would be impossible. As stated in other posts: backtrader is not pandas.