Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Sales Forecasting

A production-ready time series forecasting pipeline that predicts future retail sales using Facebook Prophet with a full Streamlit dashboard featuring interactive controls, KPI cards, confidence intervals as well as one-click CSV export.

Python Prophet Scikit-learn Streamlit License


Problem Statement

Businesses need to anticipate future demand to make smart decisions around inventory, staffing and marketing spend. This project builds a time series forecasting system that learns from historical daily sales patterns — including trend, weekly seasonality and annual seasonality as well as produces forward-looking predictions with quantified uncertainty.


Dataset Used

Default: 3 years of synthetic daily retail sales (data/data.csv) with realistic trend, seasonality, holiday spikes and noise.

Drop-in alternatives (no code changes needed):

Expected CSV format:

Date Sales Store Category
2021-01-01 972.19 Store_A Electronics
2021-01-02 1158.64 Store_A Home

Methodology

Stage Approach
Date parsing pd.to_datetime() with flexible format detection
Sorting Chronological — never shuffle time series
Missing values Forward-fill → median fallback
Feature engineering Year, month, day, weekday, lag-7, lag-30, lag-365, rolling averages
Train/test split Temporal — last 90 days as holdout (no random split)
Primary model Facebook Prophet — handles trend + seasonality + holidays natively
Baseline model Linear Regression on engineered time features
Evaluation MAE, RMSE, MAPE, R²
Forecast output Daily predictions with 95% confidence interval

Why Prophet over ARIMA?

  • No manual parameter tuning (p, d, q)
  • Robust to missing data and outliers
  • Natively models multiple seasonalities and holiday effects
  • Interpretable components (trend, weekly, yearly decomposition).

Tech Stack

  • Language: Python 3.10+
  • Forecasting: Facebook Prophet
  • ML / Baseline: Scikit-learn
  • Data: Pandas, NumPy
  • Visualisation: Matplotlib
  • UI: Streamlit
  • Persistence: Pickle.

Project Structure

Sales-Forecasting/
│
├── data/
│   └── data.csv                   # 3-year daily retail sales dataset
│
├── src/
│   ├── preprocess.py              # Loading, cleaning, feature engineering, split
│   ├── train.py                   # Prophet + Linear Regression training
│   ├── evaluate.py                # MAE, RMSE, MAPE, R² with comparison table
│   └── utils.py                   # Plotting, forecast summaries, artifact I/O
│
├── models/
│   ├── prophet_model.pkl          # Fitted Prophet model
│   ├── lr_model.pkl               # Fitted Linear Regression baseline
│   ├── lr_scaler.pkl              # StandardScaler for LR features
│   └── forecast.csv              # Pre-computed 90-day forecast
│
├── app.py                         # Streamlit dashboard
├── main.py                        # CLI pipeline entry point
├── requirements.txt
├── .gitignore
└── README.md

Installation

1. Clone the repository

git clone https://github.com/AdarshZolekar/Sales-Forecasting.git
cd Sales-Forecasting

2. Create and activate virtual environment

python -m venv .venv
source .venv/bin/activate       # macOS / Linux
.venv\Scripts\activate          # Windows

3. Install dependencies

pip install -r requirements.txt

Note: Prophet requires cmdstanpy. If you hit issues, run: pip install pystan prophet --upgrade


How to Run

Option A — CLI Pipeline

python main.py

This will:

  1. Load and clean data/data.csv
  2. Parse dates, sort chronologically, engineer time features
  3. Split data: last 90 days = test set
  4. Train Prophet (trend + weekly + yearly + monthly seasonality)
  5. Train Linear Regression baseline
  6. Evaluate both on test set and print comparison
  7. Save all model artifacts + forecast CSV.

Sample output:

==========================================================
   SALES FORECASTING — ML PIPELINE
==========================================================

[STEP 1] Preprocessing data...
[INFO] Loaded 1095 rows.
[INFO] Date range: 2021-01-01 → 2023-12-31
[INFO] Train: 1005 rows | Test: 90 rows (cutoff: 2023-10-02)

[STEP 2] Training models...
[TRAIN] Fitting Prophet model...
[INFO] Prophet test RMSE : 124.83
[TRAIN] Linear Regression — train R²: 0.9312
[INFO] Linear Reg test RMSE: 198.47

[INFO] Best model → Prophet (RMSE = 124.83)

[STEP 3] Evaluating models on test set...
  MAE   : 98.41     RMSE  : 124.83
  MAPE  : 9.12%     R²    : 0.8834

[STEP 5] Pipeline complete.
  Best model  : Prophet
  Test MAPE   : 9.12%

Option B — Streamlit Dashboard

Run python main.py first to generate artifacts.

streamlit run app.py

Open http://localhost:8501.

Dashboard features:

  • Forecast horizon slider — choose 7 to 365 days
  • KPI cards — total forecast, avg daily, peak day, growth vs last 30 days
  • Forecast chart — history + predictions + shaded 95% confidence band
  • Monthly aggregation tab — smoothed trend view
  • Actual vs Predicted toggle — overlays test set performance
  • Components toggle — decompose into trend, weekly and yearly seasonality
  • Download button — one-click CSV export of the forecast.

Model Performance

Results on 1,095-day synthetic dataset (test = last 90 days):

Model MAE RMSE MAPE
Prophet ~98 ~125 ~9% ~0.88
Linear Regression ~155 ~198 ~14% ~0.72

On real-world datasets (Superstore, Rossmann), Prophet typically achieves 8–12% MAPE for daily retail data.


Future Improvements

  • Add external regressors (promotions, weather, holidays) to Prophet
  • Implement SARIMA / ETS as additional baselines
  • Hyperparameter tuning (changepoint_prior_scale, seasonality order)
  • Per-store and per-category forecasting (hierarchical models)
  • Anomaly detection on historical data
  • MLflow experiment tracking
  • Deploy on Streamlit Cloud / AWS / GCP.

License

This project is open-source under the MIT License.


Contributions

Contributions are welcome!

  • Open an issue for bugs or feature requests.

  • Submit a pull request for improvements.

Back to Top

About

Retail sales forecasting with Facebook Prophet and Streamlit.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages