TExcelTAD
Home › ML Projects: 15 End-to-End Builds › Project 1: House Price Prediction

Project 1: House Price Prediction

A property portal wants an automatic valuation: a seller enters the facts about a flat or house and gets an estimated price with a range, so that nobody mistakes a single number for a promise. The model will value homes for sale next year using sales recorded up to this year. The level is beginner; the main skills are regression on tabular data, a time-based split, a model of the log price, prediction intervals that are checked rather than assumed, an error analysis by price band and district, and a small valuation service.

You built a house-price regressor before, in the algorithms mini project: one snapshot of houses, random cross-validation, LightGBM against a forest and a linear model. That setting has no calendar. Real sales do: prices drift with the market, and a model is always used on dates after the ones it learned from. This project is about what changes when time enters: how to split, why trees cannot follow a rising market on their own, and how wide the honest range around an estimate is.

Goal and success criteria

Criterion
Use value homes sold in the year after the training data ends
Primary metric median absolute percentage error (MdAPE) of the point estimate; MAE in thousands for the report (regression metrics)
Range an 80 % prediction interval whose coverage on the test year is between 75 % and 85 %
Baseline district median price per square metre times the area, from training sales
Target MdAPE at least 25 % lower than the baseline's on the test year
Split train 2019-2022, validation 2023, test 2024 (used once)

The data

Real sales come from land registries or notary records (often public, with terms of use that restrict bulk reuse) or from listing sites (licensed, and listing prices are not sale prices). An address plus a price identifies a person's home, so a portal must publish aggregates, not individual records, and follow its registry's licence; see privacy, consent and licensing.

Here a generator produces 3,000 sales from January 2019 to December 2024 in eight districts. A home's price is its district's price level per square metre times its area, adjusted for condition, age and distance to the centre, times a market index that rises steadily by about 6.7 % a year, times about 15 % random noise. Real markets also change pace and sometimes fall; a steady trend keeps this first project readable, and the extensions say what to do when the trend breaks.

Step 1: explore with the calendar in mind

python · try it yourself
import numpy as np
import pandas as pd

def make_sales(n=3000, seed=0):
    rng = np.random.default_rng(seed)
    names = ["old town", "harbour", "university", "riverside", "north hills", "airport", "east end", "garden city"]
    level = dict(zip(names, [5.2, 4.4, 3.6, 3.9, 3.1, 2.1, 2.4, 2.8]))          # k EUR per m2 in 2019
    month = rng.integers(0, 72, n)                                              # 0 = Jan 2019
    district = rng.choice(names, n, p=[0.08, 0.1, 0.14, 0.12, 0.16, 0.12, 0.16, 0.12])
    area = np.clip(np.round(rng.lognormal(4.3, 0.35, n)), 25, 250)
    built = rng.integers(1950, 2023, n)
    cond = rng.choice(["poor", "fair", "good", "renovated"], n, p=[0.15, 0.35, 0.35, 0.15])
    dist = np.round(rng.gamma(2.0, 2.5, n), 1)
    years = month / 12
    log_index = 0.065 * years                                                   # the market rises steadily
    log_price = (np.log([level[d] for d in district]) + np.log(area) + log_index
                 + pd.Series(cond).map({"poor": -0.15, "fair": 0, "good": 0.08, "renovated": 0.15}).to_numpy()
                 - 0.002 * np.maximum(2000 - built, 0) - 0.02 * dist + rng.normal(0, 0.15, n))
    df = pd.DataFrame({"sale_date": pd.to_datetime("2019-01-01") + pd.to_timedelta(month * 30.44 + rng.integers(0, 28, n), unit="D"),
                       "district": district, "area_m2": area, "rooms": np.clip(np.round(area / 28 + rng.normal(0, 0.7, n)), 1, 8),
                       "built": built, "condition": cond, "dist_km": dist, "price_k": np.round(np.exp(log_price), 1)})
    return df.sort_values("sale_date", ignore_index=True)

df = make_sales()
df["year"] = df.sale_date.dt.year
print(df.head(3).to_string(index=False))
print("\nsales per year:", df.year.value_counts().sort_index().to_dict())
by_year = df.groupby("year").apply(lambda g: (g.price_k / g.area_m2).median(), include_groups=False)
print("median price per m2 (k EUR) by year:", by_year.round(2).to_dict())
print("growth year on year:", (by_year.pct_change().dropna() * 100).round(1).to_dict())
ppm = (df.price_k / df.area_m2).groupby(df.district).median().sort_values()
print("\nmedian price per m2 by district:", ppm.round(2).to_dict())
skew = lambda s: float(((s - s.mean()) ** 3).mean() / s.std() ** 3)
print(f"\nskewness: price {skew(df.price_k):.2f}, log price {skew(np.log(df.price_k)):.2f}")
 sale_date    district  area_m2  rooms  built condition  dist_km  price_k  year
