Skip to content

Commit b674155

Browse files
Implement basic expense tracking
1 parent 817ebb8 commit b674155

File tree

2 files changed

+160
-0
lines changed

2 files changed

+160
-0
lines changed

Personal-Expense-Tracker/README.md

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Personal Expense Tracker CLI
2+
3+
This is a basic command-line interface (CLI) application built with Python to help you track your daily expenses. It allows you to easily add your expenditures, categorize them, and view your spending patterns over different time periods.
4+
5+
## Features
6+
7+
* **Add New Expense:** Record new expenses by providing the amount, category (e.g., food, travel, shopping, bills), date, and an optional note.
8+
* **View Expenses:** Display your expenses for a specific day, week, month, or all recorded expenses.
9+
* **Filter by Category:** View expenses belonging to a particular category.
10+
* **Data Persistence:** Your expense data is saved to a plain text file (`expenses.txt`) so it's retained between sessions.
11+
* **Simple Command-Line Interface:** Easy-to-use text-based menu for interacting with the application.
12+
13+
## Technologies Used
14+
15+
* **Python:** The core programming language used for the application logic.
16+
* **File Handling:** Used to store and retrieve expense data from a text file.
17+
* **`datetime` module:** For handling and managing date information for expenses.
18+
19+
## How to Run
20+
21+
1. Make sure you have Python installed on your system.
22+
2. Save the `expense_tracker.py` file to your local machine.
23+
3. Open your terminal or command prompt.
24+
4. Navigate to the directory where you saved the file using the `cd` command.
25+
5. Run the application by executing the command: `python expense_tracker.py`
26+
27+
## Basic Usage
28+
29+
1. Run the script. You will see a menu with different options.
30+
2. To add a new expense, choose option `1` and follow the prompts to enter the required information.
31+
3. To view expenses, choose option `2` and select the desired time period (day, week, month, or all).
32+
4. To filter expenses by category, choose option `3` and enter the category you want to view.
33+
5. To save any new expenses (though the application automatically saves on exit as well), choose option `4`.
34+
6. To exit the application, choose option `5`.
35+
36+
## Potential Future Enhancements (Ideas for Expansion)
37+
38+
* Implement a monthly budget feature with alerts.
39+
* Add a login system for multiple users.
40+
* Generate visual reports like pie charts for category-wise spending (using libraries like `matplotlib`).
41+
* Incorporate voice input for adding expenses (using `speech_recognition`).
42+
* Migrate data storage to a more structured database like SQLite.
43+
44+
* Add functionality to export expense data to CSV files.
45+
46+
---
47+
48+
> This simple Personal Expense Tracker provides a basic yet functional way to manage your finances from the command line.
+112
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import datetime
2+
3+
def add_expense(expenses):
4+
amount = float(input("Enter the expense amount: "))
5+
category = input("Category (food, travel, shopping, bills, etc.): ")
6+
date_str = input("Date (YYYY-MM-DD): ")
7+
try:
8+
date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
9+
except ValueError:
10+
print("Incorrect date format. Please use YYYY-MM-DD format.")
11+
return
12+
note = input("(Optional) Note: ")
13+
expenses.append({"amount": amount, "category": category, "date": date, "note": note})
14+
print("Expense added!")
15+
16+
def view_expenses(expenses, period="all", category_filter=None):
17+
if not expenses:
18+
print("No expenses recorded yet.")
19+
return
20+
21+
filtered_expenses = expenses
22+
if category_filter:
23+
filtered_expenses = [e for e in filtered_expenses if e["category"] == category_filter]
24+
25+
if period == "day":
26+
date_str = input("Enter the date to view expenses for (YYYY-MM-DD): ")
27+
try:
28+
date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
29+
filtered_expenses = [e for e in filtered_expenses if e["date"] == date]
30+
except ValueError:
31+
print("Incorrect date format.")
32+
return
33+
elif period == "week":
34+
date_str = input("Enter the start date of the week (YYYY-MM-DD - first day of the week): ")
35+
try:
36+
start_date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
37+
end_date = start_date + datetime.timedelta(days=6)
38+
filtered_expenses = [e for e in filtered_expenses if start_date <= e["date"] <= end_date]
39+
except ValueError:
40+
print("Incorrect date format.")
41+
return
42+
elif period == "month":
43+
year = input("Enter the year for the month (YYYY): ")
44+
month = input("Enter the month (MM): ")
45+
try:
46+
year = int(year)
47+
month = int(month)
48+
filtered_expenses = [e for e in filtered_expenses if e["date"].year == year and e["date"].month == month]
49+
except ValueError:
50+
print("Incorrect year or month format.")
51+
return
52+
53+
if not filtered_expenses:
54+
print("No expenses found for this period or category.")
55+
return
56+
57+
print("\n--- Expenses ---")
58+
total_spent = 0
59+
for expense in filtered_expenses:
60+
print(f"Amount: {expense['amount']}, Category: {expense['category']}, Date: {expense['date']}, Note: {expense['note']}")
61+
total_spent += expense['amount']
62+
print(f"\nTotal spent: {total_spent}")
63+
64+
def save_expenses(expenses, filename="expenses.txt"):
65+
with open(filename, "w") as f:
66+
for expense in expenses:
67+
f.write(f"{expense['amount']},{expense['category']},{expense['date']},{expense['note']}\n")
68+
print("Expenses saved!")
69+
70+
def load_expenses(filename="expenses.txt"):
71+
expenses = []
72+
try:
73+
with open(filename, "r") as f:
74+
for line in f:
75+
amount, category, date_str, note = line.strip().split(',')
76+
expenses.append({"amount": float(amount), "category": category, "date": datetime.datetime.strptime(date_str, "%Y-%m-%d").date(), "note": note})
77+
except FileNotFoundError:
78+
pass
79+
return expenses
80+
81+
def main():
82+
expenses = load_expenses()
83+
84+
while True:
85+
print("\n--- Personal Expense Tracker ---")
86+
print("1. Add new expense")
87+
print("2. View expenses")
88+
print("3. Filter by category")
89+
print("4. Save expenses")
90+
print("5. Exit")
91+
92+
choice = input("Choose your option: ")
93+
94+
if choice == '1':
95+
add_expense(expenses)
96+
elif choice == '2':
97+
period = input("View expenses by (day/week/month/all): ").lower()
98+
view_expenses(expenses, period)
99+
elif choice == '3':
100+
category_filter = input("Enter the category to filter by: ")
101+
view_expenses(expenses, category_filter=category_filter)
102+
elif choice == '4':
103+
save_expenses(expenses)
104+
elif choice == '5':
105+
save_expenses(expenses)
106+
print("Thank you!")
107+
break
108+
else:
109+
print("Invalid option. Please try again.")
110+
111+
if __name__ == "__main__":
112+
main()

0 commit comments

Comments
 (0)