Start learning free

LESSON 114 OF 165 · MACHINE LEARNING: TIME SERIES

Project: Forecast Next Month in Python

Practice

Next month is 4 coming weeks, and the lag model guesses one week at a time, from last week's revenue and the revenue of 4 weeks back. For the first coming week, both are known. For the second, "last week" is the first coming week, which hasn't happened yet, so you use the model's own guess for it. This is a step-by-step forecast: each guess joins the history and feeds the next one.

First the honest test, as in the last lessons: fit on train, score on the last 8 weeks, and check that the model beats both baselines. Then fit the same model again on every week of table, so the newest weeks teach it too before it forecasts.

A plain list keeps the history. list(weekly) gives back the weekly revenues as a list, oldest first. history[-1] is the last item and history[-4] the one 4 back; history.append(x) adds x at the end; history[-4:] gives back the last 4 items. The given next_week(history) builds one row from history[-1] and history[-4] and gives back the model's guess. The same pattern on other numbers prints Mon 16, Tue 18 and 34:

counts = [10, 12, 14]
for day in ["Mon", "Tue"]:
    counts.append(counts[-1] + 2)
    print(day, counts[-1])
print(sum(counts[-2:]))

Your script must print:

Last week MAE: 460.8
Average of 4 MAE: 350.0
Model MAE: 286.8
2026-12-06 3403.8
2026-12-13 3436.2
2026-12-20 3234.6
2026-12-27 3294.7
Next month: 13369.3

Your task: the starting code builds table, the baselines, features, an empty model, next_week and the 4 coming Sundays in next_dates. Fit and score the model on the time split, fit it again on every week, then forecast the 4 weeks one after another, printing each guess and, at the end, their sum. Round every number you print to 1 decimal.


Assignment
Follow the Coding Tutorial to test the model, fit it again on all weeks and forecast December one week at a time.


Hint
Inside the loop, append first, then print history[-1]: the guess you just added. The total is printed once, below the loop, so that line is not indented.


STEP 1 OF 8
    Ctrl + Enter to check

    Ts Forecast Project in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free