Personal Finance Analytics on Read-Only Data: Architecture and Implementation

    This article outlines a technical architecture for building a personal finance analysis system that aggregates data from multiple financial institutions under strict read-only access. It covers permission boundaries, transaction normalization and categorization, anomaly detection, interest calculation, natural language query handling, and result traceability, with practical code examples and an implementation checklist.

    1. Background and Problem Definition

    Personal funds are often spread across accounts at multiple financial institutions. Each institution’s app shows its own transaction history, and users must log in to each one, export data, and manually consolidate it to answer basic questions like “Where did my money go this month?” Data fragmentation is the first barrier to analysis and the core problem an automated solution must address.

    Abstracting this need into technical terms yields four sub-problems:

    • Data aggregation: uniformly read balances and transaction records from multiple accounts.
    • Semantic understanding: map user natural-language questions into explicit queries and statistical operations.
    • Rule and model analysis: produce structured outputs such as categorization, anomaly detection, and interest estimation.
    • Result presentation: deliver outputs as lists, charts, or dashboards while preserving verifiable transaction-level details.

    The rest of this article follows these four sub-problems, with additional focus on permission design and result trustworthiness.

    2. Permission Boundaries: Read-Only as the Primary Design Principle

    Financial applications handle highly sensitive data, so permission design should precede feature design. The principle of least privilege is recommended:

    • Request read access only to account lists, balances, and transaction details.
    • Do not enable write operations such as transfers, payments, or account modifications.
    • Set short validity periods for authorization tokens and allow users to revoke them at any time.
    • Store only masked account identifiers in logs; never record plaintext account numbers.

    The following illustrative server-side code validates the granted scope and rejects permissions beyond what the analysis requires:

    1. # Illustrative code: scope validation
    2. ALLOWED_SCOPES = {"accounts:read", "balances:read", "transactions:read"}
    3. def check_scopes(granted: set[str]) -> None:
    4. extra = granted - ALLOWED_SCOPES
    5. if extra:
    6. raise PermissionError(f"Granted scope exceeds analysis requirements: {sorted(extra)}")

    Such validation should be enforced at the data ingestion layer, not left to the frontend or to the caller’s discretion.

    3. Transaction Data Standardization and Categorization

    3.1 Data Cleaning

    Transaction descriptions vary widely across institutions. Common issues include: descriptions mixed with sequence numbers, date suffixes, and extra whitespace; inconsistent sign conventions for amounts; and duplicate records for the same transaction at different states (e.g., pending vs. posted). A typical cleaning pipeline includes:

    1. Remove long numeric strings and excess whitespace from descriptions.
    2. Normalize amount signs and currency precision.
    3. Store timestamps in a unified timezone and convert to the user’s timezone only for display.
    4. Merge pending and posted records to avoid double counting.

    3.2 Categorization Strategy

    A layered approach is recommended: rules first, model second, human fallback. Rules cover high-frequency merchants with low cost and explainable results; models handle long-tail transactions not covered by rules; low-confidence results go into a manual review queue, and confirmed results feed back into the rule base.

    1. import re
    2. CATEGORY_RULES = {
    3. "Dining": ["restaurant", "coffee", "takeout"],
    4. "Transport": ["subway", "fuel", "ride"],
    5. "Subscription": ["membership", "subscription", "monthly"],
    6. }
    7. def normalize_desc(raw: str) -> str:
    8. text = re.sub(r"\d{6,}", "", raw) # remove long numeric strings, e.g., sequence numbers
    9. return re.sub(r"\s+", " ", text).strip()
    10. def categorize(raw: str) -> str:
    11. desc = normalize_desc(raw)
    12. for category, keywords in CATEGORY_RULES.items():
    13. if any(k in desc for k in keywords):
    14. return category
    15. return "Uncategorized"

    The keyword rules above are only examples. A real system should maintain rules based on a sample dataset and include unit tests to prevent regressions when rules are updated.

    4. Anomalous Bill Detection

    The goal of anomaly detection is to “surface clues worth the user’s attention,” not to issue final conclusions. Three common rule types are:

    • Duplicate charges: same merchant, same amount, occurring multiple times within a short time window (e.g., 24 hours).
    • Unusual fees: fee-type transactions exceed a threshold or deviate significantly from the account’s historical average.
    • Recurring price increases: the charged amount for the same subscription merchant rises stepwise over time.

    The duplicate-charge detection logic can be expressed with the following illustrative code:

    1. from datetime import timedelta
    2. def find_duplicates(txns, window=timedelta(hours=24)):
    3. """txns: list of transaction objects sorted by time, each with time, merchant, amount.
    4. Returns suspected duplicate-charge pairs. Window is an example parameter and should be calibrated. """
    5. suspects = []
    6. for i, a in enumerate(txns):
    7. for b in txns[i + 1:]:
    8. if b.time - a.time > window:
    9. break
    10. if a.merchant == b.merchant and a.amount == b.amount:
    11. suspects.append((a, b))
    12. return suspects

    Detection results should be marked as “candidates.” Two identical charges from the same merchant could also be legitimate installments or catch-up payments, so final judgment requires user verification against the original statements.

    5. Interest Calculation: Define the Formulation First, Then Compute

    Users often ask “At this annual rate, how much interest am I paying?” To answer such questions, one must first clarify the terms and then specify the calculation basis.

    • APR (Annual Percentage Rate): nominal annual interest rate, not including compounding effects.
    • Daily rate: APR divided by 365, a common estimation basis.
    • Simple per-transaction interest: principal × APR × days / 365.
    1. def simple_interest(principal: float, apr: float, days: int) -> float:
    2. """Estimate interest using simple interest with a 365-day year. Actual terms may differ."""
    3. return round(principal * apr * days / 365, 2)

    For example, with a principal of 10,000, an APR of 18%, and 30 days, the estimate is approximately 148. If the actual billing uses daily compounding or monthly settlement, the result will differ. Therefore, the result page should display both the calculation basis and the input parameters so the user knows where the number came from.

    6. Natural Language Query Implementation

    A natural language query typically involves these steps:

    1. Intent recognition: determine whether the question is about spending by category, anomaly checks, interest calculation, or trend analysis.
    2. Parameter extraction: extract conditions such as date range, account scope, and category.
    3. Structured query: call deterministic statistical code to perform the computation.
    4. Result generation: explain the result in plain language and attach key details.

    One key design point: numbers must be computed by statistical code; the language model is responsible for understanding the question and explaining the result, not for generating monetary amounts. Below is an example intent structure:

    1. {
    2. "intent": "spending_by_category",
    3. "time_range": {"start": "2026-11-01", "end": "2026-11-30"},
    4. "accounts": "all"
    5. }

    For broader questions like “Have expenses exceeded income?”, the system should decompose the question into income and expense aggregation sub-queries, perform the difference, and state the account scope and time period used.

    7. Traceability and Result Presentation

    The credibility of financial conclusions depends on how well they can be traced. Each conclusion should ideally include:

    • The source account and time range.
    • The calculation basis and key parameters.
    • Expandable transaction details, with each transaction carrying a unique identifier.
    • Clear risk notes stating that results may contain errors and that important amounts should be verified against bank statements.

    Common presentation forms include weekly spending charts, a calendar of upcoming bills, and customizable dashboards. Dashboard configurations should be saved, editable, and decoupled from the data query logic so that statistical dimensions can be adjusted later.

    8. Implementation Checklist

    • Authorization scope is minimized; all write operations are disabled.
    • Sensitive fields are masked; no plaintext data is written to logs.
    • Categorization and anomaly rules are backed by sample datasets and unit tests.
    • Key figures can be traced back to original transactions.
    • Output includes calculation basis and risk notes.
    • Analysis results are not the sole basis for investment or lending decisions.