Building a Read-Only Personal Finance Analysis System: Design and Practice
This article describes how to design a personal finance question-answering and analysis system that works under read-only authorization. It covers least-privilege permissions, a unified transaction data model, expense categorization and monthly summaries, detection of duplicate charges, abnormal fees, and recurring bills that rise slowly over time, income-to-expense and interest estimation, and validation of results. The code shows the ideas only and is not tied to any specific platform.
1. Background and Problem Definition
Personal financial data is usually spread across accounts at several financial institutions. Each institution uses its own statement format, transaction descriptions, and settlement timing. To answer questions such as “Where did my money go this month?” or “Which charge looks wrong?”, a user often has to download several statements and compare entries one by one. Natural language queries can lower this barrier, but they couple sensitive data, model inference, and amount calculation. The design must handle these three separately. Otherwise, it is hard to guarantee the safety and accuracy of the results.
This article uses the scenario of “a smart assistant answering personal finance questions and analyzing data under read-only authorization.” It walks through the full path, from permission design to result validation. The code illustrates the ideas only and does not correspond to any specific platform’s API.
2. Core Principle: Least Privilege and Read-Only Boundaries
The first principle of the design is least privilege. The assistant only needs to read balances and transaction records. It does not need to transfer money, make payments, change account settings, or invest on the user’s behalf. Removing write operations from the capability list means the worst outcome is an incorrect answer, not a financial loss.
A typical permission layering looks like this:
| Capability | Enabled | Notes |
|---|---|---|
| Query balances | Yes | Read-only, requires explicit user authorization |
| Query transaction details | Yes | Read-only, limited to the authorized time range |
| Initiate transfers | No | Write operation, outside the capability scope |
| Investment advice and orders | No | Outside the functional boundary |
| Modify account information | No | Write operation, outside the capability scope |
Permissions must be enforced on the server side and cannot rely solely on prompt constraints. A model can be induced to output unauthorized instructions, so server-side checks are the last line of defense. The sample code below shows a default-deny approach:
# Capability allowlist: only read operations are permitted.# Any operation not listed here is denied.ALLOWED_SCOPES = {"accounts:read","transactions:read",}def assert_scope(requested: str) -> None:if requested not in ALLOWED_SCOPES:raise PermissionError(f"Operation not authorized: {requested}")
The key point of this code is default deny. When adding a new capability, it must be explicitly added to the allowlist and pass a security review. Authorization tokens should also have an expiration time and support revocation by the user at any time.
3. Data Ingestion Layer: A Unified Transaction Model
Transaction data from different sources varies widely. Some use a “summary” field, and others use a “merchant description” field. Some amounts carry a sign, while others are split into income and expense columns. Dates may be posting dates or transaction dates. Before analysis, this data must be mapped to a unified model. Otherwise, categorization, aggregation, and matching will produce errors.
The unified model should include at least the following fields: account identifier, transaction time, amount, currency, income or expense direction, original description, normalized merchant name, and category.
from dataclasses import dataclassfrom datetime import datetimefrom decimal import Decimal@dataclass(frozen=True)class Transaction:account_id: stroccurred_at: datetimeamount: Decimal # Positive values are income; negative values are expensescurrency: strraw_description: str # Keep the original text for traceabilitymerchant: str # Normalized merchant namecategory: str | None = None
Amounts should use Decimal rather than floating-point numbers. Binary floating-point cannot represent most decimal fractions exactly, so visible errors accumulate over repeated additions. In financial calculations, this is a basic requirement.
Normalization usually involves three steps. First, unify full-width and half-width characters. Second, remove reference numbers and date fragments from transaction descriptions. Third, use a mapping table to merge different spellings of the same merchant into one name. For example, the same store may appear under several abbreviations on statements from different banks. Normalization quality directly determines how reliable later statistics are, so the mapping rules should have unit tests.
4. Analysis Capabilities
4.1 Expense Categorization and Monthly Summary
The recommended categorization strategy is “rules first, model as fallback.” Rule matching is fast and deterministic, and it suits most frequent merchants. Transactions that the rules cannot match go to a model or to manual labeling, and the results are written back into the rule base.
CATEGORY_RULES = {"餐饮": ["餐", "咖啡", "外卖"],"交通": ["地铁", "加油", "停车"],"订阅": ["会员", "订阅", "月费"],}def classify(tx: Transaction) -> str:for category, keywords in CATEGORY_RULES.items():if any(k in tx.merchant for k in keywords):return categoryreturn "未分类"
The monthly summary counts only expense transactions and excludes transfers between a user’s own accounts. Otherwise, the same funds would be counted twice. The summary should include the amount and share of each category, along with the proportion of uncategorized transactions. The uncategorized share is a useful quality indicator. If it stays high, the rule base needs more keywords.
4.2 Abnormal Bill Detection
Anomalies that are easy to miss usually fall into three types: duplicate charges, abnormal fees, and recurring bills that rise slowly over time. Each type needs different detection logic, so each should be designed separately.
Duplicate charges typically show the same merchant and the same amount appearing twice within a short time window. The code below groups transactions by merchant and amount, then checks the time gap between adjacent records:
from datetime import timedeltadef find_duplicates(txs: list[Transaction],window: timedelta = timedelta(hours=24)):ordered = sorted(txs, key=lambda t: (t.merchant, t.amount, t.occurred_at))hits = []for prev, curr in zip(ordered, ordered[1:]):if (prev.merchant == curr.merchantand prev.amount == curr.amountand curr.occurred_at - prev.occurred_at <= window):hits.append((prev, curr))return hits
The time window is a key parameter. A window that is too large flags normal repeat purchases as errors. A window that is too small misses delayed postings. A reasonable approach lets users adjust the window and labels results as “possible duplicate” rather than declaring them errors. Two same-priced coffees bought at the same shop on the same day will also match this rule.
Abnormal fees can be detected with a ratio method. For example, calculate the share of total spending that fees make up for an account over a past period. If a given month’s ratio is significantly above the historical average, prompt the user to check it. Thresholds should be calibrated against the account type and historical data rather than set as fixed constants.
Gradual increases need a longer observation window. One practical method compares the average monthly amount for a merchant over the last three months with the same three months one year earlier. When the increase exceeds a set threshold, the system generates an alert. No single transaction makes this problem obvious. It appears only when you compare across time periods.
4.3 Income-to-Expense Ratio and Interest Estimation
The income-to-expense ratio is calculated as:
Income-to-expense ratio = Total expenses in the period ÷ Total income in the period
When the ratio is greater than 1, expenses exceed income. The calculation must define the statistical period clearly and state whether one-time large expenses are included.
Before estimating interest, the term needs explaining. The annual percentage rate (APR) usually refers to a nominal annual rate without compounding. Actual interest depends on the calculation method, compounding frequency, and fee structure. When contract details are unavailable, interest can be estimated from daily balances:
```python
from decimal import Decimal
def estimate_interest(daily_balances
