Personal Budget Tracker in Python



Personal budget tracker is used to manage your income and expenses. Here, we will create personal budget tracker in Python using different approaches.

Simple Budget Tracker Using Dictionaries

Dictionaries are the most convenient form of working with sets of values, therefore, our income and expenses will be managed in the same manner. This method makes it easy for us to classify our financial data and normal tasks such as entry of new data, computation of totals and preparation of summary can be done effortlessly.

Implementation

We create two dictionaries: one for income and one for expenses. Every type (like "Salary" or "Rent") is key in the dictionary, and the every corresponding amount is the value. This allows us to categorize and sum our income and expenses easily.

Code

# Simple Budget Tracker Using Dictionaries

class BudgetTracker:
   def __init__(self):
      self.income = {}
      self.expenses = {}

   def add_income(self, amount, category):
      if category in self.income:
         self.income[category] += amount
      else:
         self.income[category] = amount

   def add_expense(self, amount, category):
      if category in self.expenses:
         self.expenses[category] += amount
      else:
         self.expenses[category] = amount

   def get_total_income(self):
      return sum(self.income.values())

   def get_total_expenses(self):
      return sum(self.expenses.values())

   def display_summary(self):
      print('Income Summary:')
      for category, amount in self.income.items():
         print(f'{category}: ${amount}')
      print('Total Income:', self.get_total_income())

      print('Expenses Summary:')
      for category, amount in self.expenses.items():
         print(f'{category}: ${amount}')
      print('Total Expenses:', self.get_total_expenses())

      print('Net Savings:', self.get_total_income() - self.get_total_expenses())

# Example Usage
tracker = BudgetTracker()
tracker.add_income(5000, 'Salary')
tracker.add_income(200, 'Freelance')
tracker.add_expense(1500, 'Rent')
tracker.add_expense(200, 'Groceries')
tracker.add_expense(100, 'Utilities')
tracker.display_summary()

Output

Income Summary:
Salary: $5000
Freelance: $200
Total Income: 5200
Expenses Summary:
Rent: $1500
Groceries: $200
Utilities: $100
Total Expenses: 1800
Net Savings: 3400

Summary

The script prints out a summary of all income and expenses, along with the total income, total expenses, and net savings (income minus expenses).

Budget Tracker Using Object-oriented Concepts

We implement OOP principles into our budget tracker in order to improve its modularity. In other words, it helps to organize the data and the functionality into an easily understandable form and easily reuse them. This approach also facilitates easy management, modification and scalability in future hence meets the modern learning institution’s needs.

Implementation

We frame a Transaction class to represent each income or expense entry, with attributes for the amount and category.The BudgetTracker class contains lists of Transaction objects for income and expenses. Methods are provided to add income or expenses, calculate totals, and display a summary.

Code

# Object-Oriented Budget Tracker

class Transaction:
   def __init__(self, amount, category):
      self.amount = amount
      self.category = category

class BudgetTracker:
   def __init__(self):
      self.income = []
      self.expenses = []

   def add_income(self, amount, category):
      self.income.append(Transaction(amount, category))

   def add_expense(self, amount, category):
      self.expenses.append(Transaction(amount, category))

   def get_total_income(self):
      return sum([transaction.amount for transaction in self.income])

   def get_total_expenses(self):
     return sum([transaction.amount for transaction in self.expenses])

   def display_summary(self):
      print('Income Summary:')
      for transaction in self.income:
         print(f'{transaction.category}: ${transaction.amount}')
      print('Total Income:', self.get_total_income())

      print('Expenses Summary:')
      for transaction in self.expenses:
         print(f'{transaction.category}: ${transaction.amount}')
      print('Total Expenses:', self.get_total_expenses())

      print('Net Savings:', self.get_total_income() - self.get_total_expenses())

# Example Usage
tracker = BudgetTracker()
tracker.add_income(5000, 'Salary')
tracker.add_income(200, 'Freelance')
tracker.add_expense(1500, 'Rent')
tracker.add_expense(200, 'Groceries')
tracker.add_expense(100, 'Utilities')
tracker.display_summary()

Output

Income Summary:
Salary: $5000
Freelance: $200
Total Income: 5200
Expenses Summary:
Rent: $1500
Groceries: $200
Utilities: $100
Total Expenses: 1800
Net Savings: 3400

Summary

The script prints out each transaction's details and the totals, similar to First Approach.

Advanced Budget Tracker Using File Handling

In this method, the functionality of the budget tracker will be extended, in particular file handling capabilities will be implemented. This enables the user to store and retrieve data, in other words make the budget tracker to be used in more than one session.

Code

# Advanced Budget Tracker with File Handling

import json

