Skip to main content
LearnMLAcademy
Intermediate10 min read

Sales Forecasting — End-to-End Time-Series Project

Forecast multi-store retail sales using lag features and chronological splits, with reproducible setup, model evaluation, and an end-to-end project task.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

1. Project Goal

Forecast monthly retail sales six months ahead so inventory planners can compare a simple baseline with a seasonal model, understand every evaluation value and monitor when the time series changes.

2. What You Will Build

A deterministic 36-month retail series with trend, seasonality and small noise
Chronological train, validation and test windows
Naive and moving-average/statistical baselines plus Holt-Winters
Actual-versus-forecast and residual diagnostics with MAE and RMSE

3. Skills / Prerequisites

Review unfamiliar foundations before implementing the project. Each link points to an existing lesson used by the workflow.

4. Dataset or Inputs

The example generates one sales total for the first day of each month. In a real file, each row needs a timestamp, the amount being forecast and only covariates that would be known before the forecast is issued.

Understand every project input

Understand every project input
ElementValueWhy it matters
FrequencymonthlyAll observations share one regular interval
History36 monthsTwo years train, six months validate, six months test
Forecast horizon6 monthsHow far future decisions must extend
Season length12One yearly cycle contains 12 monthly observations
Random seed42Makes the synthetic noise reproducible

5. Architecture / Workflow

Order observations by timestamp and resolve missing periods.

Reserve the newest horizon as test and the preceding horizon as validation.

Fit baselines and stronger candidates without using future observations.

Refit the selected approach through validation, forecast test, diagnose residuals and monitor new errors.

Project figure

Forecasting respects time: past trains, future tests

Why must the split preserve chronological order?

TRAIN
months 1–24
VALIDATE
25–30
TEST
31–36
oldest evidenceforecast horizon →newest unseen months
Training ends before validation begins, and validation ends before the final test horizon. Random shuffling would let future seasonal patterns leak into model development.

6. Environment / Dependencies

  • Python 3.10+
  • NumPy and pandas
  • scikit-learn metrics
  • statsmodels for Holt-Winters

7. Data or Input Understanding

Plot the series before modeling. Trend is the long-term direction; seasonality is a pattern repeating at a known period; noise is remaining variation.

A random train/test split destroys the forecasting question because future months can teach the model about earlier months. Every transformation, lag and rolling value must use only information available at that timestamp.

8. Baseline / Simplest Working Approach

The naive forecast repeats the last observed value. A seasonal naive baseline repeats the value from 12 months earlier. These are hard to beat when the series is persistent or strongly seasonal.

Holt-Winters adds level, trend and seasonality. It is stronger than a flat baseline while remaining interpretable and consistent with existing dependencies.

Project figure

Actual sales versus two reproducible forecasts

Does the stronger model improve on the naive last-value baseline?

actualseasonal forecastheld-out month
The seasonal model follows the repeating pattern more closely than the flat naive forecast. MAE and RMSE below the chart must be computed only on the held-out horizon.

Worked Example: Calculate MAE and RMSE for four months

Given: Actual sales are [102, 108, 111, 115] and forecasts are [100, 111, 110, 119]. Residuals actual − forecast are [2, −3, 1, −4].

  1. 1Absolute errors are [2, 3, 1, 4]; their sum is 10.
  2. 2MAE = 10 / 4 = 2.50 sales units.
  3. 3Squared errors are [4, 9, 1, 16]; their sum is 30.
  4. 4RMSE = √(30 / 4) = √7.5 = 2.74 sales units.

Interpretation: Both metrics use the same four future errors. RMSE is larger because squaring gives the four-unit miss extra weight.

9. Step-by-Step Implementation

Step 1: Generate and split the series

The trend adds 1.5 units each month; the sine term repeats every 12 months; the seeded noise adds realistic variation.

Generate and split the seriesRUNNABLE CODE
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
months = pd.date_range("2023-01-01", periods=36, freq="MS")
trend = np.arange(36) * 1.5
season = 12 * np.sin(2 * np.pi * np.arange(36) / 12)
sales = 120 + trend + season + rng.normal(0, 3, 36)
series = pd.Series(sales, index=months, name="sales")

train = series.iloc[:24]
validation = series.iloc[24:30]
test = series.iloc[30:]

# Naive forecast: the last observed training value for every validation month.
naive_validation = np.repeat(train.iloc[-1], len(validation))
Representative expected output: Expected shapes: train=24, validation=6, test=6.

Step 2: Fit the seasonal candidate

The model estimates level, additive trend and a 12-month seasonal pattern from train only.

Fit the seasonal candidateRUNNABLE CODE
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from sklearn.metrics import mean_absolute_error, mean_squared_error

# 12 means one yearly season contains 12 monthly observations.
model = ExponentialSmoothing(train, trend="add", seasonal="add", seasonal_periods=12)
fit = model.fit(optimized=True)
forecast = fit.forecast(len(validation))

