The problem with this approach is around edge cases: if we buy on the ex-div date, the function will run and return dividend, even though it shouldn't. Likewise, if we sell on ex-div date the function won't run and the dividend won't be calculated.
Posts made by ovix
RE: broker.addcommissioninfo: how to add two classes Dividends and Commision?
RE: Save cerebro data to file for later plotting it on another computer
Edit 2: actually, error below is only when I add more than one data. For one data, it works fine. I can deserialize and plot no problem..
Edit: never mind, there's a problem with this method.. getting a different error:
AttributeError: Can't get attribute 'Lines_LineSeries_LineIterator_DataAccessor_ObserverBase_Observer_DataTrades_ba0f06d924224f95b2bf7797aa7ce535'
Backtrader skips pickling the 'runstrats' attribute, as seen in cerebro.py here:
def __getstate__(self): ''' Used during optimization to prevent optimization result `runstrats` from being pickled to subprocesses ''' rv = vars(self).copy() if 'runstrats' in rv: del(rv['runstrats']) return rv
I extended cerebro and overriden the method, so it pickles everything:
class MyCerebro(Cerebro): def __getstate__(self): return vars(self)
Just use "MyCerebro()" instead of bt.cerebro() and pickle that.
RE: How to save figures generated by cerebro.plot?
I just unwrapped the plot() method so I can have better control over what's going on:
def processPlots(self, cerebro, numfigs=1, iplot=True, start=None, end=None, width=16, height=9, dpi=300, tight=True, use=None, **kwargs): # if self._exactbars > 0: # return from backtrader import plot if cerebro.p.oldsync: plotter = plot.Plot_OldSync(**kwargs) else: plotter = plot.Plot(**kwargs) figs =  for stratlist in cerebro.runstrats: for si, strat in enumerate(stratlist): rfig = plotter.plot(strat, figid=si * 100, numfigs=numfigs, iplot=iplot, start=start, end=end, use=use) figs.append(rfig) # this blocks code execution # plotter.show() for fig in figs: for f in fig: f.savefig('../../static/foo.pdf', bbox_inches='tight') return figs
Just pass in cerebro instance and parameters as you normally would into the plot() function. Not sure why it breaks down figures into lists the way it does, probably to handle multiple plots, so gotta implement that.