Building an Automated Reporting Pipeline with Quarto and Python
Recurring weekly KPI decks, monthly executive scorecards, and regional performance summaries often trap data teams in a cycle of manual SQL exports, spreadsheet formatting, and screenshot copy-pasting. Whenever upstream data updates, someone has to re-run notebooks by hand and email out updated attachments.
Quarto turns literate .qmd notebooks into a production publishing engine. By pairing parameterized Quarto documents with Python, DuckDB, and a lightweight scheduler or CI runner, you can build a hands-free reporting pipeline that ingests fresh data, validates metrics, renders self-contained HTML and PDF briefings, and distributes them automatically.
Pipeline Architecture Overview
A clean automated Quarto reporting pipeline separates data extraction, metric validation, parameterized template rendering, and artifact delivery into four deterministic stages:
| Stage | Responsibility | Tools Used | Output Artifact |
|---|---|---|---|
| 1. Extract & Aggregate | Query raw warehouse/Parquet tables and compute clean KPI snapshots | Python, DuckDB, pandas | data/kpi_snapshot.parquet |
| 2. Data Quality Gate | Enforce freshness, non-null, and row-count assertions before rendering | Python (assert / Pandera checks) | Validated snapshot or fail-fast alert |
| 3. Parameterized Render | Execute .qmd templates per region/segment with dynamic titles and charts | Quarto CLI (quarto render -P), Matplotlib | dist/report_<region>.html & .pdf |
| 4. Publish & Archive | Upload versioned outputs to object storage or static hosting and notify stakeholders | GitHub Actions / cron, S3 / Cloud Storage | Timestamped links & Slack/email digest |
Project Directory Structure
Organize the project so data preparation scripts, Quarto templates, shared styling, and rendered artifacts stay cleanly separated:
automated-quarto-pipeline/
├── _quarto.yml # Project-wide defaults, themes, and output directory
├── pyproject.toml # Python dependencies
├── src/
│ ├── extract_metrics.py # Generates/fetches and validates KPI data
│ └── build_reports.py # Orchestrates parameterized Quarto builds
├── templates/
│ └── regional_kpi_report.qmd # Parameterized Quarto report template
├── data/
│ └── kpi_snapshot.parquet # Intermediate validated dataset
├── dist/ # Rendered HTML & PDF outputs (gitignored)
└── .github/
└── workflows/
└── scheduled-reports.yml # Cron + manual dispatch automation
Step 1: Install Dependencies
Install Quarto CLI (from quarto.org) along with the Python data, plotting, and Jupyter execution packages:
pip install duckdb pandas pyarrow matplotlib jupyter pyyaml
Verify that Quarto detects your Python environment:
quarto check jupyter
Step 2: Configure _quarto.yml
Create _quarto.yml at the project root so every render shares consistent formatting, code-hiding defaults, and output paths:
project:
type: default
output-dir: dist
format:
html:
theme: cosmo
toc: true
toc-depth: 2
embed-resources: true
code-fold: true
pdf:
documentclass: article
geometry:
- margin=18mm
colorlinks: true
execute:
echo: false
warning: false
error: false
Setting embed-resources: true bundles CSS, JavaScript, and base64-encoded charts inside a single portable .html file so attachments work offline without broken asset links.
Step 3: Build the Extraction & Validation Script (src/extract_metrics.py)
Before Quarto renders a single chart, run a Python step that pulls the latest records, computes daily/weekly rollups in DuckDB, and aborts early if data is stale or incomplete.
from datetime import date, timedelta
from pathlib import Path
import duckdb
import numpy as np
import pandas as pd
def generate_or_extract_orders(seed: int = 42) -> pd.DataFrame:
"""Simulate 90 days of multi-region order telemetry (replace with warehouse SQL in production)."""
rng = np.random.default_rng(seed)
end_day = date.today()
days = pd.date_range(end_day - timedelta(days=89), end_day, freq="D")
regions = ["North America", "Europe", "APAC"]
rows = []
for day in days:
weekend_factor = 0.82 if day.weekday() >= 5 else 1.0
for region in regions:
base_orders = {"North America": 420, "Europe": 310, "APAC": 260}[region]
orders = int(rng.poisson(base_orders * weekend_factor))
aov = float(rng.normal(78.0, 9.5))
refund_rate = float(np.clip(rng.normal(0.024, 0.005), 0.005, 0.08))
rows.append(
{
"order_date": day.date(),
"region": region,
"orders": orders,
"gross_revenue": round(orders * max(aov, 25.0), 2),
"refunds": round(orders * max(aov, 25.0) * refund_rate, 2),
"active_customers": int(orders * rng.uniform(0.84, 0.94)),
}
)
return pd.DataFrame(rows)
def validate_snapshot(df: pd.DataFrame) -> None:
"""Fail fast if schema, null counts, or freshness checks fail."""
required_cols = {"order_date", "region", "orders", "gross_revenue", "refunds", "active_customers"}
missing = required_cols - set(df.columns)
assert not missing, f"Missing required columns: {missing}"
assert not df.isna().any().any(), "Null values detected in KPI snapshot"
assert (df["orders"] > 0).all(), "Zero or negative order counts detected"
latest_date = pd.to_datetime(df["order_date"]).max().date()
assert latest_date >= date.today() - timedelta(days=1), f"Stale data: latest date is {latest_date}"
def run_extraction(output_path: str = "data/kpi_snapshot.parquet") -> Path:
raw_df = generate_or_extract_orders()
validate_snapshot(raw_df)
# Use DuckDB to compute clean net revenue and rolling 7-day metrics
con = duckdb.connect()
enriched_df = con.execute(
"""
SELECT
order_date,
region,
orders,
gross_revenue,
refunds,
ROUND(gross_revenue - refunds, 2) AS net_revenue,
active_customers,
ROUND((gross_revenue - refunds) / NULLIF(orders, 0), 2) AS net_aov
FROM raw_df
ORDER BY region, order_date
"""
).df()
out = Path(output_path)
out.parent.mkdir(parents=True, exist_ok=True)
enriched_df.to_parquet(out, index=False)
print(f"Validated snapshot written to {out} ({len(enriched_df)} rows)")
return out
if __name__ == "__main__":
run_extraction()
Step 4: Create the Parameterized Quarto Template (templates/regional_kpi_report.qmd)
Quarto supports YAML params: blocks that accept runtime overrides via --execute-param (-P). In Python code cells, variables defined in params are injected directly into scope.
---
title: "Executive Revenue & Operations Briefing"
subtitle: "Automated Weekly Performance Digest"
date: today
params:
region: "North America"
lookback_days: 30
data_path: "../data/kpi_snapshot.parquet"
---
```{python}
#| tags: [parameters]
region = "North America"
lookback_days = 30
data_path = "../data/kpi_snapshot.parquet"
import duckdb
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import Markdown
con = duckdb.connect()
df = con.execute(
f"""
SELECT *
FROM read_parquet('{data_path}')
WHERE region = ?
ORDER BY order_date
""",
[region],
).df()
df["order_date"] = pd.to_datetime(df["order_date"])
recent = df.tail(lookback_days).copy()
prior = df.iloc[-(2 * lookback_days) : -lookback_days].copy()
curr_rev = recent["net_revenue"].sum()
prev_rev = prior["net_revenue"].sum()
rev_delta = (curr_rev - prev_rev) / prev_rev * 100
curr_orders = int(recent["orders"].sum())
avg_aov = recent["net_aov"].mean()
refund_pct = recent["refunds"].sum() / recent["gross_revenue"].sum() * 100
display(
Markdown(
f"## {region} — Last {lookback_days} Days Summary\n\n"
f"- **Net Revenue:** `${curr_rev:,.0f}` ({rev_delta:+.1f}% vs prior {lookback_days}d)\n"
f"- **Completed Orders:** `{curr_orders:,}`\n"
f"- **Average Net Order Value:** `${avg_aov:.2f}`\n"
f"- **Refund Rate:** `{refund_pct:.2f}%`"
)
)
Daily Net Revenue Trend
recent["rolling_7d"] = recent["net_revenue"].rolling(7, min_periods=1).mean()
fig, ax = plt.subplots(figsize=(8.5, 3.6), dpi=150)
ax.bar(recent["order_date"], recent["net_revenue"], color="#cbd5e1", label="Daily Net Revenue")
ax.plot(recent["order_date"], recent["rolling_7d"], color="#0f766e", linewidth=2.2, label="7-Day Rolling Avg")
ax.set_title(f"{region}: Daily Net Revenue & 7-Day Trend", fontsize=11, fontweight="bold")
ax.set_ylabel("Net Revenue (USD)")
ax.grid(axis="y", linestyle="--", alpha=0.4)
ax.legend(frameon=False)
fig.tight_layout()
plt.show()
Most Recent 7-Day Operational Breakdown
table_df = recent.tail(7)[["order_date", "orders", "net_revenue", "net_aov", "active_customers"]].copy()
table_df["order_date"] = table_df["order_date"].dt.strftime("%Y-%m-%d")
table_df.columns = ["Date", "Orders", "Net Revenue ($)", "Net AOV ($)", "Active Customers"]
display(Markdown(table_df.to_markdown(index=False)))
## Step 5: Orchestrate Batch Rendering (`src/build_reports.py`)
Write a thin Python orchestrator that loops over every target segment, invokes `quarto render` with `-P` parameters, and writes cleanly named deliverables into `dist/`:
```python
from datetime import date
from pathlib import Path
import subprocess
from extract_metrics import run_extraction
REGIONS = ["North America", "Europe", "APAC"]
TEMPLATE = Path("templates/regional_kpi_report.qmd")
DIST_DIR = Path("dist")
def render_region_report(region: str, lookback_days: int = 30, fmt: str = "html") -> Path:
slug = region.lower().replace(" ", "-")
out_name = f"{date.today().isoformat()}_{slug}_kpi.{fmt}"
cmd = [
"quarto",
"render",
str(TEMPLATE),
"--to",
fmt,
"-P",
f"region:{region}",
"-P",
f"lookback_days:{lookback_days}",
"--output",
out_name,
]
subprocess.run(cmd, check=True)
return DIST_DIR / out_name
def main() -> None:
run_extraction()
generated = []
for region in REGIONS:
artifact = render_region_report(region=region, lookback_days=30, fmt="html")
generated.append(artifact)
print(f"Rendered: {artifact}")
print(f"\nPipeline finished successfully ({len(generated)} reports generated).")
if __name__ == "__main__":
main()
Step 6: Automate Execution with GitHub Actions
Schedule the pipeline to run every Monday at 07:00 UTC and upload the rendered reports as downloadable build artifacts (or sync them to S3/GCS):
name: Weekly Automated Quarto Reports
on:
schedule:
- cron: "0 7 * * 1"
workflow_dispatch:
jobs:
build-and-publish:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install Python dependencies
run: pip install duckdb pandas pyarrow matplotlib jupyter pyyaml tabulate
- name: Install Quarto CLI
uses: quarto-dev/quarto-actions/setup@v2
- name: Run extraction and render parameterized reports
run: python src/build_reports.py
- name: Upload rendered reports
uses: actions/upload-artifact@v4
with:
name: weekly-kpi-reports
path: dist/*.html
retention-days: 30
Best Practices for Production Quarto Pipelines
- Decouple data extraction from rendering: Keep heavy warehouse queries in
extract_metrics.pywriting to local Parquet files. If a chart styling tweak is needed, you can re-render Quarto templates in seconds without re-querying your database. - Enforce fail-fast data assertions before rendering: Never email a chart built on empty or partial tables. Put row-count, schema, and freshness checks ahead of
quarto renderso failures trigger alerts instead of misleading reports. - Use
embed-resources: truefor HTML distribution: Standalone HTML files preserve interactive tooltips, crisp SVG/PNG plots, and responsive tables inside a single file that opens cleanly from email, Slack, or object storage. - Pin Python and Quarto versions in CI: Lock package versions in
pyproject.tomlorrequirements.txtand specify the Quarto version inquarto-dev/quarto-actions/setup@v2to prevent formatting drift across runs.
Common Mistakes
- Hardcoding relative paths inside
.qmdcells without accounting for working directory: Quarto executes code cells relative to the.qmdfile's folder (templates/), not the repository root—always verify paths like../data/kpi_snapshot.parquetor pass an absolute path via-P. - Leaving raw tracebacks or warnings visible in executive reports: Set
warning: falseandecho: falsein_quarto.ymlso library deprecation notices do not clutter stakeholder briefings. - Rendering PDFs without installing TinyTeX in CI: HTML rendering works out of the box with Quarto, whereas
--to pdfrequires a TeX distribution (quarto install tinytex) or Typst (--to typst) in your container or runner.
Summary
Combining Quarto's parameterized .qmd templates with Python, DuckDB, and scheduled CI workflows eliminates manual report assembly. With a validated Parquet snapshot layer, batch -P parameter rendering, and self-contained HTML/PDF outputs, your analytics team can deliver reliable, reproducible briefings on autopilot.