← All posts

Building a Data Pipeline from Raw CSV to a Trusted Report

On this page
Sources CSV / API app DB exports BRONZE · raw exactly as received append-only + load timestamp SILVER · clean typed, deduped validated one row = one thing GOLD · business aggregates, KPIs star schema → dashboards Never edit bronze. If silver logic has a bug, fix it and rebuild from bronze.

Most data work isn’t machine learning. It’s getting data into a state where people can trust the numbers on a report. Exports arrive with duplicate rows, inconsistent spelling and dates in three formats — and each of those becomes a wrong number on a dashboard if nobody catches it.

This is the pipeline structure I use for small and medium datasets, built with nothing more than Python, pandas and SQL. To keep it honest, I ran every step on a deliberately messy export of 625 orders. It caught a bug I didn’t see coming.

The structure: bronze, silver and gold

The diagram at the top shows the three layers:

  • Bronze — the raw data, exactly as received, never changed.
  • Silver — cleaned data: correct types, no duplicates, validated.
  • Gold — business-ready tables and aggregates that feed reports.

Why keep raw? Because cleaning code always has bugs. If you only keep the cleaned version, a bug destroys data forever. With bronze kept as it is, you fix the code and run it again. As you will see below, this is not a theoretical problem.

Step 1 — Ingest to bronze

Step one is saving the export exactly as it is, with two extra columns that tell us when and from where it was loaded:

import pandas as pd
from datetime import datetime, timezone

raw = pd.read_csv("exports/orders_2022-05.csv", dtype=str)   # read everything as text first
raw["_loaded_at"]   = datetime.now(timezone.utc).isoformat()
raw["_source_file"] = "orders_2022-05.csv"
raw.to_parquet("bronze/orders/2022-05.parquet", index=False)

dtype=str is on purpose: if pandas guesses types, a code like 007 becomes the number 7 before you ever see it.

Step 2 — Validate before transforming

The pipeline should stop early, with a clear reason, when a file is broken:

def validate(df):
    errors = []
    required = {"order_id", "customer_id", "order_date", "amount"}
    if missing := required - set(df.columns):
        errors.append(f"missing columns: {missing}")
    if df["order_id"].isna().any():
        errors.append(f"{df['order_id'].isna().sum()} rows with no order_id")
    if (pd.to_numeric(df["amount"], errors="coerce") < 0).any():
        errors.append("negative amounts present")
    if errors:
        raise ValueError("Validation failed:\n  " + "\n  ".join(errors))

This is the real output when I gave it a broken export with a missing order id and a negative amount:

Validation failed:
  1 rows with no order_id
  negative amounts present

Step 3 — Clean into silver (and the bug)

The sample export has three typical problems: 25 re-exported duplicate rows, country codes written as "SA", " sa" and "Sa ", and dates in two formats (2022-03-24 and 24/03/2022).

The dates are the interesting part. These are the real results (pandas 1.5) of two ways to parse them:

pd.to_datetime(dates, errors="coerce")
  -> 1 NaT, but latest date = 2022-12-05
  -> 56 dates have day and month swapped

two explicit formats, one after the other
  -> 1 NaT, range 2022-01-01 .. 2022-05-31
  1. The first one looked perfect: only one bad date — the real not-a-date row in the file. But for every dd/mm/yyyy value where the day is 12 or less, pandas guessed month-first, so 03/02/2022 became the 2nd of March instead of the 3rd of February. The export only covers January to May, but revenue appeared in June to December. Pandas did print a UserWarning — which nobody reads in a scheduled job at 2 a.m.
  2. Parsing each known format explicitly gave correct dates.

So this is the cleaning step:

def parse_dates(s):
    iso = pd.to_datetime(s, format="%Y-%m-%d", errors="coerce")     # try each known format explicitly
    dmy = pd.to_datetime(s, format="%d/%m/%Y", errors="coerce")
    return iso.fillna(dmy)

