-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoanPredictionCode.Rmd
More file actions
2888 lines (1421 loc) · 94.8 KB
/
Copy pathLoanPredictionCode.Rmd
File metadata and controls
2888 lines (1421 loc) · 94.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
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
---
title: "Data Mining - 1A, B and 2 "
author: "Yash Karande, Shalaka Thakare, Tushar Yadav"
date: "09/06/2021"
output:
pdf_document: default
html_document: default
---
### Lending Club
## {.tabset}
### Assignment 1A and 1B
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE)
```
#### Loading necessary libraries
```{r results='hide'}
# Loading the libraries
library(tidyverse)
library(lubridate)
library(stringr)
library(pROC)
library(rpart)
library(ROCR)
library(C50)
library(caret)
library(ranger)
library(glmnet)
```
#### Loading the data
```{r pressure}
lcdf <- read_csv('/Users/yashkarande/Desktop/Loan default prediction and analysis/Assignment 1/lcDataSample.csv')
# Checking number of rows and columns in the lc dataframe
paste0('The number of rows are = ', nrow(lcdf))
paste0('The number of columns are = ',ncol(lcdf))
```
#### How many differnt types of loan status exist in the data?
```{r}
lcdf %>% group_by(loan_status) %>% tally()
paste0("Since there are values apart from the target - fullly paid and charged off we will keep only fully paid and charged off loans from the target variable.
#Filtering the dataframe and updating it to the same dataframe")
```
#### Filtering for Charged off and Fully Paid
```{r}
### Since there are values apart from the target - fullly paid and charged off we will keep only fully paid and charged off loans from the target variable.
#Filtering the dataframe and updating it to the same dataframe
lcdf <- lcdf %>% filter(loan_status == "Fully Paid" | loan_status == "Charged Off")
lcdf %>% group_by(loan_status) %>% tally()
```
#### Distribution of Loan Status
```{r}
loan_status_count <- lcdf %>% group_by(loan_status) %>% count()
pct <- round(loan_status_count$n/sum(loan_status_count$n)*100)
lbls <- paste(loan_status_count$loan_status, pct) # add percents to labels
lbls <- paste(lbls,"%",sep="") # ad % to labels
pie(loan_status_count$n, labels = lbls, main="Percentage of Loans with Loan Status")
```
#### Analzing Interest Rate
<font size="2">We will create a box plot to visualize the spread of the interest rate </font>
```{r}
summary(lcdf$int_rate)
ggplot(lcdf, aes( x = int_rate)) + geom_boxplot() +
xlab("Interest Rate ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
```
<font > 25 Percentile of loans give less than 8.9% interest rate. Median of the interest rate of all loans in 11.99%. The interest rate can go as high as 28.99 % in some case.The interest rate when higher can be a high risk loan. This interest seems really active to invest in. Very few investment products give an interest of 12%. </font>
#### Home Ownership
```{r}
ggplot(lcdf, aes( x = home_ownership)) + geom_bar(colour="black", fill="white") +ggtitle("Number of Loans By Homeownerships") + xlab("Different Types of Homeownership") + ylab("Number of Loans ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
```
<font > Most borrowers are not owning a home. Most of loans were given to people who have mortgaged and rented house. </font>
#### Loan Grades
<font>Loans also have different grade and we would want to see how many of them are present in each grade along with loan status </font>
```{r}
lcdf %>% group_by(grade) %>% tally()
```
<font >Adding the loan status to check on loan status and grade together</font>
```{r}
table(lcdf$loan_status, lcdf$grade)
```
<font>Some loans have been charged off in the grade 'A'
Some loans in grade 'G' have been fully paid. Let us look at the default percentage of each grade to get a better picture. </font>
```{r}
lcdf %>% group_by(grade) %>% summarise(TotalLoans=n(), FullyPaid=sum(loan_status=="Fully Paid"), ChargedOff=sum(loan_status=="Charged Off"), default_percentage = ChargedOff/TotalLoans*100)
```
#### How does number of loans, loan amount, interest rate vary by grade?
```{r}
# Number of Loans, Sum of Loan Amout, Mean Loan Amount Mean Int Rate by Grade
lcdf %>% group_by(grade) %>% summarise(numberOfLoans=n(), TotLoanAmt=sum(loan_amnt),MeanLoanAmt=mean(loan_amnt),defaults=sum(loan_status=="Charged Off"), defaultRate=defaults/numberOfLoans, default_percentage = defaultRate*100,MeanIntRate=mean(int_rate),stdInterest=sd(int_rate), minInt = min(int_rate),maxInt=max(int_rate),avgLoanAMt=mean(loan_amnt), sumPmnt=sum(total_pymnt),avgPmnt=mean(total_pymnt))
# Loan Amount Distribution
ggplot(lcdf, aes( x = loan_amnt)) + geom_histogram(aes(y=..density..), colour="black", fill="white", bins=15)+ geom_density(alpha=.2, fill="#FF6666") + ggtitle("Distribution of Loan Amount Changing Bins ") + xlab("Loan Amount ") + ylab("Number of Loans ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
# Loan Amount Distribution by Grade
ggplot(lcdf, aes( x = loan_amnt)) + geom_histogram(aes(fill=grade)) + ggtitle("Distribution of Loan Amount With Grade") + xlab("Loan Amount ") + ylab("Number of Loans ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
# Let us look at the distribution
ggplot(lcdf, aes( x = loan_amnt)) + geom_boxplot(aes(fill=grade)) +
xlab("Loan Amount ") + ylab("Grades of Each Loan ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
# Let us look at the loan amount along with loan status
ggplot(lcdf, aes( x = loan_amnt)) + geom_histogram(aes(y=..density..), colour="black", fill="white", bins=15)+ geom_density(alpha=.2, fill="#FF6666") + ggtitle("Distribution of Number of Loans, Loan Amount with Status ") + facet_wrap(~loan_status) + xlab("Loan Amount ") + ylab("Number of Loans ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
# Let us look at the Interest Rate
ggplot(lcdf, aes( x = int_rate)) + geom_histogram(aes(y=..density..), colour="black", fill="white")+ geom_density(alpha=.2, fill="#FF6666") +ggtitle("Distribution of Interest Rate") + xlab("Interest Rate ") + ylab("Number of Loans ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
# Interest Rate with Grade
ggplot(lcdf, aes( x = int_rate)) + geom_histogram(aes(fill=grade)) + ggtitle("Distribution of Interest Rate With Grade") + xlab("Interest Rate ") + ylab("Number of Loans ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
```
<font>The default rate percentage increases from Grade A to H. Average Payments are more than average average loan amount in each grade. Yes these numbers surprise us-> when compare the returns of the different grade with NASDAQ for last 16 years (2007-2022 Current Year) which yields about 16.7 percent average - there are some grades which are not able to beat the market. Considering both NASDAQ and P2P market are highly volatile and even further risks in P2P we would expect them to give more average returns. If we had to invest in only one grade - depending on the risk apetite we would have chosen # grade C. Although it has a low average interest rate compared to other higher risk grades(D,E,F), it has an average interest rate of 14% which is sufficient to double the money in 5 years time. </font>
<font> The loan amount varies from 400 to 38,000. Most number of loans are of the amount approximately 12,000$. Most Grade G loans are of lesser amounts. he number of charged off loans are less in overall number, and it is evident in the graph # Both these distribution seem to be left skewed. In an ideal case these would have been normally distributed.There are loans which are higher than 30,000 and still paid.Also, there are loans of less than 10,000 and charged off </font>
<font> We can see that the average interest rate is higher in higher grades of loans. Intuitively we might be more interested in higher rates, however they come with
trade off higher risk. The graph shows that the interest rate varies from 0-28. Most number of loans ~13-14% interest rate. Trend of interest rate with grade - Lower Grade corresponds to lower interest rate. Intutivetly, we should prefer a lower grade loan if both grades give same interest rate. The most common loan is grade B loan with a ~13% interest</font>
#### Outliers Analysis
```{r}
#Look at the variable summaries -- focus on a subset of the variables of interest in your analyses & modeling
#lcdf %>% select_if(is.numeric) %>% summary()
# Let us look at the outliers in loan amount -
ggplot(lcdf, aes( x = loan_amnt)) + geom_boxplot(aes(fill=grade)) +
xlab("Loan Amount ") + ylab("Grades of Each Loan ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
# Let us look at the annual income
ggplot(lcdf, aes( x = annual_inc)) + geom_histogram(aes(y=..density..), colour="black", fill="white")+ geom_density(alpha=.2, fill="#FF6666") + ggtitle("Distribution of Number of Loans With Annual Income ") + xlab("Annual Income ") + ylab("Number of Loans ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
# Let us check how are these very high income associated with loans status
ggplot(lcdf, aes( x = annual_inc, y=loan_status)) + geom_boxplot(aes(fill=loan_status)) + ggtitle("Distribution of Number of Loans With Annual Income By Loan Status - Before Removing Extreme Outliers") + xlab("Annual Income ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
```
<font> Yes, there are outliers. However to remove them we should check the frequency and also see the business use case these outliers might be justified given the fact that loan amount can vary. </font>
<font> For annual income the data seems to really skewed towards the left, very few loans have the income more than 1.5 Milliion. A person coming to lending club for loan with income more than 1.5 million might be suspicious. It is logical to think about why would a person need a loan with 1.5 million income. Hence we will remove thes 9 observation. We could alternatively assignment a maximum value, since we have 110k data point we can remove 9 rows </font>
<font> The very high income cases are for paid-off loans. # We can exclude them, however we do so we might not have a decision tree model which predicts the hypothesis that high income people pay off the loan in most cases.Going with the use case we will discard and keep them in a separate dataframe.We shall observe what difeerence it makes to out models in the later part. Compared to the 110k data size the number looks really small, hence we will remove these </font>
#### Removing the outliers for annual income
```{r}
## Chunk 12 <For knitting of .rmd file>
lcdf <- lcdf %>% filter(annual_inc <= 1500000)
# Let us look at the new distribution of annual income after outlier removal
ggplot(lcdf, aes( x = annual_inc, y=loan_status)) + geom_boxplot(aes(fill=loan_status)) + ggtitle("Distribution of Number of Loans With Annual Income By Loan Status - After Removing Extreme Outliers ") + xlab("Annual Income ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
```
<font>The plot looks much cleaner, and inference can be drawn from the the above as we have removed those outliers.We might argue to the fact that data still has outliers, but removing the ones above 1.5 IQR now we might lose essential information. However this was the case when we removed observations above 1.5 million, but they were just 9 observations in the 109k observations.</font>
#### Revol util
<font> Ratio of current balance/ high credit limit. </font>
```{r}
### Chunk 13
ggplot(lcdf, aes( x = revol_util)) + geom_boxplot() + ggtitle("Distribution of Revol Util ") + xlab("Revol Util") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
# Identified outliers by boxplot
out_ru <- boxplot(lcdf$revol_util, plot=FALSE)$out
#Let us look at these examples
out_ru_i <-which(lcdf$revol_util %in% out_ru)
lcdf[out_ru_i,]
# We will remove these 9 outliers
lcdf <- lcdf [-out_ru_i, ]
```
#### Recoveries and Total Payment Analysis
```{r}
# Recoveries - post a loan charged off gross amount recovered
# Checking if recoveries are only for charged off loans
lcdf %>% group_by(loan_status) %>%summarise(Rec=sum(recoveries))
lcdf %>% group_by(loan_status) %>%summarise(Sum_Rec=sum(recoveries), TotPmnt=sum(total_pymnt), total_rec_prncp=sum(total_rec_prncp), total_rec_int=sum(total_rec_int), total_rec_late_fee=sum(total_rec_late_fee))
```
<font> Hence recoveries are only for charged off loans, this also goes with the general idea of recovery of credit for any loan it will only be for the charged off if it has to be there. Sometimes recovery might not be present for the charged off loans as well. This is the case where there has been a loss. </font>
<font> he way to calulate recovered amount in terms of charged loans ='total_pymnt'= 'total_rec_prncp'+'total_rec_int'+'total_rec_late_fee'+'recoveries' </font>
#### Actual Return
```{r}
# Let us look at some columns
lcdf %>% select(loan_status, int_rate, funded_amnt, total_pymnt) %>% head()
# We will use the following to calculate annualized return
#annReturn = [(Total Payment - funded amount)/funded amount]*12/36*100
lcdf$annRet <- ((lcdf$total_pymnt -lcdf$funded_amnt)/lcdf$funded_amnt)*(12/36)*100
# Returns for charged off and fully paid loans
lcdf %>% group_by(loan_status) %>% summarise(avgRet=mean(annRet), stdRet=sd(annRet), minRet=min(annRet), maxRet=max(annRet))
# Do charged off loans have negative returns -
lcdf %>% select(loan_status, int_rate, funded_amnt, total_pymnt, annRet) %>% filter(annRet < 0) %>% count(loan_status)
```
<font> What is surprising here is the fact that the avg return rate differ significantly fro average interest rate . The minimum return rate for some loans which are fully paid can go as minimum as 0. </font> <font size=4> This might be because some loans which are paid off are paid off earlier than the expected date.</font>
#### Returns from loans - Fully Paid and Charged off
```{r}
## Chunk 16
# Fully Paid
lcdf %>% filter( loan_status == "Fully Paid") %>% group_by(grade) %>% summarise(nLoans=n(), avgInterest= mean(int_rate), avgLoanAmt=mean(loan_amnt), avgPmnt=mean(total_pymnt), avgRet=mean(annRet), minRet=min(annRet), maxRet=max(annRet))
# Adding subgrade
lcdf %>% filter( loan_status == "Fully Paid") %>% group_by(sub_grade) %>% summarise(nLoans=n(), avgInterest= mean(int_rate), avgLoanAmt=mean(loan_amnt), avgPmnt=mean(total_pymnt), avgRet=mean(annRet), minRet=min(annRet), maxRet=max(annRet))
# Charged Off
lcdf %>% filter( loan_status == "Charged Off") %>% group_by(grade) %>% summarise(nLoans=n(), avgInterest= mean(int_rate), avgLoanAmt=mean(loan_amnt), avgPmnt=mean(total_pymnt), avgRet=mean(annRet), minRet=min(annRet), maxRet=max(annRet))
# Adding Subgrade
lcdf %>% filter( loan_status == "Charged Off") %>% group_by(sub_grade) %>% summarise(nLoans=n(), avgInterest= mean(int_rate), avgLoanAmt=mean(loan_amnt), avgPmnt=mean(total_pymnt), avgRet=mean(annRet), minRet=min(annRet), maxRet=max(annRet))
```
# Checking if loans paid paid early -
```{r}
# Chunk 17
# 2 dates we will use - payment and issue date
head(lcdf[, c("last_pymnt_d", "issue_d")])
# Bringing them to a consistent format
lcdf$last_pymnt_d<-paste(lcdf$last_pymnt_d, "-01", sep = "")
lcdf$last_pymnt_d<-parse_date_time(lcdf$last_pymnt_d, "myd")
#Check their format now
head(lcdf[, c("last_pymnt_d", "issue_d")])
# Creating actual term column - If loan is charged off by default - 3 years
lcdf$actualTerm <- ifelse(lcdf$loan_status=="Fully Paid", as.duration(lcdf$issue_d %--% lcdf$last_pymnt_d)/dyears(1), 3)
# We know using simple interest Total = principle + pnr/100
# Hence r = (Total - principle)/principle * 100/n
# Then, considering this actual term, the actual annual return is
lcdf$actualReturn <- ifelse(lcdf$actualTerm>0, ((lcdf$total_pymnt -lcdf$funded_amnt)/lcdf$funded_amnt)*(1/lcdf$actualTerm)*100, 0)
lcdf %>% select(loan_status, int_rate, funded_amnt, total_pymnt, annRet, actualTerm, issue_d,last_pymnt_d) %>% head()
# Checking the same for charged off loans
lcdf %>% select(loan_status, int_rate, funded_amnt, total_pymnt, annRet, actualTerm, actualReturn) %>% filter(loan_status=="Charged Off") %>% head()
```
# Additional Analysis on returns
```{r}
# Chunk 17
# For cost-based performance, we may want to see the average interest rate, and the average of proportion of loan amount paid back, grouped by loan_status
lcdf%>% group_by(loan_status) %>% summarise( meanintRate=mean(int_rate), meanRet=mean((total_pymnt-funded_amnt)/funded_amnt),meanRetPer=mean((total_pymnt-funded_amnt)/funded_amnt)*100, sumTotalpymt = sum(total_pymnt), sumFundedamnt = sum(funded_amnt), term=mean(actualTerm) )
# Checking the same by grade along with loan status
lcdf%>% group_by(loan_status, grade) %>% summarise( intRate=mean(int_rate),meanRet=mean((total_pymnt-funded_amnt)/funded_amnt),
meanRetPer=mean((total_pymnt-funded_amnt)/funded_amnt)*100,sumTotalpymt = sum(total_pymnt), sumFundedamnt = sum(funded_amnt), term=mean(actualTerm) )
# For Fully Paid loans, is the average value of totRet what you'd expect, considering the average value for intRate?
lcdf %>% group_by(loan_status) %>% summarise(avgInt=mean(int_rate), avgRet=mean(actualReturn),avgTerm=mean(actualTerm))
```
<font>We also observe the actual term for loan is not 3 years in case of fully paid loans. Indeed some loans are fully paid earlier than 3 years.</font>
<font># Charged off loans are expected to have negative return irrespective of the grade. Higher graded have higher loss / negative mean return rate. But the distribution of the return is only between -0.36 - -0.466 in case of charged off loans.In case of fully paid loans, higher grades give higher average return. The range of return is higher 0.09 to 0.349.
We would want our investor to get the best returns and minimize losses at the same time.</font>
#### Distribution of actual term
```{r}
# Chunk 21
ggplot(lcdf %>% filter(loan_status=='Fully Paid'), aes( x = actualTerm)) + geom_histogram(aes(y=..density..), colour="black", fill="white", bins=50) +ggtitle("Distribution of Actual Term ") + xlab("Actual Term ") + ylab("Number of Loans ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
ggplot(lcdf %>% filter(loan_status=='Fully Paid'), aes( x = actualTerm, y=grade)) + geom_boxplot(aes(fill=grade)) + ggtitle("Distribution of Actual Term With Loan Grade ")+
xlab("Actual Term ") + ylab("Grade") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
```
#### Employment Length
```{r}
# Arranging them since they
lcdf$emp_length <- factor(lcdf$emp_length, levels=c("n/a", "< 1 year","1 year","2 years", "3 years" , "4 years", "5 years", "6 years", "7 years" , "8 years", "9 years", "10+ years" ))
# Number of loans in each employment length
ggplot(data = lcdf, aes(x = emp_length)) + geom_bar() + ggtitle("Number of Loans in Each Employement Length ") + xlab("Employement Length ") + ylab("Number of Loans ")+ theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
# Results in a table
table(lcdf$loan_status, lcdf$emp_length)
# Calculating the proportion of defaults across employment length
lcdf %>% group_by(emp_length) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), defaultPercentage=defaults/nLoans*100, avgIntRate=mean(int_rate), avgLoanAmt=mean(loan_amnt), avgActRet = mean(actualReturn), avgActTerm=mean(actualTerm))
# Plot for Distribution of Loan Amount with Employment Length
ggplot(lcdf, aes( x = loan_amnt, y=emp_length)) + geom_boxplot(aes(fill=emp_length)) +
xlab("Loan Amount ") + ylab("Employment Length ")+ggtitle("Distribution of Loan Amount with Employement Length") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
```
<font> The internal percentage of default within a grade differ by emp length. This is a good factor to understand how employment length plays a role in defaults and returns </font>
# Loan Purpose
```{r}
# Checking number of loans by purpose
lcdf %>% group_by(purpose) %>% tally()
lcdf$purpose <- as.character(lcdf$purpose )
lcdf$purpose <- str_trim(lcdf$purpose )
lcdf$purpose <- as.factor(lcdf$purpose )
lcdf$purpose <- fct_collapse(lcdf$purpose, other = c("wedding","renewable_energy", "other"),NULL = "H")
lcdf %>% group_by(purpose) %>% tally()
# Get the number of loans by loan purpose
ggplot(data = lcdf, aes(x = purpose)) + geom_bar() + ggtitle("Number of Loans By Purpose") + xlab("Purpose of Loan ") + ylab("Number of Loans ")+ theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold")) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
#Plot of loan amount by purpose
ggplot(lcdf, aes( x = loan_amnt, y=purpose)) + geom_boxplot(aes(fill=purpose)) +
xlab("Loan Amount ") + ylab("Pupose of Each Loan ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
# Percentages
lcdf %>% group_by(purpose) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), Default_per = defaults/nLoans)
#Does loan-grade vary by purpose? Which pupose the loan grade fall in?
table(lcdf$purpose, lcdf$grade)
#Bivariate analysis of employment length and purpose.
table(lcdf$purpose, lcdf$emp_length)
#do those with home-improvement loans own or rent a home? Checking because loan improvement should be with the people who own a home. Very rarely tenant would take a loan for home improvement
table(lcdf$purpose,lcdf$home_ownership)
```
<font> More than half (58 %) of loans were taken for debt consolidation. This follows the the Pareto principle of 80:20 rule, as the top 3 puposes are more than 80% of loan purposes.mall business has higher default percentage. Loan borrowed for smaller business is defaulted the most in terms of percentage.It is also indicative of the fact that borrowers are coming to lending club for small business as they might have been already declined for a loan by bank.he loans show a very similar pattern irrespective of the purpose. Most number of loans in B for some cases , C followed by A grade loans. People with 10 + years of experience are the most common borrower of loan for credit card and debt consolidation. Home improvement loans are more common with 10+ years of experience.car loans are more common with people having 2 years of experience. Which might be reflective of the fact that once people are in job for 2 years they would want to keep a car for which they come to the lending club. We can see that home improvement loans were not the all with those owning the house. This might be because they were doing home improvement in rented house. Also more than 60% home were mortgaged. Also it can happen i might not directly own the house, owned by the partner while person borrowing the loan is doing home improvement over it.We can see the distribution of loan amount by various purposes.We can see that small business loans have significant distribution, fairly wide spred. Implying scales might be diffeerent for the small business. </font>
#### Derived Attributes - proportion of satisfactory bankcard accounts, length of borrower's history, ratio of openAccounts to totalAccounts
```{r}
# num_bc_tl - number number of card
# and num_bc_sats satisfactory card
lcdf$propSatisBankcardAccts <- ifelse(lcdf$num_bc_tl>0, lcdf$num_bc_sats/lcdf$num_bc_tl, 0)
# Let us look at the column created
summary(lcdf$propSatisBankcardAccts)
# Plot
ggplot(lcdf, aes( x = propSatisBankcardAccts, y=loan_status)) + geom_boxplot(aes(fill=loan_status)) + ggtitle("Distribution of Proportion of Satisfactory Bank Cards") +
xlab("Proportion of Satisfactory Bank Cards ") + ylab(" Loan Status ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
#Another one - lets calculate the length of borrower's history
# i.e time between earliest_cr_line - open of current credit line. The month the borrowers earliers
# issue_d
# Correcting the date format
lcdf$earliest_cr_line<-paste(lcdf$earliest_cr_line, "-01", sep = "")
lcdf$earliest_cr_line<-parse_date_time(lcdf$earliest_cr_line, "myd")
lcdf$earliest_cr_line %>% head()
lcdf$borrHistory <- as.duration(lcdf$earliest_cr_line %--% lcdf$issue_d ) / dyears(1)
ggplot(lcdf, aes( x = borrHistory, y=loan_status)) + geom_boxplot(aes(fill=loan_status)) +
xlab("Borrower History in Years ") + ylab("Loan Status")+ggtitle("Distribution of Borrower History") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
#Another new attribute: ratio of openAccounts to totalAccounts
lcdf$openAccRatio <- ifelse(lcdf$total_acc>0, lcdf$open_acc/lcdf$total_acc, 0)
summary(lcdf$openAccRatio)
# Min. 1st Qu. Median Mean 3rd Qu. Max.
# 0.0000 0.3704 0.4815 0.5017 0.6154 1.0000
ggplot(lcdf, aes( x = openAccRatio)) + geom_boxplot(aes(fill=loan_status)) +
xlab("Proportion of Open Account to Total Accounts ") + ylab(" Loan Status ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
#does LC-assigned loan grade vary by borrHistory?
lcdf %>% group_by(grade) %>% summarise(avgBorrHist=mean(borrHistory))
ggplot(lcdf, aes( x = borrHistory)) + geom_boxplot(aes(fill=grade)) +
xlab("Borrower History ") + ylab(" Loan Status ") + theme(plot.title = element_text(color="#993333", size=14, face="bold.italic"), axis.title.x = element_text(color="#993333", size=14, face="bold"), axis.title.y = element_text(color="#993333", size=14, face="bold"))
lcdf %>% group_by(grade) %>% summarise(avgBorrHist=mean(borrHistory), minBorrHist=min(borrHistory), maxBorrHist = max(borrHistory), medianBorrHist=median(borrHistory))
```
<font>Yes, assigned loan grade varies, significantly with the borrower history. We can also check the min, max median in the below box plot </font>
#### Converting character variables
```{r}
#glimpse(lcdf)
# there are a few character type variables - grade, sub_grade, verification_status,....
# We can convert all of these to factor
lcdf <- lcdf %>% mutate_if(is.character, as.factor)
#Checking the datatype after conversion
#glimpse(lcdf)
```
#### Leakage variables
<font>
Concept of leakage - In statistics and machine learning, leakage (also known as data leakage or target leakage) is the use of information in the model training process which would not be expected to be available at prediction time, causing the predictive scores (metrics) to overestimate the model's utility when run in a production environment.Reference - https://en.wikipedia.org/wiki/Leakage_(machine_learning)#:~:text=In%20statistics%20and%20machine%20learning,when%20run%20in%20a%20production</font>
```{r}
#Identified the variables you want to remove
varsToRemove = c('funded_amnt_inv', 'term', 'emp_title', 'pymnt_plan', 'earliest_cr_line', 'title', 'zip_code', 'addr_state', 'out_prncp', 'out_prncp_inv', 'total_pymnt_inv', 'total_rec_prncp', 'total_rec_int', 'total_rec_late_fee', 'recoveries', 'collection_recovery_fee', 'last_credit_pull_d', 'policy_code', 'disbursement_method', 'debt_settlement_flag', 'settlement_term', 'application_type')
lcdf <- lcdf %>% select(-all_of(varsToRemove))
#Drop all the variables with names starting with "hardship" -- as they can cause leakage, unknown at the time when the loan was given.
#First checking before dropping
lcdf %>% select(starts_with("hardship"))
# Dropping
lcdf <- lcdf %>% select(-starts_with("hardship"))
#similarly, all variable starting with "settlement", these are happening after disbursement
lcdf %>% select(starts_with('settlement'))
# 4 columns
#Dropping them
lcdf <- lcdf %>% select(-starts_with("settlement"))
# Additional Leakage variables - based on our understanding
varsToRemove2 <- c("last_pymnt_d", "last_pymnt_amnt", "issue_d",'next_pymnt_d', 'deferral_term', 'payment_plan_start_date', 'debt_settlement_flag_date' )
# last_pymnt_d, last_pymnt_amnt, next_pymnt_d, deferral_term, payment_plan_start_date, debt_settlement_flag_date
lcdf <- lcdf %>% select(-all_of(varsToRemove2))
```
<font> Understanding the leakage is very important in the concept of Data Mining where we will be going ahead to predict models based on the training data. The models will be well trained if we use the leakage variable, however when we get unseen set of data the prediction will be poor as they wont be having values of these variables</font>
#### Missing Values
<font>Potential reasons for missing values in different variables?
Are some of the missing values actually 'zeros' which are not recorded in the data?
Is missing-ness informative in some way? Are there, for example, more/less defaults for cases where values on the attribute are missing ? </font>
```{r}
# Dropping columns with all n/a
lcdf %>% select_if(function(x){ all(is.na(x)) } ) # Checking what are those columns
lcdf <- lcdf %>% select_if(function(x){ ! all(is.na(x)) } ) # Dropping
# Finding names of columns which has atleast 1 missing values
names(lcdf)[colSums(is.na(lcdf)) > 0]
# Finding proportion
options(scipen=999) # To not use scientific notation
colMeans(is.na(lcdf))[colMeans(is.na(lcdf))>0]
# Finding the columns which have more than 60% missing values
names(lcdf)[colMeans(is.na(lcdf))>0.6]
nm<-names(lcdf)[colMeans(is.na(lcdf))>0.6]
lcdf <- lcdf %>% select(-all_of(nm))
#Impute missing values for remaining variables which have missing values
# - first get the columns with missing values
colMeans(is.na(lcdf))[colMeans(is.na(lcdf))>0]
nm<- names(lcdf)[colSums(is.na(lcdf))>0]
summary(lcdf[, nm])
# Replacing values - adding median values
lcdf<- lcdf %>% replace_na(list(mths_since_last_delinq=median(lcdf$mths_since_last_delinq, na.rm=TRUE), bc_open_to_buy=median(lcdf$bc_open_to_buy, na.rm=TRUE), mo_sin_old_il_acct=median(lcdf$mo_sin_old_il_acct,na.rm=TRUE), mths_since_recent_bc=median(lcdf$mths_since_recent_bc, na.rm=TRUE), mths_since_recent_inq=5, num_tl_120dpd_2m = median(lcdf$num_tl_120dpd_2m, na.rm=TRUE),percent_bc_gt_75 = median(lcdf$percent_bc_gt_75, na.rm=TRUE), bc_util=median(lcdf$bc_util, na.rm=TRUE) ))
lcdf<- lcdf %>% mutate_if(is.numeric, ~ifelse(is.na(.x), median(.x, na.rm = TRUE), .x))
dim(lcdf)
```
<font>Yes, some columns have same percentage of missing values. This could be because they are dependent columns. Information source of a column is also the source of other columns could be the reason. These missing values can be because of the following - 1. Missing Completely at Random 2. Missing at Random 3. Missing Not At Random. We could use various techniques taught in class to impute these missing values. 1. Imputing values 2. Leaving those rows. However approach for each column can be different. We could use various techniques taught in class to impute these missing values. 1. Imputing values 2. Leaving those rows. However approach for each column can be different. If they do not relate well to larger values, than we should not assume that missings are for values higher than the max.We will remove columns with more than 60% missing values, this is taken as a trial and test way - However when it comes to removing columns with NA approach could be different in each case. This could also mean loss of very important variable. We can tune our model based on the results
</font>
#### Univariate Analysis - AUC
<font> which variables are individually predictive of the outcome ?
Considering a single variable model to predict loan_status, what could be a measure of performance? AUC? For a univariate model with a variable, say, x1, what should we consider as the model 'score' for predicting loan_status? Can we take the values of x1 as the score for a model y_hat=f(x1) ? Using this approximate approach, we can then compute the AUC for each variable. AUC of a classifier is equivalent to the probability that the classifier will rank a randomly chosen positive instance higher than a randomly chosen negative instance.Reference - https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7695228/ </font>
```{r}
#We will use the function auc(response, prediction) which returns the AUC value for the specified predictor variable, and considering the response variable as the dependent.
aucAll<- sapply(lcdf %>% mutate_if(is.factor, as.numeric) %>% select_if(is.numeric), auc, response=lcdf$loan_status)
library(broom)
tidy(aucAll[aucAll > 0.5])
tidy(aucAll) %>% arrange(desc(aucAll))
```
<font>Example, actualReturn, actualTerm are in the data - we have kept these because they will be useful for evaluating performance of models.
High AUC effect on model It tells how much the model is capable of distinguishing between classes. Higher the AUC, the better the model is at predicting 0 classes as 0 and 1 classes as 1. By analogy, the Higher the AUC, the better the model is at distinguishing between patients with the disease and no disease. Will need to make sure these are not included in building the models </font>
#### Building the model - Splitting the data into Train and Test
<font> Defining train and test Train Data set: Used to fit the machine learning model.
Test Data set: Used to evaluate the fit machine learning model.While there are no set rules to define the proportion of test and train data - the split should be enough to train the model well to predict well on the unseen data. So we could try various splits and check how the model performs. Our aim throughout is good generalization. Reference - https://machinelearningmastery.com/train-test-split-for-evaluating-machine-learning-algorithms/</font>
```{r}
## set the seed to make your partition reproducible
set.seed(123)
TRNPROP = 0.5 #proportion of examples in the training sample
nr<-nrow(lcdf)
nr
trnIndex<- sample(1:nr, size = round(TRNPROP * nr), replace=FALSE)
lcdfTrn <- lcdf[trnIndex, ] # Train data
lcdfTst <- lcdf[-trnIndex, ] # Test data
```
#### Decision Tree Model -
```{r}
# Variables for the modelling
# No we dont want to use all the variable - we will remove the leakage variables we found in the AUC combined table
# Variables like actualTerm, actualReturn, annRet, total_pymnt will be useful in performance assessment, but should not be used in building the model.
varsOmit <- c('actualTerm', 'actualReturn', 'annRet', 'total_pymnt')
# Checking if target variable is factor
class(lcdf$loan_status)
# Converting it to factor where Fully paid is target
lcdf$loan_status <- factor(lcdf$loan_status, levels=c("Fully Paid", "Charged Off"))
# Decision Tree - Model
lcDT1 <- rpart(loan_status ~., data=lcdfTrn %>% select(-all_of(varsOmit)), method="class", parms = list(split = "information"), control = rpart.control(minsplit = 30))
printcp(lcDT1)
```
<font>The complexity parameter (CP)is not the error in that particular node. It is the amount by which splitting that node improved the relative error. So in your example, splitting the original root node dropped the relative error from 1.0 to 0.5, so the CP of the root node is 0.5. The CP of the next node is only 0.01 (which is the default limit for deciding when to consider splits). So splitting that node only resulted in an improvement of 0.01, so the tree building stopped there.</font>
#### Changing cp, minimum split
```{r}
lcDT1 <- rpart(loan_status ~., data=lcdfTrn %>% select(-all_of(varsOmit)), method="class", parms = list(split = "information"), control = rpart.control(cp=0.0001, minsplit = 50))
#check for performance with different cp levels
printcp(lcDT1)
lcDT1$variable.importance %>% head(10)
```
#### Pruning the tree based on different cp values - 0.0015, 0.0002, 0.0003
<font>We will now prune the tree to see the performance, this pruning will be based on different cp values </font>
```{r}
# We will change values of cp to see different models
lcDT1p1<- prune.rpart(lcDT1, cp=0.0015)
printcp(lcDT1p1)
lcDT1p1$variable.importance %>%head(10)
lcDT1p2<- prune.rpart(lcDT1, cp=0.0002)
printcp(lcDT1p2)
lcDT1p2$variable.importance %>%head(10)
lcDT1p3<- prune.rpart(lcDT1, cp=0.0003)
printcp(lcDT1p3)
lcDT1p3$variable.importance %>%head(10)
```
#### Model based on more balanced dataset
<font>Using the 'prior' parameters to account for unbalanced training data. The 'prior' parameter can be used to specify the distribution of examples across classes. By default, the prior is taken from the dataset</font>
```{r}
#Training the model considering a more balanced training dataset?
lcDT1b <- rpart(loan_status ~., data=lcdfTrn %>% select(-all_of(varsOmit)),
method="class", parms = list(split = "gini", prior=c(0.5, 0.5)),
control = rpart.control(cp=0.0, minsplit = 20, minbucket = 10, maxdepth = 20, xval=10) )
printcp(lcDT1b)
lcDT1b$variable.importance %>% head(10)
# Pruning the balanced tree
lcDT1bp<- prune.rpart(lcDT1b, cp=0.001301)
printcp(lcDT1bp)
lcDT1bp$variable.importance %>% head(10)
plot(lcDT1bp)
```
<font> We had a dataset which was first split into 50:50. We created a model changed the cost parameter.Then we pruned the tree with different values of cp. We also created a balanced model, later pruned the tree. </font>
#### Evalution of the model
```{r}
# Using the predict function, training data set
confusionM <- function(models, data) {
predTrn=predict(models,data, type='class')
tab1 = table(predicted = predTrn, true=data$loan_status)
print(mean(predTrn == data$loan_status))
return(tab1)
}
# Model with fully grown tree
# Train
confusionM(lcDT1,lcdfTrn)
# Test
confusionM(lcDT1, lcdfTst)
# Model with pruned tree with following p values
confusionM(lcDT1p2,lcdfTrn)
confusionM(lcDT1p3,lcdfTrn)
# Model with balanced dataset
confusionM(lcDT1b, lcdfTrn)
# Model balanced and pruned
confusionM(lcDT1bp, lcdfTrn)
```
#### Threshold - 0.3 from 0.5 - For all the above models
<font> We qualified all the results above 0.5 towards charged off, we will now change the threshold to a lower value. This change is based towards our goal towards detecting Charged Off Loans well. The threshold value changes are made based on the goal you want to achieve. Trying out multiple thresholds is also an option. </font>
```{r}
# 1. Using this threshold for train and test dataset
CTHRESH=0.3
# Using the model which is fully grown
predProbTrn=predict(lcDT1,lcdfTrn, type='prob')
predTrnCT = ifelse(predProbTrn[, 'Charged Off'] > CTHRESH, 'Charged Off', 'Fully Paid')
table(predTrnCT , true=lcdfTrn$loan_status)
predProbTst=predict(lcDT1,lcdfTst, type='prob')
predTstCT = ifelse(predProbTst[, 'Charged Off'] > CTHRESH, 'Charged Off', 'Fully Paid')
table(predTstCT , true=lcdfTst$loan_status)
# Building the roc and auc curve
score=predict(lcDT1,lcdfTst, type="prob")[,"Charged Off"]
pred=prediction(score, lcdfTst$loan_status, label.ordering = c("Fully Paid", "Charged Off"))
#label.ordering here specifies the 'negative', 'positive' class labels
# Closer to one specifies charged off
#ROC curve
aucPerf <-performance(pred, "tpr", "fpr")
plot(aucPerf)
abline(a=0, b= 1)
#AUC value
aucPerf=performance(pred, "auc")
aucPerf@y.values
# [[1]]
# [1] 0.6400753
#Lift curve
liftPerf <-performance(pred, "lift", "rpp")
plot(liftPerf)
# 2. Using the model which were pruned - p2
predProbTrn=predict(lcDT1p2,lcdfTrn, type='prob')
predTrnCT = ifelse(predProbTrn[, 'Charged Off'] > CTHRESH, 'Charged Off', 'Fully Paid')
table(predTrnCT , true=lcdfTrn$loan_status)
predProbTst=predict(lcDT1p2,lcdfTst, type='prob')
predTstCT = ifelse(predProbTst[, 'Charged Off'] > CTHRESH, 'Charged Off', 'Fully Paid')
table(predTstCT , true=lcdfTst$loan_status)
# Building the roc and auc curve
score=predict(lcDT1p2,lcdfTst, type="prob")[,"Charged Off"]
pred=prediction(score, lcdfTst$loan_status, label.ordering = c("Fully Paid", "Charged Off"))
#label.ordering here specifies the 'negative', 'positive' class labels
# Closer to one specifies charged off
#ROC curve
aucPerf <-performance(pred, "tpr", "fpr")
plot(aucPerf)
abline(a=0, b= 1)
#AUC value
aucPerf=performance(pred, "auc")
aucPerf@y.values