/
strategy.py
1482 lines (1412 loc) · 57.6 KB
/
strategy.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
"""Contains implementation for backtesting trading strategies."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import dataclasses
import numpy as np
import pandas as pd
from pybroker.cache import CacheDateFields
from pybroker.common import (
BarData,
DataCol,
Day,
IndicatorSymbol,
ModelSymbol,
PriceType,
quantize,
to_datetime,
to_decimal,
to_seconds,
verify_data_source_columns,
verify_date_range,
)
from pybroker.config import StrategyConfig
from pybroker.context import (
ExecContext,
ExecResult,
PosSizeContext,
set_exec_ctx_data,
set_pos_size_ctx_data,
)
from pybroker.data import AlpacaCrypto, DataSource
from pybroker.eval import BootstrapResult, EvalMetrics, EvaluateMixin
from pybroker.indicator import Indicator, IndicatorsMixin
from pybroker.model import ModelSource, ModelsMixin, TrainedModel
from pybroker.portfolio import (
Order,
Portfolio,
PortfolioBar,
PositionBar,
Trade,
)
from pybroker.scope import (
ColumnScope,
IndicatorScope,
ModelInputScope,
PendingOrderScope,
PredictionScope,
PriceScope,
StaticScope,
)
from pybroker.slippage import SlippageModel
from collections import defaultdict, deque
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from numpy.typing import NDArray
from typing import (
Callable,
Iterable,
Iterator,
Literal,
Mapping,
NamedTuple,
Optional,
Union,
)
def _between(
df: pd.DataFrame, start_date: datetime, end_date: datetime
) -> pd.DataFrame:
if df.empty:
return df
return df[
(df[DataCol.DATE.value].dt.tz_localize(None) >= start_date)
& (df[DataCol.DATE.value].dt.tz_localize(None) <= end_date)
]
def _sort_by_score(result: ExecResult) -> float:
return 0.0 if result.score is None else result.score
class Execution(NamedTuple):
r"""Represents an execution of a :class:`.Strategy`. Holds a reference to
a :class:`Callable` that implements trading logic.
Attributes:
id: Unique ID.
symbols: Ticker symbols used for execution of ``fn``.
fn: Implements trading logic.
model_names: Names of :class:`pybroker.model.ModelSource`\ s used for
execution of ``fn``.
indicator_names: Names of :class:`pybroker.indicator.Indicator`\ s
used for execution of ``fn``.
"""
id: int
symbols: frozenset[str]
fn: Optional[Callable[[ExecContext], None]]
model_names: frozenset[str]
indicator_names: frozenset[str]
class BacktestMixin:
"""Mixin implementing backtesting functionality."""
def backtest_executions(
self,
config: StrategyConfig,
executions: set[Execution],
before_exec_fn: Optional[Callable[[Mapping[str, ExecContext]], None]],
after_exec_fn: Optional[Callable[[Mapping[str, ExecContext]], None]],
sessions: Mapping[str, Mapping],
models: Mapping[ModelSymbol, TrainedModel],
indicator_data: Mapping[IndicatorSymbol, pd.Series],
test_data: pd.DataFrame,
portfolio: Portfolio,
pos_size_handler: Optional[Callable[[PosSizeContext], None]],
exit_dates: Mapping[str, np.datetime64],
slippage_model: Optional[SlippageModel] = None,
enable_fractional_shares: bool = False,
warmup: Optional[int] = None,
):
r"""Backtests a ``set`` of :class:`.Execution`\ s that implement
trading logic.
Args:
config: :class:`pybroker.config.StrategyConfig`.
executions: :class:`.Execution`\ s to run.
sessions: :class:`Mapping` of symbols to :class:`Mapping` of custom
data that persists for every bar during the
:class:`.Execution`.
models: :class:`Mapping` of :class:`pybroker.common.ModelSymbol`
pairs to :class:`pybroker.common.TrainedModel`\ s.
indicator_data: :class:`Mapping` of
:class:`pybroker.common.IndicatorSymbol` pairs to
:class:`pandas.Series` of :class:`pybroker.indicator.Indicator`
values.
test_data: :class:`pandas.DataFrame` of test data.
portfolio: :class:`pybroker.portfolio.Portfolio`.
pos_size_handler: :class:`Callable` that sets position sizes when
placing orders for buy and sell signals.
exit_dates: :class:`Mapping` of symbols to exit dates.
enable_fractional_shares: Whether to enable trading fractional
shares.
warmup: Number of bars that need to pass before running the
executions.
Returns:
:class:`.TestResult` of the backtest.
"""
test_dates = test_data[DataCol.DATE.value].unique()
test_dates.sort()
test_syms = test_data[DataCol.SYMBOL.value].unique()
test_data = (
test_data.reset_index(drop=True)
.set_index([DataCol.SYMBOL.value, DataCol.DATE.value])
.sort_index()
)
sym_end_index: dict[str, int] = defaultdict(int)
col_scope = ColumnScope(test_data)
price_scope = PriceScope(col_scope, sym_end_index)
ind_scope = IndicatorScope(indicator_data, test_dates)
input_scope = ModelInputScope(col_scope, ind_scope, models)
pred_scope = PredictionScope(models, input_scope)
pending_order_scope = PendingOrderScope()
exec_ctxs: dict[str, ExecContext] = {}
exec_fns: dict[str, Callable[[ExecContext], None]] = {}
for sym in test_syms:
for exec in executions:
if sym not in exec.symbols:
continue
exec_ctxs[sym] = ExecContext(
symbol=sym,
config=config,
portfolio=portfolio,
col_scope=col_scope,
ind_scope=ind_scope,
input_scope=input_scope,
pred_scope=pred_scope,
pending_order_scope=pending_order_scope,
models=models,
sym_end_index=sym_end_index,
session=sessions[sym],
)
if exec.fn is not None:
exec_fns[sym] = exec.fn
sym_exec_dates = {
sym: frozenset(test_data.loc[pd.IndexSlice[sym, :]].index.values)
for sym in exec_ctxs.keys()
}
cover_sched: dict[np.datetime64, list[ExecResult]] = defaultdict(list)
buy_sched: dict[np.datetime64, list[ExecResult]] = defaultdict(list)
sell_sched: dict[np.datetime64, list[ExecResult]] = defaultdict(list)
if pos_size_handler is not None:
pos_ctx = PosSizeContext(
config=config,
portfolio=portfolio,
col_scope=col_scope,
ind_scope=ind_scope,
input_scope=input_scope,
pred_scope=pred_scope,
pending_order_scope=pending_order_scope,
models=models,
sessions=sessions,
sym_end_index=sym_end_index,
)
logger = StaticScope.instance().logger
logger.backtest_executions_start(test_dates)
cover_results: deque[ExecResult] = deque()
buy_results: deque[ExecResult] = deque()
sell_results: deque[ExecResult] = deque()
exit_ctxs: deque[ExecContext] = deque()
active_ctxs: dict[str, ExecContext] = {}
for i, date in enumerate(test_dates):
active_ctxs.clear()
for sym, ctx in exec_ctxs.items():
if date not in sym_exec_dates[sym]:
continue
sym_end_index[sym] += 1
if warmup and sym_end_index[sym] <= warmup:
continue
active_ctxs[sym] = ctx
set_exec_ctx_data(ctx, date)
if (
exit_dates
and sym in exit_dates
and date == exit_dates[sym]
):
exit_ctxs.append(ctx)
is_cover_sched = date in cover_sched
is_buy_sched = date in buy_sched
is_sell_sched = date in sell_sched
if (
config.max_long_positions is not None
or pos_size_handler is not None
):
if is_cover_sched:
cover_sched[date].sort(key=_sort_by_score, reverse=True)
elif is_buy_sched:
buy_sched[date].sort(key=_sort_by_score, reverse=True)
if is_sell_sched and (
config.max_short_positions is not None
or pos_size_handler is not None
):
sell_sched[date].sort(key=_sort_by_score, reverse=True)
if pos_size_handler is not None and (
is_cover_sched or is_buy_sched or is_sell_sched
):
pos_size_buy_results = None
if is_cover_sched:
pos_size_buy_results = cover_sched[date]
elif is_buy_sched:
pos_size_buy_results = buy_sched[date]
self._set_pos_sizes(
pos_size_handler=pos_size_handler,
pos_ctx=pos_ctx,
buy_results=pos_size_buy_results,
sell_results=sell_sched[date] if is_sell_sched else None,
)
portfolio.check_stops(date, price_scope)
if is_cover_sched:
self._place_buy_orders(
date=date,
price_scope=price_scope,
pending_order_scope=pending_order_scope,
buy_sched=cover_sched,
portfolio=portfolio,
enable_fractional_shares=enable_fractional_shares,
)
if is_sell_sched:
self._place_sell_orders(
date=date,
price_scope=price_scope,
pending_order_scope=pending_order_scope,
sell_sched=sell_sched,
portfolio=portfolio,
enable_fractional_shares=enable_fractional_shares,
)
if is_buy_sched:
self._place_buy_orders(
date=date,
price_scope=price_scope,
pending_order_scope=pending_order_scope,
buy_sched=buy_sched,
portfolio=portfolio,
enable_fractional_shares=enable_fractional_shares,
)
portfolio.capture_bar(date, test_data)
if before_exec_fn is not None and active_ctxs:
before_exec_fn(active_ctxs)
for sym, ctx in active_ctxs.items():
if sym in exec_fns:
exec_fns[sym](ctx)
if after_exec_fn is not None and active_ctxs:
after_exec_fn(active_ctxs)
for ctx in active_ctxs.values():
if slippage_model and (ctx.buy_shares or ctx.sell_shares):
self._apply_slippage(slippage_model, ctx)
result = ctx.to_result()
if result is None:
continue
if result.buy_shares is not None:
if result.cover:
cover_results.append(result)
else:
buy_results.append(result)
if result.sell_shares is not None:
sell_results.append(result)
while cover_results:
self._schedule_order(
result=cover_results.popleft(),
created=date,
sym_end_index=sym_end_index,
delay=config.buy_delay,
sched=cover_sched,
col_scope=col_scope,
pending_order_scope=pending_order_scope,
)
while buy_results:
self._schedule_order(
result=buy_results.popleft(),
created=date,
sym_end_index=sym_end_index,
delay=config.buy_delay,
sched=buy_sched,
col_scope=col_scope,
pending_order_scope=pending_order_scope,
)
while sell_results:
self._schedule_order(
result=sell_results.popleft(),
created=date,
sym_end_index=sym_end_index,
delay=config.sell_delay,
sched=sell_sched,
col_scope=col_scope,
pending_order_scope=pending_order_scope,
)
while exit_ctxs:
self._exit_position(
portfolio=portfolio,
date=date,
ctx=exit_ctxs.popleft(),
exit_cover_fill_price=config.exit_cover_fill_price,
exit_sell_fill_price=config.exit_sell_fill_price,
price_scope=price_scope,
)
portfolio.incr_bars()
if i % 10 == 0 or i == len(test_dates) - 1:
logger.backtest_executions_loading(i + 1)
def _apply_slippage(
self,
slippage_model: SlippageModel,
ctx: ExecContext,
):
buy_shares = to_decimal(ctx.buy_shares) if ctx.buy_shares else None
sell_shares = to_decimal(ctx.sell_shares) if ctx.sell_shares else None
slippage_model.apply_slippage(
ctx, buy_shares=buy_shares, sell_shares=sell_shares
)
def _exit_position(
self,
portfolio: Portfolio,
date: np.datetime64,
ctx: ExecContext,
exit_cover_fill_price: Union[
PriceType, Callable[[str, BarData], Union[int, float, Decimal]]
],
exit_sell_fill_price: Union[
PriceType, Callable[[str, BarData], Union[int, float, Decimal]]
],
price_scope: PriceScope,
):
buy_fill_price = price_scope.fetch(ctx.symbol, exit_cover_fill_price)
sell_fill_price = price_scope.fetch(ctx.symbol, exit_sell_fill_price)
portfolio.exit_position(
date,
ctx.symbol,
buy_fill_price=buy_fill_price,
sell_fill_price=sell_fill_price,
)
def _set_pos_sizes(
self,
pos_size_handler: Callable[[PosSizeContext], None],
pos_ctx: PosSizeContext,
buy_results: Optional[list[ExecResult]],
sell_results: Optional[list[ExecResult]],
):
set_pos_size_ctx_data(
ctx=pos_ctx, buy_results=buy_results, sell_results=sell_results
)
pos_size_handler(pos_ctx)
for id, shares in pos_ctx._signal_shares.items():
if id < 0:
raise ValueError(f"Invalid ExecSignal id: {id}")
if buy_results is not None and sell_results is not None:
if id >= (len(buy_results) + len(sell_results)):
raise ValueError(f"Invalid ExecSignal id: {id}")
if id < len(buy_results):
buy_results[id].buy_shares = to_decimal(shares)
else:
sell_results[
id - len(buy_results)
].sell_shares = to_decimal(shares)
elif buy_results is not None:
if id >= len(buy_results):
raise ValueError(f"Invalid ExecSignal id: {id}")
buy_results[id].buy_shares = to_decimal(shares)
elif sell_results is not None:
if id >= len(sell_results):
raise ValueError(f"Invalid ExecSignal id: {id}")
sell_results[id].sell_shares = to_decimal(shares)
else:
raise ValueError(
"buy_results and sell_results cannot both be None."
)
def _schedule_order(
self,
result: ExecResult,
created: np.datetime64,
sym_end_index: Mapping[str, int],
delay: int,
sched: Mapping[np.datetime64, list[ExecResult]],
col_scope: ColumnScope,
pending_order_scope: PendingOrderScope,
):
date_loc = sym_end_index[result.symbol] - 1
dates = col_scope.fetch(result.symbol, DataCol.DATE.value)
if dates is None:
raise ValueError("Dates not found.")
logger = StaticScope.instance().logger
if date_loc + delay < len(dates):
date = dates[date_loc + delay]
order_type: Literal["buy", "sell"]
if result.buy_shares is not None:
order_type = "buy"
shares = result.buy_shares
limit_price = result.buy_limit_price
fill_price = result.buy_fill_price
elif result.sell_shares is not None:
order_type = "sell"
shares = result.sell_shares
limit_price = result.sell_limit_price
fill_price = result.sell_fill_price
else:
raise ValueError("buy_shares or sell_shares needs to be set.")
result.pending_order_id = pending_order_scope.add(
type=order_type,
symbol=result.symbol,
created=created,
exec_date=date,
shares=shares,
limit_price=limit_price,
fill_price=fill_price,
)
sched[date].append(result)
logger.debug_schedule_order(date, result)
else:
logger.debug_unscheduled_order(result)
def _place_buy_orders(
self,
date: np.datetime64,
price_scope: PriceScope,
pending_order_scope: PendingOrderScope,
buy_sched: dict[np.datetime64, list[ExecResult]],
portfolio: Portfolio,
enable_fractional_shares: bool,
):
buy_results = buy_sched[date]
for result in buy_results:
if result.buy_shares is None:
continue
if (
result.pending_order_id is None
or not pending_order_scope.contains(result.pending_order_id)
):
continue
pending_order_scope.remove(result.pending_order_id)
buy_shares = self._get_shares(
result.buy_shares, enable_fractional_shares
)
fill_price = price_scope.fetch(
result.symbol, result.buy_fill_price
)
order = portfolio.buy(
date=date,
symbol=result.symbol,
shares=buy_shares,
fill_price=fill_price,
limit_price=result.buy_limit_price,
stops=result.long_stops,
)
logger = StaticScope.instance().logger
if order is None:
logger.debug_unfilled_buy_order(
date=date,
symbol=result.symbol,
shares=buy_shares,
fill_price=fill_price,
limit_price=result.buy_limit_price,
)
else:
logger.debug_filled_buy_order(
date=date,
symbol=result.symbol,
shares=buy_shares,
fill_price=fill_price,
limit_price=result.buy_limit_price,
)
del buy_sched[date]
def _place_sell_orders(
self,
date: np.datetime64,
price_scope: PriceScope,
pending_order_scope: PendingOrderScope,
sell_sched: dict[np.datetime64, list[ExecResult]],
portfolio: Portfolio,
enable_fractional_shares: bool,
):
sell_results = sell_sched[date]
for result in sell_results:
if result.sell_shares is None:
continue
if (
result.pending_order_id is None
or not pending_order_scope.contains(result.pending_order_id)
):
continue
pending_order_scope.remove(result.pending_order_id)
sell_shares = self._get_shares(
result.sell_shares, enable_fractional_shares
)
fill_price = price_scope.fetch(
result.symbol, result.sell_fill_price
)
order = portfolio.sell(
date=date,
symbol=result.symbol,
shares=sell_shares,
fill_price=fill_price,
limit_price=result.sell_limit_price,
stops=result.short_stops,
)
logger = StaticScope.instance().logger
if order is None:
logger.debug_unfilled_sell_order(
date=date,
symbol=result.symbol,
shares=sell_shares,
fill_price=fill_price,
limit_price=result.sell_limit_price,
)
else:
logger.debug_filled_sell_order(
date=date,
symbol=result.symbol,
shares=sell_shares,
fill_price=fill_price,
limit_price=result.sell_limit_price,
)
del sell_sched[date]
def _get_shares(
self,
shares: Union[int, float, Decimal],
enable_fractional_shares: bool,
) -> Decimal:
if enable_fractional_shares:
return to_decimal(shares)
else:
return to_decimal(int(shares))
class WalkforwardWindow(NamedTuple):
"""Contains ``train_data`` and ``test_data`` of a time window used for
`Walkforward Analysis
<https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html#Walkforward-Analysis>`_.
Attributes:
train_data: Train data.
test_data: Test data.
"""
train_data: NDArray[np.int_]
test_data: NDArray[np.int_]
class WalkforwardMixin:
"""Mixin implementing logic for `Walkforward Analysis
<https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html#Walkforward-Analysis>`_.
"""
def walkforward_split(
self,
df: pd.DataFrame,
windows: int,
lookahead: int,
train_size: float = 0.9,
shuffle: bool = False,
) -> Iterator[WalkforwardWindow]:
r"""Splits a :class:`pandas.DataFrame` containing data for multiple
ticker symbols into an :class:`Iterator` of train/test time windows for
`Walkforward Analysis
<https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html#Walkforward-Analysis>`_.
Args:
df: :class:`pandas.DataFrame` of data to split into train/test
windows for Walkforward Analysis.
windows: Number of walkforward time windows.
lookahead: Number of bars in the future of the target prediction.
For example, predicting returns for the next bar would have a
``lookahead`` of ``1``. This quantity is needed to prevent
training data from leaking into the test boundary.
train_size: Amount of data in ``df`` to use for training, where
the max ``train_size`` is ``1``. For example, a ``train_size``
of ``0.9`` would result in 90% of data in ``df`` being used for
training and the remaining 10% of data being used for testing.
shuffle: Whether to randomly shuffle the data used for training.
Defaults to ``False``.
Returns:
:class:`Iterator` of :class:`.WalkforwardWindow`\ s containing
train and test data.
"""
if windows <= 0:
raise ValueError("windows needs to be > 0.")
if lookahead <= 0:
raise ValueError("lookahead needs to be > 0.")
if train_size < 0:
raise ValueError("train_size cannot be negative.")
if df.empty:
raise ValueError("DataFrame is empty.")
date_col = DataCol.DATE.value
dates = df[[date_col]]
window_dates = df[date_col].unique()
window_dates.sort()
error_msg = f"""
Invalid params for {len(window_dates)} dates:
windows: {windows}
lookahead: {lookahead}
train_size: {train_size}
"""
if train_size == 0 or train_size == 1:
window_length = int(len(window_dates) / windows)
offset = len(window_dates) - window_length * windows
for i in range(windows):
start = offset + i * window_length
end = start + window_length
if train_size == 0:
test_idx = dates[
(dates[date_col] >= window_dates[start])
& (dates[date_col] <= window_dates[end - 1])
]
test_idx = test_idx.index.to_numpy()
yield WalkforwardWindow(np.array(tuple()), test_idx)
else:
train_idx = dates[
(dates[date_col] >= window_dates[start])
& (dates[date_col] <= window_dates[end - 1])
]
train_idx = train_idx.index.to_numpy()
if shuffle:
np.random.shuffle(train_idx)
yield WalkforwardWindow(train_idx, np.array(tuple()))
elif windows == 1:
res = len(window_dates) - 1 - lookahead
if res <= 0:
raise ValueError(error_msg)
train_length = int(res * train_size)
test_length = int(res * (1 - train_size))
train_start = 0
train_end = train_length
test_start = train_end + lookahead
if test_start >= len(window_dates):
raise ValueError(error_msg)
test_end = test_start + test_length
train_idx = dates[
(dates[date_col] >= window_dates[train_start])
& (dates[date_col] <= window_dates[train_end])
]
test_idx = dates[
(dates[date_col] >= window_dates[test_start])
& (dates[date_col] <= window_dates[test_end])
]
train_idx = train_idx.index.to_numpy()
test_idx = test_idx.index.to_numpy()
if shuffle:
np.random.shuffle(train_idx)
yield WalkforwardWindow(train_idx, test_idx)
else:
res = len(window_dates) - (lookahead - 1) * windows
window_length = res / windows # type: ignore[assignment]
train_length = int(window_length * train_size)
test_length = int(window_length * (1 - train_size))
if train_length < 0 or test_length < 0:
raise ValueError(error_msg)
while True:
rem = (res - (train_length + test_length * windows)) / windows
train_incr = int(rem * train_size)
test_incr = int(rem * (1 - train_size))
if train_incr == 0 or test_incr == 0:
break
train_length += train_incr
test_length += test_incr
if train_length == 0 and test_length == 0:
raise ValueError(error_msg)
window_idx = []
for i in range(windows):
test_end = i * test_length
test_start = test_end + test_length
train_end = test_start + lookahead - 1
train_start = train_end + train_length
window_idx.append(
(train_start, train_end, test_start, test_end)
)
window_idx.reverse()
window_dates = window_dates[::-1]
for train_start, train_end, test_start, test_end in window_idx:
train_idx = dates[
(dates[date_col] > window_dates[train_start])
& (dates[date_col] <= window_dates[train_end])
]
test_idx = dates[
(dates[date_col] > window_dates[test_start])
& (dates[date_col] <= window_dates[test_end])
]
train_idx = train_idx.index.to_numpy()
test_idx = test_idx.index.to_numpy()
if shuffle:
np.random.shuffle(train_idx)
yield WalkforwardWindow(train_idx, test_idx)
@dataclass(frozen=True)
class TestResult:
"""Contains the results of backtesting a :class:`.Strategy`.
Attributes:
start_date: Starting date of backtest.
end_date: Ending date of backtest.
portfolio: :class:`pandas.DataFrame` of
:class:`pybroker.portfolio.Portfolio` balances for every bar.
positions: :class:`pandas.DataFrame` of
:class:`pybroker.portfolio.Position` balances for every bar.
orders: :class:`pandas.DataFrame` of all orders that were placed.
trades: :class:`pandas.DataFrame` of all trades that were made.
metrics: Evaluation metrics.
metrics_df: :class:`pandas.DataFrame` of evaluation metrics.
bootstrap: Randomized bootstrap evaluation metrics.
"""
start_date: datetime
end_date: datetime
portfolio: pd.DataFrame
positions: pd.DataFrame
orders: pd.DataFrame
trades: pd.DataFrame
metrics: EvalMetrics
metrics_df: pd.DataFrame
bootstrap: Optional[BootstrapResult]
class Strategy(
BacktestMixin,
EvaluateMixin,
IndicatorsMixin,
ModelsMixin,
WalkforwardMixin,
):
"""Class representing a trading strategy to backtest.
Args:
data_source: :class:`pybroker.data.DataSource` or
:class:`pandas.DataFrame` of backtesting data.
start_date: Starting date of the data to fetch from ``data_source``
(inclusive).
end_date: Ending date of the data to fetch from ``data_source``
(inclusive).
config: ``Optional`` :class:`pybroker.config.StrategyConfig`.
"""
_execution_id: int = 0
def __init__(
self,
data_source: Union[DataSource, pd.DataFrame],
start_date: Union[str, datetime],
end_date: Union[str, datetime],
config: Optional[StrategyConfig] = None,
):
self._verify_data_source(data_source)
self._data_source = data_source
self._start_date = to_datetime(start_date)
self._end_date = to_datetime(end_date)
verify_date_range(self._start_date, self._end_date)
if config is not None:
self._verify_config(config)
self._config = config
else:
self._config = StrategyConfig()
self._executions: set[Execution] = set()
self._before_exec_fn: Optional[
Callable[[Mapping[str, ExecContext]], None]
] = None
self._after_exec_fn: Optional[
Callable[[Mapping[str, ExecContext]], None]
] = None
self._pos_size_handler: Optional[
Callable[[PosSizeContext], None]
] = None
self._slippage_model: Optional[SlippageModel] = None
self._scope = StaticScope.instance()
self._logger = self._scope.logger
def _verify_config(self, config: StrategyConfig):
if config.initial_cash <= 0:
raise ValueError("initial_cash must be greater than 0.")
if (
config.max_long_positions is not None
and config.max_long_positions <= 0
):
raise ValueError("max_long_positions must be greater than 0.")
if (
config.max_short_positions is not None
and config.max_short_positions <= 0
):
raise ValueError("max_short_positions must be greater than 0.")
if config.buy_delay <= 0:
raise ValueError("buy_delay must be greater than 0.")
if config.sell_delay <= 0:
raise ValueError("sell_delay must be greater than 0.")
if config.bootstrap_samples <= 0:
raise ValueError("bootstrap_samples must be greater than 0.")
if config.bootstrap_sample_size <= 0:
raise ValueError("bootstrap_sample_size must be greater than 0.")
def _verify_data_source(
self, data_source: Union[DataSource, pd.DataFrame]
):
if isinstance(data_source, pd.DataFrame):
verify_data_source_columns(data_source)
elif not isinstance(data_source, DataSource):
raise TypeError(f"Invalid data_source type: {type(data_source)}")
def set_slippage_model(self, slippage_model: Optional[SlippageModel]):
"""Sets :class:`pybroker.slippage.SlippageModel`."""
self._slippage_model = slippage_model
def add_execution(
self,
fn: Optional[Callable[[ExecContext], None]],
symbols: Union[str, Iterable[str]],
models: Optional[Union[ModelSource, Iterable[ModelSource]]] = None,
indicators: Optional[Union[Indicator, Iterable[Indicator]]] = None,
):
r"""Adds an execution to backtest.
Args:
fn: :class:`Callable` invoked on every bar of data during the
backtest and passed an :class:`pybroker.context.ExecContext`
for each ticker symbol in ``symbols``.
symbols: Ticker symbols used to run ``fn``, where ``fn`` is called
separately for each symbol.
models: :class:`Iterable` of :class:`pybroker.model.ModelSource`\ s
to train/load for backtesting.
indicators: :class:`Iterable` of
:class:`pybroker.indicator.Indicator`\ s to compute for
backtesting.
"""
symbols = (
frozenset((symbols,))
if isinstance(symbols, str)
else frozenset(symbols)
)
if not symbols:
raise ValueError("symbols cannot be empty.")
for sym in symbols:
for exec in self._executions:
if sym in exec.symbols:
raise ValueError(
f"{sym} was already added to an execution."
)
if models is not None:
for model in (
(models,) if isinstance(models, ModelSource) else models
):
if not self._scope.has_model_source(model.name):
raise ValueError(
f"ModelSource {model.name!r} was not registered."
)
if model is not self._scope.get_model_source(model.name):
raise ValueError(
f"ModelSource {model.name!r} does not match "
"registered ModelSource."
)
model_names = (
(
frozenset((models.name,))
if isinstance(models, ModelSource)
else frozenset(model.name for model in models)
)
if models is not None
else frozenset()
)
if indicators is not None:
for ind in (
(indicators,)
if isinstance(indicators, Indicator)
else indicators
):
if not self._scope.has_indicator(ind.name):
raise ValueError(
f"Indicator {ind.name!r} was not registered."
)
if ind is not self._scope.get_indicator(ind.name):
raise ValueError(
f"Indicator {ind.name!r} does not match registered "
"Indicator."
)
ind_names = (
(
frozenset((indicators.name,))
if isinstance(indicators, Indicator)
else frozenset(ind.name for ind in indicators)
)
if indicators is not None
else frozenset()
)
self._execution_id += 1
self._executions.add(
Execution(
id=self._execution_id,
symbols=symbols,
fn=fn,
model_names=model_names,
indicator_names=ind_names,
)
)
def set_before_exec(
self, fn: Optional[Callable[[Mapping[str, ExecContext]], None]]
):
r""":class:`Callable[[Mapping[str, ExecContext]]` that runs before all
execution functions.
Args:
fn: :class:`Callable` that takes a :class:`Mapping` of all ticker
symbols to :class:`ExecContext`\ s.
"""
self._before_exec_fn = fn
def set_after_exec(
self, fn: Optional[Callable[[Mapping[str, ExecContext]], None]]
):
r""":class:`Callable[[Mapping[str, ExecContext]]` that runs after all
execution functions.
Args:
fn: :class:`Callable` that takes a :class:`Mapping` of all ticker
symbols to :class:`ExecContext`\ s.
"""
self._after_exec_fn = fn
def clear_executions(self):
"""Clears executions that were added with :meth:`.add_execution`."""
self._executions.clear()
def set_pos_size_handler(
self, fn: Optional[Callable[[PosSizeContext], None]]
):
r"""Sets a :class:`Callable` that determines position sizes to use for
buy and sell signals.
Args:
fn: :class:`Callable` invoked before placing orders for buy and
sell signals, and is passed a
:class:`pybroker.context.PosSizeContext`.
"""
self._pos_size_handler = fn
def backtest(
self,
start_date: Optional[Union[str, datetime]] = None,
end_date: Optional[Union[str, datetime]] = None,
timeframe: str = "",
between_time: Optional[tuple[str, str]] = None,
days: Optional[Union[str, Day, Iterable[Union[str, Day]]]] = None,
lookahead: int = 1,