Create the Finance Tracker
Create a file named finance_tracker.py
and add the following code:
pythonCopy codeimport json
import os
class FinanceTracker:
def __init__(self, filename='finance_data.json'):
self.filename = filename
self.transactions = self.load_data()
def load_data(self):
if os.path.exists(self.filename):
with open(self.filename, 'r') as file:
return json.load(file)
return []
def save_data(self):
with open(self.filename, 'w') as file:
json.dump(self.transactions, file)
def add_transaction(self, amount, category, description):
transaction = {
'amount': amount,
'category': category,
'description': description
}
self.transactions.append(transaction)
self.save_data()
print("Transaction added!")
def view_transactions(self):
if not self.transactions:
print("No transactions found.")
return
print("\nTransactions:")
for i, transaction in enumerate(self.transactions, 1):
print(f"{i}. {transaction['amount']} - {transaction['category']}: {transaction['description']}")
def summarize(self):
total_income = sum(t['amount'] for t in self.transactions if t['amount'] > 0)
total_expense = sum(t['amount'] for t in self.transactions if t['amount'] < 0)
balance = total_income + total_expense
print(f"\nTotal Income: {total_income}")
print(f"Total Expense: {total_expense}")
print(f"Balance: {balance}")
def main():
tracker = FinanceTracker()
while True:
print("\nPersonal Finance Tracker")
print("1. Add Transaction")
print("2. View Transactions")
print("3. Summarize")
print("4. Exit")
choice = input("Choose an option (1-4): ")
if choice == '1':
amount = float(input("Enter the transaction amount (use negative for expenses): "))
category = input("Enter the transaction category: ")
description = input("Enter a description: ")
tracker.add_transaction(amount, category, description)
elif choice == '2':
tracker.view_transactions()
elif choice == '3':
tracker.summarize()
elif choice == '4':
print("Exiting the tracker.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
Step 2: Running the Finance Tracker
- Open your terminal (or command prompt).
- Navigate to the directory where you saved
finance_tracker.py
. - Run the script using the command:bashCopy code
python finance_tracker.py
Features of the Tracker
- Add Transaction: You can add income or expense transactions. Income should be entered as a positive amount, while expenses should be negative.
- View Transactions: Displays all recorded transactions with their details.
- Summarize: Provides a summary of total income, total expenses, and the overall balance.
- Data Persistence: Transactions are saved in a JSON file (
finance_data.json
) so that you can access them even after closing the application.
Leave a Reply