2019-01-01     airport     66.0    2.0   1950      good      1.0    133.6  2019
2019-01-01 garden city     77.0    4.0   1972      good      3.6    140.6  2019
2019-01-02    east end    142.0    6.0   1976      fair      2.6    286.2  2019

sales per year: {2019: 479, 2020: 486, 2021: 470, 2022: 522, 2023: 510, 2024: 533}
median price per m2 (k EUR) by year: {2019: 3.02, 2020: 3.2, 2021: 3.41, 2022: 3.55, 2023: 3.92, 2024: 4.07}
growth year on year: {2020: 5.9, 2021: 6.7, 2022: 4.2, 2023: 10.4, 2024: 3.7}

median price per m2 by district: {'airport': 2.31, 'east end': 2.61, 'garden city': 3.02, 'north hills': 3.42, 'university': 3.96, 'riverside': 4.16, 'harbour': 4.86, 'old town': 5.54}

skewness: price 1.62, log price -0.06

Three things matter for the design. Prices rise every year: the median price per square metre goes from 3.02 k to 4.07 k EUR in six years. The year-on-year growth jumps around (4.2 % to 10.4 %) because each year's median also depends on which homes happened to sell, which is why the index below is fitted on all sales at once, not read off yearly medians. Districts differ by a factor of about 2.4 (airport 2.31 k against old town 5.54 k per square metre), so district is the strongest single feature. And prices are right-skewed (skewness 1.62) while log prices are almost symmetric (−0.06): errors on a log scale are percentages, which is how buyers and sellers think about a valuation ("10 % too high"), so the models learn the log price.

Step 2: split by time, then a baseline

train 2019-2022 val 2023 test 2024 fit 2019-2021 width: 2022 fit 2019-2022 check: 2023 2019202320242025

The model will value next year's sales, so it is evaluated that way: fit on the past, score on the following year (split strategies, time-series backtesting). A random split would let 2024 sales teach the model about 2024 prices and report an error the portal will never see. The leakage lab shows the effect in its purest form, a random walk scored with a random split:

Leaky: test rows shape a step200 daysshufflesplit 80/20kNN on dayHonest: test rows unseen until scoring200 dayssplit by timefit 1–160test 161–200Neighbouring days are nearly equal, so ashuffled test day sits between trainingdays: the model interpolates, it never forecasts.Validation R²−1−0.500.510.99leaky−7.16honest−0.98new databars stop at −1

The baseline is what an estate agent does on the back of an envelope: the district's median price per square metre in the training years, times the area. Then three LightGBM models (LightGBM) on the log price (why log): without any date, with the sale month as a feature, and with a time-adjusted target. The last one divides every price by a market index fitted on the training years (a straight line in log price per square metre, after removing district levels), lets the trees learn the rest, and multiplies by the extrapolated index at prediction time. Trees predict constants inside each leaf, so they cannot continue a trend past the last month they saw; the index does that job explicitly.

python · try it yourself
import numpy as np
import pandas as pd
from lightgbm import LGBMRegressor

def make_sales(n=3000, seed=0):
    rng = np.random.default_rng(seed)
    names = ["old town", "harbour", "university", "riverside", "north hills", "airport", "east end", "garden city"]
    level = dict(zip(names, [5.2, 4.4, 3.6, 3.9, 3.1, 2.1, 2.4, 2.8]))
    month = rng.integers(0, 72, n)
    district = rng.choice(names, n, p=[0.08, 0.1, 0.14, 0.12, 0.16, 0.12, 0.16, 0.12])
    area = np.clip(np.round(rng.lognormal(4.3, 0.35, n)), 25, 250)
    built = rng.integers(1950, 2023, n)
    cond = rng.choice(["poor", "fair", "good", "renovated"], n, p=[0.15, 0.35, 0.35, 0.15])
    dist = np.round(rng.gamma(2.0, 2.5, n), 1)
    years = month / 12
    log_index = 0.065 * years
    log_price = (np.log([level[d] for d in district]) + np.log(area) + log_index
                 + pd.Series(cond).map({"poor": -0.15, "fair": 0, "good": 0.08, "renovated": 0.15}).to_numpy()
                 - 0.002 * np.maximum(2000 - built, 0) - 0.02 * dist + rng.normal(0, 0.15, n))
    df = pd.DataFrame({"sale_date": pd.to_datetime("2019-01-01") + pd.to_timedelta(month * 30.44 + rng.integers(0, 28, n), unit="D"),
                       "district": district, "area_m2": area, "rooms": np.clip(np.round(area / 28 + rng.normal(0, 0.7, n)), 1, 8),
                       "built": built, "condition": cond, "dist_km": dist, "price_k": np.round(np.exp(log_price), 1)})
    return df.sort_values("sale_date", ignore_index=True)

