|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8; py-indent-offset:4 -*- |
| 3 | +############################################################################### |
| 4 | +# |
| 5 | +# This program is free software: you can redistribute it and/or modify |
| 6 | +# it under the terms of the GNU General Public License as published by |
| 7 | +# the Free Software Foundation, either version 3 of the License, or |
| 8 | +# (at your option) any later version. |
| 9 | +# |
| 10 | +# This program is distributed in the hope that it will be useful, |
| 11 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +# GNU General Public License for more details. |
| 14 | +# |
| 15 | +# You should have received a copy of the GNU General Public License |
| 16 | +# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 | +# |
| 18 | +############################################################################### |
| 19 | +from __future__ import absolute_import, division, print_function, unicode_literals |
| 20 | + |
| 21 | +import datetime |
| 22 | +import os |
| 23 | +import time |
| 24 | + |
| 25 | + |
| 26 | +try: |
| 27 | + time_clock = time.process_time |
| 28 | +except: |
| 29 | + time_clock = time.clock |
| 30 | + |
| 31 | +import backtrader as bt |
| 32 | + |
| 33 | + |
| 34 | +class SlipTestStrategy(bt.SignalStrategy): |
| 35 | + params = ( |
| 36 | + ("printdata", False), |
| 37 | + ("printops", False), |
| 38 | + ) |
| 39 | + |
| 40 | + def log(self, txt, dt=None, nodate=False): |
| 41 | + if not nodate: |
| 42 | + dt = dt or self.data.datetime[0] |
| 43 | + dt = bt.num2date(dt) |
| 44 | + print("%s, %s" % (dt.isoformat(), txt)) |
| 45 | + else: |
| 46 | + print("---------- %s" % (txt)) |
| 47 | + |
| 48 | + def notify_order(self, order): |
| 49 | + if order.status in [bt.Order.Submitted, bt.Order.Accepted]: |
| 50 | + return # Await further notifications |
| 51 | + |
| 52 | + if order.status == order.Completed: |
| 53 | + if isinstance(order, bt.BuyOrder): |
| 54 | + if self.p.printops: |
| 55 | + txt = "BUY, %.2f" % order.executed.price |
| 56 | + self.log(txt, order.executed.dt) |
| 57 | + chkprice = "%.2f" % order.executed.price |
| 58 | + self.buyexec.append(chkprice) |
| 59 | + else: # elif isinstance(order, SellOrder): |
| 60 | + if self.p.printops: |
| 61 | + txt = "SELL, %.2f" % order.executed.price |
| 62 | + self.log(txt, order.executed.dt) |
| 63 | + |
| 64 | + chkprice = "%.2f" % order.executed.price |
| 65 | + self.sellexec.append(chkprice) |
| 66 | + |
| 67 | + elif order.status in [order.Expired, order.Canceled, order.Margin]: |
| 68 | + if self.p.printops: |
| 69 | + self.log("%s ," % order.Status[order.status]) |
| 70 | + |
| 71 | + # Allow new orders |
| 72 | + self.order = None |
| 73 | + |
| 74 | + def __init__(self): |
| 75 | + # Flag to allow new orders in the system or not |
| 76 | + self.order = None |
| 77 | + self.price = 1285.0 |
| 78 | + self.counter = 0 |
| 79 | + |
| 80 | + def start(self): |
| 81 | + |
| 82 | + if self.p.printdata: |
| 83 | + self.log("-------------------------", nodate=True) |
| 84 | + self.log( |
| 85 | + "Starting portfolio value: %.2f" % self.broker.getvalue(), nodate=True |
| 86 | + ) |
| 87 | + |
| 88 | + self.tstart = time_clock() |
| 89 | + |
| 90 | + self.buycreate = list() |
| 91 | + self.sellcreate = list() |
| 92 | + self.buyexec = list() |
| 93 | + self.sellexec = list() |
| 94 | + |
| 95 | + def stop(self): |
| 96 | + tused = time_clock() - self.tstart |
| 97 | + if self.p.printdata: |
| 98 | + self.log("Time used: %s" % str(tused)) |
| 99 | + self.log("Final portfolio value: %.2f" % self.broker.getvalue()) |
| 100 | + self.log("Final cash value: %.2f" % self.broker.getcash()) |
| 101 | + self.log("-------------------------") |
| 102 | + else: |
| 103 | + pass |
| 104 | + |
| 105 | + def print_signal(self): |
| 106 | + if self.p.printdata: |
| 107 | + self.log( |
| 108 | + "Open, High, Low, Close, %.2f, %.2f, %.2f, %.2f" |
| 109 | + % ( |
| 110 | + self.data.open[0], |
| 111 | + self.data.high[0], |
| 112 | + self.data.low[0], |
| 113 | + self.data.close[0], |
| 114 | + ) |
| 115 | + ) |
| 116 | + |
| 117 | + def next(self): |
| 118 | + self.print_signal() |
| 119 | + |
| 120 | + if self.counter == 0: |
| 121 | + self.order = self.sell(exectype=bt.Order.Limit, price=self.price) |
| 122 | + if self.p.printops: |
| 123 | + self.log("SELL ISSUED @ %0.2f" % self.price) |
| 124 | + self.counter += 1 |
| 125 | + |
| 126 | + |
| 127 | +def test_run(main=False): |
| 128 | + """ Test a fix in bbroker. See backtrader2 pr#22 """ |
| 129 | + |
| 130 | + cerebro = bt.Cerebro() |
| 131 | + |
| 132 | + if main == True: |
| 133 | + strat_kwargs = dict(printdata=True, printops=True) |
| 134 | + else: |
| 135 | + strat_kwargs = dict(printdata=False, printops=False) |
| 136 | + |
| 137 | + cerebro.addstrategy(SlipTestStrategy, **strat_kwargs) |
| 138 | + |
| 139 | + cerebro.broker.setcash(10000.0) |
| 140 | + |
| 141 | + modpath = os.path.dirname(os.path.abspath(__file__)) |
| 142 | + dataspath = "../datas" |
| 143 | + datafile = "bbroker_try_exec_limit.txt" |
| 144 | + datapath = os.path.join(modpath, dataspath, datafile) |
| 145 | + data0 = bt.feeds.GenericCSVData( |
| 146 | + dataname=datapath, |
| 147 | + dtformat=("%Y-%m-%d"), |
| 148 | + timeframe=bt.TimeFrame.Days, |
| 149 | + compression=1, |
| 150 | + ) |
| 151 | + cerebro.adddata(data0) |
| 152 | + |
| 153 | + # Slippage/expected sell executed price |
| 154 | + expected_results = ( |
| 155 | + (0, 1297.5), |
| 156 | + (3, 1294.50), |
| 157 | + (4, 1293.50), |
| 158 | + (5, 1293.10), |
| 159 | + (10, 1293.10), |
| 160 | + ) |
| 161 | + |
| 162 | + for expected_result in expected_results: |
| 163 | + cerebro.broker.set_slippage_fixed(expected_result[0]) |
| 164 | + strat = cerebro.run() |
| 165 | + if main: |
| 166 | + print( |
| 167 | + "Slippage {}, Sell Executed {:.2f}, Expected price {:.2f}".format( |
| 168 | + expected_result[0], float(strat[0].sellexec[0]), expected_result[1] |
| 169 | + ) |
| 170 | + ) |
| 171 | + |
| 172 | + assert float(strat[0].sellexec[0]) == expected_result[1] |
| 173 | + |
| 174 | + |
| 175 | +if __name__ == "__main__": |
| 176 | + test_run(main=True) |
0 commit comments