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/

    Unable to get indicators to work

    General Code/Help
    5
    10
    2156
    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.
    • T
      Tomas last edited by

      Hello all!
      Im new to backtrader and so far im trying to get a few simple indicators to work but without any luck.

      I simply get an error on every indicator I try to use saying the following: Module 'backtrader' has no 'sma' memberpylint(no-member)

      When plotting my strategy everything but the indicator plots. I have been looking around in the documentation for a while now and still can't seem to find a fix.

      Code below:

      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 backtrader as bt
      import math
      
      # Create a Stratey
      class TestStrategy(bt.Strategy):
          params = (
              ('maperiod', 15),
          )
      
          def __init__(self):
              self.startcash = self.broker.getvalue()
              self.sma = bt.sma(self.data.close, period=15)
              self.rsi = bt.RSI_SMA(self.data.close, period=14,)
      
          def next(self):
              if not self.position:
                  if self.rsi < 30:
                      self.buy()
              else:
                  if self.rsi > 70:
                      self.close()
      
      
      class LongOnly(bt.Sizer):
      	params = (('stake', 1),)
      	def _getsizing(self, comminfo, cash, data, isbuy):
      		if isbuy:
      			divide = math.floor(cash/data.close[0])
      			self.p.stake = divide
      
      			return self.p.stake
              # Sell situation
      		position = self.broker.getposition(data)
      		if not position.size:
      			return 0 # do not sell if nothing is open
      		return self.p.stake
      
      if __name__ == '__main__':
          #Variable for our starting cash
          startcash = 10000
      
          #Create an instance of cerebro
          cerebro = bt.Cerebro(optreturn=False)
      
          # Add Sizer
          cerebro.addsizer(LongOnly)
      
          # Activate optimization
          StrategyOptimizationEnabled = False
      
          #Add our strategy
          if StrategyOptimizationEnabled == True:
              cerebro.optstrategy(TestStrategy, maperiod=range(14,21))
      
          #Get Apple data from Yahoo Finance.
          data = bt.feeds.YahooFinanceData(
              dataname='AAPL',
              fromdate = datetime.datetime(2019,1,1),
              todate = datetime.datetime(2020,1,1),
              buffered= True
              )
      
          #Add the data to Cerebro
          cerebro.adddata(data)
      
          # Set our desired cash start
          cerebro.broker.setcash(startcash)
      
          # Run over everything
          opt_runs = cerebro.run()
      
          # Set the commission
          cerebro.broker.setcommission(commission=0.005)
      
          # Generate results list
          if StrategyOptimizationEnabled == True:
              final_results_list = []
              for run in opt_runs:
                  for strategy in run:
                      value = round(strategy.broker.get_value(),2)
                      PnL = round(value - startcash,2)
                      maperiod = strategy.params.maperiod
                      final_results_list.append([maperiod,PnL])
      
              #Sort Results List
              by_period = sorted(final_results_list, key=lambda x: x[0])
              by_PnL = sorted(final_results_list, key=lambda x: x[1], reverse=True)
      
              #Print results
              print('Results: Ordered by period:')
              for result in by_period:
                  print('Period: {}, PnL: {}'.format(result[0], result[1]))
              print('Results: Ordered by Profit:')
              for result in by_PnL:
                  print('Period: {}, PnL: {}'.format(result[0], result[1]))
      
          # Plot the result
          cerebro.plot()
      
      1 Reply Last reply Reply Quote 0
      • Robin Dhillon
        Robin Dhillon last edited by

        You have to import the indicators as such:

        bt.indicators.SimpleMovingAverage(self.datas[0].close, period = 40)
        

        You will be benefitted greatly if you just took a look at the docs and navigate to the quickstart section.

        1 Reply Last reply Reply Quote 1
        • B
          backtrader administrators last edited by

          Or even the simplified

          bt.ind.SMA(...)
          

          Each indicator in the documentation lists its name and the aliases.

          1 Reply Last reply Reply Quote 0
          • T
            Tomas last edited by

            neither bt.indicators.SimpleMovingAverage(self.datas[0].close, period = 40) or bt.ind.SMA(...) works. The indicators still dont get plotted. I tried this as well from the start but gave it a shot again, still no luck

            1 Reply Last reply Reply Quote 0
            • T
              Tomas last edited by

              Well, I have tried googling it now for the past few days. Still no luck. Perhaps @backtrader has any thoughtful input as to why indicators doesn't work?

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

                Can you run the following simple script and provide results (error messages or the plot itself)? It should plot two indicators.

                from __future__ import (absolute_import, division, print_function,
                                        unicode_literals)
                
                import backtrader as bt
                
                class TestStrategy(bt.Strategy):
                
                    def __init__(self):
                        self.rsi = bt.indicators.RSI_SMA(period=14)
                        self.sma = bt.indicators.SMA(period=15)
                
                if __name__ == '__main__':
                
                    cerebro = bt.Cerebro()
                    data = bt.feeds.YahooFinanceData(
                        dataname='AAPL',
                        fromdate = datetime.datetime(2019,1,1),
                        todate = datetime.datetime(2020,1,1),
                        buffered= True
                        )
                    cerebro.adddata(data)
                    cerebro.addstrategy(TestStrategy)
                    cerebro.run()
                    cerebro.plot()
                
                • If my answer helped, hit reputation up arrow at lower right corner of the post.
                • Python Debugging With Pdb
                • New to python and bt - check this out
                1 Reply Last reply Reply Quote 1
                • B
                  backtrader administrators @Tomas last edited by

                  @tomas said in Unable to get indicators to work:

                  Perhaps @backtrader has any thoughtful input as to why indicators doesn't work?

                  It's quite simple. Instead of starting with a very simple script (even simpler than the one posted by @ab_trader, which is already very simple), you want to crack the jackpot and are putting already condition variables here and there and are also going to give optimization a try.

                  At the end of the day: you are not even adding the strategy to cerebro. But hey ... why start slow if one can generate millions with optimization from day one ....

                  T 1 Reply Last reply Reply Quote 1
                  • T
                    Tomas @backtrader last edited by

                    @backtrader
                    Well, I'm just trying to port a strategy of mine from Pinescript. I'm sorry if my question seems ignorant?

                    1 Reply Last reply Reply Quote 0
                    • B
                      backtrader administrators last edited by

                      It has nothing to do with ignorance. From your 1st post:

                      @tomas said in Unable to get indicators to work:

                      I simply get an error on every indicator I try to use saying the following: Module 'backtrader' has no 'sma' memberpylint(no-member)

                      That's not an error when executing the code. Your IDE is telling you that scanning the module backtrader didn't find something called sma. Actually and given the dynamic nature of Python and the introduction in Python 3.7 of Python of module level __getattr__, that message may actually mean absolutely nothing.

                      There is no real error if you haven't executed the code. In this particular case, the message was right on spot, sma is not part of the main backtrader module.

                      In any case, your initial code

                      @tomas said in Unable to get indicators to work:

                          def __init__(self):
                              self.startcash = self.broker.getvalue()
                              self.sma = bt.sma(self.data.close, period=15)
                      

                      Now, if one looks at the quickstart guide you will find code like this:

                              # Add a MovingAverageSimple indicator
                              self.sma = bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.maperiod)
                      

                      which makes it obvious that you didn't go through the Quickstart guide.

                      Your actual problem is not ignorance or being in the works of porting something from Pinescript. The problem as pointed out above is that you want to start with a high bar and are failing to be able go over it. See, the culprit is quite clear

                      @tomas said in Unable to get indicators to work:

                          # Activate optimization
                          StrategyOptimizationEnabled = False
                      
                          #Add our strategy
                          if StrategyOptimizationEnabled == True:
                              cerebro.optstrategy(TestStrategy, maperiod=range(14,21))
                      

                      If you optimize (which you are not doing), you add a strategy to Cerebro.

                      • Where do you actually add a strategy to cerebro if you are not optimizing?

                      Ok, I will answer it: you don't. And if you don't, no indicator can be plotted, because you are actually not instantiating any indicator. As a matter of fact, no strategy code is executing whatsoever. That would have been the 1st logical step, having a script which works without optimization, but that part is obviously missing.

                      My very sincere advice (you may fully ignore it, consider me arrogant and swear if you wish)

                      • Start with something very small and build up from there. If you cannot get to instantiate a Strategy, you are, in my very humble opinion, far away from needing to play with optimization, which in almost no instance will be of real help.

                      @ab_trader was very kind to offer you a working script with your indicators. I would suggest you use as the initial building block of a larger strategy.

                      Micahel Wei 1 Reply Last reply Reply Quote 1
                      • Micahel Wei
                        Micahel Wei @backtrader last edited by

                        @Tomas
                        I am also new to Backtrader and I got the same issue.

                        I tried to check the code and did the following changes to work:

                        Add a MovingAverageSimple indicator

                            self.sma = bt.indicators.SimpleMovingAverage(self.datas[0].close, period = self.params.myperiod)
                        

                        or
                        self.sma = bt.indicators.SimpleMovingAverage(self.dataclose, period = self.params.myperiod)

                        Good luck!

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