FEATURES = ["district", "area_m2", "rooms", "built", "condition", "dist_km"]

def prepare(df):
    X = df[FEATURES].copy()
    X["district"] = X["district"].astype("category")
    X["condition"] = X["condition"].map({"poor": 0, "fair": 1, "good": 2, "renovated": 3})
    X["months"] = (df.sale_date.dt.year - 2019) * 12 + df.sale_date.dt.month - 1
    return X

def fit_index(X, y_log):
    """Market index: a line through log(price per m2) over time, after removing district levels."""
    r = y_log - np.log(X.area_m2)
    r = r - r.groupby(X.district, observed=True).transform("mean")
    slope, intercept = np.polyfit(X.months, r, 1)
    return lambda months: intercept + slope * months, slope

def report(name, y, pred):
    ape = np.abs(pred - y) / y
    print(f"{name:26} MAE {np.mean(np.abs(pred - y)):6.1f} k  MdAPE {np.median(ape):5.1%}  bias {np.mean(pred / y - 1):+6.1%}")

df = make_sales()
X, y = prepare(df), df.price_k.to_numpy()
year = df.sale_date.dt.year.to_numpy()
tr, va = year <= 2022, year == 2023
print(f"train {tr.sum()} sales (2019-2022), validation {va.sum()} sales (2023)\n")

ppm = (df.price_k / df.area_m2)[tr].groupby(df.district[tr]).median()
report("baseline: district m2", y[va], df.district[va].map(ppm).to_numpy() * df.area_m2[va].to_numpy())

gbm = lambda: LGBMRegressor(n_estimators=400, learning_rate=0.05, num_leaves=15, random_state=0, verbose=-1)
no_time = FEATURES
m = gbm().fit(X.loc[tr, no_time], np.log(y[tr]))
report("LightGBM, no date", y[va], np.exp(m.predict(X.loc[va, no_time])))
m = gbm().fit(X[tr], np.log(y[tr]))
report("LightGBM, month feature", y[va], np.exp(m.predict(X[va])))

index, slope = fit_index(X[tr], np.log(y[tr]))
m = gbm().fit(X.loc[tr, no_time], np.log(y[tr]) - index(X.months[tr]))
report("LightGBM, time-adjusted", y[va], np.exp(m.predict(X.loc[va, no_time]) + index(X.months[va])))
print(f"\nfitted index growth: {np.expm1(12 * slope):.1%} a year (the generator: 6.7 %)")

print("\ntwo years ahead: fit 2019-2021, score 2023 (the service values homes up to two years out)")
tr2 = year <= 2021
m = gbm().fit(X[tr2], np.log(y[tr2]))
report("LightGBM, month feature", y[va], np.exp(m.predict(X[va])))
index2, _ = fit_index(X[tr2], np.log(y[tr2]))
m = gbm().fit(X.loc[tr2, no_time], np.log(y[tr2]) - index2(X.months[tr2]))
report("LightGBM, time-adjusted", y[va], np.exp(m.predict(X.loc[va, no_time]) + index2(X.months[va])))
train 1957 sales (2019-2022), validation 510 sales (2023)

baseline: district m2      MAE   62.9 k  MdAPE 17.2%  bias -13.1%
LightGBM, no date          MAE   58.3 k  MdAPE 15.3%  bias -14.2%
LightGBM, month feature    MAE   41.7 k  MdAPE 10.7%  bias  +0.5%
LightGBM, time-adjusted    MAE   41.2 k  MdAPE 10.4%  bias  +2.1%

fitted index growth: 7.1% a year (the generator: 6.7 %)

two years ahead: fit 2019-2021, score 2023 (the service values homes up to two years out)
LightGBM, month feature    MAE   55.5 k  MdAPE 14.5%  bias -11.8%
LightGBM, time-adjusted    MAE   42.9 k  MdAPE 11.0%  bias  +1.0%

What the table says, all measured on the 510 sales of 2023:

  • The baseline is 13.1 % too low on average: it uses 2019-2022 prices for 2023 homes. LightGBM without a date has the same problem (−14.2 %); better features do not fix a model that does not know prices have moved.
  • One year ahead, the month feature and the time-adjusted target are close (MdAPE 10.7 % and 10.4 %). The month-feature trees put every 2023 sale into the leaves for late 2022, which is only a few months out of date.
  • Two years ahead the difference is plain: the month-feature model is 11.8 % too low (MdAPE 14.5 %), because the trees still return late-2021 prices, while the time-adjusted model stays near zero bias (MdAPE 11.0 %). The fitted index grows 7.1 % a year against the generator's 6.7 %, close enough.

The service will value homes up to two years after its last training sale, so the time-adjusted model is chosen. It carries a risk the other does not: it assumes the trend continues. That is a statement the write-up must make, and the reason the service in Step 5 has an expiry date.

