finance.bank-reconcile-match
Match bank statement lines to ledger entries by exact amount, a date window and reference similarity, deterministically.
1.0.0 · published 2026-10-03 by charlie · Anterra
Pinned by 19 tests, run in TypeScript, Python and Rust.
What it does
The auto-match step of a bank reconciliation: pair each bank statement line with at most one cash-book entry, and list what is left on each side for a person to deal with.
**A pair is a candidate** when the amounts are exactly equal (same currency, same sign, same minor units), the dates are at most `dateWindowDays` apart in either direction, and the references are at least `minSimilarity` alike.
For example
match_bank_lines(bank lines ×3, ledger entries ×3, 3, 0)→ matches ×2, unmatched bank B3, unmatched ledger L3 a receipt and a direct debit match; the stray line on each side is left overmatch_bank_lines(bank lines ×2, ledger entries ×2, 3, 0)→ matches ×2, unmatched bank , unmatched ledger two equal payments pair by reference, not by the order the ledger lists themmatch_bank_lines(bank lines ×2, ledger entries ×2, 3, 0)→ matches ×2, unmatched bank , unmatched ledger the best pair overall is taken first, even when it is not the first bank line's nearest date
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 match_bank_lines(bank_lines: Sequence[ReconcileLine], ledger_entries: Sequence[ReconcileLine], date_window_days: int, min_similarity: int) -> Reconciliation
| bank_lines | ReconcileLine[] | lines from the bank statement |
| ledger_entries | ReconcileLine[] | unreconciled entries in the cash book |
| date_window_days | int | how many days apart a bank line and a ledger entry may be dated, 0 or more |
| min_similarity | int | the least reference similarity a match needs, 0 to 10000; 0 matches on amount and date alone |
| returns | Reconciliation |
The types it declares, generated into your project
@dataclass(frozen=True)
class ReconcileLine:
"""A bank line or a ledger entry."""
#: unique within its list
id: str
date: str
#: positive for money in, negative for money out, on both sides
amount: Money
reference: str
@dataclass(frozen=True)
class ReconcileMatch:
"""One bank line paired with one ledger entry."""
bank_id: str
ledger_id: str
#: bank date less ledger date, in days
day_difference: int
#: reference similarity, 0 to 10000
similarity: int
@dataclass(frozen=True)
class Reconciliation:
#: in bank-line order
matches: List[ReconcileMatch]
#: ids, in input order
unmatched_bank: List[str]
#: ids, in input order
unmatched_ledger: List[str]
Your code names it in one line, in the file that uses it
from fune.finance.bank_reconcile_match import match_bank_lines # finance.bank-reconcile-match@^1
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 List, Optional, Sequence
from .dates_days_between import days_between ← from dates.days-between ^1.0.0 · built alongside by fune
from .finance_bank_reconcile_match_types import ReconcileLine, ReconcileMatch, Reconciliation
from .math_round_div import round_div ← from math.round-div ^1.0.0 · built alongside by fune
def _reduce(reference: str) -> str:
out = []
for ch in reference:
if "0" <= ch <= "9" or "A" <= ch <= "Z":
out.append(ch)
elif "a" <= ch <= "z":
out.append(chr(ord(ch) - 32))
return "".join(out)
def _bigrams(text: str) -> List[str]:
return [text[i : i + 2] for i in range(len(text) - 1)]
def _similarity(a: str, b: str) -> int:
"""Sørensen-Dice on adjacent character pairs, 0 to 10000, rounded down."""
x = _reduce(a)
y = _reduce(b)
if len(x) > 0 and x == y:
return 10000
left = _bigrams(x)
right = _bigrams(y)
if len(left) == 0 or len(right) == 0:
return 0
used = [False] * len(right)
shared = 0
for pair in left:
for i, other in enumerate(right):
if not used[i] and other == pair:
used[i] = True
shared += 1
break
return round_div(2 * shared * 10000, len(left) + len(right), "down")
def _check_ids(lines: Sequence[ReconcileLine], side: str) -> None:
seen = set()
for line in lines:
if line.id in seen:
raise ValueError('duplicate %s id "%s"' % (side, line.id))
seen.add(line.id)
def match_bank_lines(
bank_lines: Sequence[ReconcileLine],
ledger_entries: Sequence[ReconcileLine],
date_window_days: int,
min_similarity: int,
) -> Reconciliation:
"""Pair bank lines with ledger entries: equal amount, dates within the
window, references alike enough, best pairs first and ties broken by input
order.
"""
if isinstance(date_window_days, bool) or not isinstance(date_window_days, int) or date_window_days < 0:
raise ValueError("dateWindowDays must be 0 or more, received %s" % (date_window_days,))
if (
isinstance(min_similarity, bool)
or not isinstance(min_similarity, int)
or min_similarity < 0
or min_similarity > 10000
):
raise ValueError("minSimilarity must be 0 to 10000, received %s" % (min_similarity,))
_check_ids(bank_lines, "bank line")
_check_ids(ledger_entries, "ledger entry")
candidates = []
for b, bank in enumerate(bank_lines):
for l, entry in enumerate(ledger_entries):
days = days_between(entry.date, bank.date)
if bank.amount.currency != entry.amount.currency or bank.amount.minor != entry.amount.minor:
continue
if abs(days) > date_window_days:
continue
score = _similarity(bank.reference, entry.reference)
if score < min_similarity:
continue
candidates.append((-score, abs(days), b, l, days, score))
candidates.sort()
bank_match: List[Optional[ReconcileMatch]] = [None] * len(bank_lines)
ledger_used = [False] * len(ledger_entries)
for _, _, b, l, days, score in candidates:
if bank_match[b] is not None or ledger_used[l]:
continue
bank_match[b] = ReconcileMatch(
bank_id=bank_lines[b].id, ledger_id=ledger_entries[l].id, day_difference=days, similarity=score
)
ledger_used[l] = True
matches = [m for m in bank_match if m is not None]
unmatched_bank = [bank.id for b, bank in enumerate(bank_lines) if bank_match[b] is None]
unmatched_ledger = [entry.id for l, entry in enumerate(ledger_entries) if not ledger_used[l]]
return Reconciliation(matches=matches, unmatched_bank=unmatched_bank, unmatched_ledger=unmatched_ledger)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.bank-reconcile-match
The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./finance.bank-reconcile-match-1.0.0-python.fune, or fetch it from a terminal with fune pull finance.bank-reconcile-match@1.0.0:python.
The whole function, every language, is one file too: finance.bank-reconcile-match-1.0.0.fune, 28,900 bytes, sha256 fb3977c3dbadd7f9c05039af4e56d6ec222201493cb059430c7cf27c85a4a88b. 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.bank-reconcile-match
after — your function gets the result and the arguments, and returns the final result.
# fune: after finance.bank-reconcile-match
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 dates.days-between in finance.bank-reconcile-match
# fune: replace math.round-div in finance.bank-reconcile-match
# fune: replace money.amount in finance.bank-reconcile-match
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.bank-reconcile-match --steps.
# fune: step finance.bank-reconcile-match 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.
| Case | Arguments | Expected | |
|---|---|---|---|
| a receipt and a direct debit match; the stray line on each side is left over | bank lines ×3, ledger entries ×3, 3, 0 | → | matches ×2, unmatched bank B3, unmatched ledger L3 |
| two equal payments pair by reference, not by the order the ledger lists them | bank lines ×2, ledger entries ×2, 3, 0 | → | matches ×2, unmatched bank , unmatched ledger |
| the best pair overall is taken first, even when it is not the first bank line's nearest date | bank lines ×2, ledger entries ×2, 3, 0 | → | matches ×2, unmatched bank , unmatched ledger |
| equal similarity: the nearer date wins | bank lines ×1, ledger entries ×2, 3, 0 | → | matches ×1, unmatched bank , unmatched ledger L1 |
| a complete tie goes to the earlier ledger entry | bank lines ×1, ledger entries ×2, 3, 0 | → | matches ×1, unmatched bank , unmatched ledger L2 |
| the date window is inclusive: 3 days matches, 4 does not | bank lines ×2, ledger entries ×2, 3, 0 | → | matches ×1, unmatched bank B2, unmatched ledger L2 |
| a zero window needs the same date | bank lines ×1, ledger entries ×1, 0, 0 | → | matches , unmatched bank B1, unmatched ledger L1 |
| a reference below the minimum similarity does not match | bank lines ×1, ledger entries ×1, 3, 5,000 | → | matches , unmatched bank B1, unmatched ledger L1 |
| similarity counts repeated pairs once each: AAAA against AA is 5000 | bank lines ×1, ledger entries ×1, 3, 5,000 | → | matches ×1, unmatched bank , unmatched ledger |
| ACME LTD against ACME is 6666, rounded down | bank lines ×1, ledger entries ×1, 3, 0 | → | matches ×1, unmatched bank , unmatched ledger |
Show the other 9 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| INV1001 against INV1002 is 8333 | bank lines ×1, ledger entries ×1, 3, 0 | → | matches ×1, unmatched bank , unmatched ledger |
| the same amount in another currency is not a match | bank lines ×1, ledger entries ×1, 3, 0 | → | matches , unmatched bank B1, unmatched ledger L1 |
| money out does not match money in | bank lines ×1, ledger entries ×1, 3, 0 | → | matches , unmatched bank B1, unmatched ledger L1 |
| nothing to match | , , 3, 0 | → | matches , unmatched bank , unmatched ledger |
| a negative window is refused | , , -1, 0 | → | error: dateWindowDays must be 0 or more |
| a similarity over 10000 is refused | , , 3, 10,001 | → | error: minSimilarity must be 0 to 10000 |
| duplicate bank ids are refused | bank lines ×2, , 3, 0 | → | error: duplicate bank line id "B1" |
| duplicate ledger ids are refused | , ledger entries ×2, 3, 0 | → | error: duplicate ledger entry id "L1" |
| an impossible date is refused | bank lines ×1, ledger entries ×1, 3, 0 | → | error: not a real calendar date |
More from the author
**Choosing among candidates** is where reconciliations go wrong, so it is fixed and global rather than first-come-first-served. All candidate pairs are ranked by, in order:
1. higher reference similarity, 2. fewer days apart, 3. earlier bank line (input order), 4. earlier ledger entry (input order),
and taken best first, skipping any pair whose bank line or ledger entry is already matched. Two payments of 500.00 on the same day, referenced INV2002 and INV2001, pair with the ledger entries of those references even when the ledger lists them the other way round; matching bank lines in order to the first equal amount would cross them. The same inputs always give the same pairs.
**Reference similarity** is a Sørensen-Dice score on character pairs, in basis points: both references are reduced to their ASCII letters and digits in upper case ("INV-1001 Acme" becomes "INV1001ACME"), and the score is twice the number of shared adjacent-character pairs over the total number of pairs, counting repeats, rounded down. Identical non-empty references score 10000; a reference with fewer than two characters after reduction scores 0 against anything else, as does an empty one. "INV1001" against "INV1001ACME" is 7500; against "INV1002" it is 8333.
Matches come back in bank-line order, with the day difference (bank date less ledger date; positive when the bank cleared later) and the similarity that justified them. Ids must be unique within each list. One-to-many matches (one deposit paying several invoices) are not attempted; they need a person or a separate rule.
Files
| Path | Bytes |
|---|---|
| README.md | 2,010 |
| impl/python.py | 3,722 |
| impl/rust.rs | 5,638 |
| impl/typescript.ts | 3,801 |
| vectors.json | 8,275 |