Module contents
Stage 9 of 9Research 120 min

Machine learning signal and final report

Follow the complete ML signal pipeline: point-in-time features, volatility-adjusted triple-barrier labels, boosting with purged validation, meta-labeling for position sizing, a backtest with costs and impact, and adjustment for registered trials. Produce a reproducible research report that honestly assesses the evidence for an edge.

After this lesson you can

  • Construct point-in-time features and triple-barrier labels without information leakage.
  • Train a gradient boosting model with purged validation and meta-labeling.
  • Evaluate the strategy with costs, impact, factor attribution, and the deflated Sharpe ratio.
  • Write a reproducible report with assumptions, trial count, and limitations.

Before you start

A complete investigation

An ML signal needs more than a model: it requires data available at the right time, labels, temporal selection, calibration, execution, costs, and a description of what was tried. This lesson produces a reproducible report that includes a negative conclusion when the data do not support an edge.

We use a Yahoo AAPL snapshot for 2020 through 2023. Prices and events may have been revised retrospectively; we do not have an archive of versions published on each date. Features use only previous rows or the decision close within this snapshot, but that does not establish historical point-in-time availability. It is a single-asset example, not a representative sample or recommendation.

Labels and timing

Triple-barrier labeling starts with a signal calculated at close tt. Hypothetical entry is fixed at open t+1t+1. We use the volatility of 20 daily returns known at close tt to define upper and lower barriers as multiples of that volatility, then inspect closes from t+1t+1 for at most five sessions. The first barrier touched gives +1 or −1; if neither is touched, the label is 0 at expiry.

InteractiveThree barriers on AAPL

AAPL, retrospectively adjusted Yahoo snapshot: 2022-01-03 to 2022-06-30, 124 sessions. Signal at close 2022-02-08, hypothetical entry at open 2022-02-09. Adjusted prices are not a historical point-in-time version.

Entry 172.05, upper barrier 175.61, lower 168.49; daily volatility before entry 2.07 %. Vertical range 127.29 to 177.65.

Blue: profit; orange: stop; dot: label close. The count uses all complete entries in this sample and changes with horizon and barriers.

Detail from 2022-02-03 to 2022-02-17: barriers are shown from open to label close; a same-day touch is represented by a small marker.

25
1.0
1.0
5
Resultstop
Label close2022-02-10
Other overlapping labels5
Profit / stop / horizon45 / 58 / 16
Figures come from a retrospective snapshot; barriers are observed only at closes.

A close beyond a barrier does not imply that a real order would have executed at that level. The model ignores the intraday path, queues, and gaps; it uses the observed close rather than the high or low. Different label intervals can overlap. The end date must accompany each label to purge training before each test block.

For example, an entry at 100 with 2% daily volatility and multipliers of one sets levels 102 and 98. If the first subsequent close is 103, assign +1 and end the label that day. If no close touches a barrier by the fifth, assign zero at the end. The exact move and exit price are not the label: the label describes an event, while the backtest calculates an open-to-open return.

The figure applies the same definition to 124 real sessions from the snapshot. Moving the start or changing the horizon recalculates the first touch and number of overlapping intervals. Class balance depends on barriers, volatility, and the sample. Do not choose these parameters by looking at the balance or profitability of the final test without recording that decision.

Features are one-day return, five-day return, 20-day volatility, and monetary volume relative to its 20-day mean. They are calculated at the signal close, before the assumed entry open. Adjusted open is approximated by multiplying the published open by adjusted close/close; monetary volume uses Yahoo fields. Adjustment conventions and revisions require independent verification. This example includes neither cross-sectional variables nor a point-in-time liquidity database.

Primary model and meta-labeling

The primary rule sells after a positive five-day return and buys after a negative one. Meta-labeling assigns one when the first barrier touched favors that direction and zero when it opposes it or expires without a touch. A higher probability does not guarantee economic profit: gains, losses, costs, and trading frequency matter.

The ML signal pipeline compares two LightGBM classifiers with depths 2 and 3. At each cutoff, an earlier segment chooses depth by log-loss, a separate later segment fits logistic calibration to model probabilities, and the next block is reserved for evaluation. Training labels must end before the test cutoff; internal fitting labels must end before the next segment. Models are refitted in five blocks of 126 signals.

The target position is the primary direction multiplied by calibrated probability, between zero and one unit of exposure. If probability is 0.6 and direction is long, the target is +0.6. This is a simple rule, not a Kelly formula or proof that size is optimal. The Brier score combines calibration and discrimination; a single value does not prove probabilities are calibrated in every regime.

Calibration is fitted on dates distinct from those used to train the classifier. Calibrating on the same in-sample fitted predictions could make confidence too optimistic. Here the calibrator is logistic regression applied to the uncalibrated probability and re-estimated at each cutoff. It can be unstable in small samples; a reliability curve by probability interval and subperiod evaluation would help diagnose it.

The meta-label treats expiry without a touch as unfavorable, even if the return at expiry is positive. The daily portfolio does not hold each trade to its barrier: it updates the target each session and earns the next open’s return. Label AUC and backtest profit therefore measure related but distinct objects. A strategy actually holding positions to the labeled exit would require modeling simultaneous positions and their fills.

Permutation importance is calculated after predicting each block: one feature is altered in that block and the AUC change is measured. It is not used for feature selection in the experiment. Independent permutation can break temporal and cross-feature relationships; negative or changing importances are not causal effects. Overall AUC is also reported, although overlapping labels mean the 630 observations are not independent.

