Personal Finance Tracker
Advanced Project
Track expenses and balance using OOP, JSON, datetime, and error handling.
Project Overview
Goal: Track income, expenses, and generate reports.
Concepts: File I/O, datetime, JSON, formatting, error handling.
Key Features:
- โข Add income and expenses
- โข Categorize transactions
- โข Generate monthly reports
- โข Calculate savings rate
- โข Budget warnings
- โข Data visualization (optional)
Technologies & Concepts:
Starter Code
๐ก This full interactive version uses input() which requires a local Python environment.Jump to the Browser Demo below to see a simplified version running in your browser.
import json
import datetime
from pathlib import Path
class FinanceTracker:
def __init__(self, filename="finance.json"):
self.filename = filename
self.data = self.load_data()
def load_data(self):
"""Load existing data or create new structure"""
try:
with open(self.filename) as f:
return json.load(f)
except FileNotFoundError:
return {"transactions": [], "balance": 0}
def save_data(self):
"""Save data to JSON file"""
with open(self.filename, "w") as f:
json.dump(self.data, f, indent=2)
def add_transaction(self, amount, description, category="General"):
"""Add income (positive) or expense (negative)"""
transaction = {
"amount": amount,
"description": description,
"category": category,
"date": datetime.date.today().isoformat()
}
self.data["transactions"].append(transaction)
self.data["balance"] += amount
self.save_data()
emoji = "๐ฐ" if amount > 0 else "๐ธ"
print(f"{emoji} Added: {description} ({amount:,.2f})")
def show_balance(self):
"""Display current balance"""
balance = self.data["balance"]
color = "green" if balance >= 0 else "red"
print(f"๐ต Current Balance: {balance:,.2f}")
def show_transactions(self, limit=10):
"""Show recent transactions"""
transactions = self.data["transactions"][-limit:]
print(f"๐ Recent Transactions (Last {limit}):")
for t in transactions:
amount = t["amount"]
sign = "+" if amount > 0 else ""
print(f" {t['date']} | {t['description']:20} | {sign}{amount:,.2f} | {t['category']}")
def monthly_report(self, month=None):
"""Generate report for specific month"""
if month is None:
month = datetime.date.today().strftime("%Y-%m")
monthly_txns = [t for t in self.data["transactions"]
if t["date"].startswith(month)]
income = sum(t["amount"] for t in monthly_txns if t["amount"] > 0)
expenses = sum(t["amount"] for t in monthly_txns if t["amount"] < 0)
print(f"๐ Report for {month}")
print(f" Income: {income:,.2f}")
print(f" Expenses: {abs(expenses):,.2f}")
print(f" Net: {income + expenses:,.2f}")
# Example usage
tracker = FinanceTracker()
tracker.add_transaction(1000, "Salary", "Income")
tracker.add_transaction(-50, "Groceries", "Food")
tracker.add_transaction(-30, "Netflix", "Entertainment")
tracker.add_transaction(200, "Freelance work", "Income")
tracker.show_balance()
tracker.show_transactions()
tracker.monthly_report()To run this locally: Save as finance_tracker.py and run python finance_tracker.py
Browser Demo (Simplified Version)
This version demonstrates the core functionality without requiring user input. Click "Run" to see it in action!
Finance Tracker Demo
from datetime import datetime
class FinanceTracker:
def __init__(self):
self.transactions = []
self.balance = 0
def add_transaction(self, amount, description, category="General"):
"""Add income (positive) or expense (negative)"""
transaction = {
"amount": amount,
"description": description,
"category": category,
"date": datetime.now().strftime("%Y-%m-%d")
}
self.transactions.append(trans
...Enhancement Ideas ๐
1. Budget System
Set monthly budgets for categories and get warnings when approaching limits.
2. Data Visualization
Use matplotlib to create charts showing spending by category over time.
3. Recurring Transactions
Add support for recurring monthly expenses (rent, subscriptions).
4. Multi-Currency Support
Track transactions in different currencies with automatic conversion.
5. Export to CSV/Excel
Allow exporting transaction history for analysis in spreadsheet software.
Next Steps
- Test the tracker with sample transactions
- Add category management (add/edit/delete categories)
- Implement search and filter functionality
- Create yearly comparison reports
- Add data visualization with charts
- Build a budget tracking system
- Consider adding user authentication for privacy