Step 3: a range, and a check that it holds

A point estimate alone invites false precision. The portal shows an 80 % range. Two ways to get one (quantile loss in boosting, calibration of uncertainty):

  • Quantile regression: train two more LightGBM models with the quantile (pinball) loss for the 10th and 90th percentiles.
  • Conformal-style residual interval: take the errors the model makes one year ahead (fit on 2019-2021, predict 2022), and use their 10th and 90th percentiles in log space as the band around every future estimate. The range is a percentage, so it is wider in euros for an expensive home. This needs no assumption about the error's shape, only that next year's errors resemble last year's.

Both are checked on 2023, data neither has seen. Coverage is the share of 2023 prices inside the range; the target is 80 %.

python · try it yourself
import numpy as np
import pandas as pd
from lightgbm import LGBMRegressor

def make_sales(n=3000, seed=0):
    rng = np.random.default_rng(seed)
    names = ["old town", "harbour", "university", "riverside", "north hills", "airport", "east end", "garden city"]
    level = dict(zip(names, [5.2, 4.4, 3.6, 3.9, 3.1, 2.1, 2.4, 2.8]))
    month = rng.integers(0, 72, n)
    district = rng.choice(names, n, p=[0.08, 0.1, 0.14, 0.12, 0.16, 0.12, 0.16, 0.12])
    area = np.clip(np.round(rng.lognormal(4.3, 0.35, n)), 25, 250)
    built = rng.integers(1950, 2023, n)
    cond = rng.choice(["poor", "fair", "good", "renovated"], n, p=[0.15, 0.35, 0.35, 0.15])
    dist = np.round(rng.gamma(2.0, 2.5, n), 1)
    years = month / 12
    log_index = 0.065 * years
    log_price = (np.log([level[d] for d in district]) + np.log(area) + log_index
                 + pd.Series(cond).map({"poor": -0.15, "fair": 0, "good": 0.08, "renovated": 0.15}).to_numpy()
                 - 0.002 * np.maximum(2000 - built, 0) - 0.02 * dist + rng.normal(0, 0.15, n))
    df = pd.DataFrame({"sale_date": pd.to_datetime("2019-01-01") + pd.to_timedelta(month * 30.44 + rng.integers(0, 28, n), unit="D"),
                       "district": district, "area_m2": area, "rooms": np.clip(np.round(area / 28 + rng.normal(0, 0.7, n)), 1, 8),
                       "built": built, "condition": cond, "dist_km": dist, "price_k": np.round(np.exp(log_price), 1)})
    return df.sort_values("sale_date", ignore_index=True)

FEATURES = ["district", "area_m2", "rooms", "built", "condition", "dist_km"]

def prepare(df):
    X = df[FEATURES].copy()
    X["district"] = X["district"].astype("category")
    X["condition"] = X["condition"].map({"poor": 0, "fair": 1, "good": 2, "renovated": 3})
    months = (df.sale_date.dt.year - 2019) * 12 + df.sale_date.dt.month - 1
    return X, months.to_numpy()

class Valuer:
    """Time-adjusted LightGBM on log price, as chosen in Step 2."""
    def __init__(self, **kw):
        self.kw = dict(n_estimators=400, learning_rate=0.05, num_leaves=15, random_state=0, verbose=-1, **kw)
    def fit(self, X, months, y):
        r = np.log(y) - np.log(X.area_m2.to_numpy())
        r = r - pd.Series(r).groupby(X.district.to_numpy()).transform("mean").to_numpy()
        self.slope, self.icpt = np.polyfit(months, r, 1)
        self.m = LGBMRegressor(**self.kw).fit(X, np.log(y) - self.index(months))
        return self
    def index(self, months):
        return self.icpt + self.slope * months
    def predict_log(self, X, months):
        return self.m.predict(X) + self.index(months)

df = make_sales()
X, months = prepare(df)
y, year = df.price_k.to_numpy(), df.sale_date.dt.year.to_numpy()
cal, val = year == 2022, year == 2023

# residual interval: one-year-ahead errors (fit 2019-2021, predict 2022) set the width
early = Valuer().fit(X[year <= 2021], months[year <= 2021], y[year <= 2021])
res = np.log(y[cal]) - early.predict_log(X[cal], months[cal])
lo_q, hi_q = np.quantile(res, [0.1, 0.9])
print(f"one-year-ahead log errors on 2022 ({cal.sum()} sales): 10th pct {lo_q:+.3f}, 90th pct {hi_q:+.3f}")
print(f"-> range from {np.expm1(lo_q):+.1%} to {np.expm1(hi_q):+.1%} around the estimate")

