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

Can we iterate string as datafeed?

  • I am using indicators value to run few of my strategies, for which I need to iterate it over string.

    import backtrader as bt
    import pandas
    import backtrader.feeds as btfeeds
    class StratData(btfeeds.PandasData):
        lines = ('Signal',)
        params = (
            ('open', None),
            ('high', None),
            ('low', None),
            ('close', None),
            ('volume', None),
            ('openinterest', None),
            ('Signal', 'Signal')
    class StrategyPrint(bt.Strategy):
        def next(self):
            print('%03d , %f' % (
    # Create a cerebro entity
    cerebro = bt.Cerebro(stdstats=False)
    # Add a strategy
    dataframe = pandas.read_csv(datapath, index_col=0)
    # Pass it to the backtrader datafeed and add it to the cerebro
    data = StratData(dataname=dataframe)
    # Run over everything

    CSV File:

    01-04-2020 08:00,RUN
    02-04-2020 08:00,STOP
    03-04-2020 08:00,STOP
    04-04-2020 08:00,RUN
    05-04-2020 08:00,RUN

    Error Log:

    File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\backtrader\", line 1127, in run
      runstrat = self.runstrategies(iterstrat)
    File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\backtrader\", line 1212, in runstrategies
    File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\backtrader\", line 438, in preload
      while self.load():
    File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\backtrader\", line 479, in load
      _loadret = self._load()
    File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\backtrader\feeds\", line 255, in _load
      line[0] = self.p.dataname.iloc[self._idx, colindex]
    File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\backtrader\", line 222, in __setitem__
      self.array[self.idx + ago] = value
    TypeError: must be real number, not str

  • Try changing RUN / STOP to 1 / 0.

  • Yes, that works. Problem is that my other model provides output in string format. I don't want to map the values. Regards.

  • You can load the data as a pandas dataframe first in backtrader, then run a simple script to convert the columns, and then load. This way you don't need to do anything with your data ongoing.

Log in to reply