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/

    __bool__ should return bool, returned LineOwnOperation

    General Code/Help
    3
    8
    278
    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.
    • Y
      yanke_zulu last edited by

      Hello
      I am receiving the following error, but could not find the problem
      I am comparing two lines and assing result to a boolean variable,

      it was acceptable to compare lines , but I am missing something
      Exception has occurred: TypeError
      bool should return bool, returned LineOwnOperation
      File "Strategy1.2.py", line 251, in next
      if bool1 and bool2:

      class myind(bt.Indicator):
      alias = ('myind',)
      lines = ('Trail1','Trail2',)
      params = (
      ('period', 3),
      ('perc', 2),
      )

      def __init__(self):
          self.alpha = 2.0 / ( self.p.period + 1.0 )
          self.addminperiod(self.p.period)   
          self.l.Trail1=bt.ind.EMA(self.data,period=self.p.period)
          self.l.SL2 = self.l.Trail1*self.p.perc
      
      
      def nextstart(self):  # calculate here the seed value
          self.l.Trail2[0]=0
                      
      def next(self):
          Trail1prev=self.lines.Trail1(-1)
          Trail2prev=self.lines.Trail2[-1]
          SL2 = self.l.Trail1*self.p.perc 
             
          temp1= (self.l.Trail1-self.l.SL2)
          First= bt.Max(Trail2prev, temp1)
          temp2= (self.l.Trail1+self.l.SL2)
          SecondCon1 = bt.Min(Trail2prev, temp2)
          SecondCon2 = bt.If(self.l.Trail1 > Trail2prev, temp1, temp2 )
          boolsecond = self.l.Trail1 < Trail2prev and Trail1prev < Trail2prev
          Second = bt.If( boolsecond, SecondCon1 , SecondCon2 ) 
          
          bool1 = self.l.Trail1 > Trail2prev 
          bool2 = Trail1prev > Trail2prev
          if bool1==True and bool2==True:
              self.l.Trail2[0]= First
          else:
              self.l.Trail2[0]= Second
      vladisld 1 Reply Last reply Reply Quote 0
      • vladisld
        vladisld @yanke_zulu last edited by

        @yanke_zulu said in __bool__ should return bool, returned LineOwnOperation:

        def next(self):
        Trail1prev=self.lines.Trail1(-1)
        Trail2prev=self.lines.Trail2[-1]

        You are using the wrong brackets. Square brackets should be used instead. Parentheses are usually used in init method for declarative expression definitions.

        See the delayed indexing docs for more info

        Y 1 Reply Last reply Reply Quote 1
        • Y
          yanke_zulu @vladisld last edited by

          @vladisld thanks it worked, I just tried with yahoo CSV, only Trail1 comes, Trail2 not shown, is there any changed required if we use CSV data feed

          data = bt.feeds.YahooFinanceCSVData(dataname='AAPL.csv')

          vladisld 1 Reply Last reply Reply Quote 0
          • vladisld
            vladisld @yanke_zulu last edited by

            @yanke_zulu said in __bool__ should return bool, returned LineOwnOperation:

            Trail2 not shown

            Where the 'Trail2' indicator is defined?

            1 Reply Last reply Reply Quote 0
            • Y
              yanke_zulu last edited by

              Re: [bool should return bool](returned LineOwnOperation)

              Trail1 and Trail 2 are in the indicator(shown below) and I am calling the indicator from strategy: myvma=most(self.data)

              Trail1 and Trail2 are plotted with
              data = DataFactory(dataname='AAPL', historical=True, fromdate=datetime(
              2020, 7, 1), timeframe=bt.TimeFrame.Days)

              however .it does not work when I try yahoo csv
              data = bt.feeds.YahooFinanceCSVData(dataname='AAPL.csv')

              class most(bt.Indicator):

              alias = ('most',)
              lines = ('Trail1','Trail2','First' , 'Second',)
              params = (
                  ('period', 3),
                  ('perc', 2),
              )
              plotinfo = dict(subplot=False)
              plotlines = dict(First=dict(_plotskip=True,), Second=dict(_plotskip=True,),
                                        Trail1=dict(alpha=1.0, linestyle='-', linewidth=2.0, color='green'), 
                                        Trail2=dict(alpha=1.0, linestyle='-', linewidth=2.0, color='magenta') )
              
              def __init__(self):
                  self.addminperiod(self.p.period)   
                  self.l.Trail1=bt.ind.EMA(self.data,period=self.p.period)
                  self.perc1=self.p.perc/100
                  #self.l.Trail1=mov_vma(self.data,pds=self.p.period)
                  
              
              #def prenext(self):
              #    self.lines.ud1=self.data.close(0)   
              def nextstart(self):  # calculate here the seed value
                  self.l.Trail2[0]=0
                              
              def next(self):
                  #self.l.SL2[0] = self.l.Trail1[0]/self.p.perc
                  Trail1prev=self.lines.Trail1[-1]
                  Trail2prev=self.lines.Trail2[-1]
                  SL2 = self.l.Trail1*(self.perc1)
                     
                  temp1= (self.l.Trail1-SL2)
                  self.l.First= bt.Max(Trail2prev, temp1)
                  temp2= (self.l.Trail1+ SL2)
                  SecondCon1 = bt.Min(Trail2prev, temp2)
                  SecondCon2 = bt.If(self.l.Trail1 > Trail2prev, temp1, temp2 )
                  boolsecond = self.l.Trail1 < Trail2prev and Trail1prev < Trail2prev
                  self.l.Second = bt.If( boolsecond, SecondCon1 , SecondCon2 ) 
                  
                  bool1 = self.l.Trail1 > Trail2prev 
                  bool2 = Trail1prev > Trail2prev
                  if bool1==True and bool2==True:
                      self.l.Trail2= self.l.First
                  else:
                      self.l.Trail2= self.l.Second
              1 Reply Last reply Reply Quote 0
              • A
                ab_trader last edited by

                Couple recommendations -

                • use backticks as it is recommended on the top of the page for clear code
                • post the whole error message, python usually shows the line of the code which returns the error, which is very helpful.

                show some respect to people who may help to resolve your issue and debug your code instead of you.

                1 Reply Last reply Reply Quote 1
                • A
                  ab_trader last edited by

                  guess the error is here:

                  if bool1==True and bool2==True:
                  

                  variable bool1 and bool2 are bt line objects therefore they can't be used with the standard if. i would recommend you to read documentation and study when you need to use line objects, and when you need to use elements of these line objects. i believe quickstart guide and concepts sections is a good starting point.

                  1 Reply Last reply Reply Quote 2
                  • Y
                    yanke_zulu last edited by

                    I changed the bool1 as mybool1 , nothing changed
                    in fact it works when I use 1 option as data,
                    but when I use 2. option(yahoo csv), I can only see Trail1

                    1-option
                    data = DataFactory(dataname=symbol, historical=True, fromdate=datetime(
                    2020, 7, 1), timeframe=bt.TimeFrame.Days)"
                    2-option

                    from matplotlib.dates import (HOURS_PER_DAY, MIN_PER_HOUR, SEC_PER_MIN,
                    MONTHS_PER_YEAR, DAYS_PER_WEEK,
                    SEC_PER_HOUR, SEC_PER_DAY,
                    num2date, rrulewrapper, YearLocator,
                    MicrosecondLocator)

                    import math
                    import alpaca_backtrader_api
                    import backtrader as bt
                    import backtrader.indicators as btind
                    from datetime import datetime
                    import numpy as np
                    import pandas as pd
                    import matplotlib.pyplot as plt

                    symbol = "AAPL"

                    ALPACA_API_KEY = ""
                    ALPACA_SECRET_KEY = ""
                    ALPACA_PAPER = True

                    class most(bt.Indicator):

                    alias = ('most',)
                    lines = ('Trail1','Trail2','First' , 'Second',)
                    params = (
                        ('period', 3),
                        ('perc', 2),
                    )
                    plotinfo = dict(subplot=False)
                    plotlines = dict(First=dict(_plotskip=True,), Second=dict(_plotskip=True,),
                                              Trail1=dict(alpha=1.0, linestyle='-', linewidth=2.0, color='green'), 
                                              Trail2=dict(alpha=1.0, linestyle='-', linewidth=2.0, color='magenta') )
                    
                    def __init__(self):
                        self.addminperiod(self.p.period)   
                        self.l.Trail1=bt.ind.EMA(self.data,period=self.p.period)
                        self.perc1=self.p.perc/100
                        #self.l.Trail1=mov_vma(self.data,pds=self.p.period)
                        
                    
                    #def prenext(self):
                    #    self.lines.ud1=self.data.close(0)   
                    def nextstart(self):  # calculate here the seed value
                        self.l.Trail2[0]=0
                                    
                    def next(self):
                        #self.l.SL2[0] = self.l.Trail1[0]/self.p.perc
                        Trail1prev=self.lines.Trail1[-1]
                        Trail2prev=self.lines.Trail2[-1]
                        SL2 = self.l.Trail1*(self.perc1)
                           
                        temp1= (self.l.Trail1-SL2)
                        self.l.First= bt.Max(Trail2prev, temp1)
                        temp2= (self.l.Trail1+ SL2)
                        SecondCon1 = bt.Min(Trail2prev, temp2)
                        SecondCon2 = bt.If(self.l.Trail1 > Trail2prev, temp1, temp2 )
                        boolsecond = self.l.Trail1 < Trail2prev and Trail1prev < Trail2prev
                        self.l.Second = bt.If( boolsecond, SecondCon1 , SecondCon2 ) 
                        
                        mybool1 = self.l.Trail1 > Trail2prev 
                        mybool2 = Trail1prev > Trail2prev
                        if mybool1==True and mybool2==True:
                            self.l.Trail2= self.l.First
                        else:
                            self.l.Trail2= self.l.Second 
                    

                    class TestStrategy(bt.Strategy):
                    def log(self, txt, dt=None):
                    ''' Logging function for this 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
                    myvma=most(self.data)

                    cerebro = bt.Cerebro()
                    cerebro.addstrategy(TestStrategy)

                    store = alpaca_backtrader_api.AlpacaStore(
                    key_id=ALPACA_API_KEY,
                    secret_key=ALPACA_SECRET_KEY,
                    paper=ALPACA_PAPER
                    )

                    if not ALPACA_PAPER:
                    broker = store.getbroker() # or just alpaca_backtrader_api.AlpacaBroker()
                    cerebro.setbroker(broker)

                    #DataFactory = store.getdata # or use alpaca_backtrader_api.AlpacaData
                    #data = DataFactory(dataname=symbol, historical=True, fromdate=datetime(

                    2020, 7, 1), timeframe=bt.TimeFrame.Days)

                    data = bt.feeds.YahooFinanceCSVData(dataname='AAPL.csv')
                    cerebro.adddata(data)

                    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
                    cerebro.run()
                    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
                    cerebro.plot(style='candlestick')

                    1 Reply Last reply Reply Quote 0
                    • 1 / 1
                    • First post
                      Last post
                    Copyright © 2016, 2017, 2018 NodeBB Forums | Contributors
                    $(document).ready(function () { app.coldLoad(); }); }