σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
XGBoost skill›Module 4 · Reading and judging the model›Topic 4.4·~1 hr 40 minAdvanced

Capstone: a ranker for next-month returns

Skill positionModule 4 of 4 · Topic 4 of 4
4.4 Capstone: a ranker for next-month returns
—Lab score— / 100Total XP—Streak—
Lecture0% read

8 min readCode examples: 5

  1. 01The pipeline in one picture
  2. 02Six features from prices
  3. 03One scale for every month
  4. 04Scores from models that never saw the month
  5. 05Reading the scores honestly
  6. 06A target with no signal, a target with one
  7. 07What you will build

The same ranker, trained the same way, finds a rank correlation of 0.21 (t-statistic 16.8) between its scores and the size of next month's move, and 0.005 (t-statistic 0.42) between its scores and the return. One pipeline, two honest answers: there is something to find in the first and nothing in the second.

01

The pipeline in one picture

Where we are. The earlier topics gave you the parts: a first model, a boosting loop, depth and regularisation, missing values, objectives and ranking, constraints, importance, validation and the cost of a model. This capstone builds one pipeline from them and runs it on real stocks. The question is the one a research team would ask: can a ranker built from price data order the stocks of next month?

  1. 1
    FeaturesSix numbers per stock and month-end, each using only prices up to that day.
  2. 2
    One scaleReplace each feature by its percentile rank among the stocks of the same month, so that a wild month and a calm one look alike.
  3. 3
    Walk-forward scoresTrain a ranker on the past only, with an embargo, and score the next block of months; repeat for five blocks.
  4. 4
    Honest readingA rank correlation for every month, its average and t-statistic, the share of good months, and the average outcome in each fifth of the scores.

The result is a table of evidence, not a trading rule. The point of the capstone is as much to see what no evidence looks like as to see what evidence looks like.

02

Six features from prices

Take the month-end closes and the monthly returns ret. Two measures of momentum, mom (from 12 months ago to one month ago) and mom6 (from 6 months ago to one month ago), leave out the latest month because the latest month is the reversal effect, which rev carries. Two measures of risk, vol and vol3, are the standard deviation of the last 12 and the last 3 monthly returns. A last one, dd, measures how far the stock is from its highest close of the last 12 months, zero at a new high.

Worked example 1. *Problem:* build the panel from the daily prices. *Plan:* take the last close of each month, compute the six features and the two targets, stack them into rows and drop the rows that have a hole. *Steps:* build_features.

main.pyPython
close = load_close()panel = build_features(close)1print(panel.shape, panel["date"].min().date(), panel["date"].max().date(), panel["ticker"].nunique())print(panel.iloc[0][["ticker", "mom", "rev", "vol", "dd", "fwd"]].to_dict())print(panel[FEATURES].describe().loc[["min", "50%", "max"]].round(3).to_dict("list"))
(17075, 10) 2001-01-31 2026-07-31 56
{'ticker': 'AAPL', 'mom': -0.7132200702843414, 'rev': 0.453225046552846, 'vol': 0.28289728519872176, 'dd': -0.6815783781658015, 'fwd': -0.15627113096800305}
{'mom': [-0.93, 0.089, 6.052], 'mom6': [-0.927, 0.044, 2.745], 'rev': [-0.577, 0.01, 1.141], 'vol': [0.017, 0.063, 0.404], 'vol3': [0.0, 0.054, 0.701], 'dd': [-0.941, -0.054, 0.0]}
  1. 1Month-end closes, six features, two targets, and the rows with holes dropped.

*Check:* 17,075 rows, 56 stocks, from January 2001 to July 2026. The first row is AAPL in January 2001 with a momentum of -0.713 (the price had fallen a lot) and a next-month return of -0.1563. The momentum goes from -0.93 to 6.05 (a stock that multiplied its price seven times) and the drawdown dd from -0.94 to 0. *What to notice:* the panel starts in 2001 because mom needs 12 months of prices, and ends in July 2026 because the last month has no next month. Each row uses only prices up to its own month-end, except fwd and move, which are labels.

03

One scale for every month

A raw volatility of 0.08 means one thing in a calm month and another in a wild one. Rank normalising replaces each feature, month by month, by the percentile rank of the stock among the stocks of that month, minus 0.5. The numbers then lie between -0.5 and 0.5 whatever the market did. A tree model does not need this (it only compares values), but a ranker that is trained across many regimes benefits from features whose meaning does not move.

Worked example 2. *Problem:* four stocks with a feature of 10, 30, 20, 40 in one month. What does the normalised feature look like, and what happens to a month in which everything is ten times bigger? *Plan:* rank inside the date, divide by the number of stocks, subtract 0.5. *Steps:* rank_normalise on a tiny frame.

main.pyPython
tiny = pd.DataFrame({"date": pd.to_datetime(["2020-01-31"] * 4 + ["2020-02-29"] * 4), "vol": [10.0, 30.0, 20.0, 40.0, 100.0, 300.0, 200.0, 400.0]})print(rank_normalise(tiny, ["vol"])["vol"].tolist())
[-0.25, 0.25, 0.0, 0.5, -0.25, 0.25, 0.0, 0.5]

*Check:* both months give -0.25, 0.25, 0.0, 0.5, the same numbers, although the second month is ten times bigger. *What to notice:* what is left is only the order of the stocks inside the month, which is what a ranker needs and what is stable from month to month.

04

Scores from models that never saw the month

Now the ranker. For every fold of a walk-forward validation (the topic before the last), train on the months before the test block, with an embargo of one month, grade the training rows with relevance_labels and give each date its own query. Then score the rows of the test block. Put all the test scores together in one array, one value for each row of the panel. The rows that are never in a test block (the first block) have no score: NaN.

Worked example 3. *Problem:* how many months get a score, and from which month? *Plan:* run walk_forward_scores on the normalised features with the return as label, and look at where the scores exist. *Steps:* below.

main.pyPython
scores = walk_forward_scores(normalised, FEATURES, "fwd")1scored = ~np.isnan(scores)print(int(scored.sum()), "of", len(scores), "rows;", normalised.loc[scored, "date"].nunique(), "months from", normalised.loc[scored, "date"].min().date(), "to", normalised.loc[scored, "date"].max().date())print(np.round(scores[scored][:5], 4).tolist())
14266 of 17075 rows; 255 months from 2005-04-30 to 2026-06-30
[-0.0406, -0.0867, -0.0068, 0.0539, -0.055]
  1. 1NaN for every row that is never in a test block.

*Check:* 14,266 of the 17,075 rows have a score; they cover 255 months, from April 2005, since the first 51 months are the history the first model trains on (with the embargo, 50 months). *What to notice:* every score comes from a model that never saw its own month or the month before. These scores can be judged without fooling ourselves.

05

Reading the scores honestly

Three questions, each with a number. Does the order agree with the outcome? For each month compute the rank correlation between the scores and the outcome among the stocks of that month. That gives one number per month, a series. Is the average different from zero? The average of the series, divided by its standard error (the t-statistic), tells how many standard errors the average is away from zero; below about 2 it could be luck. Does it show in the outcomes? The average outcome in each fifth of the scores should rise from the lowest to the highest.

Worked example 4. *Problem:* judge the scores of example 3 against the return of the next month. *Plan:* ic_series, then summarise, then quintile_means. *Steps:* below.

main.pyPython
series = ic_series(normalised, scores, "fwd")print(len(series), series.index.min().date(), series.round(3).iloc[:3].tolist())1print({key: round(value, 4) for key, value in summarise(series).items()})2print([round(v, 4) for v in quintile_means(normalised, scores, "fwd")])
255 2005-04-30 [0.317, 0.032, -0.003]
{'n': 255, 'mean': 0.0047, 'std': 0.1772, 't_stat': 0.4219, 'hit_rate': 0.4784}
[0.0103, 0.0117, 0.0094, 0.0114, 0.0118]
  1. 1Mean, spread, t-statistic and the share of good months.
  2. 2The average return in each fifth of the scores.

