Label a trade by which of profit-taking, stop loss and the holding-period limit is hit FIRST, with barriers scaled to the volatility at the event - instead of by the sign of the return N bars later, which describes a path you would have been stopped out of. TRIGGER - triple barrier, triple-barrier method, getEvents, get_events, getBins, get_bins, barrier_touched, add_vertical_barrier, pt_sl, vertical barrier, t1 touch time, getDailyVol, get_daily_vol, meta-label 0/1, fixed-time horizon labeling, fixed horizon labels, "label = sign of the 5-day forward return", "my classifier is 90 % accurate but loses money", "how do I label financial data for ML", Lopez de Prado chapter 3, AFML labeling. SKIP for weighting the overlapping labels (sample-weights-and-uniqueness), for cross-validating them (lib-purgedcv), for the secondary model (meta-labeling), for the CUSUM event sampler (structural-breaks), and for stationary features (fractional-differentiation).
Ships in fin-ml. 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 fixed-horizon label tells the model that a trade which fell through its stop and recovered was a winner. Advances in Financial Machine Learning (Lopez de Prado 2018), chapter 3. The label is the target the model optimises; if the label is about a path you could not have held, the model learns to predict something you cannot trade, and no amount of cross-validation catches it because the labels and the backtest agree with each other.
Every number below is printed by scripts/triple_barrier.py (numpy only, seed 0, 1.2 s). The
test series is 6,000 bars of clustered volatility (log-vol AR(1), phi = 0.99) with zero
drift, so every asymmetry below is geometry, not alpha. Bars are integer indices; the book keys
everything by DatetimeIndex, which changes none of the arithmetic.
⚠️ Snippet and page numbers below are as cited in mlfinpy 0.1.2's own docstrings; what is verified here is the code, not the book.
Per event t0: a profit-taking barrier at +pt * trgt, a stop-loss barrier at -sl * trgt, and
a vertical barrier vert bars later. The label is which one is touched first.
✅ Source-verified against mlfinpy 0.1.2 (mlfinpy/labeling/labeling.py, mlfinpy/util/volatility.py):
triple_barriers (AFML Snippet 3.2, page 45) computes
cum_returns = (closing_prices / close[loc] - 1) * events_.at[loc, "side"] — arithmetic
returns, signed by the side — and takes cum_returns[cum_returns > profit_taking[loc]].index.min()
for the touch. Strict inequality, first index, so a bar that lands exactly on the barrier does
not count.get_daily_vol (Snippet 3.1, page 44) is (close / close.shift(1) - 1).ewm(span=lookback).std()
with lookback = 100 — arithmetic returns, pandas' adjusted EWM, unbiased standard
deviation. ✅ The script's numpy re-implementation matches pandas' ewm(span=100).std() to
9.7e-17.get_events (Snippet 3.6, page 50) applies target = target[target > min_ret] before
anything else: 🚨 min_ret silently deletes every event whose target volatility is below
it. That is a sample filter that removes calm periods, not a label parameter.Why the target must be the local volatility. ✅ Measured, 1,136 events, pt_sl = (4, 4),
20-bar vertical barrier, split into volatility terciles by the EWMA target at the event:
| volatility tercile | resolve on the vertical barrier, vol-scaled | resolve on the vertical barrier, fixed-width |
|---|---|---|
| low | 39.8 % | 71.0 % |
| mid | 37.6 % | 37.0 % |
| high | 46.2 % | 22.4 % |
| low-to-high spread | 6.3 % | 48.5 % (7.7x) |
🚨 With one fixed barrier width, the meaning of the label changes with the regime: in the quiet third of the sample 71 % of events time out and in the noisy third only 22 % do. The model learns "class 0 means low volatility", which is a fact about the labeller, not about the future. The realised per-bar volatility here spans 40x (0.0018 to 0.0717), which is not extreme for real data.
✅ Same 1,136 events, same 20-bar horizon:
| labelling | -1 | 0 | +1 |
|---|---|---|---|
triple barrier, pt_sl = (4, 4) | 26.1 % | 41.2 % | 32.7 % |
fixed horizon, threshold = the same pt barrier | 15.9 % | 62.2 % | 21.8 % |
| fixed horizon, sign only (threshold 0) | 46.5 % | 0.0 % | 53.5 % |
The sign-only version is the one most people write, and it has no neutral class at all: every event is a directional bet, including the 41 % that the barrier method says never went anywhere.
The disagreement is not a rounding error. ✅ Measured, sign-only fixed-horizon labels against triple-barrier labels over the identical 20-bar horizon and the identical barriers:
🚨 And 6.0 % is the number for a very loose stop. Tighten it and the horizon labels fall apart:
| stop (sigma of the event's target vol) | 1.0 | 2.0 | 3.0 | 4.0 |
|---|---|---|---|---|
| horizon labels whose path went through a barrier | 43.7 % | 22.1 % | 11.8 % | 6.0 % |
At a 1-sigma stop — a perfectly ordinary risk limit — 44 % of the training labels describe trades that no longer existed by the horizon.
What that costs in the backtest. Take the ceiling: a perfect model of the fixed-horizon labels, which is the best any model trained on them can be.
| how it is scored | mean return per event |
|---|---|
| the way it was trained: hold to the horizon, no stop | +0.04243 |
| the same bets, with the same barriers honoured | +0.03336 |
| the gap | +0.00906 per event, 21 % of the apparent profit |
That 21 % is not a modelling error, a cost assumption or a slippage estimate. It is profit the backtest booked from drawdowns the risk limits would not have let you hold.
✅ Among the 608 events the sign-only label calls +1, the worst drawdown before the horizon:
| statistic | in return | in units of the event's target volatility |
|---|---|---|
| median | -0.0082 | -0.82 sigma |
| 10th percentile | -0.0330 | — |
| worst | -0.1392 | -11.09 sigma |
44.4 % of these "winners" went through a 1-sigma stop first, and 5.4 % through a 4-sigma stop. The median winner spent part of its life 0.8 sigma under water. Every one of those is a positive training example.
pt_sl sets the class balance, and the class balance is not evidence✅ Same events, same zero-drift series, only the barrier multiples change:
pt_sl | -1 | 0 | +1 | mean barrier return |
|---|---|---|---|---|
| (1, 1) | 48.6 % | 1.0 % | 50.4 % | +0.00006 |
| (2, 1) | 58.6 % | 3.8 % | 37.6 % | +0.00006 |
| (1, 2) | 34.4 % | 4.1 % | 61.4 % | +0.00040 |
| (2, 2) | 42.0 % | 10.0 % | 48.0 % | +0.00096 |
| (1, 0) — no stop | 0.0 % | 29.7 % | 70.3 % | -0.00000 |
🚨 A wide stop with a tight target produces 70 % positive labels on a series with no drift. If
you report "the model predicts up moves 70 % of the time", you are reporting pt_sl. Class
balance, base rate and any accuracy figure derived from them are properties of the barrier
geometry. pt_sl and vert are researcher degrees of freedom: record them in
../../../fin-core/skills/backtest-validation/scripts/trial_ledger.py.
✅ Source-verified in mlfinpy 0.1.2. triple_barriers decides the touch with the arithmetic
return against pt * trgt. barrier_touched (Snippet 3.9, page 55), called from get_bins,
then re-derives the label from out_df["ret"], which get_bins builds as a log return
(np.log(prices.loc[t1]) - np.log(prices.loc[t0])), and tests it against
np.log(1 + target) * events.loc[date_time, "pt"].
Those two thresholds are equal only at pt = 1. ✅ Measured on the same events:
pt_sl | horizontal touches | relabelled 0 (vertical) by the Snippet 3.9 test |
|---|---|---|
| (1, 1) | 1,125 | 0 (0.0 %) |
| (2, 2) | 1,022 | 9 (0.9 %) |
| (3, 3) | 855 | 19 (2.2 %) |
At target 2 % and pt = 2, the touch fires at r > 0.0400 and the relabelling needs
r > 0.0404; a touch inside that band is recorded as a vertical-barrier label. Small, silent,
and it grows with the multiple. If you use pt_sl above 1, decide which convention you want and
apply it in both places.
min_ret is a sample filter. get_events drops events, it does not just skip barriers.
Whatever it removes is missing from the training set and from every count you report.t1 is the touch time, not the vertical barrier. Everything downstream depends on it:
purging, embargoing, uniqueness and weights all need the bar where the label actually resolved.
Passing the vertical barrier instead over-purges; passing t0 + 1 under-purges and silently
reintroduces the leak — ../../../fin-libraries/skills/lib-purgedcv/SKILL.md owns that, and
evaluation_times is where the touch time goes.../sample-weights-and-uniqueness/SKILL.md) and cross-validate them with purging and an
embargo (../../../fin-libraries/skills/lib-purgedcv/SKILL.md). Neither is optional.../../../fin-microstructure/skills/intraday-microstructure/SKILL.md owns the bar-versus-tick question.accuracy_score.../structural-breaks/SKILL.md). Changing the sampler changes the label distribution and the
effective sample size.pip install mlfinlab cannot work — ✅ checked 2026-09-09, the PyPI JSON API returns 404
and the simple index lists zero files. The maintained fork is mlfinpy 0.1.2 (MIT), which
⚠️ pins numpy<1.27. The snippets above were read from its sdist, not from an installed copy.scripts/triple_barrier.py — the causal EWMA target volatility checked against pandas, the
first-touch scan, triple-barrier and meta-labels, fixed-horizon labels, the volatility-tercile
table, the path-conflict counts and the stop-tightness sweep, maximum adverse excursion, the
pt_sl class-balance table, and the Snippet 3.2 / 3.9 return-convention mismatch. numpy only
(pandas is used once, inside a function, purely to check the EWMA). Seed 0, 1.2 s.../sample-weights-and-uniqueness/SKILL.md takes the t1 touch times from here and turns them
into concurrency, uniqueness and sample weights. ../meta-labeling/SKILL.md takes the side
argument of get_events and adds the secondary model.
../structural-breaks/SKILL.md owns the CUSUM filter that should choose the events.
../fractional-differentiation/SKILL.md is the feature side of the same pipeline.
../../../fin-libraries/skills/lib-purgedcv/SKILL.md owns purged and embargoed cross-validation
for the overlapping labels this produces — never re-implement it.
../../../fin-core/skills/backtest-validation/SKILL.md owns the trial ledger for pt_sl and
vert. ../../../fin-core/skills/signal-construction/SKILL.md owns the causality check on the
features that go with these labels.
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
/fin-ml:triple-barrier-labelingfrom fin-ml
npx claudepluginhub howard-lynn-ye/fin-rsi --plugin fin-ml7 skills in this plugin
/bet-sizingTurn a predicted probability into a position - the 2*Phi(z)-1 size curve, averaging concurrent bets instead of adding them, discretising to buy turnover, and the concurrency budget whose divisor is usually a look-ahead. TRIGGER - bet sizing, getSignal, get_signal, getBetSize, bet size from probability, avgActiveSignals, average active bets, discreteSignal, discrete signal, step size, position from predict_proba, "how big should this trade be", "my positions flip every bar", turnover from a probability, concurrent bets leverage, budgeting bets, Lopez de Prado chapter 10, AFML bet sizing. SKIP for the Kelly fraction and how large the book should be overall (position-sizing-kelly - it owns Kelly, do not repeat it), for the secondary model that produces the probability (meta-labeling), for volatility targeting and risk budgets (portfolio-and-risk), and for the execution schedule once the size is chosen (execution-algorithms)./feature-importance-financialRank features without believing MDI - it is in-sample, it favours columns with many distinct values, and it splits credit between substitutable features; MDA under-states collinear pairs and leaks outright on a shuffled k-fold. TRIGGER - feature_importances_, feature importance, MDI, mean decrease impurity, Gini importance, MDA, mean decrease accuracy, permutation importance, permutation_importance, single feature importance, SFI, clustered feature importance, "which features matter", "my random forest says this random column is important", "importance changes every run", correlated features importance, substitution effect, Lopez de Prado chapter 8, AFML feature importance. SKIP for purged and embargoed cross-validation itself (lib-purgedcv), for the overlapping-label weights (sample-weights-and-uniqueness), for feature construction and causality (signal-construction), for factor-return attribution (factor-models), and for the trials a feature search spends (backtest-validation)./fractional-differentiationMake a price series stationary without throwing away the memory a model needs - the weight recursion, the fixed-width window, and the scan for the smallest d that passes ADF. TRIGGER - fractional differentiation, fractional differencing, fracdiff, frac_diff, frac_diff_ffd, get_weights_ffd, plotMinFFD, plot_min_ffd, "minimum d", ARFIMA, long memory, (1-B)^d, binomial weights, fixed-width window fracdiff; "my model only sees returns", "prices are non-stationary so I differenced them", "ADF says my feature is non-stationary", "should I feed prices or returns to the model", Lopez de Prado chapter 5, AFML fracdiff. SKIP for the cointegration ADF table and the fitted-residual null (stat-arb-cointegration), for unit-root and ARIMA model selection generally (time-series-forecasting-models), for making a feature causal and its warm-up (signal-construction), and for labels rather than features (triple-barrier-labeling)./meta-labelingA primary model picks the side, a secondary model trained on "was the primary right" decides whether to act - raising precision, lowering recall, and paying for itself in costs. The trap is training the secondary on rows the primary was fitted on. TRIGGER - meta-labeling, metalabeling, meta labels, secondary model, primary model side, get_events side_prediction, bin in {0,1}, "should I take this signal", precision vs recall trade-off in trading, F1 of a trading model, filter model, trade filter, "my model has high recall but loses money", "how do I improve a strategy without changing its signal", Lopez de Prado chapter 3 section 3.6, AFML meta-labeling. SKIP for producing the triple-barrier labels and the `side` argument itself (triple-barrier-labeling), for turning the secondary's probability into a position size (bet-sizing), for the Kelly fraction (position-sizing-kelly), for purged cross-validation of either model (lib-purgedcv), and for which features matter (feature-importance-financial)./sample-weights-and-uniquenessOverlapping labels are not independent observations - compute concurrency, average uniqueness and return-attributed weights, and divide your t-statistics by the overlap factor before believing any of them. TRIGGER - sample weights, average uniqueness, concurrency, overlapping labels, numCoEvents, num_concurrent_events, getAvgUniqueness, tW, sample_weight in fit(), getWeightsByReturn, get_weights_by_return, time decay weights, getTimeDecay, sequential bootstrap, seq_bootstrap, indicator matrix, effective sample size, "my labels overlap", "my t-stat is 4 but it does not hold up", "overlapping forward returns", Lopez de Prado chapter 4, AFML sample weights. SKIP for purged and embargoed cross-validation of the same labels (lib-purgedcv owns it, do not re-implement), for producing the labels and their t1 touch times (triple-barrier-labeling), for feature importance under overlap (feature-importance-financial), and for Sharpe deflation (backtest-validation)./structural-breaksSample events with the symmetric CUSUM filter instead of on a clock, and test for explosive behaviour with SADF instead of one full-sample ADF that has no power against a bubble in part of the sample. TRIGGER - CUSUM filter, cusum_filter, symmetric CUSUM, event-based sampling, t_events, event sampling for labels, SADF, supremum ADF, sup ADF, get_sadf, BSADF, backward SADF, Phillips-Shi-Yu, explosiveness test, bubble detection, structural break test, Chow test, "how do I pick the bars to label", "my ADF says nothing but the chart is obviously a bubble", "when did the regime change", Lopez de Prado chapter 17, AFML structural breaks. SKIP for labelling the events once they are sampled (triple-barrier-labeling), for making a feature stationary (fractional-differentiation), for the cointegration ADF table (stat-arb-cointegration), for hidden-state / volatility regime labels (regime-detection), and for unit-root and ARIMA selection generally (time-series-forecasting-models).