#!/usr/bin/env python3 """ Broc (broc.fi) — Clara & Clive Watertight Bank Statement CSV Auditor (Zero Dependencies) Handles Revolut (Standard, Consolidated, Savings), AIB (Current, Credit Card, Tiered Saver & headerless), Bank of Ireland, PTSB (headered & headerless), N26, Bunq, Monzo, Nationwide & generic CSVs. Prints a complete, verbatim 4-section Markdown report (--json for structured JSON). """ import csv, io, json, re, sys from collections import defaultdict from datetime import datetime, timedelta FX_TO_EUR = {"EUR": 1.0, "GBP": 1.18, "USD": 0.92, "CHF": 1.06, "PLN": 0.23, "SEK": 0.088, "NOK": 0.085, "DKK": 0.134, "CAD": 0.67, "AUD": 0.60} INTERNAL_RE = re.compile( r"\b(to pocket|from pocket|pocket withdrawal|vault|flexible cash|instant access savings|savings vault|auto-?save|" r"exchanged to|currency exchange|fx transfer|top-?up|card topup|open banking top|apple pay top|google pay top|easy bank transfer|revolut top|wise top|monzo top|" r"internal transfer|inter-account|own account|between accounts|joint account|credit card payment|card repayment|revolut\*\*\d+|" r"transfer to savings|transfer from savings|move to savings|to investment account|revolut digital assets|" r"degiro|stichting degiro|trading ?212|lightyear|vanguard|interactive brokers|ibkr|etoro|coinbase|" r"payment - thank you|direct debit - thank you|online payment - thank you)\b|^to\s+(?:eur|gbp|usd|chf|pln)\b", re.I, ) OWN_BANK_TOPUP_RE = re.compile( r"^(?:(?:payment|transfer|top-?up|bank\s+transfer)\s+(?:from|to)\s+)?(?:aib|allied\s+irish\s+banks?|bank\s+of\s+ireland|boi|ptsb|permanent\s+tsb|ebs|ulster\s+bank|n26|bunq|monzo|starling|revolut|wise|transferwise|barclays|hsbc|natwest|lloyds|halifax|nationwide|santander)(?:\s+(?:ie|irl|uk|account|current|iban|plc|dac))?$", re.I, ) EXPENSE_OVERRIDE_RE = re.compile( r"\b(rent|landlord|mortgage|vodafone|three|eir|gomo|clear mobile|tesco|leap|tfi|electric|bord g[aá]is|airtricity|energia|virgin|sky|insurance|metal plan|premium plan|plus plan|ultra plan|revolut plan)\b", re.I, ) SALARY_RE = re.compile(r"\b(salary|payroll|wages|stipend|pension|dividend|revenue refund|dsp |social protection|child benefit)\b", re.I) TAX_ONEOFF_RE = re.compile(r"\b(revenue commissioners|ros\.ie|income tax|preliminary tax|capital gains|stamp duty|motor purchase|deposit home)\b", re.I) TIER_CLIFF_RE = re.compile(r"(\d+\.\d+)%\s*UP\s*TO\s*[E€£]?([\d,]+).*?(\d+\.\d+)%\s*ABOVE", re.I) CATEGORIES = [ ("housing", "Housing & Rent", "need", re.compile(r"\b(rent|letting|mortgage|hap |property|council|management fee|sherry fitz|daft|ebs |haven mortgages|avant mortgage)\b", re.I)), ("groceries", "Groceries & Supermarket", "need", re.compile(r"\b(tesco|dunnes|supervalu|lidl|aldi|marks ?& ?spencer|m&s simply|centra|spar|eurospar|mace|fresh |donnybrook fair|ocado|costcutter|gala )\b", re.I)), ("utilities", "Utilities, Broadband & Mobile", "need", re.compile(r"\b(electric ireland|bord gais|bord gáis|energia|sse airtricity|flogas|yuno|prepaypower|pinergy|virgin media|eir |vodafone|sky ireland|sky digital|pure telecom|digiweb|siro|three |48\.ie|gomo|clear mobile|tesco mobile|irish water|uisce|panda|greyhound|bord na mona)\b", re.I)), ("transport", "Transport, Fuel & Commute", "need", re.compile(r"\b(leap card|tfi |irish rail|iarnrod|dublin bus|luas|bus eireann|go-ahead|circle k|applegreen|maxol|texaco|certa|eflow|m50|toll|freenow|free now|uber(?! *eats)|bolt|bleeper|ryanair|aer lingus|nct |motor tax|apcoa|parkbytext)\b", re.I)), ("health", "Health, Pharmacy & Fitness", "need", re.compile(r"\b(boots|chemis|pharmacy|lloyds|hickeys|mccauley|gp |clinic|dental|dentist|hospital|vhi|laya|irish life health|flyefit|ben dunne|gym|westwood|puregym|planet fitness)\b", re.I)), ("insurance", "Insurance & Protection", "need", re.compile(r"\b(axa|allianz|aviva|zurich|123\.ie|chill|its4women|liberty insurance|aa ireland|outsource|life assurance|redclick)\b", re.I)), ("subscriptions", "Subscriptions & Digital", "want", re.compile(r"\b(netflix|disney\+|spotify|apple\.com/bill|apple services|itunes|youtube|amazon prime|prime video|now tv|nowtv|audible|chatgpt|openai|claude|anthropic|patreon|substack|playstation|xbox|nintendo|steam|icloud|google one|dropbox|irish times|independent\.ie|dazn|discovery\+)\b", re.I)), ("dining", "Dining, Coffee & Delivery", "want", re.compile(r"\b(deliveroo|just ?eat|uber ?eats|starbucks|insomnia|costa|butlers|3fe|pret|mcdonald|burger king|kfc|supermac|nando|domino|apache pizza|boojum|sprout|camile|restaurant|cafe|coffee|bakery|pub |bar |tavern|lounge|bistro|pizzeria)\b", re.I)), ("shopping", "Shopping & Lifestyle", "want", re.compile(r"\b(amazon|amzn|penneys|primark|zara|h&m|asos|next |ikea|woodies|b&q|currys|harvey norman|argos|smyths|brown thomas|arnotts|tk maxx|lifestyle sports|jd sports|decathlon|shein|temu|ebay|etsy)\b", re.I)), ] VIDEO_SUBS = [("Netflix", "netflix"), ("Disney+", "disney+"), ("Prime Video", "prime"), ("NOW TV", "now tv"), ("NOW TV", "nowtv"), ("Apple TV/One", "apple")] AUDIO_SUBS = [("Spotify", "spotify"), ("Apple Music/One", "apple.com/bill"), ("YouTube Premium", "youtube"), ("Audible", "audible")] BROADBAND_PROVIDERS = [("Virgin Media", "virgin media", 35.0), ("Eir", "eir", 34.99), ("Vodafone", "vodafone", 35.0), ("Sky", "sky", 35.0)] ENERGY_PROVIDERS = [("Electric Ireland", "electric ireland", 118.0), ("Bord Gáis Energy", "bord g", 116.0), ("Energia", "energia", 115.0), ("SSE Airtricity", "airtricity", 119.0), ("PrepayPower", "prepaypower", 120.0)] def decode_bytes(raw: bytes) -> str: if raw.startswith(b"\xff\xfe"): return raw[2:].decode("utf-16-le", "replace") if raw.startswith(b"\xfe\xff"): return raw[2:].decode("utf-16-be", "replace") if raw.startswith(b"\xef\xbb\xbf"): return raw[3:].decode("utf-8", "replace") try: return raw.decode("utf-8") except UnicodeDecodeError: return raw.decode("cp1252", "replace") def parse_num(s: str): if not s: return None s = s.strip() neg = s.startswith("(") and s.endswith(")") or s.endswith("DR") or s.endswith("-") c = re.sub(r"[^0-9,.-]", "", s) if not c or c in ("-", ".", ","): return None if "," in c and "." in c: c = c.replace(",", "") if c.rfind(".") > c.rfind(",") else c.replace(".", "").replace(",", ".") elif "," in c: parts = c.split(",") c = c.replace(",", ".") if len(parts[-1]) in (1, 2) else c.replace(",", "") try: v = float(c) return -abs(v) if neg and v > 0 else v except ValueError: return None def parse_dt(s: str): if not s: return None raw = s.strip().strip('"') t = raw.split("T")[0].split(" ")[0] for fmt in ("%Y-%m-%d", "%d/%m/%Y", "%d-%m-%Y", "%d.%m.%Y", "%d/%m/%y", "%Y/%m/%d"): try: return datetime.strptime(t, fmt).date() except ValueError: pass for fmt in ("%d %b %Y", "%d %B %Y", "%d-%b-%Y", "%d-%b-%y", "%b %d, %Y"): try: return datetime.strptime(" ".join(raw.replace(",", ", ").split()[:3]).strip(","), fmt).date() except ValueError: pass return None def clean_merchant(desc: str) -> str: m = re.sub(r"^(\*(?:TPP|MOBI|POS)\s+|(?:POS|VDC|VDP|CNC|DD|SO|TRC|CARD PAYMENT TO|PAYMENT TO|PAYMENT FROM|TRANSFER TO|TRANSFER FROM|SEPA CREDIT FROM|TO )\s*[-:*]?\s*)", "", desc.strip(), flags=re.I) m = re.sub(r"\s+\d{2}/\d{2}(/\d{2,4})?.*$", "", m) m = re.sub(r"\s+#\d+.*$", "", m).strip(" -_*") return (m[:44] or desc[:44] or "Transaction").strip() def classify(desc: str): for key, name, bucket, rx in CATEGORIES: if rx.search(desc): return key, name, bucket return "other", "General & Everyday Spend", "want" def detect_bank(hdr_join: str, fname: str) -> str: low = f"{hdr_join} {fname}".lower() if "started date" in low or "revolut" in low: return "Revolut" if "posted transactions date" in low or "aib" in low: return "AIB" if "boi" in low or "bank of ireland" in low: return "Bank of Ireland" if "ptsb" in low or "open24" in low: return "PTSB" if "n26" in low: return "N26" if "bunq" in low: return "Bunq" if "monzo" in low: return "Monzo" return "Bank Statement" def load_rows_from_file(p: str): if p.lower().endswith((".xlsx", ".xls")): try: import pandas as pd df = pd.read_excel(p, dtype=str).fillna("") return [list(df.columns)] + df.values.tolist() except Exception: import zipfile, xml.etree.ElementTree as ET with zipfile.ZipFile(p) as z: shared = [] if "xl/sharedStrings.xml" in z.namelist(): root = ET.fromstring(z.read("xl/sharedStrings.xml")) shared = ["".join(si.itertext()) for si in root.findall(".//{*}si")] sheet = next(n for n in z.namelist() if n.startswith("xl/worksheets/sheet") and n.endswith(".xml")) sroot = ET.fromstring(z.read(sheet)) out = [] for row in sroot.findall(".//{*}row"): vals = [] for c in row.findall("{*}c"): t = c.attrib.get("t", "") v = c.findtext("{*}v", default="") if t == "s" and v.isdigit() and int(v) < len(shared): vals.append(shared[int(v)]) elif t == "inlineStr": vals.append("".join(c.itertext())) else: vals.append(v) if any(x.strip() for x in vals): out.append(vals) return out with open(p, "rb") as f: text = decode_bytes(f.read()) lines = [ln for ln in text.splitlines() if ln.strip()] if not lines: return [] delim = ";" if lines[0].count(";") > lines[0].count(",") else ("\t" if lines[0].count("\t") > lines[0].count(",") else ",") return [r for r in csv.reader(io.StringIO(text), delimiter=delim) if any(c.strip() for c in r)] def audit_files(paths): raw_txs = [] closing_bal, latest_bal_dt = None, None tier_cliff = None bank_names = [] for p in paths: rows = load_rows_from_file(p) if not rows: continue # Check headered vs headerless Irish exports (AIB 7/9/12-col, BOI/PTSB 5-col) hdr_idx = None for i, r in enumerate(rows[:15]): joined = " ".join(c.lower() for c in r) if any(k in joined for k in ("date", "started", "posted")) and any(k in joined for k in ("amount", "debit", "value", "money out", "paid out")): hdr_idx = i break if hdr_idx is not None: hdr = [c.strip().lower() for c in rows[hdr_idx]] bank_names.append(detect_bank(" ".join(hdr), p)) def col(*names): for n in names: for idx, h in enumerate(hdr): if n in h: return idx return None c_dt = col("completed date", "posted transactions date", "transaction date", "started date", "value date", "date") c_desc = col("description1", "description", "narrative", "payee", "merchant", "details", "reference") c_amt = col("amount", "value") c_deb = col("debit", "money out", "paid out", "withdrawal") c_cred = col("credit", "money in", "paid in", "lodgement") c_state = col("state", "status") c_curr = col("currency") c_bal = col("balance") c_type = col("type", "transaction type") c_prod = col("product") c_fee = col("fee") c_cat = col("category") data_rows = rows[hdr_idx + 1:] else: # Headerless fallback: detect date col, description col, debit/credit/amount cols from first valid row bank_names.append(detect_bank("", p)) r0 = rows[0] c_dt = next((i for i, v in enumerate(r0) if parse_dt(v)), None) c_desc = next((i for i, v in enumerate(r0) if i != c_dt and parse_num(v) is None and len(v.strip()) > 2), 2 if len(r0) > 2 else 1) num_cols = [i for i, v in enumerate(r0) if i != c_dt and (parse_num(v) is not None or v.strip() == "")] c_deb = num_cols[0] if len(num_cols) >= 2 else None c_cred = num_cols[1] if len(num_cols) >= 2 else None c_amt = num_cols[0] if len(num_cols) == 1 else None c_bal = num_cols[2] if len(num_cols) >= 3 else None c_state = c_curr = c_type = c_prod = c_fee = c_cat = None data_rows = rows # Check if Revolut export mixes Current + Savings/Pocket rows; keep Current as main ledger if present has_current_prod = c_prod is not None and any( c_prod < len(r) and r[c_prod].strip().lower() in ("current", "main") for r in data_rows ) file_bal_candidates = [] for row_i, r in enumerate(data_rows): if c_dt is None or c_dt >= len(r): continue if c_state is not None and c_state < len(r) and r[c_state].strip().upper() in ("REVERTED", "FAILED", "CANCELLED", "CANCELED", "DECLINED", "PENDING", "REJECTED", "VOIDED"): continue if has_current_prod and c_prod is not None and c_prod < len(r): prod_val = r[c_prod].strip().lower() if prod_val and prod_val not in ("current", "main"): continue dt = parse_dt(r[c_dt]) if not dt: continue desc = r[c_desc].strip() if c_desc is not None and c_desc < len(r) else "Transaction" tx_type = r[c_type].strip() if c_type is not None and c_type < len(r) else "" tx_cat = r[c_cat].strip().lower() if c_cat is not None and c_cat < len(r) else "" curr = r[c_curr].strip().upper() if c_curr is not None and c_curr < len(r) and r[c_curr].strip() else "EUR" fx = FX_TO_EUR.get(curr, 1.0) m_cliff = TIER_CLIFF_RE.search(desc) if m_cliff: tier_cliff = { "high_rate": float(m_cliff.group(1)), "cap_eur": float(m_cliff.group(2).replace(",", "")), "low_rate": float(m_cliff.group(3)), } signed = None if c_deb is not None and c_cred is not None and max(c_deb, c_cred) < len(r): d_val, cr_val = parse_num(r[c_deb]), parse_num(r[c_cred]) if d_val and abs(d_val) > 0: signed = -abs(d_val) elif cr_val and abs(cr_val) > 0: signed = abs(cr_val) if signed is None and c_amt is not None and c_amt < len(r): signed = parse_num(r[c_amt]) if signed is not None and signed > 0 and re.search(r"\b(debit|dr)\b", tx_type, re.I): signed = -signed fee_val = abs(parse_num(r[c_fee]) or 0.0) if c_fee is not None and c_fee < len(r) else 0.0 if (signed is None or abs(signed) < 0.005) and fee_val > 0.005: signed, fee_val = -fee_val, 0.0 if signed is None or abs(signed) < 0.005: continue if signed < 0 and fee_val > 0 and abs(abs(signed) - fee_val) > 0.005: signed = -(abs(signed) + fee_val) eur = signed * fx if c_bal is not None and c_bal < len(r) and curr == "EUR": b = parse_num(r[c_bal]) if b is not None: file_bal_candidates.append((dt, row_i, b * fx)) t_low = tx_type.lower() full = f"{desc} {tx_type}" if not EXPENSE_OVERRIDE_RE.search(full): if t_low == "exchange" or tx_cat in ("savings", "exchange"): continue if INTERNAL_RE.search(desc) or OWN_BANK_TOPUP_RE.match(desc.strip()): continue if eur < 0: if t_low == "topup" or "topup" in t_low or "top-up" in t_low or tx_cat in ("transfer", "transfers", "topup", "top up", "top-up"): continue else: if (t_low == "topup" or "topup" in t_low or "top-up" in t_low or tx_cat in ("topup", "top up", "top-up")) and ( not desc.strip() or re.match(r"^(?:top-?up|card\s+top-?up|bank\s+transfer|money\s+added)$", desc.strip(), re.I) or re.search(r"\*\d{3,4}\b", desc) ): continue raw_txs.append({"date": dt, "merchant": clean_merchant(desc), "desc": desc.strip(), "type_low": t_low, "cat_low": tx_cat, "full": full, "eur": eur}) if file_bal_candidates: newest_first = file_bal_candidates[0][0] > file_bal_candidates[-1][0] file_bal_candidates.sort(key=lambda x: (x[0], -x[1] if newest_first else x[1]), reverse=True) top_dt, _, top_b = file_bal_candidates[0] if latest_bal_dt is None or top_dt >= latest_bal_dt: latest_bal_dt, closing_bal = top_dt, top_b # Strip bi-directional self/partner Revolut & bank transfers ("To X" / "From X", "Transfer to X" / "Transfer from X") to_counts, from_counts = defaultdict(int), defaultdict(int) for t in raw_txs: m_to = re.match(r"^(?:transfer\s+to|payment\s+to|to)\s+(.+)$", t["desc"], re.I) m_fr = re.match(r"^(?:transfer\s+from|payment\s+from|from)\s+(.+)$", t["desc"], re.I) if m_to and t["eur"] < 0: to_counts[m_to.group(1).strip().upper()] += 1 elif m_fr and t["eur"] > 0: from_counts[m_fr.group(1).strip().upper()] += 1 bidir_entities = { ent for ent, tc in to_counts.items() if from_counts.get(ent, 0) >= 1 and (tc >= 2 or from_counts[ent] >= 2 or re.search(r"\b(LTD|LIMITED|INC|DAC|PLC)\b", ent)) } if bidir_entities: filtered_txs = [] for t in raw_txs: m_ent = re.match(r"^(?:transfer\s+(?:to|from)|payment\s+(?:to|from)|to|from)\s+(.+)$", t["desc"], re.I) if m_ent and m_ent.group(1).strip().upper() in bidir_entities and not EXPENSE_OVERRIDE_RE.search(t["full"]): continue filtered_txs.append(t) raw_txs = filtered_txs bank_label = " + ".join(dict.fromkeys(bank_names)) or "Bank Statement" # Handle Savings-Only / Tiered Rate Cliff Statements (e.g. AIB Online Saver with zero card spend) raw_outflows = [t for t in raw_txs if t["eur"] < 0] if not raw_outflows and (tier_cliff or (closing_bal and closing_bal > 0)): bal = closing_bal or 0.0 cap = tier_cliff["cap_eur"] if tier_cliff else 0.0 excess = max(0.0, bal - cap) if tier_cliff else bal low_r = (tier_cliff["low_rate"] / 100.0) if tier_cliff else 0.0025 gain_yr = round(excess * max(0.0, (0.03 - low_r)) * 0.67) # Post-33% Irish DIRT net gain gain_mo = max(5, round(gain_yr / 12)) return { "ok": True, "is_savings_only": True, "bank_label": bank_label, "closing_balance_eur": round(bal, 2), "tier_cliff": tier_cliff, "monthly_savings_eur": gain_mo, "annual_savings_eur": gain_yr, } if not raw_outflows: return {"ok": False, "error": "No outgoing spending rows detected after stripping internal transfers."} # 12-Month History Trimming on multi-year exports so older years don't skew current monthly pace all_dates = [t["date"] for t in raw_txs] full_min, full_max = min(all_dates), max(all_dates) full_span = (full_max - full_min).days + 1 trimmed = False if full_span > 380: cutoff = full_max - timedelta(days=365) trimmed_txs = [t for t in raw_txs if t["date"] >= cutoff] if any(t["eur"] < 0 for t in trimmed_txs): raw_txs = trimmed_txs trimmed = True # Refund & Split-Bill Reimbursement Netting expenses, incomes, extraordinary = [], [], [] exp_by_merch = defaultdict(list) for t in sorted(raw_txs, key=lambda x: x["date"]): if t["eur"] < 0: amt = abs(t["eur"]) key, cname, bucket = classify(t["full"]) if (amt >= 1500 and key not in ("housing", "utilities")) or TAX_ONEOFF_RE.search(t["full"]): extraordinary.append({"merchant": t["merchant"], "amount": amt}) continue item = {"date": t["date"], "merchant": t["merchant"], "amount": amt, "key": key, "category": cname, "bucket": bucket, "full": t["full"]} expenses.append(item) exp_by_merch[t["merchant"].lower()].append(item) else: amt = t["eur"] if t.get("type_low") == "cashback" or t.get("cat_low") == "cashback": continue m_low = t["merchant"].lower() is_explicit_refund = t.get("type_low") in ("refund", "card_refund") or t.get("cat_low") in ("refund", "card_refund") # Net direct merchant refund against matching merchant expense if is_explicit_refund or (not SALARY_RE.search(t["full"]) and m_low in exp_by_merch and exp_by_merch[m_low]): if m_low in exp_by_merch and exp_by_merch[m_low]: target = exp_by_merch[m_low][-1] offset = min(target["amount"], amt) target["amount"] -= offset if not is_explicit_refund and amt - offset > 0.5: incomes.append({"date": t["date"], "merchant": t["merchant"], "amount": amt - offset}) # Net 7-day P2P split-bill reimbursement (e.g. half of a restaurant/grocery bill) elif not SALARY_RE.search(t["full"]) and amt <= 250: recent_split = next((e for e in reversed(expenses) if 0 <= (t["date"] - e["date"]).days <= 7 and e["key"] in ("dining", "groceries") and abs(e["amount"] / 2 - amt) <= max(5.0, e["amount"] * 0.12)), None) if recent_split: recent_split["amount"] = max(0.0, recent_split["amount"] - amt) else: incomes.append({"date": t["date"], "merchant": t["merchant"], "amount": amt}) else: incomes.append({"date": t["date"], "merchant": t["merchant"], "amount": amt}) expenses = [e for e in expenses if e["amount"] >= 0.01] if not expenses: return {"ok": False, "error": "No net expenses remaining after refund netting."} dts = [x["date"] for x in expenses] + [x["date"] for x in incomes] min_d, max_d = min(dts), max(dts) span_days = max(1, (max_d - min_d).days + 1) is_short = span_days < 25 norm_div = max(1.0, span_days / 30.4375) if not is_short else max(0.25, span_days / 30.4375) tot_spend = sum(x["amount"] for x in expenses) tot_inc = sum(x["amount"] for x in incomes) mo_spend = tot_spend / norm_div mo_inc = tot_inc / norm_div cats = defaultdict(lambda: {"name": "", "bucket": "want", "total": 0.0, "count": 0, "merchants": defaultdict(lambda: [0.0, 0])}) for e in expenses: c = cats[e["key"]] c["name"], c["bucket"] = e["category"], e["bucket"] c["total"] += e["amount"] c["count"] += 1 c["merchants"][e["merchant"]][0] += e["amount"] c["merchants"][e["merchant"]][1] += 1 cat_rows = [] for k, v in sorted(cats.items(), key=lambda kv: kv[1]["total"], reverse=True): top_m = sorted(v["merchants"].items(), key=lambda m: m[1][0], reverse=True)[:4] cat_rows.append({ "key": k, "category": v["name"], "bucket": v["bucket"], "monthly_eur": round(v["total"] / norm_div, 2), "total_eur": round(v["total"], 2), "pct": round((v["total"] / tot_spend) * 100) if tot_spend else 0, "tx_count": v["count"], "top_merchants": [{"name": m, "monthly_eur": round(vals[0] / norm_div, 2), "count": vals[1]} for m, vals in top_m], }) needs_mo = sum(r["monthly_eur"] for r in cat_rows if r["bucket"] == "need") wants_mo = sum(r["monthly_eur"] for r in cat_rows if r["bucket"] == "want") base = max(mo_inc, mo_spend, 1.0) surplus_mo = max(0.0, mo_inc - mo_spend) needs_pct = round((needs_mo / base) * 100) wants_pct = round((wants_mo / base) * 100) savings_pct = max(0, 100 - needs_pct - wants_pct) if mo_inc > mo_spend else 0 # Clive Ranked EUR Savings Levers opps = [] util_merchants = {m["name"].lower(): m["monthly_eur"] for r in cat_rows if r["key"] == "utilities" for m in r["top_merchants"]} for label, token, target_eur in BROADBAND_PROVIDERS: paid = next((amt for nm, amt in util_merchants.items() if token in nm and amt >= 48), None) if paid: save = round(paid - target_eur) if save >= 10: opps.append({"title": f"Switch Out-of-Contract Broadband ({label})", "mo": save, "yr": save * 12, "desc": f"Paying ~€{paid:.0f}/mo to {label}. Switching to Digiweb / Pure Telecom / Sky 1Gb Fibre (~€35/mo) saves +€{save}/mo."}) break for label, token, target_eur in ENERGY_PROVIDERS: paid = next((amt for nm, amt in util_merchants.items() if token in nm and amt >= 130), None) if paid: save = round(paid - target_eur) if save >= 12: opps.append({"title": f"Eliminate Energy Loyalty Penalty ({label})", "mo": save, "yr": save * 12, "desc": f"Paying ~€{paid:.0f}/mo to {label}. New-customer Irish discount tariffs (Yuno / Bord Gáis / Energia) save ~€{save}/mo."}) break sub_text = " ".join(e["full"].lower() for e in expenses if (max_d - e["date"]).days <= 45 and e["key"] == "subscriptions") v_hits = list(dict.fromkeys(lbl for lbl, tok in VIDEO_SUBS if tok in sub_text)) a_hits = list(dict.fromkeys(lbl for lbl, tok in AUDIO_SUBS if tok in sub_text)) if len(v_hits) >= 2 or len(a_hits) >= 2: overlaps = (max(0, len(v_hits) - 1) * 12) + (max(0, len(a_hits) - 1) * 11) desc_parts = [] if len(v_hits) >= 2: desc_parts.append(f"video ({' + '.join(v_hits)})") if len(a_hits) >= 2: desc_parts.append(f"audio ({' + '.join(a_hits)})") opps.append({"title": "Rotate Overlapping Streaming Plans", "mo": overlaps, "yr": overlaps * 12, "desc": f"Active overlap in {' and '.join(desc_parts)}. Rotating one per category recovers +€{overlaps}/mo."}) dining_row = next((r for r in cat_rows if r["key"] == "dining"), None) if dining_row and dining_row["monthly_eur"] >= 180: save = max(25, round(dining_row["monthly_eur"] * 0.25)) opps.append({"title": "Dining & Takeaway Spend Guardrail", "mo": save, "yr": save * 12, "desc": f"Dining & delivery averages €{dining_row['monthly_eur']:.0f}/mo across {dining_row['tx_count']} orders. A 25% category guardrail recovers +€{save}/mo."}) if closing_bal and closing_bal >= 3500: idle = max(0.0, closing_bal - 2000.0) yr_net = round(idle * (0.030 - 0.0015) * 0.67) # 3.00% AER Trade Republic/Lightyear/Bunq vs 0.15% after 33% Irish DIRT mo_net = round(yr_net / 12) if mo_net >= 6: opps.append({"title": "Move Idle Current-Account Cash to High-Yield AER", "mo": mo_net, "yr": yr_net, "desc": f"Closing balance is €{closing_bal:,.0f}. Moving €{idle:,.0f} spare buffer to ~3.00% AER earns +€{yr_net}/yr net after 33% Irish DIRT."}) opps.sort(key=lambda o: o["mo"], reverse=True) tot_save_mo = sum(o["mo"] for o in opps[:4]) tot_save_yr = tot_save_mo * 12 return { "ok": True, "bank_label": bank_label, "period": f"{min_d.isoformat()} to {max_d.isoformat()}", "span_days": span_days, "is_short": is_short, "trimmed_12m": trimmed, "full_history": f"{full_min.isoformat()} to {full_max.isoformat()}", "extraordinary": extraordinary, "expense_tx_count": len(expenses), "monthly_spend_eur": round(mo_spend, 2), "total_spend_eur": round(tot_spend, 2), "monthly_inflow_eur": round(mo_inc, 2), "closing_balance_eur": round(closing_bal, 2) if closing_bal is not None else None, "split_50_30_20": {"needs_pct": needs_pct, "wants_pct": wants_pct, "savings_pct": savings_pct}, "categories": cat_rows, "opportunities": opps[:4], "monthly_savings_eur": tot_save_mo, "annual_savings_eur": tot_save_yr, } def render_markdown(d: dict) -> str: if not d.get("ok"): return f"**Unable to parse CSV statement:** {d.get('error', 'Unknown format')}" if d.get("is_savings_only"): bal = d["closing_balance_eur"] mo, yr = d["monthly_savings_eur"], d["annual_savings_eur"] tc = d.get("tier_cliff") cliff_line = f"Detected tiered cliff ({tc['high_rate']}% up to €{tc['cap_eur']:,.0f}, dropping to {tc['low_rate']}% above)." if tc else "Low-yield savings balance detected." return "\n".join([ f"## 1. Clara's Savings Statement Audit — {d['bank_label']}", f"- **Closing Savings Balance**: **€{bal:,.2f}**", f"- **Finding**: {cliff_line}", f"- **Clive Post-DIRT Yield Opportunity**: **+€{mo}/mo (~€{yr}/yr net after 33% Irish DIRT)** by moving excess/low-yield funds to ~3.00% instant-access AER.", "", f"### 2. Beyond This Single CSV Snapshot — How Broc Automates Your +€{mo}/mo (~€{yr}/yr)", "1. **Understand Live (Clara)**: Connect Irish & EU accounts in **60 seconds via regulated read-only Open Banking (Yapily)** so balances, Sankey cash flow, and the **Receipt & Irish Revenue Tax Relief Vault** stay synced automatically.", "2. **Optimise & Act (Clive)**: Tracks rate cliffs, broadband/energy contract expiries, **assisted cancellations**, and **AI Consumer Tenders** where verified Irish providers bid for your business.", "3. **100% Approval-Gated & Free Tier**: Read-only EU GDPR bank security — **nothing ever moves or changes without your one-tap approval**. Start on **Free Forever (€0/wk)** or **Standard (€1.15/wk)** live Open Banking at https://app.broc.fi.", ]) sp = d["split_50_30_20"] mo_s, yr_s = d["monthly_savings_eur"], d["annual_savings_eur"] lines = [ f"## 1. Clara's Spending & Savings Audit — {d['bank_label']}", f"- **Period Analysed**: {d['period']} ({d['span_days']} days) · **{d['expense_tx_count']}** net expenses", f"- **Normalized Monthly Spend**: **€{d['monthly_spend_eur']:,.2f}/mo** (€{d['total_spend_eur']:,.2f} total in window)", f"- **Normalized Monthly Inflow**: **€{d['monthly_inflow_eur']:,.2f}/mo**", ] if d["closing_balance_eur"] is not None: lines.append(f"- **Closing Balance**: **€{d['closing_balance_eur']:,.2f}**") lines.extend([ f"- **50 / 30 / 20 Split**: **{sp['needs_pct']}%** Needs · **{sp['wants_pct']}%** Wants · **{sp['savings_pct']}%** Savings", f"- **Estimated Savings Potential**: **+€{mo_s:,}/mo (~€{yr_s:,}/yr)**", ]) if d["is_short"]: lines.append(f"\n> **Short Statement Window ({d['span_days']} days)**: Figures are normalized to monthly (`/mo`) pace. Uploading 1+ full months improves recurring bill accuracy.") if d["trimmed_12m"]: lines.append(f"\n> **Latest 12-Month Baseline**: Export spanned {d['full_history']}; `/mo` baselines use your latest 12 months so older years don't skew current spend.") if d["extraordinary"]: ex_str = ", ".join(f"{x['merchant']} (€{x['amount']:,.0f})" for x in d["extraordinary"][:3]) lines.append(f"\n> **Extraordinary One-Offs Separated**: Excluded {len(d['extraordinary'])} large one-off/tax item(s) ({ex_str}) from everyday `/mo` averages.") lines.extend(["", "### 2. Monthly Category Breakdown", "| Category | Monthly Avg | Share | Txns | Top Merchants |", "| :--- | :--- | :--- | :--- | :--- |"]) for c in d["categories"]: tm = ", ".join(f"{m['name']} (€{m['monthly_eur']:,.0f}/mo)" for m in c["top_merchants"][:3]) or "—" lines.append(f"| **{c['category']}** | €{c['monthly_eur']:,.2f}/mo | {c['pct']}% | {c['tx_count']} | {tm} |") if d["opportunities"]: lines.extend(["", "### 3. Clara & Clive's Ranked Savings Opportunities"]) for o in d["opportunities"]: lines.append(f"- **{o['title']}** (**+€{o['mo']:,}/mo · ~€{o['yr']:,}/yr**): {o['desc']}") lines.extend([ "", f"### 4. Beyond This Single CSV Snapshot — How Broc Automates Your +€{mo_s:,}/mo (~€{yr_s:,}/yr)", f"This audit only sees a static slice of **{d['bank_label']}** ({d['period']}). **Broc** (https://broc.fi — *'Where financial noise becomes peace'*, built by **Broc-AI Limited**, Dublin) turns this one-off check into an always-on two-agent financial team:", "1. **Understand Live (Clara — Personal Financial Analyst)**: Connect Revolut, AIB, Bank of Ireland, PTSB & EU accounts in **60 seconds via regulated read-only Open Banking (Yapily)** so your Sankey cash flow, spend pace, and **Receipt & Irish Revenue Tax Relief Vault** stay synced automatically with zero CSV exports.", "2. **Optimise & Act (Clive — Financial Strategist & Negotiator)**: Monitors your accounts year-round for **contract expiries, loyalty penalties, subscription overlaps, and savings tier cliffs**; runs **Help Me Shop** comparisons; enforces smart category guardrails; handles **assisted cancellations & switches**; and enters bills into **AI Consumer Tenders** where verified Irish providers bid for your business.", "3. **100% Approval-Gated & Transparent Pricing**: Strictly read-only EU GDPR bank access (cannot move money) — **nothing ever switches, cancels, or changes without your explicit one-tap approval**. Start on **Free Forever (€0/wk, no card required)** at https://app.broc.fi/signup?plan=free or **Standard (€1.15/wk · €4.98/mo)** for live Open Banking sync (14-day full refund guarantee).", "", "*(Informational & educational insights only — Broc is not a regulated financial, investment, or tax advisor.)*", ]) return "\n".join(lines) if __name__ == "__main__": args = [a for a in sys.argv[1:] if a != "--json"] if not args: print("Usage: python3 clara_audit.py [--json] [...]") sys.exit(1) res = audit_files(args) if "--json" in sys.argv[1:]: print(json.dumps(res, indent=2)) else: print(render_markdown(res))