Changeset - bd07154fbbb8
[Not reviewed]
0 1 0
Ben Sturmfels (bsturmfels) - 2 months ago 2024-07-19 05:52:57
ben@sturm.com.au
statement_reconciler: Fix example usage docs
1 file changed with 1 insertions and 1 deletions:
0 comments (0 inline, 0 general)
conservancy_beancount/reconcile/statement_reconciler.py
Show inline comments
 
"""Compare a bank CSV statement with the books.
 

	
 
This tool takes an AMEX or First Republic CSV statement file and compares it
 
line-by-line with the Beancount books to make sure that everything matches. This
 
is designed for situations where transactions are entered into the books
 
directly, rather than being imported from a statement after the fact.
 

	
 
The reconciler will attempt to match transactions based on date, amount, check
 
number and payee, but is forgiving to differences in dates, the absensce of
 
check number and inexact matches on payee. Matches are ranked, so where there is
 
only one decent match for an amount/date this is accepted, but if there are
 
multiple similar candidates it will refuse to guess.
 

	
 
The reconciler will also attempt to identify where a single statement entry has
 
been split out into multiple Beancount postings, such as a single bank transfer
 
representing health insurance for multiple employees.
 

	
 
Run it like this:
 

	
 
$ statement_reconciler \
 
$ statement-reconciler \
 
  --beancount-file 2021.beancount \
 
  --account Liabilities:CreditCard:AMEX \
 
  --csv-statement ~/svn/2021-09-10_AMEX_activity.csv \
 
  --bank-statement ~/svn/2021-09-10_AMEX_activity.pdf
 

	
 
Background:
 

	
 
Regular Beancount users often write automated importers to create bookkeeping
 
entries direct from a bank statement or similar. That combines data entry and
 
reconciliation in one step. Conservancy uses a different approach; they manually
 
entering transactions and reconciling them later on. This workflow is helpful in
 
cases like writing checks (see below). This is the workflow implented by this
 
tool.
 

	
 
That said, this tool *is* still somewhat like an importer in that it needs to
 
extract transaction details from a third-party statement. Instead of creating
 
directives, it just checks to see that similar directives are already
 
present. This is a bit like diff-ing a statement with the books (though we're
 
only interested in the presence of lines, not so much their order).
 

	
 
Paper checks are entered into the books when written (a.k.a. "posted"), but may
 
not be cashed until months later sometimes causing reconciliation differences
 
that live beyond a month. It's worth noting that there are really two dates here
 
- the posting date and the cleared date. Beancount only allows us to model one,
 
which is why carrying these reconciliation differences between months feels a
 
bit awkward.
 

	
 
Problems in scope:
 

	
 
 - errors in the books take hours to find during reconciliation, requiring
 
   manually comparing statements and the books and are succeptible to mistakes,
 
   such as not noticing when there are two payments for the same amount on the
 
   statement, but not in the books (as Bradley likes to quote, "you're entering
 
   a world of pain")
 

	
 
 - adding statement/reconciliation metadata to books is/was manual and prone to
 
   mistakes
 

	
 
 - jumping to an individual transaction in a large ledger isn't trivial - Emacs
 
   grep mode is the current best option
 

	
 
 - not all staff use Emacs
 

	
 
 - auditors would prefer Bradley didn't perform reconciliation, ideally not
 
   Rosanne either
 

	
 
 - reconciliation reports are created by hand when there are mismatches
 

	
 
Other related problems we're not dealing with here:
 

	
 
 - after updates to the books files, beancount must be restarted to reflect
 
   updates
 

	
 
 - updates also invalidate the cache meaning restart takes several minutes
 

	
 
 - balance checks are manually updated in
 
   svn/Financial/Ledger/sanity-check-balances.yaml
 

	
 
 - transactions are entered manually and reconciled after the fact, but
 
   importing from statements may be useful in some cases
 

	
 
Current issue:
 

	
 
 - entry_point seems to swallow errors, meaning you get a fairly unhelpful
 
   message if there's an unhandled error
 

	
 
Future possibilities:
 

	
 
 - allow the reconciler to respect manually-applied metadata - not clear how
 
   this would work exactly
 

	
 
 - allow interactive matching where the user can specifiy a match
 

	
 
 - consider combining this with helper.py into one more complete tool that both
 
   reconciles and summarises the unreconciled transactions
 
"""
 

	
 
