-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFinance.py
More file actions
382 lines (306 loc) · 15.5 KB
/
Copy pathFinance.py
File metadata and controls
382 lines (306 loc) · 15.5 KB
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import csv
import json
import calendar
import tkinter as tk
import matplotlib.pyplot as plt
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
from datetime import datetime
from dateutil.relativedelta import relativedelta
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class FinanceApp:
def __init__(self, root):
self.root = root
self.root.title("Personal Finances App")
self.current_year = datetime.now().year
self.current_month = datetime.now().month
self.data = self.load_data()
self.setup_ui()
def setup_ui(self):
main_frame = tk.Frame(self.root)
main_frame.pack(fill=tk.BOTH, expand=True)
header_frame = tk.Frame(main_frame)
header_frame.grid(row=0, column=0, columnspan=2, pady=10, sticky="nsew")
tk.Button(header_frame, text="<", command=self.prev_month).pack(side=tk.LEFT)
self.timeline_frame = tk.Frame(header_frame)
self.timeline_frame.pack(side=tk.LEFT, expand=True, fill=tk.X)
tk.Button(header_frame, text=">", command=self.next_month).pack(side=tk.RIGHT)
left_frame = tk.Frame(main_frame)
left_frame.grid(row=1, column=0, sticky="nsew", padx=10, pady=10)
self.content_frame = tk.Frame(left_frame)
self.content_frame.pack(fill=tk.BOTH, expand=True)
button_frame = tk.Frame(left_frame)
button_frame.pack(pady=10, fill="x")
tk.Button(button_frame, text="Add Post", command=self.add_post).pack(padx=10)
tk.Button(button_frame, text="Export to CSV", command=self.export_to_csv).pack(padx=10)
self.summary_label = tk.Label(left_frame, text="")
self.summary_label.pack(pady=10)
self.graph_frame = tk.Frame(main_frame)
self.graph_frame.grid(row=1, column=1, sticky="nsew", padx=10, pady=10)
main_frame.grid_rowconfigure(1, weight=1)
main_frame.grid_columnconfigure(0, weight=1)
main_frame.grid_columnconfigure(1, weight=1)
self.update_month()
def prev_month(self):
self.current_month -= 1
if self.current_month == 0:
self.current_month = 12
self.current_year -= 1
self.update_month()
def next_month(self):
self.current_month += 1
if self.current_month == 13:
self.current_month = 1
self.current_year += 1
self.update_month()
def update_month(self):
self.update_timeline()
self.update_summary()
self.display_data()
self.display_graph()
def update_timeline(self):
for widget in self.timeline_frame.winfo_children():
widget.destroy()
for col in range(7):
self.timeline_frame.grid_columnconfigure(col, weight=1)
for i in range(7):
offset = i - 3
year, month = self.calculate_offset_date(self.current_year, self.current_month, offset)
balance = self.calculate_balance_for_month(year, month)
frame = tk.Frame(self.timeline_frame)
frame.grid(row=0, column=i, padx=10, sticky="nsew")
label_month_year = tk.Label(frame, text=f"{calendar.month_abbr[month]} {year}", font=("Arial", 10), anchor="center")
label_month_year.pack()
label_balance = tk.Label(frame, text=f"{balance:.2f}", font=("Arial", 8), anchor="center")
label_balance.pack()
if offset == 0:
label_month_year.config(font=("Arial", 10, "bold"))
label_balance.config(font=("Arial", 8, "bold"))
else:
frame.bind("<Button-1>", lambda e, y=year, m=month: self.jump_to_month(y, m))
label_month_year.bind("<Button-1>", lambda e, y=year, m=month: self.jump_to_month(y, m))
label_balance.bind("<Button-1>", lambda e, y=year, m=month: self.jump_to_month(y, m))
def jump_to_month(self, year, month):
self.current_year, self.current_month = year, month
self.update_month()
def display_data(self):
for widget in self.content_frame.winfo_children():
widget.destroy()
headers = [
("Category", lambda: self.sort_data("category")),
("Amount", lambda: self.sort_data("amount")),
("Type", lambda: self.sort_data("type")),
("Actions", None),
]
for col, (header, sort_command) in enumerate(headers):
if sort_command:
label = tk.Label(
self.content_frame, text=header, font=("Arial", 10, "bold"),
borderwidth=1, relief="solid", cursor="hand2"
)
label.bind("<Button-1>", lambda e, cmd=sort_command: cmd())
else:
label = tk.Label(
self.content_frame, text=header, font=("Arial", 10, "bold"),
borderwidth=1, relief="solid"
)
label.grid(row=0, column=col, sticky="nsew", padx=5, pady=5)
type_colors = {
"One-time": "lightgray",
"Monthly": "darkgray",
"Annual": "gray",
}
month_data = self.get_month_data()
if not month_data:
tk.Label(self.content_frame, text="No entries for this month.").grid(
row=1, column=0, columnspan=4, pady=10
)
else:
for row, post in enumerate(month_data, start=1):
type_color = type_colors.get(post["type"], "white")
tk.Label(self.content_frame, text=post["category"], font=("Arial", 10), anchor="w").grid(row=row, column=0, sticky="nsew", padx=5, pady=2)
bg_color = "lightgreen" if post["amount"] > 0 else "lightcoral"
tk.Label(self.content_frame, text=f"{post['amount']:.2f}", font=("Arial", 10), bg=bg_color).grid(row=row, column=1, sticky="nsew", padx=5, pady=2)
tk.Label(self.content_frame, text=post["type"], font=("Arial", 10), bg=type_color).grid(row=row, column=2, sticky="nsew", padx=5, pady=2)
action_frame = tk.Frame(self.content_frame)
action_frame.grid(row=row, column=3, sticky="nsew", padx=5, pady=2)
tk.Button(action_frame, text="Edit", command=lambda i=row - 1: self.edit_post(i)).pack(side=tk.LEFT, padx=5)
tk.Button(action_frame, text="Delete", command=lambda i=row - 1: self.delete_post(i)).pack(side=tk.LEFT, padx=5)
self.content_frame.grid_columnconfigure(0, weight=1)
self.content_frame.grid_columnconfigure(1, weight=1)
self.content_frame.grid_columnconfigure(2, weight=1)
self.content_frame.grid_columnconfigure(3, weight=1)
def sort_data(self, key):
reverse = getattr(self, "sort_reverse", {}).get(key, False)
if key == "amount":
self.data.sort(key=lambda x: x[key], reverse=reverse)
else:
self.data.sort(key=lambda x: x.get(key, ""), reverse=reverse)
self.sort_reverse = {key: not reverse}
self.update_month()
def display_graph(self):
for widget in self.graph_frame.winfo_children():
widget.destroy()
months, incomes, expenses, usable_incomes = [], [], [], []
for i in range(-3, 4):
year, month = self.calculate_offset_date(self.current_year, self.current_month, i)
months.append(f"{calendar.month_abbr[month]} {year}")
income = sum(post["amount"] for post in self.data if self.is_post_in_month(post, year, month) and post["amount"] > 0)
expense = sum(post["amount"] for post in self.data if self.is_post_in_month(post, year, month) and post["amount"] < 0)
usable_income = income + expense
incomes.append(income)
expenses.append(abs(expense))
usable_incomes.append(usable_income)
fig, ax = plt.subplots(figsize=(5, 3))
x = range(len(months))
ax.plot(x, incomes, marker="o", label="Income", color="green", linestyle="-")
ax.plot(x, expenses, marker="o", label="Expenses", color="red", linestyle="-")
ax.plot(x, usable_incomes, marker="o", label="Usable Income", color="blue", linestyle="--")
ax.set_xticks(x)
ax.set_xticklabels(months, rotation=45, ha="right")
ax.set_ylabel("Amount")
ax.set_title("Income, Expenses, and Usable Income")
ax.legend()
self.graph_widget = FigureCanvasTkAgg(fig, master=self.graph_frame)
self.graph_widget.draw()
self.graph_widget.get_tk_widget().pack(fill=tk.BOTH, expand=True)
def get_month_data(self):
return [post for post in self.data if self.is_post_in_month(post, self.current_year, self.current_month)]
def is_post_in_month(self, post, year, month):
if "year" not in post or "month" not in post:
return False
post_date = datetime(post["year"], post["month"], 1)
current_date = datetime(year, month, 1)
end_date = datetime(post["end_year"], post["end_month"], 1) if post.get("end_year") and post.get("end_month") else None
if post["type"] == "One-time":
return post_date == current_date
if post["type"] == "Monthly":
return post_date <= current_date and (not end_date or current_date <= end_date)
if post["type"] == "Annual":
return post_date.month == current_date.month and post_date.year <= current_date.year and (not end_date or current_date <= end_date)
return False
def get_unique_categories(self):
return sorted(set(post['category'] for post in self.data if 'category' in post))
def update_summary(self):
income = sum(post["amount"] for post in self.get_month_data() if post["amount"] > 0)
expenses = sum(post["amount"] for post in self.get_month_data() if post["amount"] < 0)
balance = income + expenses
self.summary_label.config(text=f"Income = {income:.2f}, Expenses = {expenses:.2f}, Balance = {balance:.2f}")
def calculate_offset_date(self, year, month, offset):
new_date = datetime(year, month, 1) + relativedelta(months=offset)
return new_date.year, new_date.month
def calculate_balance_for_month(self, year, month):
return sum(post["amount"] for post in self.data if self.is_post_in_month(post, year, month))
def add_post(self):
self.open_post_form("Add Post", {}, self.save_post)
def edit_post(self, index):
month_data = self.get_month_data()
post = month_data[index]
self.open_post_form("Edit Post", post, lambda new_post: self.save_edited_post(post, new_post))
def open_post_form(self, title, post, save_callback):
form_window = tk.Toplevel(self.root)
form_window.title(title)
form_window.geometry("500x300")
form_frame = tk.Frame(form_window)
form_frame.pack(pady=10, padx=10, fill="both", expand=True)
labels = [
("Category:", 0, 0),
("Amount:", 0, 2),
("Type:", 1, 0),
("Start Year:", 2, 0),
("End Year:", 2, 2),
("Start Month:", 3, 0),
("End Month:", 3, 2),
]
widgets = {}
for label_text, row, col in labels:
label = tk.Label(form_frame, text=label_text, anchor="e")
label.grid(row=row, column=col, padx=5, pady=5, sticky="e")
if label_text == "Category:":
widget = ttk.Combobox(form_frame, values=self.get_unique_categories())
widget.set(post.get("category", ""))
elif label_text == "Amount:":
widget = tk.Entry(form_frame)
widget.insert(0, str(post.get("amount", "")))
elif label_text == "Type:":
widget = ttk.Combobox(form_frame, values=["One-time", "Monthly", "Annual"])
widget.set(post.get("type", "One-time"))
elif label_text in ["Start Year:", "End Year:"]:
year_value = post.get("year" if "Start" in label_text else "end_year", "")
year_value = year_value if year_value else "" # Ensure valid empty string
widget = ttk.Combobox(form_frame, values=list(range(datetime.now().year - 10, datetime.now().year + 10)))
widget.set(year_value)
elif label_text in ["Start Month:", "End Month:"]:
month_value = post.get("month" if "Start" in label_text else "end_month", "")
month_value = month_value if month_value else "" # Ensure valid empty string
widget = ttk.Combobox(form_frame, values=list(range(1, 13)))
widget.set(month_value)
widget.grid(row=row, column=col + 1, padx=5, pady=5, sticky="w")
widgets[label_text] = widget
save_button = tk.Button(
form_window,
text="Save",
command=lambda: save_callback({
"category": widgets["Category:"].get(),
"amount": float(widgets["Amount:"].get()),
"type": widgets["Type:"].get(),
"year": int(widgets["Start Year:"].get()) if widgets["Start Year:"].get() else None,
"month": int(widgets["Start Month:"].get()) if widgets["Start Month:"].get() else None,
"end_year": int(widgets["End Year:"].get()) if widgets["End Year:"].get() else None,
"end_month": int(widgets["End Month:"].get()) if widgets["End Month:"].get() else None,
})
)
save_button.pack(pady=10)
def save_post(self, post):
self.data.append(post)
self.save_data()
self.update_month()
def save_edited_post(self, old_post, new_post):
self.data[self.data.index(old_post)] = new_post
self.save_data()
self.update_month()
def delete_post(self, index):
month_data = self.get_month_data()
self.data.remove(month_data[index])
self.save_data()
self.update_month()
def export_to_csv(self):
file_path = filedialog.asksaveasfilename(
defaultextension=".csv",
filetypes=[("CSV files", "*.csv"), ("All files", "*.*")],
title="Save CSV File"
)
if not file_path:
return
with open(file_path, mode="w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["Category", "Amount", "Type", "Start Year", "Start Month", "End Year", "End Month"])
for post in self.data:
writer.writerow([
post.get("category", ""),
post.get("amount", ""),
post.get("type", ""),
post.get("year", ""),
post.get("month", ""),
post.get("end_year", ""),
post.get("end_month", ""),
])
messagebox.showinfo("Export to CSV", f"Data successfully exported to {file_path}")
def load_data(self):
try:
with open("finances.json", "r") as f:
data = json.load(f)
for post in data:
post.setdefault("year", self.current_year)
post.setdefault("month", self.current_month)
return data
except FileNotFoundError:
return []
def save_data(self):
with open("finances.json", "w") as f:
json.dump(self.data, f)
if __name__ == "__main__":
root = tk.Tk()
app = FinanceApp(root)
root.mainloop()