All Projects
advanced

Expense Tracker

A comprehensive personal expense tracker with categories, budget limits, reporting, and data visualization using text-based charts.

Features
  • Add/edit/delete expenses
  • Category management
  • Monthly budgets
  • Expense reports
  • Text-based charts
  • Data export
Technologies Used
OOPFile HandlingdatetimeCollectionsData Analysis
Explanation

Models Expense and Budget using classes. Tracks spending by category, compares against budgets, and generates text-based bar charts for visualization.

Source Code
import json
import os
from datetime import datetime
from collections import defaultdict

class Expense:
    def __init__(self, amount, category, description, date=None):
        self.amount = amount
        self.category = category
        self.description = description
        self.date = date or datetime.now().strftime("%Y-%m-%d")

    def to_dict(self):
        return vars(self)

class ExpenseTracker:
    def __init__(self, filename="expenses.json"):
        self.filename = filename
        self.expenses = self._load()
        self.budgets = {}

    def _load(self):
        if os.path.exists(self.filename):
            with open(self.filename) as f:
                return [Expense(**e) for e in json.load(f)]
        return []

    def _save(self):
        with open(self.filename, "w") as f:
            json.dump([e.to_dict() for e in self.expenses], f, indent=2)

    def add_expense(self):
        amount = float(input("Amount: ₹"))
        category = input("Category (food/transport/entertainment/bills/other): ")
        desc = input("Description: ")
        self.expenses.append(Expense(amount, category, desc))
        self._save()
        print(f"✅ Expense of ₹{amount} added!")

        # Budget warning
        if category in self.budgets:
            spent = sum(e.amount for e in self.expenses
                       if e.category == category and e.date[:7] == datetime.now().strftime("%Y-%m"))
            if spent > self.budgets[category]:
                print(f"⚠️  Warning: Budget exceeded for {category}! (₹{spent}/₹{self.budgets[category]})")

    def set_budget(self):
        category = input("Category: ")
        amount = float(input(f"Monthly budget for {category}: ₹"))
        self.budgets[category] = amount
        print(f"✅ Budget set: {category} = ₹{amount}/month")

    def monthly_report(self):
        month = input("Month (YYYY-MM) or press Enter for current: ") or datetime.now().strftime("%Y-%m")
        monthly = [e for e in self.expenses if e.date[:7] == month]

        if not monthly:
            print(f"No expenses for {month}")
            return

        by_category = defaultdict(float)
        for e in monthly:
            by_category[e.category] += e.amount

        total = sum(by_category.values())
        print(f"\n--- Report for {month} ---")
        print(f"Total: ₹{total:.2f}\n")

        max_amount = max(by_category.values())
        for cat, amount in sorted(by_category.items(), key=lambda x: -x[1]):
            bar_len = int((amount / max_amount) * 30)
            bar = "█" * bar_len
            pct = (amount / total) * 100
            print(f"  {cat:15s} ₹{amount:8.2f} ({pct:5.1f}%) {bar}")

    def view_expenses(self):
        for e in self.expenses[-10:]:
            print(f"  {e.date} | {e.category:12s} | ₹{e.amount:8.2f} | {e.description}")

def main():
    tracker = ExpenseTracker()
    while True:
        print("\n1.Add 2.View 3.Report 4.Set Budget 5.Exit")
        ch = input("Choice: ")
        if ch == "1": tracker.add_expense()
        elif ch == "2": tracker.view_expenses()
        elif ch == "3": tracker.monthly_report()
        elif ch == "4": tracker.set_budget()
        elif ch == "5": break

main()