Introduction
Manual expense tracking is tedious — you forget to log expenses, lose receipts, and end up with inaccurate records at tax time. Automated expense tracking from bank SMS solves this: parse transaction SMS, categorize automatically, and sync to Google Sheets. Zero manual entry.
This post builds a complete system for Indian bank SMS.
How it works
Bank sends SMS → Android app forwards to webhook → Python parses SMS → Categorizes → Saves to Google Sheets
Step 1: Set up SMS forwarding
Option A: Android app (Tasker + AutoNotification)
- Install Tasker and AutoNotification on Android
- Create a Tasker profile: “When SMS received from bank numbers”
- Action: HTTP POST to your webhook with SMS body
Option B: SMS Gateway app
Use an app like “SMS Gateway” or “Webhook.site” to forward SMS to a URL.
Option C: Manual export (simplest)
Export SMS from your phone using an app like “SMS Backup & Restore” and process the CSV.
Step 2: Parse bank SMS
Indian bank SMS follow common patterns:
# HDFC Bank
"Rs 500.00 debited from A/c XX1234 on 01-03-26. Info: SWIGGY. Avl Bal: Rs 10,000.00"
# SBI
"Your A/c X1234 debited by Rs.500.00 on 01Mar26. Info: AMAZON. Avl Bal Rs.10000.00"
# ICICI
"ICICI Bank Acct XX1234 debited for Rs 500.00 on 01-Mar-26. Info: UBER. Avl Bal Rs 10000.00"
# UPI
"Rs 500.00 paid to merchant@upi via UPI. Ref: 123456. Avl Bal: Rs 10,000"
Python parser
import re
from datetime import datetime
def parse_bank_sms(sms_text):
"""Parse Indian bank SMS and extract transaction details."""
sms = sms_text.strip()
# Amount
amount_match = re.search(r"(?:Rs\.?\s*|INR\s*)([\d,]+\.?\d*)", sms, re.IGNORECASE)
amount = float(amount_match.group(1).replace(",", "")) if amount_match else None
# Type (debit/credit)
is_debit = any(kw in sms.lower() for kw in ["debited", "paid", "spent", "withdrawn"])
is_credit = any(kw in sms.lower() for kw in ["credited", "received", "deposited"])
txn_type = "debit" if is_debit else "credit" if is_credit else "unknown"
# Merchant/description
merchant = None
for pattern in [r"Info:\s*(.+?)(?:\.|$)", r"to\s+(.+?)(?:\s+via|\s+on|$)", r"at\s+(.+?)(?:\s+on|$)"]:
m = re.search(pattern, sms, re.IGNORECASE)
if m:
merchant = m.group(1).strip()
break
# Date
date = None
for pattern in [r"(\d{2}[-/]\d{2}[-/]\d{2,4})", r"(\d{2}[A-Za-z]{3}\d{2,4})"]:
m = re.search(pattern, sms)
if m:
date = m.group(1)
break
# Balance
bal_match = re.search(r"(?:Avl|Available|Bal)[:\s]*Rs\.?\s*([\d,]+\.?\d*)", sms, re.IGNORECASE)
balance = float(bal_match.group(1).replace(",", "")) if bal_match else None
return {
"amount": amount,
"type": txn_type,
"merchant": merchant,
"date": date,
"balance": balance,
"raw": sms,
}
Step 3: Auto-categorize
CATEGORIES = {
"food": ["swiggy", "zomato", "restaurant", "cafe", "dominos", "mcdonalds", "kfc"],
"transport": ["uber", "ola", "rapido", "metro", "petrol", "fuel", "parking"],
"shopping": ["amazon", "flipkart", "myntra", "ajio", "meesho"],
"utilities": ["electricity", "water", "gas", "internet", "mobile", "recharge"],
"entertainment": ["netflix", "spotify", "hotstar", "prime", "youtube"],
"health": ["pharmacy", "hospital", "clinic", "doctor", "medicine"],
"business": ["aws", "github", "notion", "slack", "zoom", "domain", "hosting"],
}
def categorize(merchant):
if not merchant:
return "uncategorized"
m = merchant.lower()
for category, keywords in CATEGORIES.items():
if any(kw in m for kw in keywords):
return category
return "uncategorized"
Step 4: Save to Google Sheets
import gspread
from google.oauth2.service_account import Credentials
from datetime import datetime
creds = Credentials.from_service_account_file("service_account.json",
scopes=["https://www.googleapis.com/auth/spreadsheets"])
gc = gspread.authorize(creds)
sheet = gc.open("Expense Tracker").sheet1
def log_expense(txn):
sheet.append_row([
txn["date"],
txn["merchant"],
txn["amount"],
txn["type"],
categorize(txn["merchant"]),
txn["balance"],
txn["raw"],
])
print(f"Logged: {txn['merchant']} - Rs. {txn['amount']} ({categorize(txn['merchant'])})")
Step 5: Full pipeline
def process_sms(sms_text):
"""Process a single SMS: parse → categorize → log."""
txn = parse_bank_sms(sms_text)
if txn["amount"] and txn["type"] == "debit":
log_expense(txn)
return txn
# Example
sms = "Rs 500.00 debited from A/c XX1234 on 01-03-26. Info: SWIGGY. Avl Bal: Rs 10,000.00"
txn = process_sms(sms)
print(txn)
# {'amount': 500.0, 'type': 'debit', 'merchant': 'SWIGGY', 'date': '01-03-26', 'balance': 10000.0, 'raw': '...'}
Step 6: Webhook receiver (for real-time)
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/webhook/sms", methods=["POST"])
def receive_sms():
data = request.json
sms_text = data.get("message", "")
txn = process_sms(sms_text)
return jsonify({"status": "ok", "transaction": txn})
if __name__ == "__main__":
app.run(port=5000)
Deploy on Render/Railway (free tier) and point your SMS forwarding app to this URL.
Step 7: Monthly summary
import pandas as pd
def monthly_summary():
sheet = gc.open("Expense Tracker").sheet1
df = pd.DataFrame(sheet.get_all_records())
# Filter current month
df["Date"] = pd.to_datetime(df["Date"], format="%d-%m-%y")
current_month = df[df["Date"].dt.month == datetime.now().month]
# Summary by category
summary = current_month.groupby("Category")["Amount"].sum().sort_values(ascending=False)
print("=== Monthly Expense Summary ===")
for cat, amt in summary.items():
print(f" {cat}: Rs. {amt:,.0f}")
print(f"\n Total: Rs. {current_month['Amount'].sum():,.0f}")
return summary
monthly_summary()
Common mistakes
- Not handling all bank formats — each bank has a different SMS format. Test with your bank’s actual SMS.
- No error handling — if parsing fails, log the raw SMS for manual review.
- Duplicate entries — if the same SMS is forwarded twice, you’ll get duplicates. Add a unique ID (transaction ref) to dedupe.
- Ignoring credits — track both debits and credits for accurate balance.
- No backup — export to CSV weekly. Google Sheets can be accidentally deleted.
Key Concepts
- SMS parsing = extracting structured data from unstructured text
- Regex = pattern matching for text extraction
- Webhook = HTTP endpoint for receiving data
- Categorization = assigning transactions to categories
- Deduplication = preventing duplicate entries
What to Try Next
- Track freelance income and expenses manually
- Automate invoices for payment tracking
- Build an expense dashboard in Streamlit
- Combine with budgeting for financial planning
FAQ
Is it safe to parse bank SMS?
Yes — you’re only reading SMS text, not accessing your bank account. The script doesn’t store or transmit sensitive data (account numbers, passwords). Store the Google Sheet securely.
What if my bank’s SMS format isn’t supported?
Add a new regex pattern for your bank’s format. Test with 5-10 real SMS messages. The parser handles the most common Indian bank formats (HDFC, SBI, ICICI, Axis, Kotak).
Can I use this for credit card SMS?
Yes — credit card SMS follow similar patterns. Add “credit card” keywords to the categorization. The parser handles both debit and credit transactions.
Is there a no-code alternative?
Yes — use Google Sheets + Apps Script to parse SMS forwarded via email. Or use a service like Mint or Walnut (India) that auto-tracks expenses from SMS. See Track Freelance Income and Expenses.