Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

04_clean_pmt_history.py 9.3 KB

You have to be logged in to leave a comment. Sign In
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
  1. '''
  2. Reads in payment history, does lots of cleaning
  3. '''
  4. import os
  5. import pickle
  6. import sys
  7. import pandas as pd
  8. from tqdm import tqdm
  9. import j_utils.munging as mg
  10. from lendingclub import config
  11. import lendingclub.csv_preparation.clean_pmt_history as cph
  12. if __name__ == '__main__':
  13. # LOADING
  14. csv_path = config.wrk_csv_dir
  15. # for now its always been one csv. Will have to revisit if they break it out to multiple
  16. pmt_hist_fnames = [f for f in os.listdir(csv_path) if 'PMTHIST' in f]
  17. if len(pmt_hist_fnames) > 1:
  18. sys.exit('more than one payment history file, need to change this code')
  19. # load in dev_ids.pkl, pmt_hist_skiprows, dtypes
  20. with open(os.path.join(config.data_dir, 'dev_ids.pkl'), "rb") as f:
  21. dev_ids = pickle.load(f)
  22. with open(os.path.join(config.data_dir, 'pmt_hist_skiprows.pkl'), "rb") as f:
  23. pmt_hist_skiprows = pickle.load(f)
  24. with open(os.path.join(config.data_dir, 'pmt_hist_dtypes.pkl'), 'rb') as f:
  25. dtypes = pickle.load(f)
  26. print('loading pmt_hist; skipping {0} rows'.format(len(pmt_hist_skiprows)))
  27. pmt_hist = pd.read_csv(os.path.join(csv_path, pmt_hist_fnames[0]),
  28. skiprows=pmt_hist_skiprows,
  29. na_values=['*'],
  30. dtype=dtypes)
  31. print("{:,}".format(len(pmt_hist)) + " rows of pmt_hist loaded")
  32. # COMPRESS MEMORY
  33. changed_type_cols, pmt_hist = mg.reduce_memory(pmt_hist)
  34. # DATA INTEGRITY PART 1
  35. id_grouped = pmt_hist.groupby('LOAN_ID')
  36. strange_pmt_hist_ids = []
  37. for ids, group in tqdm(id_grouped):
  38. if cph.detect_strange_pmt_hist(group):
  39. strange_pmt_hist_ids.append(ids)
  40. with open(os.path.join(config.data_dir, 'strange_pmt_hist_ids.pkl'), "wb") as f:
  41. pickle.dump(strange_pmt_hist_ids, f)
  42. # DATA PROCESSING
  43. # Set loan ids as int _____________________________________________________
  44. pmt_hist['LOAN_ID'] = pmt_hist['LOAN_ID'].astype(int)
  45. print('payment history for', len(pmt_hist['LOAN_ID'].unique()), 'different loan ids')
  46. # Round values to 3 decimal places ____________________________________________
  47. pmt_hist = pmt_hist.round(3)
  48. # renaming columns ____________________________________________________________
  49. rename_col_dict = {
  50. 'LOAN_ID': 'loan_id',
  51. 'PBAL_BEG_PERIOD': 'outs_princp_beg',
  52. 'PRNCP_PAID': 'princp_paid',
  53. 'INT_PAID': 'int_paid',
  54. 'FEE_PAID': 'fee_paid',
  55. 'DUE_AMT': 'amt_due',
  56. 'RECEIVED_AMT': 'amt_paid',
  57. 'RECEIVED_D': 'pmt_date',
  58. 'PERIOD_END_LSTAT': 'status_period_end',
  59. 'MONTH': 'date',
  60. 'PBAL_END_PERIOD': 'outs_princp_end',
  61. 'MOB': 'm_on_books',
  62. 'CO': 'charged_off_this_month',
  63. 'COAMT': 'charged_off_amt',
  64. 'InterestRate': 'int_rate',
  65. 'IssuedDate': 'issue_d',
  66. 'MONTHLYCONTRACTAMT': 'monthly_pmt',
  67. 'dti': 'dti',
  68. 'State': 'addr_state',
  69. 'HomeOwnership': 'home_ownership',
  70. 'MonthlyIncome': 'm_income',
  71. 'EarliestCREDITLine': 'first_credit_line',
  72. 'OpenCREDITLines': 'open_credit_lines',
  73. 'TotalCREDITLines': 'total_credit_lines',
  74. 'RevolvingCREDITBalance': 'revol_credit_bal',
  75. 'RevolvingLineUtilization': 'revol_line_util',
  76. 'Inquiries6M': 'inq_6m',
  77. 'DQ2yrs': 'dq_24m',
  78. 'MonthsSinceDQ': 'm_since_dq',
  79. 'PublicRec': 'public_recs',
  80. 'MonthsSinceLastRec': 'm_since_rec',
  81. 'EmploymentLength': 'emp_len',
  82. 'currentpolicy': 'current_policy',
  83. 'grade': 'grade',
  84. 'term': 'term',
  85. 'APPL_FICO_BAND': 'fico_apply',
  86. 'Last_FICO_BAND': 'fico_last',
  87. 'VINTAGE': 'vintage',
  88. 'PCO_RECOVERY': 'recovs',
  89. 'PCO_COLLECTION_FEE': 'recov_fees',
  90. }
  91. pmt_hist.rename(columns=rename_col_dict, inplace=True)
  92. # # There is a problem with the inquiries 6m column. Some are nan values and some
  93. # # are marked '*' with no explanation. inq6m should be in loan info so dropping
  94. # pmt_hist.drop('inq_6m', axis=1, inplace=True)
  95. # There are 5 columns dealing with money: princp_paid, int_paid, fee_paid,
  96. # recovs, and recovs_fee. princp_paid + int_paid + fee_paid is sometimes short
  97. # of amt_paid. Be conservative and rewrite amt_paid to be sum of said 3.
  98. # Also make all_cash_to_inv = amt_paid + recovs - recov_fees
  99. # Fee paid is always positive, and by inspection it is money borrower pays out
  100. pmt_hist[
  101. 'amt_paid'] = pmt_hist['princp_paid'] + pmt_hist['int_paid'] + pmt_hist['fee_paid']
  102. pmt_hist['recovs'].fillna(0, inplace=True)
  103. pmt_hist['recov_fees'].fillna(0, inplace=True)
  104. pmt_hist[
  105. 'all_cash_to_inv'] = pmt_hist['amt_paid'] + pmt_hist['recovs'] - pmt_hist['recov_fees']
  106. # turn all date columns into pandas timestamp _________________________________
  107. for col in ['pmt_date', 'date', 'issue_d', 'first_credit_line']:
  108. cph.pmt_hist_fmt_date(pmt_hist, col)
  109. # status_period_end ____________________________________________________________
  110. status_fix = {
  111. 'Current': 'current',
  112. 'Late (31-120 days)': 'late_120',
  113. 'Fully Paid': 'paid',
  114. 'Charged Off': 'charged_off',
  115. 'Default': 'defaulted',
  116. 'Late (16-30 days)': 'late_30',
  117. 'In Grace Period': 'grace_15',
  118. 'Issued': 'current'
  119. }
  120. pmt_hist['status_period_end'] = pmt_hist['status_period_end'].replace(
  121. status_fix)
  122. # home_ownership _______________________________________________________________
  123. home_ownership_fix = {
  124. 'admin_us': 'other',
  125. 'mortgage': 'mortgage',
  126. 'rent': 'rent',
  127. 'own': 'own',
  128. 'other': 'other',
  129. 'none': 'none',
  130. 'any': 'none'
  131. }
  132. pmt_hist['home_ownership'] = pmt_hist['home_ownership'].str.lower().replace(
  133. home_ownership_fix)
  134. # fico_apply __________________________________________________________________
  135. fico_apply_fix = {'850': '850-850'}
  136. pmt_hist['fico_apply'] = pmt_hist['fico_apply'].replace(fico_apply_fix)
  137. pmt_hist['fico_apply'] = (pmt_hist['fico_apply'].str[:3].astype(int) +
  138. pmt_hist['fico_apply'].str[4:].astype(int)) / 2
  139. pmt_hist['fico_apply'] = pmt_hist['fico_apply'].astype(int)
  140. # fico_last ___________________________________________________________________
  141. fico_last_fix = {'845-HIGH': '845-849', 'LOW-499': '495-499'}
  142. pmt_hist['fico_last'] = pmt_hist['fico_last'].replace(fico_last_fix)
  143. pmt_hist.loc[pmt_hist['fico_last'] != 'MISSING', 'fico_last'] = (
  144. pmt_hist.loc[pmt_hist['fico_last'] != 'MISSING', 'fico_last'].str[:3]
  145. .astype(int) + pmt_hist.loc[pmt_hist['fico_last'] != 'MISSING',
  146. 'fico_last'].str[4:].astype(int)) / 2
  147. pmt_hist.loc[pmt_hist['fico_last'] == 'MISSING', 'fico_last'] = pmt_hist.loc[
  148. pmt_hist['fico_last'] == 'MISSING', 'fico_apply']
  149. pmt_hist['fico_last'] = pmt_hist['fico_last'].astype(int)
  150. # revol_credit_bal ____________________________________________________________
  151. pmt_hist['revol_credit_bal'] = pmt_hist['revol_credit_bal'].astype(
  152. float)
  153. # fix on a few bad rows where I think there is a mistaken amt_paid ____________
  154. pmt_hist.loc[(pmt_hist['pmt_date'].isnull() & pmt_hist['amt_paid'] > 0),
  155. 'amt_paid'] = 0
  156. # compress memory
  157. changed_type_cols, pmt_hist = mg.reduce_memory(pmt_hist)
  158. # map position to column
  159. column_iloc_map = {
  160. col_name: pmt_hist.iloc[-1].index.get_loc(col_name)
  161. for col_name in pmt_hist.columns.values
  162. }
  163. # split into portions needing fixing and not needing fixing
  164. dup_date_ids = pmt_hist[pmt_hist.duplicated(
  165. ['loan_id', 'date'])]['loan_id'].unique()
  166. already_good = pmt_hist[~pmt_hist['loan_id'].isin(dup_date_ids)]
  167. needs_fixing = pmt_hist[pmt_hist['loan_id'].isin(dup_date_ids)]
  168. del pmt_hist
  169. # fix dfs with duplicate dates to be one per month
  170. fixed_dfs = []
  171. id_grouped = needs_fixing.groupby('loan_id')
  172. for ids, group in tqdm(id_grouped):
  173. if ids in dup_date_ids:
  174. fixed_dfs.append(cph.merge_dupe_dates(group, column_iloc_map))
  175. # combine dfs
  176. fixed_df = pd.concat(fixed_dfs)
  177. pmt_hist = pd.concat([already_good, fixed_df])
  178. del already_good, fixed_df
  179. # want one entry for every month for every loan until "loan end".
  180. # clean_pmt_history_2 ensured that there were not duplicate entries per month
  181. # now we ensure that there's an entry for each month
  182. id_grouped = pmt_hist.groupby('loan_id')
  183. fixed_dfs = []
  184. fixed_ids = []
  185. for ids, group in tqdm(id_grouped):
  186. fix_df = cph.insert_missing_dates(group, ids)
  187. if fix_df is not None:
  188. fixed_dfs.append(fix_df)
  189. fixed_ids.append(ids)
  190. # combine the fixed entries with ones that don't need fixing
  191. already_good = pmt_hist[~pmt_hist['loan_id'].isin(fixed_ids)]
  192. fixed_df = pd.concat(fixed_dfs)
  193. del pmt_hist
  194. pmt_hist = pd.concat([already_good, fixed_df])
  195. del already_good, fixed_df
  196. # compress memory
  197. changed_type_cols, pmt_hist = mg.reduce_memory(pmt_hist)
  198. # resort to keep relevant rows together, reset index, save
  199. pmt_hist.sort_values(by=['loan_id', 'date'], inplace=True)
  200. pmt_hist.reset_index(inplace=True, drop=True)
  201. pmt_hist.to_feather(os.path.join(config.data_dir, 'clean_pmt_history.fth'))
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...