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

Re-initialize an indicator during the life of a strategy

  • Dear All,

    I'm working on a Futures strategy that needs individual futures contract (e.g. NGZ19 for Natural Gas Dec 2019) AND continuous futures contracts. I'm backtesting over a long period of time; therefore I don't want to build a single continuous contract (from now back to 20 years). Instead, I'm building (outside of backtrader) a series of continuous contracts (@NGF00, @NGG00, .... @NGG20) i.e. each individual contract has its own continuous contract equivalent that goes back to year 2000.

    Now, I need to apply a couple of indicators on these continuous contracts. As of now, I have applied these indicators to ALL continuous contracts in this fashion (self.continuous is a dict that contains a list of objects that represent each continuous futures for a given market; the datafeed associated with the contract is accessed by

    for root in self.continuous.keys():
       for contract in self.continuous[root]:
          self.rules['ewmac_16_64'][contract] = EWMAC(, period_fast=16, period_slow=64)
          self.rules['ewmac_32_128'][contract] = EWMAC(, period_fast=32, period_slow=128)
          self.rules['ewmac_64_256'][contract] = EWMAC(, period_fast=64, period_slow=256)

    This works well BUT as you can imagine it is extremely slow (20 different futures market, 20 years, say an average of 6 contracts per year ... 3 indicators to be updated for 2400 data feeds). Off course, over time, it will be less datafeeds (contract will start expiring) but it is still very computationally intensive.

    In fact, I only need these indicators to be applied to the continuous future associated with the front month (e.g. if front month is NGM15, then I just need the indicator to be applied on @NGM15). I'm trying to find a way to re-instantiate these indicators (and preload then with data) when I roll from one contract to another. Does anyone has a trick / something smart to suggest here?

    Kind regards

  • Hello All,
    After doing more investigation on this, I understand that an indicator cannot be instantiated/modified during a strategy's life (i.e. in next() for instance).

    But is there a way, I can enable/disable an indicator (when indicator not needed) to save CPU during backtesting?

    Thanks and regards

Log in to reply