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



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


  • 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.


  • administrators

    Or even the simplified

    bt.ind.SMA(...)
    

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



  • 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



  • 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?



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

  • administrators

    @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 ....



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


  • administrators

    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.


Log in to reply
 

});