In 2005 every company report in the table is missing. By 2025 only 26% of the profit margins are. XGBoost has a rule for rows with a hole, and you can read it from the tree. The harder questions are the ones before it: what the hole means, and what you may fill it with.
Holes in the table
Where we are. The last topic made the model plainer with penalties and early stopping, always on the same three price features. Real projects add other columns, and other columns have holes. This topic adds two numbers from the quarterly reports of each company, margin (net income divided by revenue) and leverage (liabilities divided by assets), and a word, the sector.
A report only counts from the day it was filed, not from the end of the quarter it describes: the table must not use news that nobody had yet. So each month-end gets the latest report filed by then, and a company with no report yet has a hole. A hole also appears when a company did not report that number.
An entry with no number, written NaN in pandas. It is not zero: zero is a value. A missing value says "we do not know", and often the reason it is unknown tells something (a company that has not filed yet is a different kind of company from one that has).
Worked example 1. *Problem:* how many holes are there, and when? *Plan:* measure the share of missing values in each column, year by year, with missing_share. *Steps:* take the rows of a year and ask for the two report columns.
panel = build_panel(load_close(), load_quarterly())for year in (2005, 2010, 2015, 2020, 2025): rows = panel[panel["date"].dt.year == year]1 print(year, {name: round(share, 2) for name, share in missing_share(rows, FUNDAMENTALS).items()})2
2005 {'margin': 1.0, 'leverage': 1.0}
2010 {'margin': 0.85, 'leverage': 0.57}
2015 {'margin': 0.85, 'leverage': 0.4}
2020 {'margin': 0.28, 'leverage': 0.33}
2025 {'margin': 0.26, 'leverage': 0.32}- 1The rows of one year.
- 2The share of holes in each report column.
*Check:* in 2005 both columns are 1.0 (no report is in the data yet); in 2010 0.85 and 0.57; in 2020 0.28 and 0.33; in 2025 0.26 and 0.32. Over all years 72 % of the margins are missing. *What to notice:* the holes are not scattered at random: they sit mostly in the early years. A model trained on years before 2015 sees mostly holes (94 % of the margins) and is then used on years where 46 % are holes. The pattern of the holes is itself something the model has to cope with.
Let the tree decide
XGBoost accepts NaN in the features. During training, every question of every tree is tried twice, with the rows that have a hole sent to the yes side and to the no side, and the way that lowers the error more is kept. That way is the default direction of the question. At prediction time a row with a hole simply follows it.
Worked example 2. *Problem:* eight made-up stocks, in which the ones with a missing margin move much more than the others. What does the tree do? *Plan:* fit one tree of depth 2 with a learning rate of 1, print it, and read the direction of the holes with missing_directions. *Steps:* below.
toy = pd.DataFrame({"vol": [0.05, 0.06, 0.07, 0.08, 0.09, 0.10, 0.11, 0.12], "margin": [0.20, 0.15, np.nan, 0.18, np.nan, 0.10, np.nan, 0.12], "move": [0.02, 0.03, 0.12, 0.03, 0.11, 0.04, 0.13, 0.05]})tree = xgb.XGBRegressor(n_estimators=1, max_depth=2, learning_rate=1.0, tree_method="exact", base_score=float(toy["move"].mean()), min_child_weight=0, n_jobs=1, random_state=0)tree.fit(toy[["vol", "margin"]], toy["move"])print(tree.get_booster().get_dump()[0])1print(missing_directions(tree))2print(round(toy["move"].mean(), 4), np.round(tree.predict(toy[["vol", "margin"]]).astype(float), 3).tolist())
0:[margin<0.400000989] yes=1,no=2,missing=2
1:[vol<0.109999999] yes=3,no=4,missing=3
3:leaf=-0.0289999973
4:leaf=-0.00812499784
2:leaf=0.0403124988
[('margin', 'no'), ('vol', 'yes')]
0.0662 [0.037, 0.037, 0.107, 0.037, 0.107, 0.037, 0.107, 0.058]- 1missing=2 names the child that rows with a hole go to.
- 2The same information as a list.
*Check:* the first question is "is margin < 0.4?" (every real margin is below 0.4, so "yes" means "there is a number"), and the rows with a hole go to the *no* child, a leaf that answers +0.0403 on top of the average 0.0662. The prediction for the three stocks with a hole is 0.107, for the others 0.037 or 0.058. The second question, on vol, sends its holes to the yes side, but no row in the table reaches it with a hole. *What to notice:* the tree has learned that "no margin" predicts a bigger move, without any filling and without being told. The simple method, filling the margin with an average, would have hidden the difference.
Now the real panel. A tree fitted on 2012 to 2014, where the reports are present more often, has seven questions in its first tree.
recent = split_by_date(panel, "2012-01-01", "2015-01-01")model = fit_features(recent, FEATURES + FUNDAMENTALS)print(missing_directions(model))
[('vol', 'no'), ('vol', 'no'), ('leverage', 'yes'), ('margin', 'no'), ('leverage', 'no'), ('rev', 'no'), ('rev', 'no')]*Check:* each pair is a feature and the side its holes take: ('leverage', 'yes'), ('margin', 'no'), ('leverage', 'no'), and so on. *What to notice:* the directions differ from question to question. There is no single rule such as "holes are small": each question learned its own.
Filling the holes yourself
Sometimes you have to fill the holes: other models, other libraries, or you may want one rule for everyone. The usual choice is the median of the column, a typical value that a few extreme numbers cannot move. The one rule that matters: the median must come from the training rows only. The test years are the future; their median is information you do not have when you forecast.
Worked example 3. *Problem:* a training column is 1, nan, 3, 100 and a test column is nan, 5. Fill both. *Plan:* the median of the numbers that exist in the training column is 3 (the middle of 1, 3, 100); use it in both frames. *Steps:* call fill_median.
a = pd.DataFrame({"x": [1.0, np.nan, 3.0, 100.0]})b = pd.DataFrame({"x": [np.nan, 5.0]})filled_a, filled_b = fill_median(a, b, ["x"])1print(filled_a["x"].tolist(), filled_b["x"].tolist())print(b["x"].median(), a["x"].mean())
[1.0, 3.0, 3.0, 100.0] [3.0, 5.0] 5.0 34.666666666666664
- 1One median, learned on the training rows, used for both frames.
*Check:* the training hole becomes 3.0 and the test hole becomes 3.0 as well, not 5.0 (the test median) and not 34.7 (the training mean, pulled up by the 100). *What to notice:* two traps in one example. The median of the test column would leak the future, and the mean would be dragged by one extreme number.
Filling hides which values were holes, and we saw that a hole can mean something. The fix is a flag: a new column that is 1 where the value was missing and 0 otherwise. Worked example 4. *Problem:* keep the information that the margin was missing. *Plan:* make the flags with add_flags *before* filling, then fill. *Steps:* flags first, fill second.
flagged = add_flags(train, FUNDAMENTALS)filled, _ = fill_median(flagged, flagged, FUNDAMENTALS)print(list(filled.columns[-2:]), int(filled["margin_missing"].sum()), round(filled["margin"].isna().mean(), 2))print(train.groupby(filled["margin_missing"])["move"].mean().round(4).to_dict())
['margin_missing', 'leverage_missing'] 8719 0.0
{0: 0.0529, 1: 0.0571}*Check:* the two new columns are margin_missing and leverage_missing, 8,719 rows of the training years have a missing margin (94 %), and after filling there are no holes left in margin, but the flag still says where they were. The next-month move averages 0.0529 for rows with a report and 0.0571 for rows without one (in the training years): a small difference that the flag lets a tree use. *What to notice:* the order matters. Flagging after filling gives a column of zeros.
A column of categories
A sector is a word, not a number, and a tree cannot split on a word. You could turn it into one 0/1 column per sector. XGBoost can also take the word as a categorical column: it reads each category as an integer code and can split by *groups* of categories ("tech and health versus the rest"). For that the column must be a pandas Categorical, and enable_categorical=True must be set.
Worked example 5. *Problem:* make the sector a categorical column the same way for the training and the test years. *Plan:* take the list of sectors from the training rows, sorted, and build the column in both frames from that one list, so that each sector has the same code everywhere. *Steps:* below.
categories = sorted(train["sector"].unique())1as_cat = to_category(train, categories)print(categories)print(as_cat["sector"].cat.codes.head(3).tolist(), train["sector"].head(3).tolist())print(to_category(test, categories)["sector"].cat.categories.tolist() == categories)
['discretionary', 'energy', 'financials', 'health', 'industrials', 'staples', 'tech', 'telecom_utilities'] [6, 3, 3] ['tech', 'health', 'health'] True
- 1The list comes from the training rows and is reused for every frame.
*Check:* eight sectors, alphabetical, from discretionary to telecom_utilities; the first three rows are tech, health and health, with the codes 6, 3 and 3: a code is the position of the sector in the list. The test frame has exactly the same categories. *What to notice:* the codes mean nothing alone; they refer to the list. A frame built with its own list could give tech the code 2 in one place and 3 in another.
Five ways to feed the same trees
Worked example 6. *Problem:* does any of this help? *Plan:* train on the years before 2015 and score on 2015 and later, with the same 100 trees of depth 3, in five ways: the three price features only; adding the two report columns with holes left; filling them with the median; filling them and adding flags; and holes left plus the sector. *Steps:* study.
result = study(panel)for name, score in result["scores"].items(): print(name.ljust(13), round(score, 5))print("baseline ", round(result["baseline"], 5))
base 0.05204 native 0.05222 median 0.05215 median_flags 0.05216 sector 0.05188 baseline 0.05439
*Check:* base 0.05204, native 0.05222, median 0.05215, median_flags 0.05216, sector 0.05188, and the plain average 0.05439. *What to notice:* every version beats the average by about 4 to 5 %, and the five differ by less than 0.0004. The report columns, 94 % empty in training, add nothing (0.05222 is slightly worse than the 0.05204 of the price features alone). The sector helps by a hair. The honest reading: with these holes the extra columns hardly matter, and the way of treating the holes matters even less; a difference in the fourth decimal is smaller than the change you would see by shifting the cut-off year.
Five strategies, one test period, differences of 0.0002: that is not a ranking. Before you choose a strategy because it scored best, ask how much the score moves when you change the split by a year.
What you will build
The lab follows the lecture. Task 1 measures the holes and task 2 fills them with the training median. Task 3 flags them and task 4 makes the sector a categorical column. Task 5 fits the model on a chosen list of columns, and task 6 reads where its first tree sends the holes. Task 7 compares five ways of feeding the same trees.
Next topic: so far the model predicted a number, the size of a move. The next topic, Objectives: regression and ranking, changes what the model optimises: the loss is written out, a custom one is plugged in, and a ranking objective orders the stocks of each month.
Lab · what's graded
7 tasks · 100 pts- Measure the holes10 pts
- Fill with the training median15 pts
- Flag the holes10 pts
- A categorical sector10 pts
- Fit on chosen columns15 pts
- Where the holes go15 pts
- Five ways to feed the trees25 pts