Skip to content

Commit 8244585

Browse files
xnoxmementum
authored andcommitted
Allow saving figures, instead of showing them. (mementum#297)
* Allow saving figures, instead of showing them. For example, one can pass --plot savefig=True to bt-run script to store all figures as backtrader-plot-N.pdf files. Useful for running backtests non-interactively and saving plots. Currently stores as PDF, but other naming pattern and file extensions can be used (e.g. 'plot-%i.png'). Current format, figure size, and dpi optimised for widescreen on-screen viewing. * Use png, as those files are smaller.
1 parent 59849b4 commit 8244585

2 files changed

Lines changed: 10 additions & 1 deletion

File tree

backtrader/cerebro.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -865,6 +865,7 @@ def getbroker(self):
865865
broker = property(getbroker, setbroker)
866866

867867
def plot(self, plotter=None, numfigs=1, iplot=True, start=None, end=None,
868+
savefig=False, figfilename='backtrader-plot-%i.png',
868869
**kwargs):
869870
'''
870871
Plots the strategies inside cerebro
@@ -912,7 +913,10 @@ def plot(self, plotter=None, numfigs=1, iplot=True, start=None, end=None,
912913

913914
figs.append(rfig)
914915

915-
plotter.show()
916+
if savefig:
917+
plotter.savefig(figfilename % len(figs))
918+
else:
919+
plotter.show()
916920
return figs
917921

918922
def __call__(self, iterstrat):

backtrader/plot/plot.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -755,6 +755,11 @@ def plotdata(self, data, indicators):
755755
def show(self):
756756
self.mpyplot.show()
757757

758+
def savefig(self, filename='backtrader-plot.png'):
759+
fig = self.mpyplot.gcf()
760+
fig.set_size_inches(16, 9)
761+
self.mpyplot.savefig(filename, dpi=300, bbox_inches='tight')
762+
758763
def sortdataindicators(self, strategy):
759764
# These lists/dictionaries hold the subplots that go above each data
760765
self.dplotstop = list()

0 commit comments

Comments
 (0)