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.
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.
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.
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.
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]
- 1One number per column, in the order of the columns.
- 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.
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.
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
- 1The mean prediction when every row has this volatility.
- 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.
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.
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 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.
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.
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.
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.
rev rises. Which text do you pass?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