subscription-audit / detector.py
Exitvelocitybtc's picture
Deploy via deploy.sh β€” 2026-05-20T21:56:14Z
1fc95c1 verified
Raw History Blame Contribute Delete
15.5 kB
"""
Subscription detection engine.
Analyzes bank statement CSV transactions and identifies recurring subscription charges
using both heuristic rules (known merchants, cadence patterns) and pattern matching.
Privacy-first: all detection runs locally on HF compute. No data persisted.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import date, datetime, timedelta
from decimal import Decimal
from typing import List, Dict, Optional
import re
import io
import csv
from collections import defaultdict
# ─── Known subscription merchant fingerprints ────────────────────────
# Maps lowercase substring β†’ (canonical_name, category)
KNOWN_MERCHANTS = {
# Streaming
"netflix": ("Netflix", "streaming"),
"hulu": ("Hulu", "streaming"),
"disney+": ("Disney+", "streaming"),
"disneyplus": ("Disney+", "streaming"),
"hbo max": ("HBO Max", "streaming"),
"max.com": ("Max", "streaming"),
"paramount": ("Paramount+", "streaming"),
"peacock": ("Peacock", "streaming"),
"apple tv": ("Apple TV+", "streaming"),
"spotify": ("Spotify", "music"),
"apple music": ("Apple Music", "music"),
"youtube premium": ("YouTube Premium", "music/streaming"),
"youtube music": ("YouTube Music", "music"),
"tidal": ("Tidal", "music"),
"amazon prime": ("Amazon Prime", "shopping/streaming"),
"audible": ("Audible", "audiobooks"),
"kindle unlimited": ("Kindle Unlimited", "books"),
# Software / SaaS
"adobe": ("Adobe Creative Cloud", "software"),
"microsoft 365": ("Microsoft 365", "software"),
"office 365": ("Microsoft 365", "software"),
"google one": ("Google One", "cloud"),
"icloud": ("iCloud+", "cloud"),
"dropbox": ("Dropbox", "cloud"),
"notion": ("Notion", "productivity"),
"figma": ("Figma", "software"),
"github": ("GitHub", "software"),
"openai": ("ChatGPT Plus", "ai"),
"chatgpt": ("ChatGPT Plus", "ai"),
"anthropic": ("Claude Pro", "ai"),
"claude.ai": ("Claude Pro", "ai"),
"midjourney": ("Midjourney", "ai"),
"perplexity": ("Perplexity Pro", "ai"),
# Fitness
"peloton": ("Peloton", "fitness"),
"apple fitness": ("Apple Fitness+", "fitness"),
"classpass": ("ClassPass", "fitness"),
"myfitnesspal": ("MyFitnessPal Premium", "fitness"),
"strava": ("Strava Premium", "fitness"),
# Mental health / wellness
"headspace": ("Headspace", "wellness"),
"calm.com": ("Calm", "wellness"),
"betterhelp": ("BetterHelp", "wellness"),
"talkspace": ("Talkspace", "wellness"),
# Food / delivery
"doordash dashpass": ("DoorDash DashPass", "food"),
"uber one": ("Uber One", "transport/food"),
"instacart+": ("Instacart+", "food"),
"hellofresh": ("HelloFresh", "food"),
"blue apron": ("Blue Apron", "food"),
# News / media
"nyt": ("NYTimes", "news"),
"new york times": ("NYTimes", "news"),
"wsj": ("WSJ", "news"),
"wall street journal": ("WSJ", "news"),
"washington post": ("Washington Post", "news"),
"wapo": ("Washington Post", "news"),
"patreon": ("Patreon (creator)", "creator"),
"substack": ("Substack (publisher)", "creator"),
"medium": ("Medium", "news"),
# Dating
"tinder": ("Tinder Plus", "dating"),
"bumble": ("Bumble Premium", "dating"),
"match.com": ("Match", "dating"),
"hinge": ("Hinge Premium", "dating"),
# Productivity / learning
"masterclass": ("MasterClass", "learning"),
"skillshare": ("Skillshare", "learning"),
"coursera plus": ("Coursera Plus", "learning"),
"duolingo plus": ("Duolingo Plus", "learning"),
"babbel": ("Babbel", "learning"),
"linkedin premium": ("LinkedIn Premium", "career"),
# Subscription boxes
"barkbox": ("BarkBox", "boxes"),
"stitch fix": ("Stitch Fix", "boxes"),
"ipsy": ("Ipsy", "boxes"),
# Other
"1password": ("1Password", "security"),
"lastpass": ("LastPass", "security"),
"nordvpn": ("NordVPN", "security"),
"expressvpn": ("ExpressVPN", "security"),
}
@dataclass
class RawTransaction:
"""A single line item from the user's bank statement."""
date: date
description: str
amount: Decimal # positive for charges (debits)
category: str = ""
@dataclass
class DetectedSubscription:
canonical_name: str
category: str
matched_merchant_text: str
monthly_amount: Decimal
annual_amount: Decimal
cadence: str # "monthly", "annual", "quarterly", "weekly", "irregular"
occurrences: int
confidence: float # 0.0 to 1.0
first_seen: date
last_seen: date
flag_unused: bool = False
flag_duplicate_category: bool = False
transactions: List[RawTransaction] = field(default_factory=list)
@dataclass
class AuditResult:
total_subscriptions: int
total_monthly_spend: Decimal
total_annual_spend: Decimal
detected: List[DetectedSubscription]
categories_breakdown: Dict[str, Decimal]
flagged_duplicates: List[str]
flagged_unused: List[str]
insights: List[str]
# ─── CSV parsing ─────────────────────────────────────────────────────
def parse_bank_csv(csv_text: str) -> List[RawTransaction]:
"""
Flexible bank statement CSV parser. Handles common US bank exports:
Chase, BofA, Wells Fargo, Capital One, Citi, Amex, plus generic formats.
"""
reader = csv.DictReader(io.StringIO(csv_text))
txs: List[RawTransaction] = []
for row in reader:
r = {k.lower().strip(): (v or "").strip() for k, v in row.items() if k}
# date
date_str = (
r.get("date") or r.get("transaction date") or r.get("posting date")
or r.get("post date") or r.get("trans date") or ""
)
if not date_str:
continue
parsed_date = None
for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%Y-%m-%dT%H:%M:%S",
"%d/%m/%Y", "%Y/%m/%d"):
try:
parsed_date = datetime.strptime(date_str, fmt).date()
break
except ValueError:
continue
if not parsed_date:
continue
# description
description = (
r.get("description") or r.get("merchant") or r.get("memo")
or r.get("name") or r.get("payee") or r.get("details") or ""
)
if not description:
continue
# amount β€” handle multiple conventions
amount = None
amount_str = r.get("amount") or r.get("debit") or r.get("charges") or ""
if amount_str:
try:
amt = Decimal(amount_str.replace(",", "").replace("$", "").strip())
# Many bank CSVs use negative for debits; we want positive for charges
amount = abs(amt) if amt < 0 else amt
# If positive credits column exists, treat amount as charge
credits_str = r.get("credit") or r.get("credits") or ""
if credits_str and Decimal(credits_str.replace(",", "").replace("$", "") or "0") > 0:
continue # this is a credit, not a charge
except Exception:
continue
if amount is None or amount <= 0:
continue
category = r.get("category") or r.get("type") or ""
txs.append(RawTransaction(
date=parsed_date,
description=description,
amount=amount,
category=category,
))
return txs
# ─── Detection logic ─────────────────────────────────────────────────
def _normalize_merchant(description: str) -> str:
"""Strip noise from description for merchant matching."""
s = description.lower()
# Remove date stamps, transaction IDs, location codes
s = re.sub(r"\d{2}/\d{2}", "", s)
s = re.sub(r"\b\d{4,}\b", "", s)
s = re.sub(r"#\w+", "", s)
s = re.sub(r"\bpos\b|\bach\b|\bdr\b|\bcr\b|\bwww\.|\.com|\.net", "", s)
s = re.sub(r"\s+", " ", s).strip()
return s
def _match_known_merchant(description: str) -> Optional[tuple]:
"""Return (canonical_name, category) if description matches a known merchant."""
norm = _normalize_merchant(description)
for keyword, (name, cat) in KNOWN_MERCHANTS.items():
if keyword in norm:
return name, cat
return None
def _detect_cadence(dates: List[date]) -> tuple[str, float]:
"""Given dates of recurring charges, return (cadence_label, confidence)."""
if len(dates) < 2:
return "irregular", 0.3
sorted_dates = sorted(dates)
intervals = [(sorted_dates[i+1] - sorted_dates[i]).days for i in range(len(sorted_dates) - 1)]
avg = sum(intervals) / len(intervals)
# variance check β€” low variance = high confidence
variance = sum((i - avg) ** 2 for i in intervals) / len(intervals)
std_dev = variance ** 0.5
if 25 <= avg <= 35:
cadence = "monthly"
elif 80 <= avg <= 100:
cadence = "quarterly"
elif 350 <= avg <= 380:
cadence = "annual"
elif 6 <= avg <= 9:
cadence = "weekly"
elif 13 <= avg <= 17:
cadence = "biweekly"
else:
cadence = "irregular"
# Confidence: how regular is the cadence
if std_dev < 3:
confidence = 0.95
elif std_dev < 7:
confidence = 0.85
elif std_dev < 15:
confidence = 0.65
else:
confidence = 0.40
return cadence, confidence
def _normalize_to_monthly(amount: Decimal, cadence: str) -> Decimal:
"""Convert any cadence to monthly equivalent."""
if cadence == "monthly":
return amount
if cadence == "annual":
return (amount / 12).quantize(Decimal("0.01"))
if cadence == "quarterly":
return (amount / 3).quantize(Decimal("0.01"))
if cadence == "weekly":
return (amount * Decimal("4.33")).quantize(Decimal("0.01"))
if cadence == "biweekly":
return (amount * Decimal("2.17")).quantize(Decimal("0.01"))
return amount
def detect_subscriptions(transactions: List[RawTransaction]) -> AuditResult:
"""
Run full subscription detection on a list of bank transactions.
Returns AuditResult with all detected subscriptions, totals, and insights.
"""
# Step 1: Group transactions by likely merchant
by_merchant: Dict[str, List[RawTransaction]] = defaultdict(list)
for tx in transactions:
known = _match_known_merchant(tx.description)
if known:
merchant_key = known[0]
else:
# Group by normalized description (rough)
merchant_key = _normalize_merchant(tx.description)[:30]
by_merchant[merchant_key].append(tx)
# Step 2: For each merchant group with 2+ charges, evaluate as subscription candidate
detected: List[DetectedSubscription] = []
for merchant, txs in by_merchant.items():
if len(txs) < 2:
continue
amounts = [tx.amount for tx in txs]
# Check amount consistency (allow Β±5% variance for annual price increases)
avg_amount = sum(amounts, Decimal("0")) / len(amounts)
max_dev = max(abs(a - avg_amount) for a in amounts)
if avg_amount > 0 and max_dev / avg_amount > Decimal("0.20"):
# Too much variance β€” probably not a subscription (allow up to 20% for annual price increases)
continue
dates = [tx.date for tx in txs]
cadence, confidence = _detect_cadence(dates)
# Boost confidence if known merchant
known = _match_known_merchant(txs[0].description)
if known:
confidence = min(1.0, confidence + 0.10)
canonical, category = known
else:
# Generic β€” only count high-confidence regular cadences
if confidence < 0.65:
continue
canonical = merchant.title()
category = "other"
avg_amount_dec = avg_amount.quantize(Decimal("0.01"))
monthly = _normalize_to_monthly(avg_amount_dec, cadence)
annual = (monthly * 12).quantize(Decimal("0.01"))
# Unused detection: if last charge >60 days ago, flag as possibly forgotten
last_seen = max(dates)
flag_unused = (date.today() - last_seen).days > 60 if cadence in ("monthly", "annual") else False
detected.append(DetectedSubscription(
canonical_name=canonical,
category=category,
matched_merchant_text=txs[0].description[:50],
monthly_amount=monthly,
annual_amount=annual,
cadence=cadence,
occurrences=len(txs),
confidence=confidence,
first_seen=min(dates),
last_seen=last_seen,
flag_unused=flag_unused,
transactions=txs,
))
# Step 3: Flag duplicates within categories (e.g., 3 streaming services)
by_category: Dict[str, List[DetectedSubscription]] = defaultdict(list)
for s in detected:
by_category[s.category].append(s)
flagged_duplicates = []
for cat, subs in by_category.items():
if len(subs) >= 3 and cat in ("streaming", "music", "ai", "news", "fitness"):
names = ", ".join(s.canonical_name for s in subs)
flagged_duplicates.append(f"{cat}: {names}")
for s in subs:
s.flag_duplicate_category = True
# Aggregate totals
total_monthly = sum((s.monthly_amount for s in detected), Decimal("0"))
total_annual = sum((s.annual_amount for s in detected), Decimal("0"))
categories_breakdown = {
cat: sum((s.monthly_amount for s in subs), Decimal("0"))
for cat, subs in by_category.items()
}
flagged_unused = [s.canonical_name for s in detected if s.flag_unused]
# Generate insights
insights = []
if total_monthly > 0:
if total_annual > 1000:
insights.append(f"You're spending **${total_annual:,.0f}/year** on subscriptions β€” that's ${total_monthly:,.0f}/month.")
avg_household = Decimal("219") # ~2026 US average
if total_monthly > avg_household:
diff = total_monthly - avg_household
insights.append(f"That's **${diff:,.0f}/month above** the US household average of ${avg_household}/month.")
if flagged_duplicates:
for fd in flagged_duplicates:
insights.append(f"⚠️ Multiple services in same category β€” possible overlap: {fd}")
if flagged_unused:
insights.append(f"⚠️ {len(flagged_unused)} subscription(s) haven't charged in 60+ days but may auto-renew: {', '.join(flagged_unused[:5])}")
# Top spend
if detected:
top = max(detected, key=lambda s: s.monthly_amount)
insights.append(f"Highest spend: **{top.canonical_name}** at ${top.monthly_amount}/month (${top.annual_amount:,.0f}/year).")
return AuditResult(
total_subscriptions=len(detected),
total_monthly_spend=total_monthly.quantize(Decimal("0.01")),
total_annual_spend=total_annual.quantize(Decimal("0.01")),
detected=sorted(detected, key=lambda s: -s.monthly_amount),
categories_breakdown=categories_breakdown,
flagged_duplicates=flagged_duplicates,
flagged_unused=flagged_unused,
insights=insights,
)