mae = mean_absolute_error(validation, forecast)
rmse = mean_squared_error(validation, forecast) ** 0.5
print(f"validation MAE={mae:.2f}, RMSE={rmse:.2f}")

Step 3: Refit only after choosing

After validation selects a method, combine train and validation, refit once and forecast exactly six untouched test months.

Refit only after choosingRUNNABLE CODE
development = pd.concat([train, validation])
final_fit = ExponentialSmoothing(
    development, trend="add", seasonal="add", seasonal_periods=12
).fit()
test_forecast = final_fit.forecast(6)

10. Expected Results / Outputs

Read the output as evidence, not decoration

Read the output as evidence, not decoration
ModelValidation MAEValidation RMSEReading
Last-value naive13.415.1Misses trend and seasonal movement
12-month seasonal naive6.87.5Strong transparent baseline
Holt-Winters4.95.7Best candidate on this fixed validation horizon

11. Evaluation

Evaluate at the exact business horizon and report units. MAE = 4.9 means the forecast misses by about 4.9 sales units per validation month on average.

Plot residuals by time and season. Runs above zero mean under-forecasting; increasing spread suggests changing variance; one large error may correspond to a promotion, stock-out or data issue.

Project figure

Residuals reveal when the forecast is systematically wrong

Are errors centered near zero, or do they form a pattern?

0Forecast month12345678
Residual = actual − forecast. Mostly balanced dots around zero suggest no obvious bias; the large positive error in month 6 is a business event worth investigating.

12. Failure Analysis

Failure mode → diagnosis → response

Failure mode → diagnosis → response
Observed failureLikely causeNext action
Excellent validation, poor testTuned repeatedly to one six-month windowUse rolling-origin backtests
Future leakageCentered rolling mean or random splitUse past-only features and chronological folds
Seasonal missWrong period or structural changeRecheck frequency and business calendar
Large event residualPromotion/stock-out absent from inputsAdd known-ahead event features or scenarios

13. Improve the Project

Use rolling-origin validation across several historical horizons.
Add holidays and planned promotions only when known at forecast time.
Compare ARIMA or gradient-boosted lag models after strong baselines.
Produce prediction intervals so planners see uncertainty, not only a point.

14. Production Considerations

What changes beyond the notebook

What changes beyond the notebook
AreaProduction requirement
ScheduleGenerate six-month forecast after each monthly close
Data checksMissing dates, revisions, stock-outs and unit changes
MonitoringMAE/RMSE by horizon, residual bias and interval coverage
ResponseInvestigate drift, refit, or switch to fallback baseline

15. Summary / Key Takeaways

  • A forecasting dataset is ordered evidence, so development and testing must preserve time.
  • The forecast horizon determines how data is split and which errors matter to the business.
  • Last-value and seasonal-naive forecasts are essential baselines, not throwaway demos.
  • Holt-Winters adds interpretable level, trend and seasonal components without future leakage.
  • MAE gives the average absolute miss, while RMSE emphasizes larger misses.
  • Residual plots reveal bias, missing events and structural change that one metric can hide.
  • Production forecasting needs scheduled data checks, horizon-specific monitoring, uncertainty and a reliable fallback.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Sales Forecasting — End-to-End Time-Series Project"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
Why is a random train/test split wrong for monthly sales forecasting?
Question 2 of 5numerical/formula
Absolute forecast errors are 2, 3, 1 and 4. What is MAE?
Question 3 of 5interpretation
What does seasonal_periods=12 mean for monthly data?
Question 4 of 5practical selection
Which baseline best tests a strongly yearly seasonal monthly series?
Question 5 of 5debugging/diagnostic
Residuals remain positive for six consecutive forecast months. What does this suggest?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Why is a random train/test split wrong for monthly sales forecasting?▼

Correct Answer: It can let future observations influence model development for earlier periods

Forecasts must simulate predicting an unseen future from the past. Random shuffling breaks that chronological boundary.

2Absolute forecast errors are 2, 3, 1 and 4. What is MAE?▼

Correct Answer: 2.5

MAE = (2+3+1+4)/4 = 10/4 = 2.5 units.

3What does seasonal_periods=12 mean for monthly data?▼

Correct Answer: One repeating seasonal cycle is modeled as 12 monthly observations

Monthly yearly seasonality repeats after 12 observations, so the model estimates one 12-month seasonal pattern.

4Which baseline best tests a strongly yearly seasonal monthly series?▼

Correct Answer: Repeat the value from 12 months earlier

A seasonal-naive baseline repeats the corresponding observation from the previous yearly cycle and is a strong transparent comparator.

5Residuals remain positive for six consecutive forecast months. What does this suggest?▼

Correct Answer: Systematic under-forecasting

Residual = actual − forecast. Positive residuals mean actual sales repeatedly exceed forecasts, indicating downward bias.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next