qtpylib
qtpylib copied to clipboard
Backtest cannot close position if using get_positions() check
I can't close a position during backtests if I have a get_positions()['positions'] == 0
check
(I am on qtpylib version 1.5.82, Ref to #85)
Debugging:
- I believe what is happening is that after
instrument.buy(1)
, the bar will register the position correctly. The next bar, the position is NaN andget_positions()
will return a0
- Minimal example: https://gist.github.com/lionelyoung/593bf98d6fb84c60b03378b429f1c8ae
- This line is NaN for the next bar after
instrument.buy(1)
: https://github.com/ranaroussi/qtpylib/blob/048657dab146a932642f20a349cb23add3e4ec21/qtpylib/broker.py#L910
Relevant test code:
def on_bar(self, instrument):
positions = instrument.get_positions()
if not instrument.pending_orders and positions["position"] == 0:
print('BUY pos:{} counter:{}'.format(positions['position'], self.counter))
instrument.buy(1)
self.counter_at_entry = self.counter
elif positions["position"] != 0 and self.counter > self.counter_at_entry + 5:
print('SELL pos:{} counter:{}'.format(positions['position'], self.counter))
instrument.exit()
else:
print('NOACTION pos:{} counter:{}'.format(positions['position'], self.counter))
self.counter += 1
Output:
$python strategy_position_debug.py --backtest --output debug.pkl --start "2019-01-17 00:00:00" --end "2019-01-17 10:00:00" --log "logs" Active month for ES is: 201903 Server Version: 76 TWS Time at connection:20190125 01:11:12 GMT+08:00 BUY pos:0 counter:0 BUY pos:0.0 counter:1 NOACTION pos:1.0 counter:2 NOACTION pos:1.0 counter:3 BUY pos:0.0 counter:4 BUY pos:0.0 counter:5 NOACTION pos:1.0 counter:6 NOACTION pos:1.0 counter:7 BUY pos:0.0 counter:8 BUY pos:0.0 counter:9
Expected output:
$python strategy_position_debug.py --backtest --output debug.pkl --start "2019-01-17 00:00:00" --end "2019-01-17 10:00:00" --log "logs" Active month for ES is: 201903 Server Version: 76 TWS Time at connection:20190125 01:11:12 GMT+08:00 BUY pos:0 counter:0 NOACTION pos:1.0 counter:1 NOACTION pos:1.0 counter:2 NOACTION pos:1.0 counter:3 NOACTION pos:1.0 counter:4 NOACTION pos:1.0 counter:5 SELL pos:1.0 counter:6
same issue, is this a bug ??