For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
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' % ( len(self), self.data.l.Signal[0],)) # Create a cerebro entity cerebro = bt.Cerebro(stdstats=False) # Add a strategy cerebro.addstrategy(StrategyPrint) dataframe = pandas.read_csv(datapath, index_col=0) print('--------------------------------------------------') print(dataframe) print('--------------------------------------------------') # Pass it to the backtrader datafeed and add it to the cerebro data = StratData(dataname=dataframe) cerebro.adddata(data) # Run over everything cerebro.run()
CSV File:
Date,Signal
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,RUNError Log:
File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\backtrader\cerebro.py", line 1127, in run runstrat = self.runstrategies(iterstrat) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\backtrader\cerebro.py", line 1212, in runstrategies data.preload() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\backtrader\feed.py", line 438, in preload while self.load(): File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\backtrader\feed.py", line 479, in load _loadret = self._load() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\backtrader\feeds\pandafeed.py", 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\linebuffer.py", 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.