ok, just figured it out. I can reuse the DataTrades observer. No change needed for the MetaDataTrades class. It will generate multiple lines for the assets. The author sure constructed backtrader to be versatile!
Here is my code to show pnl in individual asset. Just accumulate daily settled pnl for each asset. Haven't checked the exact numbers yet. Eyeballing it looks alright comparing to the total account pnl.
class Aseet_monitor(bt.utils.py3.with_metaclass(MetaDataTrades, bt.observer.Observer)):
_stclock = True
params = (('usenames', True),)
plotinfo = dict(plot=True, subplot=True, plothlines=[0.0],
plotymargin=0.10, plotlinelabels=True)
plotlines = dict()
def next(self):
strat = self._owner
for inst in strat.datas:
pos = strat.broker.positions[inst]
cur_line = getattr(self.lines, inst._name)
comminfo = strat.broker.getcommissioninfo(inst)
if len(self) == 1:
cur_line[0] = 0
else:
if pos.size != 0:
cur_pnl = comminfo.profitandloss(pos.size, inst.close[-1],
inst.close[0])
else:
cur_pnl = 0
cur_line[0] = cur_line[-1] + cur_pnl
Here is the output. The whole strategy is carried by HG_copper, while CL and ZN are underwater almost the whole time.
Comparing to the Value observer.