trained = year <= 2022
model = Valuer().fit(X[trained], months[trained], y[trained])
centre = model.predict_log(X[val], months[val])
inside = (np.log(y[val]) >= centre + lo_q) & (np.log(y[val]) <= centre + hi_q)
print(f"\nresidual interval, coverage on 2023: {inside.mean():.1%} of {val.sum()} sales")

# quantile LightGBM for the 10th and 90th percentiles (same time adjustment)
q = {a: Valuer(objective="quantile", alpha=a).fit(X[trained], months[trained], y[trained]) for a in (0.1, 0.9)}
lo, hi = q[0.1].predict_log(X[val], months[val]), q[0.9].predict_log(X[val], months[val])
inside_q = (np.log(y[val]) >= lo) & (np.log(y[val]) <= hi)
width = lambda a, b: np.median(np.exp(b - centre) - np.exp(a - centre))     # as a share of the estimate
print(f"quantile LightGBM, coverage on 2023: {inside_q.mean():.1%}, median width {width(lo, hi):.1%} of the estimate")
print(f"residual interval width: {width(centre + lo_q, centre + hi_q):.1%} of the estimate")
one-year-ahead log errors on 2022 (522 sales): 10th pct -0.200, 90th pct +0.245
-> range from -18.1% to +27.8% around the estimate

residual interval, coverage on 2023: 84.1% of 510 sales
quantile LightGBM, coverage on 2023: 67.1%, median width 31.7% of the estimate
residual interval width: 45.9% of the estimate

The residual interval runs from −18.1 % to +27.8 % around the estimate (asymmetric, because a log band is wider above than below) and covers 84.1 % of 2023 prices, close to the 80 % it promises. The quantile models give a narrower band (31.7 % of the estimate against 45.9 %) that covers only 67.1 %: each quantile model is fitted on the training years, where it fits the noise of those years partly, and it is evaluated a year later. A narrow interval that does not hold is worse than a wide one that does, so the residual interval is chosen. Its only assumption is that the next year's errors look like the last year's, which Step 4 checks once more on 2024.

Step 4: test once, then look at the errors

Everything is decided: time-adjusted LightGBM, the residual interval. The final model is refitted on 2019-2023, which is how it would be trained to value 2024 homes, and its interval width is the one-year-ahead error of the model fitted on 2019-2022 and scored on 2023. Then 2024 is opened, once. The errors are broken down by predicted price band (what a user sees) and by district (error analysis and slices).

python · try it yourself
import numpy as np
import pandas as pd
from lightgbm import LGBMRegressor

def make_sales(n=3000, seed=0):
    rng = np.random.default_rng(seed)
    names = ["old town", "harbour", "university", "riverside", "north hills", "airport", "east end", "garden city"]
    level = dict(zip(names, [5.2, 4.4, 3.6, 3.9, 3.1, 2.1, 2.4, 2.8]))
    month = rng.integers(0, 72, n)
    district = rng.choice(names, n, p=[0.08, 0.1, 0.14, 0.12, 0.16, 0.12, 0.16, 0.12])
    area = np.clip(np.round(rng.lognormal(4.3, 0.35, n)), 25, 250)
    built = rng.integers(1950, 2023, n)
    cond = rng.choice(["poor", "fair", "good", "renovated"], n, p=[0.15, 0.35, 0.35, 0.15])
    dist = np.round(rng.gamma(2.0, 2.5, n), 1)
    years = month / 12
    log_index = 0.065 * years
    log_price = (np.log([level[d] for d in district]) + np.log(area) + log_index
                 + pd.Series(cond).map({"poor": -0.15, "fair": 0, "good": 0.08, "renovated": 0.15}).to_numpy()
                 - 0.002 * np.maximum(2000 - built, 0) - 0.02 * dist + rng.normal(0, 0.15, n))
    df = pd.DataFrame({"sale_date": pd.to_datetime("2019-01-01") + pd.to_timedelta(month * 30.44 + rng.integers(0, 28, n), unit="D"),
                       "district": district, "area_m2": area, "rooms": np.clip(np.round(area / 28 + rng.normal(0, 0.7, n)), 1, 8),
                       "built": built, "condition": cond, "dist_km": dist, "price_k": np.round(np.exp(log_price), 1)})
    return df.sort_values("sale_date", ignore_index=True)

FEATURES = ["district", "area_m2", "rooms", "built", "condition", "dist_km"]

def prepare(df):
    X = df[FEATURES].copy()
    X["district"] = X["district"].astype("category")
    X["condition"] = X["condition"].map({"poor": 0, "fair": 1, "good": 2, "renovated": 3})
    months = (df.sale_date.dt.year - 2019) * 12 + df.sale_date.dt.month - 1
    return X, months.to_numpy()

class Valuer:
    def __init__(self, **kw):
        self.kw = dict(n_estimators=400, learning_rate=0.05, num_leaves=15, random_state=0, verbose=-1, **kw)
    def fit(self, X, months, y):
        r = np.log(y) - np.log(X.area_m2.to_numpy())
        r = r - pd.Series(r).groupby(X.district.to_numpy()).transform("mean").to_numpy()
        self.slope, self.icpt = np.polyfit(months, r, 1)
        self.m = LGBMRegressor(**self.kw).fit(X, np.log(y) - self.index(months))
        return self
    def index(self, months):
        return self.icpt + self.slope * months
    def predict_log(self, X, months):
        return self.m.predict(X) + self.index(months)

df = make_sales()
X, months = prepare(df)
y, year = df.price_k.to_numpy(), df.sale_date.dt.year.to_numpy()

width_model = Valuer().fit(X[year <= 2022], months[year <= 2022], y[year <= 2022])
v = year == 2023
lo_q, hi_q = np.quantile(np.log(y[v]) - width_model.predict_log(X[v], months[v]), [0.1, 0.9])

final = Valuer().fit(X[year <= 2023], months[year <= 2023], y[year <= 2023])
t = year == 2024                                                   # the one look at the test year
centre = final.predict_log(X[t], months[t])
pred, yt = np.exp(centre), y[t]
ape = np.abs(pred - yt) / yt
inside = (np.log(yt) >= centre + lo_q) & (np.log(yt) <= centre + hi_q)
ppm = (df.price_k / df.area_m2)[year <= 2023].groupby(df.district[year <= 2023]).median()
base = df.district[t].map(ppm).to_numpy() * df.area_m2[t].to_numpy()
print(f"test 2024, {t.sum()} sales")
print(f"model:    MAE {np.mean(np.abs(pred - yt)):.1f} k, MdAPE {np.median(ape):.1%}, bias {np.mean(pred / yt - 1):+.1%}")
print(f"baseline: MAE {np.mean(np.abs(base - yt)):.1f} k, MdAPE {np.median(np.abs(base - yt) / yt):.1%}")
print(f"80 % range: coverage {inside.mean():.1%}, from {np.expm1(lo_q):+.1%} to {np.expm1(hi_q):+.1%} (log {lo_q:+.3f}, {hi_q:+.3f})")

res = pd.DataFrame({"band": pd.qcut(pred, 4, labels=["lowest 25 %", "second", "third", "highest 25 %"]),
                    "district": df.district[t].to_numpy(), "ape": ape, "inside": inside, "abs_k": np.abs(pred - yt)})
print("\nby predicted price band:")
print(res.groupby("band", observed=True).agg(n=("ape", "size"), MdAPE=("ape", "median"), MAE_k=("abs_k", "mean"),
                                             coverage=("inside", "mean")).round(3).to_string())
print("\nby district (worst three by MdAPE):")
print(res.groupby("district").agg(n=("ape", "size"), MdAPE=("ape", "median"), coverage=("inside", "mean"))
      .sort_values("MdAPE", ascending=False).head(3).round(3).to_string())
test 2024, 533 sales
model:    MAE 45.3 k, MdAPE 11.6%, bias +1.3%
baseline: MAE 75.7 k, MdAPE 19.6%
80 % range: coverage 78.2%, from -17.8% to +21.4% (log -0.196, +0.194)

by predicted price band:
                n  MdAPE   MAE_k  coverage
band
lowest 25 %   134  0.110  22.467     0.813
second        133  0.130  39.433     0.729
third         133  0.113  47.066     0.797
highest 25 %  133  0.109  72.457     0.789

by district (worst three by MdAPE):
              n  MdAPE  coverage
district
riverside    53  0.135     0.736
harbour      54  0.123     0.759
north hills  90  0.117     0.756

Against the criteria fixed at the start: MdAPE 11.6 % against the baseline's 19.6 % (41 % lower; target 25 %), coverage 78.2 % (target 75-85 %), bias +1.3 %. The interval width came out a little narrower this time (−17.8 % to +21.4 %), because it was measured on a different year; it is re-estimated each time the model is retrained.

The breakdown is more useful than the totals. The error in thousands grows with the price (22 k in the cheapest quarter, 72 k in the most expensive) while the percentage error is flat at 11-13 %, which confirms the log target was right. Coverage is lowest in the second price band (72.9 %) and in riverside (73.6 % of 53 sales). With 53 sales per district, a coverage of 73.6 % is within a few sales of 80 % and is not yet evidence of a problem; it is a slice to watch, not to tune on.

Step 5: a valuation endpoint

The deliverable is a small service (a prediction service with FastAPI). For production the model is refitted on all six years, and the interval width keeps its one-year-ahead estimate. The request schema rejects districts the model does not know and impossible areas, the response carries the range and the model version, and the "valid until" date reminds everyone that the index extrapolation goes stale. The calls go through httpx.ASGITransport, so the app runs in memory exactly as it would behind a server.

