Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    How to save indicator config to use in different strategy

    Indicators/Strategies/Analyzers
    2
    3
    846
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • S
      sfkiwi last edited by

      I am trying to figure out a way to save the configuration of all of my indicators in one strategy and then load the same configuration into a different strategy (there are more than 50 indicators and the indicators may change from time to time so it needs to be done programmatically).

      For example, say in strategy1 I have an SMA and an RSI, I want to be able to load a file from disk that will tell strategy2 to create an SMA and an RSI with the same config (including plotname) as in Strategy1. Strategy 1 and Strategy 2 have different logic and both use different feeds so the rest of the cerebro instance is quite different between Strategy1 and Strategy2.

      I had tried pickling but keep getting cannot serialize '_io.TextIOWrapper' object exceptions, which is also discussed in this thread. However pickling probably wouldn't work in any case because each indicator holds references to the cerebro context and those get pickled as well.

      Is there a way to save a config, along with the indicator plotname etc that could then be used to instantiate an indentical copy in another strategy?

      1 Reply Last reply Reply Quote 0
      • B
        backtrader administrators last edited by

        There may be something missing here to let me understand your troubles:

        • You create and configure the indicators, i.e.: you set the values for the parameters and things like plotname

        What prevents you from saving those parameters you are actually setting to a file? (pickled, in JSON Format, in .ini format, you name it)

        1 Reply Last reply Reply Quote 0
        • S
          sfkiwi last edited by

          Thanks, in the end that is pretty much what I did.
          There's likely a much more elegant way to do this than how I have done it though

          # define_indicators.py
          
          def save_indicators():
          
            indicators = {
          
              'SMA': {'ind': bt.ind.SMA, 'data': 0, 'args': {'period':10}},
              'trend': {'ind': bt.ind.SMA, 'data': 3, 'args': {'period':10}},
              'rsi_1M': { 'ind': bt.ind.RSI, 'data': 0, 'args': None },
              'rsi_5M': { 'ind': bt.ind.RSI, 'data': 1, 'args': None},
              'rsi_30M': { 'ind': bt.ind.RSI, 'data': 2, 'args': None },
              'rsi_1H': { 'ind': bt.ind.RSI, 'data': 3, 'args': None },
              'rsi_4H': {'ind': bt.ind.RSI, 'data': 4, 'args': None},
              'sto_1M': {'ind': StochasticRSI, 'data': 'rsi_1M', 'args': None},
              .....
            }
          
            DATA_DIRNAME.mkdir(parents=True, exist_ok=True)
            with open(INDICATORS_FILENAME, 'wb') as f:
              pickle.dump(indicators, f, pickle.HIGHEST_PROTOCOL)
          
          
          def build_indicators(datas, indicators):
          
              ind = dict()
              for k, v in indicators.items():
          
                  kwargs = {}
                  if v['args']:
                      kwargs = v['args']
          
                  if type(v['data']) is str:
                      data = [ind[v['data']]]
                  elif type(v['data']) is list:
                      data = list()
                      for d in v['data']:
                          if type(d) is tuple:
                              data.append(getattr(ind[d[0]], d[1]))
                          else:
                              data.append(ind[d])
                  else:
                      data = [datas[v['data']]]
                  
                  ind[k] = v['ind'](*data, plotname=k, **kwargs)
              
              return ind
          
          if __name__ == '__main__':
            save_indicators()
          
          # strategy.py
          import backtrader as bt
          from define_indicators import build_indicators
          
          class St(bt.Strategy):
          
            def __init__(self):
          
                  f = open(INDICATORS_FILENAME, 'rb')
                  indicators = pickle.load(f)
          
                  self.indicators = build_indicators(self.datas, indicators)
          1 Reply Last reply Reply Quote 0
          • 1 / 1
          • First post
            Last post
          Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors