Madhav Sharma

Retrospective

By

3 min read

Five checks for automated financial reports

Turning any spreadsheet into a financial report automatically is easy to get wrong. Five checks, with Python code, that stop a report saying something false.

I built a reporting engine that takes any CSV or Excel export and produces a variance report with charts and a PDF, without being told what the columns mean. It detects the time column, the categories and the measures, converts everything to one long format, and computes period-over-period change.

On a 100,000-row accounting file it worked end to end. It also produced a report whose top finding was a 230 percent rise in a reference number. Nothing crashed. Every figure was computed correctly. The report was still wrong, because the engine knew the shape of the data and nothing about its meaning.

These are the five guards I would now put between “detected the schema” and “wrote the report”. Each one fixes a failure I saw in my own output.

1. An ID is not a measure

The usual heuristic is that a numeric column with almost all unique values is an identifier. That catches auto-increment keys and misses reference numbers, invoice numbers and codes that repeat a little. Combine several signals instead of one.

import re
import pandas as pd

ID_NAME = re.compile(r"(^|_)(id|ref|reference|no|number|code|key)($|_)", re.I)

def looks_like_id(name: str, s: pd.Series) -> bool:
    if ID_NAME.search(name):
        return True
    if not pd.api.types.is_integer_dtype(s):
        return False
    unique_ratio = s.nunique() / max(len(s), 1)
    gaps = s.dropna().sort_values().diff().dropna()
    mostly_sequential = (gaps == 1).mean() > 0.5 if len(gaps) else False
    return unique_ratio > 0.8 or mostly_sequential

The name check alone would have caught my case. The sequential check catches keys with bland names.

2. Choose the reporting grain on purpose

If the time column holds daily dates, “period over period” silently becomes “day over day”. A monthly report needs monthly periods, so infer the grain from the data and then bucket deliberately.

def reporting_period(dates: pd.Series, target: str = "M") -> pd.Series:
    dates = pd.to_datetime(dates, errors="coerce")
    distinct_days = dates.dt.normalize().nunique()
    distinct_months = dates.dt.to_period("M").nunique()
    if distinct_days > distinct_months * 3:   # finer than monthly
        return dates.dt.to_period(target)
    return dates.dt.to_period("M")

Make the chosen grain visible in the report. A reader should never have to guess whether a change is month on month or day on day.

3. Aggregate by what the metric is

Taking the first value per entity and period is correct for a pre-aggregated table and wrong for a transaction ledger, where you need the sum. The rule depends on the kind of metric:

Metric kind Examples Aggregate with
Flow revenue, cost, debits sum
Level balance, headcount, inventory last value in the period
Ratio margin, conversion rate recompute from its parts, never average

My engine already classified metrics into flows, levels and ratios. It just didn’t use that classification when aggregating. Wire the two together.

4. Rank with the sign in mind

“Largest increases” should only ever contain increases. When a period has few records, taking the top five by change can return negative values, because there aren’t five positive ones.

def largest_increases(df: pd.DataFrame, n: int = 5) -> pd.DataFrame:
    return df[df["delta"] > 0].nlargest(n, "delta")

It looks trivial. It is also the kind of error that destroys a reader’s trust in every other number on the page.

5. Know the accounting conventions

Debits and credits are not two independent measures that happen to sit side by side. Revenue accounts are normally credit balances, expenses normally debits, and a variance only makes sense after the sign convention is applied. A generic engine that treats them as unrelated levels will report movements that an accountant would read as nonsense.

The minimum guard is to detect a debit and credit pair and compute a net movement before any variance analysis:

def net_movement(df: pd.DataFrame, debit: str, credit: str) -> pd.Series:
    return df[credit].fillna(0) - df[debit].fillna(0)

The full fix needs an account type, from a chart of accounts or a simple mapping table, and is the point where “schema-agnostic” honestly becomes “schema-aware”.

The general lesson

None of these guards needs a model. That matters if you plan to add one later to write the commentary. A language model describing a correctly computed variance is useful. A language model describing a variance in a reference number is a confident, fluent mistake.

The work behind this