For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
Sell cost returning incorrectly
-
I am working on a strategy and sharing an example for the purpose of this question. Not sure why the sell order value is not returning the correct cost. It returns the buy order value instead of the sell order value. Sharing my code below.
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.CrossOver(self.fastma, self.slowma) self.atr = self.data.ATR self.order = None def log(self, txt, dt=None): dt = self.datas[0].datetime.date() print(f'Date: {dt}, {txt}') def notify_order(self, order): self.log(f'Close: {self.close[0]}, Type {"Buy" * order.isbuy() or "Sell"} / Status {order.getstatusname()}') if order.status == order.Completed: self.execprice = order.executed.price self.totalcost = order.executed.value self.log(f'Executed price: {self.execprice}') self.log(f'Cost: {self.totalcost}') self.order = None 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): if self.order: return if not self.position: if self.cross > 0: self.order = self.buy() # 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}') else: if self.close[0] < self.fastma[0] and self.close[-1] > self.fastma[-1]: self.order = self.sell() self.log(f'SELL CREATED: {self.close[0]}') cerebro = bt.Cerebro() cerebro.broker.set_cash(100000) print(f'Starting Portfolio Value: {cerebro.broker.getvalue()}') data = pandas_custom(dataname=hdfcbank, 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()}')