-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathbacktesting.py
1730 lines (1450 loc) · 71.5 KB
/
backtesting.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Core framework data structures.
Objects from this module can also be imported from the top-level
module directly, e.g.
from backtesting import Backtest, Strategy
"""
import multiprocessing as mp
import os
import sys
import warnings
from abc import abstractmethod, ABCMeta
from concurrent.futures import ProcessPoolExecutor, as_completed
from copy import copy
from functools import lru_cache, partial
from itertools import repeat, product, chain, compress
from math import copysign
from numbers import Number
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Type, Union
import numpy as np
import pandas as pd
try:
from tqdm.auto import tqdm as _tqdm
_tqdm = partial(_tqdm, leave=False)
except ImportError:
def _tqdm(seq, **_):
return seq
from ._plotting import plot
from ._util import _as_str, _Indicator, _Data, _data_period, try_
__pdoc__ = {
'Strategy.__init__': False,
'Order.__init__': False,
'Position.__init__': False,
'Trade.__init__': False,
}
class Strategy(metaclass=ABCMeta):
"""
A trading strategy base class. Extend this class and
override methods
`backtesting.backtesting.Strategy.init` and
`backtesting.backtesting.Strategy.next` to define
your own strategy.
"""
def __init__(self, broker, data, params):
self._indicators = []
self._broker: _Broker = broker
self._data: _Data = data
self._params = self._check_params(params)
def __repr__(self):
return '<Strategy ' + str(self) + '>'
def __str__(self):
params = ','.join(f'{i[0]}={i[1]}' for i in zip(self._params.keys(),
map(_as_str, self._params.values())))
if params:
params = '(' + params + ')'
return f'{self.__class__.__name__}{params}'
def _check_params(self, params):
for k, v in params.items():
if not hasattr(self, k):
raise AttributeError(
f"Strategy '{self.__class__.__name__}' is missing parameter '{k}'."
"Strategy class should define parameters as class variables before they "
"can be optimized or run with.")
setattr(self, k, v)
return params
def I(self, # noqa: E741, E743
func: Callable, *args,
name=None, plot=True, overlay=None, color=None, scatter=False, histogram=False,
**kwargs) -> np.ndarray:
"""
Declare indicator. An indicator is just an array of values,
but one that is revealed gradually in
`backtesting.backtesting.Strategy.next` much like
`backtesting.backtesting.Strategy.data` is.
Returns `np.ndarray` of indicator values.
`func` is a function that returns the indicator array(s) of
same length as `backtesting.backtesting.Strategy.data`.
In the plot legend, the indicator is labeled with
function name, unless `name` overrides it.
If `plot` is `True`, the indicator is plotted on the resulting
`backtesting.backtesting.Backtest.plot`.
If `overlay` is `True`, the indicator is plotted overlaying the
price candlestick chart (suitable e.g. for moving averages).
If `False`, the indicator is plotted standalone below the
candlestick chart. By default, a heuristic is used which decides
correctly most of the time.
`color` can be string hex RGB triplet or X11 color name.
By default, the next available color is assigned.
If `scatter` is `True`, the plotted indicator marker will be a
circle instead of a connected line segment (default).
If `histogram` is `True`, the indicator values will be plotted
as a histogram instead of line or circle. When `histogram` is
`True`, 'scatter' value will be ignored even if it's set.
Additional `*args` and `**kwargs` are passed to `func` and can
be used for parameters.
For example, using simple moving average function from TA-Lib:
def init():
self.sma = self.I(ta.SMA, self.data.Close, self.n_sma)
"""
if name is None:
params = ','.join(filter(None, map(_as_str, chain(args, kwargs.values()))))
func_name = _as_str(func)
name = (f'{func_name}({params})' if params else f'{func_name}')
else:
name = name.format(*map(_as_str, args),
**dict(zip(kwargs.keys(), map(_as_str, kwargs.values()))))
try:
value = func(*args, **kwargs)
except Exception as e:
raise RuntimeError(f'Indicator "{name}" errored with exception: {e}')
if isinstance(value, pd.DataFrame):
value = value.values.T
if value is not None:
value = try_(lambda: np.asarray(value, order='C'), None)
is_arraylike = value is not None
# Optionally flip the array if the user returned e.g. `df.values`
if is_arraylike and np.argmax(value.shape) == 0:
value = value.T
if not is_arraylike or not 1 <= value.ndim <= 2 or value.shape[-1] != len(self._data.Close):
raise ValueError(
'Indicators must return (optionally a tuple of) numpy.arrays of same '
f'length as `data` (data shape: {self._data.Close.shape}; indicator "{name}"'
f'shape: {getattr(value, "shape" , "")}, returned value: {value})')
if plot and overlay is None and np.issubdtype(value.dtype, np.number):
x = value / self._data.Close
# By default, overlay if strong majority of indicator values
# is within 30% of Close
with np.errstate(invalid='ignore'):
overlay = ((x < 1.4) & (x > .6)).mean() > .6
value = _Indicator(value, name=name, plot=plot, overlay=overlay,
color=color, scatter=scatter, histogram=histogram,
# _Indicator.s Series accessor uses this:
index=self.data.index)
self._indicators.append(value)
return value
@abstractmethod
def init(self):
"""
Initialize the strategy.
Override this method.
Declare indicators (with `backtesting.backtesting.Strategy.I`).
Precompute what needs to be precomputed or can be precomputed
in a vectorized fashion before the strategy starts.
If you extend composable strategies from `backtesting.lib`,
make sure to call:
super().init()
"""
@abstractmethod
def next(self):
"""
Main strategy runtime method, called as each new
`backtesting.backtesting.Strategy.data`
instance (row; full candlestick bar) becomes available.
This is the main method where strategy decisions
upon data precomputed in `backtesting.backtesting.Strategy.init`
take place.
If you extend composable strategies from `backtesting.lib`,
make sure to call:
super().next()
"""
class __FULL_EQUITY(float):
def __repr__(self): return '.9999'
_FULL_EQUITY = __FULL_EQUITY(1 - sys.float_info.epsilon)
def buy(self, *,
size: float = _FULL_EQUITY,
limit: float = None,
stop: float = None,
sl: float = None,
tp: float = None):
"""
Place a new long order. For explanation of parameters, see `Order` and its properties.
See also `Strategy.sell()`.
"""
assert 0 < size < 1 or round(size) == size, \
"size must be a positive fraction of equity, or a positive whole number of units"
return self._broker.new_order(size, limit, stop, sl, tp)
def sell(self, *,
size: float = _FULL_EQUITY,
limit: float = None,
stop: float = None,
sl: float = None,
tp: float = None):
"""
Place a new short order. For explanation of parameters, see `Order` and its properties.
See also `Strategy.buy()`.
"""
assert 0 < size < 1 or round(size) == size, \
"size must be a positive fraction of equity, or a positive whole number of units"
return self._broker.new_order(-size, limit, stop, sl, tp)
@property
def equity(self) -> float:
"""Current account equity (cash plus assets)."""
return self._broker.equity
@property
def data(self) -> _Data:
"""
Price data, roughly as passed into
`backtesting.backtesting.Backtest.__init__`,
but with two significant exceptions:
* `data` is _not_ a DataFrame, but a custom structure
that serves customized numpy arrays for reasons of performance
and convenience. Besides OHLCV columns, `.index` and length,
it offers `.pip` property, the smallest price unit of change.
* Within `backtesting.backtesting.Strategy.init`, `data` arrays
are available in full length, as passed into
`backtesting.backtesting.Backtest.__init__`
(for precomputing indicators and such). However, within
`backtesting.backtesting.Strategy.next`, `data` arrays are
only as long as the current iteration, simulating gradual
price point revelation. In each call of
`backtesting.backtesting.Strategy.next` (iteratively called by
`backtesting.backtesting.Backtest` internally),
the last array value (e.g. `data.Close[-1]`)
is always the _most recent_ value.
* If you need data arrays (e.g. `data.Close`) to be indexed
**Pandas series**, you can call their `.s` accessor
(e.g. `data.Close.s`). If you need the whole of data
as a **DataFrame**, use `.df` accessor (i.e. `data.df`).
"""
return self._data
@property
def position(self) -> 'Position':
"""Instance of `backtesting.backtesting.Position`."""
return self._broker.position
@property
def orders(self) -> 'Tuple[Order, ...]':
"""List of orders (see `Order`) waiting for execution."""
return _Orders(self._broker.orders)
@property
def trades(self) -> 'Tuple[Trade, ...]':
"""List of active trades (see `Trade`)."""
return tuple(self._broker.trades)
@property
def closed_trades(self) -> 'Tuple[Trade, ...]':
"""List of settled trades (see `Trade`)."""
return tuple(self._broker.closed_trades)
class _Orders(tuple):
"""
TODO: remove this class. Only for deprecation.
"""
def cancel(self):
"""Cancel all non-contingent (i.e. SL/TP) orders."""
for order in self:
if not order.is_contingent:
order.cancel()
def __getattr__(self, item):
# TODO: Warn on deprecations from the previous version. Remove in the next.
removed_attrs = ('entry', 'set_entry', 'is_long', 'is_short',
'sl', 'tp', 'set_sl', 'set_tp')
if item in removed_attrs:
raise AttributeError(f'Strategy.orders.{"/.".join(removed_attrs)} were removed in'
'Backtesting 0.2.0. '
'Use `Order` API instead. See docs.')
raise AttributeError(f"'tuple' object has no attribute {item!r}")
class Position:
"""
Currently held asset position, available as
`backtesting.backtesting.Strategy.position` within
`backtesting.backtesting.Strategy.next`.
Can be used in boolean contexts, e.g.
if self.position:
... # we have a position, either long or short
"""
def __init__(self, broker: '_Broker'):
self.__broker = broker
def __bool__(self):
return self.size != 0
@property
def size(self) -> float:
"""Position size in units of asset. Negative if position is short."""
return sum(trade.size for trade in self.__broker.trades)
@property
def pl(self) -> float:
"""Profit (positive) or loss (negative) of the current position in cash units."""
return sum(trade.pl for trade in self.__broker.trades)
@property
def pl_pct(self) -> float:
"""Profit (positive) or loss (negative) of the current position in percent."""
weights = np.abs([trade.size for trade in self.__broker.trades])
weights = weights / weights.sum()
pl_pcts = np.array([trade.pl_pct for trade in self.__broker.trades])
return (pl_pcts * weights).sum()
@property
def is_long(self) -> bool:
"""True if the position is long (position size is positive)."""
return self.size > 0
@property
def is_short(self) -> bool:
"""True if the position is short (position size is negative)."""
return self.size < 0
def close(self, portion: float = 1.):
"""
Close portion of position by closing `portion` of each active trade. See `Trade.close`.
"""
for trade in self.__broker.trades:
trade.close(portion)
def __repr__(self):
return f'<Position: {self.size} ({len(self.__broker.trades)} trades)>'
class _OutOfMoneyError(Exception):
pass
class Order:
"""
Place new orders through `Strategy.buy()` and `Strategy.sell()`.
Query existing orders through `Strategy.orders`.
When an order is executed or [filled], it results in a `Trade`.
If you wish to modify aspects of a placed but not yet filled order,
cancel it and place a new one instead.
All placed orders are [Good 'Til Canceled].
[filled]: https://www.investopedia.com/terms/f/fill.asp
[Good 'Til Canceled]: https://www.investopedia.com/terms/g/gtc.asp
"""
def __init__(self, broker: '_Broker',
size: float,
limit_price: float = None,
stop_price: float = None,
sl_price: float = None,
tp_price: float = None,
parent_trade: 'Trade' = None):
self.__broker = broker
assert size != 0
self.__size = size
self.__limit_price = limit_price
self.__stop_price = stop_price
self.__sl_price = sl_price
self.__tp_price = tp_price
self.__parent_trade = parent_trade
def _replace(self, **kwargs):
for k, v in kwargs.items():
setattr(self, f'_{self.__class__.__qualname__}__{k}', v)
return self
def __repr__(self):
return '<Order {}>'.format(', '.join(f'{param}={round(value, 5)}'
for param, value in (
('size', self.__size),
('limit', self.__limit_price),
('stop', self.__stop_price),
('sl', self.__sl_price),
('tp', self.__tp_price),
('contingent', self.is_contingent),
) if value is not None))
def cancel(self):
"""Cancel the order."""
self.__broker.orders.remove(self)
trade = self.__parent_trade
if trade:
if self is trade._sl_order:
trade._replace(sl_order=None)
elif self is trade._tp_order:
trade._replace(tp_order=None)
else:
assert False
# Fields getters
@property
def size(self) -> float:
"""
Order size (negative for short orders).
If size is a value between 0 and 1, it is interpreted as a fraction of current
available liquidity (cash plus `Position.pl` minus used margin).
A value greater than or equal to 1 indicates an absolute number of units.
"""
return self.__size
@property
def limit(self) -> Optional[float]:
"""
Order limit price for [limit orders], or None for [market orders],
which are filled at next available price.
[limit orders]: https://www.investopedia.com/terms/l/limitorder.asp
[market orders]: https://www.investopedia.com/terms/m/marketorder.asp
"""
return self.__limit_price
@property
def stop(self) -> Optional[float]:
"""
Order stop price for [stop-limit/stop-market][_] order,
otherwise None if no stop was set, or the stop price has already been hit.
[_]: https://www.investopedia.com/terms/s/stoporder.asp
"""
return self.__stop_price
@property
def sl(self) -> Optional[float]:
"""
A stop-loss price at which, if set, a new contingent stop-market order
will be placed upon the `Trade` following this order's execution.
See also `Trade.sl`.
"""
return self.__sl_price
@property
def tp(self) -> Optional[float]:
"""
A take-profit price at which, if set, a new contingent limit order
will be placed upon the `Trade` following this order's execution.
See also `Trade.tp`.
"""
return self.__tp_price
@property
def parent_trade(self):
return self.__parent_trade
__pdoc__['Order.parent_trade'] = False
# Extra properties
@property
def is_long(self):
"""True if the order is long (order size is positive)."""
return self.__size > 0
@property
def is_short(self):
"""True if the order is short (order size is negative)."""
return self.__size < 0
@property
def is_contingent(self):
"""
True for [contingent] orders, i.e. [OCO] stop-loss and take-profit bracket orders
placed upon an active trade. Remaining contingent orders are canceled when
their parent `Trade` is closed.
You can modify contingent orders through `Trade.sl` and `Trade.tp`.
[contingent]: https://www.investopedia.com/terms/c/contingentorder.asp
[OCO]: https://www.investopedia.com/terms/o/oco.asp
"""
return bool(self.__parent_trade)
class Trade:
"""
When an `Order` is filled, it results in an active `Trade`.
Find active trades in `Strategy.trades` and closed, settled trades in `Strategy.closed_trades`.
"""
def __init__(self, broker: '_Broker', size: int, entry_price: float, entry_bar):
self.__broker = broker
self.__size = size
self.__entry_price = entry_price
self.__exit_price: Optional[float] = None
self.__entry_bar: int = entry_bar
self.__exit_bar: Optional[int] = None
self.__sl_order: Optional[Order] = None
self.__tp_order: Optional[Order] = None
def __repr__(self):
return f'<Trade size={self.__size} time={self.__entry_bar}-{self.__exit_bar or ""} ' \
f'price={self.__entry_price}-{self.__exit_price or ""} pl={self.pl:.0f}>'
def _replace(self, **kwargs):
for k, v in kwargs.items():
setattr(self, f'_{self.__class__.__qualname__}__{k}', v)
return self
def _copy(self, **kwargs):
return copy(self)._replace(**kwargs)
def close(self, portion: float = 1.):
"""Place new `Order` to close `portion` of the trade at next market price."""
assert 0 < portion <= 1, "portion must be a fraction between 0 and 1"
size = copysign(max(1, round(abs(self.__size) * portion)), -self.__size)
order = Order(self.__broker, size, parent_trade=self)
self.__broker.orders.insert(0, order)
# Fields getters
@property
def size(self):
"""Trade size (volume; negative for short trades)."""
return self.__size
@property
def entry_price(self) -> float:
"""Trade entry price."""
return self.__entry_price
@property
def exit_price(self) -> Optional[float]:
"""Trade exit price (or None if the trade is still active)."""
return self.__exit_price
@property
def entry_bar(self) -> int:
"""Candlestick bar index of when the trade was entered."""
return self.__entry_bar
@property
def exit_bar(self) -> Optional[int]:
"""
Candlestick bar index of when the trade was exited
(or None if the trade is still active).
"""
return self.__exit_bar
@property
def _sl_order(self):
return self.__sl_order
@property
def _tp_order(self):
return self.__tp_order
# Extra properties
@property
def entry_time(self) -> Union[pd.Timestamp, int]:
"""Datetime of when the trade was entered."""
return self.__broker._data.index[self.__entry_bar]
@property
def exit_time(self) -> Optional[Union[pd.Timestamp, int]]:
"""Datetime of when the trade was exited."""
if self.__exit_bar is None:
return None
return self.__broker._data.index[self.__exit_bar]
@property
def is_long(self):
"""True if the trade is long (trade size is positive)."""
return self.__size > 0
@property
def is_short(self):
"""True if the trade is short (trade size is negative)."""
return not self.is_long
@property
def pl(self):
"""Trade profit (positive) or loss (negative) in cash units."""
price = self.__exit_price or self.__broker.last_price
return self.__size * (price - self.__entry_price)
@property
def pl_pct(self):
"""Trade profit (positive) or loss (negative) in percent."""
price = self.__exit_price or self.__broker.last_price
return copysign(1, self.__size) * (price / self.__entry_price - 1)
@property
def value(self):
"""Trade total value in cash (volume × price)."""
price = self.__exit_price or self.__broker.last_price
return abs(self.__size) * price
# SL/TP management API
@property
def sl(self):
"""
Stop-loss price at which to close the trade.
This variable is writable. By assigning it a new price value,
you create or modify the existing SL order.
By assigning it `None`, you cancel it.
"""
return self.__sl_order and self.__sl_order.stop
@sl.setter
def sl(self, price: float):
self.__set_contingent('sl', price)
@property
def tp(self):
"""
Take-profit price at which to close the trade.
This property is writable. By assigning it a new price value,
you create or modify the existing TP order.
By assigning it `None`, you cancel it.
"""
return self.__tp_order and self.__tp_order.limit
@tp.setter
def tp(self, price: float):
self.__set_contingent('tp', price)
def __set_contingent(self, type, price):
assert type in ('sl', 'tp')
assert price is None or 0 < price < np.inf
attr = f'_{self.__class__.__qualname__}__{type}_order'
order: Order = getattr(self, attr)
if order:
order.cancel()
if price:
kwargs = dict(stop=price) if type == 'sl' else dict(limit=price)
order = self.__broker.new_order(-self.size, trade=self, **kwargs)
setattr(self, attr, order)
class _Broker:
def __init__(self, *, data, cash, commission, margin,
trade_on_close, hedging, exclusive_orders, index):
assert 0 < cash, f"cash should be >0, is {cash}"
assert -.1 <= commission < .1, \
("commission should be between -10% "
f"(e.g. market-maker's rebates) and 10% (fees), is {commission}")
assert 0 < margin <= 1, f"margin should be between 0 and 1, is {margin}"
self._data: _Data = data
self._cash = cash
self._commission = commission
self._leverage = 1 / margin
self._trade_on_close = trade_on_close
self._hedging = hedging
self._exclusive_orders = exclusive_orders
self._equity = np.tile(np.nan, len(index))
self.orders: List[Order] = []
self.trades: List[Trade] = []
self.position = Position(self)
self.closed_trades: List[Trade] = []
def __repr__(self):
return f'<Broker: {self._cash:.0f}{self.position.pl:+.1f} ({len(self.trades)} trades)>'
def new_order(self,
size: float,
limit: float = None,
stop: float = None,
sl: float = None,
tp: float = None,
*,
trade: Trade = None):
"""
Argument size indicates whether the order is long or short
"""
size = float(size)
stop = stop and float(stop)
limit = limit and float(limit)
sl = sl and float(sl)
tp = tp and float(tp)
is_long = size > 0
adjusted_price = self._adjusted_price(size)
if is_long:
if not (sl or -np.inf) < (limit or stop or adjusted_price) < (tp or np.inf):
raise ValueError(
"Long orders require: "
f"SL ({sl}) < LIMIT ({limit or stop or adjusted_price}) < TP ({tp})")
else:
if not (tp or -np.inf) < (limit or stop or adjusted_price) < (sl or np.inf):
raise ValueError(
"Short orders require: "
f"TP ({tp}) < LIMIT ({limit or stop or adjusted_price}) < SL ({sl})")
order = Order(self, size, limit, stop, sl, tp, trade)
# Put the new order in the order queue,
# inserting SL/TP/trade-closing orders in-front
if trade:
self.orders.insert(0, order)
else:
# If exclusive orders (each new order auto-closes previous orders/position),
# cancel all non-contingent orders and close all open trades beforehand
if self._exclusive_orders:
for o in self.orders:
if not o.is_contingent:
o.cancel()
for t in self.trades:
t.close()
self.orders.append(order)
return order
@property
def last_price(self) -> float:
""" Price at the last (current) close. """
return self._data.Close[-1]
def _adjusted_price(self, size=None, price=None) -> float:
"""
Long/short `price`, adjusted for commisions.
In long positions, the adjusted price is a fraction higher, and vice versa.
"""
return (price or self.last_price) * (1 + copysign(self._commission, size))
@property
def equity(self) -> float:
return self._cash + sum(trade.pl for trade in self.trades)
@property
def margin_available(self) -> float:
# From https://github.com/QuantConnect/Lean/pull/3768
margin_used = sum(trade.value / self._leverage for trade in self.trades)
return max(0, self.equity - margin_used)
def next(self):
i = self._i = len(self._data) - 1
self._process_orders()
# Log account equity for the equity curve
equity = self.equity
self._equity[i] = equity
# If equity is negative, set all to 0 and stop the simulation
if equity <= 0:
assert self.margin_available <= 0
for trade in self.trades:
self._close_trade(trade, self._data.Close[-1], i)
self._cash = 0
self._equity[i:] = 0
raise _OutOfMoneyError
def _process_orders(self):
data = self._data
open, high, low = data.Open[-1], data.High[-1], data.Low[-1]
prev_close = data.Close[-2]
reprocess_orders = False
# Process orders
for order in list(self.orders): # type: Order
# Related SL/TP order was already removed
if order not in self.orders:
continue
# Check if stop condition was hit
stop_price = order.stop
if stop_price:
is_stop_hit = ((high > stop_price) if order.is_long else (low < stop_price))
if not is_stop_hit:
continue
# > When the stop price is reached, a stop order becomes a market/limit order.
# https://www.sec.gov/fast-answers/answersstopordhtm.html
order._replace(stop_price=None)
# Determine purchase price.
# Check if limit order can be filled.
if order.limit:
is_limit_hit = low < order.limit if order.is_long else high > order.limit
# When stop and limit are hit within the same bar, we pessimistically
# assume limit was hit before the stop (i.e. "before it counts")
is_limit_hit_before_stop = (is_limit_hit and
(order.limit < (stop_price or -np.inf)
if order.is_long
else order.limit > (stop_price or np.inf)))
if not is_limit_hit or is_limit_hit_before_stop:
continue
# stop_price, if set, was hit within this bar
price = (min(stop_price or open, order.limit)
if order.is_long else
max(stop_price or open, order.limit))
else:
# Market-if-touched / market order
price = prev_close if self._trade_on_close else open
price = (max(price, stop_price or -np.inf)
if order.is_long else
min(price, stop_price or np.inf))
# Determine entry/exit bar index
is_market_order = not order.limit and not stop_price
time_index = (self._i - 1) if is_market_order and self._trade_on_close else self._i
# If order is a SL/TP order, it should close an existing trade it was contingent upon
if order.parent_trade:
trade = order.parent_trade
_prev_size = trade.size
# If order.size is "greater" than trade.size, this order is a trade.close()
# order and part of the trade was already closed beforehand
size = copysign(min(abs(_prev_size), abs(order.size)), order.size)
# If this trade isn't already closed (e.g. on multiple `trade.close(.5)` calls)
if trade in self.trades:
self._reduce_trade(trade, price, size, time_index)
assert order.size != -_prev_size or trade not in self.trades
if order in (trade._sl_order,
trade._tp_order):
assert order.size == -trade.size
assert order not in self.orders # Removed when trade was closed
else:
# It's a trade.close() order, now done
assert abs(_prev_size) >= abs(size) >= 1
self.orders.remove(order)
continue
# Else this is a stand-alone trade
# Adjust price to include commission (or bid-ask spread).
# In long positions, the adjusted price is a fraction higher, and vice versa.
adjusted_price = self._adjusted_price(order.size, price)
# If order size was specified proportionally,
# precompute true size in units, accounting for margin and spread/commissions
size = order.size
if -1 < size < 1:
size = copysign(int((self.margin_available * self._leverage * abs(size))
// adjusted_price), size)
# Not enough cash/margin even for a single unit
if not size:
self.orders.remove(order)
continue
assert size == round(size)
need_size = int(size)
if not self._hedging:
# Fill position by FIFO closing/reducing existing opposite-facing trades.
# Existing trades are closed at unadjusted price, because the adjustment
# was already made when buying.
for trade in list(self.trades):
if trade.is_long == order.is_long:
continue
assert trade.size * order.size < 0
# Order size greater than this opposite-directed existing trade,
# so it will be closed completely
if abs(need_size) >= abs(trade.size):
self._close_trade(trade, price, time_index)
need_size += trade.size
else:
# The existing trade is larger than the new order,
# so it will only be closed partially
self._reduce_trade(trade, price, need_size, time_index)
need_size = 0
if not need_size:
break
# If we don't have enough liquidity to cover for the order, cancel it
if abs(need_size) * adjusted_price > self.margin_available * self._leverage:
self.orders.remove(order)
continue
# Open a new trade
if need_size:
self._open_trade(adjusted_price, need_size, order.sl, order.tp, time_index)
# We need to reprocess the SL/TP orders newly added to the queue.
# This allows e.g. SL hitting in the same bar the order was open.
# See https://github.com/kernc/backtesting.py/issues/119
if order.sl or order.tp:
if is_market_order:
reprocess_orders = True
elif (low <= (order.sl or -np.inf) <= high or
low <= (order.tp or -np.inf) <= high):
warnings.warn(
f"({data.index[-1]}) A contingent SL/TP order would execute in the "
"same bar its parent stop/limit order was turned into a trade. "
"Since we can't assert the precise intra-candle "
"price movement, the affected SL/TP order will instead be executed on "
"the next (matching) price/bar, making the result (of this trade) "
"somewhat dubious. "
"See https://github.com/kernc/backtesting.py/issues/119",
UserWarning)
# Order processed
self.orders.remove(order)
if reprocess_orders:
self._process_orders()
def _reduce_trade(self, trade: Trade, price: float, size: float, time_index: int):
assert trade.size * size < 0
assert abs(trade.size) >= abs(size)
size_left = trade.size + size
assert size_left * trade.size >= 0
if not size_left:
close_trade = trade
else:
# Reduce existing trade ...
trade._replace(size=size_left)
if trade._sl_order:
trade._sl_order._replace(size=-trade.size)
if trade._tp_order:
trade._tp_order._replace(size=-trade.size)
# ... by closing a reduced copy of it
close_trade = trade._copy(size=-size, sl_order=None, tp_order=None)
self.trades.append(close_trade)
self._close_trade(close_trade, price, time_index)
def _close_trade(self, trade: Trade, price: float, time_index: int):
self.trades.remove(trade)
if trade._sl_order:
self.orders.remove(trade._sl_order)
if trade._tp_order:
self.orders.remove(trade._tp_order)
self.closed_trades.append(trade._replace(exit_price=price, exit_bar=time_index))
self._cash += trade.pl
def _open_trade(self, price: float, size: int, sl: float, tp: float, time_index: int):
trade = Trade(self, size, price, time_index)
self.trades.append(trade)
# Create SL/TP (bracket) orders.
# Make sure SL order is created first so it gets adversarially processed before TP order
# in case of an ambiguous tie (both hit within a single bar).
# Note, sl/tp orders are inserted at the front of the list, thus order reversed.
if tp:
trade.tp = tp
if sl:
trade.sl = sl
class Backtest:
"""
Backtest a particular (parameterized) strategy
on particular data.
Upon initialization, call method
`backtesting.backtesting.Backtest.run` to run a backtest
instance, or `backtesting.backtesting.Backtest.optimize` to
optimize it.
"""
def __init__(self,
data: pd.DataFrame,
strategy: Type[Strategy],
*,
cash: float = 10_000,
commission: float = .0,
margin: float = 1.,
trade_on_close=False,
hedging=False,
exclusive_orders=False
):
"""
Initialize a backtest. Requires data and a strategy to test.
`data` is a `pd.DataFrame` with columns:
`Open`, `High`, `Low`, `Close`, and (optionally) `Volume`.
If any columns are missing, set them to what you have available,