Post

Expense Tracker

Python Expense Tracker

In the hustle and bustle of daily life, it’s easy to lose track of where our hard-earned money is going. Whether it’s those daily coffee runs or impromptu shopping sprees, small expenses can quickly add up and throw our budget off balance. That’s where having an expense tracker comes in handy. And what better way to keep tabs on your spending than by creating your very own expense tracker with Python?

Importing Modules and Defining Main Function:

1
2
3
4
5
6
7
8
9
10
from expense import Expense
import calendar
import datetime

def main():
    expense_file_path = "expenses.csv"
    budget = 2000
    expense = get_user_expense()
    save_expense_to_file(expense, expense_file_path)
    summarize_expenses(expense_file_path, budget)
  • Expense Input: The get_user_expense() function prompts the user to input the expense name, amount, and category. Categories are predefined with emojis for easy identification.
  • Saving to File: The save_expense_to_file() function saves the user’s expense details to a CSV file named expenses.csv.
  • Summarizing Expenses: The summarize_expenses() function reads the expenses from the CSV file, calculates total spending, categorizes expenses, and provides a summary including total spent, remaining budget, and daily budget allowance.

Getting User Expense Input Function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def get_user_expense():
    expense_name = input("Enter expense name: ")
    expense_amount = float(input("Enter expense amount: "))
    expense_categories = [
        "🎂Food", 
        "🏡Home", 
        "🏬Work", 
        "😀Fun", 
        "🎈Misc"
    ]
    while True:
        print("Select a category: ")
        for i, category_name in enumerate(expense_categories):
            print(f" {i+1}. {category_name}")

        selected_index = int(input("Enter a category number [1-5]: ")) -1 

        if selected_index in range(len(expense_categories)):
            selected_category = expense_categories[selected_index]
            new_expense = Expense(name=expense_name, category=selected_category, amount=expense_amount)
            return new_expense
        else:
            print("Invalid selection. Please try another!")

Saving Expense to File Function:

1
2
3
def save_expense_to_file(expense: Expense, expense_file_path):
    with open(expense_file_path, "a", encoding="utf-8") as f:
        f.write(f"{expense.name},{expense.amount},{expense.category}\n")

Summarizing Expenses Function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def summarize_expenses(expense_file_path, budget):
    expenses = []
    with open(expense_file_path, "r", encoding="utf-8") as f:
        lines = f.readlines()
        for line in lines:
            expense_name, expense_amount, expense_category = line.strip().split(",")
            line_expense = Expense(
                name=expense_name, amount=float(expense_amount), category=expense_category
            )
            expenses.append(line_expense)
    
    amount_by_category = {}
    for expense in expenses:
        key = expense.category
        if key in amount_by_category:
            amount_by_category[key] += expense.amount
        else:
            amount_by_category[key] = expense.amount

    print("Expenses By Category 📈:")
    for key, amount in amount_by_category.items():
        print(f"  {key}: ${amount:.2f}")

    total_spent = sum([x.amount for x in expenses])
    print(f"You've spent ${total_spent:.2f} this month!")

    remaining_budget = budget - total_spent
    print(f"Budget Remaining: ${remaining_budget:.2f}")

    now = datetime.datetime.now()
    days_in_month = calendar.monthrange(now.year, now.month)[1]
    remaining_days = days_in_month - now.day 
    daily_budget = remaining_budget / remaining_days
    print(f"Budget per day is {daily_budget:.2f}")

You can easily customize this code to fit your specific needs. Here are a few ideas:

  • Custom Categories: Modify the expense_categories list to add or remove categories according to your spending habits.
  • Enhanced Tracking: Expand the functionality to track expenses over multiple months or years by modifying the file handling and summary calculation accordingly.
  • Graphical Representation: Integrate libraries like Matplotlib to visualize your spending habits over time.

Conclusion

Tracking your expenses is an essential part of financial management, and with this simple Python expense tracker, you have a powerful tool at your disposal. By understanding where your money is going, you can make more informed decisions and work towards achieving your financial goals. So why not give it a try and take control of your finances today? Happy tracking! 📊💰

This post is licensed under CC BY 4.0 by the author.