python · try it yourself
import asyncio
from typing import Literal
import httpx
import numpy as np
import pandas as pd
from fastapi import FastAPI
from lightgbm import LGBMRegressor
from pydantic import BaseModel, Field

def make_sales(n=3000, seed=0):
    rng = np.random.default_rng(seed)
    names = ["old town", "harbour", "university", "riverside", "north hills", "airport", "east end", "garden city"]
    level = dict(zip(names, [5.2, 4.4, 3.6, 3.9, 3.1, 2.1, 2.4, 2.8]))
    month = rng.integers(0, 72, n)
    district = rng.choice(names, n, p=[0.08, 0.1, 0.14, 0.12, 0.16, 0.12, 0.16, 0.12])
    area = np.clip(np.round(rng.lognormal(4.3, 0.35, n)), 25, 250)
    built = rng.integers(1950, 2023, n)
    cond = rng.choice(["poor", "fair", "good", "renovated"], n, p=[0.15, 0.35, 0.35, 0.15])
    dist = np.round(rng.gamma(2.0, 2.5, n), 1)
    years = month / 12
    log_index = 0.065 * years
    log_price = (np.log([level[d] for d in district]) + np.log(area) + log_index
                 + pd.Series(cond).map({"poor": -0.15, "fair": 0, "good": 0.08, "renovated": 0.15}).to_numpy()
                 - 0.002 * np.maximum(2000 - built, 0) - 0.02 * dist + rng.normal(0, 0.15, n))
    df = pd.DataFrame({"sale_date": pd.to_datetime("2019-01-01") + pd.to_timedelta(month * 30.44 + rng.integers(0, 28, n), unit="D"),
                       "district": district, "area_m2": area, "rooms": np.clip(np.round(area / 28 + rng.normal(0, 0.7, n)), 1, 8),
                       "built": built, "condition": cond, "dist_km": dist, "price_k": np.round(np.exp(log_price), 1)})
    return df.sort_values("sale_date", ignore_index=True)

DISTRICTS = ["old town", "harbour", "university", "riverside", "north hills", "airport", "east end", "garden city"]
COND = {"poor": 0, "fair": 1, "good": 2, "renovated": 3}

def features(df):
    X = df[["district", "area_m2", "rooms", "built", "condition", "dist_km"]].copy()
    X["district"] = pd.Categorical(X["district"], categories=DISTRICTS)
    X["condition"] = X["condition"].map(COND)
    return X

# ---- training (all sales 2019-2024); interval width from the 2023 one-year-ahead check ----
df = make_sales()
X, y = features(df), df.price_k.to_numpy()
months = ((df.sale_date.dt.year - 2019) * 12 + df.sale_date.dt.month - 1).to_numpy()
r = np.log(y) - np.log(df.area_m2.to_numpy())
r = r - pd.Series(r).groupby(df.district.to_numpy()).transform("mean").to_numpy()
slope, icpt = np.polyfit(months, r, 1)
model = LGBMRegressor(n_estimators=400, learning_rate=0.05, num_leaves=15, random_state=0, verbose=-1)
model.fit(X, np.log(y) - (icpt + slope * months))
LO, HI = -0.196, 0.194                                 # Step 4: one-year-ahead log-error percentiles
VALUE_MONTH = 6 * 12 + 6                           # mid-2025: valuations are for next year
VERSION = "valuer-2025.1 (trained on 2019-2024)"

# ---- the service ----
class Home(BaseModel):
    district: Literal[tuple(DISTRICTS)]
    area_m2: float = Field(ge=15, le=400)
    rooms: int = Field(ge=1, le=12)
    built: int = Field(ge=1800, le=2025)
    condition: Literal["poor", "fair", "good", "renovated"]
    dist_km: float = Field(ge=0, le=60)

app = FastAPI()

@app.post("/valuation")
async def valuation(home: Home):
    centre = model.predict(features(pd.DataFrame([home.model_dump()])))[0] + icpt + slope * VALUE_MONTH
    return {"estimate_k": round(float(np.exp(centre)), 0),
            "range_80_k": [round(float(np.exp(centre + LO)), 0), round(float(np.exp(centre + HI)), 0)],
            "model": VERSION, "valid_until": "2025-12-31"}

async def main():
    async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
        flat = {"district": "harbour", "area_m2": 72, "rooms": 3, "built": 1998, "condition": "good", "dist_km": 2.5}
        house = {"district": "garden city", "area_m2": 140, "rooms": 5, "built": 1975, "condition": "fair", "dist_km": 9}
        for body in (flat, house):
            r = await client.post("/valuation", json=body)
            print(r.status_code, r.json())
        r = await client.post("/valuation", json={**flat, "district": "Harbour", "area_m2": 7})
        print(r.status_code, [(e["loc"][-1], e["type"]) for e in r.json()["detail"]])