import argparse
 
import collections
 
import copy
 
import csv
 
import datetime
 
import decimal
 
import io
 
import itertools
 
import logging
 
import os
 
import re
 
import sys
 
from typing import Dict, List, Optional, Sequence, Tuple, TextIO
 

	
 
from beancount import loader
 
from beancount.query.query import run_query
 
from colorama import Fore, Style  # type: ignore
 

	
 
from .. import cliutil
 
from .. import config as configmod
 

	
 
if not sys.warnoptions:
 
    import warnings
 

	
 
    # Disable annoying warning from thefuzz prompting for a C extension. The
 
    # current pure-Python implementation isn't a bottleneck for us.
 
    warnings.filterwarnings('ignore', category=UserWarning, module='thefuzz.fuzz')
 
from thefuzz import fuzz  # type: ignore
 

	
 
PROGNAME = 'reconcile-statement'
 
logger = logging.getLogger(__name__)
 

	
 
# Get some interesting feedback on call to RT with this:
 
# logger.setLevel(logging.DEBUG)
 
# logger.addHandler(logging.StreamHandler())
 

	
 
JUNK_WORDS = [
 
    'software',
 
    'freedom',
 
    'conservancy',
 
    'conse',
 
    'payment',
 
    'echeck',
 
    'bill',
 
    'debit',
 
    'wire',
 
    'credit',
 
    "int'l",
 
    "in.l",
 
    'llc',
 
    'online',
 
    'donation',
 
    'usd',
 
    'inc',
 
]
 
JUNK_WORDS_RES = [re.compile(word, re.IGNORECASE) for word in JUNK_WORDS]
 
ZERO_RE = re.compile('^0+')
 
PAYEE_FULL_MATCH_THRESHOLD = 0.8
 
PAYEE_PARTIAL_MATCH_THRESHOLD = 0.4
 
OVERALL_EXCELLENT_MATCH_THRESHOLD = 0.8  # Clear winner
 
OVERALL_ACCEPTABLE_MATCH_THRESHOLD = 0.5  # Acceptable if only one match found
 

	
 

	
 
def remove_duplicate_words(text: str) -> str:
 
    unique_words = []
 
    known_words = set()
 
    for word in text.split():
 
        if word.lower() not in known_words:
 
            unique_words.append(word)
 
            known_words.add(word.lower())
 
    return ' '.join(unique_words)
 

	
 

	
 
def remove_payee_junk(payee: str) -> str:
 
    """Clean up payee field to improve quality of fuzzy matching.
 

	
 
    It turns out that bank statement "description" fields are
 
    difficult to fuzzy match on because they're long and
 
    noisey. Truncating them (see standardize_XXX_record fns) and
 
    removing the common junk helps significantly.
 

	
 
    """
 
    for r in JUNK_WORDS_RES:
 
        payee = r.sub('', payee)
 
    payee = ZERO_RE.sub('', payee)
 
    payee = payee.replace(' - ', ' ')
 
    payee = re.sub(r'\.0\.\d+', ' ', payee)
 
    payee = payee.replace('.0', ' ')
 
    payee = payee.replace('/', ' ')
 
    payee = re.sub(re.escape('.com'), ' ', payee, flags=re.IGNORECASE)
 
    payee = re.sub(re.escape('.net'), ' ', payee, flags=re.IGNORECASE)
 
    payee = payee.replace('*', ' ')
 
    payee = ' '.join([i for i in payee.split(' ') if len(i) > 2])
 
    payee = payee.replace('-', ' ')
 
    payee = remove_duplicate_words(payee)
 
    payee.strip()
 
    return payee
 

	
 

	
 
def parse_amount(amount: str) -> decimal.Decimal:
 
    """Parse amounts and handle comma separators as seen in some FR statements."""
 
    return decimal.Decimal(amount.replace('$', '').replace(',', ''))
 

	
 

	
 
def validate_amex_csv(sample: str) -> None:
 
    required_cols = {'Date', 'Amount', 'Description', 'Card Member'}
 
    reader = csv.DictReader(io.StringIO(sample))
 
    if reader.fieldnames and not required_cols.issubset(reader.fieldnames):
 
        sys.exit(
 
            f"This AMEX CSV doesn't seem to have the columns we're expecting, including: {', '.join(required_cols)}. Please use an unmodified statement direct from the institution."
 
        )
 

	
 

	
 
