Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    TypeError: super(type, obj): obj must be an instance or subtype of type

    General Code/Help
    2
    11
    1222
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Giovanni Caridi
      Giovanni Caridi last edited by

      Hello, I'm starting to use Backtrader library. I had code some lines to download data from Yahoo Finance and add to cerebro.
      But when I run the code I have this error, how can I fix it?

      start = datetime.datetime(2014, 1, 1)
      end = datetime.datetime(2019, 3, 1)
      
      df = data.get_data_yahoo('UBI.MI', start, end)
      df.to_csv('/Users/giovannicaridi/.spyder-py3/UBI.csv')
      
      if __name__ == '__main__':          
                               
      cerebro = bt.Cerebro() 
      
      cerebro.addstrategy(Cross_Medie)
      
      modpath = os.path.basename(os.path.abspath(sys.argv[0]))  
      datapath = os.path.join(modpath,'/Users/giovannicaridi/.spyder-py3/UBI.csv')  
      
      
      data = bt.feeds.YahooFinanceData(
      dataname = datapath,
      fromdate = datetime.datetime(2015,1,1),
      todate = datetime.datetime(2018,12,31), 
      reverse=False)   
      
      
      
      File 
      "/Users/giovannicaridi/opt/anaconda3/lib/python3.7/sitepackages/backtrader/feeds/yahoo.py", line 94, in start
      super(YahooFinanceCSVData, self).start()
      TypeError: super(type, obj): obj must be an instance or subtype of type
      

      Thanks for you support

      Regards,
      Giovanni

      1 Reply Last reply Reply Quote 0
      • run-out
        run-out last edited by

        Read about it here. You can do it just like in this.

            data = bt.feeds.YahooFinanceData(
                dataname="FB",
                fromdate=datetime.datetime(2020, 1, 1),
                todate=datetime.datetime(2020, 6, 30),
                reverse=False)
        
        

        RunBacktest.com

        Giovanni Caridi 1 Reply Last reply Reply Quote 0
        • Giovanni Caridi
          Giovanni Caridi @run-out last edited by

          @run-out I changed my code but same error occured:

          if __name__ == '__main__':          
                                     
          
          # Inizializzo istanza Cerebro
          cerebro = bt.Cerebro() 
          
          # Aggiungo una strategia
          cerebro.addstrategy(Cross_Medie)
          
          # Inizializzo il file (inserisco i dati storici mettendo il percorso completo del file
          modpath = os.path.basename(os.path.abspath(sys.argv[0]))  
          
          # Salvo i dati nella variabile data (Create a Data Feed)
          data = bt.feeds.YahooFinanceData(
          dataname = "FB",
          fromdate = datetime.datetime(2015,1,1), # Do not pass values before this date
          todate = datetime.datetime(2018,12,31), # Do not pass values after this date
          reverse=False)   
          
          # Aggiungiamo i dati a Cerebro
          cerebro.adddata(data)
          
          # Imposto il portafoglio depositando il capitale iniziale
          capitale_iniziale = 100000
          cerebro.broker.setcash(capitale_iniziale) 
          
          # Imposto il numero di azioni che traderò
          cerebro.addsizer(bt.sizers.FixedSize, stake=1000)
          
          # Imposto il valore delle commissioni
          cerebro.broker.setcommission(commission=0.0002)
          
          # Stampo le condizioni iniziali
          print('Valore iniziale Portafoglio: %.2f' % cerebro.broker.getvalue())
          
          # Avvio l'instanza (il programma)
          cerebro.run()    
          
          # Stampo le condizioni finali
          print('Valore del Portafoglio iniziale: %.2f' % cerebro.broker.getvalue())
          cerebro.broker.getvalue()
          
          1 Reply Last reply Reply Quote 0
          • run-out
            run-out last edited by

            I lifted your code;

            data = bt.feeds.YahooFinanceData(
            dataname = "FB",
            fromdate = datetime.datetime(2015,1,1), # Do not pass values before this date
            todate = datetime.datetime(2018,12,31), # Do not pass values after this date
            reverse=False)   
            

            verbatum into my module and it works. So this means your setup must be missing something.

            I had a look at the backtrader class for bt.feeds.YahooFinanceData and it indicates you must have the request library installed.

            except ImportError:
            msg = ('The new Yahoo data feed requires to have the requests '
            'module installed. Please use pip install requests or '
            'the method of your choice')

            Have a look to see if you have requests installed.

            RunBacktest.com

            Giovanni Caridi 1 Reply Last reply Reply Quote 0
            • Giovanni Caridi
              Giovanni Caridi @run-out last edited by

              @run-out said in TypeError: super(type, obj): obj must be an instance or subtype of type:

              YahooFinanceData

              I have these setting:

              pip install backtrader

              from future import (absolute_import, division, print_function,unicode_literals)
              import backtrader as bt
              import backtrader.indicators as btind
              import backtrader.analyzers as btanalyzers
              import datetime # For datetime objects
              import os.path # To manage paths
              import sys # To find out the script name (in argv[0])

              import numpy as np
              import pandas as pd
              import matplotlib.pyplot as plt
              pd.core.common.is_list_like = pd.api.types.is_list_like
              from pandas_datareader import data, wb
              import yfinance as yf
              import datetime

              1 Reply Last reply Reply Quote 0
              • Giovanni Caridi
                Giovanni Caridi last edited by

                I run the code into Jupyter using CSV file saved after Yahoo importing but no trades happened, porfolio values before and after the test is egual and no print out appear:

                class Cross_Medie(bt.Strategy):
                         params = (('Med_vel',50), ('Med_len', 100))
                
                         # Inizializzo le due medie
                  def __init__(self):
                        self.sma_vel = btind.SMA(period = self.p.Med_vel)
                        self.sma_len = btind.SMA(period = self.p.Med_len)
                    
                    # Definisco il segnale di acquisto/vendita
                    self.buysig = btind.CrossOver(self.sma_vel, self.sma_len)
                    
                    # Salvo i dati di closing (self.datas[0] è l'orologio del sistema, 
                    # utile per verificare se una candela in chiusura rompre una media/indicatore)
                    # Keep a reference to the "close" line in the data[0] dataseries
                    self.dataclose = self.datas[0].close
                
                def next(self):
                
                if  self.position.size:    # verifico se sono in posizione
                    
                      if self.buysig < 0:  # vuol dire che sono dentro long (incrocio a ribasso)
                          self.close()     # chiudo la posizione esistente
                          self.sell()      
                        
                      elif self.buysig > 0: # vuol dire che sono dentro short (incrocio a rialzo)
                          self.close()      # chiudo la posizione esistente
                          self.buy()
                        
                else:                     # non sono in posizione
                         
                    if self.buysig > 0:   # segnale positivo 
                        self.buy()        # acquisto
                        
                    elif self.buysig < 0: # segnale negativo
                        self.sell()       # vendo
                        
                      
                def stampa(self, txt, dt=None):
                
                      dt = dt or self.datas[0].datetime.date(0)  
                      print('%s, %s' % (dt.isoformat(), txt))    
                
                
                def notify_order(self, order):
                
                       if order.status in [order.Submitted, order.Accepted]:
                       # ordine acquisto/vendita accettato
                       return
                
                # Verifica se ordine completato
                if order.status in [order.Completed]:
                    if order.isbuy():
                        # Stampo dettaglio di quantità, prezzo e commissioni
                        self.stampa('ACQ ESEGUITO, QTY: %.2f, PREZZO: %.2f, COSTO: %.2f, COMM: %.2f')
                        % (order.executed.size,order.executed.price,order.executed.comm))
                
                        self.buyprice = order.executed.price
                        self.buycomm = order.executed.comm
                
                    else: # Vendita
                        self.stampa('VEND ESEGUITA, QTY: %.2f, PREZZO: %.2f, COSTO: %.2f, COMM: %.2f')
                        % (order.executed.size,order.executed.price,order.executed.comm))
                
                        self.bar_executed = len(self)
                        
                elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                  self.stampa('Ordine Cancellato')
                 
                self.order = None    
                  
                
                def notify_trade(salef, trade):
                if not trade.isclosed:
                    return
                self.stampa('PROFITTO OPERAZIONE, LORDO %.2f, NETTO %.2f' % (trade.pnl, trade.pnlcomm))        
                        
                    
                dataAAPL = yf.download("AAPL", start="2015-01-01", end="2019-04-30")
                dataAAPL.to_csv('/Users/giovannicaridi/.spyder-py3/AAPL.csv')
                

                ​

                if __name__ == '__main__':       
                                           
                
                # Inizializzo istanza Cerebro
                cerebro = bt.Cerebro() 
                
                # Aggiungo una strategia
                cerebro.addstrategy(Cross_Medie)
                
                # Inizializzo il file (inserisco i dati storici mettendo il percorso completo del file
                modpath = os.path.basename(os.path.abspath(sys.argv[0]))  
                datapath = os.path.join(modpath, '/Users/giovannicaridi/.spyder-py3/AAPL.csv')
                
                # Salvo i dati nella variabile data (Create a Data Feed)
                data = bt.feeds.YahooFinanceData(
                       dataname = datapath,
                       fromdate = datetime.datetime(2016,1,1), # Do not pass values before this date
                       todate = datetime.datetime(2018,12,31), # Do not pass values after this date
                       reverse=False)   
                
                # Aggiungiamo i dati a Cerebro
                cerebro.adddata(data)
                capitale_iniziale = 100000
                cerebro.broker.setcash(capitale_iniziale) 
                
                # Imposto il numero di azioni che traderò
                cerebro.addsizer(bt.sizers.FixedSize, stake=1000)
                
                # Imposto il valore delle commissioni
                cerebro.broker.setcommission(commission=0.0002)
                
                # Stampo le condizioni iniziali
                print('Valore iniziale Portafoglio: %.2f' % cerebro.broker.getvalue())
                cerebro.run()    
                
                # Stampo le condizioni finali
                print('Valore del Portafoglio finale: %.2f' % cerebro.broker.getvalue())
                cerebro.broker.getvalue() 
                

                [100%**] 1 of 1 completed
                Valore iniziale Portafoglio: 100000.00
                Valore del Portafoglio finale: 100000.00

                Giovanni Caridi 1 Reply Last reply Reply Quote 0
                • Giovanni Caridi
                  Giovanni Caridi @Giovanni Caridi last edited by

                  I tried now to re-run and appear this error:

                  File "<tokenize>", line 140
                  dataname = datapath,
                  ^
                  IndentationError: unindent does not match any outer indentation level

                  1 Reply Last reply Reply Quote 0
                  • run-out
                    run-out last edited by

                    @Giovanni-Caridi said in TypeError: super(type, obj): obj must be an instance or subtype of type:

                    if name == 'main':

                    After the if name == 'main': line, you must indent all of the following code by 4 spaces.

                    RunBacktest.com

                    Giovanni Caridi 1 Reply Last reply Reply Quote 1
                    • Giovanni Caridi
                      Giovanni Caridi @run-out last edited by

                      @run-out Done, but I have this output:

                      [100%**] 1 of 1 completed
                      Valore iniziale Portafoglio: 100000.00
                      Valore del Portafoglio finale: 100000.00

                      No print out, no trades happened..

                      1 Reply Last reply Reply Quote 0
                      • Giovanni Caridi
                        Giovanni Caridi last edited by

                        In Spyder I have the same initial error:

                        File "/Users/giovannicaridi/opt/anaconda3/lib/python3.7/site-packages/backtrader/feeds/yahoo.py", line 94, in start
                        super(YahooFinanceCSVData, self).start()

                        TypeError: super(type, obj): obj must be an instance or subtype of type

                        1 Reply Last reply Reply Quote 0
                        • Giovanni Caridi
                          Giovanni Caridi last edited by

                          This could be the solution?

                          In Python 3, using the new super().__init__() instead of super(Derived, self).__init__() solves the problem.
                          Source: https://stackoverflow.com/a/52898473/2476373

                          1 Reply Last reply Reply Quote 0
                          • 1 / 1
                          • First post
                            Last post
                          Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors