σμ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 3 · Features, objectives and priors›Topic 3.2·~55 minAdvanced

Objectives: regression and ranking

Skill positionModule 3 of 4 · Topic 2 of 3
3.2 Objectives: regression and ranking
—Lab score— / 100Total XP—Streak—
Lecture0% read

10 min readCode examples: 8

  1. 01A loss is a slope and a curvature
  2. 02Three losses
  3. 03Plug your own loss into XGBoost
  4. 04Ranking: order inside a date
  5. 05The comparison: a number against an order
  6. 06What you will build

One huge error of 9 moves a squared-error leaf by 2.25; a pseudo-Huber leaf by 0.33. Change the loss and you change what the model cares about. And when the question is "who ranks above whom this month", a ranking loss can answer it directly.

01

A loss is a slope and a curvature

Where we are. The last topics tuned and regularised a model that always minimised the same thing, the squared error. That is a choice. The squared error treats a miss of 10 as a hundred times worse than a miss of 1, it is built for a number, and it knows nothing about ranking. XGBoost lets you change the objective, the loss that boosting reduces. The change is smaller than it sounds, because boosting only needs two numbers from a loss.

DefinitionGradient and hessian

For one row and the current prediction f: the gradient g is the slope of the loss with respect to f (which way to move and how hard), and the hessian h is the curvature, the slope of the slope (how far to trust the slope). In words: g says "you are too high by this much", h says "and this is how steep the bowl is here".

leaf answer = − Σg / (Σh + λ)(1)Σ is the sum over the rows in the leaf; λ (lambda) is the penalty of the last topic. For the squared error g = f − y and h = 1, so the answer is the mean residual, as before

Worked example 1. *Problem:* three rows with y = 3, 5, 9, all predicted 5. What do the gradient and hessian of the squared error say, and what does a leaf holding them answer? *Plan:* g = f − y, h = 1; then apply equation 1 with λ = 0 and with λ = 1. *Steps:* below.

main.pyPython
y = np.array([3.0, 5.0, 9.0])pred = np.full(3, 5.0)g, h = squared_error_grad_hess(y, pred)1print(g.tolist(), h.tolist())print(round(-g.sum() / (h.sum() + 0.0), 4), round(-g.sum() / (h.sum() + 1.0), 4))2
[2.0, 0.0, -4.0] [1.0, 1.0, 1.0]
0.6667 0.5
  1. 1The slope and the curvature of the squared error.
  2. 2The leaf answer for lambda 0 and for lambda 1.

*Check:* the gradients are 2, 0, -4 (the first row is predicted too high, the last too low), the hessians are 1, 1, 1. The leaf answers -(-2) / 3 = 0.6667 with λ = 0 (the mean of the residuals -2, 0, 4) and 0.5 with λ = 1. *What to notice:* the answer pushes the prediction up, because on balance the rows were predicted too low. Equation 1 is the whole interface between a loss and a tree.

02

Three losses

The squared error (f − y)² / 2 has the slope f − y and the curvature 1. The logistic loss is for labels that are 0 or 1 ("did the stock rise?"). The model produces a raw score, the *margin*, and the probability is p = 1 / (1 + e^(−margin)). The loss is −(y log p + (1 − y) log(1 − p)), its slope is p − y and its curvature p (1 − p). A confident correct prediction has almost no slope and no curvature: nothing is left to learn from it.

main.pyPython
for margin in (-2.0, 0.0, 2.0):    g, h = logistic_grad_hess([1.0], [margin])    print(margin, round(float(1 / (1 + np.exp(-margin))), 3), round(float(g[0]), 3), round(float(h[0]), 3))
-2.0 0.119 -0.881 0.105
0.0 0.5 -0.5 0.25
2.0 0.881 -0.119 0.105

