backtest-engine 0.1.0__cp310-abi3-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- backtest_engine/__init__.py +73 -0
- backtest_engine/__main__.py +6 -0
- backtest_engine/_backtest_engine.pyd +0 -0
- backtest_engine/_backtest_engine.pyi +223 -0
- backtest_engine/cli.py +290 -0
- backtest_engine/detector.py +204 -0
- backtest_engine/py.typed +0 -0
- backtest_engine/report.py +28 -0
- backtest_engine/strategies.py +163 -0
- backtest_engine/walkforward.py +163 -0
- backtest_engine-0.1.0.dist-info/METADATA +448 -0
- backtest_engine-0.1.0.dist-info/RECORD +15 -0
- backtest_engine-0.1.0.dist-info/WHEEL +4 -0
- backtest_engine-0.1.0.dist-info/licenses/LICENSE +21 -0
- backtest_engine-0.1.0.dist-info/sboms/backtest-engine.cyclonedx.json +1179 -0
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""backtest-engine: event-driven backtesting with a look-ahead detector."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from ._backtest_engine import (
|
|
6
|
+
BacktestResult,
|
|
7
|
+
Bar,
|
|
8
|
+
Context,
|
|
9
|
+
DataAccess,
|
|
10
|
+
Decision,
|
|
11
|
+
EngineConfig,
|
|
12
|
+
EquityPoint,
|
|
13
|
+
FutureAccessError,
|
|
14
|
+
Metrics,
|
|
15
|
+
Order,
|
|
16
|
+
PointInTimeStore,
|
|
17
|
+
Trade,
|
|
18
|
+
run_backtest,
|
|
19
|
+
sha256_hex,
|
|
20
|
+
version,
|
|
21
|
+
)
|
|
22
|
+
from .detector import (
|
|
23
|
+
Divergence,
|
|
24
|
+
LookAheadError,
|
|
25
|
+
LookAheadReport,
|
|
26
|
+
check_lookahead,
|
|
27
|
+
run_checked,
|
|
28
|
+
)
|
|
29
|
+
from .report import write_report
|
|
30
|
+
from .strategies import (
|
|
31
|
+
STRATEGIES,
|
|
32
|
+
FullSampleZScore,
|
|
33
|
+
LookAheadTrap,
|
|
34
|
+
MeanReversion,
|
|
35
|
+
MovingAverage,
|
|
36
|
+
Strategy,
|
|
37
|
+
)
|
|
38
|
+
from .walkforward import Fold, WalkForwardResult, walk_forward
|
|
39
|
+
|
|
40
|
+
__version__ = version()
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"STRATEGIES",
|
|
44
|
+
"Bar",
|
|
45
|
+
"BacktestResult",
|
|
46
|
+
"Context",
|
|
47
|
+
"DataAccess",
|
|
48
|
+
"Decision",
|
|
49
|
+
"Divergence",
|
|
50
|
+
"EngineConfig",
|
|
51
|
+
"EquityPoint",
|
|
52
|
+
"Fold",
|
|
53
|
+
"FutureAccessError",
|
|
54
|
+
"FullSampleZScore",
|
|
55
|
+
"LookAheadError",
|
|
56
|
+
"LookAheadReport",
|
|
57
|
+
"LookAheadTrap",
|
|
58
|
+
"MeanReversion",
|
|
59
|
+
"Metrics",
|
|
60
|
+
"MovingAverage",
|
|
61
|
+
"Order",
|
|
62
|
+
"PointInTimeStore",
|
|
63
|
+
"Strategy",
|
|
64
|
+
"Trade",
|
|
65
|
+
"WalkForwardResult",
|
|
66
|
+
"__version__",
|
|
67
|
+
"check_lookahead",
|
|
68
|
+
"run_backtest",
|
|
69
|
+
"run_checked",
|
|
70
|
+
"sha256_hex",
|
|
71
|
+
"walk_forward",
|
|
72
|
+
"write_report",
|
|
73
|
+
]
|
|
Binary file
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""Type stubs for the Rust extension module."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Final
|
|
4
|
+
|
|
5
|
+
class FutureAccessError(RuntimeError): ...
|
|
6
|
+
|
|
7
|
+
class Bar:
|
|
8
|
+
symbol: str
|
|
9
|
+
ts: int
|
|
10
|
+
published_at: int
|
|
11
|
+
version: int
|
|
12
|
+
open: float
|
|
13
|
+
high: float
|
|
14
|
+
low: float
|
|
15
|
+
close: float
|
|
16
|
+
volume: float
|
|
17
|
+
|
|
18
|
+
@property
|
|
19
|
+
def datetime(self) -> str: ...
|
|
20
|
+
@property
|
|
21
|
+
def date(self) -> str: ...
|
|
22
|
+
@property
|
|
23
|
+
def published_datetime(self) -> str: ...
|
|
24
|
+
|
|
25
|
+
class Order:
|
|
26
|
+
def __init__(self, symbol: str, target_weight: float) -> None: ...
|
|
27
|
+
@property
|
|
28
|
+
def symbol(self) -> str: ...
|
|
29
|
+
@property
|
|
30
|
+
def target_weight(self) -> float: ...
|
|
31
|
+
|
|
32
|
+
class Trade:
|
|
33
|
+
ts: int
|
|
34
|
+
symbol: str
|
|
35
|
+
side: str
|
|
36
|
+
quantity: float
|
|
37
|
+
price: float
|
|
38
|
+
reference_price: float
|
|
39
|
+
notional: float
|
|
40
|
+
commission: float
|
|
41
|
+
spread_cost: float
|
|
42
|
+
slippage_cost: float
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def date(self) -> str: ...
|
|
46
|
+
@property
|
|
47
|
+
def total_cost(self) -> float: ...
|
|
48
|
+
|
|
49
|
+
class EquityPoint:
|
|
50
|
+
ts: int
|
|
51
|
+
equity: float
|
|
52
|
+
cash: float
|
|
53
|
+
position_value: float
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def date(self) -> str: ...
|
|
57
|
+
|
|
58
|
+
class Decision:
|
|
59
|
+
ts: int
|
|
60
|
+
symbol: str
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def date(self) -> str: ...
|
|
64
|
+
@property
|
|
65
|
+
def orders(self) -> list[Order]: ...
|
|
66
|
+
|
|
67
|
+
class DataAccess:
|
|
68
|
+
clock: int
|
|
69
|
+
symbol: str
|
|
70
|
+
requested_ts: int
|
|
71
|
+
effective_ts: int | None
|
|
72
|
+
returned_ts: int | None
|
|
73
|
+
future: bool
|
|
74
|
+
kind: str
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def clock_date(self) -> str: ...
|
|
78
|
+
@property
|
|
79
|
+
def requested_date(self) -> str: ...
|
|
80
|
+
@property
|
|
81
|
+
def returned_date(self) -> str | None: ...
|
|
82
|
+
|
|
83
|
+
class Metrics:
|
|
84
|
+
total_return: float
|
|
85
|
+
annualized_volatility: float
|
|
86
|
+
sharpe: float
|
|
87
|
+
max_drawdown: float
|
|
88
|
+
turnover: float
|
|
89
|
+
total_cost: float
|
|
90
|
+
commission_cost: float
|
|
91
|
+
spread_cost: float
|
|
92
|
+
slippage_cost: float
|
|
93
|
+
cost_bps: float
|
|
94
|
+
final_equity: float
|
|
95
|
+
initial_cash: float
|
|
96
|
+
n_trades: int
|
|
97
|
+
n_bars: int
|
|
98
|
+
avg_exposure: float
|
|
99
|
+
|
|
100
|
+
class EngineConfig:
|
|
101
|
+
def __init__(
|
|
102
|
+
self,
|
|
103
|
+
initial_cash: float = ...,
|
|
104
|
+
commission_bps: float = ...,
|
|
105
|
+
commission_fixed: float = ...,
|
|
106
|
+
spread_bps: float = ...,
|
|
107
|
+
slippage_bps_at_full_volume: float = ...,
|
|
108
|
+
periods_per_year: int = ...,
|
|
109
|
+
start_ts: int | None = ...,
|
|
110
|
+
end_ts: int | None = ...,
|
|
111
|
+
masked: bool = ...,
|
|
112
|
+
strict_future_access: bool = ...,
|
|
113
|
+
) -> None: ...
|
|
114
|
+
@property
|
|
115
|
+
def initial_cash(self) -> float: ...
|
|
116
|
+
@property
|
|
117
|
+
def commission_bps(self) -> float: ...
|
|
118
|
+
@property
|
|
119
|
+
def commission_fixed(self) -> float: ...
|
|
120
|
+
@property
|
|
121
|
+
def spread_bps(self) -> float: ...
|
|
122
|
+
@property
|
|
123
|
+
def slippage_bps_at_full_volume(self) -> float: ...
|
|
124
|
+
@property
|
|
125
|
+
def periods_per_year(self) -> int: ...
|
|
126
|
+
@property
|
|
127
|
+
def start_ts(self) -> int | None: ...
|
|
128
|
+
@property
|
|
129
|
+
def end_ts(self) -> int | None: ...
|
|
130
|
+
@property
|
|
131
|
+
def masked(self) -> bool: ...
|
|
132
|
+
@property
|
|
133
|
+
def strict_future_access(self) -> bool: ...
|
|
134
|
+
def variant(
|
|
135
|
+
self, masked: bool | None = ..., strict_future_access: bool | None = ...
|
|
136
|
+
) -> EngineConfig: ...
|
|
137
|
+
def with_window(self, start_ts: int | None, end_ts: int | None) -> EngineConfig: ...
|
|
138
|
+
def without_costs(self) -> EngineConfig: ...
|
|
139
|
+
|
|
140
|
+
class PointInTimeStore:
|
|
141
|
+
@staticmethod
|
|
142
|
+
def from_csv(path: str) -> PointInTimeStore: ...
|
|
143
|
+
@staticmethod
|
|
144
|
+
def from_csv_str(text: str) -> PointInTimeStore: ...
|
|
145
|
+
@property
|
|
146
|
+
def data_hash(self) -> str: ...
|
|
147
|
+
@property
|
|
148
|
+
def bar_count(self) -> int: ...
|
|
149
|
+
@property
|
|
150
|
+
def revision_count(self) -> int: ...
|
|
151
|
+
@property
|
|
152
|
+
def first_ts(self) -> int | None: ...
|
|
153
|
+
@property
|
|
154
|
+
def last_ts(self) -> int | None: ...
|
|
155
|
+
@property
|
|
156
|
+
def first_date(self) -> str | None: ...
|
|
157
|
+
@property
|
|
158
|
+
def last_date(self) -> str | None: ...
|
|
159
|
+
def __len__(self) -> int: ...
|
|
160
|
+
def symbols(self) -> list[str]: ...
|
|
161
|
+
def timestamps(self) -> list[int]: ...
|
|
162
|
+
def rows(self) -> list[Bar]: ...
|
|
163
|
+
def as_of(self, symbol: str, ts: int) -> Bar | None: ...
|
|
164
|
+
def history_before(self, symbol: str, as_of: int, limit: int) -> list[Bar]: ...
|
|
165
|
+
|
|
166
|
+
class Context:
|
|
167
|
+
@property
|
|
168
|
+
def now(self) -> int: ...
|
|
169
|
+
@property
|
|
170
|
+
def datetime(self) -> str: ...
|
|
171
|
+
@property
|
|
172
|
+
def date(self) -> str: ...
|
|
173
|
+
@property
|
|
174
|
+
def equity(self) -> float: ...
|
|
175
|
+
@property
|
|
176
|
+
def cash(self) -> float: ...
|
|
177
|
+
@property
|
|
178
|
+
def masked(self) -> bool: ...
|
|
179
|
+
@property
|
|
180
|
+
def strict_future_access(self) -> bool: ...
|
|
181
|
+
def position(self, symbol: str) -> float: ...
|
|
182
|
+
def positions(self) -> list[tuple[str, float]]: ...
|
|
183
|
+
def price(self, symbol: str) -> float | None: ...
|
|
184
|
+
def history(self, symbol: str, limit: int) -> list[Bar]: ...
|
|
185
|
+
def as_of(self, symbol: str, ts: int) -> Bar | None: ...
|
|
186
|
+
def as_of_iso(self, symbol: str, ts: str) -> Bar | None: ...
|
|
187
|
+
def research_series(self, symbol: str) -> list[Bar]: ...
|
|
188
|
+
def order(self, symbol: str, target_weight: float) -> Order: ...
|
|
189
|
+
|
|
190
|
+
class BacktestResult:
|
|
191
|
+
@property
|
|
192
|
+
def metrics(self) -> Metrics: ...
|
|
193
|
+
@property
|
|
194
|
+
def equity(self) -> list[EquityPoint]: ...
|
|
195
|
+
@property
|
|
196
|
+
def trades(self) -> list[Trade]: ...
|
|
197
|
+
@property
|
|
198
|
+
def decisions(self) -> list[Decision]: ...
|
|
199
|
+
@property
|
|
200
|
+
def data_accesses(self) -> list[DataAccess]: ...
|
|
201
|
+
@property
|
|
202
|
+
def unfilled_orders(self) -> list[Order]: ...
|
|
203
|
+
@property
|
|
204
|
+
def config(self) -> EngineConfig: ...
|
|
205
|
+
@property
|
|
206
|
+
def symbols(self) -> list[str]: ...
|
|
207
|
+
initial_cash: float
|
|
208
|
+
final_equity: float
|
|
209
|
+
data_hash: str
|
|
210
|
+
data_rows: int
|
|
211
|
+
data_revisions: int
|
|
212
|
+
data_start_ts: int | None
|
|
213
|
+
data_end_ts: int | None
|
|
214
|
+
bars_processed: int
|
|
215
|
+
def render_html(self, strategy_name: str, title: str, lookahead_verdict: str) -> str: ...
|
|
216
|
+
|
|
217
|
+
def run_backtest(
|
|
218
|
+
strategy: Any, store: PointInTimeStore, config: EngineConfig
|
|
219
|
+
) -> BacktestResult: ...
|
|
220
|
+
def sha256_hex(text: str) -> str: ...
|
|
221
|
+
def version() -> str: ...
|
|
222
|
+
|
|
223
|
+
__version__: Final[str]
|
backtest_engine/cli.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"""Command line interface.
|
|
2
|
+
|
|
3
|
+
python -m backtest_engine backtest --strategy moving_average --window 20
|
|
4
|
+
python -m backtest_engine check --strategy lookahead_trap --expect-detected
|
|
5
|
+
python -m backtest_engine walkforward --strategy moving_average --windows 5,10,20,50
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
from collections.abc import Callable, Sequence
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
|
|
14
|
+
from ._backtest_engine import (
|
|
15
|
+
BacktestResult,
|
|
16
|
+
EngineConfig,
|
|
17
|
+
PointInTimeStore,
|
|
18
|
+
run_backtest,
|
|
19
|
+
)
|
|
20
|
+
from .detector import check_lookahead
|
|
21
|
+
from .report import write_report
|
|
22
|
+
from .strategies import (
|
|
23
|
+
STRATEGIES,
|
|
24
|
+
FullSampleZScore,
|
|
25
|
+
LookAheadTrap,
|
|
26
|
+
MeanReversion,
|
|
27
|
+
MovingAverage,
|
|
28
|
+
Strategy,
|
|
29
|
+
)
|
|
30
|
+
from .walkforward import WalkForwardResult, walk_forward
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _factory(name: str, args: argparse.Namespace) -> Callable[[], Strategy]:
|
|
34
|
+
if name == "moving_average":
|
|
35
|
+
window = int(args.window)
|
|
36
|
+
return lambda: MovingAverage(window=window)
|
|
37
|
+
if name == "mean_reversion":
|
|
38
|
+
window = int(args.window)
|
|
39
|
+
entry_z = float(args.entry_z)
|
|
40
|
+
return lambda: MeanReversion(window=window, entry_z=entry_z)
|
|
41
|
+
if name == "lookahead_trap":
|
|
42
|
+
horizon = int(args.horizon_days) * 86_400
|
|
43
|
+
return lambda: LookAheadTrap(horizon_seconds=horizon)
|
|
44
|
+
if name == "full_sample_zscore":
|
|
45
|
+
return lambda: FullSampleZScore()
|
|
46
|
+
raise ValueError(f"unknown strategy {name!r}")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _config(args: argparse.Namespace) -> EngineConfig:
|
|
50
|
+
config = EngineConfig(
|
|
51
|
+
initial_cash=float(args.initial_cash),
|
|
52
|
+
commission_bps=float(args.commission_bps),
|
|
53
|
+
spread_bps=float(args.spread_bps),
|
|
54
|
+
slippage_bps_at_full_volume=float(args.slippage_bps),
|
|
55
|
+
periods_per_year=int(args.periods_per_year),
|
|
56
|
+
)
|
|
57
|
+
if bool(args.no_costs):
|
|
58
|
+
config = config.without_costs()
|
|
59
|
+
return config
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _strategy_label(name: str, args: argparse.Namespace) -> str:
|
|
63
|
+
if name == "moving_average":
|
|
64
|
+
return f"Moving average (window={int(args.window)})"
|
|
65
|
+
if name == "mean_reversion":
|
|
66
|
+
return f"Mean reversion (window={int(args.window)}, entry_z={float(args.entry_z):g})"
|
|
67
|
+
if name == "lookahead_trap":
|
|
68
|
+
return f"Look-ahead trap (horizon={int(args.horizon_days)}d)"
|
|
69
|
+
if name == "full_sample_zscore":
|
|
70
|
+
return "Full-sample z-score (subtle look-ahead)"
|
|
71
|
+
return name
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _print_result(result: BacktestResult) -> None:
|
|
75
|
+
metrics = result.metrics
|
|
76
|
+
print(f" total return {metrics.total_return * 100:.4f}%")
|
|
77
|
+
print(f" annualized volatility {metrics.annualized_volatility * 100:.4f}%")
|
|
78
|
+
print(f" Sharpe {metrics.sharpe:.4f}")
|
|
79
|
+
print(f" max drawdown {metrics.max_drawdown * 100:.4f}%")
|
|
80
|
+
print(f" turnover {metrics.turnover:.4f}x")
|
|
81
|
+
print(f" total cost {metrics.total_cost:.2f} ({metrics.cost_bps:.2f} bps)")
|
|
82
|
+
print(f" fills {metrics.n_trades}")
|
|
83
|
+
print(f" final equity {metrics.final_equity:.2f}")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _add_common(parser: argparse.ArgumentParser) -> None:
|
|
87
|
+
parser.add_argument("--data", default="data/sample.csv", help="point-in-time CSV")
|
|
88
|
+
parser.add_argument(
|
|
89
|
+
"--strategy",
|
|
90
|
+
choices=sorted(STRATEGIES),
|
|
91
|
+
default="moving_average",
|
|
92
|
+
help="strategy to run",
|
|
93
|
+
)
|
|
94
|
+
parser.add_argument("--window", type=int, default=20)
|
|
95
|
+
parser.add_argument("--entry-z", type=float, default=1.0)
|
|
96
|
+
parser.add_argument("--horizon-days", type=int, default=1)
|
|
97
|
+
parser.add_argument("--initial-cash", type=float, default=1_000_000.0)
|
|
98
|
+
parser.add_argument("--commission-bps", type=float, default=1.0)
|
|
99
|
+
parser.add_argument("--spread-bps", type=float, default=2.0)
|
|
100
|
+
parser.add_argument("--slippage-bps", type=float, default=100.0)
|
|
101
|
+
parser.add_argument("--periods-per-year", type=int, default=252)
|
|
102
|
+
parser.add_argument(
|
|
103
|
+
"--no-costs",
|
|
104
|
+
action="store_true",
|
|
105
|
+
help="zero commission, spread and slippage",
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _add_backtest(parser: argparse.ArgumentParser) -> None:
|
|
110
|
+
_add_common(parser)
|
|
111
|
+
parser.add_argument("--report", default="reports/example.html")
|
|
112
|
+
parser.add_argument("--title", default=None)
|
|
113
|
+
parser.add_argument(
|
|
114
|
+
"--no-check",
|
|
115
|
+
action="store_true",
|
|
116
|
+
help="skip the masked look-ahead replay (debug only)",
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _add_check(parser: argparse.ArgumentParser) -> None:
|
|
121
|
+
_add_common(parser)
|
|
122
|
+
parser.add_argument(
|
|
123
|
+
"--expect-detected",
|
|
124
|
+
action="store_true",
|
|
125
|
+
help="exit 0 only if the detector rejects the strategy",
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _add_walkforward(parser: argparse.ArgumentParser) -> None:
|
|
130
|
+
_add_common(parser)
|
|
131
|
+
parser.add_argument("--train", type=int, default=252)
|
|
132
|
+
parser.add_argument("--test", type=int, default=63)
|
|
133
|
+
parser.add_argument("--step", type=int, default=None)
|
|
134
|
+
parser.add_argument("--windows", default="5,10,20,50")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _cmd_backtest(args: argparse.Namespace) -> int:
|
|
138
|
+
store = PointInTimeStore.from_csv(str(args.data))
|
|
139
|
+
config = _config(args)
|
|
140
|
+
name = str(args.strategy)
|
|
141
|
+
factory = _factory(name, args)
|
|
142
|
+
label = _strategy_label(name, args)
|
|
143
|
+
|
|
144
|
+
if bool(args.no_check):
|
|
145
|
+
verdict = "NOT RUN - the report was generated without a masked replay"
|
|
146
|
+
else:
|
|
147
|
+
check = check_lookahead(factory, store, config, strategy_name=label)
|
|
148
|
+
if not check.passed:
|
|
149
|
+
print(check.summary)
|
|
150
|
+
print("refusing to write a performance report for a rejected strategy")
|
|
151
|
+
return 1
|
|
152
|
+
verdict = "PASSED - masked replay reproduced every decision; 0 future reads"
|
|
153
|
+
|
|
154
|
+
result = run_backtest(factory(), store, config)
|
|
155
|
+
title = str(args.title) if args.title is not None else f"Backtest report - {label}"
|
|
156
|
+
digest = write_report(
|
|
157
|
+
result,
|
|
158
|
+
str(args.report),
|
|
159
|
+
strategy_name=label,
|
|
160
|
+
title=title,
|
|
161
|
+
lookahead_verdict=verdict,
|
|
162
|
+
)
|
|
163
|
+
print(f"strategy: {label}")
|
|
164
|
+
_print_result(result)
|
|
165
|
+
print(f"report: {args.report}")
|
|
166
|
+
print(f"sha256: {digest}")
|
|
167
|
+
return 0
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _cmd_check(args: argparse.Namespace) -> int:
|
|
171
|
+
store = PointInTimeStore.from_csv(str(args.data))
|
|
172
|
+
config = _config(args)
|
|
173
|
+
name = str(args.strategy)
|
|
174
|
+
factory = _factory(name, args)
|
|
175
|
+
report = check_lookahead(
|
|
176
|
+
factory,
|
|
177
|
+
store,
|
|
178
|
+
config,
|
|
179
|
+
strategy_name=_strategy_label(name, args),
|
|
180
|
+
)
|
|
181
|
+
print(report.summary)
|
|
182
|
+
detected = not report.passed
|
|
183
|
+
if bool(args.expect_detected):
|
|
184
|
+
if detected:
|
|
185
|
+
print("expected detection: CONFIRMED")
|
|
186
|
+
return 0
|
|
187
|
+
print("expected detection: FAILED - the strategy was not flagged")
|
|
188
|
+
return 1
|
|
189
|
+
return 1 if detected else 0
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _date(ts: int) -> str:
|
|
193
|
+
return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%d")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _print_walkforward(result: WalkForwardResult) -> None:
|
|
197
|
+
print(
|
|
198
|
+
"fold train_start train_end test_start test_end best params"
|
|
199
|
+
" test return test Sharpe"
|
|
200
|
+
)
|
|
201
|
+
for fold in result.folds:
|
|
202
|
+
params = ", ".join(f"{key}={value}" for key, value in fold.params)
|
|
203
|
+
print(
|
|
204
|
+
f"{fold.index:>4} {_date(fold.train_start_ts)} {_date(fold.train_end_ts)} "
|
|
205
|
+
f"{_date(fold.test_start_ts)} {_date(fold.test_end_ts)} {params:<42} "
|
|
206
|
+
f"{fold.test.metrics.total_return * 100:>10.4f}% {fold.test.metrics.sharpe:>11.4f}"
|
|
207
|
+
)
|
|
208
|
+
print()
|
|
209
|
+
print("aggregate out-of-sample:")
|
|
210
|
+
print(f" folds {len(result.folds)}")
|
|
211
|
+
print(f" total return {result.total_return * 100:.4f}%")
|
|
212
|
+
print(f" annualized volatility {result.annualized_volatility * 100:.4f}%")
|
|
213
|
+
print(f" Sharpe {result.sharpe:.4f}")
|
|
214
|
+
print(f" max drawdown {result.max_drawdown * 100:.4f}%")
|
|
215
|
+
print(f" total cost {result.total_cost:.2f}")
|
|
216
|
+
print(f" fills {result.n_trades}")
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _cmd_walkforward(args: argparse.Namespace) -> int:
|
|
220
|
+
store = PointInTimeStore.from_csv(str(args.data))
|
|
221
|
+
config = _config(args)
|
|
222
|
+
name = str(args.strategy)
|
|
223
|
+
if name == "lookahead_trap":
|
|
224
|
+
print("walk-forward is not meaningful for the deliberate look-ahead trap")
|
|
225
|
+
return 2
|
|
226
|
+
if name == "full_sample_zscore":
|
|
227
|
+
print("walk-forward is not meaningful for the full-sample look-ahead strategy")
|
|
228
|
+
return 2
|
|
229
|
+
windows = [int(part) for part in str(args.windows).split(",") if part.strip()]
|
|
230
|
+
if not windows:
|
|
231
|
+
print("--windows must contain at least one integer")
|
|
232
|
+
return 2
|
|
233
|
+
if name == "moving_average":
|
|
234
|
+
grid: list[dict[str, object]] = [{"window": window} for window in windows]
|
|
235
|
+
|
|
236
|
+
def ma_factory(**params: object) -> Strategy:
|
|
237
|
+
return MovingAverage(window=int(str(params["window"])))
|
|
238
|
+
|
|
239
|
+
factory: Callable[..., Strategy] = ma_factory
|
|
240
|
+
else:
|
|
241
|
+
entry_z = float(args.entry_z)
|
|
242
|
+
grid = [{"window": window, "entry_z": entry_z} for window in windows]
|
|
243
|
+
|
|
244
|
+
def mr_factory(**params: object) -> Strategy:
|
|
245
|
+
return MeanReversion(
|
|
246
|
+
window=int(str(params["window"])),
|
|
247
|
+
entry_z=float(str(params["entry_z"])),
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
factory = mr_factory
|
|
251
|
+
|
|
252
|
+
result = walk_forward(
|
|
253
|
+
factory,
|
|
254
|
+
store,
|
|
255
|
+
config,
|
|
256
|
+
train_bars=int(args.train),
|
|
257
|
+
test_bars=int(args.test),
|
|
258
|
+
step_bars=int(args.step) if args.step is not None else None,
|
|
259
|
+
grid=grid,
|
|
260
|
+
)
|
|
261
|
+
_print_walkforward(result)
|
|
262
|
+
return 0
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def make_parser() -> argparse.ArgumentParser:
|
|
266
|
+
parser = argparse.ArgumentParser(
|
|
267
|
+
prog="backtest-engine",
|
|
268
|
+
description="Event-driven backtester with a look-ahead detector.",
|
|
269
|
+
)
|
|
270
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
271
|
+
_add_backtest(subparsers.add_parser("backtest", help="run a backtest and write HTML"))
|
|
272
|
+
_add_check(subparsers.add_parser("check", help="run only the look-ahead detector"))
|
|
273
|
+
_add_walkforward(
|
|
274
|
+
subparsers.add_parser("walkforward", help="run non-overlapping train/test folds")
|
|
275
|
+
)
|
|
276
|
+
return parser
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
280
|
+
parser = make_parser()
|
|
281
|
+
args = parser.parse_args(argv)
|
|
282
|
+
command = str(args.command)
|
|
283
|
+
if command == "backtest":
|
|
284
|
+
return _cmd_backtest(args)
|
|
285
|
+
if command == "check":
|
|
286
|
+
return _cmd_check(args)
|
|
287
|
+
if command == "walkforward":
|
|
288
|
+
return _cmd_walkforward(args)
|
|
289
|
+
parser.error(f"unknown command {command!r}")
|
|
290
|
+
return 2
|