For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

How to execute a buy sell order in backtrader?



  • I made a simple moving average crossover stratergy to buy and sell AAPL stocks .

    class MyStrategy(bt.Strategy):
        def __init__(self):
            self.sma= bt.ind.SMA(period=5)
        def next(self):
            if self.sma[0]>self.data.close[0]:
            # current sma greater than current close price
                print('BUY CREATE, %.2f' % self.data.close[0])
                self.buy()
            elif self.sma[0]<self.data.close[0]:
            # current sma lesser than current close price
                print('SELL CREATE, %.2f' % self.data.close[0])
                self.sell()
    

    But the TradeAnalyzer result shows that only two trades have happened in a period of four years which is odd and those are also losing trades. I tried changing the sma period and also the trading days but the results are the same.

    ===============================================================================
    TradeAnalyzer:
      -----------------------------------------------------------------------------
      - total:
        - total: 2
        - open: 1
        - closed: 1
      -----------------------------------------------------------------------------
      - streak:
        +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        - won:
          - current: 0
          - longest: 0
        +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        - lost:
          - current: 1
          - longest: 1
      -------------------------------------------
    

    This is the full code.

    • I know there are different ways to get buy sell signals in backtrader example self.signal_add(bt.SIGNAL_LONG, crossover) but my prefered method is with the conditional statements.
    from datetime import datetime
    import backtrader as bt
    import pandas as pd
    from pandas_datareader import data as pdr
    import matplotlib.pyplot as plt
    from pprint import pprint
    
    data = pdr.get_data_yahoo('AAPL', start=datetime(2014, 8, 13), end=datetime(2018, 8, 14))
    
    data.columns=['high', 'low', 'open', 'close', 'volume', 'adj_close']
    data['pct']=data.close.pct_change()
    data['pct2']=data.close.pct_change(3)
    data['pct3']=data.close.pct_change(5)
    
    class PandasData(bt.feeds.PandasData):
        lines = ('adj_close','pct','pct2','pct3')
        params = (
            ('datetime', None),
            ('open','open'),
            ('high','high'),
            ('low','low'),
            ('close','close'),
            ('volume','volume'),
            ('openinterest',None),
            ('adj_close','adj_close'),
            ('pct','pct'),
            ('pct2','pct2'),
            ('pct3','pct3'),
        )
    
    class MyStrategy(bt.Strategy):
        def __init__(self):
            self.sma= bt.ind.SMA(period=5)
        def next(self):
            if self.sma[0]>self.data.close[0]:
            # current sma greater than current close price
                print('BUY CREATE, %.2f' % self.data.close[0])
                self.buy()
            elif self.sma[0]<self.data.close[0]:
            # current sma lesser than current close price
                print('SELL CREATE, %.2f' % self.data.close[0])
                self.sell()
    
    cerebro = bt.Cerebro()
    cerebro.addstrategy(MyStrategy)
    
    df = PandasData(dataname=data)
    cerebro.adddata(df)
    
    cerebro.broker.setcash(100000.0)
    
    cerebro.broker.setcommission(commission=0.05)
    
    cerebro.addanalyzer(bt.analyzers.TradeAnalyzer,_name="Basic_stats")
    
    print('Starting Balance: %.2f' % cerebro.broker.getvalue())
    
    strats =  cerebro.run(stdstats=False)
    strat = strats[0]
    cerebro.addobserver(bt.observers.Value)
    
    for e in strat.analyzers:
        e.print()
    
    print('Final Balance: %.2f' % cerebro.broker.getvalue())
    
    

  • administrators

    @backtrader14 said in How to execute a buy sell order in backtrader?:

    I made a simple moving average crossover stratergy to buy and sell AAPL stocks

    Sorry, but you haven't.

    @backtrader14 said in How to execute a buy sell order in backtrader?:

    class MyStrategy(bt.Strategy):
        def __init__(self):
            self.sma= bt.ind.SMA(period=5)
    

    If you only have 1 moving average, it is difficult to conceive that you have a moving average crossover strategy.

    You will argue ... "it's a crossover nevertheless ... i was righ". No, you are not. Precision is important: you want to play with money at some point int time.

    @backtrader14 said in How to execute a buy sell order in backtrader?:

    But the TradeAnalyzer result shows that only two trades

    Change to a moving average crossover.

    @backtrader14 said in How to execute a buy sell order in backtrader?:

        def next(self):
            if self.sma[0]>self.data.close[0]:
            # current sma greater than current close price
                print('BUY CREATE, %.2f' % self.data.close[0])
                self.buy()
            elif self.sma[0]<self.data.close[0]:
            # current sma lesser than current close price
                print('SELL CREATE, %.2f' % self.data.close[0])
                self.sell()
    

    You are not even reversing the position, you are at some point in time opening a position and simply closing it at some other point in time. You have print statements but your log is that of the TradeAnalyzer which can only tell you what has happened and not why.

    Do the following:

    • Decide if you want a moving average crossover or another type of crossover.
    • Learn about the close method to close an open position or reverse the position using the appropriate size
    • You may want to check the position size
    • Use notify_order and log what the notifications tell you.


  • If you plot the results, you might see that you buy at each bar when sma is more than close and sell at each bar when sma is less than close. This is not crossover strategy.



  • @ab_trader said in How to execute a buy sell order in backtrader?:

    ot the results, you might see that you buy at each bar when sma is more than close and sell at each bar when sma is less than close. This is not crossover strategy.

    Yeah saw that mistake late. It seems this crossover strategy doesn't work with AAPL I tried a RSI method which seems to work.



});