Budget App Project (code) in Python

← Back to Projects

Budget App in Python.

About the project: This is to create a project for a Budget App in Python. This will be self-contained script that helps you track your income and expenses.

This program will be a console-based application that allows you to add income and expenses, and then view your current balance and transaction history.

The data will be saved to a file, so your records are persistent between sessions.

This Python script is a complete and interactive Budget App that stores your data in a JSON file.

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

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()





← Back to Projects