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/

    Strategy returning incorrect result

    Indicators/Strategies/Analyzers
    1
    1
    76
    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.
    • V
      Vypy1 last edited by

      Hi, this maybe elementary, but why is my strategy returning an unexpected result. It is selling the stock 1 day after it places the buy order. I have given a sample of it below. I went over it tons of time but I seem to be missing something and could use a different set of eyes.

      I want to test placing stoptrail orders on a single data feed before I move to multiple data feeds. Hence created this sample code to test.

      I am using a custom pandas class to feed data.

      class pandas_custom(bt.feeds.PandasData):
          
          lines = ('ATR',)
          
          params = (
          ('nocase', True),
          ('datetime', None),
          ('open', -1),
          ('high', -1),
          ('low', -1),
          ('close', -1),
          ('volume', -1),
          ('openinterest', -1),
          ('ATR', -1)
          )
      
      class test_strat(bt.Strategy):
          
          params = (('fma', 20), ('sma', 50))
          
          
          def __init__(self):
              
              self.close = self.data.close
              self.fastma = bt.talib.EMA(self.close, timeperiod = self.p.fma)
              self.slowma = bt.talib.EMA(self.close, timeperiod = self.p.sma)
              self.cross = bt.indicators.CrossUp(self.fastma, self.slowma)
              self.atr = self.data.ATR
              self.execprice = None
              self.orefs = []
              
          def log(self, txt, dt=None):
              dt = self.datas[0].datetime.date()
              print(f'Date: {dt}, {txt}')
              
          
          def notify_order(self, order):
      
              if order.status in [order.Submitted, order.Accepted]:
                  self.log(f'Status: {order.getstatusname()}')
              
              
              elif order.status in [order.Completed]:
              
                  if order.isbuy():
                      self.log(f'BUY EXECUTED: Price: {order.executed.price}, Cost: {order.executed.value}')
                      self.log(f'Account Balance: {cerebro.broker.getcash()}')
                      
                  if order.issell():
                      self.log(f'SELL EXECUTED: Price: {order.executed.price}, Cost: {order.executed.value}')
                      self.log(f'Account Balance: {cerebro.broker.getcash()}')
                      
                  
                  self.execprice = order.executed.price
                  self.totalcost = order.executed.value
                      
                      
              elif order.status in [order.Rejected, order.Margin, order.Cancelled]:
                  self.log('order rejected/cancelled by broker or insufficient margin')
                  
              
                  
              if not order.alive() and order.ref in self.orefs:
                  self.orefs.remove(order.ref)
                  print(f'Order Numbers are {self.orefs}')
                  
              
          
          def notify_trade(self, trade):
              if trade.isopen:
                  return  
              
              else:
                  self.log(f'OPERATION PROFIT: GROSS {trade.pnl}, NET {trade.pnlcomm}, Trade PnL: {trade.pnlcomm/self.totalcost}')
                  self.log(f'Updated Account Balance: {cerebro.broker.getcash()}')
          
                  
                  
          def next(self):
              
              self.log(f'Close: {self.close[0]}')
                  
              if self.orefs:
                  return
      
              
              if not self.position:
                  
                  if self.cross > 0:
                      o1 = self.buy(transmit=False)
      
                      
                      o2 = self.sell(exectype = bt.Order.Stop, price = self.close[0] * 0.95, parent=o1, transmit=True)
      
                      self.log(f'BUY CREATED: {self.close[0]}, STOP CREATED: {self.close[0] * 0.95}')
                      
                      self.orefs = [o1.ref, o2.ref]
                      
      cerebro = bt.Cerebro()
      cerebro.broker.set_cash(100000)
      
      print(f'Starting Portfolio Value: {cerebro.broker.getvalue()}')
      
      data = pandas_custom(dataname=bajfin, datetime=None, open=-1, high=-1, low=-1, close=-1, volume=-1, ATR=-1)
      cerebro.adddata(data)
      cerebro.addstrategy(test_strat)
      cerebro.addsizer(bt.sizers.FixedSize, stake=10)
      
      cerebro.run()
      
      
      print(f'Final Portfolio Value: {cerebro.broker.getvalue()}')
      
      1 Reply Last reply Reply Quote 0
      • 1 / 1
      • First post
        Last post
      Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors