UPI Transaction Analyzer: Categorize Payments from Bank Statements
Build an AI agent that extracts UPI transactions from Indian bank statements, categorizes merchants, and surfaces spending insights. Full TypeScript walkthrough.
Unified Payments Interface (UPI) handles over 15 billion transactions a month in India. For developers building lending apps, personal finance tools, or expense dashboards, understanding a user's UPI behaviour from their bank statement is essential — and messy.
This guide shows you how to build a UPI Transaction Analyzer agent in TypeScript. It calls the Lekha API to extract structured transaction data from any Indian bank statement, then categorizes UPI payments by merchant, app, and category.
What You'll Build
A TypeScript agent that:
Why UPI Analysis Is Hard Without AI
UPI transaction descriptions are notoriously inconsistent across Indian banks. The same ₹500 Swiggy order appears as:
UPI/CR/2651234567/SWIGGY/BANKB0005/YBL/UPI-SWIGGY INDIA P-YESB0000001-240507P2M/UPI/Swiggy Order 7843UPI REF NO 4121987654321 SWIGGYA rules engine breaks on day one. Vision AI with a well-structured prompt handles all of these — and Lekha has already done that work for every major Indian bank.
Prerequisites
Step 1: Extract Bank Statement Data
Install the Lekha SDK:
bun add lekha-sdk
or
npm install lekha-sdk
Extract structured data from a bank statement:
import { LekhaClient } from "lekha-sdk";
import { readFileSync } from "fs";
const lekha = new LekhaClient({ apiKey: process.env.LEKHA_API_KEY! });
async function extractStatement(filePath: string) {
const file = readFileSync(filePath);
const blob = new Blob([file], { type: "application/pdf" });
const result = await lekha.extract({
document: blob,
type: "bank_statement",
});
if (!result.success) {
throw new Error(Extraction failed: ${result.error.message});
}
return result.data;
}
The returned data object includes transactions — an array of structured entries with date, description, amount, type (credit / debit), and balance.
Step 2: Filter UPI Transactions
UPI transactions share common patterns. Lekha normalizes descriptions, but we can still reliably identify UPI entries:
interface Transaction {
date: string;
description: string;
amount: number;
type: "credit" | "debit";
balance: number;
}
interface UpiTransaction extends Transaction {
upiRef?: string;
upiApp?: string;
merchant?: string;
category?: string;
}
function filterUpi(transactions: Transaction[]): UpiTransaction[] {
const upiPattern = /\b(upi|bhim|phonep|gpay|paytm|neft\/upi)\b/i;
return transactions
.filter((t) => upiPattern.test(t.description))
.map((t) => ({ ...t }));
}
Step 3: Identify the UPI App
Different UPI apps leave distinct fingerprints in transaction descriptions:
const UPI_APP_PATTERNS: Record = {
PhonePe: /phonep(e|ay)|ybl\d/i,
"Google Pay": /gpay|okaxis|okhdfcbank|oksbi|okicici/i,
Paytm: /paytm|pytm/i,
BHIM: /bhim/i,
AmazonPay: /amazon\s*pay|apl\d/i,
CRED: /\bcred\b/i,
Slice: /\bslice\b/i,
Jupiter: /jupiter/i,
"Juspay / Others": /.*/,
};
function detectUpiApp(description: string): string {
for (const [app, pattern] of Object.entries(UPI_APP_PATTERNS)) {
if (pattern.test(description)) return app;
}
return "Unknown";
}
Step 4: Categorize Merchants with Claude
For merchant categorization, use Claude to classify each unique merchant name. Batching all unique merchants into one prompt keeps costs low:
import Anthropic from "@anthropic-ai/sdk";, }, ], });const anthropic = new Anthropic();
const CATEGORIES = [ "food_delivery", "restaurants", "groceries", "fuel", "utilities", "subscriptions", "rent", "healthcare", "education", "shopping", "travel", "transfers_p2p", "government", "insurance", "other", ];
async function categorizeMerchants( merchants: string[], ): Promise
> { const unique = [...new Set(merchants)]; const response = await anthropic.messages.create({ model: "claude-haiku-5-5", max_tokens: 1024, messages: [ { role: "user", content:
Categorize each of these Indian UPI merchant names into one of: ${CATEGORIES.join(", ")}. Merchants: ${unique.map((m, i) =>${i + 1}. ${m}).join("\n")}Respond with a JSON object mapping each merchant name exactly to its category. Example: {"Swiggy": "food_delivery", "BPCL Petrol": "fuel"}
const text = response.content[0].type === "text" ? response.content[0].text : ""; const jsonMatch = text.match(/\{[\s\S]+\}/); return jsonMatch ? JSON.parse(jsonMatch[0]) : {}; }
Step 5: Extract Merchant Names from Descriptions
UPI descriptions embed the merchant name, but its position varies by bank. A simple heuristic works well for most formats:
function extractMerchant(description: string): string {
// Remove common prefixes
let clean = description
.replace(/^(upi\/cr|upi\/dr|p2m|p2p|upi|neft\/upi)[\/\-\s]*/i, "")
.replace(/\/?\d{10,}/g, "") // remove ref numbers
.replace(/\/(ybl|okicici|okhdfcbank|oksbi|okaxis|paytm)\d*/gi, "")
.trim();
// Take the first meaningful segment
const parts = clean.split(/[\/\-|]/);
const name = parts.find((p) => p.trim().length > 2)?.trim() ?? description;
return name.substring(0, 40);
}
Step 6: Assemble the Agent
interface SpendingReport {
period: { from: string; to: string };
totalUpiDebits: number;
totalUpiCredits: number;
transactionCount: number;
byApp: Record;
byCategory: Record;
topMerchants: Array<{ merchant: string; amount: number; count: number }>;
}
async function analyzeUpiTransactions(
statementPath: string,
): Promise {
// 1. Extract statement
const statement = await extractStatement(statementPath);
const allTransactions: Transaction[] = statement.transactions;
// 2. Filter UPI transactions
const upiTxns = filterUpi(allTransactions);
// 3. Extract merchant names
const withMerchants = upiTxns.map((t) => ({
...t,
merchant: extractMerchant(t.description),
upiApp: detectUpiApp(t.description),
}));
// 4. Categorize merchants (batch call to Claude)
const merchantNames = withMerchants.map((t) => t.merchant);
const categories = await categorizeMerchants(merchantNames);
const enriched: UpiTransaction[] = withMerchants.map((t) => ({
...t,
category: categories[t.merchant] ?? "other",
}));
// 5. Aggregate
const debits = enriched.filter((t) => t.type === "debit");
const credits = enriched.filter((t) => t.type === "credit");
const byApp: Record = {};
const byCategory: Record = {};
const merchantMap: Record = {};
for (const t of debits) {
const app = t.upiApp ?? "Unknown";
byApp[app] = byApp[app] ?? { count: 0, amount: 0 };
byApp[app].count++;
byApp[app].amount += t.amount;
const cat = t.category ?? "other";
byCategory[cat] = byCategory[cat] ?? { count: 0, amount: 0 };
byCategory[cat].count++;
byCategory[cat].amount += t.amount;
const m = t.merchant ?? "Unknown";
merchantMap[m] = merchantMap[m] ?? { amount: 0, count: 0 };
merchantMap[m].amount += t.amount;
merchantMap[m].count++;
}
const topMerchants = Object.entries(merchantMap)
.map(([merchant, stats]) => ({ merchant, ...stats }))
.sort((a, b) => b.amount - a.amount)
.slice(0, 10);
const dates = allTransactions.map((t) => t.date).sort();
return {
period: { from: dates[0], to: dates[dates.length - 1] },
totalUpiDebits: debits.reduce((s, t) => s + t.amount, 0),
totalUpiCredits: credits.reduce((s, t) => s + t.amount, 0),
transactionCount: enriched.length,
byApp,
byCategory,
topMerchants,
};
}
Example Output
{
"period": { "from": "2026-10-01", "to": "2026-10-31" },
"totalUpiDebits": 42350,
"totalUpiCredits": 5000,
"transactionCount": 87,
"byApp": {
"PhonePe": { "count": 41, "amount": 18200 },
"Google Pay": { "count": 29, "amount": 14750 },
"Paytm": { "count": 17, "amount": 9400 }
},
"byCategory": {
"food_delivery": { "count": 22, "amount": 8900 },
"groceries": { "count": 15, "amount": 6200 },
"fuel": { "count": 8, "amount": 5600 },
"subscriptions": { "count": 6, "amount": 2850 }
},
"topMerchants": [
{ "merchant": "BPCL Petrol", "amount": 4800, "count": 5 },
{ "merchant": "Swiggy", "amount": 3900, "count": 11 },
{ "merchant": "BigBasket", "amount": 3400, "count": 4 }
]
}
Practical Applications
Lending underwriting: Identify rent payments and recurring utility bills as proof of financial responsibility. Flag unusually high P2P transfers that may indicate undeclared liabilities. Personal finance dashboards: Show users exactly where their UPI money goes — most people are surprised by the food delivery total. BNPL eligibility: Use UPI transaction frequency and category mix as a soft credit signal for thin-file borrowers who lack a credit score. Expense reimbursement: Match UPI fuel and travel transactions against business trips for automated expense claims.FAQ
Can this handle statements from any Indian bank? Yes. Lekha supports all major Indian banks including SBI, HDFC, ICICI, Axis, Kotak, PNB, Canara, Union Bank, and 30+ others. The underlying extraction model normalizes transaction descriptions across all formats before your code sees them. How accurate is the merchant categorization? Claude Haiku classifies Indian merchant names with high accuracy because it has seen enough Indian fintech data to recognize names like "IRCTC", "Nykaa", or "BigBasket" without training. For production, maintain a custom override map for edge cases. Does Lekha store the PDF I upload? No. Lekha processes documents in memory only and does not persist your users' financial documents, in line with India's DPDP Act requirements. How much does this cost per analysis? A typical 3-month bank statement with ~300 transactions costs one Lekha API call plus a small Claude Haiku call for categorization (usually under ₹1 per analysis at scale).UPI is the heartbeat of Indian digital finance. Build the tools that make sense of it — start with a free Lekha API key at lekhadev.com and test your first statement in the playground in minutes.