Bill Analysis with Read-Only Access: A Practical Guide to Detecting Duplicate Charges
A practical guide to building an automated bank statement analysis system under read-only authorization. Covers a four-layer architecture, transaction normalization, duplicate charge and recurring subscription detection with Python examples, and the security and compliance requirements needed to protect sensitive financial data.
1. Background: Why Automated Bill Analysis Matters
Most people hold multiple bank and credit cards, with statements scattered across different pages in inconsistent formats. Subscription charges are small and recur over long periods, so it’s easy to forget them—until a reconciliation reveals duplicate payments or charges for services that were cancelled long ago.
Manual line-by-line review works, but it’s slow and error-prone. Automated analysis consolidates all transactions into a single view, then uses rules and statistics to flag anomalies, so users only need to review the handful of transactions that actually require judgment.
The hard part is data sensitivity. Account statements contain income, spending habits, and merchant information. Any integration must first answer three questions: who can access the data, what is the scope of access, and how long is the data retained. These three questions define the system’s architectural boundaries.
2. Overall Architecture: A Four-Layer Design
A maintainable bill analysis system typically splits into four layers.
- Data ingestion layer: Retrieves transaction data under user authorization. Common approaches include data aggregation services provided by licensed institutions, or direct integration with banks’ open APIs. Regardless of the approach, the system should use access tokens and never store plaintext credentials such as online banking passwords.
- Data normalization layer: Unifies transactions from different sources into a common field structure, cleans merchant names, and standardizes currency units and time formats.
- Analysis layer: Uses rules, statistical methods, and classification models to detect duplicate charges, identify recurring subscriptions, and categorize spending.
- Presentation and alerting layer: Outputs monthly summaries, anomaly lists, and notifications, and provides entry points for users to confirm or dismiss findings.
The benefit of layering is that each layer can be replaced independently. For example, if the ingestion channel changes, only the first layer needs modification—the other three remain untouched.
3. Design Principles for Read-Only Authorization
Read-only access is the baseline requirement for this kind of system. It only needs to read statements—it never needs to initiate transfers, modify account details, or make payments on the user’s behalf. The narrower the authorization scope, the smaller the potential damage if credentials leak.
When implementing read-only access, focus on the following:
- Least privilege: Request only permissions for querying transaction records and basic account information. Never request payment-related permissions.
- Token management: Encrypt access tokens at rest, set expiry periods, and rotate them regularly. When a user revokes authorization, the system should immediately delete the corresponding token and stop pulling data.
- Authorization transparency: Clearly state on the authorization page what data will be read, how it will be used, and how long it will be kept, letting users decide whether to consent.
- Data minimization: Store only the fields needed for analysis. For example, keep only the last four digits of a card number or a masked identifier—never the full number.
- Retention limits: Define an explicit data retention period, automatically purge expired data, and let users export or delete their data at any time.
4. Transaction Normalization
Statement formats vary widely across sources. The same transaction might appear as “Coffee Shop Downtown #1234” from one source and “COFFEE SHOP DT” from another. The goal of normalization is to make these records mergeable.
Normalization typically involves three types of processing.
Store amounts as integers. Adding floating-point numbers directly introduces precision errors, so amounts should be stored as integers in the smallest currency unit (e.g., cents). When parsing strings, use a decimal type to avoid going through floats.
Merchant name cleaning. Remove reference numbers, store codes, long digit strings, and redundant separators; normalize case and whitespace. Cleaning rules should be configurable, and the original merchant name should be retained for troubleshooting.
Time and timezone unification. A statement’s posting date and the actual transaction time may differ. When detecting duplicate charges, decide explicitly which field to use, and standardize timezones across the system.
Here is a normalization example:
import refrom decimal import Decimal, ROUND_HALF_UPdef normalize_merchant(raw: str) -> str:"""Clean merchant name: normalize case, strip long digit strings and redundant separators."""name = raw.upper()name = re.sub(r"\d{4,}", "", name) # remove reference numbers and long digit stringsname = re.sub(r"[*#_\-]+", " ", name) # unify separatorsname = re.sub(r"\s+", " ", name).strip() # collapse whitespacereturn namedef amount_to_cents(raw: str) -> int:"""Convert an amount string to an integer in cents, avoiding floating-point errors."""value = Decimal(raw.replace(",", "")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)return int(value * 100)print(normalize_merchant("Coffee Shop DT 20241105 *001")) # Output: COFFEE SHOP DT 001print(amount_to_cents("1,280.5")) # Output: 128050
5. Detecting Duplicate Charges and Recurring Subscriptions
“Duplicate charge” is the anomaly users care about most, but it isn’t a single phenomenon. In practice, it helps to distinguish three cases.
- Short-window repeats: The same merchant and amount appear multiple times within a very short window. This could be a system error, a double-submitted order—or a legitimate repeated purchase.
- Recurring subscriptions: The same merchant and amount recur at a fixed interval, such as monthly. These charges are legitimate in themselves, but users should be reminded if they no longer use the service.
- Suspected duplicates: The same merchant with similar but not identical amounts, or charges duplicated across different accounts. These require human confirmation.
The core detection logic is grouping plus interval analysis. The following code demonstrates basic detection for the first two cases.
from dataclasses import dataclassfrom datetime import datefrom collections import defaultdictimport statistics@dataclassclass Transaction:txn_date: dateamount_cents: int # integer amount in centsmerchant: str # cleaned merchant nameaccount_id: str # masked account identifierdef find_short_window_repeats(txns, window_days=3):"""Flag same merchant + same amount recurring within a short window as suspected duplicates."""groups = defaultdict(list)for t in sorted(txns, key=lambda x: x.txn_date):groups[(t.merchant, t.amount_cents)].append(t)suspects = []for items in groups.values():for prev, cur in zip(items, items[1:]):if (cur.txn_date - prev.txn_date).days <= window_days:suspects.append((prev, cur))return suspectsdef detect_recurring(txns, min_occurrences=3, tolerance_days=3):"""Detect same-amount charges recurring at a fixed interval as recurring subscriptions."""groups = defaultdict(list)for t in sorted(txns, key=lambda x: x.txn_date):groups[(t.merchant, t.amount_cents)].append(t.txn_date)results = []for (merchant, amount), dates in groups.items():if len(dates) < min_occurrences:continueintervals = [(b - a).days for a, b in zip(dates, dates[1:])]period = statistics.median(intervals)if period < 7: # intervals shorter than a week are not treated as subscriptionscontinueif all(abs(i - period) <= tolerance_days for i in intervals):results.append({"merchant": merchant,"amount_cents": amount,"period_days": period,"count": len(dates),})return results
Both functions are basic versions. In real use, watch out for false positives. For example, two same-priced purchases at the same coffee shop in one day are common—flagging them as duplicates would annoy users. A more robust approach:
- Apply an amount threshold; by default, don’t alert on small, high-frequency purchases.
- Let users mark a merchant as “normal spending,” and have the system remember that preference.
- Trigger recurring-subscription alerts only within user-defined bounds—for example, only for charges that have occurred three or more consecutive times and exceed a certain amount.
6. Bill Summaries and Spending Categorization
Beyond duplicate detection, bill analysis should answer “where did the money go.” A common approach is to categorize merchants with rules first, then generate summaries with statistics.
Rule-based categorization matches keywords in merchant names—transactions containing terms like “grocery,” “restaurant,” “transit,” or “telecom” are assigned to the corresponding category. Rules are simple and explainable, making them a good starting point. Unmatched transactions go into an “uncategorized” bucket for manual confirmation, and confirmed results can feed back into the rule set.
Once rules reach a reasonable coverage rate, a text classification model can help handle long-tail merchants. Model output should include a confidence score; low-confidence results should still go to the user for confirmation, so misclassifications don’t directly distort monthly reports.
A summary view typically includes:
- Monthly total spending and income, broken down by account and category;
- Changes versus the previous month, with large shifts highlighted;
- A list of recurring subscriptions, including amounts, charge dates, and annualized totals;
- A list of transactions pending confirmation.
Avoid presenting conclusions without context. A statement like “dining spending increased this month” should be accompanied by the specific amounts, the comparison baseline, and the main merchants, so users can judge for themselves.
7. Security and Compliance Requirements
Financial data demands stricter security than ordinary business data. Address the following areas in your design.
Encryption in transit and at rest. All APIs should use encrypted channels; sensitive fields should be encrypted in the database, with keys managed by a dedicated key management service, stored separately from business data.
Log masking. Logs must not contain direct associations between full account numbers, amounts, and user identities. For debugging, use hashed identifiers instead of raw values.
Access control. Follow least privilege: operations staff should not be able to view user-level details by default. Log all access to sensitive data in audit logs and review them regularly.
Compliance and consent. Processing personal financial information must comply with the personal data protection and financial data regulations of your jurisdiction. The product should offer a clear privacy statement, support user rights to access, export, and delete their data, and re-obtain consent when the purpose of data processing changes.
Failures and revocation. When authorization expires or is revoked, the system should stop pulling data and delete related data within the agreed period. Sync failures should produce clear notifications—never silently keep stale data, which misleads users.
8. Pre-Launch Engineering Checklist
Before going live, verify each of the following:
- Authorization scope is read-only; no code path can initiate payments.
- Access tokens are encrypted at rest, with revocation and rotation mechanisms in place.
- All amounts are stored and computed as integers in the smallest unit, with unit tests covering precision edge cases.
- Merchant cleaning rules are configurable, and original fields are retained for traceability.
- Thresholds for duplicate charges and recurring subscriptions are user-adjustable, and false positives can be flagged and fed back.
- Sensitive fields are encrypted, logs are masked, and audit logs are queryable.
- Users can export and delete all their data, and deletion includes confirmation and completion notifications.
- Abnormal states such as sync failures and expired authorization have corresponding UI messages and retry strategies.
Working through this checklist makes the system’s core capabilities more stable and makes security reviews easier to pass.
