auditbacktest 1.0.0__py3-none-any.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.
- auditbacktest/__init__.py +43 -0
- auditbacktest/cli.py +99 -0
- auditbacktest/costs.py +143 -0
- auditbacktest/leakage.py +300 -0
- auditbacktest/overfitting.py +307 -0
- auditbacktest/py.typed +0 -0
- auditbacktest/reliability.py +199 -0
- auditbacktest/suite.py +119 -0
- auditbacktest/types.py +151 -0
- auditbacktest-1.0.0.dist-info/METADATA +201 -0
- auditbacktest-1.0.0.dist-info/RECORD +14 -0
- auditbacktest-1.0.0.dist-info/WHEEL +4 -0
- auditbacktest-1.0.0.dist-info/entry_points.txt +2 -0
- auditbacktest-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Nine-check leakage, overfitting, decay, and cost-stress auditor for trading backtests."""
|
|
2
|
+
|
|
3
|
+
from auditbacktest.costs import cost_stress_ladder, reimplementation_parity
|
|
4
|
+
from auditbacktest.leakage import (
|
|
5
|
+
execution_delay_test,
|
|
6
|
+
future_mutation_test,
|
|
7
|
+
static_leakage_scan,
|
|
8
|
+
)
|
|
9
|
+
from auditbacktest.overfitting import (
|
|
10
|
+
cscv_pbo,
|
|
11
|
+
deflated_sharpe_ratio,
|
|
12
|
+
probabilistic_sharpe_ratio,
|
|
13
|
+
sharpe_stats,
|
|
14
|
+
)
|
|
15
|
+
from auditbacktest.reliability import (
|
|
16
|
+
audit_self_check,
|
|
17
|
+
cusum_decay_test,
|
|
18
|
+
volatility_break_test,
|
|
19
|
+
)
|
|
20
|
+
from auditbacktest.suite import run_audit
|
|
21
|
+
from auditbacktest.types import AuditReport, CheckResult, Status
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"AuditReport",
|
|
25
|
+
"CheckResult",
|
|
26
|
+
"Status",
|
|
27
|
+
"__version__",
|
|
28
|
+
"audit_self_check",
|
|
29
|
+
"cost_stress_ladder",
|
|
30
|
+
"cscv_pbo",
|
|
31
|
+
"cusum_decay_test",
|
|
32
|
+
"deflated_sharpe_ratio",
|
|
33
|
+
"execution_delay_test",
|
|
34
|
+
"future_mutation_test",
|
|
35
|
+
"probabilistic_sharpe_ratio",
|
|
36
|
+
"reimplementation_parity",
|
|
37
|
+
"run_audit",
|
|
38
|
+
"sharpe_stats",
|
|
39
|
+
"static_leakage_scan",
|
|
40
|
+
"volatility_break_test",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
__version__ = "1.0.0"
|
auditbacktest/cli.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Command-line interface for auditing backtest return files and strategy scripts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import polars as pl
|
|
10
|
+
|
|
11
|
+
from auditbacktest.leakage import static_leakage_scan
|
|
12
|
+
from auditbacktest.suite import run_audit
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _read_table(path: Path) -> pl.DataFrame:
|
|
16
|
+
suffix = path.suffix.lower()
|
|
17
|
+
if suffix == ".csv":
|
|
18
|
+
return pl.read_csv(path)
|
|
19
|
+
if suffix == ".parquet":
|
|
20
|
+
return pl.read_parquet(path)
|
|
21
|
+
raise ValueError(f"unsupported file format {suffix!r}; expected .csv or .parquet")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
25
|
+
parser = argparse.ArgumentParser(
|
|
26
|
+
prog="auditbacktest",
|
|
27
|
+
description="Audit backtest return streams and strategy source code.",
|
|
28
|
+
)
|
|
29
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
30
|
+
|
|
31
|
+
run_p = sub.add_parser("run", help="Run statistical, decay, and cost checks on a CSV/Parquet.")
|
|
32
|
+
run_p.add_argument("path", type=Path, help="Input .csv or .parquet file.")
|
|
33
|
+
run_p.add_argument("--ret-col", default="ret", help="Net return column name (default: ret).")
|
|
34
|
+
run_p.add_argument("--gross-col", default=None, help="Optional gross return column.")
|
|
35
|
+
run_p.add_argument("--cost-col", default=None, help="Optional non-negative cost column.")
|
|
36
|
+
run_p.add_argument("--ref-col", default=None, help="Optional reference return column.")
|
|
37
|
+
run_p.add_argument("--source", type=Path, default=None, help="Optional strategy .py to scan.")
|
|
38
|
+
run_p.add_argument("--n-trials", type=int, default=1, help="Number of strategy variants tried.")
|
|
39
|
+
run_p.add_argument("--periods", type=int, default=252, help="Periods per year (default: 252).")
|
|
40
|
+
run_p.add_argument("--expected-sr", type=float, default=0.0, help="Expected annualized SR.")
|
|
41
|
+
run_p.add_argument("--title", default="auditbacktest", help="Report title.")
|
|
42
|
+
run_p.add_argument("--strict", action="store_true", help="Fail if any check is SKIP.")
|
|
43
|
+
run_p.add_argument("--html", type=Path, default=None, help="Write dark-theme HTML tearsheet.")
|
|
44
|
+
run_p.add_argument("--json", type=Path, default=None, help="Write JSON audit report.")
|
|
45
|
+
|
|
46
|
+
scan_p = sub.add_parser("scan", help="AST scan a Python file for lookahead patterns.")
|
|
47
|
+
scan_p.add_argument("path", type=Path, help="Python file to scan.")
|
|
48
|
+
|
|
49
|
+
args = parser.parse_args(argv)
|
|
50
|
+
|
|
51
|
+
if args.command == "scan":
|
|
52
|
+
res = static_leakage_scan(args.path)
|
|
53
|
+
print(f"{res.status}: {res.summary}")
|
|
54
|
+
for hit in res.details["findings"]:
|
|
55
|
+
print(f" line {hit['line']}: [{hit['rule']}] {hit['detail']}")
|
|
56
|
+
return 0 if res.status == "PASS" else 1
|
|
57
|
+
|
|
58
|
+
df = _read_table(args.path)
|
|
59
|
+
if args.ret_col not in df.columns:
|
|
60
|
+
raise ValueError(f"input table is missing return column {args.ret_col!r}")
|
|
61
|
+
returns = df[args.ret_col].cast(pl.Float64).to_numpy()
|
|
62
|
+
|
|
63
|
+
gross = None
|
|
64
|
+
costs = None
|
|
65
|
+
if args.cost_col is not None:
|
|
66
|
+
if args.cost_col not in df.columns:
|
|
67
|
+
raise ValueError(f"input table is missing cost column {args.cost_col!r}")
|
|
68
|
+
costs = df[args.cost_col].cast(pl.Float64).to_numpy()
|
|
69
|
+
if args.gross_col is not None:
|
|
70
|
+
if args.gross_col not in df.columns:
|
|
71
|
+
raise ValueError(f"input table is missing gross column {args.gross_col!r}")
|
|
72
|
+
gross = df[args.gross_col].cast(pl.Float64).to_numpy()
|
|
73
|
+
else:
|
|
74
|
+
gross = returns + costs
|
|
75
|
+
|
|
76
|
+
ref = None
|
|
77
|
+
if args.ref_col is not None:
|
|
78
|
+
if args.ref_col not in df.columns:
|
|
79
|
+
raise ValueError(f"input table is missing reference column {args.ref_col!r}")
|
|
80
|
+
ref = df[args.ref_col].cast(pl.Float64).to_numpy()
|
|
81
|
+
|
|
82
|
+
report = run_audit(
|
|
83
|
+
returns,
|
|
84
|
+
title=args.title,
|
|
85
|
+
n_trials=args.n_trials,
|
|
86
|
+
periods_per_year=args.periods,
|
|
87
|
+
expected_sr=args.expected_sr,
|
|
88
|
+
strict=args.strict,
|
|
89
|
+
source_code=args.source,
|
|
90
|
+
gross_returns=gross,
|
|
91
|
+
trade_costs=costs,
|
|
92
|
+
reference_returns=ref,
|
|
93
|
+
)
|
|
94
|
+
print(report.to_markdown())
|
|
95
|
+
if args.html is not None:
|
|
96
|
+
args.html.write_text(report.to_html(), encoding="utf-8")
|
|
97
|
+
if args.json is not None:
|
|
98
|
+
args.json.write_text(report.to_json(), encoding="utf-8")
|
|
99
|
+
return 0 if report.passed else 1
|
auditbacktest/costs.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Family 4 — Cost realism stress ladder and reimplementation parity."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from numpy.typing import ArrayLike, NDArray
|
|
10
|
+
|
|
11
|
+
from auditbacktest.types import CheckResult, Status
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _perf_summary(net: NDArray[np.float64], periods_per_year: int) -> dict[str, float]:
|
|
15
|
+
mean = float(np.mean(net))
|
|
16
|
+
std = float(np.std(net, ddof=1))
|
|
17
|
+
sharpe = (mean / std) * math.sqrt(periods_per_year) if std > 0.0 else 0.0
|
|
18
|
+
|
|
19
|
+
downside = net[net < 0.0]
|
|
20
|
+
down_std = float(np.sqrt(np.mean(downside * downside))) if downside.size else 0.0
|
|
21
|
+
sortino = (mean / down_std) * math.sqrt(periods_per_year) if down_std > 0.0 else 0.0
|
|
22
|
+
|
|
23
|
+
equity = np.cumprod(1.0 + net)
|
|
24
|
+
peak = np.maximum.accumulate(equity)
|
|
25
|
+
dd = equity / peak - 1.0
|
|
26
|
+
max_dd = float(np.min(dd))
|
|
27
|
+
|
|
28
|
+
years = net.size / float(periods_per_year)
|
|
29
|
+
final_eq = float(equity[-1])
|
|
30
|
+
cagr = (final_eq ** (1.0 / years) - 1.0) if (final_eq > 0.0 and years > 0.0) else -1.0
|
|
31
|
+
calmar = cagr / abs(max_dd) if max_dd < 0.0 else 0.0
|
|
32
|
+
|
|
33
|
+
gains = float(np.sum(net[net > 0.0]))
|
|
34
|
+
losses = float(np.abs(np.sum(net[net < 0.0])))
|
|
35
|
+
pf = gains / losses if losses > 0.0 else float("inf")
|
|
36
|
+
return {
|
|
37
|
+
"sharpe": sharpe,
|
|
38
|
+
"sortino": sortino,
|
|
39
|
+
"cagr": cagr,
|
|
40
|
+
"max_dd": max_dd,
|
|
41
|
+
"calmar": calmar,
|
|
42
|
+
"profit_factor": pf,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def cost_stress_ladder(
|
|
47
|
+
gross_returns: ArrayLike,
|
|
48
|
+
trade_costs: ArrayLike,
|
|
49
|
+
*,
|
|
50
|
+
multipliers: Sequence[float] = (0.0, 1.0, 1.5, 2.0, 3.0),
|
|
51
|
+
periods_per_year: int = 252,
|
|
52
|
+
min_2x_sharpe: float = 0.5,
|
|
53
|
+
) -> CheckResult:
|
|
54
|
+
"""Evaluate net performance across cost multipliers and solve breakeven drag.
|
|
55
|
+
|
|
56
|
+
``trade_costs`` must be non-negative per-period cost drag in the same return
|
|
57
|
+
units as ``gross_returns`` (so ``net = gross_returns - m * trade_costs``).
|
|
58
|
+
"""
|
|
59
|
+
gross = np.asarray(gross_returns, dtype=np.float64)
|
|
60
|
+
costs = np.asarray(trade_costs, dtype=np.float64)
|
|
61
|
+
if gross.ndim != 1 or costs.ndim != 1 or gross.size != costs.size or gross.size < 4:
|
|
62
|
+
raise ValueError("gross_returns and trade_costs must be 1-D arrays of equal length >= 4")
|
|
63
|
+
if not (np.all(np.isfinite(gross)) and np.all(np.isfinite(costs))):
|
|
64
|
+
raise ValueError("gross_returns and trade_costs must be finite")
|
|
65
|
+
if np.any(costs < 0.0):
|
|
66
|
+
raise ValueError("trade_costs must be non-negative")
|
|
67
|
+
if not multipliers or any(m < 0.0 for m in multipliers):
|
|
68
|
+
raise ValueError("multipliers must be a non-empty sequence of non-negative numbers")
|
|
69
|
+
|
|
70
|
+
ladder: dict[str, dict[str, float]] = {}
|
|
71
|
+
for m in multipliers:
|
|
72
|
+
ladder[f"{m:.2g}x"] = _perf_summary(gross - float(m) * costs, periods_per_year)
|
|
73
|
+
|
|
74
|
+
mean_gross = float(np.mean(gross))
|
|
75
|
+
mean_cost = float(np.mean(costs))
|
|
76
|
+
if mean_cost > 0.0:
|
|
77
|
+
breakeven = mean_gross / mean_cost
|
|
78
|
+
else:
|
|
79
|
+
breakeven = float("inf") if mean_gross > 0.0 else 0.0
|
|
80
|
+
|
|
81
|
+
stress_2x = _perf_summary(gross - 2.0 * costs, periods_per_year)["sharpe"]
|
|
82
|
+
status: Status
|
|
83
|
+
if stress_2x >= min_2x_sharpe:
|
|
84
|
+
status = "PASS"
|
|
85
|
+
elif stress_2x > 0.0:
|
|
86
|
+
status = "WARN"
|
|
87
|
+
else:
|
|
88
|
+
status = "FAIL"
|
|
89
|
+
|
|
90
|
+
return CheckResult(
|
|
91
|
+
name="cost_stress_ladder",
|
|
92
|
+
family="costs",
|
|
93
|
+
status=status,
|
|
94
|
+
metric=stress_2x,
|
|
95
|
+
threshold=min_2x_sharpe,
|
|
96
|
+
summary=(
|
|
97
|
+
f"2x-cost Sharpe={stress_2x:.2f} (breakeven={breakeven:.2f}x, "
|
|
98
|
+
f"1x={_perf_summary(gross - costs, periods_per_year)['sharpe']:.2f})"
|
|
99
|
+
),
|
|
100
|
+
details={
|
|
101
|
+
"sharpe_2x": stress_2x,
|
|
102
|
+
"breakeven_multiplier": breakeven,
|
|
103
|
+
"ladder": ladder,
|
|
104
|
+
},
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def reimplementation_parity(
|
|
109
|
+
primary: ArrayLike,
|
|
110
|
+
reference: ArrayLike,
|
|
111
|
+
*,
|
|
112
|
+
atol: float = 1e-10,
|
|
113
|
+
periods_per_year: int = 252,
|
|
114
|
+
) -> CheckResult:
|
|
115
|
+
"""Verify two independent return implementations agree within ``atol``."""
|
|
116
|
+
a = np.asarray(primary, dtype=np.float64)
|
|
117
|
+
b = np.asarray(reference, dtype=np.float64)
|
|
118
|
+
if a.ndim != 1 or b.ndim != 1 or a.size != b.size or a.size < 2:
|
|
119
|
+
raise ValueError("primary and reference must be 1-D arrays of equal length >= 2")
|
|
120
|
+
if not (np.all(np.isfinite(a)) and np.all(np.isfinite(b))):
|
|
121
|
+
raise ValueError("primary and reference must be finite")
|
|
122
|
+
if atol < 0.0:
|
|
123
|
+
raise ValueError(f"atol must be non-negative, got {atol}")
|
|
124
|
+
|
|
125
|
+
max_diff = float(np.max(np.abs(a - b)))
|
|
126
|
+
sr_a = _perf_summary(a, periods_per_year)["sharpe"]
|
|
127
|
+
sr_b = _perf_summary(b, periods_per_year)["sharpe"]
|
|
128
|
+
sr_gap = abs(sr_a - sr_b)
|
|
129
|
+
passed = max_diff <= atol
|
|
130
|
+
|
|
131
|
+
return CheckResult(
|
|
132
|
+
name="reimplementation_parity",
|
|
133
|
+
family="costs",
|
|
134
|
+
status="PASS" if passed else "FAIL",
|
|
135
|
+
metric=max_diff,
|
|
136
|
+
threshold=atol,
|
|
137
|
+
summary=(
|
|
138
|
+
f"max diff {max_diff:.3e} <= {atol:.1e} (Sharpe gap {sr_gap:.4f})"
|
|
139
|
+
if passed
|
|
140
|
+
else f"PARITY MISMATCH: max diff {max_diff:.3e} > {atol:.1e} (Sharpe gap {sr_gap:.4f})"
|
|
141
|
+
),
|
|
142
|
+
details={"max_abs_diff": max_diff, "sharpe_gap": sr_gap},
|
|
143
|
+
)
|
auditbacktest/leakage.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"""Family 1 — Data leakage detection: future-bar mutation, delay test, and AST scan."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import math
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import polars as pl
|
|
13
|
+
from numpy.typing import ArrayLike, NDArray
|
|
14
|
+
|
|
15
|
+
from auditbacktest.types import CheckResult, Status
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _to_numeric_matrix(output: Any) -> NDArray[np.float64]:
|
|
19
|
+
"""Extract numeric values from an ndarray, Polars Series, or Polars DataFrame."""
|
|
20
|
+
if isinstance(output, np.ndarray):
|
|
21
|
+
arr = np.asarray(output, dtype=np.float64)
|
|
22
|
+
return arr.reshape(arr.shape[0], -1) if arr.ndim > 1 else arr.reshape(-1, 1)
|
|
23
|
+
if isinstance(output, pl.Series):
|
|
24
|
+
return output.cast(pl.Float64).to_numpy().reshape(-1, 1)
|
|
25
|
+
if isinstance(output, pl.DataFrame):
|
|
26
|
+
num_cols = [c for c, dt in output.schema.items() if dt.is_numeric()]
|
|
27
|
+
if not num_cols:
|
|
28
|
+
raise ValueError("DataFrame output has no numeric columns to compare")
|
|
29
|
+
return output.select(num_cols).to_numpy().astype(np.float64, copy=False)
|
|
30
|
+
raise TypeError(
|
|
31
|
+
f"fn must return np.ndarray, pl.Series, or pl.DataFrame, got {type(output).__name__}"
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _mutate_future(data: pl.DataFrame | NDArray[np.float64], cutoff: int, mode: str) -> Any:
|
|
36
|
+
"""Perturb rows strictly after ``cutoff`` while leaving rows ``<= cutoff`` untouched."""
|
|
37
|
+
if isinstance(data, pl.DataFrame):
|
|
38
|
+
head = data.slice(0, cutoff + 1)
|
|
39
|
+
tail = data.slice(cutoff + 1)
|
|
40
|
+
num_cols = [c for c, dt in tail.schema.items() if dt.is_numeric()]
|
|
41
|
+
if mode == "scale_up":
|
|
42
|
+
mut = tail.with_columns(
|
|
43
|
+
[(pl.col(c).cast(pl.Float64) * 1.25).alias(c) for c in num_cols]
|
|
44
|
+
)
|
|
45
|
+
elif mode == "scale_down":
|
|
46
|
+
mut = tail.with_columns(
|
|
47
|
+
[(pl.col(c).cast(pl.Float64) * 0.80).alias(c) for c in num_cols]
|
|
48
|
+
)
|
|
49
|
+
else:
|
|
50
|
+
mut = tail.reverse().with_columns(
|
|
51
|
+
[(-2.5 * pl.col(c).cast(pl.Float64) - 17.0).alias(c) for c in num_cols]
|
|
52
|
+
)
|
|
53
|
+
return pl.concat([head, mut.cast(head.schema)])
|
|
54
|
+
|
|
55
|
+
arr = np.asarray(data, dtype=np.float64).copy()
|
|
56
|
+
if mode == "scale_up":
|
|
57
|
+
arr[cutoff + 1 :] *= 1.25
|
|
58
|
+
elif mode == "scale_down":
|
|
59
|
+
arr[cutoff + 1 :] *= 0.80
|
|
60
|
+
else:
|
|
61
|
+
arr[cutoff + 1 :] = -2.5 * arr[cutoff + 1 :][::-1] - 17.0
|
|
62
|
+
return arr
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _max_prefix_diff(base: NDArray[np.float64], alt: NDArray[np.float64], cutoff: int) -> float:
|
|
66
|
+
a = base[: cutoff + 1]
|
|
67
|
+
b = alt[: cutoff + 1]
|
|
68
|
+
if a.shape != b.shape:
|
|
69
|
+
return float("inf")
|
|
70
|
+
nan_mismatch = np.isnan(a) != np.isnan(b)
|
|
71
|
+
if np.any(nan_mismatch):
|
|
72
|
+
return float("inf")
|
|
73
|
+
valid = ~np.isnan(a)
|
|
74
|
+
if not np.any(valid):
|
|
75
|
+
return 0.0
|
|
76
|
+
return float(np.max(np.abs(a[valid] - b[valid])))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def future_mutation_test(
|
|
80
|
+
fn: Callable[[Any], Any],
|
|
81
|
+
data: pl.DataFrame | NDArray[np.float64],
|
|
82
|
+
cutoff: int,
|
|
83
|
+
*,
|
|
84
|
+
atol: float = 1e-12,
|
|
85
|
+
) -> CheckResult:
|
|
86
|
+
"""Prove mutating rows strictly after ``cutoff`` leaves outputs ``<= cutoff`` unchanged.
|
|
87
|
+
|
|
88
|
+
Runs ``fn`` on the original dataset and on three perturbed copies (``+25%``,
|
|
89
|
+
``-20%``, and a reversed shock) applied strictly to indices ``> cutoff``.
|
|
90
|
+
Any change above ``atol`` at or before ``cutoff`` proves lookahead bias.
|
|
91
|
+
"""
|
|
92
|
+
n = data.height if isinstance(data, pl.DataFrame) else int(np.asarray(data).shape[0])
|
|
93
|
+
if cutoff < 0 or cutoff >= n - 1:
|
|
94
|
+
raise ValueError(f"cutoff must satisfy 0 <= cutoff < n - 1 (n={n}), got {cutoff}")
|
|
95
|
+
if atol < 0:
|
|
96
|
+
raise ValueError(f"atol must be non-negative, got {atol}")
|
|
97
|
+
|
|
98
|
+
base_mat = _to_numeric_matrix(fn(data))
|
|
99
|
+
diffs: dict[str, float] = {}
|
|
100
|
+
for mode in ("scale_up", "scale_down", "shock"):
|
|
101
|
+
mutated = _mutate_future(data, cutoff, mode)
|
|
102
|
+
alt_mat = _to_numeric_matrix(fn(mutated))
|
|
103
|
+
diffs[mode] = _max_prefix_diff(base_mat, alt_mat, cutoff)
|
|
104
|
+
|
|
105
|
+
worst = max(diffs.values())
|
|
106
|
+
passed = worst <= atol
|
|
107
|
+
return CheckResult(
|
|
108
|
+
name="future_mutation",
|
|
109
|
+
family="leakage",
|
|
110
|
+
status="PASS" if passed else "FAIL",
|
|
111
|
+
metric=worst,
|
|
112
|
+
threshold=atol,
|
|
113
|
+
summary=(
|
|
114
|
+
f"max prefix drift {worst:.3e} <= {atol:.1e} across 3 future mutations"
|
|
115
|
+
if passed
|
|
116
|
+
else f"LOOKAHEAD DETECTED: prefix drifted by {worst:.3e} (> {atol:.1e})"
|
|
117
|
+
),
|
|
118
|
+
details={"cutoff": cutoff, "n_rows": n, "diffs": diffs},
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _int_literal(node: ast.AST) -> int | None:
|
|
123
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, int) and not isinstance(
|
|
124
|
+
node.value, bool
|
|
125
|
+
):
|
|
126
|
+
return node.value
|
|
127
|
+
if (
|
|
128
|
+
isinstance(node, ast.UnaryOp)
|
|
129
|
+
and isinstance(node.op, ast.USub)
|
|
130
|
+
and isinstance(node.operand, ast.Constant)
|
|
131
|
+
and isinstance(node.operand.value, int)
|
|
132
|
+
):
|
|
133
|
+
return -node.operand.value
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _str_literal(node: ast.AST) -> str | None:
|
|
138
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
139
|
+
return node.value
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _bool_literal(node: ast.AST) -> bool | None:
|
|
144
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, bool):
|
|
145
|
+
return node.value
|
|
146
|
+
return None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def execution_delay_test(
|
|
150
|
+
positions: ArrayLike,
|
|
151
|
+
asset_returns: ArrayLike,
|
|
152
|
+
*,
|
|
153
|
+
periods_per_year: int = 252,
|
|
154
|
+
max_sharpe_drop: float = 0.50,
|
|
155
|
+
) -> CheckResult:
|
|
156
|
+
"""Detect same-bar close-to-close execution lookahead via a 1-bar signal delay.
|
|
157
|
+
|
|
158
|
+
Compares the Sharpe ratio of ``positions * asset_returns`` (same-bar fill)
|
|
159
|
+
against ``shift(positions, +1) * asset_returns`` (next-bar fill). A real
|
|
160
|
+
intraday or daily signal loses a small amount of edge to 1-bar latency; a
|
|
161
|
+
strategy that silently trades on bar ``t``'s close while claiming bar ``t``'s
|
|
162
|
+
return collapses when delayed by one bar.
|
|
163
|
+
"""
|
|
164
|
+
pos = np.asarray(positions, dtype=np.float64)
|
|
165
|
+
ret = np.asarray(asset_returns, dtype=np.float64)
|
|
166
|
+
if pos.ndim != 1 or ret.ndim != 1 or pos.size != ret.size or pos.size < 10:
|
|
167
|
+
raise ValueError("positions and asset_returns must be 1-D arrays of equal length >= 10")
|
|
168
|
+
if not (np.all(np.isfinite(pos)) and np.all(np.isfinite(ret))):
|
|
169
|
+
raise ValueError("positions and asset_returns must be finite")
|
|
170
|
+
if not (0.0 < max_sharpe_drop <= 1.0):
|
|
171
|
+
raise ValueError(f"max_sharpe_drop must lie in (0, 1], got {max_sharpe_drop}")
|
|
172
|
+
|
|
173
|
+
def _sr(r: NDArray[np.float64]) -> float:
|
|
174
|
+
std = float(np.std(r, ddof=1))
|
|
175
|
+
return (float(np.mean(r)) / std) * math.sqrt(periods_per_year) if std > 0.0 else 0.0
|
|
176
|
+
|
|
177
|
+
sr_base = _sr(pos * ret)
|
|
178
|
+
delayed_pos = np.empty_like(pos)
|
|
179
|
+
delayed_pos[0] = 0.0
|
|
180
|
+
delayed_pos[1:] = pos[:-1]
|
|
181
|
+
sr_delay = _sr(delayed_pos * ret)
|
|
182
|
+
|
|
183
|
+
if sr_base <= 0.0:
|
|
184
|
+
drop = 0.0
|
|
185
|
+
status: Status = "PASS"
|
|
186
|
+
else:
|
|
187
|
+
drop = max(0.0, (sr_base - sr_delay) / sr_base)
|
|
188
|
+
if drop <= max_sharpe_drop and sr_delay > 0.0:
|
|
189
|
+
status = "PASS"
|
|
190
|
+
elif sr_delay > 0.0:
|
|
191
|
+
status = "WARN"
|
|
192
|
+
else:
|
|
193
|
+
status = "FAIL"
|
|
194
|
+
|
|
195
|
+
return CheckResult(
|
|
196
|
+
name="execution_delay",
|
|
197
|
+
family="leakage",
|
|
198
|
+
status=status,
|
|
199
|
+
metric=drop,
|
|
200
|
+
threshold=max_sharpe_drop,
|
|
201
|
+
summary=(
|
|
202
|
+
f"1-bar delay SR {sr_base:.2f} -> {sr_delay:.2f} (drop {drop:.1%})"
|
|
203
|
+
if status != "FAIL"
|
|
204
|
+
else f"EXECUTION LOOKAHEAD: 1-bar delay collapsed SR {sr_base:.2f} -> {sr_delay:.2f}"
|
|
205
|
+
),
|
|
206
|
+
details={"sr_base": sr_base, "sr_delayed": sr_delay, "drop_fraction": drop},
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def static_leakage_scan(source_or_path: str | Path) -> CheckResult:
|
|
211
|
+
"""AST scan for common lookahead calls in Python strategy or feature code.
|
|
212
|
+
|
|
213
|
+
Flags negative ``.shift(-k)``, ``.bfill()`` / ``.backward_fill()``,
|
|
214
|
+
``fillna(method='bfill'|'backfill')``, ``rolling(..., center=True)``,
|
|
215
|
+
``join_asof(..., strategy='forward'|'nearest')``, and ``.fit_transform(...)``
|
|
216
|
+
calls on unsplit feature matrices.
|
|
217
|
+
"""
|
|
218
|
+
if isinstance(source_or_path, Path):
|
|
219
|
+
code = source_or_path.read_text(encoding="utf-8")
|
|
220
|
+
label = str(source_or_path)
|
|
221
|
+
else:
|
|
222
|
+
code = source_or_path
|
|
223
|
+
label = "<string>"
|
|
224
|
+
|
|
225
|
+
tree = ast.parse(code)
|
|
226
|
+
findings: list[dict[str, Any]] = []
|
|
227
|
+
|
|
228
|
+
for node in ast.walk(tree):
|
|
229
|
+
if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
|
|
230
|
+
continue
|
|
231
|
+
attr = node.func.attr
|
|
232
|
+
line = getattr(node, "lineno", 0)
|
|
233
|
+
|
|
234
|
+
if attr == "shift":
|
|
235
|
+
arg: ast.AST | None = node.args[0] if node.args else None
|
|
236
|
+
if arg is None:
|
|
237
|
+
for kw in node.keywords:
|
|
238
|
+
if kw.arg in ("n", "periods"):
|
|
239
|
+
arg = kw.value
|
|
240
|
+
break
|
|
241
|
+
val = _int_literal(arg) if arg is not None else None
|
|
242
|
+
if val is not None and val < 0:
|
|
243
|
+
findings.append({"line": line, "rule": "negative_shift", "detail": f"shift({val})"})
|
|
244
|
+
|
|
245
|
+
elif attr in ("bfill", "backward_fill"):
|
|
246
|
+
findings.append({"line": line, "rule": "backward_fill", "detail": f".{attr}()"})
|
|
247
|
+
|
|
248
|
+
elif attr in ("fillna", "fill_null"):
|
|
249
|
+
for kw in node.keywords:
|
|
250
|
+
if kw.arg in ("method", "strategy"):
|
|
251
|
+
sval = _str_literal(kw.value)
|
|
252
|
+
if sval in ("bfill", "backfill", "backward"):
|
|
253
|
+
findings.append(
|
|
254
|
+
{"line": line, "rule": "backward_fill", "detail": f"{attr}({sval!r})"}
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
elif attr == "rolling":
|
|
258
|
+
for kw in node.keywords:
|
|
259
|
+
if kw.arg == "center" and _bool_literal(kw.value) is True:
|
|
260
|
+
findings.append(
|
|
261
|
+
{"line": line, "rule": "centered_rolling", "detail": "rolling(center=True)"}
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
elif attr == "join_asof":
|
|
265
|
+
for kw in node.keywords:
|
|
266
|
+
if kw.arg in ("strategy", "direction"):
|
|
267
|
+
sval = _str_literal(kw.value)
|
|
268
|
+
if sval in ("forward", "nearest"):
|
|
269
|
+
findings.append(
|
|
270
|
+
{
|
|
271
|
+
"line": line,
|
|
272
|
+
"rule": "non_causal_asof",
|
|
273
|
+
"detail": f"join_asof({kw.arg}={sval!r})",
|
|
274
|
+
}
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
elif attr == "fit_transform":
|
|
278
|
+
findings.append(
|
|
279
|
+
{
|
|
280
|
+
"line": line,
|
|
281
|
+
"rule": "full_sample_fit_transform",
|
|
282
|
+
"detail": ".fit_transform()",
|
|
283
|
+
}
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
findings.sort(key=lambda item: (item["line"], item["rule"]))
|
|
287
|
+
passed = len(findings) == 0
|
|
288
|
+
return CheckResult(
|
|
289
|
+
name="static_leakage_scan",
|
|
290
|
+
family="leakage",
|
|
291
|
+
status="PASS" if passed else "FAIL",
|
|
292
|
+
metric=float(len(findings)),
|
|
293
|
+
threshold=0.0,
|
|
294
|
+
summary=(
|
|
295
|
+
f"0 static lookahead patterns in {label}"
|
|
296
|
+
if passed
|
|
297
|
+
else f"{len(findings)} lookahead pattern(s) flagged in {label}"
|
|
298
|
+
),
|
|
299
|
+
details={"source": label, "findings": findings},
|
|
300
|
+
)
|