A model with 100 trees, trained on 9,292 stock-months, predicts next month's return with an error of 0.0788. A plain average of the past returns gets 0.0786. This topic builds that model, and then shows why that result is a normal one.
Trees, boosting and the model you are about to fit
This is the first topic of the XGBoost skill, so there is no earlier result to build on. By the end you will be able to fit an XGBoost model on a table of numbers, predict with it, and judge it against the simplest possible forecast. The running example for the whole skill is one table: 56 US stocks, one row per stock and month-end, three numbers known at the end of the month (the features), and the return of the next month (the target).
XGBoost is a library that builds a prediction out of many small decision trees. Start with one tree.
A list of yes/no questions about the features, such as "was last month's return below zero?", that ends in a number: the prediction. Rows that give the same answers get the same prediction, usually the average target of the training rows that ended in the same place.
A tree with a single question is called a stump. Worked example 1. *Problem:* six stocks, made-up numbers, with rev (last month's return), mom (the return of the year before that) and fwd (next month's return). Predict fwd with one question about rev. *Plan:* ask "is rev below zero?", split the rows in two groups, predict the average fwd of each group, and measure how far the predictions are from the truth, compared with predicting the overall average for everyone. *Steps:* below.
print(toy)low = toy["rev"] < 01stump = np.where(low, toy.loc[low, "fwd"].mean(), toy.loc[~low, "fwd"].mean())2print(stump.round(3))print(round(rmse(toy["fwd"], toy["fwd"].mean()), 4), round(rmse(toy["fwd"], stump), 4))
mom rev fwd 0 0.30 -0.08 0.07 1 0.10 0.04 -0.01 2 -0.20 0.06 0.00 3 0.25 -0.02 0.05 4 -0.10 -0.05 0.04 5 0.05 0.03 -0.03 [ 0.053 -0.013 -0.013 0.053 0.053 -0.013] 0.0356 0.0125
- 1One yes/no question splits the rows in two.
- 2Each side predicts its own average.
*Check:* three stocks fell last month and their next month averages 0.053, the other three average -0.013, so the prediction is one of those two numbers for every row. The error drops from 0.0356 (everyone gets the overall average) to 0.0125. *What to notice:* a stump already uses the feature, and the question is a guess that came from reading the table. XGBoost searches for the best question by trying many thresholds and keeping the one that lowers the error most.
Building many small trees one after another. Each new tree is fitted to what the earlier trees still get wrong (the leftovers, called residuals), and its prediction is added to the total with a small weight called the learning rate.
Worked example 2. *Problem:* improve the stump of example 1. *Plan:* compute the leftovers fwd - stump, fit a second stump to the leftovers with a question about mom, and add its prediction to the first. *Steps:* leftovers, second stump, sum, error.
left = toy["fwd"] - stump1high = toy["mom"] > 0.2second = np.where(high, left[high].mean(), left[~high].mean())total = stump + second2print(left.round(3).tolist())print(second.round(3).tolist())print(round(rmse(toy["fwd"], stump), 4), round(rmse(toy["fwd"], total), 4))
[0.017, 0.003, 0.013, -0.003, -0.013, -0.017] [0.007, -0.003, -0.003, 0.007, -0.003, -0.003] 0.0125 0.0115
- 1The second tree is trained on the leftovers, not on fwd.
- 2The prediction is a sum of trees.
*Check:* the first stump's error 0.0125 falls to 0.0115 after the second tree, and the numbers in the second list are small because the leftovers are small. *What to notice:* each tree alone is weak, and their sum is better. This is boosting in full. XGBoost does exactly this with hundreds of trees, a smarter search for the questions and a learning rate below 1, so that no single tree decides too much. The next topic builds the loop yourself; here you only use the library.
Test on the future, not on a shuffle
A model that is judged on the rows it learned from always looks good, because it can remember them. So the data is split in two: a training part the model learns from, and a test part it has never seen. For stock data the split is by date: you train on the past and test on the future, because that is the only order in which a forecast is ever used. A random shuffle would put the same month, with the same market-wide move, into both parts.
Worked example 3. *Problem:* split the real panel before 2015. *Plan:* turn the cut-off into a timestamp, make one mask for the dates before it and one for the dates on or after it, and index the panel with each mask. *Steps:* below. The panel is built by the given build_panel from data/close.csv.
panel = build_panel(load_close())cutoff = pd.Timestamp("2015-01-01")train = panel[panel["date"] < cutoff]1test = panel[panel["date"] >= cutoff]2print(panel.shape, train.shape, test.shape)print(train["date"].max().date(), test["date"].min().date())
(17075, 6) (9292, 6) (7783, 6) 2014-12-31 2015-01-31
- 1Strictly before: the cut-off month belongs to the test part.
- 2On or after.
*Check:* 9292 + 7783 = 17075, so no row is lost or counted twice, and the last training date is 2014-12-31 while the first test date is 2015-01-31. *What to notice:* the simple method, train_test_split with a shuffle, does not look wrong, it just answers a different question. Here the panel has 307 months, 139 of them in the test part.
The target of the last training row (December 2014) is the return of January 2015, which is also the month that the first test row has just lived through. So the two parts touch by one month. For monthly data that is a small effect, and a later topic of this skill (time-aware validation) shows how to leave a gap, called an embargo, when it matters.
Three lines: build, fit, predict
Every XGBoost model in scikit-learn style has the same three moves. Build the model object and set its choices, fit it on the features and the target of the training rows, and predict for the features of any rows. The features go in as a table with one column per feature, and the target as one column of numbers.
- 1Build
xgb.XGBRegressor(n_estimators=100, max_depth=3, learning_rate=0.05, ...)creates a model with the number of trees, the depth of each tree and the weight of each tree. Nothing is learned yet. - 2Fit
model.fit(train[FEATURES], train["fwd"])finds the trees. Select the feature columns by name: the target and the ticker must not go in. - 3Predict
model.predict(frame[FEATURES])returns one number per row, in the order of the rows.
Worked example 4. *Problem:* fit on the training part and predict the test part. *Plan:* use the settings of the steps above, plus tree_method="hist" (the fast way to look for questions, explained in the last topic of the skill), n_jobs=1 and random_state=0 so that every run gives the same model. *Steps:* build, fit, predict, look at the answer.
model = xgb.XGBRegressor(n_estimators=100, max_depth=3, learning_rate=0.05, tree_method="hist", n_jobs=1, random_state=0)1model.fit(train[FEATURES], train["fwd"])2pred = model.predict(test[FEATURES])3print(type(pred).__name__, pred.shape, pred.dtype)print(pred[:4].round(4))print(model.get_booster().num_boosted_rounds())
ndarray (7783,) float32 [0.0078 0.009 0.0069 0.0011] 100
- 1Build: only the choices are set.
- 2Fit: the trees are found here.
- 3Predict: one number per test row.
*Check:* there is one prediction per test row (7783), the first four are small numbers around one percent, and the booster holds 100 trees. *What to notice:* the model answers in the unit of the target, a monthly return. Now the common mistake: passing the whole table to fit.
try: xgb.XGBRegressor(n_estimators=5).fit(train, train["fwd"])except ValueError as error: print(str(error).splitlines()[0])
DataFrame.dtypes for data must be int, float, bool or category. When categorical type is supplied, the experimental DMatrix parameter`enable_categorical` must be set to `True`. Invalid columns:date: datetime64[us], ticker: str
The message is about the type of the columns: the ticker is text, and a model cannot split on text. Even if the ticker were removed, fwd itself would still be among the columns, and a model that sees the answer looks brilliant for the wrong reason. Always pick the feature columns by name.
- CallWhat it does
- xgb.XGBRegressor(...)Creates a model; the choices are arguments.nothing is learned
- model.fit(X, y)Learns the trees; returns the model.X holds the features only
- model.predict(X)One prediction per row.same columns as fit
- model.get_params()The choices, as a dictionary.shows the defaults too
- model.feature_importances_How much each feature was used.sums to 1
Is it better than the average?
A number that says "0.0788" means nothing alone. A forecast is only worth something if it beats the simplest forecast you could have made, and for returns that is the plain average of the training target, the same prediction for every stock. So there are always two scores side by side. The first is the size of the typical error.
Root mean squared error: take the error of each row (truth minus prediction), square it so that the sign disappears, average the squares, and take the square root so that the result is back in the unit of the target. For a monthly return, 0.08 means a typical miss of 8 percentage points.
Worked example 5. *Problem:* the true returns are 0.02, -0.04 and 0.06 and a model predicts 0.01, -0.01 and 0.02. What is the RMSE, and what would the average (0.0133) have scored? *Plan:* subtract, square, average, square root, for both predictions. *Steps:* below.
y = np.array([0.02, -0.04, 0.06])guess = np.array([0.01, -0.01, 0.02])print(((y - guess) ** 2).round(5).tolist())print(round(rmse(y, guess), 4), round(rmse(y, y.mean()), 4))
[0.0001, 0.0009, 0.0016] 0.0294 0.0411
*Check:* the squares are 0.0001, 0.0009 and 0.0016, their mean is 0.00087 and its square root is 0.0294; the average scores 0.0411. *What to notice:* here the model is better than the average, because its errors are smaller. A single number as the prediction (the average) works in the same function, because numpy repeats it for every row.
The second score asks a question that fits a stock-picking use better: does the model rank the stocks of a month correctly? A portfolio does not need the exact return, it needs the winners above the losers.
For one date, replace the predictions and the true returns of the stocks by their ranks (1 for the smallest) and take the ordinary correlation of the two lists of ranks: this is the Spearman correlation. Average it over the dates. +1 is a perfect ranking, 0 is no skill, and for monthly stock returns 0.02 to 0.05 is already useful.
Worked example 6. *Problem:* four stocks on one date, true returns 1, 2, 3 and 100 (percent) and predictions 1, 2, 3 and 4. What is the rank IC? *Plan:* rank both lists and correlate the ranks. *Steps:* rank, correlate, compare with the correlation of the raw values.
truth = pd.Series([1.0, 2.0, 3.0, 100.0])score = pd.Series([1.0, 2.0, 3.0, 4.0])print(truth.rank().tolist(), score.rank().tolist())print(round(score.corr(truth, method="spearman"), 3), round(score.corr(truth), 3))
[1.0, 2.0, 3.0, 4.0] [1.0, 2.0, 3.0, 4.0] 1.0 0.785
*Check:* the ranks are the same list, so the rank IC is 1.0, a perfect ordering. *What to notice:* the ordinary correlation of the raw values is only 0.785, because the huge 100 pulls it away from a straight line. Ranks ignore sizes and look at order only. The rank IC is computed inside each date and then averaged, because a market-wide move would otherwise look like skill: if every stock rises in one month and the model predicted a high month, that is not a ranking.
The honest comparison
Worked example 7. *Problem:* judge the model of example 4 on the test part. *Plan:* score the model's predictions, score the training average, and compute the rank IC; then do it again with 10 and 500 trees, to see what more trees do. *Steps:* below.
for n in (10, 100, 500):1 model = fit_model(train, n_trees=n) seen = rmse(train["fwd"], predict(model, train))2 new = rmse(test["fwd"], predict(model, test))3 print(n, round(seen, 4), round(new, 4), round(mean_rank_ic(test, predict(model, test)), 3))print("baseline", round(rmse(test["fwd"], train["fwd"].mean()), 4))
10 0.0799 0.0786 -0.003 100 0.0776 0.0788 -0.01 500 0.0737 0.0797 -0.026 baseline 0.0786
- 1The same function, only the number of trees changes.
- 2The error on rows the model learned from.
- 3The error on rows it has not seen.
*Check:* with more trees the error on the training rows keeps falling (0.0799, 0.0776, 0.0737), and the error on new rows rises (0.0786, 0.0788, 0.0797) until it is above the baseline 0.0786. The rank IC also falls below zero. *What to notice:* the model is learning the noise of the training months, which is called overfitting. Three features describe very little of a stock's next month, and a tree model that is allowed to be complex will find patterns that do not repeat. The skill ahead is largely about making the model simple enough to keep what is real: depth, learning rate, regularisation and early stopping.
That is the honest result: three features do not give a better forecast of next month's return than a constant. This is normal for stock returns, which are mostly noise, and it is why every number in this skill is judged against a baseline on data from after the training period. A model that scores well on the rows it learned from tells you nothing.
What you will build
The lab follows the lecture. Task 1 splits the panel by date. Task 2 fits the XGBoost model, task 3 predicts with it. Task 4 scores a forecast with the RMSE and task 5 with the rank IC. Task 6 runs the whole experiment on the real panel and compares the model with the average.
Next topic: you used a boosting library as a black box. The next topic, Gradient boosting intuition, opens the box: the leftover-fitting idea of example 2 becomes a loop of about 30 lines that you write yourself and compare with XGBoost.
Lab · what's graded
6 tasks · 100 pts- Split by date10 pts
- Fit the model20 pts
- Predict10 pts
- Score by RMSE10 pts
- Score by rank IC20 pts
- The honest comparison30 pts