If you build a finance dashboard on top of an accounting system, the first serious question from a user will be: "Why does your gross profit not match my P&L?" You need an answer that is better than "timing". The reliable way to reconcile KPI with profit and loss figures is to stop comparing totals and start comparing accounts.
This post walks through an account-by-account reconciliation in Python (with a Django flavor): fetch both sides, normalize them, diff with Decimal, roll the diff up to KPI lines, and classify the causes.
Why totals-only checks fail
Comparing "our gross profit" with "their gross profit" tells you that something is wrong, not what. A difference of 350 could be one missing invoice, a deleted transaction you still hold, a timezone edge, or two larger errors cancelling out. Two errors of +900 and −900 even produce a perfect match on totals.
An account-level diff fixes that. Every account in the P&L has an ID; your synced transactions carry the same ID; your KPI definitions map accounts to lines such as sales, cost of sales and operating costs. So reconciliation has three layers:
- Mapping coverage: does every P&L account with a balance map to a KPI line?
- Account diff: for each account, does your total equal the ledger's total for the same period and basis?
- Line check: do the rolled-up KPI lines equal the P&L's own subtotals?
Step 1: get the ledger side by account
QuickBooks Online and Xero both expose a P&L report through their APIs:
- QuickBooks Online:
GET /v3/company/<realmId>/reports/ProfitAndLosswithstart_dateandend_date(yyyy-mm-dd) and anaccounting_methodofCashorAccrual. See Intuit's Run reports guide. - Xero:
GET /api.xro/2.0/Reports/ProfitAndLosswithfromDateandtoDate. Check its options for cash vs accrual before you compare. See Xero's Reports API documentation.
Both return nested report rows (sections, account rows, subtotals) rather than a flat list, so write a small flattener per provider that yields account_id -> (name, amount) for account rows only and skips subtotal rows. Keep the subtotals separately for layer 3.
Two normalizations matter before diffing:
- Signs. P&L reports show income and expenses as positive numbers. If your transaction store uses debit/credit signs, convert it to the report's convention once, in one place.
- Dates. Report end dates are inclusive. If your own queries use half-open ranges (
>= start AND < end), add one day to the report's end date when you build your window.
Step 2: compute your side from synced data
In Django, a single grouped query gives per-account totals for the same window:
from datetime import date, timedelta from decimal import Decimal from django.db.models import Sum def our_totals(company, start: date, end_inclusive: date) -> dict[str, Decimal]: rows = ( LedgerLine.objects .filter(company=company, txn_date__gte=start, txn_date__lt=end_inclusive + timedelta(days=1)) .values("account_id") .annotate(total=Sum("amount")) ) return {r["account_id"]: r["total"] for r in rows} Use DecimalField for money end to end. Floats will produce "differences" of 0.0000001 that nobody can explain.
Step 3: diff account by account
from dataclasses import dataclass from decimal import Decimal TOLERANCE = Decimal("0.01") @dataclass(frozen=True) class AccountDiff: account_id: str name: str ledger: Decimal ours: Decimal @property def delta(self) -> Decimal: return self.ours - self.ledger def diff_accounts(ledger: dict[str, tuple[str, Decimal]], ours: dict[str, Decimal], tolerance: Decimal = TOLERANCE) -> list[AccountDiff]: diffs = [] for acc in ledger.keys() | ours.keys(): name, ledger_amt = ledger.get(acc, ("(missing from P&L)", Decimal("0"))) our_amt = ours.get(acc, Decimal("0")) if abs(our_amt - ledger_amt) > tolerance: diffs.append(AccountDiff(acc, name, ledger_amt, our_amt)) return sorted(diffs, key=lambda d: abs(d.delta), reverse=True) The union of keys is the important part: an account that exists only on one side is the most common real finding. Sorting by absolute delta puts the account worth investigating first.
With sample data (made-up numbers), the output looks like this:
5100 Freight in ledger=1200.00 ours=0 delta=-1200.00 4000 Sales ledger=52000.00 ours=51650.00 delta=-350.00 Step 4: roll up to KPI lines and catch unmapped accounts
from collections import defaultdict def roll_up(amounts: dict[str, Decimal], mapping: dict[str, str]): lines: dict[str, Decimal] = defaultdict(Decimal) unmapped: dict[str, Decimal] = {} for acc, amount in amounts.items(): line = mapping.get(acc) if line is None: if amount: unmapped[acc] = amount else: lines[line] += amount return dict(lines), unmapped Run it on the ledger amounts, not yours. If unmapped is not empty, some money in the P&L never reaches a KPI, and the user should see a warning with the amount, not a silently lower cost of sales. In the sample, account 5100 (freight in) has 1,200 with no mapping: the dashboard's gross margin would be overstated until someone maps it.
Then compare each rolled-up line with the matching P&L subtotal (total income, total cost of sales). If accounts match but lines do not, your mapping puts an account on the wrong line.
Step 5: classify the causes
A diff is only useful if it comes with a likely reason. These are the usual suspects, roughly in order of frequency:
| Symptom | Likely cause |
|---|---|
| Account missing on your side | Not synced yet, or excluded by a filter |
| Account missing on the ledger side | Transaction deleted or voided in the ledger, still in your store |
| Many accounts off by small amounts | Cash vs accrual basis mismatch |
| Differences near period edges | Inclusive vs exclusive end date, or time zone of timestamps |
| Whole-cent differences on many lines | Rounding per line vs per document |
| Foreign-currency accounts off | Your store holds transaction currency, the report holds home currency |
Store the reconciliation result (period, basis, per-account diffs, unmapped list, run time) as a row, so you can show history and catch regressions after a connector change.
Practical rules
- Reconcile closed periods first. Open months move while you compare.
- Pin the basis explicitly on both sides; never rely on a report default.
- Re-run after each sync for the last closed month and alert on new diffs.
- Show the diff to users. "Matches your P&L except freight in (1,200, unmapped)" builds more trust than a green tick.
How Lumetric approaches it
Lumetric, a read-only reporting dashboard over QuickBooks Online, Xero, Shopify and CSV/Excel uploads, reconciles its figures against the QuickBooks or Xero P&L account by account, uses versioned mappings, and warns about unmapped amounts. It also documents what its connectors do not sync today (QuickBooks deletions, Xero credit notes, Shopify refunds), which is exactly the kind of gap the diff above is designed to surface.
See how Lumetric handles this: https://lumetric.example/?utm_source=devto&utm_medium=blog&utm_campaign=launch_m1&utm_content=d010-article
Originally published at Lumetric blog.