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

Is Backtrader event-driven or vectorized?



  • I know there is already a similar question in the community: https://community.backtrader.com/topic/242/is-backtrader-event-driven-or-vectorized

    It says Backtrader is both event-driven and vectorized. But I still have a question about it.

    For example, the SMA indicator's real logic is as the following(basicops.py#L341):

    class Average(PeriodN):
        alias = ('ArithmeticMean', 'Mean',)
        lines = ('av',)
    
        def next(self):
            self.line[0] = \
                math.fsum(self.data.get(size=self.p.period)) / self.p.period
    
        def once(self, start, end):
            src = self.data.array
            dst = self.line.array
            period = self.p.period
    
            for i in range(start, end):
                dst[i] = math.fsum(src[i - period + 1:i + 1]) / period
    

    In the once() function it calculates SMA in a for loop, which doesn't make use of Numpy vectorization at all.

    To my understanding, here is a Pandas way to calculate SMA:

    sma = df['close'].rolling(N).mean()
    

    It will make use of the vectorization capability from Pandas&NumPy, this is the real vectorized version, which is much faster than for loop.

    In summary, Backtrader seems like an event-driven backtesting framework.

    Why is Backtrader both event-driven and vectorized? Thanks!



  • Backtrader is not 'vectorized' in a classic definition of this term as you may see from the post you've mentioned

    I guess the attempt to use the approach you've suggested was done in numpylines branch of the original repository - but it was never merged back.



  • @vladisld I thought that by using the python array library, that many of the speed benefits were picked up similar to vectorizing, since the array library is just a thin wrapper for C? However, your point is valid, it is definitely not vectorized in the pandas/numpy sense of things.



  • @vladisld @run-out Thanks for your clarification !

    Now I'm sure that Backtrader is a pure event-driven framework.

    vectorized means it must take advantage of SMID operations like numpy and Pandas(Pandas actually uses numpy under the hood).


Log in to reply
 

});