For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
Problems with the portfolio after order execution
-
I am both a python and trading novice. I wanted to highlight all portfolio movements based on each individual order. Unfortunately I am not with the value of my portfolio after the orders executed, there are numbers on which I do not agree. I certainly will not have understood the functioning of Bachtrader well. Could you give me some explanations? Thank you.
from __future__ import (absolute_import, division, print_function, unicode_literals) import argparse import datetime import backtrader as bt class St(bt.Strategy): params = dict( ma=bt.ind.SMA, p1=200, p2=30, stoptype=bt.Order.StopTrail, trailamount=0.0050, trailpercent=0.0, ) def __init__(self): ma1 = self.p.ma(period=self.p.p1) self.crup = bt.ind.CrossUp(self.data.close, ma1) self.order = None self.orefs = list() def notify_trade(self, trade): if trade.isclosed: print('Size: {:.4f} Profit: Gross {:.4f}, Net {:.4f}'.format(trade.size, trade.pnl, trade.pnlcomm)) print('Final Portfolio Value: ', self.broker.getvalue()) def notify_order(self, order): print('{}: Order ref: {} / Type {} / Status {}'.format( self.data.datetime.date(0), order.ref, 'Buy' * order.isbuy() or 'Sell', order.getstatusname())) print('Portfolio Value: ', self.broker.getvalue()) if order.status == order.Completed: print('order is buy?: ', order.isbuy()) if order.isbuy(): print('BUY EXECUTED, Price: ', order.executed.price, 'Cost: ', order.executed.value, 'Comm: ', order.executed.comm) else: print('SELL EXECUTED, Price: ', order.executed.price, 'Cost: ', order.executed.value, 'Comm: ', order.executed.comm) if not order.alive() and order.ref in self.orefs: self.orefs.remove(order.ref) def next(self): if self.orefs: return # pending orders do nothing if not self.position: if self.crup: o = self.buy() self.order = None print('*' * 50) print('{}: Oref {} / Buy at {}'.format( self.datetime.date(), o.ref, self.data.close[0])) elif self.order is None: self.order = self.sell(exectype=self.p.stoptype, trailamount=self.p.trailamount, trailpercent=self.p.trailpercent) if self.p.trailamount: tcheck = self.data.close - self.p.trailamount else: tcheck = self.data.close * (1.0 - self.p.trailpercent) print(','.join( map(str, [self.datetime.date(), self.data.close[0], self.order.created.price, tcheck]) ) ) print('-' * 10) # else: # if self.p.trailamount: # tcheck = self.data.close - self.p.trailamount # else: # tcheck = self.data.close * (1.0 - self.p.trailpercent) # print(','.join( # map(str, [self.datetime.date(), self.data.close[0], # self.order.created.price, tcheck]) # ) # ) class MyBuySell(bt.observers.BuySell): params = (('barplot', True), ('bardist', 0.0)) plotlines = dict( buy=dict(marker='$\u21E7$', markersize=10.0), sell=dict(marker='$\u21E9$', markersize=10.0) ) def runstrat(): cerebro = bt.Cerebro() stockkwargs = dict( timeframe=bt.TimeFrame.Minutes, rtbar=False, # use RealTime 5 seconds bars historical=True, # only historical download what=None, # historical - what to show TRADES MIDPOINT BID ASK BID_ASK HISTORICAL_VOLATILITY OPTION_IMPLIED_VOLATILITY useRTH=False, # historical - download only Regular Trading Hours qcheck=0.5, # timeout in seconds (float) to check for events backfill_start=True, # do backfilling at the start backfill=True, # do backfilling when reconnecting fromdate=datetime.datetime(2018, 1, 2), # get data from.. todate=datetime.datetime(2020, 3, 11), # get data to # dtformat='%Y-%m-%d %H:%M', dtformat='%d/%m/%Y %H:%M', datetime=0, open=1, high=2, low=3, close=4, openinterest=-1, time=-1, volume=5, latethrough=False, # let late samples through tradename=None # use a different asset as order target ) # Data feed data0 = bt.feeds.GenericCSVData(dataname='C:\\Dati\\Python\\BackTrader\\Prova\\USD_CHF_5min_parz.csv', **stockkwargs) cerebro.adddata(data0) # cash cerebro.broker.setcash(1000.0) # Sizer cerebro.addsizer(bt.sizers.SizerFix, stake=100) # Strategy cerebro.addstrategy(St) # Observer cerebro.addobserver(MyBuySell) # Execute cerebro.run() cerebro.plot(style='candlestick', volume=False) if __name__ == '__main__': runstrat()
************************************************** 2019-01-02: Oref 1 / Buy at 0.98706 2019-01-02: Order ref: 1 / Type Buy / Status Submitted Portfolio Value: 1000.0029999999999 2019-01-02: Order ref: 1 / Type Buy / Status Accepted Portfolio Value: 1000.0029999999999 2019-01-02: Order ref: 1 / Type Buy / Status Completed Portfolio Value: 1000.0029999999999 order is buy?: True BUY EXECUTED, Price: 0.98706 Cost: 98.706 Comm: 0.0 2019-01-02,0.98709,0.98209,0.98209 ---------- 2019-01-02: Order ref: 2 / Type Sell / Status Submitted Portfolio Value: 999.994 2019-01-02: Order ref: 2 / Type Sell / Status Accepted Portfolio Value: 999.994 2019-01-04: Order ref: 2 / Type Sell / Status Completed Portfolio Value: 999.847 order is buy?: False SELL EXECUTED, Price: 0.98553 Cost: 98.706 Comm: 0.0 Size: 0.0000 Profit: Gross -0.1530, Net -0.1530 Final Portfolio Value: 999.847 ************************************************** 2019-01-08: Oref 3 / Buy at 0.98162 2019-01-08: Order ref: 3 / Type Buy / Status Submitted Portfolio Value: 999.8639999999999 2019-01-08: Order ref: 3 / Type Buy / Status Accepted Portfolio Value: 999.8639999999999 2019-01-08: Order ref: 3 / Type Buy / Status Completed Portfolio Value: 999.8639999999999 order is buy?: True BUY EXECUTED, Price: 0.98162 Cost: 98.162 Comm: 0.0 2019-01-08,0.98179,0.97679,0.97679 ---------- 2019-01-08: Order ref: 4 / Type Sell / Status Submitted Portfolio Value: 999.861 2019-01-08: Order ref: 4 / Type Sell / Status Accepted Portfolio Value: 999.861 2019-01-09: Order ref: 4 / Type Sell / Status Completed Portfolio Value: 999.478 order is buy?: False SELL EXECUTED, Price: 0.97793 Cost: 98.162 Comm: 0.0 Size: 0.0000 Profit: Gross -0.3690, Net -0.3690 Final Portfolio Value: 999.478 **************************************************
-
Ok the portfolio is updated even if the order is not completed
C:\Users\Giovanni\Anaconda3\python.exe C:/Dati/Python/BackTrader/Prova/tests/Prova_Stop_Trail.py ************************************************** 2019-01-02: Oref 1 / Buy at 0.98706 2019-01-02: Order ref: 1 / Type Buy / Status Submitted / Dataclose: 0.98709 Portfolio Value: 1000.0029999999999 2019-01-02: Order ref: 1 / Type Buy / Status Accepted / Dataclose: 0.98709 Portfolio Value: 1000.0029999999999 2019-01-02: Order ref: 1 / Type Buy / Status Completed / Dataclose: 0.98709 Portfolio Value: 1000.0029999999999 order is buy?: True BUY EXECUTED, Price: 0.98706 Cost: 98.706 Comm: 0.0 2019-01-02,0.98709,0.98209,0.98209 ---------- 2019-01-02: Order ref: 2 / Type Sell / Status Submitted / Dataclose: 0.987 Portfolio Value: 999.994 2019-01-02: Order ref: 2 / Type Sell / Status Accepted / Dataclose: 0.987 Portfolio Value: 999.994 2019-01-04: Order ref: 2 / Type Sell / Status Completed / Dataclose: 0.98595 Portfolio Value: 999.847 order is buy?: False SELL EXECUTED, Price: 0.98553 Cost: 98.706 Comm: 0.0 Size: 0.0000 Profit: Gross -0.1530, Net -0.1530 Final Portfolio Value: 999.847 ************************************************** 2019-01-08: Oref 3 / Buy at 0.98162 2019-01-08: Order ref: 3 / Type Buy / Status Submitted / Dataclose: 0.98179 Portfolio Value: 999.8639999999999 2019-01-08: Order ref: 3 / Type Buy / Status Accepted / Dataclose: 0.98179 Portfolio Value: 999.8639999999999 2019-01-08: Order ref: 3 / Type Buy / Status Completed / Dataclose: 0.98179 Portfolio Value: 999.8639999999999 order is buy?: True BUY EXECUTED, Price: 0.98162 Cost: 98.162 Comm: 0.0 2019-01-08,0.98179,0.97679,0.97679 ---------- 2019-01-08: Order ref: 4 / Type Sell / Status Submitted / Dataclose: 0.98176 Portfolio Value: 999.861 2019-01-08: Order ref: 4 / Type Sell / Status Accepted / Dataclose: 0.98176 Portfolio Value: 999.861 2019-01-09: Order ref: 4 / Type Sell / Status Completed / Dataclose: 0.97801 Portfolio Value: 999.478 order is buy?: False SELL EXECUTED, Price: 0.97793 Cost: 98.162 Comm: 0.0 Size: 0.0000 Profit: Gross -0.3690, Net -0.3690 Final Portfolio Value: 999.478 **************************************************