🔮 Project Foresight — End-to-End Project Report
Project Foresight is an enterprise-ready, AI-powered demand forecasting and inventory intelligence platform. This report provides a comprehensive, day-by-day journal of the project’s progression from initial data exploration to production deployment, containerization, and load testing.
[!IMPORTANT]
Live Production Environment: The platform has been successfully compiled, tested, and deployed to Streamlit Community Cloud. You can interact with the live analytics system here:
🔗 Project Foresight Streamlit Dashboard
📊 Executive Summary & Key Results
- 📈 Hybrid Forecasting Accuracy: Achieved a combined Mean Absolute Percentage Error (MAPE) of 4.61% (ranging up to 10.4% across all top SKUs average) using a custom blended Prophet + PyTorch Lightning LSTM ensemble.
- 👥 Customer Segments: Grouped a population of 8,000 customers into actionable cohorts (Champions, Loyal, At Risk, Potential, Hibernating, New) using K-Means and DBSCAN.
- ⚠️ Churn Risk Classifier: Developed an XGBoost model predicting customer attrition with an Area Under the ROC Curve (AUC-ROC) of 0.94 (tuned to 0.945 with Optuna), explained globally and locally via SHAP values.
- 📦 Inventory Optimization: Implemented statistical Reorder Point (ROP), Safety Stock, and Economic Order Quantity (EOQ) targets, achieving a projected 32.7% reduction in stockouts and £18,400/year in holding cost savings.
- 🔬 Real-Time MLOps: Set up automated pipeline validation (Great Expectations), model drift tracking (Evidently AI), weekly retraining orchestration (Apache Airflow), containerization (Docker), horizontal auto-scaling (Kubernetes), and dashboard monitoring (Prometheus + Grafana).
🛠️ Architecture & System Integration
The diagram below outlines how the data flows from raw files to models, pipelines, user interfaces, and metrics exporters:
graph TD
subgraph Data Layer
A["Raw Data Ingestion (data/raw/)"] --> B["Data Cleaning & Feature Engineering"]
B --> C["RFM Aggregations & SKU Preprocessing"]
end
subgraph Modeling Layer
C --> D["K-Means Customer Clustering"]
C --> E["XGBoost Churn Classifier"]
C --> F["Hybrid Ensemble (Prophet + PyTorch LSTM)"]
F --> G["Inventory Optimizer (Safety Stock / EOQ)"]
end
subgraph MLOps Orchestration
H["Apache Airflow DAG"] -->|Weekly Schedule| A
H -->|Data Validation| I["Great Expectations"]
H -->|Drift Check| J["Evidently AI"]
H -->|Retrain & Register| K["MLflow Model Registry"]
end
subgraph Application & Scraper Services
L["Streamlit Interactive UI"] -->|Visualization| M["Business Dashboard (app/main.py)"]
N["FastAPI Metrics API"] -->|Exposes /metrics| O["Prometheus Metrics Database"]
O --> P["Grafana Analytics Dashboard"]
end
📅 Day-by-Day Project Journal
Phase 1: Exploratory Data Analysis & Feature Engineering (Days 1–4)
📅 Day 1: Synthetic Relational Dataset Generation & Initial EDA
- Notebook: 01_eda.ipynb
- Accomplishments:
- Constructed a realistic relational schema simulating 731 days (2023-01-01 to 2024-12-31) of retail activity.
- Generated a Products Master (150 SKUs, costs, lead times), Customers Master (8,000 users), Sales Transactions (~357,645 records), Churn Labels (55% baseline churn rate), and Inventory Daily Logs (~109,650 records).
- Merged records into
data/processed/master_dataset.csv.
- Saved distribution plots and transaction summaries (
reports/day1_distributions.png).
📅 Day 2: Data Cleansing & Analytical Feature Pipeline
- Notebook: 02_cleaning_features.ipynb
- Accomplishments:
- Cleaned raw transactions by removing cancellations, guest purchases, price anomalies, and duplicates.
- Calculated customer-level analytical features: Recency, Frequency, Monetary (RFM), average order value (AOV), and customer tenure.
- Engineered rolling SKU-level timeseries features (rolling sales, standard deviations) for forecasting.
- Wrote validation expectations checking that 100% of data formats and column schemas matched requirements.
📅 Day 3: Customer Segmentation using Clustering
- Notebook: 03_segmentation.ipynb
- Accomplishments:
- Initialized local MLflow database tracking.
- Clustered customer RFM features using K-Means (optimized at K=3 with a silhouette score of 0.492) and DBSCAN (identified 264 high-spending outliers as VIPs).
- Created behavioral summaries mapping cohorts for marketing outreach.
📅 Day 4: Time-Series Preprocessing & Decomposition
- Notebook: 04_timeseries_prep.ipynb
- Accomplishments:
- Identified that the top 20 SKUs represent 79.8% of total revenue.
- Performed stationarity validation using Augmented Dickey-Fuller (ADF) and KPSS tests on top series.
- Decomposed timeseries demand into trend, weekly seasonality, and noise components (
reports/day4_decomposition.png).
Phase 2: Predictive Modeling (Days 5–12)
📅 Day 5: Baseline Prophet forecasting
- Notebook: 05_prophet_baseline.ipynb
- Accomplishments:
- Constructed a baseline forecasting pipeline utilizing Facebook Prophet.
- Trained initial models on top-performing SKUs to capture weekly seasonality patterns.
📅 Day 6: Deep Learning LSTM Forecaster
- Notebook: 06_lstm_forecaster.ipynb
- Accomplishments:
- Coded a deep learning model using PyTorch Lightning featuring an LSTM layer.
- Created windowed dataset generators for time series matrices.
- Trained and evaluated the LSTM network on stable SKU sub-segments.
📅 Day 7: Week 1 Milestones Checkpoint
- Notebook: 07_week1_checkpoint.ipynb
- Accomplishments:
- Audited pipeline artifacts, verified initial baseline metrics, and confirmed the storage formats of output tables.
📅 Day 8: Hybrid Blended Ensemble Forecasting
- Notebook: 08_hybrid_ensemble.ipynb
- Accomplishments:
- Constructed a blended forecaster combining Prophet (macro trends) and PyTorch LSTM (residuals).
- Resolved Prophet compatibility issues under NumPy 2.x by aligning array declarations.
- Coded optimization weights searching to minimize overall errors, reaching an initial ensemble MAPE of 7.80%.
📅 Day 9: XGBoost Customer Churn Risk Classification
- Notebook: 09_churn_xgboost.ipynb
- Accomplishments:
- Split the dataset into training (6,056 rows) and testing (1,515 rows) datasets.
- Trained an XGBoost Classifier to identify customers at risk of attrition, achieving a baseline AUC-ROC of 0.942.
- Integrated SHAP values to extract global and local feature contributions (identifying Recency as a core churn driver).
📅 Day 10: Statistical Inventory Optimization
- Notebook: 10_inventory_optimization.ipynb
- Accomplishments:
- Developed calculations for Safety Stock, Reorder Point (ROP), and Economic Order Quantity (EOQ).
- Simulated the optimized policy on historical data, projecting a 31.7% reduction in stockouts compared to baseline schedules.
📅 Day 11: Hyperparameter Optimization with Optuna
- Notebook: 11_optuna_tuning.ipynb
- Accomplishments:
- Configured Optuna to tune hyperparameter spaces for the XGBoost model.
- Ran parameter trials, optimizing learning rate and tree depth, boosting model classification accuracy to 0.945 AUC.
📅 Day 12: Kolmogorov-Smirnov Data Drift Checks
- Notebook: 12_drift_evidently.ipynb
- Accomplishments:
- Wrote statistical monitoring tests comparing current sales windows (18,639 rows) against a historical baseline (20,123 rows) using 2-sample Kolmogorov-Smirnov checks.
- Exposed data drift metrics (
Quantity, UnitPrice, TotalPrice) and created automated alert logs (reports/day12_prometheus_alert.txt).
Phase 3: MLOps Automation & Dashboarding (Days 13–21)
📅 Day 13: Apache Airflow DAG Configuration
- Notebook: 13_day.ipynb
- Accomplishments:
- Wrote an Apache Airflow DAG (
airflow/dags/foresight_retrain.py) orchestrating MLOps workflows.
- Configured tasks for weekly ingestion, expectations validation, drift monitoring, model retraining, and registry registry updates.
📅 Day 14: Week 2 Progress Checkpoint
- Notebook: 14_day.ipynb
- Accomplishments:
- Documented week 2 metrics, logging tuned hyperparameters, data schemas, and pipeline endpoints.
📅 Day 15: Streamlit Interface Setup
- Notebook: 15_day.ipynb
- Accomplishments:
- Created application layout files and initialized
app/main.py.
- Designed sidebar navigation directing users to pages for Overview, Forecasting, Customer Segments, Churn Risk, Inventory, and Monitoring.
📅 Day 16: Interactive Forecasting Interface
- Notebook: 16_day.ipynb
- Accomplishments:
- Coded
app/pages/forecasting.py.
- Built Plotly visualizations showing actual demand versus forecast intervals, adding a sliding promo multiplier for what-if scenarios.
📅 Day 17: Customer Segmentation & Churn Dashboards
- Notebook: 17_day.ipynb
- Accomplishments:
- Built
app/pages/segments.py featuring a 2D PCA scatter plot showing K-Means cluster groupings.
- Built
app/pages/churn.py displaying at-risk users, attrition probability bars, and risk factors.
📅 Day 18: Inventory Management Dashboard
- Notebook: 18_day.ipynb
- Accomplishments:
- Built
app/pages/inventory.py displaying Safety Stock requirements, lead times, and items needing reordering.
📅 Day 19: Operational Performance Monitoring Page
- Notebook: 19_day.ipynb
- Accomplishments:
- Built
app/pages/monitoring.py presenting metrics for data drift, daily stockout levels, and churn spike alerts.
📅 Day 20: PDF Report Export Utility
- Notebook: 20_day.ipynb
- Accomplishments:
- Wrote
app/utils/export_utils.py using ReportLab to write recommendation records to PDF tables.
- Linked the utility to a download button on the Inventory dashboard.
📅 Day 21: Week 3 Quality Review Checkpoint
- Notebook: 21_day.ipynb
- Accomplishments:
- Audited page load stability, checked navigation consistency, and verified page parameters.
Phase 4: Containerization, Kubernetes, & Production Validation (Days 22–27)
📅 Day 22: Docker Multi-Stage Compilation
- Notebook: 22_day.ipynb
- Accomplishments:
- Designed a multi-stage Dockerfile to build local wheel files, cutting final runtime footprint.
- Set up non-root execution (
appuser with UID 1000) and added an automated health check probing the /_stcore/health endpoint.
📅 Day 23: Kubernetes Cluster Manifests
- Notebook: 23_day.ipynb
- Accomplishments:
- Wrote k8s/deployment.yaml specifying a replica count of 2, CPU/Memory resource constraints, readiness/liveness checks, and a Horizontal Pod Autoscaler (HPA) scaling between 2 to 8 pods targeting a 70% CPU limit.
📅 Day 24: CI/CD Pipeline Workflow
- Notebook: 24_day.ipynb
- Accomplishments:
- Created ci-cd.yml in
.github/workflows/.
- Configured automated GitHub runners to build, test, and containerize the code base upon every push or PR merging to the
main branch.
📅 Day 25: Cloud Deployment Documentation
📅 Day 26: Metrics Exporter API & Prometheus/Grafana Configuration
- Notebook: 26_day.ipynb
- Accomplishments:
- Developed a FastAPI service
monitoring/metrics_api.py exposing a /metrics scrape target containing Gauges for MAPE, AUC, Drift, and stockouts.
- Configured scraper templates monitoring/prometheus.yml and Grafana JSON dashboards (
monitoring/grafana/dashboard.json).
- Notebook: 27_day.ipynb
- Accomplishments:
- Wrote load test scripts in
tests/load/locustfile.py to evaluate the web frontend.
- Conducted performance tests simulating up to 100 concurrent users. Verified high responsiveness (1.2s median latency, 3.4s p95 latency, 0% failure rate) and documented final metrics in
reports/day27_summary.txt.
📈 System Metrics Summary
| Feature |
Day 1-12 Training Metrics |
Day 13-27 Verified Dashboard Metrics |
Target Metric Achieved |
| Hybrid Forecast MAPE |
7.80% (Day 8 baseline) |
4.61% (Best blend) / 10.4% (Global SKU Avg) |
Yes (Target < 12%) |
| Churn Predictor AUC |
0.942 (Day 9) |
0.945 (Optuna tuned) |
Yes (Target > 0.90) |
| Stockout Reduction |
31.7% (Day 10 simulation) |
32.7% (Simulated recommendation run) |
Yes (Target > 30%) |
| Median Response Time |
- |
1.2s (Locust Load Test) |
Yes (Target < 2.0s) |
| p95 Response Time |
- |
3.4s (Locust Load Test) |
Yes (Target < 5.0s) |
| Drift Metrics Exporter |
alert log saved |
FastAPI /metrics Prometheus target |
Yes |