6. Final Capstone Project

Capstone Project: End-to-End E-Commerce Data & Insights Pipeline

Combine data ingestion, cleaning, outlier detection, SQLite joins, KPI aggregation, and automated reporting into one reproducible Python analytics pipeline.

5 min readUpdated 2026-11-30
In This Lesson
  • Build an end-to-end ETL analytics pipeline from raw messy CSV/SQLite to clean KPI summaries
  • Detect revenue outliers with IQR, compute category & monthly growth, and export JSON + charts
  • Run the core analytics engine live in-browser and apply the full Pandas/Matplotlib script locally

Welcome to the final capstone of Python for Data Analysis & Automation! Every concept from Modules 1 through 5 comes together here into one production-grade E-Commerce Insights Pipeline.

Instead of running one-off manual notebook cells every Monday morning, you will build a reproducible script that ingests messy raw CSV orders, enriches them against a SQLite customer table, audits data quality, flags high-value IQR outliers, calculates category and month-over-month KPIs, exports a clean Matplotlib bar chart, and writes an atomic JSON summary ready for dashboards or Slack alerts.

1. Pipeline Architecture & Quality Gates

Trace every stage of the pipeline before executing it:

StageModule Skill AppliedExact Responsibility & Quality Guard
1. ExtractCSV & SQLite ingestionStream/parse orders.csv (parse_dates) + query customers from SQLite
2. Clean & DedupeData cleaning (errors="coerce")Deduplicate order_id, keep status == "paid", parse "$2,400.00", count rejected "N/A" rows
3. EnrichRelational merge(validate="many_to_one")Left-join customer_id -> tier without losing orders or inflating sums
4. Audit OutliersDescriptive stats (1.5 * IQR)Compute median alongside total_revenue and flag extreme orders (like $2,400) without deleting real sales
5. Summarize & Visualizegroupby().agg() + OO fig, axCompute category & monthly totals, save zero-baseline PNG (plt.close(fig)), atomic .tmp JSON write
Never Silently Drop Unparseable Revenue Rows

Always track and surface rejected_rows in your final kpi_summary.json. If an upstream checkout service changes currency formatting tomorrow, seeing rejected_rows jump from 1 to 400 prevents leadership from acting on incomplete revenue numbers!

2. Live Interactive Analytics Engine (Run in Browser)

Run the complete Extract → Clean → SQLite Left Join → IQR Outlier Detection → Category & Monthly KPI → CLI Bar Chart engine right here in Pyodide:

Python 3Capstone Engine: E-Commerce Cleaning, IQR Audit & KPI Pipeline
Output

Click “Run Code” to execute this snippet right in your browser.

3. Full Local Pandas & Matplotlib Script (ecommerce_pipeline.py)

Save this production-ready script locally with pandas and matplotlib installed to generate both category_revenue.png and an atomically written kpi_summary.json:

python
import json
import logging
from pathlib import Path
import sqlite3
import matplotlib.pyplot as plt
import pandas as pd

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")


def run_pipeline(orders_csv: Path, db_path: Path, out_dir: Path) -> dict:
    out_dir.mkdir(parents=True, exist_ok=True)

    # 1. Load, deduplicate, and filter paid orders
    df = pd.read_csv(orders_csv, parse_dates=["ordered_at"])
    df = df.sort_values("ordered_at").drop_duplicates(subset=["order_id"], keep="first")
    df["status"] = df["status"].str.strip().str.lower()
    df = df.loc[df["status"] == "paid"].copy()

    # 2. Clean currency strings safely with errors="coerce"
    df["amount"] = (
        df["amount"]
        .astype(str)
        .str.replace(r"[$,]", "", regex=True)
        .pipe(pd.to_numeric, errors="coerce")
    )
    rejected = int(df["amount"].isna().sum())
    df = df.dropna(subset=["amount"]).copy()

    # 3. Enrich with customer tier from SQLite (many-to-one validation)
    with sqlite3.connect(db_path) as conn:
        customers = pd.read_sql_query("SELECT id AS customer_id, tier FROM customers", conn)

    merged = pd.merge(df, customers, on="customer_id", how="left", validate="many_to_one")
    assert len(merged) == len(df), "Join row explosion detected!"
    merged["tier"] = merged["tier"].fillna("Unknown")

    # 4. Flag IQR outliers without deleting valid revenue
    q1, q3 = merged["amount"].quantile([0.25, 0.75])
    upper_fence = q3 + 1.5 * (q3 - q1)
    outlier_count = int((merged["amount"] > upper_fence).sum())

    # 5. Aggregate Category & Monthly KPIs
    by_category = (
        merged.groupby("category", as_index=False)
        .agg(revenue=("amount", "sum"), orders=("order_id", "count"))
        .sort_values("revenue", ascending=False)
    )

    # 6. Export zero-baseline Matplotlib bar chart (free figure memory after saving!)
    fig, ax = plt.subplots(figsize=(7, 4))
    ax.bar(by_category["category"], by_category["revenue"], color="#4f46e5")
    ax.set_title("Paid Revenue by Category", fontweight="bold")
    ax.set_ylabel("Revenue (USD)")
    ax.set_ylim(bottom=0)
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    fig.tight_layout()
    fig.savefig(out_dir / "category_revenue.png", dpi=150)
    plt.close(fig)

    # 7. Atomic JSON summary export
    summary = {
        "valid_orders": int(len(merged)),
        "rejected_rows": rejected,
        "outlier_orders": outlier_count,
        "total_revenue": round(float(merged["amount"].sum()), 2),
        "median_order": round(float(merged["amount"].median()), 2),
        "by_category": by_category.to_dict(orient="records"),
    }
    json_path = out_dir / "kpi_summary.json"
    tmp_path = json_path.with_suffix(".json.tmp")
    tmp_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")
    tmp_path.replace(json_path)
    logging.info("Pipeline completed: %s valid orders, %s rejected.", len(merged), rejected)
    return summary
Production Habit: Separate Calculation From Scheduling

Notice run_pipeline(orders_csv, db_path, out_dir) takes explicit Path inputs and returns summary. That design makes it trivial to unit-test with pytest using temporary folders (tmp_path), AND trivial to invoke daily from cron or GitHub Actions!

Capstone Checklist & Next Steps

Data Analysis Capstone Checklist

0/4 done

Ready to earn your certificate? Head to the Final Assessment to test your Python data analysis and automation mastery!