Building your first statistical model
How do you forecast a month that has not happened yet? An introduction to time series, built on a simple regression you can run yourself, and an honest look at where it fails.
How do you forecast a month that has not happened yet? An introduction to time series, built on a simple regression you can run yourself, and an honest look at where it fails.
A note on reading time: The reading time shown above is too high. It also counts the data and code behind the interactive charts. The article itself takes about seven minutes to read.
Picture a buyer at a retail chain in September, deciding how much stock to order for December. In the U.S. retail data used in this article, December alone brought in 9.7 percent of all sales in 2015, nearly a tenth of the year in one month. Order too little and the shelves run empty. With too much, the rest goes out in January at a discount.
The buyer needs a number for a month that has not happened yet, and the only material at hand is the past. Here is that past: 293 months of U.S. retail sales, from January 1992 to May 2016.
| Year | Average month |
|---|---|
| 1992 | 167,842 |
| 1993 | 179,425 |
| 1994 | 194,186 |
| 1995 | 204,219 |
| 1996 | 216,983 |
| 1997 | 227,178 |
| 1998 | 237,746 |
| 1999 | 257,249 |
| 2000 | 273,961 |
| 2001 | 281,576 |
| 2002 | 288,256 |
| 2003 | 301,038 |
| 2004 | 320,550 |
| 2005 | 340,479 |
| 2006 | 357,863 |
| 2007 | 369,978 |
| 2008 | 365,982 |
| 2009 | 338,747 |
| 2010 | 357,148 |
| 2011 | 383,131 |
| 2012 | 402,199 |
| 2013 | 416,770 |
| 2014 | 434,295 |
| 2015 | 444,170 |
| 2016 (Jan–May) | 439,386 |
Most of what a forecaster needs is visible in the chart. Sales climb over time, from about 146,000 in January 1992 to about 471,000 in May 2016, in the file's own units. Each year also has the same shape: in 23 of the 24 full years, December was the strongest month, and in 23 of them the weakest month was January or February. Then, in 2008 and 2009, the climb stops, and annual sales in the file fall 1.1 and then 7.4 percent.
A series like this, one value recorded at regular intervals and kept in time order, is called a time series. Order matters because this month's sales resemble last month's. The same structure sits behind electricity demand, website traffic and hospital admissions, so the method in this article carries over to them.
The climb and the yearly shape are regular, which means a method that learns them from the past can extend them forward. A recession is a different kind of thing. Nothing in the years before 2008 announced it.
The simplest forecast needs no model at all. Take last December's sales and call it the forecast for this December. Forecasters call this the seasonal naive rule, and it is the baseline any serious method has to beat.
One step up, smoothing methods average recent months and give the newest ones the most weight, so the forecast adapts as the series moves. Statistical models such as ARIMA go further and describe how each month depends on the months before it. Machine-learning methods, from decision trees to neural networks, can take in many more inputs, such as prices, holidays or weather, and find patterns nobody wrote down in advance.
Each step buys flexibility and costs transparency. A neural network can fit the past closely and still give no reason for its forecast. For a first model, the opposite trade is the more useful one.
This article uses linear regression, one of the oldest tools in statistics. It draws the straight line that fits a cloud of points best, and the result reads like a recipe. Here the recipe has two ingredients: a fixed amount of growth per month, and a fixed adjustment for each calendar month, large and positive for December and negative for February. Every number the model learns can be printed and checked.
The formula. For each month, the model computes a prediction:
ŷt = β0 + β1 · t + βmonth
One month, worked through. December 2015 is month number 287:
167,668 + 968.7 × 287 + 45,823 ≈ 491,500
The real value was 518,253, so the model fell about 26,750 short. The β values are the only things the computer learns. Everything else is the recipe written down above: start level, plus growth times months passed, plus the adjustment for the time of year.
The recipe has an obvious limit. It can only extend patterns it has already seen, so a straight line cannot see a recession coming.
For readers who code, the full script follows. Pandas and scikit-learn, two free Python libraries for tables and machine learning, are the only extras. If you do not code, skip the box, because the text describes each step.
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
# 1. Load a real series: monthly U.S. retail sales, January 1992 to May 2016
url = "https://raw.githubusercontent.com/facebook/prophet/main/examples/example_retail_sales.csv"
df = pd.read_csv(url, parse_dates=["ds"], index_col="ds")
y = df["y"]
# 2. Turn the calendar into columns: a month counter and the month of the year
df["t"] = np.arange(len(df))
df["month"] = df.index.month
X = pd.get_dummies(df[["t", "month"]], columns=["month"], dtype=float)
# 3. Split by date, never at random: hold out the last 60 months
cut = len(df) - 60
X_train, X_test = X.iloc[:cut], X.iloc[cut:]
y_train, y_test = y.iloc[:cut], y.iloc[cut:]
# 4. Fit the line and predict the unseen months
model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)
# 5. Compare with the naive guess: "same month one year earlier"
naive = y.shift(12).iloc[cut:]
print(f"model MAE: {np.abs(y_test - pred).mean():.0f}")
print(f"naive MAE: {np.abs(y_test - naive).mean():.0f}")
Step 1 loads the data, one number per month. A model cannot read a calendar, so step 2 puts the data into a form it can read. It adds a counter that numbers the months from 0 to 292 and carries the climb.
The month of the year needs different handling. Written as a plain number from 1 to 12, it would force the model to raise its adjustment in equal steps from January to December, as if December were simply more month than November. So each calendar month gets its own column instead, set to 1 when a row belongs to that month and 0 otherwise. The columns work like light switches. In a December row only the December switch is on, so the model adds December's adjustment and no other. The table below shows what the data looks like once step 2 is done.
y is the month's sales, t counts the months, and the twelve columns from Jan to Dec are the switches. Follow the highlighted 1s: they step one column to the right each month and start over every January.| month | y | t | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1992-01 | 146,376 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1992-02 | 147,079 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1992-03 | 159,336 | 2 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1992-04 | 163,669 | 3 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1992-05 | 170,068 | 4 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1992-06 | 168,663 | 5 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1992-07 | 169,890 | 6 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
| 1992-08 | 170,364 | 7 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 |
| 1992-09 | 164,617 | 8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
| 1992-10 | 173,655 | 9 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 1992-11 | 171,547 | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
| 1992-12 | 208,838 | 11 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
| 1993-01 | 153,221 | 12 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| … | … | … | … | … | … | … | … | … | … | … | … | … | … | … |
| 2016-04 | 450,935 | 291 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 2016-05 | 471,421 | 292 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
Step 4 fits the line, and the learned growth comes out at 11,624 per year.
minimize Σ (yt − ŷt)2
The sum runs over all training months, and yt is the real value. In words: for every month, take the miss between real and predicted value, square it so large misses weigh more, and add everything up. The chosen β values are the ones with the smallest total.
Step 3 trains on the 233 months from January 1992 to May 2011 and hides the 60 months from June 2011 to May 2016. A random split would show the model the months on both sides of every test month, which turns forecasting into filling gaps, so the split follows the calendar. The score is the mean absolute error, the average size of the miss.
MAE = 1⁄n · Σ |yt − ŷt|
Here n is the number of test months. In words: take each miss, ignore whether it was too high or too low, and average. An MAE of 8,411 means the forecast was off by about 8,411 units in a typical month.
A score means little on its own, so the model needs an opponent. The obvious one is the seasonal naive rule from earlier, which step 5 computes: it forecasts each month with the real value from the same month a year before. Take April 2013, when sales were 408,381. The model predicted 411,600 and missed by 3,219. For the naive rule, the forecast was April 2012’s 393,035, a miss of 15,346.
Repeat that for all 60 test months and average the misses. The model's average miss is 8,411, about 2.0 percent of a typical month's sales, and the naive rule's is 16,466, or 3.9 percent. In 49 of the 60 months the model came closer, and it cut the average error almost in half.
The contest is also tilted against the model. For a month in 2015, the naive rule gets to use real sales from 2014. The model has to forecast all five years without ever seeing 2012, 2013 or 2014. Beating an opponent with fresher information suggests the line has learned something real.
The chart lays the model over the real data. Left of the dotted line, the dashed orange line is the fit to the training years. To the right, the solid orange line is the forecast, drawn without the model ever seeing those months. Switch to the test window to compare the two lines month by month.
This article is an introduction, and the model is the simplest one that does the job. A 2 percent miss sounds precise, yet sales grew 4.6 percent a year on average from 2010 to 2015, so the typical miss was about two-fifths of a year's growth. Where that error comes from is where forecasting gets interesting, and each of the following topics deserves a closer look than this piece can give it.
For a first model, the line does its job. It runs in seconds, came closer than last year's value in 49 of 60 test months, and shows in one chart where the economy moved without it. Whether a 2 percent miss is good enough depends on the decision it feeds, and only the person making that decision can say.
Your link has expired. Please request a new one.
Your link has expired. Please request a new one.
Your link has expired. Please request a new one.
Great! You've successfully signed up.
Great! You've successfully signed up.
Welcome back! You've successfully signed in.
Success! You now have access to additional content.