-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpense_tracker.py
271 lines (221 loc) · 8.21 KB
/
expense_tracker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import csv
import datetime
expenses = []
categories = []
def add_expense():
date_str = input("Enter the expense date (YYYY-MM-DD): ")
try:
date = datetime.datetime.strptime(date_str, "%Y-%m-%d")
except ValueError:
print("Invalid date format. Please enter the date in the correct format (YYYY-MM-DD).")
return
category = input("Enter the expense category: ").lower()
if category not in categories:
add_category(category)
description = input("Enter the expense description: ")
amount = float(input("Enter the expense amount: "))
if amount <= 0:
print("Invalid amount. Please enter a positive value.")
return
expense = {
"date": date,
"category": category,
"description": description,
"amount": amount,
}
expenses.append(expense)
print("Expense added successfully!")
def add_category(category):
if category not in categories:
categories.append(category)
print(f"Category '{category}' added successfully!")
else:
print(f"Category '{category}' already exists!")
def print_expenses(expenses):
print("ID Date Category Description Amount")
print("---------------------------------------------------------")
for i, expense in enumerate(expenses, start=1):
date_str = expense["date"].strftime("%Y-%m-%d")
category = expense["category"]
description = expense["description"]
amount = expense["amount"]
print(f"{i:<4}{date_str:<12}{category:<15}{description:<18}{amount:.2f}")
def view_expenses():
if not expenses:
print("No expenses found.")
else:
print("Expense List:")
print("-------------")
print_expenses(expenses)
def filter_expenses():
if not expenses:
print("No expenses found.")
return
print("Filter Expenses:")
print("1. Filter by Date Range")
print("2. Filter by Category")
print("3. Filter by Date Range and Category")
choice = input("Enter your choice (1-3): ")
if choice == "1":
filter_by_date_range()
elif choice == "2":
filter_by_category()
elif choice == "3":
filter_by_date_range_and_category()
else:
print("Invalid choice. Please try again.")
def filter_by_date_range():
start_date_str = input("Enter the start date (YYYY-MM-DD): ")
end_date_str = input("Enter the end date (YYYY-MM-DD): ")
try:
start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d")
end_date = datetime.datetime.strptime(end_date_str, "%Y-%m-%d")
except ValueError:
print("Invalid date format. Please enter the dates in the correct format (YYYY-MM-DD).")
return
filtered_expenses = [
expense for expense in expenses
if start_date <= expense["date"] <= end_date
]
if not filtered_expenses:
print("No expenses found within the specified date range.")
else:
print("Filtered Expense List:")
print("------------------")
print_expenses(filtered_expenses)
def filter_by_category():
category = input("Enter the category: ")
if category not in categories:
print("Category not found.")
return
filtered_expenses = [
expense for expense in expenses
if expense["category"] == category
]
if not filtered_expenses:
print("No expenses found for the specified category.")
else:
print("Filtered Expense List:")
print("------------------")
print_expenses(filtered_expenses)
def filter_by_date_range_and_category():
start_date_str = input("Enter the start date (YYYY-MM-DD): ")
end_date_str = input("Enter the end date (YYYY-MM-DD): ")
try:
start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d")
end_date = datetime.datetime.strptime(end_date_str, "%Y-%m-%d")
except ValueError:
print("Invalid date format. Please enter the dates in the correct format (YYYY-MM-DD).")
return
category = input("Enter the category: ")
if category not in categories:
print("Category not found.")
return
filtered_expenses = [
expense for expense in expenses
if start_date <= expense["date"] <= end_date and expense["category"] == category
]
if not filtered_expenses:
print("No expenses found for the specified date range and category.")
else:
print("Filtered Expense List:")
print("------------------")
print_expenses(filtered_expenses)
def calculate_total_expenses():
if not expenses:
print("No expenses found.")
return
print("Calculate Total Expenses:")
print("1. Calculate total for all expenses")
print("2. Calculate total within a date range")
choice = input("Enter your choice (1-2): ")
if choice == "1":
total_expenses = sum(expense["amount"] for expense in expenses)
print(f"Total Expenses: {total_expenses}")
elif choice == "2":
start_date_str = input("Enter the start date (YYYY-MM-DD): ")
end_date_str = input("Enter the end date (YYYY-MM-DD): ")
try:
start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d")
end_date = datetime.datetime.strptime(end_date_str, "%Y-%m-%d")
except ValueError:
print("Invalid date format. Please enter the dates in the correct format (YYYY-MM-DD).")
return
total_expenses = sum(
expense["amount"]
for expense in expenses
if start_date <= expense["date"] <= end_date
)
print(f"Total Expenses within {start_date_str} and {end_date_str}: {total_expenses}")
else:
print("Invalid choice. Please try again.")
def delete_expense():
if not expenses:
print("No expenses found.")
return
view_expenses()
expense_id = int(input("Enter the expense ID to delete: "))
if expense_id < 1 or expense_id > len(expenses):
print("Invalid expense ID. Please try again.")
return
del expenses[expense_id - 1]
print("Expense deleted successfully!")
print_expenses(expenses)
def export_expense_data():
if not expenses:
print("No expenses found.")
return
file_name = input("Enter the file name to export (e.g., expenses.csv): ")
if not file_name.endswith(".csv"):
print("Invalid file name. The file must be in CSV format.")
return
try:
with open(file_name, "w", newline="") as csvfile:
fieldnames = ["Date", "Category", "Description", "Amount"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for expense in expenses:
writer.writerow({
"Date": expense["date"].strftime("%Y-%m-%d"),
"Category": expense["category"],
"Description": expense["description"],
"Amount": expense["amount"],
})
print(f"Expense data exported to {file_name} successfully!")
except IOError:
print("An error occurred while exporting the expense data.")
def main():
while True:
print("\nExpense Tracker")
print("---------------")
print("1. Add an Expense")
print("2. View Expense List")
print("3. Filter Expenses")
print("4. Calculate Total Expenses")
print("5. Delete an Expense")
print("6. Export Expense Data")
print("7. Add categories")
print("8. Exit")
choice = input("Enter your choice (1-8): ")
if choice == "1":
print("Enter expense details:")
add_expense()
elif choice == "2":
view_expenses()
elif choice == "3":
filter_expenses()
elif choice == "4":
calculate_total_expenses()
elif choice == "5":
delete_expense()
elif choice == "6":
export_expense_data()
elif choice == "7":
category = input("Enter the new category: ").lower()
add_category(category)
elif choice == "8":
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
main()