-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1857 lines (1549 loc) · 71.2 KB
/
Copy pathapp.py
File metadata and controls
1857 lines (1549 loc) · 71.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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, request, jsonify, render_template, send_from_directory
from werkzeug.utils import secure_filename
import io
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from flask_cors import CORS
from datetime import datetime, timedelta
import os
from dotenv import load_dotenv
from openai import OpenAI
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import json
from agents import AgentManager
from utils import (
detect_spending_anomalies, generate_spending_insights,
calculate_income_stability, detect_income_seasonality,
project_income_trends, calculate_income_volatility,
calculate_health_score, identify_risk_factors,
predict_time_series, calculate_overall_risk,
generate_risk_mitigation_plan, analyze_goal_progress,
prepare_recommendation_context, parse_ai_recommendations,
generate_fallback_recommendations
)
import plaid
from plaid.api import plaid_api
from plaid.model.link_token_create_request import LinkTokenCreateRequest
from plaid.model.link_token_create_request_user import LinkTokenCreateRequestUser
from plaid.model.products import Products
from plaid.model.country_code import CountryCode
from plaid.model.item_public_token_exchange_request import ItemPublicTokenExchangeRequest
from plaid.model.transactions_sync_request import TransactionsSyncRequest
load_dotenv()
app = Flask(__name__)
# Load configuration
from config import get_config
config = get_config()
app.config.from_object(config)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
app.config['UPLOAD_EXTENSIONS'] = {'.csv', '.xlsx', '.xls'}
app.config['JWT_COOKIE_CSRF_PROTECT'] = False # Disable CSRF for JWT
db = SQLAlchemy(app)
jwt = JWTManager(app)
CORS(app, supports_credentials=True)
# Configure OpenAI API (PipeShift)
client = OpenAI(
api_key=os.getenv('OPENAI_API_KEY'),
base_url=os.getenv('OPENAI_BASE_URL', 'https://api.pipeshift.com/api/v0/')
)
AI_MODEL = os.getenv('OPENAI_MODEL', 'neysa-qwen3-vl-30b-a3b')
# Initialize Agent Manager
agent_manager = AgentManager()
# Plaid Configuration
PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')
PLAID_SECRET = os.getenv('PLAID_SECRET')
PLAID_ENV = os.getenv('PLAID_ENV', 'sandbox')
# Map environment to Plaid host
plaid_env_map = {
'sandbox': plaid.Environment.Sandbox,
'development': plaid.Environment.Development,
'production': plaid.Environment.Production
}
# Handle if Development doesn't exist in this Plaid version
if not hasattr(plaid.Environment, 'Development'):
plaid_env_map['development'] = plaid.Environment.Sandbox
configuration = plaid.Configuration(
host=plaid_env_map.get(PLAID_ENV, plaid.Environment.Sandbox),
api_key={
'clientId': PLAID_CLIENT_ID,
'secret': PLAID_SECRET,
}
)
api_client = plaid.ApiClient(configuration)
plaid_client = plaid_api.PlaidApi(api_client)
# JWT Error Handlers
@jwt.expired_token_loader
def expired_token_callback(jwt_header, jwt_payload):
print(f"JWT EXPIRED: {jwt_payload}")
return jsonify({'error': 'Token has expired'}), 401
@jwt.invalid_token_loader
def invalid_token_callback(error):
print(f"JWT INVALID: {error}")
return jsonify({'error': 'Invalid token'}), 401
@jwt.unauthorized_loader
def missing_token_callback(error):
print(f"JWT MISSING: {error}")
return jsonify({'error': 'Authorization token is required'}), 401
# Serve static files
@app.route('/')
def index():
return send_from_directory('static', 'index.html')
@app.route('/api/test')
def test():
"""Test endpoint - no auth required"""
return jsonify({'status': 'ok', 'message': 'API is working'})
@app.route('/<path:path>')
def static_files(path):
return send_from_directory('static', path)
# Database Models
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(120), nullable=False)
name = db.Column(db.String(100), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
profile = db.relationship('UserProfile', backref='user', uselist=False)
transactions = db.relationship('Transaction', backref='user', lazy=True)
class UserProfile(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
employment_type = db.Column(db.String(50)) # 'gig', 'informal', 'formal'
monthly_income_range = db.Column(db.String(20))
financial_goals = db.Column(db.Text)
risk_tolerance = db.Column(db.String(20)) # 'low', 'medium', 'high'
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class Transaction(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
amount = db.Column(db.Float, nullable=False)
category = db.Column(db.String(50), nullable=False)
description = db.Column(db.String(200))
transaction_type = db.Column(db.String(20), nullable=False) # 'income', 'expense'
date = db.Column(db.DateTime, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
class FinancialInsight(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
insight_type = db.Column(db.String(50), nullable=False) # 'spending_pattern', 'income_alert', 'recommendation'
content = db.Column(db.Text, nullable=False)
priority = db.Column(db.String(20), default='medium') # 'low', 'medium', 'high'
created_at = db.Column(db.DateTime, default=datetime.utcnow)
is_read = db.Column(db.Boolean, default=False)
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
title = db.Column(db.String(200), nullable=False)
description = db.Column(db.Text)
agent_type = db.Column(db.String(50), nullable=False) # 'financial', 'research', 'productivity', 'learning'
task_type = db.Column(db.String(50), nullable=False) # Specific task type within agent
priority = db.Column(db.String(20), default='medium') # 'low', 'medium', 'high'
status = db.Column(db.String(20), default='pending') # 'pending', 'in_progress', 'completed', 'failed'
task_data = db.Column(db.Text) # JSON string of task data
result = db.Column(db.Text) # JSON string of task result
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
completed_at = db.Column(db.DateTime)
# Relationships for agent coordination
parent_task_id = db.Column(db.Integer, db.ForeignKey('task.id'), nullable=True)
child_tasks = db.relationship('Task', backref=db.backref('parent_task', remote_side=[id]), lazy='dynamic')
class AgentWorkflow(db.Model):
"""Track agent workflows and coordination"""
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
workflow_name = db.Column(db.String(100), nullable=False)
agent_sequence = db.Column(db.Text) # JSON array of agent types in order
current_step = db.Column(db.Integer, default=0)
status = db.Column(db.String(20), default='active') # 'active', 'completed', 'failed'
task_ids = db.Column(db.Text) # JSON array of task IDs in this workflow
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class PlaidAccount(db.Model):
"""Store Plaid connected bank accounts"""
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
access_token = db.Column(db.String(200), nullable=False) # Encrypt in production!
item_id = db.Column(db.String(100), nullable=False)
institution_name = db.Column(db.String(100))
institution_id = db.Column(db.String(100))
account_name = db.Column(db.String(100))
account_type = db.Column(db.String(50))
last_synced = db.Column(db.DateTime)
is_active = db.Column(db.Boolean, default=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
# Routes
@app.route('/api/auth/register', methods=['POST'])
def register():
data = request.get_json()
if User.query.filter_by(email=data['email']).first():
return jsonify({'error': 'Email already exists'}), 400
user = User(
email=data['email'],
password=data['password'], # In production, hash this password
name=data['name']
)
db.session.add(user)
db.session.commit()
# Create user profile
profile = UserProfile(user_id=user.id)
db.session.add(profile)
db.session.commit()
access_token = create_access_token(identity=str(user.id))
return jsonify({
'access_token': access_token,
'user': {
'id': user.id,
'email': user.email,
'name': user.name
}
}), 201
@app.route('/api/auth/login', methods=['POST'])
def login():
data = request.get_json()
user = User.query.filter_by(email=data['email']).first()
if user and user.password == data['password']: # In production, verify hashed password
access_token = create_access_token(identity=str(user.id))
return jsonify({
'access_token': access_token,
'user': {
'id': user.id,
'email': user.email,
'name': user.name
}
})
else:
return jsonify({'error': 'Invalid credentials'}), 401
def get_current_user_id():
"""Helper to get user ID as integer from JWT"""
return int(get_jwt_identity())
def categorize_transaction(description, amount, transaction_type):
"""Smart transaction categorization with keyword matching and AI fallback"""
desc_lower = description.lower()
# Income categories
if transaction_type == 'income':
if any(word in desc_lower for word in ['salary', 'payroll', 'wage', 'pay']):
return 'Salary'
elif any(word in desc_lower for word in ['freelance', 'consulting', 'contract', 'gig']):
return 'Freelance'
elif any(word in desc_lower for word in ['dividend', 'interest', 'investment', 'stock']):
return 'Investment'
elif any(word in desc_lower for word in ['bonus', 'commission', 'tip']):
return 'Bonus'
elif any(word in desc_lower for word in ['refund', 'reimbursement']):
return 'Refund'
else:
return 'Other Income'
# Expense categories - Housing
if any(word in desc_lower for word in ['rent', 'mortgage', 'property', 'lease']):
return 'Housing'
# Utilities
if any(word in desc_lower for word in ['electric', 'electricity', 'pg&e', 'pge', 'power', 'water', 'gas bill', 'utility']):
return 'Utilities'
if any(word in desc_lower for word in ['internet', 'comcast', 'xfinity', 'wifi', 'broadband']):
return 'Utilities'
if any(word in desc_lower for word in ['phone', 'mobile', 'verizon', 'at&t', 'tmobile', 't-mobile', 'cellular']):
return 'Utilities'
# Transportation
if any(word in desc_lower for word in ['gas', 'fuel', 'shell', 'chevron', '76', 'exxon', 'mobil', 'bp', 'arco', 'petrol']):
return 'Transportation'
if any(word in desc_lower for word in ['uber', 'lyft', 'taxi', 'cab', 'ride']):
return 'Transportation'
if any(word in desc_lower for word in ['parking', 'toll', 'metro', 'transit', 'bus', 'train']):
return 'Transportation'
if any(word in desc_lower for word in ['car insurance', 'auto insurance', 'geico', 'progressive', 'state farm']):
return 'Transportation'
if any(word in desc_lower for word in ['car wash', 'oil change', 'mechanic', 'repair', 'maintenance', 'tire']):
return 'Transportation'
# Food & Dining
if any(word in desc_lower for word in ['grocery', 'groceries', 'supermarket', 'safeway', 'whole foods', 'trader joe', 'costco', 'walmart', 'target']):
return 'Groceries'
if any(word in desc_lower for word in ['restaurant', 'cafe', 'coffee', 'starbucks', 'dunkin', 'mcdonald', 'burger', 'pizza', 'chipotle', 'subway', 'taco', 'dining', 'food', 'lunch', 'dinner', 'breakfast']):
return 'Dining'
# Entertainment & Subscriptions
if any(word in desc_lower for word in ['netflix', 'hulu', 'disney', 'spotify', 'apple music', 'youtube premium', 'amazon prime', 'subscription', 'streaming']):
return 'Entertainment'
if any(word in desc_lower for word in ['gym', 'fitness', 'yoga', 'la fitness', 'planet fitness', 'workout']):
return 'Entertainment'
if any(word in desc_lower for word in ['movie', 'cinema', 'theater', 'amc', 'concert', 'show', 'ticket']):
return 'Entertainment'
if any(word in desc_lower for word in ['game', 'gaming', 'steam', 'playstation', 'xbox', 'nintendo']):
return 'Entertainment'
# Shopping
if any(word in desc_lower for word in ['amazon', 'ebay', 'etsy', 'shopping', 'purchase']):
return 'Shopping'
if any(word in desc_lower for word in ['clothing', 'clothes', 'fashion', 'nordstrom', 'macy', 'gap', 'zara', 'h&m']):
return 'Shopping'
if any(word in desc_lower for word in ['electronics', 'best buy', 'apple store', 'computer', 'phone']):
return 'Shopping'
if any(word in desc_lower for word in ['home depot', 'lowes', 'hardware', 'furniture', 'ikea']):
return 'Shopping'
# Healthcare
if any(word in desc_lower for word in ['health insurance', 'medical', 'doctor', 'hospital', 'clinic', 'pharmacy', 'cvs', 'walgreens', 'prescription', 'medicine']):
return 'Healthcare'
if any(word in desc_lower for word in ['dental', 'dentist', 'orthodont']):
return 'Healthcare'
if any(word in desc_lower for word in ['vet', 'veterinary', 'animal hospital', 'pet clinic']):
return 'Pet Care'
# Personal Care
if any(word in desc_lower for word in ['haircut', 'salon', 'barber', 'spa', 'beauty', 'cosmetic']):
return 'Personal Care'
# Education
if any(word in desc_lower for word in ['school', 'tuition', 'education', 'course', 'udemy', 'coursera', 'book', 'textbook']):
return 'Education'
# Gifts & Donations
if any(word in desc_lower for word in ['gift', 'present', 'donation', 'charity']):
return 'Gifts'
# Insurance (non-auto)
if any(word in desc_lower for word in ['insurance']) and 'auto' not in desc_lower and 'car' not in desc_lower:
return 'Insurance'
# Default: Use AI for unclear cases
try:
cat_prompt = f"""Categorize this transaction into ONE of these categories:
Housing, Utilities, Transportation, Groceries, Dining, Entertainment, Shopping, Healthcare, Pet Care, Personal Care, Education, Gifts, Insurance, Other
Transaction: {description}
Amount: ${amount}
Return ONLY the category name, nothing else."""
cat_response = client.chat.completions.create(
model=AI_MODEL,
messages=[
{"role": "system", "content": "Return only the category name from the provided list."},
{"role": "user", "content": cat_prompt}
],
max_tokens=20,
temperature=0.1
)
category = cat_response.choices[0].message.content.strip()
# Validate it's one of our categories
valid_categories = ['Housing', 'Utilities', 'Transportation', 'Groceries', 'Dining', 'Entertainment',
'Shopping', 'Healthcare', 'Pet Care', 'Personal Care', 'Education', 'Gifts', 'Insurance']
if category in valid_categories:
return category
except:
pass
return 'Other'
def generate_insights_for_user(user_id):
"""Generate AI-powered financial insights for a user"""
try:
# Get user's transactions
transactions = Transaction.query.filter_by(user_id=user_id).all()
if not transactions or len(transactions) < 3:
# Create a welcome insight
insight = FinancialInsight(
user_id=user_id,
insight_type='welcome',
content='Welcome! Start adding transactions to get personalized AI insights about your spending patterns, savings opportunities, and financial health.',
priority='low'
)
db.session.add(insight)
db.session.commit()
return
# Convert to DataFrame
df = pd.DataFrame([{
'amount': t.amount,
'category': t.category,
'type': t.transaction_type,
'date': t.date
} for t in transactions])
# Separate income and expenses
expenses = df[df['type'] == 'expense']
income = df[df['type'] == 'income']
insights_to_create = []
# 1. Spending pattern insights
if not expenses.empty:
category_spending = expenses.groupby('category')['amount'].sum().sort_values(ascending=False)
total_expenses = category_spending.sum()
# Top spending category
if len(category_spending) > 0:
top_category = category_spending.index[0]
top_amount = category_spending.iloc[0]
top_percentage = (top_amount / total_expenses) * 100
if top_percentage > 30:
insights_to_create.append({
'insight_type': 'spending_pattern',
'content': f'Your {top_category} spending accounts for {top_percentage:.1f}% (${top_amount:.2f}) of total expenses. Consider reviewing this category for potential savings.',
'priority': 'high' if top_percentage > 50 else 'medium'
})
# 2. Income vs Expenses
if not income.empty and not expenses.empty:
total_income = income['amount'].sum()
total_expenses_val = expenses['amount'].sum()
savings_rate = ((total_income - total_expenses_val) / total_income * 100) if total_income > 0 else 0
if savings_rate < 10:
insights_to_create.append({
'insight_type': 'savings_alert',
'content': f'Your savings rate is {savings_rate:.1f}%. Financial experts recommend saving at least 20% of your income. Try to reduce expenses or increase income.',
'priority': 'high'
})
elif savings_rate >= 20:
insights_to_create.append({
'insight_type': 'savings_success',
'content': f'Great job! You\'re saving {savings_rate:.1f}% of your income. Keep up the excellent financial discipline!',
'priority': 'low'
})
# 3. Recent spending trends
if not expenses.empty:
expenses['date'] = pd.to_datetime(expenses['date'])
expenses = expenses.sort_values('date')
# Last 30 days vs previous 30 days
recent_date = expenses['date'].max()
last_30_days = expenses[expenses['date'] >= (recent_date - pd.Timedelta(days=30))]
prev_30_days = expenses[(expenses['date'] >= (recent_date - pd.Timedelta(days=60))) &
(expenses['date'] < (recent_date - pd.Timedelta(days=30)))]
if not last_30_days.empty and not prev_30_days.empty:
recent_spending = last_30_days['amount'].sum()
previous_spending = prev_30_days['amount'].sum()
change_pct = ((recent_spending - previous_spending) / previous_spending * 100) if previous_spending > 0 else 0
if abs(change_pct) > 20:
direction = 'increased' if change_pct > 0 else 'decreased'
insights_to_create.append({
'insight_type': 'trend_alert',
'content': f'Your spending has {direction} by {abs(change_pct):.1f}% in the last 30 days compared to the previous period. Review your recent transactions to understand this change.',
'priority': 'medium'
})
# 4. Unusual transactions
if not expenses.empty and len(expenses) > 10:
mean_expense = expenses['amount'].mean()
std_expense = expenses['amount'].std()
unusual_threshold = mean_expense + (2 * std_expense)
unusual_transactions = expenses[expenses['amount'] > unusual_threshold]
if len(unusual_transactions) > 0:
insights_to_create.append({
'insight_type': 'anomaly_detection',
'content': f'Detected {len(unusual_transactions)} unusually large transaction(s). Largest: ${unusual_transactions["amount"].max():.2f} in {unusual_transactions.iloc[unusual_transactions["amount"].argmax()]["category"]}.',
'priority': 'medium'
})
# 5. Category recommendations
if not expenses.empty:
# Find categories with high spending
avg_by_category = expenses.groupby('category')['amount'].mean()
for category, avg_amount in avg_by_category.items():
if avg_amount > 100 and category.lower() in ['shopping', 'entertainment', 'dining']:
insights_to_create.append({
'insight_type': 'recommendation',
'content': f'Your average {category} transaction is ${avg_amount:.2f}. Consider setting a budget limit for this category to control spending.',
'priority': 'low'
})
break # Only add one recommendation
# Save insights to database
for insight_data in insights_to_create[:5]: # Limit to 5 insights
insight = FinancialInsight(
user_id=user_id,
insight_type=insight_data['insight_type'],
content=insight_data['content'],
priority=insight_data['priority']
)
db.session.add(insight)
db.session.commit()
print(f"Generated {len(insights_to_create)} insights for user {user_id}")
except Exception as e:
print(f"Error generating insights: {e}")
db.session.rollback()
@app.route('/api/profile', methods=['GET', 'PUT'])
@jwt_required()
def user_profile():
user_id = get_current_user_id()
profile = UserProfile.query.filter_by(user_id=user_id).first()
if request.method == 'GET':
return jsonify({
'employment_type': profile.employment_type,
'monthly_income_range': profile.monthly_income_range,
'financial_goals': profile.financial_goals,
'risk_tolerance': profile.risk_tolerance
})
elif request.method == 'PUT':
data = request.get_json()
profile.employment_type = data.get('employment_type', profile.employment_type)
profile.monthly_income_range = data.get('monthly_income_range', profile.monthly_income_range)
profile.financial_goals = data.get('financial_goals', profile.financial_goals)
profile.risk_tolerance = data.get('risk_tolerance', profile.risk_tolerance)
profile.updated_at = datetime.utcnow()
db.session.commit()
return jsonify({'message': 'Profile updated successfully'})
@app.route('/api/transactions', methods=['GET', 'POST'])
@jwt_required()
def transactions():
user_id = get_current_user_id()
if request.method == 'GET':
transactions = Transaction.query.filter_by(user_id=user_id).order_by(Transaction.date.desc()).all()
return jsonify([{
'id': t.id,
'amount': t.amount,
'category': t.category,
'description': t.description,
'transaction_type': t.transaction_type,
'date': t.date.isoformat()
} for t in transactions])
elif request.method == 'POST':
data = request.get_json()
transaction = Transaction(
user_id=user_id,
amount=data['amount'],
category=data['category'],
description=data.get('description', ''),
transaction_type=data['transaction_type'],
date=datetime.fromisoformat(data['date'])
)
db.session.add(transaction)
db.session.commit()
# Trigger analysis for new transaction
analyze_transaction_patterns(user_id, transaction)
return jsonify({'message': 'Transaction added successfully', 'id': transaction.id}), 201
@app.route('/api/insights', methods=['GET'])
@jwt_required()
def get_insights():
user_id = get_current_user_id()
# Auto-generate insights if none exist
existing_insights = FinancialInsight.query.filter_by(user_id=user_id).count()
if existing_insights == 0:
try:
generate_insights_for_user(user_id)
except Exception as e:
print(f"Error generating insights: {e}")
insights = FinancialInsight.query.filter_by(user_id=user_id).order_by(FinancialInsight.created_at.desc()).limit(20).all()
return jsonify([{
'id': i.id,
'insight_type': i.insight_type,
'content': i.content,
'priority': i.priority,
'created_at': i.created_at.isoformat(),
'is_read': i.is_read
} for i in insights])
@app.route('/api/analysis/spending-patterns', methods=['GET'])
@jwt_required()
def spending_patterns():
user_id = get_current_user_id()
transactions = Transaction.query.filter_by(user_id=user_id, transaction_type='expense').all()
if not transactions:
return jsonify({
'category_spending': {},
'monthly_trends': {},
'total_expenses': 0,
'average_monthly': 0
})
# Convert to DataFrame for analysis
df = pd.DataFrame([{
'amount': t.amount,
'category': t.category,
'date': t.date
} for t in transactions])
# Category-wise spending
category_spending = df.groupby('category')['amount'].sum().to_dict()
# Monthly trends
df['month'] = pd.to_datetime(df['date']).dt.to_period('M')
monthly_spending = df.groupby('month')['amount'].sum().to_dict()
return jsonify({
'category_spending': {str(k): float(v) for k, v in category_spending.items()},
'monthly_trends': {str(k): float(v) for k, v in monthly_spending.items()},
'total_expenses': float(df['amount'].sum()),
'average_monthly': float(df.groupby('month')['amount'].sum().mean()) if len(df) > 0 else 0
})
@app.route('/api/analysis/income-variability', methods=['GET'])
@jwt_required()
def income_variability():
user_id = get_current_user_id()
transactions = Transaction.query.filter_by(user_id=user_id, transaction_type='income').all()
if not transactions:
return jsonify({
'monthly_income': {},
'average_income': 0,
'total_income': 0,
'variability': 0,
'stability_score': 1.0
})
df = pd.DataFrame([{
'amount': t.amount,
'date': t.date
} for t in transactions])
df['month'] = pd.to_datetime(df['date']).dt.to_period('M')
monthly_income = df.groupby('month')['amount'].sum()
# Calculate variability metrics
income_std = float(monthly_income.std()) if len(monthly_income) > 1 else 0
income_mean = float(monthly_income.mean())
variability_score = income_std / income_mean if income_mean > 0 else 0
return jsonify({
'variability_score': variability_score,
'variability': variability_score,
'monthly_income': {str(k): float(v) for k, v in monthly_income.to_dict().items()},
'average_income': income_mean,
'total_income': float(df['amount'].sum()),
'income_stability': 'stable' if variability_score < 0.2 else 'moderate' if variability_score < 0.5 else 'highly_variable'
})
@app.route('/api/coach/advice', methods=['POST'])
@jwt_required()
def get_financial_advice():
user_id = get_current_user_id()
data = request.get_json()
user_context = data.get('context', '')
# Get user's financial data
user = User.query.get(user_id)
profile = user.profile
recent_transactions = Transaction.query.filter_by(user_id=user_id).order_by(Transaction.date.desc()).limit(20).all()
# Prepare context for Gemini
financial_summary = prepare_financial_summary(user, profile, recent_transactions)
prompt = f"""
As an expert financial coach specializing in gig workers and informal sector employees,
provide personalized advice based on the following financial data:
User Profile: {financial_summary}
Specific Context: {user_context}
Consider:
1. Income variability and irregular cash flow
2. Emergency fund needs for unstable income
3. Debt management strategies
4. Savings automation for irregular income
5. Investment options for risk tolerance level: {profile.risk_tolerance}
Provide actionable, specific advice in 3-5 bullet points. Be encouraging and practical.
"""
try:
response = client.chat.completions.create(
model=AI_MODEL,
messages=[
{"role": "system", "content": "You are an expert financial coach."},
{"role": "user", "content": prompt}
],
max_tokens=1000,
temperature=0.7
)
return jsonify({'advice': response.choices[0].message.content})
except Exception as e:
return jsonify({'error': 'Failed to generate advice', 'details': str(e)}), 500
def prepare_financial_summary(user, profile, transactions):
"""Prepare a summary of user's financial situation for AI analysis"""
income_transactions = [t for t in transactions if t.transaction_type == 'income']
expense_transactions = [t for t in transactions if t.transaction_type == 'expense']
total_income = sum(t.amount for t in income_transactions)
total_expenses = sum(t.amount for t in expense_transactions)
return f"""
Name: {user.name}
Employment Type: {profile.employment_type}
Monthly Income Range: {profile.monthly_income_range}
Risk Tolerance: {profile.risk_tolerance}
Financial Goals: {profile.financial_goals}
Recent Income: {total_income}
Recent Expenses: {total_expenses}
Net Income: {total_income - total_expenses}
"""
def analyze_transaction_patterns(user_id, transaction):
"""Analyze transaction patterns and generate insights"""
try:
# Get recent transactions for pattern analysis
recent_transactions = Transaction.query.filter_by(user_id=user_id).order_by(Transaction.date.desc()).limit(30).all()
if len(recent_transactions) < 5:
return # Not enough data for analysis
# Analyze spending patterns
if transaction.transaction_type == 'expense':
analyze_spending_spike(user_id, transaction, recent_transactions)
# Analyze income patterns for gig workers
if transaction.transaction_type == 'income':
analyze_income_pattern(user_id, transaction, recent_transactions)
except Exception as e:
print(f"Error in pattern analysis: {e}")
def analyze_spending_spike(user_id, new_transaction, recent_transactions):
"""Detect unusual spending spikes"""
category_transactions = [t for t in recent_transactions if t.category == new_transaction.category and t.transaction_type == 'expense']
if len(category_transactions) < 3:
return
amounts = [t.amount for t in category_transactions]
avg_amount = np.mean(amounts)
std_amount = np.std(amounts)
# Check if new transaction is significantly higher than average
if new_transaction.amount > avg_amount + 2 * std_amount:
insight = FinancialInsight(
user_id=user_id,
insight_type='spending_pattern',
content=f"Unusual spending detected in {new_transaction.category}: ${new_transaction.amount:.2f} is significantly higher than your average of ${avg_amount:.2f}",
priority='high'
)
db.session.add(insight)
db.session.commit()
def analyze_income_pattern(user_id, new_transaction, recent_transactions):
"""Analyze income patterns for gig workers"""
income_transactions = [t for t in recent_transactions if t.transaction_type == 'income']
if len(income_transactions) < 3:
return
# Check for income gaps
sorted_dates = sorted([t.date for t in income_transactions])
gaps = []
for i in range(1, len(sorted_dates)):
gap = (sorted_dates[i] - sorted_dates[i-1]).days
gaps.append(gap)
avg_gap = np.mean(gaps)
if avg_gap > 14: # More than 2 weeks between income on average
insight = FinancialInsight(
user_id=user_id,
insight_type='income_alert',
content=f"Irregular income pattern detected: Average gap of {avg_gap:.1f} days between income sources. Consider building a larger emergency fund.",
priority='medium'
)
db.session.add(insight)
db.session.commit()
# Multi-Agent Routes
@app.route('/api/agents', methods=['GET'])
@jwt_required()
def get_agents():
"""Get all available agents and their capabilities"""
return jsonify(agent_manager.get_agent_capabilities())
@app.route('/api/agents/performance', methods=['GET'])
@jwt_required()
def get_agent_performance():
"""Get performance metrics for all agents"""
return jsonify(agent_manager.get_agent_performance())
@app.route('/api/tasks', methods=['GET', 'POST'])
@jwt_required()
def manage_tasks():
"""Get user tasks or create new task"""
user_id = get_current_user_id()
if request.method == 'GET':
tasks = Task.query.filter_by(user_id=user_id).order_by(Task.created_at.desc()).all()
return jsonify([{
'id': t.id,
'title': t.title,
'description': t.description,
'agent_type': t.agent_type,
'task_type': t.task_type,
'priority': t.priority,
'status': t.status,
'result': json.loads(t.result) if t.result else None,
'created_at': t.created_at.isoformat(),
'completed_at': t.completed_at.isoformat() if t.completed_at else None
} for t in tasks])
elif request.method == 'POST':
data = request.get_json()
# Create task record
task = Task(
user_id=user_id,
title=data['title'],
description=data.get('description', ''),
agent_type=data['agent_type'],
task_type=data.get('task_type', 'general'),
priority=data.get('priority', 'medium'),
task_data=json.dumps(data.get('task_data', {}))
)
db.session.add(task)
db.session.commit()
# Route task to appropriate agent
task_data = {
'agent_type': data['agent_type'],
'task_type': data.get('task_type', 'general'),
**data.get('task_data', {})
}
try:
import asyncio
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
result = loop.run_until_complete(agent_manager.route_task(task_data))
# Update task with result
task.status = 'completed' if result['success'] else 'failed'
task.result = json.dumps(result)
task.completed_at = datetime.utcnow()
db.session.commit()
return jsonify({
'message': 'Task completed',
'task_id': task.id,
'result': result
})
except Exception as e:
task.status = 'failed'
task.result = json.dumps({'error': str(e)})
db.session.commit()
return jsonify({'error': 'Task processing failed', 'details': str(e)}), 500
@app.route('/api/tasks/<int:task_id>', methods=['GET', 'PUT', 'DELETE'])
@jwt_required()
def manage_task(task_id):
"""Get, update, or delete specific task"""
user_id = get_current_user_id()
task = Task.query.filter_by(id=task_id, user_id=user_id).first()
if not task:
return jsonify({'error': 'Task not found'}), 404
if request.method == 'GET':
return jsonify({
'id': task.id,
'title': task.title,
'description': task.description,
'agent_type': task.agent_type,
'task_type': task.task_type,
'priority': task.priority,
'status': task.status,
'task_data': json.loads(task.task_data) if task.task_data else {},
'result': json.loads(task.result) if task.result else None,
'created_at': task.created_at.isoformat(),
'updated_at': task.updated_at.isoformat(),
'completed_at': task.completed_at.isoformat() if task.completed_at else None
})
elif request.method == 'PUT':
data = request.get_json()
task.title = data.get('title', task.title)
task.description = data.get('description', task.description)
task.priority = data.get('priority', task.priority)
task.status = data.get('status', task.status)
task.updated_at = datetime.utcnow()
db.session.commit()
return jsonify({'message': 'Task updated successfully'})
elif request.method == 'DELETE':
db.session.delete(task)
db.session.commit()
return jsonify({'message': 'Task deleted successfully'})
@app.route('/api/tasks/<int:task_id>/rerun', methods=['POST'])
@jwt_required()
def rerun_task(task_id):
"""Rerun a failed or completed task"""
user_id = get_current_user_id()
task = Task.query.filter_by(id=task_id, user_id=user_id).first()
if not task:
return jsonify({'error': 'Task not found'}), 404
# Reset task status
task.status = 'pending'
task.result = None
task.completed_at = None
db.session.commit()
# Rerun task
task_data = json.loads(task.task_data) if task.task_data else {}
task_data.update({
'agent_type': task.agent_type,
'task_type': task.task_type
})
try:
import asyncio
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
result = loop.run_until_complete(agent_manager.route_task(task_data))
task.status = 'completed' if result['success'] else 'failed'
task.result = json.dumps(result)
task.completed_at = datetime.utcnow()
db.session.commit()
return jsonify({
'message': 'Task rerun completed',
'result': result
})
except Exception as e:
task.status = 'failed'
task.result = json.dumps({'error': str(e)})
db.session.commit()
return jsonify({'error': 'Task rerun failed', 'details': str(e)}), 500
# Enhanced Financial Analysis Endpoints
@app.route('/api/insights/generate', methods=['POST'])
@jwt_required()
def generate_insights():
"""Manually trigger insight generation"""
user_id = get_current_user_id()
try:
# Delete old insights
FinancialInsight.query.filter_by(user_id=user_id).delete()
db.session.commit()
# Generate new insights
generate_insights_for_user(user_id)
return jsonify({'message': 'Insights generated successfully'}), 200
except Exception as e:
return jsonify({'error': 'Failed to generate insights', 'details': str(e)}), 500
@app.route('/api/analysis/comprehensive', methods=['GET'])
@jwt_required()
def comprehensive_financial_analysis():
"""Comprehensive financial analysis combining all metrics"""
user_id = get_current_user_id()
try:
# Get user's financial data
transactions = Transaction.query.filter_by(user_id=user_id).all()