Okay, here's a Python code for a simple command-line budget manager. It allows you to add income and expenses, view transactions, see a summary, and saves the data to a JSON file so it persists between runs.
import json
import os
import datetime
# --- Constants ---
DATA_FILE = "budget_data.json"
DATE_FORMAT = "%Y-%m-%d" # ISO format (YYYY-MM-DD)
# --- Data Handling Functions ---
def load_transactions(filename=DATA_FILE):
"""Loads transactions from a JSON file."""
if not os.path.exists(filename):
return [] # Return empty list if file doesn't exist
try:
with open(filename, 'r') as f:
data = json.load(f)
# Ensure data is a list, handle potential corruption
if not isinstance(data, list):
print(f"Warning: Data file '{filename}' is corrupted. Starting fresh.")
return []
# Optional: Validate transaction structure if needed
return data
except (json.JSONDecodeError, IOError) as e:
print(f"Error loading data from '{filename}': {e}. Starting fresh.")
return []
def save_transactions(transactions, filename=DATA_FILE):
"""Saves transactions to a JSON file."""
try:
with open(filename, 'w') as f:
json.dump(transactions, f, indent=4) # Use indent for readability
except IOError as e:
print(f"Error saving data to '{filename}': {e}")
# --- Core Budgeting Functions ---
def add_transaction(transactions):
"""Prompts user for details and adds a new transaction (income or expense)."""
while True:
trans_type = input("Enter transaction type (income/expense): ").lower().strip()
if trans_type in ['income', 'expense']:
break
else:
print("Invalid type. Please enter 'income' or 'expense'.")
description = input(f"Enter {trans_type} description: ").strip()
if not description:
print("Description cannot be empty.")
return # Don't add if description is empty
while True:
try:
amount_str = input(f"Enter {trans_type} amount: ").strip()
amount = float(amount_str)
if amount <= 0:
print("Amount must be positive.")
else:
break # Valid amount entered
except ValueError:
print("Invalid amount. Please enter a number.")
category = None
if trans_type == 'expense':
category = input("Enter expense category (optional, press Enter to skip): ").strip()
if not category:
category = "Uncategorized" # Default if empty
# Get current date
current_date = datetime.date.today().strftime(DATE_FORMAT)
transaction = {
"type": trans_type,
"description": description,
"amount": amount,
"category": category,
"date": current_date
}
transactions.append(transaction)
print(f"{trans_type.capitalize()} added successfully!")
return True # Indicate that a change was made
def view_transactions(transactions):
"""Displays all recorded transactions."""
if not transactions:
print("\nNo transactions recorded yet.")
return
print("\n--- All Transactions ---")
print(f"{'Date':<12} {'Type':<10} {'Description':<25} {'Category':<15} {'Amount':>10}")
print("-" * 75)
# Sort by date for better viewing (optional)
sorted_transactions = sorted(transactions, key=lambda x: x.get('date', ''))
for t in sorted_transactions:
date_str = t.get('date', 'N/A')
trans_type = t.get('type', 'N/A').capitalize()
desc = t.get('description', 'N/A')
cat = t.get('category', 'N/A') if trans_type == 'Expense' else ''
amount = t.get('amount', 0.0)
# Truncate long descriptions
desc_short = (desc[:22] + '...') if len(desc) > 25 else desc
print(f"{date_str:<12} {trans_type:<10} {desc_short:<25} {cat:<15} {amount:>10.2f}")
print("-" * 75)
def view_summary(transactions):
"""Calculates and displays the total income, expenses, and balance."""
total_income = 0.0
total_expenses = 0.0
expenses_by_category = {}
for t in transactions:
amount = t.get('amount', 0.0)
if t.get('type') == 'income':
total_income += amount
elif t.get('type') == 'expense':
total_expenses += amount
category = t.get('category', 'Uncategorized')
expenses_by_category[category] = expenses_by_category.get(category, 0) + amount
balance = total_income - total_expenses
print("\n--- Budget Summary ---")
print(f"Total Income: {total_income:>10.2f}")
print(f"Total Expenses: {total_expenses:>10.2f}")
print("-" * 30)
print(f"Balance: {balance:>10.2f}")
print("-" * 30)
if expenses_by_category:
print("\nExpenses by Category:")
# Sort categories by amount spent (descending)
sorted_categories = sorted(expenses_by_category.items(), key=lambda item: item[1], reverse=True)
for category, amount in sorted_categories:
print(f"- {category:<20} {amount:>10.2f}")
print("-" * 30)
# --- Main Application Logic ---
def display_menu():
"""Displays the main menu options."""
print("\n===== Budget Manager =====")
print("1. Add Income")
print("2. Add Expense")
print("3. View Transactions")
print("4. View Summary")
print("5. Exit")
print("==========================")
def main():
"""Main function to run the budget manager application."""
transactions = load_transactions()
while True:
display_menu()
choice = input("Enter your choice (1-5): ").strip()
made_change = False # Flag to track if saving is needed
if choice == '1':
# Add Income
if add_transaction(transactions):
made_change = True
elif choice == '2':
# Add Expense
if add_transaction(transactions):
made_change = True
elif choice == '3':
# View Transactions
view_transactions(transactions)
elif choice == '4':
# View Summary
view_summary(transactions)
elif choice == '5':
# Exit
print("Exiting Budget Manager. Goodbye!")
break
else:
print("Invalid choice. Please enter a number between 1 and 5.")
# Save after modification if needed
if made_change:
save_transactions(transactions)
made_change = False # Reset flag after saving
# --- Run the Application ---
if __name__ == "__main__":
main()
How to Use:
- Save: Save the code as a Python file (e.g.,
budget_manager.py).
- Run: Open a terminal or command prompt, navigate to the directory where you saved the file, and run it using:
python budget_manager.py
- Interact: Follow the menu prompts:
- Enter
1 to add income.
- Enter
2 to add an expense (you'll be asked for a category).
- Enter
3 to see a list of all entries.
- Enter
4 to see a summary (total income, expenses, balance, and expenses breakdown by category).
- Enter
5 to exit.
- Data Persistence: The data is automatically saved to a file named
budget_data.json in the same directory. When you run the script again, it will load the previous data.
Key Features:
- Add Income/Expense: Records transactions with description, amount, and date. Expenses also have categories.
- View Transactions: Lists all entries chronologically (by default, sorted by date).
- View Summary: Calculates and shows total income, total expenses, net balance, and a breakdown of expenses by category.
- Data Persistence: Uses
budget_data.json to store data, so it's saved between program runs.
- Error Handling: Basic checks for valid input (numbers for amounts, correct transaction types) and file operations.
- User-Friendly: Simple menu-driven interface.