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

Cerebro plot failed to run



  • from future import (absolute_import, division, print_function,
    unicode_literals)

    import backtrader as bt

    class TestStrategy(bt.Strategy):

    def log(self, txt, dt=None):
        ''' Logging function fot this strategy'''
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))
    
    def __init__(self):
        # Keep a reference to the "close" line in the data[0] dataseries
        self.dataclose = self.datas[0].close
    
        # To keep track of pending orders and buy price/commission
        self.order = None
        self.buyprice = None
        self.buycomm = None
    
    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            return
    
        # Check if an order has been completed
        # Attention: broker could reject order if not enough cash
        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                    (order.executed.price,
                     order.executed.value,
                     order.executed.comm))
    
                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
            else:  # Sell
                self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                         (order.executed.price,
                          order.executed.value,
                          order.executed.comm))
    
            self.bar_executed = len(self)
    
        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')
    
        self.order = None
    
    def notify_trade(self, trade):
        if not trade.isclosed:
            return
    
        self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                 (trade.pnl, trade.pnlcomm))
    
    def next(self):
        # Simply log the closing price of the series from the reference
        self.log('Close, %.2f' % self.dataclose[0])
    
        # Check if an order is pending ... if yes, we cannot send a 2nd one
        if self.order:
            return
    
        # Check if we are in the market
        if not self.position:
    
            # Not yet ... we MIGHT BUY if ...
            if self.dataclose[0] < self.dataclose[-1]:
                # current close less than previous close
    
                if self.dataclose[-1] < self.dataclose[-2]:
                    # previous close less than the previous close
    
                    # BUY, BUY, BUY!!! (with default parameters)
                    self.log('BUY CREATE, %.2f' % self.dataclose[0])
    
                    # Keep track of the created order to avoid a 2nd order
                    self.order = self.buy()
    
        else:
    
            # Already in the market ... we might sell
            if len(self) >= (self.bar_executed + 5):
                # SELL, SELL, SELL!!! (with all possible default parameters)
                self.log('SELL CREATE, %.2f' % self.dataclose[0])
    
                # Keep track of the created order to avoid a 2nd order
                self.order = self.sell()
    

    if name == 'main':
    # Create a cerebro entity
    cerebro = bt.Cerebro()

    # Add a strategy
    strats = cerebro.addstrategy(
        TestStrategy)
    
    kl = abu.ABuSymbolPd.make_kl_df('F', n_folds=int(2))
    kl = kl[['open', 'high', 'low', 'close', 'volume']]
    data = bt.feeds.PandasData(dataname=kl)
    
    # Add the Data Feed to Cerebro
    cerebro.adddata(data)
    
    # Set our desired cash start
    cerebro.broker.setcash(1000.0)
    cerebro.broker.set_coc(True)
    # Add a FixedSize sizer according to the stake
    cerebro.addsizer(bt.sizers.FixedSize, stake=10)
    
    # Set the commission
    cerebro.broker.setcommission(commission=0.0)
    
    # Print out the starting conditions
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    
    # Run over everything
    cerebro.run()
    
    # Print out the final result
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    
    cerebro.plot()
    

    Above are my code, and whenever I am running cerebro.plot(). I have the following errors.

    <IPython.core.display.HTML object>
    cerebro.plot()
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\backtrader\cerebro.py", line 996, in plot
    plotter.show()
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\backtrader\plot\plot.py", line 794, in show
    self.mpyplot.show()
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\matplotlib\pyplot.py", line 254, in show
    return _show(*args, **kw)
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\matplotlib\backends\backend_nbagg.py", line 255, in show
    manager.show()
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\matplotlib\backends\backend_nbagg.py", line 91, in show
    self._create_comm()
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\matplotlib\backends\backend_nbagg.py", line 123, in _create_comm
    self.add_web_socket(comm)
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\matplotlib\backends\backend_webagg_core.py", line 433, in add_web_socket
    self.resize(w, h)
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\matplotlib\backends\backend_webagg_core.py", line 419, in resize
    size=(w / self.canvas._dpi_ratio, h / self.canvas._dpi_ratio))
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\matplotlib\backends\backend_webagg_core.py", line 490, in _send_event
    s.send_json(payload)
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\matplotlib\backends\backend_nbagg.py", line 199, in send_json
    self.comm.send({'data': json.dumps(content)})
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\ipykernel\comm\comm.py", line 121, in send
    data=data, metadata=metadata, buffers=buffers,
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\ipykernel\comm\comm.py", line 66, in _publish_msg
    self.kernel.session.send(self.kernel.iopub_socket, msg_type,
    AttributeError: 'NoneType' object has no attribute 'session'
    Error in atexit._run_exitfuncs:
    Traceback (most recent call last):
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\matplotlib_pylab_helpers.py", line 74, in destroy_all
    manager.destroy()
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\matplotlib\backends\backend_nbagg.py", line 127, in destroy
    self._send_event('close')
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\matplotlib\backends\backend_webagg_core.py", line 490, in _send_event
    s.send_json(payload)
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\matplotlib\backends\backend_nbagg.py", line 199, in send_json
    self.comm.send({'data': json.dumps(content)})
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\ipykernel\comm\comm.py", line 121, in send
    data=data, metadata=metadata, buffers=buffers,
    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\ipykernel\comm\comm.py", line 66, in _publish_msg
    self.kernel.session.send(self.kernel.iopub_socket, msg_type,
    AttributeError: 'NoneType' object has no attribute 'session'

    Please let me know what goes wrong, thank for your help!


  • administrators

    @heekah7 said in Cerebro plot failed to run:

    Please let me know what goes wrong, thank for your help!

    1. You missed the top of the forum, what basically renders your code unreadable.
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
    
    1. Something is broken well beyond the realm of backtrader

    @heekah7 said in Cerebro plot failed to run:

    File "C:\Users~\PycharmProjects\helloworld\venv\lib\site-packages\ipykernel\comm\comm.py", line 66, in _publish_msg
    self.kernel.session.send(self.kernel.iopub_socket, msg_type,
    AttributeError: 'NoneType' object has no attribute 'session'

    If you see the log, it is everything due to a connection which matplotlib opens. Nothing to do with backtrader