...and an alternative implementation showing % contribution of each asset to overall portfolio value --
class PortfolioObserverPercent0(bt.observer.Observer):
_stclock = True
lines = ()
CASH_LINE = '$CASH'
REBALANCE_LINE = '_REBALANCE'
plotinfo = dict(plot=True, subplot=True, plotlinelabels=True, plotlinevalues=False, plothlines=[100.0])
plotlines = dict(_REBALANCE=dict(marker='|', markersize=8.0, color='gray'))
def next(self):
# total portfolio value
tot_value = self._owner.broker.get_value()
# add cash
cumsum = self._owner.broker.get_cash()
self.set_line(self.CASH_LINE, 0, cumsum / tot_value * 100)
# add symbol positions
for data in self.datas:
dname = data._name
cumsum += self._owner.broker.get_value([data])
self.set_line(dname, 0, cumsum / tot_value * 100)
# is this a rebalancing day?
if self._owner._orderspending:
self.set_line(self.REBALANCE_LINE, 0, 0)
def set_line(self, dname, ind, value):
"""Set named line value at index"""
getattr(self.lines, dname)[ind] = value
def make_portfolio_observer_percent(symbols: tuple):
"""Make portfolio observer with customized list of symbols"""
return type('PortfolioObserverPercent', (PortfolioObserverPercent0,), {'lines': (symbols + (PortfolioObserver0.CASH_LINE, PortfolioObserver0.REBALANCE_LINE))})