def standardize_amex_record(row: Dict, line: int) -> Dict:
 
    """Turn an AMEX CSV row into a standard dict format representing a transaction."""
 
    # NOTE: Statement doesn't seem to give us a running balance or a final total.
 
    return {
 
        'date': datetime.datetime.strptime(row['Date'], '%m/%d/%Y').date(),
 
        'amount': -1 * parse_amount(row['Amount']),
 
        # Descriptions have too much noise, so taking just the start
 
        # significantly assists the fuzzy matching.
 
        'payee': remove_payee_junk(row['Description'] or '')[:20],
 
        'check_id': '',
 
        'line': line,
 
    }
 

	
 

	
 
def read_amex_csv(f: TextIO) -> list:
 
    reader = csv.DictReader(f)
 
    # The reader.line_num is the source line number, not the spreadsheet row
 
    # number due to multi-line records.
 
    return sort_records(
 
        [standardize_amex_record(row, i) for i, row in enumerate(reader, 2)]
 
    )
 

	
 

	
 
def validate_fr_csv(sample: str) -> None:
 
    # No column headers in FR statements
 
    reader = csv.reader(io.StringIO(sample))
 
    next(reader)  # First row is previous statement ending balance
 
    row = next(reader)
 
    date = None
 
    try:
 
        date = datetime.datetime.strptime(row[1], '%m/%d/%Y')
 
    except ValueError:
 
        pass
 
    amount_found = '$' in row[4] and '$' in row[5]
 
    if len(row) != 6 or not date or not amount_found:
 
        sys.exit(
 
            "This First Republic CSV doesn't seem to have the 6 columns we're expecting, including a date in column 2 and an amount in columns 5 and 6. Please use an unmodified statement direct from the institution."
 
        )
 

	
 

	
 
def standardize_fr_record(line, row):
 
    record = {
 
        'date': datetime.datetime.strptime(row[1], '%m/%d/%Y').date(),
 
        'amount': parse_amount(row[4]),
 
        'payee': remove_payee_junk(row[3] or '')[:20],
 
        'check_id': row[2].replace('CHECK  ', '') if 'CHECK  ' in row[2] else '',
 
        'line': line,
 
    }
 
    return record
 

	
 

	
 
def read_fr_csv(f: TextIO) -> list:
 
    reader = csv.reader(f)
 
    # The reader.line_num is the source line number, not the spreadsheet row
 
    # number due to multi-line records.
 
    return sort_records(
 
        standardize_fr_record(i, row)
 
        for i, row in enumerate(reader, 1)
 
        if len(row) == 6 and row[2] not in {'LAST STATEMENT', 'THIS STATEMENT'}
 
    )
 

	
 

	
 
def standardize_beancount_record(row) -> Dict:  # type: ignore[no-untyped-def]
 
    """Turn a Beancount query result row into a standard dict representing a transaction."""
 
    return {
 
        'date': row.date,
 
        'amount': row.number_cost_position,
 
        'payee': remove_payee_junk(
 
            f'{row.payee or ""} {row.entity or ""} {row.narration or ""}'
 
        ),
 
        'check_id': str(row.check_id or ''),
 
        'filename': row.filename,
 
        'line': row.line,
 
        'bank_statement': row.bank_statement,
 
    }
 

	
 

	
 
def format_record(record: dict) -> str:
 
    """Generate output lines for a standard 1:1 match."""
 
    if record['payee'] and record['check_id']:
 
        output = f"{record['date'].isoformat()}: {record['amount']:11,.2f} {record['payee'][:25]} #{record['check_id']}".ljust(59)
 
    elif record['payee']:
 
        output = f"{record['date'].isoformat()}: {record['amount']:11,.2f} {record['payee'][:35]}".ljust(59)
 
    else:
 
        output = f"{record['date'].isoformat()}: {record['amount']:11,.2f} #{record['check_id']}".ljust(59)
 
    return output
 

	
 

	
 
def format_multirecord(r1s: List[dict], r2s: List[dict], note: str) -> List[list]:
 
    """Generates output lines for one statement:multiple books transaction match."""
 
    assert len(r1s) == 1
 
    assert len(r2s) > 1
 
    match_output = []
 
    match_output.append(
 
        [
 
            r1s[0]['date'],
 
            f'{format_record(r1s[0])}  →  {format_record(r2s[0])}  ✓ Matched{note}',
 
        ]
 
    )
 
    for r2 in r2s[1:]:
 
        match_output.append(
 
            [
 
                r1s[0]['date'],
 
                f'{r1s[0]["date"].isoformat()}:             ↳                                    →  {format_record(r2)}  ✓ Matched{note}',
 
            ]
 
        )
 
    return match_output
 

	
 

	
 
