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

Adding multiple indicators from csv



  • I'm trying to add a second indicator into my datafeed class but it doesn't work
    I tried different options but nothing, I show the last script

    class GenericCSV_PE(btfeeds.GenericCSVData):

    lines = ('1indicator',),('2indicator',)
      
    params = (('1indicator',8),('2indicator', 9),)
    

    this is the output

    TypeError: getattr(): attribute name must be string.

    Thanks in advance



  • Using this code I can create the class but it doesn't work

    import backtrader as bt
    import backtrader.feeds as btfeeds
    from datetime import datetime
    from datetime import date
    import backtrader.plot
    import matplotlib
    matplotlib.use('TKAgg')
    from matplotlib import pyplot as plt
    from backtrader_plotting import Bokeh
    from backtrader_plotting.schemes import Tradimo

    class GenericCSV_PE(btfeeds.GenericCSVData):

    params = (
        ('dtformat', '%Y%m%d'),
        ('datetime', 0),
        ('open', 1),
        ('high', 2),
        ('low', 3),
        ('close', 4),
        ('adjusted',5),
        ('volume', 6),
        ('1indicator',7),
        ('2indicator',8),
            )
    

    class trump_lev(bt.Strategy):

    def __init__(self):
        self.2indicator = data.2indicator
    self.1indicator = data.1indicator
    def next(self):
        if not self.position:
            if self.1indicator[-1]>35:
                if self.2indicator'[-1] < -0.5:
                    self.sell(size=1)
                if self.dyn_corr[-1]>0.3:
                    self.buy(size=1)
    
    
    
        else:
            if self.1indicator[-1]>35:
                if self.position.size >0:
    
                     if self.dyn_corr[-1] < -0.2:
                        self.close(size=1)
    
    
                elif self.position.size<0:
                      if self.dyn_corr[-1]>0.2  :
                        self.close(size=1)
        portvalue = cerebro.broker.getvalue()
    
        print('Portfolio Value: ${}'.format(portvalue))
        print(self.position.size) 
    

    .......



  • I wonder how it even compiles. Identifiers in python can't start with a number.

    Quoting https://beginnersbook.com/2019/03/python-keywords-and-identifiers/:

    • The name of the variable must always start with either a letter or an underscore (_). For example: _str, str, num, _num are all valid name for the variables.
    • The name of the variable cannot start with a number. For example: 9num is not a valid variable name.
    • The name of the variable cannot have special characters such as %, $, # etc, they can only have alphanumeric characters and underscore (A to Z, a to z, 0-9 or _ ).
    • Variable name is case sensitive in Python which means num and NUM are two different variables in python.


  • I'm sorry this is the exact code. 1indicator and 2 indicator was generic

    import backtrader as bt
    import backtrader.feeds as btfeeds
    from datetime import datetime
    from datetime import date
    import backtrader.plot
    import matplotlib
    matplotlib.use('TKAgg')
    from matplotlib import pyplot as plt
    from backtrader_plotting import Bokeh
    from backtrader_plotting.schemes import Tradimo

    class GenericCSV_PE(btfeeds.GenericCSVData):
    params = (
    ('dtformat', '%Y%m%d'),
    ('datetime', 0),
    ('open', 1),
    ('high', 2),
    ('low', 3),
    ('close', 4),
    ('adjusted',5),
    ('volume', 6),
    ('dyn_corr',8),
    # ('trump_trend',9),
    )

    ################################################### strategy n. ###################################################

    class trump_lev(bt.Strategy):

    def __init__(self):
        self.dyn_corr = data.dyn_corr
        self.trump_trend = data.trump_trend
    def next(self):
        if not self.position:
            if self.trump_trend[-1]>35:
                if self.dyn_corr[-1] < -0.5:
                    self.sell(size=1)
                if self.dyn_corr[-1]>0.3:
                    self.buy(size=1)
    
    
        else:
            if self.trump_trend[-1]>35:
                if self.position.size >0:
    
                     if self.dyn_corr[-1] < -0.2:
                        self.close(size=1)
    
    
                elif self.position.size<0:
                      if self.dyn_corr[-1]>0.2  :
                        self.close(size=1)
        portvalue = cerebro.broker.getvalue()
    
        print('Portfolio Value: ${}'.format(portvalue))
        print(self.position.size)     
    

    #Variable for our starting cash
    startcash = 3000

    #Create an instance of cerebro
    cerebro = bt.Cerebro()

    #Add our strategy
    cerebro.addstrategy(trump_lev)

    #Get S&P500 from CSV
    data = GenericCSV_PE(
    dataname= r'C:\Users\MARCOFIORAVANTIPC\Google Drive\MSC FINANCE AND BANKING\thesis_2\apollo 1\dataset\dataset.csv',

    fromdate=datetime(2019, 1, 1),
    

    todate=datetime.datetime(2019, 12, 31),

    nullvalue=0.0,
    
    dtformat=('%Y-%m-%d'),
    
    datetime = 1,
    open = 2,
    high = 3,
    low = 4,
    
    close = 5,
    adjusted = 6,
    

    volume = 7,

    dyn_corr = 12,
    trump_trend = 13,
    
        )
    

    #Add the data to Cerebro
    cerebro.adddata(data)

    Set our desired cash start

    cerebro.broker.setcash(startcash)

    Run over everything

    cerebro.run()

    #Get final portfolio Value
    portvalue = cerebro.broker.getvalue()
    pnl = portvalue - startcash

    #Print out the final result
    print('Final Portfolio Value: ${}'.format(portvalue))
    print('Initial Portfolio Value: ${}'.format(startcash))
    print('P/L: ${}'.format(pnl))

    #Finally plot the end results
    cerebro.plot(iplot=False)
    cerebro.plot()


Log in to reply
 

});