Functional Weave
Code in Python

finance.ledger.trial-balance

Trial balance from journal lines: debit or credit balance per account, and proof that debits equal credits.

1.0.0 · published 2026-10-03 by charlie · Anterra

Pinned by 13 tests, run in TypeScript, Python and Rust.

What it does

Totals every account's debits and credits and shows each account's balance on the side it falls, the way a trial balance is printed. If double entry was kept, the debit column equals the credit column; `balanced` says whether it does.

The lines can come from any number of journals: a trial balance is built from the whole ledger for a period, not one journal at a time. The lines are checked with finance.ledger.journal-validate first, and a line that cannot be totalled meaningfully is an error, thrown with that capability's message: an amount in another currency, a negative amount, or a malformed account code. An unbalanced set of lines is not an error. Proving whether the ledger balances is what a trial balance is for, so that is the `balanced` answer.

For example

  • trial_balance(lines ×7, GBP) → rows ×5, total debit £120.00, total credit £120.00, balanced true three journals: a sale, a receipt and an expense
  • trial_balance(lines ×2, GBP) → rows ×2, total debit £1.00, total credit £1.00, balanced true accounts sort as text, so 1000 comes before 900
  • trial_balance(lines ×4, GBP) → rows ×3, total debit £5.00, total credit £5.00, balanced true an account that nets to zero keeps its row

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

def trial_balance(lines: Sequence[JournalLine], currency: str) -> TrialBalance
linesJournalLine[]every posted journal line in the period, from any number of journals
currencystringthe ledger's currency; every amount must be in it
returnsTrialBalance

The types it declares, generated into your project

@dataclass(frozen=True)
class TrialBalanceRow:
    """One account's line on the trial balance."""

    account: str
    #: total debits posted
    debits: Money
    #: total credits posted
    credits: Money
    #: debits less credits when that is positive; otherwise zero
    debit_balance: Money
    #: credits less debits when that is positive; otherwise zero
    credit_balance: Money

@dataclass(frozen=True)
class TrialBalance:
    #: one per account, sorted by account code as text
    rows: List[TrialBalanceRow]
    #: sum of the debit balances
    total_debit: Money
    #: sum of the credit balances
    total_credit: Money
    #: whether the two totals agree
    balanced: bool

Your code names it in one line, in the file that uses it

from fune.finance.ledger.trial_balance import trial_balance  # finance.ledger.trial-balance@^1
impl/python.py · 56 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from typing import Dict, List, Sequence, Tuple

from .finance_ledger_journal_validate import validate_journal  ← from finance.ledger.journal-validate ^1.0.0 · built alongside by fune
from .finance_ledger_journal_validate_types import JournalLine
from .finance_ledger_trial_balance_types import TrialBalance, TrialBalanceRow
from .money_add import add_money  ← from money.add ^1.0.0 · built alongside by fune
from .money_amount import Money, money  ← from money.amount ^1.0.0 · built alongside by fune

_FATAL = ("invalid-account", "currency-mismatch", "negative-amount")


