-
Notifications
You must be signed in to change notification settings - Fork 0
/
Risk Analysis.Rmd
2633 lines (1319 loc) · 87.7 KB
/
Risk Analysis.Rmd
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: "Risk Analysis"
author: "Shalaka Thakare/(Group Project)"
date: "2022-11-02"
output: html_document
---
Lending Club
Background
Problem Statement
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE)
```
Importing the Libraries
```{r}
library(tidyverse)
library(lubridate)
library(stringr)
library(pROC)
library(rpart)
library(ROCR)
library(caret)
library(ranger)
library(plotluck)
```
Loading the data...
```{r}
lcdf <- read_csv('C:/Users/sthaka3/Desktop/Credit_Risk_Project/lcData100K.csv')
# Checking number of rows and columns in the lc dataframe
cat('Number of rows = ', nrow(lcdf))
cat('\nNumber of columns = ',ncol(lcdf))
```
Exploring the data
```{r}
head(lcdf)
summary(lcdf)
```
How many different types of loan status exist in the data?
```{r}
lcdf %>% group_by(loan_status) %>% tally()
```
Looks like our target variable- loan_status has only 2 values- Charged Off and Fully Paid.
Let's check the distribution of loan status across all records
```{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")
```
Analyzing Home Ownerships
```{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"))
```
We can see that most of the borrowers have their home on rent or mortgage as compared to those who own their homes.
Let's now visualize the spread of interest rate to get a better understanding of the given data
```{r}
summary(lcdf$int_rate)
ggplot(lcdf, aes( x = int_rate)) + geom_boxplot(color="#993333",outlier.color = "black") +
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 have an interest rate of less than 8.9%. Median of the interest rate of all loans in 11.99%. The interest rate can go as high as 28.99 % in some case. This interest seems really active to invest in. Very few investment products give an interest of 12%. </font>
Let's understand interest rates vary according to loan grade
```{r}
ggplot(lcdf, aes( y = int_rate, x=grade,color= grade)) + geom_boxplot(outlier.color="black") + xlab("Loan grade ") +
ylab("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"))
```
We can see that the median interest rate increases as we go from grade A to grade G, probably due to higher risk.
Let's summarize the data to check percent of defaults using loan status for all loan grades
```{r}
lcdf %>% group_by(grade) %>% summarise(TotalLoans=n(), FullyPaid=sum(loan_status=="Fully Paid"), ChargedOff=sum(loan_status=="Charged Off"), Percent_defaults = ChargedOff/TotalLoans*100)
```
The percent of default loans is higher for lower grade loans. This explains why interest rates are higher for the same.
Now, let's look at a wider picture to see how number of loans, loan amount, interest rate vary by grade. First, lets do some calculations
```{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, Percent_defaults = 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))
```
```{r}
# 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"))
```
<font> The loan amount varies from 0 to 35,000. The number of charged off loans are less in overall number,which is evident in the graph. 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. This means that loan status has more to do with loan grade rather than the loan amount. </font>
```{r}
# 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"))
```
The loan amount for most loans is approximately \$12000.Loan amount is lower for lower grade loans.Let's dive deeper into the relationship with loan amount and loan grade.
```{r}
# Let us look at the distribution
ggplot(lcdf, aes( y = loan_amnt, x=grade,color= grade)) + geom_boxplot(outlier.color="black") + xlab("Loan grade ") +
ylab("Loan Amount") + 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"))
```
We can see that loans falling under A and B grades have higher loan amounts, while those for C, D, E and F are slightly lesser.Range for loan amounts with Grade G have a broader range.
```{r}
# 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> We can see that the average interest rate is higher in higher grades of loans. Higher interest rates can mean higher returns for investors, but this also means higher risk. Interest rates vary from 0 to 28 percent. Most loans have an interest rate of 12-14%.</font>
Let's analyze the data with respect to purpose of loans
```{r}
table(lcdf$purpose)
```
```{r}
# Checking number of loans by purpose
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")
# 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("Purpose 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"))
#Bivariate analysis of employment length and purpose.
table(lcdf$purpose, lcdf$emp_length)
# Percentages
lcdf %>% group_by(purpose) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), Default_per = (defaults/nLoans)*100)
#Does loan-grade vary by purpose? Which pupose the loan grade fall in?
table(lcdf$purpose, lcdf$grade)
#do those with home-improvement loans own or rent a home?
lcdf %>% group_by(home_ownership) %>% summarise(nLoans=n(), purpose_home_ownership=sum(purpose=="home_improvement"))
```
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 purposes are more than 80% of loan purposes. While the most number of loans are for the purpose of debt consolidation/credit card, the maximum percent of defaults are found to be for the purpose of small businesses, moving and housing loan. Most credit card and debt consolidation loans fall under grade B, small business loan mostly fall under grade D and moving under grade C. 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. Other than this, there are several people taking loans for home improvement when their Home ownership status says that they are living on rent. This seems suspicious because rarely will a tenant issue a loan for improvement.
Now that we understand purpose of loans with other factors, let's check the relationship between employment length and other variables
```{r}
# Arranging emp_length as factor variables
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))
# 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"))
```
Checking for Outliers
```{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 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> For annual income the data seems to be skewed towards the left. very few borrowers have an income more than 1.5 Milliion. It would be rare occurrence for someone to have an income more than 1.5 million and issue a loan from lending club, so we could consider these data points as outliers. Hence we will remove these 9 observations, which make up a very small percent of all the records in the dataset, therefore the impact would be next to negligible. </font>
<font> The very high income cases are for paid-off loans. We could 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 difference 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 Outliers....
```{r}
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"))
```
Now that we have removed the data points over 1.5 million, our data looks much cleaner but outliers still exist.Although, if we would remove the data points above the upper bound(by multiplying the IQR by 1.5), we would have lost essential data.
Let's calculate annual returns
```{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)
```
We can see that the minimum returns for charged off loans can be as low as 0. This could be because borrowers are paying off their loans much earlier than expected. Maximum returns from fully paid loans could be as high as 16.5%, which cannot be possiblefor high grade loans. While chances of the loan being fully paid are higher for higher grade loans, investors might consider investing in lower grade loans for higher returns.
Let's further analyze exactly how early or late are the loans being paid?
```{r}
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()
```
Let's find out actual return with respect to actual term.
```{r}
# 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))
ggplot(lcdf, aes( x = actualReturn)) + geom_histogram(aes(fill=grade)) + ggtitle("Distribution of Actual Returns With Grade") + xlab("Actual Return ") + 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"))
```
We can see that the actual term is not 3 years for fully paid loans. This could be the reason why returns are lower than expected. Charged off loans are expected to have negative return irrespective of the grade. Higher graded have higher loss / negative mean return rate.
Let's check distribution of actual term
```{r}
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"))
```
Derived attributes
```{r}
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))
```
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)
```
Data Leakage Concept of leakage - It 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)\#](https://en.wikipedia.org/wiki/Leakage_(machine_learning)#){.uri}:\~: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))
```
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
Missing Values
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
```{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)
```
Some columns have same percentage of missing values. This could be because they are dependent columns. Information source for one column could 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
Next, we can perform a Univariate Analysis to understand exactly Which variables are individually predictive of the outcome
```{r}
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))
```
### Building the model - Splitting the data into Train and Test
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/
```{r}
# First trial with a 50% split
## 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
# 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)
```
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.
### 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
We will now prune the tree to see the performance, this pruning will be based on different cp values
```{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)
```
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.
### 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")
# [[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")
# [[1]]
# [1] 0.6400753
#Lift curve
liftPerf <-performance(pred, "lift", "rpp")
plot(liftPerf)
# 3. Using the model which were pruned - p2
predProbTrn=predict(lcDT1p3,lcdfTrn, type='prob')
predTrnCT = ifelse(predProbTrn[, 'Charged Off'] > CTHRESH, 'Charged Off', 'Fully Paid')
table(predTrnCT , true=lcdfTrn$loan_status)
predProbTst=predict(lcDT1p3,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(lcDT1p3,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")
#Lift curve
liftPerf <-performance(pred, "lift", "rpp")
plot(liftPerf)
# 4. Using the model which was balanced
predProbTrn=predict(lcDT1b,lcdfTrn, type='prob')
predTrnCT = ifelse(predProbTrn[, 'Charged Off'] > CTHRESH, 'Charged Off', 'Fully Paid')
table(predTrnCT , true=lcdfTrn$loan_status)
predProbTst=predict(lcDT1b,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(lcDT1b,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")
#Lift curve
liftPerf <-performance(pred, "lift", "rpp")
plot(liftPerf)
# 5. Using the model which was balanced and pruned
predProbTrn=predict(lcDT1bp,lcdfTrn, type='prob')
predTrnCT = ifelse(predProbTrn[, 'Charged Off'] > CTHRESH, 'Charged Off', 'Fully Paid')
table(predTrnCT , true=lcdfTrn$loan_status)
predProbTst=predict(lcDT1bp,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(lcDT1bp,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")
#Lift curve
liftPerf <-performance(pred, "lift", "rpp")
plot(liftPerf)
```
<font> We have observed both confusion matrix and roc auc curve for the following models - The model which was fully grown, pruned, and balanced - we added the threshold values as well. </font>
### C50 Decision Tree Model
<font>This algorithm uses an information entropy computation to determine the best rule that splits the data, at that node, into purer classes by minimizing the computed entropy value. This means that as each node splits the data, based on the rule at that node, each subset of data split by the rule will contain less diversity of classes and will, eventually, contain only one class [complete purity]. This process is simple to compute and therefore C50 runs quickly. C50 is robust. It can work with both numeric or categorical data [this example shows both types]. It can also tolerate missing data values. The output from the R implementation can be either a decision tree or a rule set. The output model can be used to assign [predict] a class to new unclassified data items. Reference - http://mercury.webster.edu/aleshunas/R_learning_infrastructure/Classification%20of%20data%20using%20decision%20tree%20and%20regression%20tree%20methods.html </font>
```{r}
library(C50)