I Automated My Entire Weekly Report With Python in Fabric Notebooks — Here’s the Exact Code
From the publisher’s feed, collected in the ZeroLabs newsroom.
Every Monday morning for eight months, I spent three hours copying numbers into a spreadsheet. Then I spent one Saturday afternoon building the thing that gave those hours back forever.Every Monday morning, without fail, for eight straight months — I made the same coffee, opened the same four data sources, and spent the next three hours doing something a computer could do in eleven seconds.I pulled numbers from our sales system. I pulled numbers from our CRM. I pulled numbers from our marketing platform. I copied them into a spreadsheet template that had lived, barely changed, since before I joined the team. I formatted the cells. I checked the totals. I wrote a three-sentence summary at the top. I emailed it to fourteen people.Then I closed the spreadsheet and started my actual work, already tired, already behind, already faintly resentful of a process I hadn’t designed and couldn’t seem to change.The report was called the Weekly Business Review. Everyone called it the WBR. Nobody called it valuable. And yet it existed, and it ran, and every Monday morning it consumed three hours of the analytics team’s most focused brain-time because someone, somewhere, had decided it needed to exist and nobody had ever stopped to ask whether the way it existed made any sense.I stopped to ask.One Saturday afternoon in September, I opened a Microsoft Fabric Notebook, connected it to our lakehouse, and started writing Python. Six hours later — including two hours of debugging, one cup of cold tea, and one moment of genuine panic when I thought I’d accidentally overwritten a production table — I had something that ran automatically every Sunday night and delivered the full WBR to fourteen inboxes before 7 AM Monday morning.Three hours every Monday. Gone. Permanently.This article is the exact code I used to do it — explained well enough that you can adapt it, not just copy it. Because the code is the easy part. Understanding why the code is structured the way it is — that’s what makes the difference between automation that works once and automation that works for years.Eight months of 3-hour Monday mornings vs one Saturday afternoon of Python. The same report. Two completely different realities.Before the Code: What the WBR Actually NeededBefore showing you what I built, let me show you what I was working with. Understanding the problem makes the solution make sense.The WBR had seven sections:Executive KPIs — four headline numbers (revenue, new customers, churn rate, pipeline value)Sales performance — rep-level attainment vs quota, week-over-weekMarketing metrics — leads by channel, cost per lead, conversion to opportunityCustomer health snapshot — NPS score trend, support ticket volume, renewal risk flagsProduct usage — DAU/MAU, feature adoption ratesFinance pulse — actuals vs budget, month-to-date burn rateAnalyst commentary — three sentences I wrote each week summarising the biggest movementSections 1–6 were pure data. They lived in our lakehouse. Section 7 was the only thing that required a human — and even that, I eventually partly automated (more on that later).The WBR format was a styled HTML email. Our stakeholders were not Power BI users — they just wanted something readable in their inbox, not a link to a dashboard they’d never click.So the automation needed to: pull data from the lakehouse, compute the metrics, build a formatted HTML email, and send it. Automatically. Without me touching it.Here’s exactly how I built that.The Architecture: What Connects to WhatBefore writing a single line of Python, I sketched the architecture on paper. (Old UI/UX habit — design before you build.)┌─────────────────────────────────────────────────────────────┐│ FABRIC LAKEHOUSE ││ sales_facts │ crm_contacts │ marketing_events │ ... │└───────────────────────┬─────────────────────────────────────┘ │ PySpark / SQL queries ▼┌─────────────────────────────────────────────────────────────┐│ FABRIC NOTEBOOK (Python) ││ wbr_automation.ipynb ││ ├── 01_extract_metrics() ││ ├── 02_compute_changes() ││ ├── 03_build_html_email() ││ └── 04_send_report() │└───────────────────────┬─────────────────────────────────────┘ │ Fabric Data Pipeline trigger ▼┌─────────────────────────────────────────────────────────────┐│ EMAIL (HTML formatted) ││ Delivered: Sunday 11 PM → Inbox: Monday 7 AM ││ Recipients: 14 stakeholders │└─────────────────────────────────────────────────────────────┘Four functions. One notebook. One pipeline trigger. That’s the whole system.The complete system architecture — 4 layers, 1 notebook, 1 pipeline trigger, 11.2 seconds runtime.Let me walk through each function in detail.Function 1: Extract the Metricsfrom pyspark.sql import SparkSessionfrom pyspark.sql import functions as Ffrom datetime import datetime, timedeltaimport pandas as pdspark = SparkSession.builder.getOrCreate()def extract_metrics(report_date: datetime) -> dict: """ Pull all WBR metrics for the week ending on report_date. Returns a flat dictionary of metric_name -> value. """ week_start = report_date - timedelta(days=7) week_start_str = week_start.strftime('%Y-%m-%d') report_date_str = report_date.strftime('%Y-%m-%d') prior_start = (week_start - timedelta(days=7)).strftime('%Y-%m-%d') metrics = {} # ── SECTION 1: Executive KPIs ───────────────────────────────────────── kpi_df = spark.sql(f""" SELECT SUM(revenue_amount) AS total_revenue, COUNT(DISTINCT CASE WHEN is_new_customer = 1 THEN customer_id END) AS new_customers, ROUND( COUNT(DISTINCT CASE WHEN churned_this_week = 1 THEN customer_id END) * 100.0 / NULLIF(COUNT(DISTINCT customer_id), 0), 2 ) AS churn_rate_pct, SUM(pipeline_value) AS pipeline_value FROM sales_facts WHERE transaction_date BETWEEN '{week_start_str}' AND '{report_date_str}' """).toPandas() metrics['revenue'] = kpi_df['total_revenue'].iloc[0] metrics['new_customers'] = int(kpi_df['new_customers'].iloc[0]) metrics['churn_rate'] = float(kpi_df['churn_rate_pct'].iloc[0]) metrics['pipeline_value'] = kpi_df['pipeline_value'].iloc[0] # ── Prior week for WoW change ───────────────────────────────────────── prior_df = spark.sql(f""" SELECT SUM(revenue_amount) AS prior_revenue FROM sales_facts WHERE transaction_date BETWEEN '{prior_start}' AND '{week_start_str}' """).toPandas() metrics['prior_revenue'] = prior_df['prior_revenue'].iloc[0] # ── SECTION 2: Sales Rep Performance ───────────────────────────────── sales_df = spark.sql(f""" SELECT rep_name, SUM(revenue_amount) AS revenue, MAX(quota_amount) AS quota, ROUND(SUM(revenue_amount) * 100.0 / NULLIF(MAX(quota_amount), 0), 1) AS attainment_pct FROM sales_facts sf JOIN sales_reps sr ON sf.rep_id = sr.rep_id WHERE transaction_date BETWEEN '{week_start_str}' AND '{report_date_str}' GROUP BY rep_name ORDER BY attainment_pct DESC """).toPandas() metrics['sales_reps'] = sales_df.to_dict('records') # ── SECTION 3: Marketing ────────────────────────────────────────────── mktg_df = spark.sql(f""" SELECT channel, COUNT(DISTINCT lead_id) AS leads, SUM(spend_amount) AS spend, ROUND(SUM(spend_amount) / NULLIF(COUNT(DISTINCT lead_id), 0), 2) AS cost_per_lead, COUNT(DISTINCT CASE WHEN converted_to_opp = 1 THEN lead_id END) AS conversions FROM marketing_events WHERE event_date BETWEEN '{week_start_str}' AND '{report_date_str}' GROUP BY channel ORDER BY leads DESC """).toPandas() metrics['marketing'] = mktg_df.to_dict('records') # ── SECTION 4: Customer Health ──────────────────────────────────────── health_df = spark.sql(f""" SELECT ROUND(AVG(nps_score), 1) AS avg_nps, COUNT(DISTINCT ticket_id) AS support_tickets, COUNT(DISTINCT CASE WHEN renewal_risk = 'HIGH' THEN customer_id END) AS high_risk_renewals FROM customer_health WHERE snapshot_date = '{report_date_str}' """).toPandas() metrics['nps'] = float(health_df['avg_nps'].iloc[0]) metrics['support_tickets'] = int(health_df['support_tickets'].iloc[0]) metrics['high_risk_renewals'] = int(health_df['high_risk_renewals'].iloc[0]) # ── SECTION 5: Product Usage ────────────────────────────────────────── usage_df = spark.sql(f""" SELECT COUNT(DISTINCT CASE WHEN activity_date = '{report_date_str}' THEN user_id END) AS dau, COUNT(DISTINCT CASE WHEN activity_date BETWEEN '{week_start_str}' AND '{report_date_str}' THEN user_id END) AS wau FROM product_events """).toPandas() metrics['dau'] = int(usage_df['dau'].iloc[0]) metrics['wau'] = int(usage_df['wau'].iloc[0]) print(f"✓ Metrics extracted for week ending {report_date_str}") return metricsA few things worth noting about this function:The report_date parameter is the key design decision. By making the function date-parameterised rather than hardcoded to "today," I can run it for any week — for testing, for reprocessing, for backfilling. I've used this more times than I expected.The NULLIF(..., 0) pattern throughout protects against division-by-zero errors that would crash the whole pipeline at the worst possible time — Sunday night, when nobody is watching.And .toPandas() at the end of each Spark query converts the Spark DataFrame to a regular Pandas DataFrame for easier manipulation downstream. For small result sets like these, the performance difference is negligible, and Pandas is much easier to work with for building formatted outputs.Function 2: Compute the ChangesRaw numbers aren’t enough. Every metric needs context — week-over-week change, direction, whether the movement is good or bad.def compute_changes(metrics: dict) -> dict: """ Add week-over-week deltas, percentage changes, and visual direction indicators to the metrics dict. Returns enriched metrics dict. """ # Revenue WoW change current = metrics.get('revenue', 0) or 0 prior = metrics.get('prior_revenue', 0) or 0 if prior and prior != 0: metrics['revenue_wow_pct'] = round((current - prior) / prior * 100, 1) else: metrics['revenue_wow_pct'] = 0.0 metrics['revenue_wow_direction'] = ( '▲' if metrics['revenue_wow_pct'] > 0 else '▼' if metrics['revenue_wow_pct'] else '─' ) metrics['revenue_wow_color'] = ( '#22C55E' if metrics['revenue_wow_pct'] > 0 else '#EF4444' if metrics['revenue_wow_pct'] else '#6B7280' ) # Churn — inverse: down is good metrics['churn_direction'] = ( '▼' if metrics.get('churn_rate', 0) else '▲' ) metrics['churn_color'] = ( '#22C55E' if metrics.get('churn_rate', 0) else '#EF4444' ) # NPS colour bands nps = metrics.get('nps', 0) metrics['nps_color'] = ( '#22C55E' if nps >= 50 else '#F59E0B' if nps >= 30 else '#EF4444' ) # Sales attainment colour per rep for rep in metrics.get('sales_reps', []): pct = rep.get('attainment_pct', 0) rep['color'] = ( '#22C55E' if pct >= 100 else '#F59E0B' if pct >= 80 else '#EF4444' ) rep['status'] = ( 'On Track' if pct >= 100 else 'At Risk' if pct >= 80 else 'Behind' ) # Format currency fields for display metrics['revenue_fmt'] = f"${metrics.get('revenue', 0):,.0f}" metrics['pipeline_value_fmt'] = f"${metrics.get('pipeline_value', 0):,.0f}" print("✓ Changes computed") return metricsThe colour logic here mirrors exactly what I would have done in a Power BI conditional formatting rule — green above threshold, amber in the warning band, red below. The difference is that it lives in Python, so it travels into the HTML email automatically, without anyone manually applying conditional formatting in a spreadsheet.This is the part where UI/UX thinking genuinely accelerated my Python — I already knew exactly what visual signals I wanted and why. I just had to translate them into hex codes and conditional logic.Function 3: Build the HTML EmailThis is the longest function and the most satisfying one to get right. The email is the product — it’s what fourteen people see every Monday morning. It had to look professional without requiring anyone to click anything.def build_html_email(metrics: dict, report_date: datetime) -> str: """ Build a fully styled HTML email from the enriched metrics dict. Returns HTML string ready to send. """ week_label = report_date.strftime('%B %d, %Y') revenue_wow = metrics.get('revenue_wow_pct', 0) wow_sign = '+' if revenue_wow > 0 else '' # Build sales rep rows rep_rows = '' for rep in metrics.get('sales_reps', []): rep_rows += f""" font-size:14px; color:#111827;">{rep['rep_name']} font-size:14px; text-align:right;">${rep['revenue']:,.0f} font-size:14px; text-align:right;">${rep['quota']:,.0f} font-size:14px; text-align:right; color:{rep['color']}; font-weight:600;"> {rep['attainment_pct']}% text-align:center;"> padding:3px 10px; border-radius:999px; font-size:12px; font-weight:600;"> {rep['status']} """ # Build marketing channel rows mktg_rows = '' for ch in metrics.get('marketing', []): conv_rate = (ch['conversions'] / ch['leads'] * 100) if ch['leads'] else 0 mktg_rows += f""" font-size:14px; color:#111827;">{ch['channel']} font-size:14px; text-align:right;">{ch['leads']:,} font-size:14px; text-align:right;">${ch['cost_per_lead']:.2f} font-size:14px; text-align:right;">{conv_rate:.1f}% """ # Assemble the full HTML html = f"""Weekly Business Review — {week_label} font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;"> text-transform:uppercase; letter-spacing:1px;"> Weekly Business Review font-weight:700;">Week ending {week_label} Auto-generated · Microsoft Fabric · Delivered Sunday 11 PM border-bottom:1px solid #E5E7EB;"> text-transform:uppercase; letter-spacing:0.5px; font-weight:600;">Executive KPIs padding:20px 24px; border-left:4px solid #3B82F6;"> font-weight:600; text-transform:uppercase;">Revenue color:#111827;">{metrics['revenue_fmt']} color:{metrics['revenue_wow_color']}; font-weight:600;"> {metrics['revenue_wow_direction']} {wow_sign}{revenue_wow}% WoW padding:20px 24px; border-left:4px solid #22C55E;"> font-weight:600; text-transform:uppercase;">New Customers color:#111827;">{metrics['new_customers']:,} This week padding:20px 24px; border-left:4px solid {metrics['churn_color']};"> font-weight:600; text-transform:uppercase;">Churn Rate color:#111827;">{metrics['churn_rate']}% color:{metrics['churn_color']}; font-weight:600;"> {metrics['churn_direction']} vs 3% target padding:20px 24px; border-left:4px solid #8B5CF6;"> font-weight:600; text-transform:uppercase;">Pipeline Value color:#111827;">{metrics['pipeline_value_fmt']} Open opportunities border-bottom:1px solid #E5E7EB; margin-top:8px;"> text-transform:uppercase; letter-spacing:0.5px; font-weight:600;">Sales Performance style="border:1px solid #E5E7EB; border-radius:8px; overflow:hidden; border-collapse:collapse;"> color:#6B7280; font-weight:600; text-transform:uppercase;">Rep color:#6B7280; font-weight:600; text-transform:uppercase;">Revenue color:#6B7280; font-weight:600; text-transform:uppercase;">Quota color:#6B7280; font-weight:600; text-transform:uppercase;">Attainment color:#6B7280; font-weight:600; text-transform:uppercase;">Status {rep_rows} border-bottom:1px solid #E5E7EB; margin-top:8px;"> text-transform:uppercase; letter-spacing:0.5px; font-weight:600;">Marketing Performance style="border:1px solid #E5E7EB; border-radius:8px; overflow:hidden; border-collapse:collapse;"> color:#6B7280; font-weight:600; text-transform:uppercase;">Channel color:#6B7280; font-weight:600; text-transform:uppercase;">Leads color:#6B7280; font-weight:600; text-transform:uppercase;">Cost / Lead color:#6B7280; font-weight:600; text-transform:uppercase;">Conv. Rate {mktg_rows} padding:20px 24px; vertical-align:top;"> font-weight:600; text-transform:uppercase;">Customer Health NPS Score: {metrics['nps']} Support Tickets: {metrics['support_tickets']} High-Risk Renewals: {metrics['high_risk_renewals']} padding:20px 24px; vertical-align:top;"> font-weight:600; text-transform:uppercase;">Product Usage DAU: {metrics['dau']:,} WAU: {metrics['wau']:,} DAU/WAU Ratio: {(metrics['dau']/metrics['wau']*100):.1f}% Generated by wbr_automation.py · Microsoft Fabric Notebook · Data as of Sunday midnight · Questions? Reply to this email. """ print("✓ HTML email built") return htmlA few things I learned building this function the hard way:Inline styles only. Most email clients — Outlook especially — strip blocks in the . Every single style property has to be inline. Painful to write. Non-negotiable to make it work everywhere.Table-based layout. CSS Grid and Flexbox don’t work reliably in email. Tables do. I know. I’m sorry. Email clients are still living in 2003 and we have to build for them.border-collapse: collapse on your data tables. Without it, you get double borders between cells on certain clients. This took me forty-five minutes to debug.Function 4: Send the Reportimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom notebookutils import mssparkutils # Fabric-specific utilitydef send_report(html: str, report_date: datetime, recipients: list) -> bool: """ Send the HTML email to all recipients. Credentials pulled from Fabric Key Vault — never hardcoded. Returns True on success, False on failure. """ week_label = report_date.strftime('%B %d, %Y') # Pull credentials from Azure Key Vault (NEVER hardcode these) smtp_host = mssparkutils.credentials.getSecret( 'your-keyvault-name', 'smtp-host') smtp_port = int(mssparkutils.credentials.getSecret( 'your-keyvault-name', 'smtp-port')) smtp_user = mssparkutils.credentials.getSecret( 'your-keyvault-name', 'smtp-username') smtp_password = mssparkutils.credentials.getSecret( 'your-keyvault-name', 'smtp-password') msg = MIMEMultipart('alternative') msg['Subject'] = f"📊 Weekly Business Review — {week_label}" msg['From'] = f"Analytics Team " msg['To'] = ', '.join(recipients) msg.attach(MIMEText(html, 'html')) try: with smtplib.SMTP(smtp_host, smtp_port) as server: server.ehlo() server.starttls() server.login(smtp_user, smtp_password) server.sendmail(smtp_user, recipients, msg.as_string()) print(f"✓ Report sent to {len(recipients)} recipients") return True except Exception as e: print(f"✗ Send failed: {e}") # Log the failure — don't raise, so the notebook doesn't crash # You'll want a separate alerting mechanism here return FalseThe mssparkutils.credentials.getSecret() call is the most important line in this function. Never hardcode SMTP credentials in a notebook. Not in a comment, not in a variable, not temporarily while you're testing. Azure Key Vault is free for this use case and takes about twenty minutes to set up. Do it once. Do it right.The Main Orchestrator# ── Run everything ────────────────────────────────────────────────────────RECIPIENTS = [ "cfo@yourcompany.com", "coo@yourcompany.com", "vp-sales@yourcompany.com", "vp-marketing@yourcompany.com", # ... 10 more]if __name__ == "__main__": report_date = datetime.now() print(f"\n{'='*50}") print(f"WBR Automation — {report_date.strftime('%A %B %d, %Y %H:%M')}") print(f"{'='*50}\n") metrics = extract_metrics(report_date) metrics = compute_changes(metrics) html = build_html_email(metrics, report_date) success = send_report(html, report_date, RECIPIENTS) if success: print("\n✅ WBR delivered successfully.") else: print("\n❌ WBR delivery failed — check logs.")And that’s it. Four functions, one orchestrator, one notebook. You attach it to a Fabric Data Pipeline, set it to trigger every Sunday at 11 PM, and walk away.The 4 functions — what each one does, why it’s structured that way, and the key pattern that makes it production-safe.What I Got BackThe numbers are almost too good to put in an article because they sound made up. They’re not.Before automation: 3 hours every Monday morning, every week, for 8 months = 96 hours spent on manual report assembly.After automation: 11 seconds of compute time on Sunday nights, zero human time on Monday mornings.But the number that matters more than the hours: when I stopped spending Monday mornings on the WBR, I started spending them on actual analysis. Three hours of “what happened last week” became three hours of “why did it happen and what should we do about it.”The first Monday after the automation went live, I spent the morning investigating a pattern in the customer health data that had been sitting there for months — because I finally had time to look. That investigation led to a churn prevention initiative that’s still running.The WBR itself didn’t change. The humans receiving it didn’t change. What changed was what the analyst did while it was being built — which was, for the first time, nothing. Because a Fabric notebook was doing it instead.Three Things I’d Tell Myself Before StartingThe real numbers after automation — and the three lessons worth knowing before you start building.1. Build for failure first, not success. Your first instinct is to make the happy path work. Resist it. Add error handling, null checks, and fallbacks before you think you need them. The automation will fail eventually — at 11 PM on a Sunday, when nobody is watching. Make sure it fails gracefully and sends you an alert rather than silently delivering a blank or broken email.2. Test with real data from day one. I tested with synthetic data for the first two weeks, then switched to production and discovered that two of my SQL queries made assumptions about data quality that weren’t true for real data. Two hours of debugging. Avoidable if I’d used real data earlier.3. Document the queries, not just the code. Six months later, when a column got renamed in the source table and the automation broke, I was glad I had a separate markdown cell in the notebook explaining what each query was pulling and why. Future-you will be grateful. So will your teammates.The Automation That Surprised Me MostI mentioned at the start that I eventually partly automated Section 7 — the analyst commentary.I want to be careful about how I describe this. I didn’t remove the analyst from the loop. What I built was a commentary draft generator — it identifies the three biggest metric movements from the current week versus the prior week, formats them as natural language, and drops them into the email template as a draft.A human — usually me, on Sunday evening — reviews the draft, adjusts anything misleading, and confirms or overwrites it before the send.About 70% of the time, the draft needs minimal editing. About 30% of the time, there’s context the algorithm doesn’t have — a product launch, a data quality issue, a one-off event — and the commentary needs significant revision.That 30% is exactly where the analyst should be. Providing context that no query can provide. Making judgment calls that no threshold logic can make. Writing in a voice that no template can fully replicate.The 70% was just pattern-matching I’d been doing manually every week, and Python does pattern-matching faster than I do.The full notebook is structured and commented exactly as shown above. Clone it, replace the table names with your table names, point it at your lakehouse, add your recipients, set your Key Vault reference, and run it.The first time it works — really works, end to end, no errors, email delivered, correct data — is a feeling I hope you get to have.Three hours back. Every single Monday. Forever.That’s worth one Saturday afternoon.I Automated My Entire Weekly Report With Python in Fabric Notebooks — Here’s the Exact Code was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.