df = pd.read_parquet("bronze/orders/2022-05.parquet")
df = (df
      .rename(columns=str.lower)
      .assign(
          order_date = lambda d: parse_dates(d["order_date"]),
          amount     = lambda d: pd.to_numeric(d["amount"], errors="coerce"),
          country    = lambda d: d["country"].str.strip().str.upper(),
      )
      .dropna(subset=["order_id", "order_date"])
      .drop_duplicates(subset="order_id", keep="last"))         # latest version of each order wins
df.to_parquet("silver/orders/2022-05.parquet", index=False)

Result: 625 bronze rows became 599 silver rows (25 duplicates and 1 unreadable date removed), and the country codes became exactly AE, BH, KW and SA.

Step 4 — Model the gold layer

For reporting, the gold layer uses a star schema:

fact_orders order_id, amount, qty customer_key, date_key dim_customer name, segment, country dim_date day, month, quarter, FY dim_product category, brand

Facts are events with numbers (orders, payments). Dimensions describe them (who, when, what). Reports slice facts by dimensions, and this structure keeps those queries simple and fast.

Step 5 — Load and query with SQL

With clean silver data, a database and some SQL answer the real questions:

import sqlite3
con = sqlite3.connect("warehouse.db")
df.to_sql("silver_orders", con, if_exists="replace", index=False)

Monthly revenue with month-over-month growth, using the LAG window function:

WITH monthly AS (
  SELECT strftime('%Y-%m', order_date) AS month, SUM(amount) AS revenue
  FROM silver_orders GROUP BY 1
)
SELECT month, ROUND(revenue, 2) AS revenue,
       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
             / LAG(revenue) OVER (ORDER BY month), 1) AS mom_growth_pct
FROM monthly ORDER BY month;
  month  revenue  mom_growth_pct
2022-01 56435.70             NaN
2022-02 49384.90           -12.5
2022-03 55957.40            13.3
2022-04 48029.26           -14.2
2022-05 61793.76            28.7

And the same result as a chart for the report:

Monthly revenue chart

Two more patterns worth knowing by heart — the latest order of each customer with ROW_NUMBER, and a running total with SUM() OVER:

SELECT * FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn
  FROM silver_orders
) WHERE rn = 1;

SELECT customer_id, order_date, amount,
       SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_total
FROM silver_orders;

Step 6 — Test the data, not only the code

Every run ends with data tests:

q = lambda sql: con.execute(sql).fetchone()[0]
checks = {
  "table not empty":    q("SELECT COUNT(*) FROM silver_orders") > 0,
  "no duplicate keys":  q("SELECT COUNT(*) - COUNT(DISTINCT order_id) FROM silver_orders") == 0,
  "no null amounts":    q("SELECT COUNT(*) FROM silver_orders WHERE amount IS NULL") == 0,
  "dates inside the export window":
      q("SELECT COUNT(*) FROM silver_orders WHERE order_date NOT BETWEEN '2022-01-01' AND '2022-05-31'") == 0,
  "totals reconcile with bronze": abs(q("SELECT SUM(amount) FROM silver_orders") - bronze_total) < 0.01,
}
  PASS  table not empty
  PASS  no duplicate keys
  PASS  no null amounts
  PASS  dates inside the export window
  PASS  totals reconcile with bronze

Lesson learned: Here is the important lesson from step 3: with the swapped dates, the first three checks and the reconciliation check all passed — the total was correct, only the months were wrong. The “dates inside the export window” check is the one that catches it. Add range checks for every date and amount column, not only totals.

Step 7 — Make it repeatable and schedule it

A pipeline should be idempotent: running it twice gives the same result as running it once. Process one date partition at a time and overwrite it, instead of appending. Then schedule it:

# cron: every day at 02:00, process yesterday's partition
0 2 * * * cd /opt/pipeline && python run.py --date "$(date -d yesterday +\%F)" >> logs/run.log 2>&1

When cron and scripts are no longer enough — dependencies between jobs, retries, backfills — that is the right moment for a scheduler like Apache Airflow. Not before.

Why every step earns its place

A trustworthy pipeline keeps raw data untouched, validates early, parses types explicitly, de-duplicates by the business key, separates facts from dimensions and tests the data on every run. The date bug here shows why: it looked right, passed the usual checks, and would have reported revenue in months that never happened. The pandas date-parsing docs are worth a careful read.