For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

optstrategy() and plotting

  • Hi Everybody, dear @backtrader,

    When I try to use optstrategy() with a Pandas data source, I cannot plot my results to png files. As I understand, this should be possible, according to the documentation:

    savefig: set to True to save to a file rather than plot
    figfilename: name of the file. Use {j} in the name for the strategy index to which the figure corresponds and use `{i}`` to insert figure number if multiple figures are being used per strategy plot

    I'd like to plot my results after each run has finished.

    This is my code:

               if g_save_plot==True:
                   plot_file_path = log_file_path.replace('.txt','_{j}_{i}.png')
                   cerebro.plot(savefig=True, figfilename=plot_file_path) #numfigs=len(g_instruments), 

    However, when I call this, I get an error:

    Traceback (most recent call last):
     File "C:\Baixinho\", line 962, in <module>
       cancelled = bt_backtest.backtest(g_data_source, g_backtest_mode, g_resolution, loaded_training_df, training_fold_ranges_df, model, g_db, test_df, g_log_file_path)                
     File "C:\Baixinho\", line 995, in backtest
       cerebro.plot(savefig=True, figfilename=plot_file_path) #numfigs=len(g_instruments), 
     File "C:\Users\peter\Anaconda3\lib\site-packages\backtrader\", line 927, in plot
       start=start, end=end)
     File "C:\Users\peter\Anaconda3\lib\site-packages\backtrader\plot\", line 119, in plot
       if not strategy.datas:
    AttributeError: 'OptReturn' object has no attribute 'datas'

    And this is line 119 and 120 in (I've just upgraded backtrader to the latest version):

           if not strategy.datas:

    I don’t really get why “strategy” is an OptReturn object, but I’m not a Python expert.

    Do I misunderstand the usage of cerebro.plot() when optimizing strategies?

    Alternatively, it would be great to be able to save the plots separately, when a strategy finished (method stop()). Is that possible?


  • administrators

    OptReturn is a simplified return instance which mimics a strategy, to reduce the overhead of message passing from worker processes to the main process.

    See: Docs - Optimization Improvements

    Plotting has never been tested with optimization (not an expected use case)

Log in to reply

Looks like your connection to Backtrader Community was lost, please wait while we try to reconnect.