asyncio.run(main())
200 {'estimate_k': 538.0, 'range_80_k': [442.0, 653.0], 'model': 'valuer-2025.1 (trained on 2019-2024)', 'valid_until': '2025-12-31'}
200 {'estimate_k': 452.0, 'range_80_k': [371.0, 549.0], 'model': 'valuer-2025.1 (trained on 2019-2024)', 'valid_until': '2025-12-31'}
422 [('district', 'literal_error'), ('area_m2', 'greater_than_equal')]

The harbour flat is valued at 538 k EUR with an 80 % range of 442-653 k, the garden-city house at 452 k (371-549 k). The range is not symmetric in euros, because it is symmetric in percentage terms on the log scale. The bad request is rejected with 422 and two reasons: "Harbour" is not one of the known district names (case matters), and 7 square metres is below the minimum. A model that silently valued an unknown district would return the average level of the city and look plausible, which is the worst failure for a valuation.

Extensions

  • Replace the straight-line index with a repeat-sales index or a monthly index from a time-series model, and backtest both over several years (rolling origin).
  • Add neighbourhood features from earlier sales only (median price per m2 of the last 12 months within the district): lag, rolling and group features, computed strictly from the past.
  • Make the range adapt to the home: conformalised quantile regression widens the band where the quantile models are unsure.
  • Monitor the live service: the share of sale prices inside the range, month by month, is the earliest sign that the market has moved (monitoring).
  • Package the model with its metadata and serve it from a container: model artefacts, Docker for models.

Write-up template

text
Project: automatic valuation, <market>, <date>
Data: source and licence, period, number of sales, what a "sale" is (registry vs listing)
Split: train <years> / validation <year> / test <year>, why time-based
Baseline: <rule>, test MdAPE <x> %
Model: <model, target transform, how time is handled>, test MAE <x> k, MdAPE <x> %, bias <x> %
Range: <method>, nominal 80 %, test coverage <x> %, typical width <x> % of the price
Errors: worst price band <...>, worst districts <...>, likely reasons
Limits: index extrapolation horizon, homes unlike the training data, data not covered
Privacy: what is published (aggregates only?), licence terms of the data source

Practice

  1. Change the generator so that prices fall 5 % in 2024 (replace the index by np.where(years < 5, 0.065 * years, 0.325 - 0.05 * (years - 5))) and rerun Step 4. What happens to the bias and the coverage, and which part of the model is responsible?
Answer

The model's index extrapolates the rise, so the 2024 estimates come out too high (the bias, +1.3 % in Step 4, becomes large and positive: the index adds about 6.7 % for a year in which prices fell 5 %) and many 2024 prices fall below the lower end of the range, so coverage drops well below 80 %. The trees are not to blame: the straight-line index is. This is why the service has a valid_until date and why the share of sales inside the range should be monitored (monitoring); a falling coverage is the first sign of a turning market.

  1. A colleague proposes a random 80/20 split "because it gives a lower error". What would you answer?
Answer

The lower error is the problem: with a random split, sales from the same months as the test sales are in training, so the model is scored on interpolation, while the service always extrapolates into the next year. The leakage lab (time-series case) shows the same gap. Report the time-split error; mention the random-split figure only to explain why it is not used.

  1. Why are the errors analysed by predicted price band rather than by actual price band?
Answer

Because the user sees only the prediction. "Valuations above 500 k are off by 11 %" is a statement the portal can show next to an estimate. Grouping by the actual price also mixes in a selection effect: the homes whose actual price is very high are disproportionately the ones the model under-estimated, so the top actual band always looks biased low.

Test yourself

Two years ahead, the LightGBM model with the sale month as a feature is 11.8 % too low on 2023 prices. Why?

  1. It overfits the training months
  2. Trees predict leaf averages, so for any month after the training data they return prices from the end of the training period
  3. The month feature leaks the test labels
  4. LightGBM cannot use integer features

The quantile LightGBM interval covered 67.1 % of 2023 prices, the residual interval 84.1 %. Both were meant to be 80 % intervals. Which statement is right?

  1. The narrower interval is better because it is more precise
  2. Coverage must be checked on data the interval was not built from; the quantile band was too narrow for next-year sales
  3. Coverage cannot be measured for regression
  4. The residual interval cheats because it uses the 2023 data

Error by predicted price band: MAE grows from 22 k to 72 k, MdAPE stays at 11-13 %. What does this support?

  1. Modelling the log price, since errors are roughly proportional to price
  2. Removing expensive homes from the data
  3. Using MAE as the only metric
  4. A separate model per band

Why does the valuation response carry a valid_until date?

  1. HTTP requires it
  2. The estimate relies on extrapolating the market index, which goes stale as time passes beyond the training data
  3. LightGBM models expire
  4. To force users to call the service again