-
Notifications
You must be signed in to change notification settings - Fork 1
/
Credit Risk Assessment - Nicken Shidqia N.py
3837 lines (2204 loc) · 108 KB
/
Credit Risk Assessment - Nicken Shidqia N.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
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
#!/usr/bin/env python
# coding: utf-8
# # Credit Risk Assessment
# ## Import Libraries & Read Data
# In[1]:
#import library
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
#display all columns
pd.set_option('display.max_columns', None)
#display all row
pd.set_option('display.max_rows', None)
# In[2]:
#read data
df = pd.read_csv(r'D:\Dokumen\Portfolio Project\Credit Risk IDX Partners/loan_data_2007_2014.csv')
df.head()
# ## Data Cleaning
# In[3]:
#check rows & column
df.shape
print(f'row : {df.shape[0]}')
print(f'column : {df.shape[1]}')
# In[4]:
#drop columnn Unnamed: 0 because it is just index on dataset
df.drop(columns =['Unnamed: 0'], inplace = True)
df.head()
# In[5]:
#data understanding
df.info()
# In[6]:
#create subset based on column data type
categorical = df.select_dtypes(include = 'object')
numerical = df.select_dtypes(exclude = 'object')
#convert column to list
categorical_col = categorical.columns.to_list()
numerical_col = numerical.columns.to_list()
# In[7]:
df[numerical_col].describe()
# In[8]:
#check null values on numerical
df[numerical_col].isnull().sum()
# There are many features of numerical column that have null values :
# - annual_inc
# - delinq_2yrs
# - inq_last_6mths
# - mths_since_last_delinq
# - mths_since_last_record
# - open_acc
# - pub_rec
# - revol_util
# - total_acc
# - collections_12_mths_ex_med
# - mths_since_last_major_derog
# - annual_inc_joint
# - dti_joint
# - verification_status_joint
# - acc_now_delinq
# - tot_coll_amt
# - tot_cur_bal
# - open_acc_6m
# - open_il_6m
# - open_il_12m
# - open_il_24m
# - mths_since_rcnt_il
# - total_bal_il
# - il_util
# - open_rv_12m
# - open_rv_24m
# - max_bal_bc
# - all_util
# - total_rev_hi_lim
# - inq_fi
# - total_cu_tl
# - inq_last_12m
# In[9]:
#check null values on categorical
df[categorical_col].isnull().sum()
# There are many features of categorical column that have null values :
# - emp_title
# - emp_length
# - desc
# - last_pymnt_d
# - next_pymnt_d
# - last_credit_pull_d
# In[10]:
df[categorical_col].describe().T
# Insight :
# Some features with date values still have object data type, need to convert it to datetime :
# - issue_d
# - last_pymnt_d
# - next_pymnt_d
# - last_credit_pull_d
# ### Check Duplicated Values
# In[11]:
#check duplicated values
df.duplicated().sum()
# Insight :
# There is no duplicate data
# ### Check Missing Values
# In[12]:
#count total null in each column
sum_null = df.isnull().sum()
#count % of total null in each column
missing_percent = (sum_null * 100)/len(df)
#type of each column
df_type = [df[col].dtype for col in df.columns]
#create new dataframe for missing value
df_isnull = pd.DataFrame({'total_null':sum_null,
'data_type':df_type,
'percentage_missing':missing_percent})
#sort percentage of missing value from largest to lowest
df_isnull.sort_values('percentage_missing', ascending = False, inplace = True)
#display all missing values
df_isnull_sort = df_isnull[df_isnull['percentage_missing']>0].reset_index()
df_isnull_sort
# ### Handling Missing Value
# In[13]:
#drop feature that have missing value > 50%
col_null = df_isnull.loc[df_isnull['percentage_missing']>50].index.tolist()
df.drop(columns = col_null, inplace = True)
# In[14]:
df.head(2)
# In[15]:
#replace missing values on feature tot_coll_amt, tot_cur_bal, total_rev_hi_lim with 0,
#the assumption is the customer didnt' borrow again
for item in ['tot_coll_amt', 'tot_cur_bal', 'total_rev_hi_lim']:
df[item] = df[item].fillna(0)
# **Notes :**
# - 'tot_coll_amt' = Total collection amounts ever owed
# - 'tot_cur_bal' = Total current balance of all accounts
# - 'total_rev_hi_lim' = Total revolving high credit/credit limit
# In[16]:
df[['tot_coll_amt', 'tot_cur_bal', 'total_rev_hi_lim']].head(2)
# In[17]:
#replace missing values on numerical category with median
numericals = df.select_dtypes(exclude = 'object')
for item in numericals:
df[item] = df[item].fillna(df[item].median())
# In[18]:
numericals.head(2)
# In[19]:
#replace missing values on categorical with mode
categoricals = df.select_dtypes(include = 'object')
for item in categoricals:
df[item] = df[item].fillna(df[item].mode().iloc[0])
# In[20]:
#check whether still have missing value
df.isnull().sum()
# ### Drop Unnecessary Column
# In[21]:
df.drop(columns = ['member_id','url','title','addr_state','zip_code','policy_code','application_type','emp_title'], inplace = True)
df_clean = df.copy()
# ## Feature Engineering
# ### Feature : 'earliest_cr_line','last_credit_pull_d','last_pymnt_d','issue_d','next_pymnt_d'
# In[22]:
#check date feature
df_clean[['earliest_cr_line','last_credit_pull_d','last_pymnt_d','issue_d','next_pymnt_d']].head(2)
# In[23]:
#change format to datetime
df_clean['earliest_cr_line']=pd.to_datetime(df_clean['earliest_cr_line'], format = '%b-%y')
df_clean['last_credit_pull_d']=pd.to_datetime(df_clean['last_credit_pull_d'], format = '%b-%y')
df_clean['last_pymnt_d']=pd.to_datetime(df_clean['last_pymnt_d'], format = '%b-%y')
df_clean['issue_d']=pd.to_datetime(df_clean['issue_d'], format = '%b-%y')
df_clean['next_pymnt_d']=pd.to_datetime(df_clean['next_pymnt_d'], format = '%b-%y')
#check date feature after conversion:
df_clean[['earliest_cr_line','last_credit_pull_d','last_pymnt_d','issue_d','next_pymnt_d']].head(2)
# **Notes :**
# - 'earliest_cr_line' = The month the borrower's earliest reported credit line was opened
# - 'last_pymnt_d' = Last month payment was received
# - 'issue_d'= The month which the loan was funded
# - 'next_pymnt_d' = Next scheduled payment date
# In[24]:
#Adding new feature :
#pymnt_time = the number of month between 'next_pymnt_d' and 'last_pymnt_d'
#credit_pull_year = the number of year between 'last_credit_pull_d' and 'earliest_cr_line'
#adding pymnt_time
def diff_month(d1,d2):
return (d1.year - d2.year)*12 + (d1.month - d2.month)
df_clean['pymnt_time'] = df_clean.apply(lambda x : diff_month(x.next_pymnt_d, x.last_pymnt_d), axis =1)
#adding credit_pull_year
def diff_year(d1,d2):
return (d1.year - d2.year)
df_clean['credit_pull_year'] = df_clean.apply(lambda x : diff_year(x.last_credit_pull_d, x.earliest_cr_line), axis =1)
df_clean.head(2)
# In[25]:
#display pymnt_time < 0
df_clean[df_clean['pymnt_time']<0][['next_pymnt_d','last_pymnt_d','pymnt_time']]
# **Insight :**
# There are negative values in pymnt_time, it means that the customer cannot afford to make a payment.
# So the values gonna get replaced with 0
# In[26]:
#display credit_pull_year
df_clean[df_clean['credit_pull_year']<0][['last_credit_pull_d', 'earliest_cr_line', 'credit_pull_year']].head()
# **Insight :**
# There are negative values in credit_pull_year, because there are false input in earliest_cr_line column.
# So the values gonna get replaced with the maximum of the credit_pull_year feature.
# In[27]:
#replace the value of 'pymnt_time' and 'credit_pull_year'
df_clean.loc[df_clean['pymnt_time']<0] = 0
df_clean.loc[df_clean['credit_pull_year']<0] = df_clean['credit_pull_year'].max()
# In[28]:
#check if 'pymnt_time' and 'credit_pull_year' already getting replaced
df_clean[['pymnt_time','credit_pull_year']].sort_values(['pymnt_time','credit_pull_year'],ascending = [True, True]).head(5)
# ### Feature : Term
# In[29]:
#count term value
df_clean['term'].value_counts()
# In[30]:
#extract number from string with regex capture
df_clean['term'] = df_clean['term'].str.extract('(\d+)')
# In[31]:
#check whether the number already being extract
df_clean['term'].head()
# In[32]:
#count extract of term value
df_clean['term'].value_counts()
# In[33]:
#display feature data
df_clean.head(3)
# ## Exploratory Data Analysis (EDA)
# ### Removing Highly Correlated Features
# In[34]:
#copy dataset
df_eda = df_clean.copy()
# In[35]:
#drop id columns
df_eda.drop(columns = ['id'], inplace = True)
# In[36]:
#plot correlation matrix with 3 decimal places
plt.figure(figsize=(25,25))
sns.heatmap(df_eda.corr(), annot = True, fmt = '.3f')
# **Notes:**
# remove feature that have correlation > 0.9, because it could lead to biased result if left unchecked
# In[37]:
#correlation table with absolute number (no negative, only positive)
corr_matrix = df_eda.corr().abs()
corr_matrix
# **Notes :**
# **Removing highly correlated features (Dimensionality Reduction in Python)**
# Features that are perfectly correlated to each other, with a correlation coefficient of one or minus one, bring no new information to a dataset but do add to the complexity. So naturally, we would want to drop one of the two features that hold the same information. In addition to this we might want to drop features that have correlation coefficients close to one or minus one if they are measurements of the same or similar things. Not just for simplicity's sake but also to avoid models to overfit on the small, probably meaningless, differences between these values.
# **Notes :**
# Correlation coefficients whose magnitude are between 0.7 and 0.9 indicate variables which can be considered highly correlated. Because of that, for correlation > 0.9 are gonna removed
# In[38]:
#create and apply mask
mask = corr_matrix.where(np.triu(np.ones(corr_matrix.shape, dtype = bool), k=1))
mask
# In[39]:
#high correlated column
high_col = [col for col in mask.columns if any (mask[col] > 0.9)]
high_col
# In[40]:
#drop high correlated column
df_eda.drop(high_col, axis = 1, inplace = True)
# In[41]:
df_eda.head(2)
# In[42]:
#display categorical value
df_eda.select_dtypes(include = 'object').nunique()
# grade and sub_grade has similar interpretations, so drop the sub_grade, because already represented with grade
# In[43]:
#drop sub_grade column
df_eda.drop(['sub_grade'],axis =1, inplace =True)
# ### Univariate Analysis
# In[44]:
#create subset of numerical and categorical
num = df_eda.select_dtypes(include = 'number').columns
category = df_eda.select_dtypes(include ='object').columns
# In[45]:
df_eda.select_dtypes(include ='object').head(2)
# #### Loan Status
# In[46]:
#plot loan status with descending order:
plt.figure(figsize=(15,10))
sns.countplot(y = df_eda['loan_status'], palette='Set2', order =df_eda['loan_status'].value_counts().index)
plt.title('Loan Status', fontsize=14)
for i,value in enumerate(df_eda['loan_status'].value_counts(normalize=True).mul(100).round(2)):
text = f'{value} %'
plt.text(value, i, text, fontsize=15, ha='left')
plt.xlabel('Count')
plt.ylabel('Loan Status')
plt.show()
# **Insight :**
# - The majority of loan status distribution is current 47.95%, and fully paid 39.54%, it means that the borrower are meeting their payment obligation.
# - There are significant number of charged off 9.08%. It means that the borrower has become delinquent on payments, and potential financial loss from the lender.
# - Late (31-120 days) is 1.48%. It means that there are delay in loan payment for 31-120 days, potential warnings that the lender has financial difficulties
# - In grace period with 0.67%. The grace period is a time allowance for repaying the loan principal and interest within a certain period. And it is available after the payment due date (maturity). Need to do monitoring to minimize loan failure.
# - Doesn't meet the credit policy with 0.43%. It means some borrowers were proved, even though doesn't meet the standard credit criteria.
#
# From those insight, gonna create new feature called **loan_status** that indicates if the loan is considered good or bad.
# - **Good loan** status is either current and fully paid.
# - **Bad loan** status except for these 2 things.
# In[47]:
#copy new dataframe
df_loan = df_eda.copy()
#create list of good loan
good_loan = ['Current','Fully Paid']
#create new column 'target'
#if the value is 0 means good loan, if 1 means bad loan
df_loan['target'] = df_loan['loan_status'].apply(lambda x : 0 if x in good_loan else 1)
# In[48]:
#check if the column already being added
df_loan.head(2)
# In[49]:
df_loan['target'].value_counts()
# In[50]:
plt.figure(figsize=(15,10))
sns.countplot(y = df_loan['target'], palette='Set2', order =df_loan['target'].value_counts().index)
plt.title('Borrower Status Rate', fontsize=20)
for i,value in enumerate(df_loan['target'].value_counts(normalize=True).mul(100).round(2)):
text = f'{value} %'
plt.text(value, i, text, fontsize=15, ha='left', va='center')
plt.xlabel('Borrower Status Rate', fontsize=15)
plt.ylabel('percentage', fontsize=15)
plt.show()
# **Insight :**
# - Good loan status got high percentage with 87.49%. It means that the bank's loan performing is good. It seems that the bank has good risk management and credit assessment.
# - Bad loan status got low percentage with 12.51%. It means the bank need to analyzing the characteristic of the borrower, so they could identify early warnings sign, and implement the mitigation from failure of pay loans from customers.
# #### Credit Purpose
# In[51]:
#plot number of loan purpose
plt.figure(figsize=(15,10))
sns.countplot(y = df_loan['purpose'], palette='Set2', order =df_loan['purpose'].value_counts().index)
plt.title('Number of Loan Purpose', fontsize=20)
for i,value in enumerate(df_loan['purpose'].value_counts(normalize=True).mul(100).round(2)):
text = f'{value} %'
plt.text(value, i, text, fontsize=15, ha='left', va='center')
plt.xlabel('Count', fontsize=15)
plt.ylabel('Purpose', fontsize=15)
plt.show()
# **Insight :**
# - Debt consolidation got the highest percentage for load purpose with 58.67%. Debt consolidation is preferred because the customer can taking out a single loan or credit card to pay off multiple debts. The benefits of debt consolidation include a potentially lower interest rate and lower monthly payments.
# - Credit card got high percentage too with 22.27%. Credit card is preferred because it is typically offer all kinds of perks and benefits, including a one-time signing bonus for a new cardholder, cash back for purchases, rewards points, and frequent-flyer miles. Credit cards provide a level of safety for the user that a debit card and cash can't: fraud protection.
# - Home improvement got 5.67% for loan purpose. Home improvement is preferred because the borrower could get funds faster. Applying for a personal loan is generally a seamless process that can be completed online in minutes. Many online lenders also offer same or next-day funding, which means the borrower can get started on home improvements immediately. Also the fixed interest rate on a personal loan also means the monthly payment will stay the same, making it easier to work into spending plan each month over the life of the loan.
# #### Grade
# In[52]:
df_loan['grade'].value_counts()
# In[53]:
#plot number of grade
plt.figure(figsize=(15,10))
sns.countplot(y = df_loan['grade'], palette='Set2', order =df_loan['grade'].value_counts().index)
plt.title('Number of Grade', fontsize=20)
for i,value in enumerate(df_loan['grade'].value_counts(normalize=True).mul(100).round(2)):
text = f'{value} %'
plt.text(value, i, text, fontsize=15, ha='left', va='center')
plt.xlabel('Count', fontsize=15)
plt.ylabel('Grade', fontsize=15)
plt.show()
# **Insight :**
# - Middle grade B and C got the highest percentage with 29.28% and 26.8%. It means that quality score to a loan based on a borrower's credit history, quality of the collateral, and the likelihood of repayment of the principal and interest are considered moderate.
# - Grade D with 16.45%. It means that the number of borrower that doesn't have good likelihood of repayment history is quite high.
# - Grade A with 16.01%. It means that quality score to a loan based on a borrower's credit history are considered high. It could lead with low risk of load failure.
# - Grade E,F,G got the lowest percentage. Grade E,F,G are high risk grade, because because the likelihood that the borrower will repay the loan is low. So the loan company need to tighten the criteria for loan borrowers.
# #### Loan Term
# In[54]:
df_loan['term'].value_counts()
# In[55]:
#plot number of loan term
plt.figure(figsize=(15,10))
sns.countplot(y = df_loan['term'], palette='Set2', order =df_loan['term'].value_counts().index)
plt.title('Number of Loan Term', fontsize=20)
for i,value in enumerate(df_loan['term'].value_counts(normalize=True).mul(100).round(2)):
text = f'{value} %'
plt.text(value, i, text, fontsize=15, ha='left', va='center')
plt.xlabel('Count', fontsize=15)
plt.ylabel('Loan Term', fontsize=15)
plt.show()
# **Insight :**
# 36 month of loan term got the highest percentage with 72.47%. It means that short term loan are preferred by borrowers rather than long term loan. The reason could be because :
# - Compared to long term loans, the amount of interest paid is significantly less.
# - These loans are considered less risky compared to long term loans because of a shorter maturity date.
# - Short term loans are the lifesavers of smaller businesses or individuals who suffer from less than stellar credit scores.
# #### Home Ownership
# In[56]:
df_loan['home_ownership'].value_counts()
# In[57]:
#plot number of home ownership
plt.figure(figsize=(15,10))
sns.countplot(y = df_loan['home_ownership'], palette='Set2', order =df_loan['home_ownership'].value_counts().index)
plt.title('Number of Home Ownership', fontsize=20)
for i,value in enumerate(df_loan['home_ownership'].value_counts(normalize=True).mul(100).round(2)):
text = f'{value} %'
plt.text(value, i, text, fontsize=15, ha='left', va='center')
plt.xlabel('Count', fontsize=15)
plt.ylabel('Home Ownership', fontsize=15)
plt.show()
# **Insight :**
# - The borrower that has mortgage got the highest percentage on home ownership with 50.44%. The reason that mortgage customer is so many because a mortgage allows the customer to purchase a home without paying the full purchase price in cash. And for many people taking out a mortgage loan makes a property affordable because it would take too long to save up.
# - The second highest is the borrower that rent their houses with 40.35%. The reason that customer choose rent rather than buying house is because no maintenance costs or repair bills, access to amenities like pool or fitness centre, no real estate taxes, and more flexibility as to where to live.
# - The borrower that own their houses is 8.9%. Only small portions for the customer that fully paid off their properties or acquired them without mortgage.
# ### Bivariate Analysis
# #### Borrower Status Rate by Grade
# In[58]:
#create cross tabulation of grade and target
grade_crosstab = pd.crosstab(df_loan['grade'],df_loan['target'], normalize='index').sort_values(by=1).round(2)
grade_crosstab
# In[59]:
#bar plot for grade and target
grade_bar = grade_crosstab.sort_values(by=1, ascending=False).plot(kind='barh', stacked=True, rot=0, colormap ='Pastel2')
grade_bar.legend(['Good', 'Bad'], bbox_to_anchor=(1,1), loc='upper left')
#add annotation
for i in grade_bar.containers:
grade_bar.bar_label(i, label_type='center')
#set title and x,y axis label
plt.title('Borrower Status Rate by Grade', size=15)
plt.xlabel('Grade', size=12)
plt.ylabel('Percentage', size=12)
# **Insight :**
# - Grade A has the most of good borrowers with 96%, and has the least of bad borrowers with only 4%.So Grade A has the least probability of loan default.
# - Grade G has the least of good borrowers with 66%, and has the most of bad borrowers with 34%. So Grade G has the most probability of loan default.
# - The lower the quality of a grade, the higher the number of bad borrowers, which will lead to a higher possibility of loan default.
# #### Borrower Status Rate by Last Credit Pull Year
# *) Notes :
# Credit pull happens when borowers officially apply for credit, such as by filling out a credit card application. The last credit pull date shows if the borrower has recently applied for other loans or credit cards.
# In[60]:
#display needed column
df_loan[['earliest_cr_line','last_credit_pull_d','last_pymnt_d','issue_d','next_pymnt_d','target']].head(2)
# In[61]:
#convert to datetime
df_loan['last_credit_pull_d'] = pd.to_datetime(df_loan['last_credit_pull_d'], errors='coerce')
# In[62]:
#extract year from 'last_credit_pull_d'
df_loan['last_credit_pull_d_year'] = df_loan['last_credit_pull_d'].dt.year
# In[63]:
#check whether year already being extracted
df_loan['last_credit_pull_d_year'].head(2)
# In[64]:
#create cross tabulation for last_credit_pull_d_year and target
pull_d_year_ct = pd.crosstab(df_loan['last_credit_pull_d_year'],df_loan['target'])
pull_d_year_sum = pull_d_year_ct.sum(axis=1).astype(float)
pull_d_year_rate = pull_d_year_ct.div(pull_d_year_sum, axis=0)
pull_d_year_rate.index = np.arange(2007,2017)
# In[65]:
#create percentage of good and bad borrowers each year
good = pull_d_year_rate[0]
bad = pull_d_year_rate[1]
# In[66]:
#plot borrower's status rate
plt.figure(figsize=(10,7))
plt.plot(pull_d_year_rate.index, good, marker='D',linestyle ='-', color='#9FBB73' ,label = 'Good Borrower')
plt.plot(pull_d_year_rate.index, bad, marker='D',linestyle ='-', color='#EC8F5E' ,label = 'Bad Borrower')
#create percentage labels
for x,y in zip(pull_d_year_rate.index, good.round(2)):
plt.text(x,y,f'{y*100}%', ha='center', va='bottom', color='black' )
for x,y in zip(pull_d_year_rate.index, bad.round(2)):
plt.text(x,y,f'{y*100}%', ha='center', va='bottom', color='black')
#set tick labels
plt.xticks(np.arange(2007,2017,1))
plt.yticks(np.arange(0,1.1,0.1))
#set grid lines
plt.grid(True, linestyle='--', alpha=0.5)
#set title and x,y axis label
plt.title('Borrower Status Rate by Last Credit Pull Year', size=15)
plt.xlabel('Year', size=12)
plt.ylabel('Percentage', size=12)
#add legend
plt.legend()
#adjust plot margins so labels wont being cut off
plt.tight_layout()
plt.show()
# **Insight :**
# - From 2007 to 2008, there was a slight increase 4% in the number of good borrowers. But from 2008 to 2009, there was a quite drastic decrease of 13%.
# - The upward trend for good borrower started from 2009 to 2016.This means that many borrowers pay their loans on time, and the credit selection for borrowers by loan companies is quite strict.
# - From 2007 to 2008, there was a slight decrease 5% in the number of bad borrowers. But from 2008 to 2009, there was a quite drastic increase of 21%.
# - The downward trend for bad borrower started from 2009 to 2016.This would be good signal for lenders company.
# #### Borrower Status Rate by Last Payment Date
# *) Last payment date is date of last payment received. The last payment date shows if the borrower is having difficulty making payments.
# In[67]:
#convert to datetime
df_loan['last_pymnt_d'] = pd.to_datetime(df_loan['last_pymnt_d'], errors='coerce')
# In[68]:
#extract year from 'last_pymnt_d'
df_loan['last_pymnt_d_year'] = df_loan['last_pymnt_d'].dt.year
# In[69]:
#create cross tabulation for last_pymnt_d and target
last_pymnt_d_year_ct = pd.crosstab(df_loan['last_pymnt_d_year'],df_loan['target'])
last_pymnt_d_year_sum = last_pymnt_d_year_ct.sum(axis=1).astype(float)
last_pymnt_d_year_rate = last_pymnt_d_year_ct.div(last_pymnt_d_year_sum, axis=0)
last_pymnt_d_year_rate.index = np.arange(2007,2017)
# In[70]:
#create percentage of good and bad borrowers each year
goods = last_pymnt_d_year_rate[0]
bads = last_pymnt_d_year_rate[1]
# In[71]:
#good and bad borrowers from 2008 to 2016
goods_1 = goods[1:]
bads_1 = bads[1:]
# In[72]:
#create range year from 2008 to 2016
range_year = last_pymnt_d_year_rate.index[1:]
range_year
# In[73]:
#plot borrower's status rate
plt.figure(figsize=(10,7))
plt.plot(range_year, goods_1, marker='D',linestyle ='-', color='#9FBB73' ,label = 'Good Borrower')
plt.plot(range_year, bads_1, marker='D',linestyle ='-', color='#EC8F5E' ,label = 'Bad Borrower')
#create percentage labels
for x,y in zip(range_year, goods_1.round(2)):
plt.text(x,y,f'{y:.1%}', ha='center', va='bottom', color='black' )
for x,y in zip(range_year, bads_1.round(2)):
plt.text(x,y,f'{y:.1%}', ha='center', va='bottom', color='black')
#set tick labels
plt.xticks(np.arange(2008,2017,1))
plt.yticks(np.arange(0,1.1,0.1))
#set grid lines
plt.grid(True, linestyle='--', alpha=0.5)
#set title and x,y axis label
plt.title('Borrower Status Rate by Last Payment Year', size=15)
plt.xlabel('Year', size=12)
plt.ylabel('Percentage', size=12)
#add legend
plt.legend()
#adjust plot margins so labels wont being cut off
plt.tight_layout()
plt.show()
# **Insight :**
# - There is upward trend for good borrower by last payment year from 2008 to 2016. It means that the percentage of customers who have no difficulty in paying is getting higher. And this is good for the sustainability of the loan company's revenue.
# - There is downward trend for bad borrower by last payment year from 2008 to 2016. It means that the company's performance is very good in selecting loan applications by borrowers.
# - The difference percentage between good and bad borrowers for 2016 is really signicant with 98%. It means that the management could implement the stategy and policy in borrower eligibility and risk assessment.
# #### Borrower's Status Interest Rate
# In[74]:
#create new dataframe
data_kde = df_loan[['last_pymnt_d_year', 'int_rate', 'target']]
data_kde.head(2)
# In[75]:
#select data from 2008 - 2016
kde_1 = data_kde[data_kde['last_pymnt_d_year']>2007].sort_values('last_pymnt_d_year', ascending = True)
kde_1.head(2)
# In[76]:
#average interest rate
int_avg = round(df_loan['int_rate'].mean(),2)
#average interest rate of good borrower
kde_good = kde_1[kde_1['target']==0]
int_good = round(kde_good['int_rate'].mean(),2)
#average interest rate of bad borrower
kde_bad = kde_1[kde_1['target']==1].sort_values('last_pymnt_d_year', ascending = True)
int_bad = round(kde_bad['int_rate'].mean(),2)
print(f'average interest rate: {int_avg}')
print(f'average good borrower int rate: {int_good}')
print(f'average bad borrower int rate: {int_bad}')
# In[77]:
#plot borrower's status rate
plt.figure(figsize=(8,6))
#create Kernel Density Estimation
sns.kdeplot(data = kde_1, x='int_rate', hue='target', palette='Set2')
#add vertical line at the average of int_rate
plt.axvline(kde_1['int_rate'].mean(), color = 'black', linestyle ='dashed', linewidth = 1, alpha=0.5)
plt.axvline(int_good, color = 'green', linestyle ='dashed', linewidth = 1, alpha=0.5)
plt.axvline(int_bad, color = 'orange', linestyle ='dashed', linewidth = 1, alpha=0.5)
#set the title
plt.title("Borrower's Status Interest Rate")
#set the legend
plt.legend(['Bad Borrower', 'Good Borrower'])
#create percentage labels
plt.text(0.62, 0.8, f"mean interest rate: {int_avg}\n"
f"mean good borrower int rate: {int_good}\n"
f"mean bad borrower int rate: {int_bad}"
, bbox=dict(facecolor='w', alpha=0.5, pad=5),
transform=plt.gca().transAxes, ha="left", va="top")
plt.tight_layout()
plt.show()
# Based on creditninja.com(2023), the loan interest rate obtained by the borrower depends on the credit score and loan term. A good credit score makes it possible to access lower interest rates when applying for a personal loan. Credit scores depend on the borrower's creditworthiness and financial stability as well as that of the lender. The average interest rate on personal loans for borrowers with excellent credit is between 10% and 12.5%. For a good credit score, the average rate is 13% – 16%. The lower the borrower's credit score, the higher the interest rate will be to offset the increased risk the lender assumes.
#
# **Insight :**
# - The average interest rate for all borrowers is 13.91%.
# - The average interest rate for good borrowers is 13.54%.
# - The average interest rate for bad borrowers is 15.9%.
# - The average loan interest rate for all borrowers at ID/X Partners is still relatively good because it is in the range of 13% – 16%. The reason why the average interest rate for bad borrowers is higher than for good borrowers is because the lower the borrower's credit score is, the higher the interest rates become to compensate for the increased risk the lender takes on.
# In[78]:
#function for automation
#create function for kde plot
def kda_chart(data, x, hue, palette, good, bad, title, size_x, size_y, text_all, value_all, text_good, value_good, text_bad, value_bad):
#plot borrower's status rate
plt.figure(figsize=(8,6))
#create Kernel Density Estimation
sns.kdeplot(data = data, x=x, hue=hue, palette=palette)
#add vertical line at the average of int_rate
plt.axvline(data[x].mean(), color = 'black', linestyle ='dashed', linewidth = 1, alpha=0.5)
plt.axvline(good, color = 'green', linestyle ='dashed', linewidth = 1, alpha=0.5)
plt.axvline(bad, color = 'orange', linestyle ='dashed', linewidth = 1, alpha=0.5)
#create percentage labels