Budget Tracker App Project in Python

← Back to Projects

Budget Tracker Application in Python (Console-Based Project)

About the project:
This project demonstrates how to build a console-based budget tracker application using Python. It allows users to record income and expenses, calculate their current balance, and store transaction history persistently.

The application uses a local JSON file to save financial data, ensuring that all records remain available even after the program is closed and reopened.

This project is designed for learners who want to practice file handling, data structures, and basic financial logic in Python.

You can run it, and it will guide you through adding new transactions and viewing your summary.

To use it, just save the code as a Python file and run it from your terminal. The budget_data.json file will be created automatically in the same directory.


Project Level: Intermediate


How the Budget App Works

  • The program loads existing budget data from a JSON file
  • Users can add income or expense transactions
  • Each transaction updates the total balance
  • All transactions are stored with timestamps
  • The data is saved automatically when the program exits

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# budget_app.py

import json
import os
from datetime import datetime

# Filename for storing budget data
BUDGET_FILE = "budget_data.json"

def load_data():
    """
    Loads budget data (transactions and balance) from a JSON file.
    Returns a dictionary with 'balance' and 'transactions' keys.
    If the file doesn't exist, it returns a new, empty data structure.
    """
    if os.path.exists(BUDGET_FILE) and os.stat(BUDGET_FILE).st_size > 0:
        try:
            with open(BUDGET_FILE, 'r') as f:
                return json.load(f)
        except json.JSONDecodeError:
            print("Warning: Budget file is corrupted or empty. Starting a new budget.")
            return {"balance": 0.0, "transactions": []}
    return {"balance": 0.0, "transactions": []}

def save_data(data):
    """
    Saves the budget data dictionary to a JSON file.
    """
    with open(BUDGET_FILE, 'w') as f:
        json.dump(data, f, indent=4)
    print("Budget data saved successfully.")

def add_transaction(data, transaction_type):
    """
    Prompts the user for a new transaction and adds it to the data.
    """
    description = input(f"Enter description for {transaction_type}: ").strip()
    if not description:
        print("Description cannot be empty. Transaction not added.")
        return

    try:
        amount = float(input(f"Enter amount for {transaction_type}: ").strip())
        if amount <= 0:
            print("Amount must be a positive number.")
            return

        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        transaction = {
            "type": transaction_type,
            "description": description,
            "amount": amount,
            "timestamp": timestamp
        }

        # Update the balance
        if transaction_type == "income":
            data['balance'] += amount
        elif transaction_type == "expense":
            data['balance'] -= amount
        
        # Add the transaction to the list
        data['transactions'].append(transaction)
        
        print(f"{transaction_type.capitalize()} of ${amount:.2f} added.")
    except ValueError:
        print("Invalid amount. Please enter a number.")

def view_summary(data):
    """
    Displays the current balance and all transaction history.
    """
    print("\n--- Budget Summary ---")
    print(f"Current Balance: ${data['balance']:.2f}")
    
    if not data['transactions']:
        print("\nNo transactions recorded yet.")
        return
    
    print("\nTransaction History:")
    for transaction in data['transactions']:
        trans_type = transaction.get('type', 'N/A').capitalize()
        description = transaction.get('description', 'N/A')
        amount = transaction.get('amount', 0)
        date_time = transaction.get('timestamp', 'N/A')

        if trans_type.lower() == 'expense':
            print(f"- {date_time} | {trans_type}: ${amount:.2f} | {description}")
        else:
            print(f"+ {date_time} | {trans_type}: ${amount:.2f} | {description}")

    print("----------------------")

def main():
    """
    Main function to run the Budget App with a menu.
    """
    data = load_data()

    print("--- Python Budget App ---")

    while True:
        print("\nMenu:")
        print("1. Add Income")
        print("2. Add Expense")
        print("3. View Summary")
        print("4. Quit and Save")

        choice = input("Enter your choice (1-4): ").strip()

        if choice == '1':
            add_transaction(data, "income")
        elif choice == '2':
            add_transaction(data, "expense")
        elif choice == '3':
            view_summary(data)
        elif choice == '4':
            save_data(data)
            print("Exiting Budget App. Goodbye!")
            break
        else:
            print("Invalid choice. Please enter a number between 1 and 4.")

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()





What You Will Learn From This Project

  • How to read and write JSON files in Python
  • How to build a menu-driven console application
  • How to store and process financial data
  • How to work with dates and timestamps
  • How to structure a real-world Python project

Limitations and Notes

This project is intended for learning purposes only. It does not include advanced features such as budgeting categories, data encryption, or multi-user support.

For real-world financial applications, additional security and validation mechanisms are required.


Ideas to Extend This Project

  • Add monthly budgeting categories
  • Export transactions to CSV
  • Add graphical charts using Matplotlib
  • Create a GUI version using Tkinter
  • Store data in a database instead of JSON



← Back to Projects