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
matchBankLines(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 overmatchBankLines(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 themmatchBankLines(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.
export function matchBankLines(bankLines: readonly ReconcileLine[], ledgerEntries: readonly ReconcileLine[], dateWindowDays: number, minSimilarity: number): Reconciliation
| bankLines | ReconcileLine[] | lines from the bank statement |
| ledgerEntries | ReconcileLine[] | unreconciled entries in the cash book |
| dateWindowDays | int | how many days apart a bank line and a ledger entry may be dated, 0 or more |
| minSimilarity | 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
/** A bank line or a ledger entry. */
export interface ReconcileLine {
/** unique within its list */
readonly id: string;
readonly date: string;
/** positive for money in, negative for money out, on both sides */
readonly amount: Money;
readonly reference: string;
}
/** One bank line paired with one ledger entry. */
export interface ReconcileMatch {
readonly bankId: string;
readonly ledgerId: string;
/** bank date less ledger date, in days */
readonly dayDifference: number;
/** reference similarity, 0 to 10000 */
readonly similarity: number;
}
export interface Reconciliation {
/** in bank-line order */
readonly matches: readonly ReconcileMatch[];
/** ids, in input order */
readonly unmatchedBank: readonly string[];
/** ids, in input order */
readonly unmatchedLedger: readonly string[];
}
Your code names it in one line, in the file that uses it
import { matchBankLines } from "#fune/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.
import { daysBetween } from "./dates_days_between.ts"; ← from dates.days-between ^1.0.0 · built alongside by fune
import { roundDiv } from "./math_round_div.ts"; ← from math.round-div ^1.0.0 · built alongside by fune
import { type ReconcileLine, type ReconcileMatch, type Reconciliation } from "./finance_bank_reconcile_match_types.ts";
function reduce(reference: string): string {
let out = "";
for (let i = 0; i < reference.length; i += 1) {
const code = reference.charCodeAt(i);
if ((code >= 48 && code <= 57) || (code >= 65 && code <= 90)) out += reference[i];
else if (code >= 97 && code <= 122) out += String.fromCharCode(code - 32);
}
return out;
}
function bigrams(text: string): string[] {
const out: string[] = [];
for (let i = 0; i + 1 < text.length; i += 1) out.push(text.slice(i, i + 2));
return out;
}
/** Sørensen-Dice on adjacent character pairs, 0 to 10000, rounded down. */
function similarity(a: string, b: string): number {
const x = reduce(a);
const y = reduce(b);
if (x.length > 0 && x === y) return 10000;
const left = bigrams(x);
const right = bigrams(y);
if (left.length === 0 || right.length === 0) return 0;
const used = right.map(() => false);
let shared = 0;
for (const pair of left) {
const at = right.findIndex((other, i) => !used[i] && other === pair);
if (at >= 0) {
used[at] = true;
shared += 1;
}
}
return roundDiv(2 * shared * 10000, left.length + right.length, "down");
}
function checkIds(lines: readonly ReconcileLine[], side: string): void {
const seen = new Set<string>();
for (const line of lines) {
if (seen.has(line.id)) throw new RangeError(`duplicate ${side} id "${line.id}"`);
seen.add(line.id);
}
}
/**
* Pair bank lines with ledger entries: equal amount, dates within the window,
* references alike enough, best pairs first and ties broken by input order.
*/
export function matchBankLines(
bankLines: readonly ReconcileLine[],
ledgerEntries: readonly ReconcileLine[],
dateWindowDays: number,
minSimilarity: number,
): Reconciliation {
if (!Number.isInteger(dateWindowDays) || dateWindowDays < 0) {
throw new RangeError(`dateWindowDays must be 0 or more, received ${dateWindowDays}`);
}
if (!Number.isInteger(minSimilarity) || minSimilarity < 0 || minSimilarity > 10000) {
throw new RangeError(`minSimilarity must be 0 to 10000, received ${minSimilarity}`);
}
checkIds(bankLines, "bank line");
checkIds(ledgerEntries, "ledger entry");
const candidates: { b: number; l: number; days: number; score: number }[] = [];
bankLines.forEach((bank, b) => {
ledgerEntries.forEach((entry, l) => {
const days = daysBetween(entry.date, bank.date);
if (bank.amount.currency !== entry.amount.currency || bank.amount.minor !== entry.amount.minor) return;
if (Math.abs(days) > dateWindowDays) return;
const score = similarity(bank.reference, entry.reference);
if (score < minSimilarity) return;
candidates.push({ b, l, days, score });
});
});
candidates.sort((p, q) => q.score - p.score || Math.abs(p.days) - Math.abs(q.days) || p.b - q.b || p.l - q.l);
const bankMatch: (ReconcileMatch | null)[] = bankLines.map(() => null);
const ledgerUsed = ledgerEntries.map(() => false);
for (const c of candidates) {
if (bankMatch[c.b] !== null || ledgerUsed[c.l]) continue;
bankMatch[c.b] = { bankId: bankLines[c.b].id, ledgerId: ledgerEntries[c.l].id, dayDifference: c.days, similarity: c.score };
ledgerUsed[c.l] = true;
}
const matches: ReconcileMatch[] = [];
const unmatchedBank: string[] = [];
bankLines.forEach((bank, b) => {
const m = bankMatch[b];
if (m === null) unmatchedBank.push(bank.id);
else matches.push(m);
});
const unmatchedLedger = ledgerEntries.filter((_, l) => !ledgerUsed[l]).map((e) => e.id);
return { matches, unmatchedBank, unmatchedLedger };
}Install
fune build
With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 3 dependencies, pins them in fune.lock, downloads only the TypeScript 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 TypeScript implementation. Install it without the registry with fune add ./finance.bank-reconcile-match-1.0.0-typescript.fune, or fetch it from a terminal with fune pull finance.bank-reconcile-match@1.0.0:typescript.
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 |