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

Using Timer to Buy and different indicator to Sell Strategy Help



  • Hi, I'm new to backtrader so thank you in advance for answering a probably obvious question.

    My example strategy is to execute a buy on a given day (weekday 4), and sell according to an indicator (when RSI >70) .

    I am having trouble getting these 2 actions to tie together correctly. I can run the code successfully, but it seems as though it isn't taking into account the buy day.

    Any help / further guidance is appreciated.

    import backtrader as bt
    import datetime
    matplotlib.use('QT5Agg')
    
    class firstStrategy(bt.Strategy):
    
        def __init__(self):
            self.rsi = bt.indicators.RSI_SMA(self.data.close, period=21)
            self.add_timer(
            when=bt.timer.SESSION_END,
            weekday=[4],
            weekcarry=True,
            timername='buytimer', # in case the day is a non-trading day the timer should kick in on the next trading day
            )
        def notify_timer(self, timer, when, *args, **kwargs):
            if not self.position:
                    self.buy(size=1)
        
        def next(self):
    #        if not self.position:
    #            self.notify_timer(timer,when)
    #
    #        else:
            if self.rsi > 70:
                    self.sell(size=1)
    
    
    #Variable for our starting cash
    startcash = 100000
    
    #Create an instance of cerebro
    cerebro = bt.Cerebro()
    
    #Add our strategy
    cerebro.addstrategy(firstStrategy)
    
    data = bt.feeds.YahooFinanceCSVData(
        dataname='BTC-USD.csv',
        fromdate=datetime.datetime(2019, 5, 1),   #2014, 9, 21
        todate=datetime.datetime(2020, 7, 8)
        )
    
    #Add the data to Cerebro
    cerebro.adddata(data)
    
    # Set our desired cash start
    cerebro.broker.setcash(startcash)
    
    # Run over everything
    cerebro.run()
    
    #Get final portfolio Value
    portvalue = cerebro.broker.getvalue()
    pnl = portvalue - startcash
    
    #Print out the final result
    print('Final Portfolio Value: ${}'.format(portvalue))
    print('P/L: ${}'.format(pnl))
    
    #Finally plot the end results
    cerebro.plot(style='candlestick',iplot=False)
    


  • Just a few things to tidy up your code.

    @Liz said in Using Timer to Buy and different indicator to Sell Strategy Help:

    weekday=[4],

    Weekdays is plural.

    Check if there's an open order in:

     def notify_timer(self, timer, when, *args, **kwargs):
            if not self.position or not self.order:
                self.buy(size=1)
    

    Use close instead of sell in next:

     if self.position and self.rsi > 70:
         self.close()
    

Log in to reply
 

});