CyberFreezeDev Loading
  1. Home
  2. Blog
  3. How-to guides
  4. Linear regression example: a simple sales forecast

How-to guides

Linear regression example: a simple sales forecast

Linear regression is the simplest forecasting model worth knowing. A worked sales example in scikit-learn, how to read what it prints, and the situations where it gives confident wrong answers.

A potted cactus on a shop counter in front of a rail of shirts
A potted cactus on a shop counter in front of a rail of shirts

Linear regression predicts a number as a weighted sum of inputs plus a constant, for example sales = intercept + a × month + b × ad spend. You fit it on past months, read each coefficient as how much sales move per unit of that input with the others held fixed, and judge it by its error on months it never saw. It works for a steady trend with a few drivers, and fails on seasonal peaks and on very little data.

An early 1800s printed chart of monthly air pressure and temperature in Manchester for 1807 to 1809
Most forecasts start from a chart like this: monthly figures over time, with a trend and often a shape that repeats every year.

What does linear regression assume?

The model draws the straight line (or flat plane, with more inputs) that keeps the squared gaps to the data as small as possible. For forecasts to be trustworthy, Forecasting: Principles and Practice by Hyndman and Athanasopoulos lists what the errors should look like:

  • Mean zero, otherwise forecasts are biased high or low.
  • Not autocorrelated: this month's miss should not predict next month's.
  • Unrelated to the inputs.
  • Ideally normally distributed with constant variance, which makes prediction ranges easier to work out.

In sales terms: the relationship should be roughly straight, nothing important should be missing from the inputs, and the inputs should not be near copies of each other.

A worked example with scikit-learn

Here are 12 months of invented figures for a small shop, in ₹ thousand: sales and ad spend. We train on months 1 to 9 and test on months 10 to 12, because a forecast must be judged on months the model has not seen.

import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error

df = pd.DataFrame({
    "month":    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    "ad_spend": [20, 25, 22, 30, 28, 35, 32, 30, 38, 40, 36, 45],
    "sales":    [249, 264, 269, 298, 302, 324, 324, 324, 352, 374, 350, 404],
})
X, y = df[["month", "ad_spend"]], df["sales"]
train, test = df["month"] <= 9, df["month"] >= 10

model = LinearRegression().fit(X[train], y[train])
print(model.intercept_, model.coef_)
print(mean_absolute_error(y[test], model.predict(X[test])))

Run with scikit-learn 1.9.1, it prints an intercept of 190.8, coefficients of 7.43 for month and 2.52 for ad spend, and a mean absolute error of 10.7. The predictions for months 10 to 12 are 365.8, 363.2 and 393.3 against actual sales of 374, 350 and 404. The LinearRegression documentation lists the other attributes and defaults.

How do you read the coefficients and the error?

  • Month, 7.43: with ad spend held fixed, sales rise by about ₹7,430 a month in this data. That is the trend.
  • Ad spend, 2.52: each extra ₹1,000 of ad spend goes with about ₹2,520 more sales, month held fixed. This is an association, not proof that ads cause sales. Ad spend also rose through the year (the two inputs have a correlation of 0.92), so the model has to split the credit between them, and with nine rows that split can move a lot when one month is added.
  • Intercept, 190.8: the predicted sales at month 0 with no ad spend. It sits outside the data, so do not read it as a real figure.
  • Error: model.score gives R² of 0.995 on the training months. That looks excellent and means little, because it is measured on the data the line was fitted to. The number to report is the error on the test months: ₹10,700 on average, about 3 percent of sales in those months.
  • Baseline: always compare with something simple. Predicting each month as last month's sales gives an average error of ₹33,300 on the same three months, so the model earns its place here.

To forecast month 13 you must supply its ad spend; at ₹40,000 the model predicts ₹388,100. A forecast that needs next month's inputs is only as good as your guess of them. Our glossary entry on model evaluation covers other error measures.

Cupped hands holding a string of small glowing lights
Festive peaks repeat every year, and a straight line through the months cannot see them unless you tell it which month is which.

When does linear regression fail?

  • Seasonality. A month number cannot represent a Diwali or year end peak. The model averages it away and misses it every year.
  • Few data points. Nine rows and three parameters leave the coefficients fragile. One unusual month moves them, and an error measured on three months is itself uncertain.
  • Changes in the business. A new branch, a price change or a lost customer breaks the trend, and a straight line extends the old trend forever.
  • Errors that run in streaks. If the model misses high several months in a row, something is missing from the inputs.
  • Outliers. One bulk order can tilt the whole line. Find it and decide whether it belongs.

What to try next

  1. Seasonal dummy variables. Add one yes or no column per month. FPP3 explains why you use one fewer than the number of seasons, 11 for monthly data, to avoid the "dummy variable trap". You need several years of history for this to work.
  2. Test across several cut off dates. scikit-learn's TimeSeriesSplit trains on earlier months and tests on later ones, since ordinary cross validation would train on the future and test on the past.
  3. Forecasting methods built for time series. The same free book covers exponential smoothing and ARIMA models in chapters 8 and 9. Its code is in R, but the ideas carry over to Python libraries.
  4. Keep the baseline. Any new model has to beat last month's value and last year's same month.

If you are deciding whether a forecast is worth building at all, our post on where an AI consultant starts with a small business covers choosing a first project and checking the numbers before you build.

Learning this with your team

Regression is a good first model for an analyst to build because every number it prints can be explained. Our AI training workshops include a session for technical teams on their own masked data, with output tested against an evaluation set, and AI strategy consulting helps decide which AI projects, forecasts included, are worth funding. Book a consultation to talk it through.