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

trouble for order management while backtesting



  • hi,
    I am new here and have little knowledge of coding. I am trying to build an algorithm that is having a crossover of sma30, rsi and atr. as i initiate backtesting. there is only one order placed. can any one help me in this
    here is the full code. if you want to check it plz backtest it and assist me.

    import datetime
    import backtrader as bt
    import backtrader.feeds as btfeeds
    from backtrader import indicators

    from nsepy import get_history
    from datetime import date

    class mystrategy(bt.Strategy):
    def log(self, txt, dt = None):
    dt = dt or self.datas[0].datetime.date(0)
    print("%s, %s" % (dt, txt))

    def __init__(self):
    	self.dataclose = self.datas[0].close
    	self.order = None
    	self.buyprice = None
    	self.buycomm = None
    	self.sma30 = bt.talib.SMA(self.data.close, period = 30)
    	self.atr = bt.talib.ATR(self.data.high, self.data.low, self.data.close, period = 14)
    	self.rsi = bt.talib.RSI(self.data.close, period = 14)
    
    def notify_order(self, order):
    	if order.status in [order.Submitted, order.Accepted]:
    		return
    	if order.status in [order.Completed]:
    		if order.isbuy():
    			self.log("Buy executed, price %.2f, cost %.2f, comm %.2f" % (order.executed.price, order.executed.value, order.executed.comm))
    			self.buyprice = order.executed.price
    			self.buycomm = order.executed.comm
    		else:
    			self.log("Sell executed, price %.2f, cost %.2f, comm %.2f" % (order.executed.price, order.executed.value, order.executed.comm))
    		self.bar_executed = len(self)
    
    	elif order.status in [order.Canceled, order.Margin, order.Rejected]:
    		self.log("order Canceled/Margin/Rejected")
    	self.order = None
    
    def notify_trade(self, trade):
    	if not trade.isclosed:
    		return
    	self.log("Operation profit , gross %.2f, net %.2f" % (trade.pnl, trade.pnlcomm))
    
    def next(self):
    	self.log("Close, %.2f" % self.dataclose[0])
    	if self.order:
    		return
    	if not self.position:
    		if self.sma30[0] > self.atr[0] and self.rsi[0] > 50:
    			self.log("Buy Create, %.2f" % self.dataclose[0])
    			self.order = self.buy()
    	else:
    		if self.rsi[0] < 50 and self.sma30[0] < self.atr[0]:
    			self.log("Sell Create, %.2f" % self.dataclose[0])
    			self.order = self.sell()
    

    if name == "main":
    cerebro = bt.Cerebro()
    cerebro.addstrategy(mystrategy)

    data = btfeeds.GenericCSVData(
    	dataname="sbin.csv",
    	fromdate=datetime.datetime(2015, 1, 1),
    	todate=datetime.datetime(2020, 4, 30),
    	nullvalue=0.0,
    	dtformat=('%Y-%m-%d'),
    	datetime=0,
    	high=5,
    	low=6,
    	open=4,
    	close=8,
    	volume=10,
    	openinterest=-1,
    	)
    
    cerebro.adddata(data)
    cerebro.broker.setcash(100000)
    cerebro.addsizer(bt.sizers.FixedSize, stake = 10)
    cerebro.broker.setcommission(commission = 0.01)
    print("Starting Portfolio Value: %.2f" % cerebro.broker.getvalue())
    cerebro.run()
    print("Final Portfolio Value: %.2f" % cerebro.broker.getvalue())
    cerebro.plot()


  • @Akshay-Mehara said in trouble for order management while backtesting:

    hi,
    I am new here and have little knowledge of coding. I am trying to build an algorithm that is having a crossover of sma30, rsi and atr. as i initiate backtesting. there is only one order placed. can any one help me in this
    here is the full code. if you want to check it plz backtest it and assist me.

    import datetime
    import backtrader as bt
    import backtrader.feeds as btfeeds
    from backtrader import indicators

    from nsepy import get_history
    from datetime import date

    class mystrategy(bt.Strategy):
    def log(self, txt, dt = None):
    dt = dt or self.datas[0].datetime.date(0)
    print("%s, %s" % (dt, txt))

    def init(self):
    self.dataclose = self.datas[0].close
    self.order = None
    self.buyprice = None
    self.buycomm = None
    self.sma30 = bt.talib.SMA(self.data.close, period = 30)
    self.atr = bt.talib.ATR(self.data.high, self.data.low, self.data.close, period = 14)
    self.rsi = bt.talib.RSI(self.data.close, period = 14)

    def notify_order(self, order):
    if order.status in [order.Submitted, order.Accepted]:
    return
    if order.status in [order.Completed]:
    if order.isbuy():
    self.log("Buy executed, price %.2f, cost %.2f, comm %.2f" % (order.executed.price, order.executed.value, order.executed.comm))
    self.buyprice = order.executed.price
    self.buycomm = order.executed.comm
    else:
    self.log("Sell executed, price %.2f, cost %.2f, comm %.2f" % (order.executed.price, order.executed.value, order.executed.comm))
    self.bar_executed = len(self)

      elif order.status in [order.Canceled, order.Margin, order.Rejected]:
      	self.log("order Canceled/Margin/Rejected")
      self.order = None
    

    def notify_trade(self, trade):
    if not trade.isclosed:
    return
    self.log("Operation profit , gross %.2f, net %.2f" % (trade.pnl, trade.pnlcomm))

    def next(self):
    self.log("Close, %.2f" % self.dataclose[0])
    if self.order:
    return
    if not self.position:
    if self.sma30[0] > self.atr[0] and self.rsi[0] > 50:
    self.log("Buy Create, %.2f" % self.dataclose[0])
    self.order = self.buy()
    else:
    if self.rsi[0] < 50 and self.sma30[0] < self.atr[0]:
    self.log("Sell Create, %.2f" % self.dataclose[0])
    self.order = self.sell()

    if name == "main":
    cerebro = bt.Cerebro()
    cerebro.addstrategy(mystrategy)

    data = btfeeds.GenericCSVData(
    dataname="sbin.csv",
    fromdate=datetime.datetime(2015, 1, 1),
    todate=datetime.datetime(2020, 4, 30),
    nullvalue=0.0,
    dtformat=('%Y-%m-%d'),
    datetime=0,
    high=5,
    low=6,
    open=4,
    close=8,
    volume=10,
    openinterest=-1,
    )

    cerebro.adddata(data)
    cerebro.broker.setcash(100000)
    cerebro.addsizer(bt.sizers.FixedSize, stake = 10)
    cerebro.broker.setcommission(commission = 0.01)
    print("Starting Portfolio Value: %.2f" % cerebro.broker.getvalue())
    cerebro.run()
    print("Final Portfolio Value: %.2f" % cerebro.broker.getvalue())
    cerebro.plot()

    the csv file for backtesting data



  • What result were you expecting?



  • I don;t think that comparison of the sma and atr will bring you a lot of the signals. sma is roughly the price, and atr is the volatility, price change.



  • @run-out I thought it would give me buy and sell signals. but it only gave buy signal


Log in to reply
 

});