CoolFace
Apppublic

Rishabh5825/Probabilistic-Revenue-Forecasting

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
App README

πŸ“ˆ Probabilistic Revenue Forecasting for E-Commerce Marketing

![Python](https://www.python.org/downloads/) ![Streamlit](https://streamlit.io) ![Scikit-Learn](https://scikit-learn.org/) ![LangGraph](https://langchain-ai.github.io/langgraph/)

A production-grade, end-to-end Bayesian forecasting system that ingests omni-channel marketing data (Google Ads, Meta Ads, Microsoft Ads), generates probabilistic revenue predictions with calibrated uncertainty intervals (P10/P50/P90), and delivers LLM-powered causal summaries β€” all through an interactive Streamlit dashboard.


🎯 The Problem

Marketing teams pour budgets across Google, Meta, and Microsoft campaigns, but have no reliable way to answer: "If I spend X next month, what revenue range should I actually expect?" Point-estimate forecasts hide uncertainty. This system replaces guesswork with mathematically honest confidence intervals so executives know the best case, expected case, and worst case before committing a single dollar.


πŸ—οΈ Architecture & Engineering Principles

This project was built following Bayesian-first and Mathematical Honesty principles.

  1. 1.Probabilistic, Not Point-Estimate: Every forecast is a full posterior distribution via BayesianRidge, not a single number. We draw 5,000 Monte Carlo samples per segment and report P10/P50/P90 revenue intervals so stakeholders see the true uncertainty envelope.
  2. 2.Hierarchical Roll-Up: Forecasts are generated at the Channel Γ— Campaign Type level (e.g., Google β†’ PMAX, Meta β†’ Retargeting), then statistically aggregated upward to channel-level and account-level totals β€” preserving correlation structure across segments.
  3. 3.Recursive Multi-Step Forecasting: Instead of a single jump prediction, the system forecasts one week at a time, feeding predicted values back as lag features for the next week. This prevents the classic "flat-line" failure of naΓ―ve multi-step models.
  4. 4.Zero-Inflation Handling: Sparse segments (e.g., Microsoft Shopping) with >50% zero-revenue weeks get a dampened zero-injection layer on the Monte Carlo samples, preventing the model from hallucinating revenue where none historically existed.
  5. 5.AI-Powered Causal Summaries: A 9-node LangGraph state machine analyzes the numerical forecast outputs, detects anomalies, assesses confidence, and uses Groq (Qwen-2.5-32b) to generate executive-ready causal narratives and budget reallocation opportunities.

✨ Key Features

  • β€”Bayesian Revenue Forecasting: Predicts future revenue across 3 channels and 12+ campaign types using 20+ engineered features including ad-stock lags, seasonality harmonics, holiday flags, YoY growth, and rolling efficiency metrics.
  • β€”Dynamic Budget Simulator: Adjust total budget with a slider and instantly see projected P10/P50/P90 revenue outcomes using fitted OLS response curves with diminishing-returns elasticity (default Ξ± = 0.75).
  • β€”AI Executive Insights: LangGraph orchestrates sequential LLM calls to produce a structured JSON report: executive summary, key revenue drivers, identified risks, statistical anomalies, and concrete budget reallocation opportunities.
  • β€”Interactive Streamlit Dashboard: 5-page clinical-grade UI combining Plotly visualizations with real-time forecasting β€” Account Overview, Channel Drilldown, Budget Simulator, AI Insights, and Historical Data Explorer.
  • β€”Hackathon-Ready Pipeline: Single-command execution via run.sh with pre-trained pickle artifacts, pinned dependencies, and reproducible seeds.

πŸ› οΈ Technology Stack

LayerTechnologies
LanguagePython 3.12
ML & StatsScikit-Learn (BayesianRidge), Statsmodels (OLS), NumPy, Pandas, SciPy
AI / LLMLangChain, LangGraph, Groq API (Qwen-2.5-32b-it)
FrontendStreamlit, Plotly
DeploymentHugging Face Spaces, GitHub

πŸš€ How to Run the Project (Step-by-Step)

To run this entire system end-to-end on your local machine, follow these instructions.

Step 1: Environment Setup

Clone the repository and install the locked dependencies to guarantee reproducibility.

bash
git clone https://github.com/your-username/Probabilistic-Revenue-Forecasting.git
cd Probabilistic-Revenue-Forecasting

# Create and activate a virtual environment
python -m venv .venv
.venv\Scripts\activate          # Windows
# source .venv/bin/activate     # Mac/Linux

# Install all dependencies
pip install -r requirements.txt

Step 2: Configure Environment Variables

Create a .env file in the root directory and add your Groq API keys:

env
GROQ_API_KEY_1=your_groq_api_key_here
GROQ_API_KEY_2=your_second_groq_api_key_here

Note: The AI Insights feature requires valid Groq API keys. All other features work without them.

Step 3: Train the Bayesian Pipeline (One-Time Setup)

This step ingests the raw CSV data, applies schema normalization, engineers 20+ features, fits the BayesianRidge models per segment, and serializes everything to a pickle artifact.

bash
python Forecasting/train.py

You should see "Models successfully saved to pickle/model.pkl" in the terminal.

Step 4: Generate the Baseline Forecast

Load the pre-trained model and produce probabilistic predictions. You can specify a forecast window of 30, 60, or 90 days:

bash
python Forecasting/main.py --data_dir ./data --model_path ./pickle/model.pkl --output_path ./output/predictions.csv

Or simply run the hackathon entry point:

bash
bash run.sh

Step 5: Launch the Dashboard

bash
streamlit run ui_backend/streamlit_app/app.py

A browser window will automatically open at `http://localhost:8501`. You can now view account-level metrics, drill into channels, simulate budget scenarios, and read AI-generated causal insights!


πŸ“‚ Project Structure

text
β”œβ”€β”€ run.sh                       # Single-command entry point (hackathon pipeline)
β”œβ”€β”€ requirements.txt             # Pinned Python dependencies
β”œβ”€β”€ app.py                       # Hugging Face Spaces entry point
β”œβ”€β”€ data/                        # Raw marketing CSV datasets (overwritten at test time)
β”‚   β”œβ”€β”€ google_ads_campaign_stats.csv
β”‚   β”œβ”€β”€ meta_ads_campaign_stats.csv
β”‚   └── bing_campaign_stats.csv
β”œβ”€β”€ pickle/                      # Pre-trained model artifacts
β”‚   └── model.pkl                # Serialized BayesianRidge models + ResponseCurves
β”œβ”€β”€ Forecasting/                 # Core ML pipeline
β”‚   β”œβ”€β”€ train.py                 # Phase 1: Train & serialize models
β”‚   β”œβ”€β”€ main.py                  # Phase 2: Load model β†’ predict β†’ export CSV
β”‚   β”œβ”€β”€ pipeline.py              # Schema normalization & weekly aggregation
β”‚   β”œβ”€β”€ feature_engineering.py   # 20+ feature transformations (lags, seasonality, etc.)
β”‚   β”œβ”€β”€ models.py                # BayesianForecaster & SeasonalNaiveForecaster classes
β”‚   └── budget_simulator.py      # OLS response curve with diminishing-returns elasticity
β”œβ”€β”€ llm_Integration/             # LangGraph AI processing layer
β”‚   β”œβ”€β”€ graph.py                 # 9-node state machine for causal analysis
β”‚   β”œβ”€β”€ config.py                # Groq API & model configuration
β”‚   β”œβ”€β”€ nodes/                   # Individual LangGraph node implementations
β”‚   └── prompts/                 # LLM prompt templates
β”œβ”€β”€ ui_backend/                  # Frontend application
β”‚   └── streamlit_app/           # Streamlit dashboard
β”‚       β”œβ”€β”€ app.py               # Main app entry with sidebar navigation
β”‚       β”œβ”€β”€ pages/               # 5 dashboard pages
β”‚       β”‚   β”œβ”€β”€ 1_Dashboard.py   # Account-level metrics & channel breakdown
β”‚       β”‚   β”œβ”€β”€ 2_Channels.py    # Campaign-type drilldown with efficiency matrix
β”‚       β”‚   β”œβ”€β”€ 3_Budget_Sim.py  # Interactive budget simulator
β”‚       β”‚   β”œβ”€β”€ 4_AI_Insights.py # LangGraph causal summaries
β”‚       β”‚   └── 5_Data_Explorer.py # Historical trend visualization
β”‚       └── styles/              # Custom CSS
└── README.md

πŸ”¬ Model Details & Methodology

ComponentImplementation
Primary ModelBayesianRidge with RobustScaler β€” produces posterior mean + sigma for each prediction
Fallback ModelSeasonalNaiveForecaster β€” activated when a segment has <8 data points
Uncertainty5,000 Monte Carlo samples drawn from N(ΞΌ, Οƒ) in log-space, then expm1-transformed
Bias CorrectionConditional log-normal correction: +0.5σ² only when Οƒ < 1.0 to prevent over-prediction in volatile segments
Zero InflationSegments with >50% zero weeks get dampened zero-injection (50% of historical zero rate)
Response CurvesOLS log-log regression: Revenue = a Γ— Spend^b, with elasticity capped at (0, 1) to enforce diminishing returns
Interval FloorAdaptive minimum interval width scaled by model uncertainty: clip(Οƒ Γ— 0.8, 0.15, 0.50) Γ— P50

⚠️ Deployment Notes

  • β€”Hugging Face Spaces: The dashboard runs as a standalone Streamlit app reading directly from pre-generated JSON artifacts. No backend server required.
  • β€”Hackathon Pipeline: The automated testing system runs ./run.sh ./data ./pickle/model.pkl ./output/predictions.csv β€” this loads the pickle, generates features from the test data, and writes predictions to CSV.
  • β€”LLM Dependency: The AI Insights page requires valid Groq API keys. All forecasting and simulation features work fully offline with no network calls.
  • β€”Reproducibility: Random seed is set to 42 via np.random.seed(42) before all prediction runs. All dependency versions are pinned in requirements.txt.