*Check:* 255 monthly correlations; their average is 0.0047, their standard deviation 0.177, the t-statistic 0.42 and 48 % of the months are positive. The fifths of the scores have average returns of 1.03 %, 1.17 %, 0.94 %, 1.14 % and 1.18 %. *What to notice:* the average is a tenth of a standard error away from nothing in a series whose months swing by 0.18 either way, and the fifths do not rise. This is what no skill looks like. A single month with a correlation of 0.3 would have looked like a discovery; 255 months say it is noise.

Do not read one fold

A correlation computed on one month, or on one fold, can be large by luck. Judge the average over all the scored months and its t-statistic, and look at how the fifths behave.

06

A target with no signal, a target with one

A pipeline you trust should say "nothing here" when there is nothing, and "something here" when there is. Run it on the size of the next move, which earlier topics showed is predictable, and compare. Worked example 5. *Problem:* the whole story in one call. *Plan:* study runs three pipelines: the return (normalised features), the size of the move (normalised features) and the size of the move (raw features). *Steps:* below.

main.pyPython
result = study(close)print(result["rows"], result["dates"])for name in ("returns", "risk", "risk_raw"):    s = result[name]["summary"]    print(name.ljust(9), round(s["mean"], 4), round(s["t_stat"], 2), f"{s['hit_rate']:.0%}", [round(v, 4) for v in result[name]["quintiles"]])
17075 307
returns   0.0047 0.42 48% [0.0103, 0.0117, 0.0094, 0.0114, 0.0118]
risk      0.2114 16.83 85% [0.042, 0.0475, 0.0539, 0.0601, 0.0785]
risk_raw  0.2153 17.45 86% [0.042, 0.048, 0.0532, 0.06, 0.0788]

*Check:* for the return the average rank correlation is 0.0047 (t 0.42, 48 % of months positive); for the size of the move it is 0.2114 (t 16.83, 85 %), and the fifths rise steadily from 4.2 % to 7.85 %. With the raw features the numbers are the same to the second decimal (0.2153, t 17.45). *What to notice:* the same code, the same models, the same validation: one answer is "nothing", the other is "a lot". The difference is in the data. And the rank normalisation made no difference to a tree model, as expected.

What the real data says56 US stocks, 307 months, 255 scored months from April 2005; five walk-forward folds with an embargo of one month
Panel17,075 rows6 features, 2 targets, 56 stocks, January 2001 to July 2026
Return of next monthIC 0.005 (t 0.42)48% of months positive; the fifths of the scores earn 0.94% to 1.18%: no pattern
Size of next moveIC 0.211 (t 16.8)85% of months positive; the fifths rise from 4.2% to 7.85%
Raw featuresIC 0.215 (t 17.5)the same as normalised: trees only compare values

Key takeaways

  • Build features from the past only. Everything but the label must be known at the month-end; the label is the only column that looks ahead.
  • Score only what the model never saw. Walk-forward folds with an embargo give a score for every month from a model trained on earlier months.
  • Judge with a series, not a number. A rank correlation per month, its average, t-statistic and hit rate, and the outcome by fifth of the scores.
  • Know what nothing looks like. A pipeline that says nothing for returns and a lot for risk can be trusted when it later says something about a new signal.
Quick check
Your turn. A ranker's monthly rank correlations over 100 months have an average of 0.02 and a standard deviation of 0.20. What is the t-statistic, and what do you conclude?
Pick an answer.
07

What you will build

The lab follows the lecture. Task 1 builds the panel from daily prices and task 2 rank-normalises the features. Task 3 produces the walk-forward scores of a ranker. Task 4 computes the monthly rank correlations, task 5 summarises them and task 6 averages the outcome by fifth of the scores. Task 7 runs the whole pipeline for the return and for the size of the move.

This is the last topic of the XGBoost skill. The next skill in the data-science track, LightGBM, uses the same panel and the same questions with a different library, so that every result can be compared with the ones you have just produced.

Lab · what's graded

7 tasks · 100 pts
  • Six features from prices20 pts
  • One scale each month10 pts
  • Walk-forward scores25 pts
  • Monthly rank correlations10 pts
  • An honest summary10 pts
  • Outcome by fifth10 pts
  • Nothing and something15 pts
Explorer · lab-xg-11
▾ lab-xg-11
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-xg-11$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-xg-11 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes