Build a Smart Expense Tracker with AI Categorization
You’ve probably downloaded a bank CSV, stared at 200 lines of “Uber,” “Starbucks,” and “Amazon,” and wondered: which of these is actually “food” and which is “transportation”? Manually categorizing expenses is tedious, inconsistent, and frankly, a waste of your brainpower. But with a little Python and an AI model, you can build a smart expense tracker that automatically sorts every transaction into the right category—accurately, instantly, and ready to use today.
In this guide, you’ll build a working expense categorizer that:
- Reads your bank CSV or Excel file
- Sends transaction descriptions to an LLM (like OpenAI’s GPT)
- Returns a structured category for each row
- Exports a clean, categorized file you can import into Excel, Google Sheets, or your accounting software
No fancy apps. No subscriptions. Just code you can run in minutes.
Why AI Categorization Beats Manual Sorting
Manual categorization fails because it’s subjective. One person calls “Uber” Transportation; another calls it Commute. AI removes that ambiguity by applying consistent rules across thousands of transactions.
More importantly, AI scales. You can categorize 50 transactions or 5,000 with the same effort. And unlike rigid rule-based systems (e.g., “if merchant = ‘Uber’ → Transportation”), AI handles edge cases: “Uber for Business” might be Work Travel, while “Uber Eats” is Food.
The result? A dynamic, self-improving categorizer that adapts to your spending patterns without you rewriting code.
Setting Up Your Environment
Before writing code, you need three things:
-
A bank transaction file (CSV or Excel) with columns like
merchant,description,amount,date - An LLM API key (OpenAI, Anthropic, or any compatible provider)
- Python 3.8+ with these packages:
pip install pandas openai
If you’re using OpenAI, register at openai.com, create an API key, and store it securely. Never hardcode it in your script—use environment variables:
export OPENAI_API_KEY="your-secret-key-here"
The Core Python Code: One Script, Full Automation
Here’s a complete, working script that reads your expenses, categorizes them with AI, and exports the result:
import pandas as pd
import os
from openai import OpenAI
# Load API key from environment
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# Define your expense categories
CATEGORIES = [
"Food & Dining",
"Transportation",
"Entertainment",
"Shopping",
"Utilities",
"Healthcare",
"Travel",
"Other"
]
# Prompt template for AI
PROMPT = f"""
You are an expense categorization assistant.
Given a transaction description, assign it to ONE of these categories:
{CATEGORIES}
Rules:
- Be precise. If unsure, choose "Other".
- Return ONLY the category name, no extra text.
Transaction: {transaction_desc}
Category:
"""
def categorize_expense(description: str) -> str:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": PROMPT.replace("{transaction_desc}", description)}],
max_tokens=10
)
return response.choices[0].message.content.strip()
# Load your transaction file
df = pd.read_csv("transactions.csv") # or "transactions.xlsx"
# Apply categorization
print("Categorizing expenses...")
df["AI_Category"] = df["description"].apply(categorize_expense)
# Export result
df.to_csv("categorized_transactions.csv", index=False)
print(f"✅ Saved to categorized_transactions.csv with {len(df)} rows categorized.")
Run this script with:
python expense_tracker.py
Within seconds, you’ll have a categorized_transactions.csv file ready to import into Excel, Google Sheets, or QuickBooks.
Making It Smarter: Few-Shot Learning and Confidence Scores
The basic script works, but you can make it more accurate by adding context. Instead of sending just one description, include a few examples of already-categorized transactions (this is called few-shot learning).
Update your prompt to include examples:
EXAMPLES = [
{"desc": "Uber ride to airport", "cat": "Transportation"},
{"desc": "Starbucks coffee", "cat": "Food & Dining"},
{"desc": "Netflix subscription", "cat": "Entertainment"}
]
examples_text = "\n".join([f"- {e['desc']} → {e['cat']}" for e in EXAMPLES])
PROMPT = f"""
You are an expense categorization assistant.
Examples:
{examples_text}
Categories: {CATEGORIES}
Rules:
- Match the style of the examples.
- Return ONLY the category name.
Transaction: {transaction_desc}
Category:
"""
This approach significantly improves accuracy, especially for ambiguous merchants.
For enterprise use, you can also ask the AI to return a confidence score (high/medium/low) and route medium/low-confidence items to human review—exactly as described in modern AI expense workflows [6].
From Script to Full App: Next Steps
This script is your foundation. To turn it into a real app:
-
Add a UI: Use
streamlitorgradiofor a web interface where users upload CSVs and see results instantly. - Persist categories: Save your custom category list to a JSON file so users can add “Gym Membership” or “Pet Supplies.”
- Automate: Run the script weekly via cron or GitHub Actions to auto-process new bank exports.
-
Visualize: Plot spending by category using
matplotliborplotlyto spot trends.
You can even integrate this with Glide or Airtable to build a no-code frontend that triggers the AI backend [2][4].
Why This Matters for Your Daily Life
You don’t need to be a data scientist to benefit from AI. This script gives you:
- Time savings: No more 30-minute manual sorting sessions
- Consistency: Every “Uber” is treated the same way
- Insight: Instant category totals help you spot spending leaks
- Control: You define the categories—no black-box algorithms
And because it’s open-source Python, you can modify it forever: add new categories, change the model, or connect it to your bank API.
Start Today: Your First Categorized CSV
Don’t wait for a “perfect” app. Grab your latest bank CSV, run the script above, and see your expenses auto-categorized in under 5 minutes.
Your call to action:
- Download your transaction history in CSV format [7]
- Paste the code into
expense_tracker.py - Run it and open
categorized_transactions.csv
You’ll have a smart expense tracker before your next coffee break. And once you see how clean your data looks, you’ll never go back to manual sorting.
The future of personal finance isn’t more apps—it’s smarter automation. And you just built it.
If you found this helpful, consider buying me a coffee ☕ — it keeps these articles coming!
Also check out my AI tools collection: AI 次元世界 — free AI tools for developers.
🔒 Want More?
This article covers the basics. In Content Creator Ultimate Bundle (Save 33%) ($29.99), you get:
- Complete source code
- Advanced techniques
- Real-world examples
- Step-by-step tutorials
- Bonus templates
喜欢这篇文章?关注获取更多Python自动化内容!
Top comments (0)