For the true label 1: at the margin −2 the probability is only 0.119 and the slope is −0.881, a strong pull upwards; at 0 the slope is −0.5; at +2 the probability is 0.881 and the slope has shrunk to −0.119. The curvature is largest (0.25) at the margin 0, where the model is least sure.

The pseudo-Huber loss is for numbers that have outliers. With the error r = f − y and a size δ (delta), the loss is δ² (√(1 + (r/δ)²) − 1): it looks like the squared error when r is small and like the absolute error when r is large. Its slope is r / √(1 + (r/δ)²), which never exceeds δ, and its curvature is (1 + (r/δ)²)^(−3/2), which fades for big errors. Worked example 2. *Problem:* four rows, y = 1, 1.1, 0.9, 10, all predicted 1: one is an outlier. How much does the outlier move a leaf under each loss? *Plan:* compute the gradient and hessian of both and apply equation 1 with λ = 0.

main.pyPython
y = np.array([1.0, 1.1, 0.9, 10.0])pred = np.ones(4)for name, loss in (("squared", squared_error_grad_hess), ("pseudo-Huber", lambda a, b: pseudo_huber_grad_hess(a, b, 1.0))):    g, h = loss(y, pred)1    print(name.ljust(12), g.round(4).tolist(), h.round(4).tolist(), round(-g.sum() / h.sum(), 4))
squared      [0.0, -0.1, 0.1, -9.0] [1.0, 1.0, 1.0, 1.0] 2.25
pseudo-Huber [0.0, -0.0995, 0.0995, -0.9939] [1.0, 0.9852, 0.9852, 0.0013] 0.3344
  1. 1Slopes, curvatures and the leaf answer.

*Check:* with the squared error the outlier has the slope -9 and the leaf answers 2.25, pulled up by one row. With the pseudo-Huber loss the outlier's slope is capped at -0.9939, its curvature is 0.0013 (the loss no longer trusts it), and the leaf answers 0.3344. *What to notice:* the choice of loss decides how much a handful of extreme rows can steer the trees. In stock data, where a few months have enormous moves, that choice matters.

A slope and a curvature are easy to get wrong by a sign or a factor, and there is a check that needs no library: nudge the prediction a little and watch how the loss changes. Worked example 3. *Problem:* is the pseudo-Huber slope right at r = 0.3 with δ = 0.2? *Plan:* compare the formula with the numerical slope (loss(f + ε) − loss(f − ε)) / 2ε. *Steps:* below.

main.pyPython
delta, f, y, eps = 0.2, 0.3, 0.0, 1e-6loss = lambda z: delta**2 * (np.sqrt(1 + ((z - y) / delta) ** 2) - 1)formula, _ = pseudo_huber_grad_hess([y], [f], delta)print(round(float(formula[0]), 6), round((loss(f + eps) - loss(f - eps)) / (2 * eps), 6))
0.16641 0.16641

*Check:* both numbers are 0.166410. *What to notice:* the lab's tests use this check for all three losses, so a wrong sign or a missing square is caught at once.

03

Plug your own loss into XGBoost

An XGBoost regressor accepts the objective either as a name ("reg:squarederror", "reg:pseudohubererror") or as a function (y_true, y_pred) → (gradient, hessian). With a function, XGBoost does not know where the predictions should start, so you give the starting point yourself with base_score; the lab uses the mean of the training target for every model, so the comparisons are fair.

Worked example 4. *Problem:* is your squared-error function the same as XGBoost's built-in loss, and is your pseudo-Huber function the same as reg:pseudohubererror? *Plan:* fit each pair with the same settings and compare the test predictions; the largest absolute difference should be nothing but rounding. *Steps:* fit_with_objective with a name and with a function.

main.pyPython
panel = build_panel(load_close())train = split_by_date(panel, "1900-01-01", "2015-01-01")test = split_by_date(panel, "2015-01-01")mine = lambda y_true, y_pred: squared_error_grad_hess(y_true, y_pred)huber = lambda y_true, y_pred: pseudo_huber_grad_hess(y_true, y_pred, 0.05)1a = fit_with_objective(train, "reg:squarederror").predict(test[FEATURES])2b = fit_with_objective(train, mine).predict(test[FEATURES])c = fit_with_objective(train, "reg:pseudohubererror", huber_slope=0.05).predict(test[FEATURES])3d = fit_with_objective(train, huber).predict(test[FEATURES])4print(float(np.max(np.abs(a - b))), f"{float(np.max(np.abs(c - d))):.1e}", f"{float(np.max(np.abs(a - c))):.2f}")
0.0 1.5e-08 0.10
  1. 1Built-in, by name.
  2. 2The same loss, as your function.
  3. 3Built-in pseudo-Huber with its slope parameter.
  4. 4Your function with delta 0.05.

*Check:* the squared-error pair differs by 0.0 and the pseudo-Huber pair by 1.5e-08, rounding of 32-bit numbers. The two different losses differ from each other by 0.10, in the unit of the move. *What to notice:* your functions *are* the objectives. Anything with a slope and a curvature can be a loss: an asymmetric one that punishes missing a big move more than overshooting it, or a quantile loss, are written the same way.

04

Ranking: order inside a date

Portfolio decisions are often about order, not size: buy the top fifth of the stocks of the month, avoid the bottom fifth. A regressor spends its effort on getting the sizes right. A ranker is trained for order only. Its target is a grade inside each date: rank the stocks of the date from the smallest value of the quantity you care about, and cut the ranks into groups (grade 0 for the lowest fifth, up to grade 4). A date is a *query*: only stocks of the same date are compared.

Worked example 5. *Problem:* six stocks on one date have the values 0.04, 0.09, 0.02, 0.07, 0.05, 0.11. Give them grades 0 to 2. *Plan:* rank them from the smallest, then grade = (rank − 1) × 3 // 6. *Steps:* relevance_labels.

main.pyPython
one_date = pd.DataFrame({"date": pd.to_datetime(["2020-01-31"] * 6), "move": [0.04, 0.09, 0.02, 0.07, 0.05, 0.11]})print(one_date["move"].rank(method="first").astype(int).tolist())print(relevance_labels(one_date, "move", 3).tolist())
[2, 5, 1, 4, 3, 6]
[0, 2, 0, 1, 1, 2]

*Check:* the ranks are 2, 5, 1, 4, 3, 6 and the grades 0, 2, 0, 1, 1, 2: two stocks in each grade. *What to notice:* the size of the values disappeared. The biggest move gets the top grade whether it is 0.11 or 11. That makes a ranker robust to outliers.

How does a model learn from grades? Pairwise ranking takes every pair of stocks of one date with different grades and asks the model to give the higher grade the higher score. With scores sᵢ and sⱼ, the loss of a pair in which i should be above j is log(1 + e^(−(sᵢ − sⱼ))): small when sᵢ is much larger than sⱼ, large when the order is wrong. Worked example 6. *Problem:* three stocks with the grades 1, 2, 0 and the scores 0.2, 0.5, −0.1. What is the pairwise loss? *Plan:* list the pairs in which one grade is higher, compute the loss for each, add them. *Steps:* below.

main.pyPython
scores = np.array([0.2, 0.5, -0.1])grades = np.array([1, 2, 0])total = 0.0for i in range(3):    for j in range(3):        if grades[i] > grades[j]:1            pair = float(np.log(1 + np.exp(-(scores[i] - scores[j]))))2            print(i, ">", j, round(pair, 4))            total += pairprint(round(total, 4))
0 > 2 0.5544
1 > 0 0.5544
1 > 2 0.4375
1.5462
  1. 1Stock i should be above stock j.
  2. 2The loss is small when the scores agree with the grades.

*Check:* three pairs: stock 1 over stock 0 (0.5544), stock 1 over stock 2 (0.4375) and stock 0 over stock 2 (0.5544); they add up to 1.5462. All three scores are in the right order, so the loss is not large, but it is not 0 either: the training goes on pushing the scores apart. *What to notice:* the loss depends only on the differences of scores inside a date. Adding the same number to every score of a date changes nothing, which is why a ranker's score has no unit.

05

The comparison: a number against an order

Worked example 7. *Problem:* for the size of next month's move, is a ranker better than a regressor, and does it work for the direction of the return? *Plan:* train both on the years before 2015 and judge on the later ones with the rank IC (the average per-date Spearman correlation) and with the spread between the top fifth and the bottom fifth of the predictions. Then train a ranker on grades of the return itself. *Steps:* study.

main.pyPython
result = study(panel)print(f"{result['gap_squared']:.1e}", f"{result['gap_huber']:.1e}")print(round(result["ic_regressor"], 4), round(result["ic_ranker"], 4))print(round(result["spread_regressor"], 4), round(result["spread_ranker"], 4))print(round(result["ic_ranker_returns"], 4))
0.0e+00 1.5e-08
0.1861 0.1894
0.0317 0.0321
-0.0021

*Check:* the regressor reaches a rank IC of 0.1861 and the ranker 0.1894; the stocks the ranker puts in the top fifth moved 0.0321 more than the ones in the bottom fifth, against 0.0317 for the regressor. For the *direction* of the return, a ranker trained on grades of fwd has a rank IC of -0.0021: nothing. *What to notice:* the two models are about equally good at the size of the move, as the features hold the same information either way. The ranker's real use is when the order is all you need, and when your target has outliers. And a ranker cannot find a signal that is not in the features: for the return itself it finds none.

Which number to optimise

A model trained for squared error and a model trained for ranking can have the same rank IC and very different errors in the unit of the target. Pick the objective that matches the decision: sizes for pricing and risk, order for selection.

What the real data says56 US stocks; trained before 2015, scored from 2015
Custom against built-in0 / 1.5e-08largest difference in a test prediction: squared error / pseudo-Huber
Rank IC, size of move0.186 / 0.189regressor / ranker
Top minus bottom fifth0.0317 / 0.0321regressor / ranker, in move size
Rank IC, return direction-0.002a ranker trained on the grades of the return itself

Key takeaways

  • A loss is two numbers. The slope and the curvature at each row are all boosting needs; a leaf answers −Σg / (Σh + λ).
  • Check by nudging. Compare the formula with the change in the loss for a small move of the prediction; it catches wrong signs and factors.
  • The loss sets the priorities. Squared error lets outliers steer; pseudo-Huber caps them; logistic is for yes/no labels.
  • Rank inside a date. Grades are made per date, and a ranker learns to put the higher grade first among stocks of the same date.
Quick check
Your turn. A row has the true value 4 and the model predicts 1. What are the gradient and hessian of the squared error (f − y)² / 2?
Pick an answer.
06

What you will build

The lab follows the lecture. Tasks 1 to 3 write the slope and the curvature of the squared error, the logistic loss and the pseudo-Huber loss. Task 4 trains a model with any objective, a name or your own function. Task 5 turns a column into grades inside each date and task 6 trains a ranker on them. Task 7 checks your losses against XGBoost's and compares a regressor with a ranker on the real panel.

Next topic: the models so far used only what the data says. The next topic, Monotone constraints for financial priors, adds what an analyst already knows, for instance that a riskier stock should not be predicted to move less, by forcing the model's response to a feature to go one way only.

Lab · what's graded

7 tasks · 100 pts
  • Squared error10 pts
  • Logistic loss10 pts
  • Pseudo-Huber loss15 pts
  • Fit with any objective10 pts
  • Grades inside each date15 pts
  • Train a ranker15 pts
  • A number against an order25 pts
Explorer · lab-xg-06
▾ lab-xg-06
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-xg-06$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-xg-06 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