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/

    Based on signal from 1 stock trade another stock

    General Code/Help
    1
    2
    78
    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.
    • D
      doomdaam last edited by

      I am using the default template for creating own strategy.

      Goal of the strategy is:

      if index_sma is above the index SMA,
      and macro_sma is above macro SMA,
      and rente_sma is above the rente SMA

      we BUY VO (and sell ^TNX if we have a ^TNX position open)

      else if:
      index_sma is below index SMA,
      and macro_sma is below macro SMA,
      and rente_sma is below rente SMA

      we SELL VO and buy ^TNX.

      I am having a hard time implementing this. I tried but I am not sure where to include how to sell and buy VO and TNX.

      import datetime
      import matplotlib 
      import backtrader as bt
      import backtrader.feeds as btfeeds
      import backtrader.indicators as btind
      
      class MultiDataStrategy(bt.Strategy):
          '''
          This strategy operates on 2 datas. The expectation is that the 2 datas are
          correlated and the 2nd data is used to generate signals on the 1st
      
            - Buy/Sell Operationss will be executed on the 1st data
            - The signals are generated using a Simple Moving Average on the 2nd data
              when the close price crosses upwwards/downwards
      
          The strategy is a long-only strategy
          '''
          params = dict(
              printout=True,
          )
      
          def log(self, txt, dt=None):
              if self.p.printout:
                  dt = dt or self.data.datetime[0]
                  dt = bt.num2date(dt)
                  print('%s, %s' % (dt.isoformat(), txt))
      
          def notify_order(self, order):
              if order.status in [bt.Order.Submitted, bt.Order.Accepted]:
                  return  # Await further notifications
      
              if order.status == order.Completed:
                  if order.isbuy():
                      buytxt = 'BUY COMPLETE, %.2f' % order.executed.price
                      self.log(buytxt, order.executed.dt)
                  else:
                      selltxt = 'SELL COMPLETE, %.2f' % order.executed.price
                      self.log(selltxt, order.executed.dt)
      
              elif order.status in [order.Expired, order.Canceled, order.Margin]:
                  self.log('%s ,' % order.Status[order.status])
                  pass  # Simply log
      
              # Allow new orders
              self.orderid = None
      
          def __init__(self):
              # To control operation entries
              self.orderid = None
      
              index_sma = btind.MovAv.SMA(self.data0, period=200)
              macro_sma = btind.MovAv.SMA(self.data1, period=100)        
              rente_sma = btind.MovAv.SMA(self.data3, period=100)
              
              self.index_signal = btind.CrossOver(self.data0.close, index_sma)
      
              
          def next(self):
              if self.orderid:
                  return  
      
              if not self.position:  # not yet in market
                  if self.index_signal == 1:
                      #if self.index_signal is above 200SMA buy the VO stocks
                      self.log('BUY CREATE , %.2f' % self.data4.close[0])
                      self.buy()
      
              elif self.index_signal == 0:
                  #if self.index_signal is below 200SMA sell the VO stock and buy ^TNX
                      self.log('SELL CREATE , %.2f' % self.data4.close[0])
                      self.sell()
      
          def stop(self):
              print('==================================================')
              print('Starting Value - %.2f' % self.broker.startingcash)
              print('Ending   Value - %.2f' % self.broker.getvalue())
              print('==================================================')
      

      Here is my data load and cerebro settings:

      cerebro = bt.Cerebro()
      
       # Get the dates 
      fromdate = datetime.datetime(2015,1,1)
      todate = datetime.datetime(2021,5,1)
      
      data0 = bt.feeds.YahooFinanceData(dataname='^DJI', fromdate=fromdate,
                                        todate=todate)
      
      data1 = bt.feeds.YahooFinanceData(dataname='CL=F', fromdate=fromdate,
                                        todate=todate)
      
      data2 = bt.feeds.YahooFinanceData(dataname='GC=F', fromdate=fromdate,
                                        todate=todate)
      
      data3 = bt.feeds.YahooFinanceData(dataname='^TNX', fromdate=fromdate,
                                        todate=todate)
      
      data4 = bt.feeds.YahooFinanceData(dataname='VO', fromdate=fromdate,
                                        todate=todate)
      
      # Add the 1st data to cerebro
      cerebro.adddata(data0)
      cerebro.adddata(data1)
      cerebro.adddata(data2)
      cerebro.adddata(data3)
      cerebro.adddata(data4)
      
       # Add the strategy
      cerebro.addstrategy(MultiDataStrategy)
      
      cerebro.addsizer(bt.sizers.PercentSizer, percents=20)
      cerebro.run()
      
      D 1 Reply Last reply Reply Quote 0
      • D
        doomdaam @doomdaam last edited by

        @doomdaam Sorry I made a mistake. It is not supposed to trade ^TNX at all only VO.

        ^TNX is the rente sma.

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