Simple Personal Finance Tracker in Python
First, make sure you have Python installed on your system. You can use any text editor or IDE to write your code.
Code
import json
class FinanceTracker:
def __init__(self, filename='finance_data.json'):
self.filename = filename
self.load_data()
def load_data(self):
try:
with open(self.filename, 'r') as f:
self.data = json.load(f)
except FileNotFoundError:
self.data = {'income': 0, 'expenses': [], 'balance': 0}
def save_data(self):
with open(self.filename, 'w') as f:
json.dump(self.data, f)
def add_income(self, amount):
self.data['income'] += amount
self.update_balance()
self.save_data()
def add_expense(self, amount, description):
self.data['expenses'].append({'amount': amount, 'description': description})
self.update_balance()
self.save_data()
def update_balance(self):
total_expenses = sum(expense['amount'] for expense in self.data['expenses'])
self.data['balance'] = self.data['income'] - total_expenses
def view_summary(self):
print(f"Total Income: ${self.data['income']}")
print("Expenses:")
for expense in self.data['expenses']:
print(f" - ${expense['amount']} for {expense['description']}")
print(f"Balance: ${self.data['balance']}")
def main():
tracker = FinanceTracker()
while True:
print("\nPersonal Finance Tracker")
print("1. Add Income")
print("2. Add Expense")
print("3. View Summary")
print("4. Exit")
choice = input("Select an option: ")
if choice == '1':
amount = float(input("Enter income amount: "))
tracker.add_income(amount)
elif choice == '2':
amount = float(input("Enter expense amount: "))
description = input("Enter expense description: ")
tracker.add_expense(amount, description)
elif choice == '3':
tracker.view_summary()
elif choice == '4':
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
How to Run the Code
The data will be saved in a file named finance_data.json
in the same directory, allowing you to track your finances over time.
Copy the Code: Copy the code above into a new file called finance_tracker.py
.
Run the Script: Open a terminal (or command prompt), navigate to the directory where you saved the file, and run:
python finance_tracker.py
Interact with the Tracker:
Choose options to add income, add expenses, or view your financial summary.
Leave a Reply