class BudgetTracker:
   def __init__(self):
      self.income = {}
      self.expenses = {}

   def add_income(self, amount, category):
      if category in self.income:
         self.income[category] += amount
      else:
         self.income[category] = amount

   def add_expense(self, amount, category):
      if category in self.expenses:
         self.expenses[category] += amount
      else:
         self.expenses[category] = amount

   def save_to_file(self, filename):
      data = {
         'income': self.income,
         'expenses': self.expenses
      }
      with open(filename, 'w') as file:
         json.dump(data, file)

   def load_from_file(self, filename):
      with open(filename, 'r') as file:
         data = json.load(file)
         self.income = data['income']
         self.expenses = data['expenses']

   def get_total_income(self):
      return sum(self.income.values())

   def get_total_expenses(self):
      return sum(self.expenses.values())

   def display_summary(self):
      print('Income Summary:')
      for category, amount in self.income.items():
         print(f'{category}: ${amount}')
      print('Total Income:', self.get_total_income())

      print('Expenses Summary:')
      for category, amount in self.expenses.items():
         print(f'{category}: ${amount}')
      print('Total Expenses:', self.get_total_expenses())

      print('Net Savings:', self.get_total_income() - self.get_total_expenses())

# Example Usage
tracker = BudgetTracker()
tracker.add_income(5000, 'Salary')
tracker.add_income(200, 'Freelance')
tracker.add_expense(1500, 'Rent')
tracker.add_expense(200, 'Groceries')
tracker.add_expense(100, 'Utilities')
tracker.save_to_file('budget_data.json')

# Load and display the summary
tracker.load_from_file('budget_data.json')
tracker.display_summary()

Output

Income Summary:
Salary: $5000
Freelance: $200
Total Income: 5200
Expenses Summary:
Rent: $1500
Groceries: $200
Utilities: $100
Total Expenses: 1800
Net Savings: 3400

Summary

In this output, the budget tracker can save and load data from a file.

Interactive Budget Tracker with User Input and File Handling

In this approach, the budget tracker will be enriched with the interactive user input option of income and expense addition. The user can now provide the information directly via the console which has greatly increased application's dynamism and everyday usefulness.

Explanation

The user_input() method gives a menu-driven interface that facilitates income addition, expenses addition, saving the data to a file, loading the data from a file, or program exit.

The user can, through the console, input amounts and categories thus making the budget tracker more interactive.

MENU OPTION: Add Income Add Expense Save Load Exit

Code

import json

class BudgetTracker:
   def __init__(self):
      self.income = {}
      self.expenses = {}

   def add_income(self, amount, category):
      if category in self.income:
         self.income[category] += amount
      else:
         self.income[category] = amount

   def add_expense(self, amount, category):
      if category in self.expenses:
         self.expenses[category] += amount
      else:
         self.expenses[category] = amount

   def save_to_file(self, filename):
      data = {
         'income': self.income,
         'expenses': self.expenses
      }
      with open(filename, 'w') as file:
         json.dump(data, file)

   def load_from_file(self, filename):
      try:
         with open(filename, 'r') as file:
            data = json.load(file)
            self.income = data['income']
            self.expenses = data['expenses']
            print(f"Data loaded successfully from {filename}.")
      except FileNotFoundError:
         print(f"Error: The file '{filename}' does not exist. Please check the filename and try again.")

   def get_total_income(self):
      return sum(self.income.values())

   def get_total_expenses(self):
      return sum(self.expenses.values())

   def display_summary(self):
      print('Income Summary:')
      for category, amount in self.income.items():
         print(f'{category}: ${amount}')
      print('Total Income:', self.get_total_income())

      print('Expenses Summary:')
      for category, amount in self.expenses.items():
         print(f'{category}: ${amount}')
      print('Total Expenses:', self.get_total_expenses())

      print('Net Savings:', self.get_total_income() - self.get_total_expenses())

   def user_input(self):
      print("Welcome to the Budget Tracker!")
      print("You can use the following categories or create your own:")
      print("  - Income: Salary, Freelance, Investments")
      print("  - Expenses: Rent, Groceries, Utilities, Entertainment")

      while True:
         action = input("\nWhat would you like to do? (Add Income/Add Expense/Save/Load/Exit): ").lower()
         if action == 'add income':
            amount = float(input("Enter the amount (e.g., 5000): "))
            category = input("Enter the category (e.g., Salary, Freelance): ")
            self.add_income(amount, category)
            print(f"Added income: ${amount} under '{category}' category.")
         elif action == 'add expense':
            amount = float(input("Enter the amount (e.g., 1500): "))
            category = input("Enter the category (e.g., Rent, Groceries): ")
            self.add_expense(amount, category)
            print(f"Added expense: ${amount} under '{category}' category.")
         elif action == 'save':
            filename = input("Enter the filename to save data (e.g., my_budget.json): ")
            self.save_to_file(filename)
            print(f"Data saved successfully to '{filename}'.")
         elif action == 'load':
            filename = input("Enter the filename to load data (e.g., my_budget.json): ")
            self.load_from_file(filename)
         elif action == 'exit':
            print("Exiting the Budget Tracker. Goodbye!")
            break
         else:
            print("Invalid action. Please try again.")

# Example Usage
tracker = BudgetTracker()
tracker.user_input()

Output

Budget Tracker

After that it will create Load −

Budget Tracker

Summary

This program will very interactively lead the user through alternatives and show summaries based on user's choices. The data will be a permanent factor due to the fact that the file will be handled.

python_projects_from_basic_to_advanced.htm
Advertisements