Always free. For everyone.
Course outline
Module 15 of 20 · Machine learning

Forecast what comes next

Build time features, evaluate in date order, and compare honest forecasting baselines. This module has 3 lessons and takes about 1h 30m. Each lesson has a practice exercise that runs real Python in your browser and a short quiz.

Start module 15 in the Learning Lab
LESSON 1 OF 3

Build features that respect time

30 minEnergy
WHAT YOU WILL DO

Create lag and rolling features without using the value being predicted.

To forecast tomorrow's electricity demand, use information available today. A lag is an earlier observation. Lag 1 is the previous day, while a three-day rolling mean summarises the three days before the target.

The loop below starts at day 3 because it needs three earlier values. Its target is demand[t]. Every feature comes from a position strictly before t. Including demand[t] in a rolling average would quietly reveal part of the answer.

Check timestamps before modelling. Missing dates and readings published late can make a row-based lag differ from a real one-day lag. This small synthetic series assumes equally spaced daily observations available immediately.

See it in action

example.pyPython 3
import numpy as np

demand = np.array([20, 22, 21, 25, 26, 24, 28, 30], dtype=float)
X, y = [], []
for t in range(3, len(demand)):
    X.append([demand[t - 1], demand[t - 3:t].mean()])
    y.append(demand[t])
X, y = np.array(X), np.array(y)
for features, target in zip(X, y):
    print("Yesterday, past 3-day mean:", features.round(2), "Target:", target)
Keep this in mind

A good forecast feature must exist at the moment you make the prediction.

LESSON 2 OF 3

Validate by walking forward

30 minHealthcare
WHAT YOU WILL DO

Measure an appointment-volume forecast using expanding historical windows.

A clinic wants to estimate tomorrow's appointment volume for staffing. In this synthetic operations example, evaluation must imitate deployment: learn from earlier days, then predict a later day.

Walk-forward validation repeats that process across several cutoffs. The example fits a simple linear trend, predicts one day, records the error, then adds the observed day before making the next forecast. A persistence baseline predicts the latest observed count.

These are one-step forecasts updated daily. Their errors do not measure the harder task of predicting a whole month without new observations. Reserve a final later period if you use these validation results to choose model settings.

See it in action

example.pyPython 3
import numpy as np

appointments = np.array([20, 22, 21, 24, 25, 27, 26, 30, 31, 32], dtype=float)
trend_errors, baseline_errors = [], []
for cutoff in range(5, len(appointments)):
    days = np.arange(cutoff)
    design = np.column_stack([np.ones(cutoff), days])
    weights = np.linalg.lstsq(design, appointments[:cutoff], rcond=None)[0]
    prediction = np.array([1, cutoff]) @ weights
    actual = appointments[cutoff]
    trend_errors.append(abs(actual - prediction))
    baseline_errors.append(abs(actual - appointments[cutoff - 1]))
    print(f"Train days 0-{cutoff - 1}, predict {cutoff}: {prediction:.1f}")
print("Trend MAE:", round(float(np.mean(trend_errors)), 2))
print("Persistence MAE:", round(float(np.mean(baseline_errors)), 2))
Keep this in mind

Match the validation horizon and update schedule to the real forecasting task.

LESSON 3 OF 3

Beat a seasonal baseline

30 minFinance
WHAT YOU WILL DO

Compare forecast errors against an appropriate repeating-pattern baseline.

A fictional equipment shop has a seven-day sales pattern. Predicting the same weekday from the previous week is called a seasonal naive forecast. It can be a strong baseline when weekday effects are stable.

Compare it with predicting the previous day on exactly the same future dates. Mean absolute error, or MAE, reports the average error in the original sales units. A complicated model earns its place only if it improves useful outcomes on unseen dates.

The example also reports the largest error, because the average can hide a costly miss. This synthetic exercise teaches evaluation, not a financial forecast. Holidays, closures, missing days, and changing demand would need explicit handling in a real project.

See it in action

example.pyPython 3
import numpy as np

sales = np.array([20, 25, 28, 30, 40, 65, 55,
                  21, 24, 29, 32, 39, 67, 54,
                  22, 26, 30, 31, 42, 68, 56], dtype=float)
start = 14  # Evaluate only on the final week.
actual = sales[start:]
previous_day = sales[start - 1:-1]
previous_week = sales[start - 7:-7]
for name, prediction in [("Yesterday", previous_day), ("Last week", previous_week)]:
    errors = np.abs(actual - prediction)
    print(name, "MAE:", round(float(errors.mean()), 2),
          "largest miss:", float(errors.max()))
Keep this in mind

Start with a baseline that reflects the rhythm of the problem.

ABOUT THE LEARNING LAB

Free, open and run by a nonprofit.

This page is part of Python to AI, a free course of 20 modules and 60 lessons in the engineering.fit( ) Learning Lab. The Learning Lab is built and run by engineering.fit( ), a nonprofit founded by Abdullateef Opeyemi Bakare that helps African engineering students gain research experience. You do not need an account or pay a fee to learn.

Course outline · Project lab · Visit engineering-fit.org