-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpense.py
270 lines (206 loc) · 10.2 KB
/
expense.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
import PySimpleGUI as psg
import sys
import os
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import seaborn as sns
my_custom_style = {
"axes.facecolor": "#394a6d", # Background color of the plotting area
"axes.edgecolor": "#52de97", # Color of the edges of the plotting area
"axes.labelcolor": "#e6e6e6", # Color of axis labels
"text.color": "#e6e6e6", # Color of text
"xtick.color": "#e6e6e6", # Color of x-axis ticks
"ytick.color": "#e6e6e6", # Color of y-axis ticks
"grid.color": "#52de97", # Color of grid lines
"grid.linewidth": 0.5, # Width of grid lines
"figure.facecolor": "#394a6d", # Background color of the entire figure
"figure.edgecolor": "#52de97" # Color of the edges of the figure
}
# Set the custom style using Seaborn's set_style() function
sns.set_style(my_custom_style)
my_custom_palette = ["#3795BD","#FFD369","#03C988","#C02739","#FF4D00"]
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
if not os.path.isfile('./data.csv'):
f = open('./data.csv',encoding="utf-8-sig",mode='w+')
f.write("Date,Reason,Category,Amount")
data = []
with open("./data.csv",encoding="utf-8-sig") as f:
data = f.read().split('\n')
f.close()
Headers = data[0].split(",")
Rows = [row.split(',') for row in data[1::] if len(row)>0]
total = sum([float(r[3]) for r in Rows])
def monthdata(month,Headers,Rows):
rows = [[x[0],x[1],x[2],float(x[3])] for x in Rows if int(x[0].split('-')[1])==month]
new_df = pd.DataFrame(rows,columns=Headers)
return new_df.groupby('Category',as_index =False).sum(numeric_only=True),new_df.groupby('Date',as_index =False).sum(numeric_only=True)
def sort_help(dt):
date = dt[0].split("-")
return int(date[1]),int(date[0])
Rows.sort(key=sort_help)
def block_focus(window):
for key in window.key_dict: # Remove dash box of all Buttons
element = window[key]
if isinstance(element, psg.Button):
element.block_focus()
def popup_add_expense():
layout = [
[psg.Text('Date: ',size=(10,1)), psg.InputText(key='Date',disabled=True,size=(31,1)),psg.CalendarButton("Select Date",close_when_date_chosen=True, target="Date", format='%d-%m-%Y',size=(10,1),font="arial 15")],
[psg.Text('Reason: ',size=(10,1)), psg.InputText(key='Reason',size=(40,1))],
[psg.Text('Category: ',size=(10,1)), psg.Combo(["drink","flat","food","other","travel"],key='Category',size=(39,1),default_value="Click to Choose",readonly=True)],
[psg.Text('Amount: ',size=(10,1)), psg.InputText(key='Amount',size=(40,1))],
[psg.Button("Add Expense to data",key="Add",size=(50,1))]
]
window = psg.Window("Add new expense", layout, use_default_focus=False, finalize=True, modal=True)
block_focus(window)
event, values = window.read()
window.close()
return [values['Date'],values['Reason'],values['Category'],values['Amount']] if event == 'Add' else None
def draw_figure(canvas, figure):
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
figure_canvas_agg.draw()
figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
return figure_canvas_agg
def popup_show_graphs(fig):
layout = [
[psg.Canvas(key='figcanvas',background_color='black')]
]
window = psg.Window("Expense Tracker",layout,resizable=True,finalize=True)
draw_figure(window['figcanvas'].TKCanvas, fig)
block_focus(window)
event, values = window.read()
window.close()
psg.set_options(font=('Consolas', 16))
psg.theme("DarkTeal2")
read_table = psg.Table(values=Rows,headings=Headers,
auto_size_columns=True,
display_row_numbers=False,
justification='center', key='-TABLE-',
selected_row_colors='yellow on blue',
enable_events=True,
expand_x=True,
expand_y=True,
enable_click_events=True
)
months = ["All","January","February","March","April","May","June","July","August","September","October","November","December"]
categories = ["All","food","flat","drink","other","travel"]
layout = [
[psg.Text("Expense Tracker",font=" Arial 30 bold",justification='center',size=(1500,1))],
[psg.Combo(months,key="Month",default_value="All",size=(30,1),readonly=True),psg.Button("Filter Month",key="filmonth",size=(30,1),),psg.Combo(categories,key="Category",default_value="All",size=(30,1),readonly=True),psg.Button("Filter Category",key="filcat",size=(30,1))],
[psg.Button("Filter by Month and Category",key="filmthcat",size=(150,1))],
[read_table],
[psg.Text("Total Amount : ",font="roboto 20"),psg.InputText(str(round(total,2)),key='total',disabled=True,font="Roboto 20",size=(100,1))],
[psg.Button("Add Expense ➕ ",key="Add"),psg.Button("Show Graph for Month",size=(90,1),key="show"),psg.Button("Save File 💾",key="Save")]
]
window = psg.Window("Expense Tracker",layout,size=(1500,800),resizable=True,icon=resource_path("rupee-indian.ico"))
while True:
event, values = window.read(timeout=1000)
if event in (None, 'Exit'):
ch = psg.popup_yes_no("Want to save ?",title="save before exit")
if ch=="Yes":
s = []
s.append(",".join(Headers))
for x in Rows:
s.append(",".join(x))
f = open("./data.csv",mode="w+",encoding="utf-8-sig")
f.write("\n".join(s))
f.close()
psg.popup("Saved Succesfully")
break
if event=="filmonth":
filrows = []
if values['Month']=="All":
filrows=Rows
filtotal = total
window["-TABLE-"].update(filrows)
window['total'].update(round(filtotal,2))
if values['Month']!="All":
mindex = months.index(values["Month"])
filrows = [x for x in Rows if int(x[0].split('-')[1])==mindex]
if len(filrows)==0:
psg.popup("No Records Found for month {mth}".format(mth=values["Month"]))
filtotal = sum([float(r[3]) for r in filrows])
window["-TABLE-"].update(filrows)
window["total"].update(round(filtotal,2))
if event=="filcat":
filrows = []
print(values['Category'])
if values['Category']=="All":
filrows=Rows
filtotal = total
window["-TABLE-"].update(filrows)
window['total'].update(round(filtotal,2))
if values['Category']!="All":
fcat = values["Category"]
filrows = [x for x in Rows if x[2]==fcat]
filtotal = sum([float(r[3]) for r in filrows])
window["-TABLE-"].update(filrows)
window["total"].update(round(filtotal,2))
if event=="filmthcat":
if values['Category']!="All" and values['Month']!="All":
mindex = months.index(values["Month"])
fcat = values["Category"]
filrows = [x for x in Rows if x[2]==fcat and int(x[0].split('-')[1])==mindex]
filtotal = sum([float(r[3]) for r in filrows])
window["-TABLE-"].update(filrows)
window["total"].update(round(filtotal,2))
if values['Category']=="All" and values['Month']=="All":
filrows = Rows
filtotal = sum([float(r[3]) for r in filrows])
window["-TABLE-"].update(filrows)
window["total"].update(round(filtotal,2))
if event=="Add":
new_row = popup_add_expense()
if new_row==None:
print("Canceled Entry")
elif "" not in new_row and new_row[3].isdigit():
Rows+=[new_row]
Rows.sort(key=sort_help)
total += float(new_row[3])
window['-TABLE-'].update(Rows)
window['total'].update(round(total,2))
psg.popup("Added Succesfuly")
else:
psg.popup("Something Went Wrong")
if event=="Save":
s = []
s.append(",".join(Headers))
for x in Rows:
s.append(",".join(x))
f = open("./data.csv",mode="w+",encoding="utf-8-sig")
f.write("\n".join(s))
f.close()
psg.popup("Saved Succesfully")
if event=="show":
if values['Month']!="All":
mindex = months.index(values["Month"])
categoryexpense,daywise = monthdata(mindex,Headers,Rows)
if len(categoryexpense)>0:
fig, ax = plt.subplots(ncols=2,figsize=(30,10))
catex = sns.barplot(categoryexpense,x='Category',y='Amount',ax=ax[0],palette=my_custom_palette)
catex.axes.set_title("Category wise Amount")
catex.set_xlabel("Category")
catex.set_ylabel("Amount")
catex.bar_label(catex.containers[0])
catex.tick_params()
dayexp = sns.barplot(daywise,x='Date',y='Amount',ax=ax[1])
dayexp.axes.set_title("Date Wise Amount")
dayexp.set_xlabel("Date")
dayexp.set_ylabel("Amount")
dayexp.set_xticklabels(labels=daywise['Date'].to_list(),rotation=90)
dayexp.bar_label(dayexp.containers[0],fontsize=18,rotation=90)
dayexp.tick_params(labelsize=10)
fig.suptitle('Basic Dashboard',fontsize=50)
fig.set_animated()
popup_show_graphs(fig)
else:
psg.popup("No Records Found")
else:
psg.popup("Select a month")
window.close()