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,
0 comments (0 inline, 0 general)