Costs, attribution, and registry

Each closing signal determines position at the next open and open-to-open return. The backtest uses fixed reference capital of one million for costs, full spread 10 bp, commission and slippage 1 bp each, and impact 0,5σQ/ADV0,5\sigma\sqrt{Q/ADV} with volatility and average volume calculated before the open. These are assumptions rather than observed quotes or fills. Financing, short borrowing, weight drift, permanent impact, and liquidity constraints are excluded.

The vectorized and event-driven engines are compared without costs and with fractional shares under ideal execution at the open. Equality checks accounting under the same clock, not fill feasibility. Costs are applied in the vectorized engine. Monthly attribution uses official Kenneth French factors and HAC errors; the first partial month is excluded. Daily returns are grouped by initial open date, while factors are monthly with another price convention, so intervals at month boundaries do not align exactly. Estimated alpha depends on the model, sample, and this misalignment.

In the vectorized engine, row tt contains return from open tt to the next open; its position comes from the previous close’s signal. The event-driven engine converts the same weight into fractional shares at the open and marks them at the next price. The comparison covers the entire curve, not only its final value. For net cost, absolute weight change is applied to fixed reference capital; the compounded curve does not change the size used to calculate impact.

The registry contains the two predefined candidates and a third column with the selection derived from internal validations. DSR uses two as an approximation to the number of trials, not three independent trials. It excludes other decisions or explorations outside the registry and does not automatically correct temporal dependence or selection across the entire project. Three input hashes and the registry hash identify this run.

The two candidates are evaluated on the same blocks to record their trajectories, but the selection at each cutoff uses the prior validation segment. The selected column may combine different models over time. With only two Sharpes and correlated returns, the cross-sectional dispersion entering DSR is highly uncertain. Read 0.200 as an approximate diagnostic for this limited family, not an exact probability of success or failure.

Local laboratory and result

The reproducible research report combines assumptions, procedures, results, trial count, and limitations so another person can repeat and discuss the analysis.

Download p01final.py and test_p01final.py, along with p01data.py, p01vector.py, p01events.py, p01cost.py, p01trials.py, and p01metrics.py from previous lessons. Install NumPy, pandas, SciPy, scikit-learn, statsmodels, LightGBM, and pytest. With the same raw files and package versions, run python p01final.py to generate p01_project/final/research.html, the metrics report, manifest, and registered series. P01_AAPL_PATH, P01_FACTOR_ROOT, P01_MOM_PATH, and P01_FINAL_ROOT allow existing snapshots and destination to be used.

[ ]Research pipeline and reportLocal GPU
import os,sys
from pathlib import Path
import pytest
lib=Path(os.environ.get('P01_LIB_DIR','.')).resolve()
if not (lib/'p01final.py').exists(): raise FileNotFoundError('Descarga los módulos del proyecto en P01_LIB_DIR')
sys.path.insert(0,str(lib))
from p01final import experiment
os.environ['PYTEST_DISABLE_PLUGIN_AUTOLOAD']='1'
status=pytest.main([str(lib/'test_p01final.py'),'-q','-p','no:cacheprovider'])
assert status==0
experiment()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The verified run has 1006 original sessions and 630 predictions in five blocks between June 2021 and December 2023. The final remaining block of one observation is excluded. Meta AUC 0.517 and Brier 0.236 do not establish an edge; the strategy trades on every evaluated signal because size is proportional to a positive probability.

Conventional annual gross Sharpe is −0.281, net Sharpe is −0.528, and compounded net capital ends at 0.851. The maximum difference between engines in the ideal no-cost comparison is 3.22×10−153.22\times10^{-15}. Approximate DSR with two candidates is 0.200. Regression over 30 complete months gives monthly alpha −0.00885 and HAC statistic −2.63; the sample is short, signals overlap, and prior selection limits inference. The conclusion of this run is that a net edge has not been demonstrated.

Mean permutation importance for AUC is approximately 0.0025 for one-day return, 0.0215 for five-day return, 0.0078 for volatility, and −0.0190 for relative volume. Importances vary across blocks; they were not used to reselect features and do not prove a causal relationship. The generated report preserves cutoffs, metrics, assumptions, data versions by hash, and candidate count. The AAPL SHA-256 used is 5851521fa13f58bce8df6f15760e087126e693727d526cfaea4b50b482089208.

Exercises

CodeFirst barrier
Implement triple_barrier(prices,vol,pt,sl,horizon) for a path with initial price prices[0] and at least horizon later prices. Return (label, exit index, reason): +1 and 'beneficio' when touching the upper barrier, −1 and 'stop' when touching the lower, or 0 and 'horizonte' if neither is touched.
def triple_barrier(prices,vol,pt,sl,horizon):
  raise NotImplementedError()
Shift+Enter to run
QuizAUC and economics
Why might an AUC of 0.53 be economically relevant or irrelevant?
NumericMeta size
With this lesson's rule, a long primary direction and calibrated probability 0.6, what is the target weight?
QuizForgotten attempts
If another 40 configurations are discovered to have been tested before selection, what should be revised in the report?

What to remember

Key idea
A reproducible report includes data, timing, selection, costs, uncertainty, and negative results. An attractive curve alone does not answer whether an edge exists.