Decide whether a result survives the number of things you tried. TRIGGER - "I tried N strategies or parameters and the best one..."; overfitting, p-hacking, data snooping, "is this result real", "is this statistically significant"; deflated Sharpe, DSR, PSR, the trial ledger; White's Reality Check, Hansen SPA, StepM, model confidence set, arch.bootstrap; purged or combinatorial cross-validation, embargo, walk-forward, "cross validation on time series without leaking"; a grid search, hyperopt or AutoML picked a winner; triple-barrier labeling, meta-labeling, fractional differentiation, mlfinlab. Load whenever a Sharpe ratio is about to be offered as evidence for trading. SKIP for plain performance metrics - Sharpe, Sortino, CAGR, drawdown (portfolio-and-risk); for PBO, CSCV and the minimum backtest length (backtest-overfitting); and for Bonferroni, Holm, Benjamini-Hochberg or Benjamini-Yekutieli over a ledger of trials (multiple-testing-ledger). The deflated and probabilistic Sharpe ratios are computed HERE.
Ships in fin-core. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
A backtest reports the maximum of a search. The question is never "what was the Sharpe" but "what was the Sharpe, given how many things were tried, and how much of the sample was independent." This skill answers both.
pip install purgedcv # purged/combinatorial CV + PSR/DSR. MIT. py>=3.10
pip install skfolio # CPCV composed with sklearn GridSearchCV. BSD-3
pip install arch # SPA / Reality Check / StepM / MCS. THE significance toolkit
pip install RiskLabAI # broadest AFML reimplementation. BSD-3. py>=3.12
pip install ml4t-diagnostic # DSR, PBO, CPCV, feature importance. MIT. py>=3.12
pip install jsharpe # PSR, MinTRL + FWER/FDR corrections. MIT. py>=3.11
🚨 Do not plan around mlfinlab. Not installable from PyPI; the GitHub source is stubbed
(every function body is pass); licence is proprietary all-rights-reserved; silent since 2023.
🚨 fracdiff is archived (2023-12) and requires_python <3.10 — unusable on modern Python.
⚠️ pypbo is the reference PBO/CSCV implementation but is not on PyPI and is AGPL-3.0.
⚠️ sharpebench (v0.17.1, 2026-09-02) covers this whole surface but declares no repository
URL on PyPI — provenance unverifiable. New and unvetted; do not default to it.
Any CV that shuffles is catastrophic here. train_test_split, KFold(shuffle=True), default
cross_val_score on a DataFrame. Even unshuffled KFold fails without purging.
from purgedcv import PurgedKFold, CombinatorialPurgedCV
cv = PurgedKFold(n_splits=5,
prediction_times=t0, # when the feature was known
evaluation_times=t1, # when the label resolved <- forces honesty
purge_horizon="1D", embargo="2D")
cv = CombinatorialPurgedCV(n_splits=6, n_test_groups=2,
prediction_times=t0, evaluation_times=t1)
purgedcv is the best standalone choice precisely because it requires evaluation_times —
you cannot use it without confronting your label horizon. It is sklearn-protocol compliant, so it
drops into cross_val_score / GridSearchCV / Pipeline with no glue, and audit_splitter()
gives per-fold leakage diagnostics.
Rules:
skfolio, purged_size/embargo_size are counted in observations, not time — with
dollar/volume bars a fixed count is a wildly varying span. Its split() also yields
(train, [test_0, test_1, ...]), not sklearn's 2-tuple.Evidence that CPCV is the right default: Arian, Norouzi & Seco, Knowledge-Based Systems 305
(2024), doi 10.1016/j.knosys.2024.112477 — in a synthetic controlled environment (Heston, Merton
jumps, drift-burst, regime-switching), CPCV markedly outperforms K-Fold, Purged K-Fold and
especially Walk-Forward on both PBO and DSR, with walk-forward showing weak false-discovery
control and high temporal variability. ⚠️ The lead author also authors RiskLabAI — peer-reviewed
but not disinterested.
arch.bootstrap — the right tool for "better than the benchmark after searching"This is the most under-used correct answer in the field. ✅ verified API, executed on arch 8.0.0:
from arch.bootstrap import SPA, RealityCheck, StepM, MCS, optimal_block_length
| Question | Class |
|---|---|
| "Is the best of my N strategies better than the benchmark, accounting for having searched N?" | RealityCheck (White 2000; alias of SPA) |
| Same, studentized + recentered so poor models don't distort it | SPA (Hansen 2005) |
| Which strategies beat the benchmark, with FWER control | StepM (Romano-Wolf) |
| The set of models indistinguishable from the best at 1−α | MCS (Hansen-Lunde-Nason 2011) |
🚨 ALL THREE TAKE LOSSES, NOT RETURNS. ✅ Verified from arch/bootstrap/multiple_comparison.py:
SPA/StepM document benchmark as "T element array of benchmark model losses" and models
as "T by k element array of alternative model losses"; MCS's parameter is literally named
losses. Passing returns silently inverts every one of these tests — it asks which strategy is
worst. Convert first: losses = -returns.
bm_loss = -benchmark_returns # (T,) NEGATE
mdl_loss = -model_returns # (T, k) NEGATE
spa = SPA(bm_loss, mdl_loss, reps=1000, block_size=10, seed=7); spa.compute()
spa.pvalues # {'lower':…, 'consistent':…, 'upper':…} -> report 'consistent'
stepm = StepM(bm_loss, mdl_loss, size=0.05, reps=1000, block_size=10); stepm.compute()
stepm.superior_models # survives FWER control
mcs = MCS(mdl_loss, size=0.10, reps=1000, block_size=10); mcs.compute()
mcs.included, mcs.excluded
optimal_block_length(bm_loss) # Politis-White; pick block_size from this, not by eye
🚨 Other gotchas:
lower liberal, upper conservative. Report consistent.RealityCheck is a zero-code subclass of SPA — same interface, same loss convention.block_size from optimal_block_length — preserving serial dependence is the entire point.No dominant maintained package exists — this is a genuine ecosystem gap and the formulas are
short enough to inline. Available in purgedcv, ml4t-diagnostic, jsharpe, RiskLabAI.
🚨 quantstats has sharpe/sortino but NO PSR/DSR/MinTRL — do not reach for it here.
import numpy as np
from scipy.stats import norm, skew, kurtosis
def probabilistic_sharpe_ratio(r, sr_benchmark=0.0):
"""P(true SR > sr_benchmark), correcting for skew, kurtosis, sample length.
r and sr_benchmark must be on the SAME per-period scale."""
T = len(r)
sr = r.mean() / r.std(ddof=1)
g3, g4 = skew(r), kurtosis(r, fisher=False) # g4 = NON-excess kurtosis
num = (sr - sr_benchmark) * np.sqrt(T - 1)
den = np.sqrt(1 - g3 * sr + ((g4 - 1) / 4) * sr ** 2)
return norm.cdf(num / den)
def deflated_sharpe_ratio(r, n_trials, sr_variance):
"""PSR evaluated against the EXPECTED MAX Sharpe of n_trials independent backtests."""
e = np.euler_gamma
sr0 = np.sqrt(sr_variance) * (
(1 - e) * norm.ppf(1 - 1 / n_trials) + e * norm.ppf(1 - 1 / (n_trials * np.e))
)
return probabilistic_sharpe_ratio(r, sr_benchmark=sr0)
⚠️ Formula transcription unverified against the source papers — check before publishing.
🔴 n_trials is the input that decides the answer, and it is almost always underreported. It is
every configuration you tried: every barrier multiple, lookback, threshold, feature set, universe
filter, rebalance frequency — including abandoned ones, and including everything an automated search
(RD-Agent, gplearn, Optuna, hyperopt) evaluated. No library can recover it for you. Reporting
n_trials = "the 5 models I saved" makes DSR a rubber stamp.
Keep a trial ledger. Append every candidate and its parameters before looking at out-of-sample
results. scripts/trial_ledger.py provides a minimal append-only implementation.
Also check whether a given DSR implementation actually applies the skew/kurtosis adjustment or silently assumes IID normal — the expected-max term should use the Euler–Mascheroni constant.
DSR's two companions live in their own skills. ../backtest-overfitting/SKILL.md owns the
Probability of Backtest Overfitting via CSCV and the Minimum Backtest Length — the same
expected-max term, inverted for the sample length a claimed Sharpe needs at a given trial count.
../multiple-testing-ledger/SKILL.md owns family-wise error and false-discovery control over the
whole ledger, and the haircut a Sharpe takes. fin_skills.api.guards.research_audit.reality_check
runs the integrity, cost, deflation, PBO and regime stages in that order and stops at the first
failure.
| Method | Correct implementation | Note |
|---|---|---|
| Triple-barrier labeling | RiskLabAI (meta_events, triple_barrier), ml4t.engineer.labeling, mlfinpy (MIT, stale) | mlfinlab's is a pass stub |
| Meta-labeling | RiskLabAI.meta_labeling, mlfinpy.get_bins (side path) | 🚨 primary model must emit out-of-sample sides |
| Fractional differentiation (FFD) | RiskLabAI (FFD + ADF min-d) | fracdiff archived, py<3.10 |
| Purged / combinatorial CV | purgedcv, skfolio, RiskLabAI | |
| Sample uniqueness / time-decay weights | RiskLabAI, mlfinpy.sampling, ml4t-engineer | Sequential bootstrap is O(n²); effect is modest (uniqueness ~0.6→0.7) |
| PSR / DSR / MinTRL | purgedcv, jsharpe, ml4t-diagnostic | |
| PBO via CSCV | pypbo (AGPL, git-only), ml4t-diagnostic, RiskLabAI | pip install pbo does not exist |
| Tick / volume / dollar / imbalance bars | ml4t.engineer.bars, RiskLabAI, mlfinpy | Imbalance bars' EWMA warm-up is arbitrary and materially changes bar counts |
| Bet sizing | RiskLabAI | Thinnest coverage of any AFML chapter |
🚨 A verified bug worth knowing, present in mlfinlab's API and its faithful clones: get_bins
throws away which barrier get_events already determined was touched, and re-infers the label
by comparing the realized return to thresholds. Two consequences: (a) threshold inconsistency —
barrier_touched tests against pt·log(1+target) while the barrier was placed at
log(1+pt·target) (for target=0.02, pt=2: 0.0396 vs 0.0392), so borderline events are mislabeled;
(b) prices = close.reindex(all_dates, method="bfill") — backfill resolves a missing t1 to the
next available price, a forward-looking value. Fix: capture which barrier was hit inside
get_events and carry it through.
AFML is not seriously contested in the literature; it is under-tested. No substantive published rebuttal of triple-barrier or meta-labeling exists. But:
min_ret, CUSUM threshold, bar type, embargo width,
fractional d — is a researcher degree of freedom that inflates your trial count.A result is not reportable without: the metric and its annualization factor; the risk-free convention; the CV scheme with purge and embargo; the trial count and where the ledger lives; the cost model; and the confidence interval. A 3-year Sharpe of 1.0 has a standard error near 0.58.
A negative result is a result. "The baseline did not clear the pre-registered threshold" is the correct output far more often than a positive one, and pre-registering the threshold is what makes it credible.
The optional fin-libraries plugin carries a dedicated skill for each library below. Load one
only after this skill has told you which library you want:
lib-arch — archlib-purgedcv — purgedcvWhat SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
18 skills in this plugin
/backtesting-enginesChoose a backtesting engine and know what it silently models wrong. TRIGGER - "backtest this", backtest a crossover or a moving-average strategy, simulate a strategy, walk-forward, parameter sweep, "test this trading idea"; comparing or choosing backtest frameworks; vectorbt, backtesting.py, backtrader, zipline, PyBroker, bt, nautilus_trader, LEAN, freqtrade, jesse; how an engine models fills, slippage, commissions; what slippage to assume, partial fills, margin, shorting or delistings; taking a strategy from backtest to live; "my backtest looks too good"; "works in backtest but loses money live". Several popular engines fill at the signal's own bar close by default. SKIP for judging whether a finished result is real (backtest-validation) for A-share rules (china-trading-stack), for crypto funding and perpetuals (crypto-data-and-execution), for options, which need assignment and settlement no engine here models (options-backtesting), and for measuring fills you already have (execution-cost-analysis)./backtest-overfittingDecide whether an edge that passed every mechanical check is still just the best of N tries. TRIGGER - PBO, probability of backtest overfitting, CSCV, combinatorially symmetric cross validation, logit of the out-of-sample rank; minimum backtest length, MinBTL, "how much history do I need", "how many parameter sets can I try on N years of data"; a grid search, Optuna or AutoML picked a winner and it decayed; "in-sample Sharpe 2, live Sharpe 0", "the best parameter set stopped working", "is this peak on my parameter surface real"; pypbo, RiskLabAI CSCV. SKIP for the deflated and probabilistic Sharpe ratios, the trial ledger and SPA/StepM/MCS against a benchmark (backtest-validation); for family-wise error and false-discovery control over a whole research programme (multiple-testing-ledger); for the purged and combinatorial CV splitters themselves (lib-purgedcv); for the mechanical leakage gates that come first (research-integrity-guards); and for regime coverage of the test window (regime-detection)./broker-execution-apisConnect to a broker and place orders without accidentally trading live money. TRIGGER - connect to Interactive Brokers, TWS, IB Gateway, ib_async, ib_insync, ibapi, Alpaca, Schwab, schwab-py, Tastytrade, Tradier or Robinhood; place, modify or cancel an order; read positions or balances; set up paper trading; order types, time-in-force, bracket or OCO orders, client order ID; FIX, quickfix, simplefix; "make sure I don't send a live order"; a broker connection being refused. Load before any code that can transmit an order. SKIP for crypto exchanges and ccxt (crypto-data-and-execution), and for vnpy, CTP, QMT or any Chinese broker gateway (china-trading-stack). This skill answers TWS/Gateway port and connection failures on its own - the fin-libraries deep dive is optional and most installs will not have it./combining-data-sourcesCombine information of DIFFERENT kinds into one research view whose every number can be traced back to what was knowable when. TRIGGER - joining prices to fundamentals, earnings or a macro series; building a signal from a filing plus a price; merging two vendors into one series; "which vendor do I trust"; combine_first / fillna / bfill across sources; assembling a company dossier, profile or research view from several places; a field that must carry its provenance; "when did this number become knowable"; period_end vs filed vs available; a ticker that changed company mid-sample; filling a ResultCard's data block. SKIP for the mechanics of ONE as-of join (safe_asof, in market-data-engineering); for reconciling two price series from two vendors (reconcile_sources, in market-data-sourcing); for auditing a finished backtest (research-integrity-guards); and for resolving a ticker to a permanent id (security-master-and-symbology)./derivatives-pricingChoose a derivatives pricing library and get its Greek units and conventions right. TRIGGER - option pricing, implied volatility, IV, Greeks, delta, gamma, vega, theta, rho; which pricing library, exotics coverage; QuantLib, vollib, py_vollib, financepy, rateslib, optionlab; option chains. Greek scaling differs by 100x and 365x between the three common libraries, and one popular fixed-income package is not open source. SKIP for option lifecycle events - assignment, pin risk, expiry - live or backtested, and for historical option chains and vendors (options-backtesting). SKIP for the models themselves - implementing one (option-pricing-models), fitting a smile (implied-vol-surface), building a curve (term-structure-models), bond accrued and the 30/360 family (bond-conventions-and-accrued), duration and DV01 (duration-convexity-and-dv01), and projection-versus-discount choice on a swap (ois-discounting-and-multi-curve)./etf-mechanicsWhy an ETF's price series does not behave like the index it tracks - daily-reset leverage, NAV vs price, distributions, holdings files and fees. TRIGGER - "why is my 3x ETF down when the index is flat", TQQQ decay, SQQQ, leveraged ETF long term, inverse ETF, volatility drag, daily reset; premium to NAV, discount to NAV, iNAV, creation/redemption, "bond ETF trading below NAV"; ETF distribution, capital gains distribution, return of capital, "ETF dropped on the ex-date", phantom drop; ETF holdings file, constituents CSV, index reconstitution, Russell rebalance, "I used today's holdings for the backtest"; expense ratio drag, tracking difference vs tracking error, "ETF returned less than the index". SKIP for downloading price series and vendor adjustment defaults (market-data-sourcing) - holdings files stay here, for UNG, USO or VIXY roll yield and contango (futures-continuous-contracts), for auditing a finished backtest (research-integrity-guards), and for weights, Sharpe or drawdown (portfolio-and-risk)./fin-core:backtest-validationfrom fin-core
npx claudepluginhub howard-lynn-ye/fin-rsi --plugin fin-core