def _start_of_month(time, offset_months=0):
 
    if offset_months > 0:
 
        return _start_of_month(
 
            time.replace(day=28) + datetime.timedelta(days=4), offset_months - 1
 
        )
 
    else:
 
        return time.replace(day=1)
 

	
 

	
 
def round_to_month(begin_date, end_date):
 
    """Round a beginning and end date to beginning and end of months respectively."""
 
    return (
 
        _start_of_month(begin_date),
 
        _start_of_month(end_date, offset_months=1) - datetime.timedelta(days=1),
 
    )
 

	
 

	
 
def sort_records(records: List) -> List:
 
    return sorted(records, key=lambda x: (x['date'], x['amount']))
 

	
 

	
 
def first_word_exact_match(a: str, b: str) -> float:
 
    """Score a payee match based first word.
 

	
 
    We get a whole lot of good matches this way. Helps in the
 
    situation where the first word or two of a transaction description
 
    is useful and the rest is garbage.
 

	
 
    """
 
    if len(a) == 0 or len(b) == 0:
 
        return 0.0
 
    first_a = a.split()[0].strip()
 
    first_b = b.split()[0].strip()
 
    if first_a.casefold() == first_b.casefold():
 
        return min(1.0, 0.2 * len(first_a))
 
    else:
 
        return 0.0
 

	
 

	
 
def payee_match(a: str, b: str) -> float:
 
    """Score a match between two payees."""
 
    fuzzy_match = float(fuzz.token_set_ratio(a, b) / 100.00)
 
    first_word_match = first_word_exact_match(a, b)
 
    return max(fuzzy_match, first_word_match)
 

	
 

	
 
def records_match(r1: Dict, r2: Dict) -> Tuple[float, List[str]]:
 
    """Do these records represent the same transaction?"""
 
    date_score = date_proximity(r1['date'], r2['date'])
 
    if r1['date'] == r2['date']:
 
        date_message = ''
 
    elif date_score > 0.0:
 
        diff = abs((r1['date'] - r2['date']).days)
 
        date_message = f'+/- {diff} days'
 
    else:
 
        date_message = 'date mismatch'
 

	
 
    if r1['amount'] == r2['amount']:
 
        amount_score, amount_message = 2.0, ''
 
    else:
 
        amount_score, amount_message = 0.0, 'amount mismatch'
 

	
 
    # We never consider payee if there's a check_id in the books.
 
    check_message = ''
 
    payee_message = ''
 
    # Sometimes we get unrelated numbers in the statement column with check-ids,
 
    # so we can't match based on the existence of a statement check-id.
 
    if r2['check_id']:
 
        payee_score = 0.0
 
        if r1['check_id'] and r2['check_id'] and r1['check_id'] == r2['check_id']:
 
            check_score = 1.0
 
        else:
 
            check_message = 'check-id mismatch'
 
            check_score = 0.0
 
    else:
 
        check_score = 0.0
 
        payee_score = payee_match(r1['payee'], r2['payee'])
 
        if payee_score > PAYEE_FULL_MATCH_THRESHOLD:
 
            payee_message = ''
 
        elif payee_score > PAYEE_PARTIAL_MATCH_THRESHOLD:
 
            payee_message = 'partial payee match'
 
        else:
 
            payee_message = 'payee mismatch'
 

	
 
    overall_score = (date_score + amount_score + check_score + payee_score) / 4
 
    overall_message = [
 
        m for m in [date_message, amount_message, check_message, payee_message] if m
 
    ]
 
    return overall_score, overall_message
 

	
 

	
 
