Build a Budget Tracker and Expense Analyzer
Knowing where your money goes is one of the most useful things you can do with data. In this project, you'll build a budget analyzer that takes a list of expenses, categorizes them, compares spending to budget limits, and generates a report with practical recommendations.
This is a great project because the same logic applies whether you're tracking personal spending, a department budget, or a company's operating costs. The scale changes, but the analysis stays the same.
Step 1: Create the Expense Data
Our dataset is a month of personal expenses. Each entry has a date, a description, an amount, and a category. We'll also define monthly budget limits for each category.
Create an expense DataFrame from the provided dictionary and:
1. Convert the date column to datetime
2. Print the total number of expenses
3. Print the total amount spent (formatted to 2 decimal places)
4. Print the average expense amount
5. Print the most expensive single expense (description and amount)
Format:
Total expenses: 8
Total spent: $XXX.XX
Average expense: $XX.XX
Largest expense: DESCRIPTION ($XX.XX)import pandas as pd
expenses = {
'date': ['2024-03-01', '2024-03-05', '2024-03-08', '2024-03-12',
'2024-03-15', '2024-03-20', '2024-03-25', '2024-03-28'],
'description': ['Grocery store', 'Gas station', 'Restaurant',
'Phone bill', 'Gym', 'Movie tickets',
'Grocery store', 'Electric bill'],
'amount': [85.50, 45.00, 62.30, 65.00, 40.00, 28.00, 92.15, 120.00]
}
# Create DataFrame and print summary
Step 2: Categorize Expenses
Raw expense descriptions are messy. "Grocery store" and "Gas station" need to be mapped to budget categories like "Food" and "Transport." We'll build a mapping function that assigns each expense to its category.
Write a function categorize_expense(description) that maps expense descriptions to categories using keyword matching:
Then apply it to the DataFrame to create a category column, and print how many expenses are in each category.
import pandas as pd
def categorize_expense(description):
# Your code here
pass
expenses = {
'description': ['Grocery store', 'Electric bill', 'Coffee shop',
'Gas station', 'Restaurant', 'Movie tickets',
'Phone bill', 'Gym membership', 'Uber ride',
'Streaming service'],
'amount': [85.50, 120.00, 6.75, 45.00, 62.30, 28.00, 65.00, 40.00, 22.00, 15.99]
}
df = pd.DataFrame(expenses)
df['category'] = df['description'].apply(categorize_expense)
print(df[['description', 'category']].to_string(index=False))
print(f'\nExpenses per category:')
print(df['category'].value_counts().to_string())Step 3: Calculate Totals by Category
Now that every expense has a category, we can calculate how much was spent in each category. This is the core of budget analysis: grouping expenses and summing them up.
Write a function spending_by_category(df) that:
1. Groups by the category column
2. Calculates total spending, number of transactions, and average transaction amount per category
3. Sorts by total spending (highest first)
4. Returns the result as a DataFrame with columns: total, count, average
Print the result.
import pandas as pd
def spending_by_category(df):
# Your code here
pass
data = {
'category': ['Food', 'Food', 'Food', 'Utilities', 'Utilities',
'Transport', 'Transport', 'Entertainment', 'Health'],
'amount': [85.50, 62.30, 6.75, 120.00, 65.00, 45.00, 22.00, 28.00, 40.00]
}
df = pd.DataFrame(data)
result = spending_by_category(df)
print(result)Step 4: Compare Spending to Budget Limits
Having spending totals is useful, but the real insight comes from comparing them to your budget. Are you over or under in each category? By how much? This is where the analysis becomes actionable.
Write a function compare_to_budget(spending_totals, budget_limits) that:
category, spent, budget, difference, statusdifference is budget - spent (positive = under budget, negative = over)status is "Under" if difference >= 0, else "OVER"Print each category's status.
import pandas as pd
def compare_to_budget(spending_totals, budget_limits):
# Your code here
pass
spending = {'Food': 450.00, 'Utilities': 255.00, 'Transport': 120.00,
'Entertainment': 139.99, 'Health': 52.50}
budget = {'Food': 400.00, 'Utilities': 300.00, 'Transport': 150.00,
'Entertainment': 100.00, 'Health': 75.00}
results = compare_to_budget(spending, budget)
for r in results:
print(f'{r["category"]}: ${r["spent"]:.2f} / ${r["budget"]:.2f} [{r["status"]}]')Step 5: Identify Overspending Patterns
Knowing you're over budget is step one. Step two is understanding why. Let's dig into the categories where spending exceeded the budget and find the specific expenses responsible.
Write a function find_overspending(df, budget_limits) that:
1. Calculates total spending per category
2. Identifies categories that are over budget
3. For each over-budget category, finds the largest single expense in that category
4. Prints the overspending details
Format for each over-budget category:
OVER BUDGET: CATEGORY ($SPENT / $BUDGET)
Biggest expense: DESCRIPTION ($AMOUNT)If no categories are over budget, print: All categories within budget!
import pandas as pd
def find_overspending(df, budget_limits):
# Your code here
pass
data = {
'description': ['Grocery store', 'Restaurant', 'Coffee', 'Electric bill',
'Movie tickets', 'Concert', 'Gas station'],
'category': ['Food', 'Food', 'Food', 'Utilities',
'Entertainment', 'Entertainment', 'Transport'],
'amount': [120.00, 85.00, 25.00, 150.00, 45.00, 95.00, 40.00]
}
df = pd.DataFrame(data)
budget = {'Food': 200.00, 'Utilities': 300.00, 'Entertainment': 100.00, 'Transport': 150.00}
find_overspending(df, budget)Step 6: Generate the Budget Report
The final step is putting everything together into a complete budget report with recommendations. A good budget report tells you what happened, highlights the problems, and suggests what to do about them.
Write a function budget_report(df, budget_limits) that prints a complete budget report:
1. Header: "MONTHLY BUDGET REPORT" with = separators
2. Overview: Total spent, total budget, and overall status
3. Category breakdown: Each category showing spent vs budget and status
4. Recommendations: For each over-budget category, suggest reducing spending
Use this exact format:
==============================
MONTHLY BUDGET REPORT
==============================
Total Spent: $XXX.XX
Total Budget: $XXX.XX
Status: Under budget / OVER BUDGET
------------------------------
Category Breakdown:
Food: $XXX.XX / $XXX.XX [STATUS]
...
------------------------------
Recommendations:
- Reduce CATEGORY spending by $XX.XX
==============================import pandas as pd
def budget_report(df, budget_limits):
# Your code here
pass
data = {
'description': ['Grocery store', 'Restaurant', 'Electric bill',
'Movie tickets', 'Concert', 'Gas station', 'Gym'],
'category': ['Food', 'Food', 'Utilities',
'Entertainment', 'Entertainment', 'Transport', 'Health'],
'amount': [120.00, 85.00, 150.00, 45.00, 95.00, 40.00, 30.00]
}
df = pd.DataFrame(data)
budget = {'Food': 200.00, 'Utilities': 300.00, 'Entertainment': 100.00,
'Transport': 150.00, 'Health': 75.00}
budget_report(df, budget)What You Built
| You built a complete budget tracking and analysis system: | ||
|---|---|---|
| --- | --- | --- |
| Data loading | Create and inspect expense data | pd.DataFrame(), basic stats |
| Categorization | Map descriptions to budget categories | Keyword matching, .apply() |
| Totals | Sum spending by category | .groupby().agg() |
| Comparison | Check against budget limits | Dictionary lookups, conditions |
| Overspending | Identify and drill into problems | Filtering, .idxmax() |
| Reporting | Generate formatted report | f-string formatting |
The keyword-based categorization and budget comparison pattern is the foundation of financial analysis tools. Professional budgeting software works on the same principles, just at a larger scale.