def trial_balance(lines: Sequence[JournalLine], currency: str) -> TrialBalance:
    """A trial balance: each account's balance on its own side, and whether the
    debit column equals the credit column.

    Lines that cannot be totalled are raised with journal-validate's message;
    an unbalanced ledger is an answer, not an error.
    """
    check = validate_journal(lines, currency)
    for problem in check.problems:
        if problem.code in _FATAL:
            raise ValueError(problem.message)

    zero = money(0, currency)
    totals: Dict[str, Tuple[Money, Money]] = {}
    for line in lines:
        if line.debit.minor == 0 and line.credit.minor == 0:
            continue
        debits, credits = totals.get(line.account, (zero, zero))
        totals[line.account] = (add_money(debits, line.debit), add_money(credits, line.credit))

    rows: List[TrialBalanceRow] = []
    total_debit = zero
    total_credit = zero
    for account in sorted(totals):
        debits, credits = totals[account]
        net = debits.minor - credits.minor
        debit_balance = money(net if net > 0 else 0, currency)
        credit_balance = money(-net if net < 0 else 0, currency)
        rows.append(
            TrialBalanceRow(
                account=account,
                debits=debits,
                credits=credits,
                debit_balance=debit_balance,
                credit_balance=credit_balance,
            )
        )
        total_debit = add_money(total_debit, debit_balance)
        total_credit = add_money(total_credit, credit_balance)
    return TrialBalance(
        rows=rows,
        total_debit=total_debit,
        total_credit=total_credit,
        balanced=total_debit.minor == total_credit.minor,
    )

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 3 dependencies, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add finance.ledger.trial-balance
Download for Python finance.ledger.trial-balance-1.0.0-python.fune · 18,451 bytes sha256 508345adad6d0023e90861c3d060defdaeca2bd4ade220c95087a982f30b59fa

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./finance.ledger.trial-balance-1.0.0-python.fune, or fetch it from a terminal with fune pull finance.ledger.trial-balance@1.0.0:python.

The whole function, every language, is one file too: finance.ledger.trial-balance-1.0.0.fune, 24,288 bytes, sha256 cec194b001064de3bcd8096dca2aab7883610285ae3ebb71ca1ec50454999df3. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

# fune: before finance.ledger.trial-balance

after — your function gets the result and the arguments, and returns the final result.

# fune: after finance.ledger.trial-balance

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

# fune: replace finance.ledger.journal-validate in finance.ledger.trial-balance
# fune: replace money.add in finance.ledger.trial-balance
# fune: replace money.amount in finance.ledger.trial-balance

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show finance.ledger.trial-balance --steps.

# fune: step finance.ledger.trial-balance after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
three journals: a sale, a receipt and an expense lines ×7, GBP → rows ×5, total debit £120.00, total credit £120.00, balanced true
accounts sort as text, so 1000 comes before 900 lines ×2, GBP → rows ×2, total debit £1.00, total credit £1.00, balanced true
an account that nets to zero keeps its row lines ×4, GBP → rows ×3, total debit £5.00, total credit £5.00, balanced true
an unbalanced ledger is an answer, not an error lines ×2, GBP → rows ×2, total debit £100.00, total credit £99.99, balanced false
no lines: an empty trial balance that balances , GBP → rows , total debit £0.00, total credit £0.00, balanced true
zero lines are skipped and make no row lines ×3, GBP → rows ×2, total debit £1.00, total credit £1.00, balanced true
a line with both sides is totalled on both lines ×2, GBP → rows ×2, total debit £3.00, total credit £3.00, balanced true
many postings to one account lines ×4, GBP → rows ×2, total debit £0.06, total credit £0.06, balanced true
a euro ledger lines ×2, EUR → rows ×2, total debit €1.00, total credit €1.00, balanced true
a line in another currency is refused lines ×2, GBP → error: line 2: amount is in EUR, not the journal currency GBP
Show the other 3 tests
CaseArgumentsExpected
a negative amount is refused lines ×2, GBP → error: line 1: debit and credit must not be negative
a malformed account code is refused lines ×2, GBP → error: line 1: account "12 00" is not a valid account code
the ledger currency must be an ISO code , pounds → error: ISO 4217

More from the author

Lines with a zero debit and a zero credit are skipped and do not create a row. A line with both a debit and a credit is totalled on both sides. An account whose debits and credits cancel still has a row, with both balances zero, because it had postings.

Rows are sorted by account code as text (byte order), which is how a chart of accounts with codes like `1200-01` sorts. Codes of different lengths do not sort numerically: `1000` comes before `900`. Pad codes to a fixed width if a numeric order is wanted.

Files

PathBytes
README.md1,307
impl/python.py2,140
impl/rust.rs3,521
impl/typescript.ts2,104
vectors.json10,143