简体   繁体   中英

Backtrader issue

I have this error when I run my code using Backtrader library:

**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**

This is my code:

   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   
   import os.path    
   import sys        


  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




class Cross_Medie(bt.Strategy):

# Definisco la media veloce e la media lenta (utile per l'ottimizzazione)
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):

# Funzione di stampa per capire cosa sta succedendo
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


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))        
        
    
    
    

 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/GOOGL.csv')


 # Salvo i dati nella variabile data (Create a Data Feed)
 data = bt.feeds.YahooFinanceCSVData(dataname = datapath, fromdate = 
 datetime.datetime(2016,1,1),todate = datetime.datetime(2018,12,31),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 finale: %.2f' % cerebro.broker.getvalue())
 cerebro.broker.getvalue() 

It seems like you're not using the formatter correctly in your calls to self.stampa() .

Change it to (look at the parentheses):

self.stampa('ACQ ESEGUITO, QTY: %.2f, PREZZO: %.2f, COSTO: %.2f, COMM: %.2f' % (order.executed.size, order.executed.price, order.executed.value, order.executed.comm)) 

And:

self.stampa('VEND ESEGUITA, QTY: %.2f, PREZZO: %.2f, COSTO: %.2f, COMM: %.2f' % (order.executed.size, order.executed.price, order.executed.value, order.executed.comm))

You'll then get:

Valore iniziale Portafoglio: 100000.00
2016-11-08, Ordine Cancellato
2017-01-26, VEND ESEGUITA, QTY: -1000.00, PREZZO: 3613425305.27, COSTO: -3613425305270.00, COMM: 722685061.05
2017-04-28, Ordine Cancellato
2017-04-28, Ordine Cancellato
2017-05-23, ACQ ESEGUITO, QTY: 1000.00, PREZZO: 3211721136.68, COSTO: -3613425305270.00, COMM: 642344227.34
2017-05-23, VEND ESEGUITA, QTY: -1000.00, PREZZO: 3211721136.68, COSTO: -3211721136680.00, COMM: 642344227.34

I try also to run cerebro.plot() but no graph is showed

cerebro.plot()
<IPython.core.display.Javascript object>
<IPython.core.display.HTML object>
Out[2]: [[<Figure size 432x288 with 5 Axes>]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM