σμ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.3·~50 minAdvanced

Monotone constraints for financial priors

Skill positionModule 3 of 4 · Topic 3 of 3
3.3 Monotone constraints for financial priors
—Lab score— / 100Total XP—Streak—
Lecture0% read

7 min readCode examples: 4

  1. 01A rule the data cannot learn
  2. 02Writing the rule
  3. 03Checking the rule: partial dependence
  4. 04Row by row
  5. 05A right prior, a wrong prior, no prior
  6. 06What you will build

Without a rule, a model that predicts the size of next month's move has 0 rows out of 300 whose prediction only rises with volatility. With one line, 300 of 300 do, and the test error moves by 0.00008. A right prior is free; a wrong one costs 0.0008.

01

A rule the data cannot learn

Where we are. The last topic made the model plainer by penalties. This topic adds something different in kind: knowledge that does not come from the data. A tree model fits whatever shape the training rows suggest, and with thousands of leaves some of those shapes are bumps of noise. Ask what the model predicts for a stock as its volatility goes from low to high, everything else fixed, and you will often see a curve that rises, dips, and rises again. An analyst knows that a riskier stock should not be predicted to move less.

DefinitionMonotone constraint

A rule on one feature: when it goes up and all the others stay the same, the prediction may not go down (sign +1) or may not go up (sign −1). During training XGBoost refuses any split that would break the rule, so the finished model obeys it for every possible row, not only on average.

Constraints are most useful where finance gives a firm direction: more volatility means a bigger move, a higher default probability means a higher loss, a larger bid–ask spread means a higher trading cost. They stop the model from learning a coincidence that contradicts what you know, and they make the model easier to explain to a risk committee.

02

Writing the rule

XGBoost reads the rule as a text with one number per feature column, in the order of the columns the model is fitted on: 1 for a rising rule, -1 for a falling one and 0 for no rule. For the columns mom, rev, vol, a rising rule on vol is "(0,0,1)".

Worked example 1. *Problem:* write the text for "momentum may only lower the prediction, volatility may only raise it", then check the rule on a tiny model. *Plan:* look each column up in a dictionary of signs, defaulting to 0, and join the numbers; then fit on made-up rows where the truth does the opposite of the rule on one feature. *Steps:* below.

main.pyPython
print(constraint_string(FEATURES, {"mom": -1, "vol": 1}), constraint_string(FEATURES, {}), constraint_string(["vol", "mom"], {"mom": 1}))1x = np.linspace(0, 1, 40)tiny = pd.DataFrame({"mom": 0.0, "rev": 0.0, "vol": x, "move": np.where(x < 0.5, x, 1 - x) + 0.01 * np.sin(40 * x)})free = xgb.XGBRegressor(n_estimators=30, max_depth=3, learning_rate=0.3, n_jobs=1, random_state=0).fit(tiny[FEATURES], tiny["move"])held = xgb.XGBRegressor(n_estimators=30, max_depth=3, learning_rate=0.3, n_jobs=1, random_state=0, monotone_constraints="(0,0,1)").fit(tiny[FEATURES], tiny["move"])print(np.round(free.predict(tiny[FEATURES]).astype(float)[[0, 10, 20, 30, 39]], 2).tolist())2print(np.round(held.predict(tiny[FEATURES]).astype(float)[[0, 10, 20, 30, 39]], 2).tolist())
(-1,0,1) (0,0,0) (0,1)
[0.0, 0.25, 0.49, 0.22, 0.01]
[0.0, 0.25, 0.29, 0.29, 0.29]
  1. 1One number per column, in the order of the columns.
  2. 2The truth rises and then falls; the rule says never fall.

*Check:* the first text is (-1,0,1), the second (0,0,0), and with the columns in another order the entries move with them ((0,1) for ["vol", "mom"] with a rule on momentum). The data rise up to 0.5 and then fall; the free model follows them down, while the constrained model rises and then stays level. *What to notice:* the rule beat the data. That is the intention when you are sure of the rule and the data are noisy, and a bug when you are not. The first line is what the lab's constraint_string produces.

03

Checking the rule: partial dependence

To see what a model does as one feature moves, use the partial dependence: set the feature to a value in every row, predict, and average; do it for a grid of values. It answers "on average, what would the prediction be if every stock had this volatility?".

Worked example 2. *Problem:* is the average prediction rising with vol, for a free model and for one with the rule? *Plan:* fit both on the years before 2011 with 150 trees of depth 4; take a grid of 25 volatilities between the 2nd and the 98th percentile of the fit years; compute the curve on the validation years (2011 to 2014); and test it with is_monotone. *Steps:* below.

main.pyPython
panel = build_panel(load_close())fit = split_by_date(panel, "1900-01-01", "2011-01-01")valid = split_by_date(panel, "2011-01-01", "2015-01-01")test = split_by_date(panel, "2015-01-01")grid = np.linspace(fit["vol"].quantile(0.02), fit["vol"].quantile(0.98), 25)for name, signs in (("free", {}), ("vol_up", {"vol": 1})):1    model = fit_constrained(fit, signs)2    curve = partial_dependence(model, valid, "vol", grid)    print(name.ljust(7), curve[[0, 6, 12, 18, 24]].round(4).tolist(), "smallest step", round(float(np.diff(curve).min()), 5), is_monotone(curve, 1))
free    [0.0331, 0.0582, 0.0836, 0.1016, 0.1086] smallest step -0.00434 False
vol_up  [0.0306, 0.0579, 0.0812, 0.1018, 0.1103] smallest step 0.0 True
  1. 1The mean prediction when every row has this volatility.
  2. 2The smallest step of the curve, and whether it ever goes down.

*Check:* both curves go from about 0.03 to about 0.11 as volatility rises, which is the real effect. The free curve has steps as low as -0.00434, so is_monotone says False; the constrained curve never steps down (the smallest step is 0.0) and says True. *What to notice:* a dip of 0.004 on a scale of 0.08 is small, but it is the kind of wiggle that makes the model's forecast for a riskier stock lower than for a safer one. The simple method, reading the importance of vol, would not show it.

Averages can hide things. The next section checks each row on its own.

04

Row by row

A constraint is a promise about every row. Take the first few hundred rows; for each one, move vol along the grid with everything else fixed, and look at the row's own curve. A row passes if its curve obeys the rule. The share of rows that pass is a stricter check than the average curve.

Worked example 3. *Problem:* what share of the 300 first validation rows rise with vol in each model? *Plan:* use monotone_share with sign +1. *Steps:* the same two models.

main.pyPython
for name, signs in (("free", {}), ("vol_up", {"vol": 1})):    model = fit_constrained(fit, signs)    print(name.ljust(7), monotone_share(model, valid, "vol", grid, 1), monotone_share(model, valid, "vol", grid, -1))
free    0.0 0.0
vol_up  1.0 0.0

*Check:* for the free model 0.0 of the rows rise all the way (every row has at least one small dip somewhere on the grid), and 0.0 fall. For the constrained model 1.0 of the rows rise: the rule holds for every row. *What to notice:* the average curve of the free model looked nearly right, and not one row obeyed the rule exactly. The rule is a property of each row, and a model without the constraint does not have it.

A level step counts

A constrained model often has flat parts: for a stretch of the grid the prediction does not change. A flat curve obeys both a rising and a falling rule, which is why the check allows a step of zero.

05

A right prior, a wrong prior, no prior

Worked example 4. *Problem:* what does the rule cost in accuracy? *Plan:* fit three models on the fit years: free, with the right rule (vol up) and with the wrong rule (vol down), and score them on the validation and the test years. *Steps:* study.

main.pyPython
result = study(panel)print("baseline", round(result["baseline"], 5))for name in ("free", "vol_up", "vol_down"):    row = result[name]    print(name.ljust(9), round(row["rmse_valid"], 5), round(row["rmse_test"], 5), row["increasing"], row["decreasing"], round(row["share_up"], 2))
baseline 0.05453
free      0.03691 0.05207 False False 0.0
vol_up    0.03692 0.05215 True False 1.0
vol_down  0.03802 0.05286 False True 0.98

*Check:* the free model scores 0.03691 on the validation years and 0.05207 on the test years. The right rule gives 0.03692 and 0.05215: the same, to the fourth decimal. The wrong rule gives 0.03802 and 0.05286, clearly worse on both, and its partial dependence falls (decreasing is True), as the rule forces. The share of rows rising with vol is 0.98 for it, not 0: the rows whose prediction does not depend on volatility at all (flat curves) count as both rising and falling. *What to notice:* a right prior costs nothing and gives a model you can explain; a wrong prior costs accuracy, and the validation error shows it. That is the way to test a prior: fit with and without it, and look at the years the model has not seen.

Only constrain what you are sure of

Reversal is a good example of a feature without a clear direction: rev can predict a bigger move after a big rise or a big fall, so the effect is U-shaped and no sign is right. A constraint on it would hide the signal. Constrain a feature when theory gives a direction, and let the data speak otherwise.

What the real data says56 US stocks; fit before 2011, validation 2011 to 2014, test from 2015
Free model0.03691 / 0.05207validation / test error; partial dependence dips by up to 0.0043
Rising rule on vol0.03692 / 0.05215the same accuracy; 300 of 300 rows rise with vol
Falling rule on vol0.03802 / 0.05286a wrong prior: worse on both
Baseline0.05453the plain average, on the test years

Key takeaways

  • A constraint is knowledge. It tells the model a direction the data cannot be trusted to find; XGBoost builds every tree under the rule.
  • One number per column. The text lists signs in the order of the fitted columns: 1 rising, −1 falling, 0 free.
  • Check every row. A partial dependence can look right on average; the share of rows that obey is the real test.
  • Test the prior. Fit with and without it and compare on unseen years: a right prior costs nothing, a wrong one shows in the error.
Quick check
Your turn. The model is fitted on the columns ["vol", "mom", "rev"] and you want the prediction to fall as rev rises. Which text do you pass?
Pick an answer.
06

What you will build

The lab follows the lecture. Task 1 writes the constraint text and task 2 fits a model under it. Task 3 computes the partial dependence and task 4 tests a curve for monotonicity. Task 5 measures the share of rows that obey the rule. Task 6 compares a free model, a model with a right prior and a model with a wrong prior on the real panel.

Next topic: you now have a model you trust a little more. The next topic, Feature importance: gain versus SHAP, asks what the model learned: which features it used most, and how much each one contributed to a single prediction.

Lab · what's graded

6 tasks · 100 pts
  • Write the rule10 pts
  • Fit under the rule10 pts
  • Partial dependence20 pts
  • Is the curve monotone10 pts
  • Row by row20 pts
  • Right prior, wrong prior, no prior30 pts
Explorer · lab-xg-07
▾ lab-xg-07
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-xg-07$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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