How can I get observers records for custom plotting?
-
The built-in plotting style not good for me, I want to draw with
plotly
. But how can I export the trade record, cash/value record, etc..? -
@asdasda I use plotly. You can export your analyzers (not observers) at the end of your backtest. When you call:
cerebro.run()
cerebro returns a list of strategy objects at the end of the backtest. Usually you run one backtest a time so there's only one strategy object in the list, but some people run multiple strategies at once.
In the strategy object are all the analyzers, amongst other things.
The analyzers are contained in a list so that if you go:
strat = cerebro.run() # analyzers are found in a list here. strat[0].analyzers # you find all the analyzers here.
There's a handy method to get the results of your analyzer.
strat[0].analyzers.getbyname("trade_list").get_analysis()
Analyzers have different outputs so it's really up to you to move this data to a csv/excel/db file.
Here is an example of an analyzer being converted for a database and for going to an excel sheet.
Here's an example of an analyzer and the code I use after to convert it to db and excel.
# ANALYZER: class CashMarket(bt.analyzers.Analyzer): """ Analyzer returning cash and market values """ def __init__(self): self.current_date = None def start(self): super(CashMarket, self).start() def create_analysis(self): self.rets = {} self.vals = 0.0 def notify_cashvalue(self, cash, value): date = self.data.datetime.date() if date != self.current_date: self.vals = (cash, value) self.rets[self.strategy.datetime.datetime()] = self.vals self.current_date = date else: pass def get_analysis(self): return self.rets # CONVERTING RESULTS def cashmarket( scene, analyzer, test_number, workbook=None, sheet_format=None, agg_dict=None ): """ Portfolio cash and total values. :param workbook: Excel workbook to be saved to disk. :param analyzer: Backtest analyzer. :param sheet_format: Dictionary holding formatting information such as col width, font etc. :param agg_dict: Collects the dictionary outputs from backtrader for using in platting. :return workbook: Excel workbook to be saved to disk. """ # Get the stats auto ordered nested dictionary value = analyzer.get_analysis() columns = [ "Date", "Cash", "Value", ] if scene["save_db"]: df = pd.DataFrame(value) df = df.T df = df.reset_index() df.columns = columns df = add_key_to_df(df, test_number) agg_dict["value"] = df if scene["save_excel"]: worksheet = workbook.add_worksheet("value") worksheet.write_row(0, 0, columns) worksheet.set_row(0, None, sheet_format["header_format"]) worksheet.set_column("A:C", sheet_format["wide"], sheet_format["float_2d"]) for i, (k, v) in enumerate(value.items()): date = k.strftime("%y-%m-%d %H:%M") worksheet.write_row(i + 1, 0, [date]) worksheet.write_row(i + 1, 1, v) return workbook, agg_dict
-
@run-out It looks good, thank you.
-
@run-out But why my analyzers are empty? I had run
strategies = cerebro.run()
. -