-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
263 lines (216 loc) · 8.11 KB
/
Copy pathapp.py
File metadata and controls
263 lines (216 loc) · 8.11 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
from flask import Flask, render_template, request, jsonify, redirect, url_for
from flask_cors import CORS
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import pickle
import os
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LinearRegression
import json
app = Flask(__name__)
CORS(app)
# File paths
DATA_FILE = 'expenses.csv'
MODEL_FILE = 'category_model.pkl'
VECTORIZER_FILE = 'vectorizer.pkl'
# Initialize data
def init_data():
if not os.path.exists(DATA_FILE):
df = pd.DataFrame(columns=['Date', 'Amount', 'Description', 'Category'])
df.to_csv(DATA_FILE, index=False)
# Load data
def load_data():
if os.path.exists(DATA_FILE):
df = pd.read_csv(DATA_FILE)
# Ensure Date column is datetime
df['Date'] = pd.to_datetime(df['Date'], format='mixed', errors='coerce')
return df
return pd.DataFrame(columns=['Date', 'Amount', 'Description', 'Category'])
# Save data
def save_data(df):
df.to_csv(DATA_FILE, index=False)
# Train category prediction model
def train_category_model():
df = load_data()
if len(df) > 0 and 'Category' in df.columns and df['Category'].notna().sum() > 0:
# Filter out rows without categories for training
training_data = df.dropna(subset=['Category', 'Description'])
if len(training_data) > 0:
# Vectorize descriptions
vectorizer = TfidfVectorizer(stop_words='english', max_features=1000)
X = vectorizer.fit_transform(training_data['Description'])
# Train model
model = MultinomialNB()
model.fit(X, training_data['Category'])
# Save model and vectorizer
with open(MODEL_FILE, 'wb') as f:
pickle.dump(model, f)
with open(VECTORIZER_FILE, 'wb') as f:
pickle.dump(vectorizer, f)
return True
return False
# Predict category
def predict_category(description):
if os.path.exists(MODEL_FILE) and os.path.exists(VECTORIZER_FILE):
try:
with open(MODEL_FILE, 'rb') as f:
model = pickle.load(f)
with open(VECTORIZER_FILE, 'rb') as f:
vectorizer = pickle.load(f)
# Vectorize input
X = vectorizer.transform([description])
prediction = model.predict(X)[0]
return prediction
except:
return "Other"
else:
return "Other"
# Forecast spending
def forecast_spending():
df = load_data()
if len(df) > 0 and df['Amount'].sum() > 0:
# Prepare data for forecasting
df['Date'] = pd.to_datetime(df['Date'])
df['Date_ordinal'] = df['Date'].apply(lambda x: x.toordinal())
# Group by date and sum amounts
daily_spending = df.groupby('Date')['Amount'].sum().reset_index()
daily_spending['Date_ordinal'] = daily_spending['Date'].apply(lambda x: x.toordinal())
if len(daily_spending) > 1:
# Train linear regression model
X = daily_spending[['Date_ordinal']]
y = daily_spending['Amount']
model = LinearRegression()
model.fit(X, y)
# Predict next 30 days
last_date = daily_spending['Date'].max()
future_dates = [(last_date + timedelta(days=i)).toordinal() for i in range(1, 31)]
future_predictions = model.predict(np.array(future_dates).reshape(-1, 1))
return float(future_predictions.mean())
return 0.0
# Find spending patterns
def find_spending_patterns():
df = load_data()
if len(df) > 0:
df['Date'] = pd.to_datetime(df['Date'])
df['DayOfWeek'] = df['Date'].dt.dayofweek
df['IsWeekend'] = df['DayOfWeek'].isin([5, 6]) # Saturday=5, Sunday=6
weekend_spending = df[df['IsWeekend']]['Amount'].sum()
weekday_spending = df[~df['IsWeekend']]['Amount'].sum()
if weekday_spending > 0:
weekend_premium = ((weekend_spending - weekday_spending) / weekday_spending) * 100
return float(weekend_premium)
return 0.0
# Routes
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/expenses', methods=['GET'])
def get_expenses():
df = load_data()
# Convert datetime to string for JSON serialization
df['Date'] = df['Date'].astype(str)
return jsonify(df.to_dict(orient='records'))
@app.route('/api/expenses', methods=['POST'])
def add_expense():
data = request.get_json()
# Load existing data
df = load_data()
# Create new expense
new_expense = pd.DataFrame({
'Date': [data['date']],
'Amount': [float(data['amount'])],
'Description': [data['description']],
'Category': [data['category']]
})
# Add to existing data
df = pd.concat([df, new_expense], ignore_index=True)
# Save data
save_data(df)
# Retrain model
train_category_model()
return jsonify({'status': 'success'})
@app.route('/api/predict_category', methods=['POST'])
def api_predict_category():
data = request.get_json()
description = data['description']
category = predict_category(description)
return jsonify({'category': category})
@app.route('/api/dashboard')
def get_dashboard_data():
df = load_data()
if len(df) == 0:
return jsonify({
'total_spent': 0,
'avg_daily': 0,
'unique_categories': 0,
'category_spending': {},
'daily_spending': {}
})
# Summary metrics
total_spent = float(df['Amount'].sum())
avg_daily = float(df.groupby(df['Date'].dt.date)['Amount'].sum().mean())
unique_categories = int(df['Category'].nunique())
# Category breakdown
category_spending = df.groupby('Category')['Amount'].sum().to_dict()
category_spending = {k: float(v) for k, v in category_spending.items()}
# Daily spending trend
daily_spending = df.groupby(df['Date'].dt.date)['Amount'].sum()
daily_spending = {str(k): float(v) for k, v in daily_spending.items()}
return jsonify({
'total_spent': total_spent,
'avg_daily': avg_daily,
'unique_categories': unique_categories,
'category_spending': category_spending,
'daily_spending': daily_spending
})
@app.route('/api/predictions')
def get_predictions():
predicted_spending = forecast_spending()
weekend_premium = find_spending_patterns()
# Sample predictions
sample_descriptions = [
"Groceries from supermarket",
"Uber ride to office",
"Netflix subscription",
"Dinner at restaurant",
"Gas for car"
]
predictions = {}
for desc in sample_descriptions:
predictions[desc] = predict_category(desc)
return jsonify({
'predicted_spending': predicted_spending,
'weekend_premium': weekend_premium,
'sample_predictions': predictions
})
@app.route('/api/insights')
def get_insights():
df = load_data()
if len(df) == 0:
return jsonify({
'weekend_premium': 0,
'top_categories': [],
'total_spent': 0,
'suggested_savings': 0
})
# Weekend vs Weekday spending
weekend_premium = find_spending_patterns()
# Top spending categories
top_cats = df.groupby('Category')['Amount'].sum().sort_values(ascending=False).head(3)
top_categories = [{'category': k, 'amount': float(v)} for k, v in top_cats.items()]
# Budget recommendations
total_spent = float(df['Amount'].sum())
suggested_savings = total_spent * 0.1 # 10% savings suggestion
return jsonify({
'weekend_premium': weekend_premium,
'top_categories': top_categories,
'total_spent': total_spent,
'suggested_savings': suggested_savings
})
if __name__ == '__main__':
init_data()
# Train model on startup if we have data
train_category_model()
app.run(debug=True, host='0.0.0.0', port=5000)