Is backtrader predefined indicator stateless?
-
Hi,
I'm trying to implement some kind of strategy, which pick stock base on some criteria at some time, then trade those stock.So the data feed is dynamically changing.
I run cerebro with preload=True, so it will always use new data.
But it require the indicator to be stateless, which all the line caculate with new data feed, and don't keep any state from old data feed.So I'm wondering if Is backtrader predefined indicator (for example SMA, crossover) stateless. And if it's not stateless, is there any general way to reset the indicator to initial state?
Thanks
-
@yacc-don I am not sure what is
stateless indicator
and what isalways new data
with thepreload=True
, butbt
works the following way (unless you hacked it somehow):- all data feeds loaded once at the very beginning of the backtest, after
cerebro
initiated - indicators are initiated/calculated in the
__init()__
in pseudo-batch mode (if possible) cerebro
goes bar by bar and calculates rest of the indicators indicators and perform strategy rules
IIRC
preload=True
helps to runbatch
mode and speed up the backtest.@yacc-don said in Is backtrader predefined indicator stateless?:
So the data feed is dynamically changing.
If you plan to load and un-load data feeds during backtest, than
bt
is not doing this. See my clarification above. - all data feeds loaded once at the very beginning of the backtest, after
-
sorry, my mistake.
I run cerebro with preload=False, then I change the content of data feed at some time.
As for stateless and stateful, here is example.
class stateful_crossover(bt.Indicator): def next(self): if self.data0 < self.data1: if self.state == OVER: #check state caculate by old data self.line.crossover = -1 self.state = UNDER #keep state elif self.data0 > self.data1: if self.state == UNDER: self.line.crossover = 1 self.state = OVER #keep state class stateless_crossover(bt.Indicator): def next(self): #always caculate result from new data, not keeping any state if self.data0 < self.data1 and self.data0[-1] > self.data1[-1]: self.line.crossover = -1 elif self.data0 > self.data1 and self.data0[-1] <self.data1[-1]: self.line.crossover = 1
So I'm wondering if Is backtrader predefined indicator (for example crossover etc) stateless. And if it's not stateless, is there any general way to reset the indicator to initial state?
Thanks
-
My guess would be that you are trying to differentiate recursive and non-recursive indicators. Both of these types are in
bt
indicator database and they are mainly defined by the nature of the required calculations. I believe the best way for you would be to look into the source code on the github, and define by yourself, if the indicators are good for you or they need to be re-written.Honestly, I don't see any reasons of why any of the examples stated above (first need to have
self.state
variable to be defined at the beginning) will not work withbt
. -
@ab_trader Thanks