retrieve backtraders information as a dataframe
-
Hi,
I'm pretty new to backtrader. I've read through the manual but haven't found the answer yet to a question I have. Is there a way to retrieve everything you feed into backtrader as a dataframe.
for example, we feed OHLC data into backtrader, we create 2 moving averages, we add a long and short signal when crossing over etc.
Is there a way to then also get all this information in a dataframe? eg the columns would look something like:
Date, Open, High, Low, Close, MA1, MA2, Signal
thanks
-
Using analyzers. The return of running cerebro is a strategy object.
strat = cerebro.run()
'strat' in this case is a strategy object and will contain any analyzers you have built and added to the cerebro engine. The analyzer will be the data in the form of a dictionary. In your case because you desire your custom indicators along with your OHLCV, you could build a custom analyzer. Here is an example you can use for the class definition:
class OHLCMMS(bt.analyzers.Analyzer): """This analyzer reports the OHLCV +lines of each of datas. Params: - timeframe (default: ``None``) If ``None`` then the timeframe of the 1st data of the system will be used - compression (default: ``None``) Only used for sub-day timeframes to for example work on an hourly timeframe by specifying "TimeFrame.Minutes" and 60 as compression If ``None`` then the compression of the 1st data of the system will be used Methods: - get_analysis Returns a dictionary with returns as values and the datetime points for each return as keys """ def start(self): tf = min(d._timeframe for d in self.datas) self._usedate = tf >= bt.TimeFrame.Days self.rets = {} def next(self): self.rets[self.data.datetime.datetime()] = [ self.datas[0].open[0], self.datas[0].high[0], self.datas[0].low[0], self.datas[0].close[0], self.MA1[0], self.MA2[0], self.signal[0], ] def get_analysis(self): return self.rets
To add this to cerebro:
cerebro.addanalyzer(OHLCMMS, _name="OHLCMMS")
After you run the backtest you can extract your information from 'strat' as follows:
strat[0].analyzers.getbyname("OHLCMMS").get_analysis()
Which you can then turn into a dataframe as:
df = pd.DataFrame.from_dict( strat[0].analyzers.getbyname("OHLCMMS").get_analysis(), orient="index", columns=["open", "high", "low", "close", "MA1", "MA2", "signal"], )
-
@run-out thanks a lot, really appreciated! hadn't read that far yet so should have just read the full guide first.
-
@run-out that is smart,thanks