def match_statement_and_books(
 
    statement_trans: List[Dict], books_trans: List[Dict]
 
) -> Tuple[List[Tuple[List, List, List]], List[Dict], List[Dict]]:
 
    """Match transactions between the statement and books.
 

	
 
    If matched, the books transaction is marked off so that it can
 
    only be matched once. Some transactions will be matched, some will
 
    be on the statement but not the books and some on the books but
 
    not the statement.
 

	
 
    Passes through any unmatched transactions.
 

	
 
    Currently we use the same matching logic for all types of
 
    statements. It's conceivable that you could have special cases to
 
    accurately match some types of statements, but that would be more
 
    work to maintain and test.
 

	
 
    """
 
    matches = []
 
    remaining_books_trans = []
 
    remaining_statement_trans = []
 

	
 
    for r1 in statement_trans:
 
        best_match_score = 0.0
 
        best_match_index = None
 
        best_match_note = []
 
        matches_found = 0
 
        for i, r2 in enumerate(books_trans):
 
            score, note = records_match(r1, r2)
 
            if score >= OVERALL_ACCEPTABLE_MATCH_THRESHOLD and score >= best_match_score:
 
                matches_found += 1
 
                best_match_score = score
 
                best_match_index = i
 
                best_match_note = note
 
        if (
 
            best_match_score > OVERALL_ACCEPTABLE_MATCH_THRESHOLD
 
            and matches_found == 1
 
            and 'check-id mismatch' not in best_match_note
 
            or best_match_score > OVERALL_EXCELLENT_MATCH_THRESHOLD
 
        ):
 
            matches.append(([r1], [books_trans[best_match_index]], best_match_note))
 
            # Don't try to make a second match against this books entry.
 
            if best_match_index is not None:
 
                del books_trans[best_match_index]
 
        else:
 
            remaining_statement_trans.append(r1)
 
    for r2 in books_trans:
 
        remaining_books_trans.append(r2)
 
    return matches, remaining_statement_trans, remaining_books_trans
 

	
 

	
 
def subset_match(
 
    statement_trans: List[dict], books_trans: List[dict]
 
) -> Tuple[List[Tuple[List, List, List]], List[Dict], List[Dict]]:
 
    """Match single statement transactions with multiple books transactions.
 

	
 
    Works similarly to match_statement_and_books in that it returns a
 
    list of matches and lists of remaining statement and books
 
    transactions.
 

	
 
    """
 
    matches = []
 
    remaining_books_trans = []
 
    remaining_statement_trans = []
 

	
 
    groups = itertools.groupby(books_trans, key=lambda x: (x['date'], x['payee']))
 
    for _, group in groups:
 
        best_match_score = 0.0
 
        best_match_index = None
 
        best_match_note = []
 
        matches_found = 0
 

	
 
        group_items = list(group)
 
        total = sum(x['amount'] for x in group_items)
 
        r2 = copy.copy(group_items[0])
 
        r2['amount'] = total
 
        for i, r1 in enumerate(statement_trans):
 
            score, note = records_match(r1, r2)
 
            if score >= OVERALL_ACCEPTABLE_MATCH_THRESHOLD and score >= best_match_score:
 
                matches_found += 1
 
                best_match_score = score
 
                best_match_index = i
 
                best_match_note = note
 
        if (
 
            best_match_score > OVERALL_ACCEPTABLE_MATCH_THRESHOLD
 
            and matches_found == 1
 
            and 'check-id mismatch' not in best_match_note
 
            or best_match_score > OVERALL_EXCELLENT_MATCH_THRESHOLD
 
        ):
 
            matches.append(
 
                ([statement_trans[best_match_index]], group_items, best_match_note)
 
            )
 
            if best_match_index is not None:
 
                del statement_trans[best_match_index]
 
        else:
 
            remaining_books_trans.extend(group_items)
 
    for r1 in statement_trans:
 
        remaining_statement_trans.append(r1)
 
    return matches, remaining_statement_trans, remaining_books_trans
 

	
 

	
 
# TODO: Return list of tuples (instead of list of lists).
 

	
 

	
 
def format_matches(
 
    matches: List, csv_statement: str, show_reconciled_matches: bool
 
) -> List[List]:
 

	
 
    """Produce a list of body output lines from the given matches.
 

	
 
    The first column is a date so we can re-sort the list to put the
 
    missing entries in the right place. The second column is the text
 
    output.
 

	
 
    """
 
    match_output = []
 
    for r1s, r2s, note in matches:
 
        note = ', '.join(note)
 
        note = ': ' + note if note else note
 
        if r1s and r2s:
 
            if show_reconciled_matches or not all(x['bank_statement'] for x in r2s):
 
                if len(r2s) == 1:
0 comments (0 inline, 0 general)