-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_sample_data.py
More file actions
341 lines (304 loc) · 11.8 KB
/
Copy pathcreate_sample_data.py
File metadata and controls
341 lines (304 loc) · 11.8 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
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from flask import Flask
from datetime import datetime, timedelta
import random
from werkzeug.security import generate_password_hash
from database import db
from models.user_model import User, UserRole, KycStatus
from models.loan_model import Loan, LoanStatus
from services.notification_service import Notification, NotificationType, NotificationChannel
from services.behavior_monitor_service import PaymentRecord
from services.emi_service import calculate_emi
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///loan_management.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
def check_existing_data():
existing_loans = db.session.query(Loan).count()
return existing_loans > 0
def get_borrower_user():
borrower = db.session.query(User).filter(User.email == 'borrower1@example.com').first()
if not borrower:
borrower = User(
username='borrower1',
email='borrower1@example.com',
password_hash=generate_password_hash('password123'),
name='John Doe',
phone='1234567890',
income=50000.0,
bank_account='123456789',
role=UserRole.BORROWER,
kyc_status=KycStatus.VERIFIED
)
db.session.add(borrower)
db.session.commit()
return borrower
def create_sample_loans(borrower):
loan_configs = [
{
'amount': 50000.0,
'tenure': 12,
'interest_rate': 10.5,
'status': LoanStatus.SUBMITTED,
'risk_category': 'LOW',
'risk_score': 0.15,
'ai_recommendation': 'Approve',
'ai_confidence': 85.0,
'fraud_risk': 'LOW',
'fraud_confidence': 95.0
},
{
'amount': 100000.0,
'tenure': 24,
'interest_rate': 12.0,
'status': LoanStatus.UNDER_REVIEW,
'risk_category': 'LOW',
'risk_score': 0.25,
'ai_recommendation': 'Approve',
'ai_confidence': 78.0,
'fraud_risk': 'LOW',
'fraud_confidence': 92.0
},
{
'amount': 75000.0,
'tenure': 18,
'interest_rate': 11.5,
'status': LoanStatus.APPROVED,
'risk_category': 'MEDIUM',
'risk_score': 0.45,
'ai_recommendation': 'Review',
'ai_confidence': 65.0,
'fraud_risk': 'LOW',
'fraud_confidence': 88.0
},
{
'amount': 200000.0,
'tenure': 36,
'interest_rate': 14.0,
'status': LoanStatus.REJECTED,
'risk_category': 'HIGH',
'risk_score': 0.78,
'ai_recommendation': 'Reject',
'ai_confidence': 82.0,
'fraud_risk': 'MEDIUM',
'fraud_confidence': 75.0
},
{
'amount': 150000.0,
'tenure': 24,
'interest_rate': 11.0,
'status': LoanStatus.ACTIVE,
'risk_category': 'LOW',
'risk_score': 0.20,
'ai_recommendation': 'Approve',
'ai_confidence': 88.0,
'fraud_risk': 'LOW',
'fraud_confidence': 94.0,
'approved_at': datetime.utcnow() - timedelta(days=90),
'outstanding_balance': 95000.0
},
{
'amount': 250000.0,
'tenure': 36,
'interest_rate': 13.5,
'status': LoanStatus.ACTIVE,
'risk_category': 'MEDIUM',
'risk_score': 0.42,
'ai_recommendation': 'Review',
'ai_confidence': 70.0,
'fraud_risk': 'LOW',
'fraud_confidence': 89.0,
'approved_at': datetime.utcnow() - timedelta(days=180),
'outstanding_balance': 175000.0
},
{
'amount': 30000.0,
'tenure': 6,
'interest_rate': 9.5,
'status': LoanStatus.CLOSED,
'risk_category': 'LOW',
'risk_score': 0.10,
'ai_recommendation': 'Approve',
'ai_confidence': 92.0,
'fraud_risk': 'LOW',
'fraud_confidence': 98.0,
'approved_at': datetime.utcnow() - timedelta(days=365),
'outstanding_balance': 0.0
},
{
'amount': 180000.0,
'tenure': 30,
'interest_rate': 12.5,
'status': LoanStatus.ACTIVE,
'risk_category': 'HIGH',
'risk_score': 0.72,
'ai_recommendation': 'Reject',
'ai_confidence': 76.0,
'fraud_risk': 'MEDIUM',
'fraud_confidence': 72.0,
'approved_at': datetime.utcnow() - timedelta(days=60),
'outstanding_balance': 150000.0
},
{
'amount': 60000.0,
'tenure': 15,
'interest_rate': 10.0,
'status': LoanStatus.SUBMITTED,
'risk_category': 'MEDIUM',
'risk_score': 0.48,
'ai_recommendation': 'Review',
'ai_confidence': 68.0,
'fraud_risk': 'LOW',
'fraud_confidence': 85.0
},
{
'amount': 120000.0,
'tenure': 20,
'interest_rate': 11.0,
'status': LoanStatus.UNDER_REVIEW,
'risk_category': 'HIGH',
'risk_score': 0.68,
'ai_recommendation': 'Reject',
'ai_confidence': 74.0,
'fraud_risk': 'MEDIUM',
'fraud_confidence': 70.0
}
]
loans = []
for config in loan_configs:
emi = calculate_emi(config['amount'], config['interest_rate'], config['tenure'])
loan = Loan(
user_id=borrower.id,
amount=config['amount'],
tenure=config['tenure'],
interest_rate=config['interest_rate'],
status=config['status'],
emi_amount=emi,
outstanding_balance=config.get('outstanding_balance', config['amount']),
created_at=datetime.utcnow() - timedelta(days=random.randint(1, 180)),
approved_at=config.get('approved_at'),
risk_score=config['risk_score'],
risk_category=config['risk_category'],
ai_recommendation=config['ai_recommendation'],
ai_confidence=config['ai_confidence'],
fraud_risk=config['fraud_risk'],
fraud_confidence=config['fraud_confidence']
)
db.session.add(loan)
loans.append(loan)
db.session.commit()
return loans
def create_payment_records(borrower, loans):
active_loans = [loan for loan in loans if loan.status == LoanStatus.ACTIVE]
payment_statuses = ['PAID', 'PAID', 'PAID', 'ON_TIME', 'DELAYED', 'MISSED']
for loan in active_loans:
num_payments = random.randint(3, 8)
for i in range(num_payments):
due_date = loan.approved_at + timedelta(days=30 * (i + 1))
if i < num_payments - 1:
delay = random.choice([-2, -1, 0, 1, 3, 7])
payment_date = due_date + timedelta(days=delay)
status = 'PAID'
else:
payment_date = None
status = 'PENDING'
payment_record = PaymentRecord(
user_id=borrower.id,
loan_id=loan.id,
amount=loan.emi_amount,
due_date=due_date,
payment_date=payment_date,
status=status,
delay_days=(payment_date - due_date).days if payment_date else 0
)
db.session.add(payment_record)
db.session.commit()
def create_notifications(borrower, loans):
notification_configs = [
{
'type': NotificationType.EMI_DUE_REMINDER,
'message': 'Reminder: Your EMI of ₹12,500 is due on 15 March 2026.',
'channel': NotificationChannel.EMAIL
},
{
'type': NotificationType.PAYMENT_CONFIRMATION,
'message': 'Payment of ₹12,500 received. Thank you for your repayment.',
'channel': NotificationChannel.BOTH
},
{
'type': NotificationType.RISK_ALERT,
'message': 'Alert: Your loan has MEDIUM risk. Please maintain timely repayments.',
'channel': NotificationChannel.EMAIL
},
{
'type': NotificationType.REPAYMENT_NUDGE,
'message': 'Your repayment behavior impacts your loan eligibility. Please ensure timely payments.',
'channel': NotificationChannel.SMS
},
{
'type': NotificationType.EMI_DUE_REMINDER,
'message': 'Reminder: Your EMI of ₹8,750 is due on 20 March 2026.',
'channel': NotificationChannel.BOTH
},
{
'type': NotificationType.PAYMENT_CONFIRMATION,
'message': 'Payment of ₹8,750 received. Thank you for your repayment.',
'channel': NotificationChannel.EMAIL
}
]
for i, config in enumerate(notification_configs):
loan = loans[i % len(loans)] if loans else None
notification = Notification(
user_id=borrower.id,
loan_id=loan.id if loan else None,
notification_type=config['type'].value,
channel=config['channel'].value,
message=config['message'],
sent_at=datetime.utcnow() - timedelta(days=random.randint(0, 30)),
is_read=random.choice([True, False])
)
db.session.add(notification)
db.session.commit()
def clear_existing_sample_data():
db.session.query(PaymentRecord).delete()
db.session.query(Notification).delete()
db.session.query(Loan).delete()
db.session.commit()
def main(force_recreate=False):
with app.app_context():
if check_existing_data():
if force_recreate:
print("Clearing existing sample data...")
clear_existing_sample_data()
else:
print("Sample data already exists in the database.")
print("Run with --force flag to clear and recreate sample data.")
return
print("Creating sample loan data...")
borrower = get_borrower_user()
print(f"Using borrower: {borrower.email}")
loans = create_sample_loans(borrower)
print(f"Created {len(loans)} sample loans")
create_payment_records(borrower, loans)
print("Created sample payment records")
create_notifications(borrower, loans)
print("Created sample notifications")
print("\nSample data created successfully!")
print(f"- Loans with SUBMITTED status: {sum(1 for l in loans if l.status == LoanStatus.SUBMITTED)}")
print(f"- Loans with UNDER_REVIEW status: {sum(1 for l in loans if l.status == LoanStatus.UNDER_REVIEW)}")
print(f"- Loans with APPROVED status: {sum(1 for l in loans if l.status == LoanStatus.APPROVED)}")
print(f"- Loans with REJECTED status: {sum(1 for l in loans if l.status == LoanStatus.REJECTED)}")
print(f"- Loans with ACTIVE status: {sum(1 for l in loans if l.status == LoanStatus.ACTIVE)}")
print(f"- Loans with CLOSED status: {sum(1 for l in loans if l.status == LoanStatus.CLOSED)}")
print(f"- LOW risk loans: {sum(1 for l in loans if l.risk_category == 'LOW')}")
print(f"- MEDIUM risk loans: {sum(1 for l in loans if l.risk_category == 'MEDIUM')}")
print(f"- HIGH risk loans: {sum(1 for l in loans if l.risk_category == 'HIGH')}")
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Create sample loan data')
parser.add_argument('--force', '-f', action='store_true',
help='Clear existing sample data and recreate')
args = parser.parse_args()
main(force_recreate=args.force)