30 min read · AI for business · AI technology and models

An equipment shop orders based on last month's sales, adjusted by gut feeling. Some months it runs out of stock, some months it is stuck with excess. Then someone suggests trying an AI forecast. The problem is that the accuracy figures people show usually come from asking the model to predict a period it has already seen, or from comparing it against a method nobody really uses. Only one question matters: when it predicts a period it has not seen, and is compared with a simple method that could replace it, is this model really better?
This article works through it step by step in Python with numpy, without pandas, so there is nothing extra to install. It includes fictional data that contains the real problems (stockouts, bad rows, intermittent products), code you can run yourself, real output, and a test suite. Managers can read just the explanations and tables to get the picture. Engineers can run it alongside.
The real problem: sales are not demand, and an AI that is not compared with something simple means nothing
Recorded sales are what was sold, not what people wanted to buy. If a product is out of stock for a few weeks, it looks like sales dropped. If you teach a model with those numbers, it learns that demand disappeared and recommends ordering less, which causes more stockouts. Also, without a benchmark, the word accurate means nothing. A good-looking score may be no better than a method that simply copies last year's sales.
Consider three hypothetical situations, not projects of any BT San customer.
- A retail building materials shop: cement and paint were out of stock for two months at the start of the rainy season. The recorded sales were low, the purchasing team read that as few people buying, ordered less the next year, and ran out of stock again.
- A souvenir snack manufacturer: sales spike before Songkran and New Year every year. The team used a three-month trailing average, so it under-ordered at the peak and was left with excess after the festival.
- A machine spare parts distributor: some parts sell only a few units a year, and most weeks are zero. Percentage metrics cannot be computed, and the team needs a way of measuring that still works when there are zeros.
All three cases follow the same principle: clean the data without letting stockouts turn into low demand, measure every method on the same exam that does not leak, and accept the model only when it truly beats the simple methods.
What the textbook says, and what this example takes as its basis
| Topic | What the documentation says | What it means for our code |
|---|---|---|
| Benchmark methods | The textbook Forecasting: Principles and Practice (FPP3) uses four simple methods as benchmarks: mean, naive, seasonal naive and drift | Every model must be compared with naive and seasonal naive first |
| Measuring accuracy | FPP3 defines MAE and says percentage metrics (such as MAPE) are infinite or undefined if any actual value equals zero. MASE scales the error by the MAE of the naive method (or seasonal naive when the data has seasonality) on the training data | Intermittent products cannot use MAPE; use MAE, WAPE and MASE |
| Splitting tests by time | FPP3 describes time series cross-validation, where each round's training set contains only data before the test point and the starting point moves forward (rolling forecasting origin). scikit-learn's TimeSeriesSplit says that, unlike ordinary cross-validation, each successive training set is a superset of the previous one | Never split randomly. Split by time, and the model sees only the past of the starting point |
| Forecast intervals | FPP3 describes a bootstrap method based on the errors when you do not want to assume a normal distribution, taking percentiles. The resulting interval can be asymmetric | Use quantiles of the backtest errors to build the interval (this example does a simplified version) |
| Missing data | FPP3 warns that missing data has many causes, that you should check whether gaps bias the model, and that replacing unusual values without asking what caused them is dangerous (that page does not discuss stockouts directly; treating a stockout week as an unknown value is our own design decision) | A stockout week is an unknown value (NaN), not a low number |
| Least squares | The numpy.linalg.lstsq documentation says it finds the solution that minimizes the Euclidean 2-norm of b - ax | Use lstsq to fit the regression model without installing another library |
The data in the example is generated by us with a fixed seed. The seasonality is built as a sin wave with a festival effect multiplied in. The regression model in the example has the same form as the one used to generate the data, so it has an unrealistic advantage compared with real data. The wins and losses in this article show how to measure, not the results you would get for your own business.
Overview of the example
All the code is in the folder examples/demand-forecasting-time-series-ai/. It uses Python 3 with numpy, without pandas, and makes no network calls. The data is three fictional products with weekly sales over 156 weeks (three years).
| File | Purpose |
|---|---|
| gen_data.py / sales.csv | Generates fictional data with a fixed seed, including festival weeks, stockouts and three kinds of deliberately bad rows |
| clean.py | Loads the CSV, reports bad rows, and turns stockout weeks into NaN |
| metrics.py | MAE, WAPE, MAPE and MASE |
| models.py | naive, seasonal naive, moving average, and a regression on trend and seasonality |
| backtest.py | A rolling-origin backtest, forecast intervals, and the reorder point |
| demo.py / test_forecast.py | The script that runs everything, and a unittest suite with 11 cases |
Product A sells steadily with an upward trend. Product B sells less and was out of stock for eight weeks in the second year. Product C sells intermittently, mostly zero or one unit. Every product has four festival weeks a year (start of the year, Songkran, 11.11, and the end of the year). This calendar is known in advance, so it can be used as a model variable.
Step 1: cleaning: stockouts, empty data, negative values, duplicate rows
The file sales.csv contains bad rows that were put in on purpose: one negative sales row (a correction that was entered as negative sales), one empty sales row, and a week that was entered twice. In addition, product B has a stockout column marking the weeks it was out of stock, where the recorded sales are only leftover scraps.
"""Load sales.csv and turn it into demand arrays. Stock-out weeks become NaN, not small numbers."""
import csv
from datetime import date
import numpy as np
def load(path, censor=True):
"""Return ({sku: demand array with NaN}, {sku: event flags}, report list)."""
rows, report = {}, []
with open(path, newline="") as f:
for r in csv.DictReader(f):
key = (r["sku"], r["week_start"])
if key in rows:
report.append(f"duplicate {key[0]} {key[1]}: keep the later row")
rows[key] = r # later row wins
skus = sorted({k[0] for k in rows})
weeks = sorted({k[1] for k in rows})
t0 = date.fromisoformat(weeks[0])
out, events = {}, {}
for s in skus:
y = np.full(len(weeks), np.nan)
ev = np.zeros(len(weeks))
for k, r in rows.items():
if k[0] != s:
continue
i = (date.fromisoformat(k[1]) - t0).days // 7
ev[i] = float(r["event"])
if r["units"] == "":
report.append(f"{s} {k[1]}: units blank -> unknown (NaN)")
elif float(r["units"]) < 0:
report.append(f"{s} {k[1]}: negative units {r['units']} -> unknown (NaN)")
elif r["stockout"] == "1" and censor:
report.append(f"{s} {k[1]}: stock-out, recorded {r['units']} -> censored (NaN)")
else:
y[i] = float(r["units"])
out[s], events[s] = y, ev
return out, events, report- A stockout week becomes NaN, not zero, because we do not know what the real demand was. Guessing a number and teaching the model with it is riskier than leaving it empty, so we leave it as NaN and let the fitting step skip it. (Estimating the demand for that period properly needs a dedicated method, which is outside this example.)
- Every row that is fixed or dropped needs a report line, so a person can go back and ask the source, instead of fixing things silently.
- This example does not separate the causes of empty data. In real work you must ask whether it is empty because nothing was entered or because nothing could be sold. The two are not the same.
Step 2: metrics: MAE, WAPE, MASE, and why MAPE breaks when there are zeros
"""Accuracy measures (Hyndman & Athanasopoulos, FPP3 ch. 5.8). NaN actuals are skipped."""
import numpy as np
def _pairs(y, f):
y, f = np.asarray(y, float), np.asarray(f, float)
m = ~np.isnan(y) & ~np.isnan(f)
return y[m], f[m]
def mae(y, f):
y, f = _pairs(y, f)
return float(np.mean(np.abs(y - f)))
def wape(y, f):
"""Sum of absolute errors / sum of actuals: stays finite when single weeks are zero."""
y, f = _pairs(y, f)
return float(np.sum(np.abs(y - f)) / np.sum(np.abs(y)))
def mape(y, f):
"""Mean absolute percentage error. Undefined (inf) if any actual is 0."""
y, f = _pairs(y, f)
if np.any(y == 0):
return float("inf")
return float(np.mean(np.abs((y - f) / y)))
def seasonal_naive_scale(train, m):
"""In-sample MAE of the seasonal naive forecast: the denominator of MASE."""
train = np.asarray(train, float)
d = np.abs(train[m:] - train[:-m])
return float(np.nanmean(d))
def mase(y, f, scale):
"""MAE divided by the training seasonal-naive MAE. Below 1 = better than seasonal naive."""
return mae(y, f) / scale- MAE is the mean of the absolute errors, in units. Read it directly: how many units the forecast misses by per week.
- WAPE is the sum of the absolute errors divided by the sum of actual sales, giving a percentage that can still be computed even when some weeks are zero. Note that this name is common in the field but is not a metric in the FPP3 textbook. We use it because the formula is simple and can be explained to executives.
- MAPE divides by the actual value week by week. If any week has zero sales, it cannot be computed. The example returns inf, in line with the textbook saying it is undefined when any actual value is zero, and when the actual value is very small, MAPE jumps abnormally high.
- MASE divides the model's MAE by the MAE of seasonal naive on the training data. It can be used to compare across products of different sizes. A value below 1 means better than seasonal naive on the training data (the denominator is computed from the first two years, not from seasonal naive's results on the test period).
Step 3: baselines and one regression model
The baselines you need before saying AI are naive (use the latest week's sales), an eight-week moving average, and seasonal naive (use the same week of last year). That last one is the finish line the model has to cross.
def seasonal_naive(y, h, **_):
t = len(y)
out = []
for i in range(h):
v = y[t + i - M] # same week last year (needs i < M)
# simplified: if last year's week is unknown use the mean of the last 4 valid weeks;
# production: use the average of the same week in earlier years or an interpolated value.
out.append(_last_valid(y) if np.isnan(v) else v)
return np.array(out)The model we try is a least-squares linear regression with a constant term, a time trend, two pairs of yearly sin and cos waves, and a festival-week flag. It is fitted with numpy lstsq, using only the weeks where sales are known.
def design(t, event):
t = np.asarray(t, float)
cols = [np.ones_like(t), t]
for k in (1, 2):
cols += [np.sin(2 * np.pi * k * t / M), np.cos(2 * np.pi * k * t / M)]
cols.append(event[t.astype(int)])
return np.column_stack(cols)
def regression(y, h, event=None, **_):
"""Trend + 2 yearly harmonics + event flag, fitted by least squares on known weeks only."""
t = np.arange(len(y))
ok = ~np.isnan(y)
beta, *_ = np.linalg.lstsq(design(t[ok], event), y[ok], rcond=None)
pred = design(np.arange(len(y), len(y) + h), event) @ beta
return np.maximum(pred, 0)This is not the best model, and it is not meant to be. It was chosen because the code is short, the coefficients can be read, and it is easy to see whether each part helps. If a fair test does not show it beating seasonal naive, there is no need to build anything more complicated.
Step 4: a rolling-origin backtest that does not leak
The example sets it up like this: train on the first two years (104 weeks), forecast four weeks ahead, then move the starting point forward two weeks at a time until week 156, giving 25 rounds. In each round the model sees only the data before the starting point. This matches what FPP3 and TimeSeriesSplit describe.
def origins(n, first, h, step):
"""Forecast origins: train on y[:o], test on y[o:o+h]. Test never overlaps train."""
return [o for o in range(first, n - h + 1, step)]
def run(y, model, event, first=104, h=4, step=2):
"""Return list of (origin, forecast, actual). The model only ever sees y[:o]."""
out = []
for o in origins(len(y), first, h, step):
hist = y[:o].copy() # copy: a model cannot peek at the future by accident
f = model(hist, h, event=event)
out.append((o, f, y[o:o + h]))
return out- Pass y[:o].copy() to the model, not the full array. Even if the model is written wrongly, it cannot see the future.
- A common mistake is splitting training and test data at random. The weeks after a test point then sit in the training set, and the model sees the trend ahead of time, so the score is unrealistically good.
- The festival calendar for the future can be passed in because it is known in advance, but future sales are strictly forbidden.
- Overlapping rounds (two weeks at a time, forecasting four weeks) mean the errors of different rounds are not independent. The score therefore carries more uncertainty than the number of rounds suggests.
A real run: results for every method and every product
demo.py runs all the steps. The metrics are computed from the errors of all rounds pooled together, skipping weeks where the actual value is unknown.
for sku, y in data.items():
scale = mt.seasonal_naive_scale(y[:FIRST], models.M)
print(f"\nSKU {sku} (MASE scale = {scale:.2f} units)")
print(f" {'model':<16}{'MAE':>8}{'WAPE':>8}{'MAPE':>8}{'MASE':>8}")
for name, m in MODELS.items():
res = bt.run(y, m, event)
results[sku, name] = res
a, f = bt.stack(res)
print(f" {name:<16}{mt.mae(a, f):>8.2f}{mt.wape(a, f):>8.2f}{fmt(mt.mape(a, f)):>8}{mt.mase(a, f, scale):>8.2f}")
best = min(MODELS, key=lambda k: mt.mae(*bt.stack(results[sku, k])))
sn = mt.mae(*bt.stack(results[sku, "seasonal naive"]))
reg = mt.mae(*bt.stack(results[sku, "regression"]))
print(f" regression vs seasonal naive MAE: {reg:.2f} vs {sn:.2f} -> "
f"{'regression wins' if reg < sn else 'seasonal naive is enough'} (best overall: {best})")== 1. cleaning report ==
duplicate A 2023-12-18: keep the later row
A 2023-07-31: negative units -5 -> unknown (NaN)
A 2024-09-23: units blank -> unknown (NaN)
B 2024-05-06: stock-out, recorded 0 -> censored (NaN)
B 2024-05-13: stock-out, recorded 2 -> censored (NaN)
B 2024-05-20: stock-out, recorded 1 -> censored (NaN)
B 2024-05-27: stock-out, recorded 1 -> censored (NaN)
B 2024-06-03: stock-out, recorded 2 -> censored (NaN)
B 2024-06-10: stock-out, recorded 0 -> censored (NaN)
B 2024-06-17: stock-out, recorded 1 -> censored (NaN)
B 2024-06-24: stock-out, recorded 0 -> censored (NaN)
== 2. rolling-origin backtest: first origin week 104, horizon 4, step 2 ==
origins: 25 | test weeks scored 104..155, stock-out weeks skipped
SKU A (MASE scale = 12.00 units)
model MAE WAPE MAPE MASE
naive 27.10 0.17 0.17 2.26
seasonal naive 18.54 0.12 0.11 1.54
moving avg 8w 25.30 0.16 0.16 2.11
regression 11.84 0.07 0.07 0.99
regression vs seasonal naive MAE: 11.84 vs 18.54 -> regression wins (best overall: regression)
SKU B (MASE scale = 9.07 units)
model MAE WAPE MAPE MASE
naive 12.95 0.17 0.16 1.43
seasonal naive 8.73 0.11 0.11 0.96
moving avg 8w 10.06 0.13 0.13 1.11
regression 6.21 0.08 0.08 0.68
regression vs seasonal naive MAE: 6.21 vs 8.73 -> regression wins (best overall: regression)
SKU C (MASE scale = 0.85 units)
model MAE WAPE MAPE MASE
naive 1.20 1.25 inf 1.42
seasonal naive 0.99 1.03 inf 1.17
moving avg 8w 0.88 0.92 inf 1.04
regression 0.87 0.90 inf 1.03
regression vs seasonal naive MAE: 0.87 vs 0.99 -> regression wins (best overall: regression)
== 3. stock-out: treat zeros as demand or as unknown (SKU B, regression) ==
stock-out weeks as sales MAE 14.91
stock-out weeks as unknown MAE 6.21
forecast weeks 104-107 trained on raw: [81.5 39.6 41.7 44. ] cleaned: [88.6 51.9 53.3 54.9]
== 4. prediction interval 10-90% (SKU A, regression) ==
residual quantiles from first 12 origins; coverage on the other 13: 73% (target 80%)
== 5. reorder point (lead time 2 weeks, service 95%) ==
SKU A: forecast next 2 weeks 332 + safety stock 58 = reorder point 391 (errors from 25 origins)
SKU B: forecast next 2 weeks 159 + safety stock 16 = reorder point 175 (errors from 25 origins)Reading the output step by step
- The cleaning report caught everything: the duplicate row, the negative sales, the empty sales, and the eight stockout weeks of product B (some weeks were recorded as 0 to 2 units).
- Product A: seasonal naive has an MAE of 18.54 and the regression has 11.84 (MASE 1.54 against 0.99). The regression wins clearly, because sales trend upward and copying last year cannot keep up. But remember that the data was generated to have this pattern.
- Product B: seasonal naive 8.73, regression 6.21. The regression wins again, partly because seasonal naive has to use a fallback value when last year's week was a stockout.
- Product C: MAPE is inf for every method because some weeks have zero sales. WAPE is about 0.9 to 1.25, meaning the error is as large as the sales themselves. The regression (0.87) is not clearly different from the moving average (0.88) and beats seasonal naive (0.99) only slightly. A difference this small should not be taken as evidence that it found a pattern. For a product like this, an accurate weekly sales forecast cannot be done. Set the stock policy from the average sales rate and the risk you can accept.
- The last line printed for each product compares only the regression with seasonal naive and names the method with the lowest MAE. It does not test statistical significance. If the difference is small (as with product C), choose the simpler method.
The effect of counting stockouts as sales
raw, _, _ = load("sales.csv", censor=False)
for label, d in (("stock-out weeks as sales", raw), ("stock-out weeks as unknown", data)):
res = bt.run(d["B"], models.regression, event)
o = np.array([r[0] for r in res])
# score against the cleaned series so both variants face the same real demand
a = np.concatenate([data["B"][x:x + H] for x in o])
f = np.concatenate([r[1] for r in res])
print(f" {label:<28} MAE {mt.mae(a, f):.2f}")
fit_raw = models.regression(raw["B"][:FIRST], 4, event=event)
fit_cln = models.regression(data["B"][:FIRST], 4, event=event)
print(" forecast weeks 104-107 trained on raw:", np.round(fit_raw, 1), " cleaned:", np.round(fit_cln, 1))In section 3 of the output, if stockouts are counted as sales, the regression's MAE is 14.91, but if they are treated as unknown it is 6.21, and the forecasts for weeks 104 to 107 differ clearly (about 11 to 12 units lower in the last three weeks, from 51.9, 53.3, 54.9 down to 39.6, 41.7, 44.0). All of this comes only from changing how those eight weeks are handled. The model and the rest of the data are unchanged.
Step 5: forecast intervals from backtest errors
A single point forecast looks more certain than it is. The simplest way that needs no distribution assumption is to collect the errors (actual minus forecast) from the backtest and add the 10th and 90th percentile quantiles to the point forecast, giving an 80 percent interval. The FPP3 textbook calls a similar idea bootstrapped residuals, which is based on sampling full future paths. This example does a simplified version.
def interval(point, residuals, lo=0.1, hi=0.9):
"""Add empirical residual quantiles to a point forecast (FPP3: bootstrapped residual intervals, simplified)."""
q = np.nanquantile(residuals, [lo, hi])
return np.maximum(point + q[0], 0), point + q[1]
def reorder_point(point, results, lead=2, service=0.95):
"""Forecast demand over the lead time plus safety stock from backtest errors summed over `lead` weeks."""
errs = []
for _, f, a in results:
e = a[:lead] - f[:lead]
if not np.isnan(e).any():
errs.append(e.sum())
safety = max(0.0, float(np.quantile(errs, service)))
return float(np.sum(point[:lead])) + safety, safety, len(errs) res = results["A", "regression"]
half = len(res) // 2
resid = np.array([x for r in res[:half] for x in (r[2] - r[1])])
lo, hi = bt.interval(np.concatenate([r[1] for r in res[half:]]), resid)
a2 = np.concatenate([r[2] for r in res[half:]])
ok = ~np.isnan(a2)
print(f" residual quantiles from first {half} origins; coverage on the other {len(res) - half}: "
f"{np.mean((a2[ok] >= lo[ok]) & (a2[ok] <= hi[ok])):.0%} (target 80%)")The result is that the interval covered 73 percent of actual values in the second half, although the target was 80. This example has only a bit over ten rounds per half, and the rounds overlap, so it is no surprise that it misses the target. It is still a warning: do not trust an interval computed from a small sample too much, and always check coverage against data that was not used to set the interval.
Step 6: from forecast to reorder point and safety stock
The real decision is how much stock should be left when you place an order. The reorder point equals the sales expected during the lead time, plus safety stock to cover forecast misses. In the example, safety stock comes from the cumulative errors of the first two weeks in each backtest round, taking the 95th percentile. The reorder_point function in backtest.py above does this.
print("\n== 5. reorder point (lead time 2 weeks, service 95%) ==")
for sku in "AB":
point = models.regression(data[sku], H, event=event)
rop, ss, k = bt.reorder_point(point, results[sku, "regression"])
print(f" SKU {sku}: forecast next 2 weeks {point[:2].sum():.0f} + safety stock {ss:.0f} "
f"= reorder point {rop:.0f} (errors from {k} origins)")The results: for product A, the two-week forecast is 332 units, plus safety stock of 58, giving a reorder point of 391 units. For product B, 159 plus 16 equals 175 units. The 95 percent figure from 25 overlapping rounds is only a rough estimate, and it does not include the uncertainty of the lead time itself, price, holding cost or minimum order quantity. These need to be discussed with the purchasing team.
If you have seen the safety stock formula of z times the standard deviation times the square root of the lead time, it assumes that errors are normally distributed and that each week is independent. This example avoids that by measuring the actual cumulative errors from the backtest. The formula itself is not cited from a source in this article.
The test suite: metrics match the formulas and the backtest does not leak
test_forecast.py has 11 cases. Running python3 -m unittest gives OK. Two groups of cases matter most: the metric formulas, and no leakage.
class MetricTests(unittest.TestCase):
def test_formulas_by_hand(self):
y, f = [10, 20, 30], [12, 18, 33] # errors 2, 2, 3
self.assertAlmostEqual(mt.mae(y, f), 7 / 3)
self.assertAlmostEqual(mt.wape(y, f), 7 / 60)
self.assertAlmostEqual(mt.mape(y, f), (0.2 + 0.1 + 0.1) / 3)
self.assertAlmostEqual(mt.mase(y, f, scale=2.0), 7 / 3 / 2.0)
def test_mape_breaks_on_zero_wape_does_not(self):
y, f = [0, 4, 0, 2], [1, 3, 1, 2]
self.assertEqual(mt.mape(y, f), float("inf"))
self.assertAlmostEqual(mt.wape(y, f), 3 / 6)
def test_mase_scale_is_seasonal_naive_mae(self):
train = [1, 2, 3, 4, 3, 4, 5, 6] # m=4: |3-1|,|4-2|,|5-3|,|6-4| all 2
self.assertAlmostEqual(mt.seasonal_naive_scale(train, 4), 2.0)
def test_nan_actuals_are_skipped(self):
self.assertAlmostEqual(mt.mae([1, np.nan, 3], [2, 9, 3]), 0.5) def test_model_only_sees_the_past(self):
y = np.arange(156, dtype=float)
seen = []
def spy(hist, h, event=None):
seen.append(hist.copy())
return np.zeros(h)
res = bt.run(y, spy, np.zeros(200))
for (o, _, actual), hist in zip(res, seen):
self.assertEqual(len(hist), o)
self.assertTrue(np.array_equal(hist, y[:o]))
self.assertTrue(np.array_equal(actual, y[o:o + 4]))
def test_changing_the_future_does_not_change_forecasts(self):
rng = np.random.default_rng(1)
y = rng.uniform(50, 100, 156)
ev = np.zeros(200)
y2 = y.copy()
y2[120:] = 1e9 # poison everything after origin 120
for m in (models.naive, models.seasonal_naive, models.moving_average, models.regression):
r1 = bt.run(y, m, ev)
r2 = bt.run(y2, m, ev)
checked = 0
for (o, f1, _), (_, f2, _) in zip(r1, r2):
if o <= 120: # origins at or before 120 must not feel the poisoned future
self.assertTrue(np.allclose(f1, f2), (m.__name__, o))
checked += 1
self.assertGreater(checked, 5)- The spy case passes in a fake model that records the data it receives, then confirms that the length equals the starting point exactly and the content matches y[:o].
- The case that sets future sales to 1e9 is applied to every model. If any model secretly looks at the future, the forecasts of earlier rounds will change.
- This test checks that the example code does not leak. It does not guarantee that your real data does not leak, which requires checking that every variable is truly known in advance at the time you have to place the order.
Putting it into practice: what to change from the example
- Product level and frequency: decide first whether to forecast weekly at SKU level or monthly by product group, to match the ordering cycle, not the data you happen to have.
- Festival and promotion calendar: keep it as a table that can be planned in advance. Festivals that move (on the lunar calendar) must have their actual dates specified every year, not fixed week numbers as in the example.
- Stockouts: record the actual stockout dates from the inventory system, rather than guessing from zero sales, which cannot be told apart from nobody buying.
- Next models: only when the regression truly beats seasonal naive on real data, try other methods (exponential smoothing, ARIMA, gradient boosting), and judge them with the same backtest.
- Monitoring after launch: compare forecasts with actual sales every week, and set conditions for retraining or falling back to seasonal naive.
- Longer data: the example has three years. A yearly seasonality fitted from two years of history has very little evidence behind it. For real data, the longer the better.
Hypothetical examples: applying it to three businesses
A building materials shop that runs out of stock at the start of the rainy season
You need a record of which days items were out of stock before training anything. If you do not have one, start collecting it today, and in the meantime use seasonal naive with the stockout periods filled in using values the sales team estimates. The effect of this uncertainty should be reflected in safety stock.
A snack manufacturer whose sales spike with festivals
A festival flag helps the regression model a lot, but the effect of each festival (Songkran versus New Year) differs. Try separate flags per festival once there are enough years of data, and check whether it beats seasonal naive in the backtest rounds that cover those festivals, rather than averaging over the whole year.
A parts distributor with intermittent sales
Parts that sell only a few units a year should not be forecast weekly. Try aggregating by month or by group, or use a minimum stock policy and check when a quotation comes in. Use WAPE and MASE as metrics, not MAPE.
Common mistakes and a checklist
- Splitting training and test data at random, which lets the model see the future.
- Counting stockout weeks as sales, so the model learns that demand is low.
- Having no baseline, or comparing only against a method nobody uses, and not against seasonal naive.
- Using MAPE on products that have zero sales, which gives infinite or distorted results.
- Reporting only the average across all products, where high-volume products hide the ones that miss badly.
- Using variables that are not known in advance when you place the order, such as that month's own sales.
- Tuning parameters repeatedly against the test results until the model memorizes the exam.
- Trusting forecast intervals whose coverage has never been checked.
- Mark stockout weeks, empty data and negative values, and keep a report of the fixes.
- Set the product level, frequency and horizon to match the ordering cycle.
- Set baselines of at least naive and seasonal naive, and agree on the metrics and the criteria for better before seeing the results.
- Run a rolling-origin backtest where the model sees only the past of each point.
- Report results per product, using MAE, WAPE and MASE.
- Accept the model only when it beats seasonal naive consistently. If the difference is small, use the simpler method.
- Build forecast intervals, check coverage, then convert them into reorder points together with the purchasing team.
- Set monitoring points and conditions for reviewing the model after launch.
Limitations of the example: the data is fictional and was generated to match the form of the regression model, so the wins are overstated. It does not build a full bootstrap forecast interval, does not estimate demand during stockouts, has no parameter selection, has no new or discontinued products, does not include lead-time uncertainty, and the safety stock does not consider cost. Use it for learning, not as production-ready code. All data was generated by us.
References
- Forecasting: Principles and Practice (3rd ed.): Some simple forecasting methods (mean, naive, seasonal naive, drift) (accessed 2026-11-21)
- Forecasting: Principles and Practice (3rd ed.): Evaluating point forecast accuracy (MAE, MAPE, MASE) (accessed 2026-11-21)
- Forecasting: Principles and Practice (3rd ed.): Time series cross-validation (rolling forecasting origin) (accessed 2026-11-21)
- Forecasting: Principles and Practice (3rd ed.): Prediction intervals (bootstrapped residuals) (accessed 2026-11-21)
- Forecasting: Principles and Practice (3rd ed.): Dealing with outliers and missing values (accessed 2026-11-21)
- scikit-learn: TimeSeriesSplit (accessed 2026-11-21)
- NumPy: numpy.linalg.lstsq (accessed 2026-11-21)




