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

How to restrict cerebro to plot only curves I need?



  • Hi,
    I was working through basic example in the quick start tutorial by plugging in my own data. It happens that my data only has 'Open, High, Low, Close' data and doesn't 'volume' or anything else. When I plugin this data into the quickstart example, cerebro.plot() is throwing errors like below which I believe is due to lack of 'volume' data.

    '''
    File "C:\Users\digaurav\AppData\Local\Continuum\anaconda3\lib\site-packages\backtrader\plot\plot.py", line 645, in plotdata
    data, opens, highs, lows, closes, volumes, vollabel)

    File "C:\Users\digaurav\AppData\Local\Continuum\anaconda3\lib\site-packages\backtrader\plot\plot.py", line 591, in plotvolume
    ax.set_ylim(0, volylim, auto=True)

    File "C:\Users\digaurav\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\axes_base.py", line 3272, in set_ylim
    top = self._validate_converted_limits(top, self.convert_yunits)

    File "C:\Users\digaurav\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\axes_base.py", line 2876, in _validate_converted_limits
    raise ValueError("Axis limits cannot be NaN or Inf")
    '''



  • Check out the following doc chapter - Docs - Plotting

    Plotting options have a parameter volume, which control plotting of volume diagram.



  • Hi
    I am not able to figure out from that. Can you please give a code sample. Or my code is below, please be kind to say what change I should make. This code is a slight modification of the quickstart example which just prints close values.

    from __future__ import (absolute_import, division, print_function,
                            unicode_literals)
    
    import datetime  # For datetime objects
    import os.path  # To manage paths
    import sys  # To find out the script name (in argv[0])
    import pandas as pd
    import numpy as np
    import datetime
    import matplotlib
    
    # Import the backtrader platform
    import backtrader as bt
    import backtrader.feeds as btfeeds
    
    def MakeArbitraryData():
        A = np.random.randint(0,10,size=(5,4)) #create 5 X 5 matrix of random integers
        Apd = pd.DataFrame(data=A,columns=['Open','High','Close','Low'])
        DateRange = [datetime.date(2018,3,i) for i in range(1,6)]
        Apd['Date']=pd.Series(DateRange,dtype='datetime64[ns]')
        Apd = Apd.set_index('Date')
        return Apd
        
    #add a strategy to just print close value
    class TestStrategy(bt.Strategy):
        
        def log(self, txt, dt=None):
            """logging function for this strategy
                this is essentially the print function for the strategy"""
            dt = dt or self.datas[0].datetime.date(0)
            print('%s, %s' % (dt.isoformat(),txt))
                
        def __init__(self):
            self.dataclose = self.datas[0].close
            # To keep track of pending orders
            self.order = None
                    
        def next(self):
            self.log('Close, %.2f' % self.dataclose[0])
            
            
            if self.order:
                return
            
            
    
    if __name__ == '__main__':
        # Create a cerebro entity
        cerebro = bt.Cerebro()
        cerebro.addstrategy(TestStrategy)    
        StockData = MakeArbitraryData()
        data = bt.feeds.PandasData(dataname=Stock1Data,
                                   # datetime='Date',
                                   nocase=True,
                                   )
        # Add the Data Feed to Cerebro
        cerebro.adddata(data)
    
        # Set our desired cash start
        cerebro.broker.setcash(1000.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()


  • Try

    cerebro.plot(volume = False)
    

  • administrators


Log in to reply
 

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