Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
494 lines (366 loc) · 12.2 KB
/
Copy pathapp.py
File metadata and controls
494 lines (366 loc) · 12.2 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import sqlite3
import csv
import io
from flask import Flask, render_template, request, redirect, Response
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
app = Flask(__name__)
DATABASE = "smartbudget.db"
def create_table():
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS expenses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
amount REAL NOT NULL,
category TEXT NOT NULL,
date TEXT NOT NULL
)
""")
conn.commit()
conn.close()
def update_database():
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
try:
cursor.execute(
"ALTER TABLE expenses ADD COLUMN category TEXT"
)
except:
pass
try:
cursor.execute(
"ALTER TABLE expenses ADD COLUMN date TEXT"
)
except:
pass
conn.commit()
conn.close()
@app.route("/")
def home():
from datetime import datetime
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
# Fetch all expenses
cursor.execute("""
SELECT id, name, amount, category, date
FROM expenses
ORDER BY date DESC, id DESC
""")
expenses = cursor.fetchall()
# Calculate total spending
cursor.execute("SELECT SUM(amount) FROM expenses")
total = cursor.fetchone()[0] or 0
# Category-wise spending for the chart
cursor.execute("""
SELECT category, SUM(amount)
FROM expenses
WHERE category IS NOT NULL
GROUP BY category
""")
category_data = cursor.fetchall()
categories = []
amounts = []
for category, amount in category_data:
if category:
categories.append(category)
amounts.append(amount)
# Get current month in YYYY-MM format
current_month = datetime.now().strftime("%Y-%m")
# Current month's total spending
cursor.execute("""
SELECT SUM(amount)
FROM expenses
WHERE date LIKE ?
""", (current_month + "%",))
monthly_total = cursor.fetchone()[0] or 0
# Current month's transaction count
cursor.execute("""
SELECT COUNT(*)
FROM expenses
WHERE date LIKE ?
""", (current_month + "%",))
monthly_transaction_count = cursor.fetchone()[0]
if monthly_transaction_count > 0:
average_expense = monthly_total / monthly_transaction_count
else:
average_expense = 0
# Total number of transactions
cursor.execute("SELECT COUNT(*) FROM expenses")
transaction_count = cursor.fetchone()[0]
# Highest single expense
cursor.execute("SELECT MAX(amount) FROM expenses")
highest_expense = cursor.fetchone()[0] or 0
# Most frequently used category
cursor.execute("""
SELECT category, COUNT(*) AS category_count
FROM expenses
WHERE category IS NOT NULL
GROUP BY category
ORDER BY category_count DESC
LIMIT 1
""")
top_category_result = cursor.fetchone()
if top_category_result:
top_category = top_category_result[0]
else:
top_category = "None"
# Current month's category-wise spending
cursor.execute("""
SELECT category, SUM(amount)
FROM expenses
WHERE date LIKE ?
AND category IS NOT NULL
GROUP BY category
""", (current_month + "%",))
monthly_category_data = cursor.fetchall()
conn.close()
# -------------------------------------------------
# BUDGET RECOMMENDATION ENGINE
# -------------------------------------------------
recommendations = []
if monthly_total == 0:
recommendations.append({
"type": "info",
"title": "Start recording expenses",
"message": (
"No expenses have been recorded for the current month. "
"Add a few transactions to receive personalized recommendations."
)
})
else:
category_percentages = {}
for category, category_amount in monthly_category_data:
if category:
percentage = (category_amount / monthly_total) * 100
category_percentages[category.lower()] = {
"name": category,
"amount": category_amount,
"percentage": percentage
}
# Food recommendation
food_data = category_percentages.get("food")
if food_data and food_data["percentage"] >= 35:
recommendations.append({
"type": "warning",
"title": "High food spending",
"message": (
f"Food represents {food_data['percentage']:.1f}% of your "
"monthly expenses. Consider reducing restaurant orders "
"or planning meals in advance."
)
})
# Entertainment recommendation
entertainment_data = category_percentages.get("entertainment")
if entertainment_data and entertainment_data["percentage"] >= 20:
recommendations.append({
"type": "warning",
"title": "Review entertainment expenses",
"message": (
f"Entertainment accounts for "
f"{entertainment_data['percentage']:.1f}% of this month's "
"spending. Setting a weekly entertainment limit may help."
)
})
# Shopping recommendation
shopping_data = category_percentages.get("shopping")
if shopping_data and shopping_data["percentage"] >= 25:
recommendations.append({
"type": "warning",
"title": "Shopping expenses are significant",
"message": (
f"Shopping represents {shopping_data['percentage']:.1f}% "
"of your monthly spending. Review non-essential purchases "
"before buying."
)
})
# Transport recommendation
transport_data = category_percentages.get("transport")
if transport_data and transport_data["percentage"] >= 20:
recommendations.append({
"type": "info",
"title": "Optimize transport costs",
"message": (
f"Transport represents {transport_data['percentage']:.1f}% "
"of your monthly expenses. Public transport, ride sharing, "
"or route planning could reduce this amount."
)
})
# Detect the largest spending category
if monthly_category_data:
largest_category = max(
monthly_category_data,
key=lambda item: item[1]
)
largest_category_name = largest_category[0]
largest_category_amount = largest_category[1]
largest_category_percentage = (
largest_category_amount / monthly_total
) * 100
if largest_category_percentage >= 40:
recommendations.append({
"type": "warning",
"title": "Spending is concentrated",
"message": (
f"{largest_category_name} is your largest category and "
f"uses {largest_category_percentage:.1f}% of this "
"month's spending. Review this category for possible savings."
)
})
# Large single expense recommendation
if highest_expense >= monthly_total * 0.40:
recommendations.append({
"type": "info",
"title": "Large individual expense detected",
"message": (
f"Your highest recorded expense is ₹{highest_expense:.2f}. "
"Large purchases should be planned separately from regular "
"monthly spending."
)
})
# Positive recommendation
if len(monthly_category_data) >= 3:
highest_percentage = max(
(amount / monthly_total) * 100
for _, amount in monthly_category_data
)
if highest_percentage < 35:
recommendations.append({
"type": "success",
"title": "Balanced spending pattern",
"message": (
"Your spending is distributed across several categories "
"without one category dominating the budget."
)
})
# General recommendation when no warning rule is triggered
if not recommendations:
recommendations.append({
"type": "success",
"title": "Spending looks controlled",
"message": (
"No unusually high spending pattern was detected this month. "
"Continue recording expenses regularly to maintain accurate insights."
)
})
return render_template(
"index.html",
expenses=expenses,
total=total,
categories=categories,
amounts=amounts,
monthly_total=monthly_total,
average_expense=average_expense,
transaction_count=transaction_count,
monthly_transaction_count=monthly_transaction_count,
highest_expense=highest_expense,
top_category=top_category,
recommendations=recommendations
)
@app.route("/add", methods=["POST"])
def add_expense():
name = request.form["name"]
amount = request.form["amount"]
category = request.form["category"]
date = request.form["date"]
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO expenses
(name, amount, category, date)
VALUES (?, ?, ?, ?)
""",
(name, amount, category, date)
)
conn.commit()
conn.close()
return redirect("/")
@app.route("/delete/<int:id>")
def delete_expense(id):
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute(
"DELETE FROM expenses WHERE id=?",
(id,)
)
conn.commit()
conn.close()
return redirect("/")
@app.route("/export")
def export():
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute("SELECT * FROM expenses")
expenses = cursor.fetchall()
conn.close()
output = io.StringIO()
writer = csv.writer(output)
writer.writerow([
"ID",
"Name",
"Amount",
"Category",
"Date"
])
for expense in expenses:
writer.writerow(expense)
response = Response(
output.getvalue(),
mimetype="text/csv"
)
response.headers["Content-Disposition"] = "attachment; filename=expenses.csv"
return response
@app.route("/export_pdf")
def export_pdf():
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute("SELECT * FROM expenses")
expenses = cursor.fetchall()
conn.close()
buffer = io.BytesIO()
pdf = SimpleDocTemplate(
buffer,
pagesize=letter
)
elements = []
styles = getSampleStyleSheet()
title = Paragraph(
"SmartBudget<br/>Personal Expense Tracker and Budget Management System",
styles["Title"]
)
elements.append(title)
data = [
[
"ID",
"Name",
"Amount",
"Category",
"Date"
]
]
for expense in expenses:
data.append(expense)
table = Table(data)
table.setStyle(
TableStyle([
('GRID',(0,0),(-1,-1),1,None)
])
)
elements.append(table)
pdf.build(elements)
buffer.seek(0)
return Response(
buffer,
mimetype="application/pdf",
headers={
"Content-Disposition":
"attachment; filename=SmartBudget_Report.pdf"
}
)
if __name__ == "__main__":
create_table()
update_database()
app.run(debug=True)