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

invest_script.py 7.9 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
  1. '''
  2. Script to run every time there is an investment round
  3. '''
  4. import os
  5. import sys
  6. import argparse
  7. import requests
  8. import math
  9. import datetime
  10. import timeit
  11. import pytz
  12. import pickle
  13. import json
  14. import numpy as np
  15. import pandas as pd
  16. import sqlalchemy
  17. from sqlalchemy import create_engine
  18. # trying to embed matplotlib plots into emails
  19. from email.message import EmailMessage
  20. from email.utils import make_msgid
  21. import mimetypes
  22. # LC imports
  23. import user_creds.account_info as acc_info
  24. from lendingclub.investing import investing_utils as inv_util
  25. from lendingclub.modeling import score_utils as scr_util
  26. from lendingclub import config
  27. from lendingclub.modeling.models import Model
  28. parser = argparse.ArgumentParser()
  29. parser.add_argument('--test', '-t', help='Boolean, if True will invest fast and not wait', action='store_true')
  30. args = parser.parse_args()
  31. test = args.test
  32. def handle_new_cols_to_sql(df, table_name, con):
  33. '''
  34. If new columns are added, bring in existing sql table and combine with
  35. pandas, then rewrite out new dataframe
  36. '''
  37. try:
  38. #this will fail if there is a new column
  39. df.to_sql(name=table_name, con=con, if_exists = 'append', index=False)
  40. except sqlalchemy.exc.OperationalError:
  41. data = pd.read_sql(f'SELECT * FROM {table_name}', con)
  42. df2 = pd.concat([data,df])
  43. df2.to_sql(name=table_name, con=con, if_exists = 'replace', index=False)
  44. # lendingclub account + API related constants
  45. inv_amt = 250.00
  46. cash_limit = 0.00
  47. token = acc_info.token
  48. inv_acc_id = acc_info.investor_id
  49. portfolio_id = acc_info.portfolio_id
  50. my_gmail_account = acc_info.from_email_throwaway
  51. my_gmail_password = acc_info.password_throwaway
  52. my_recipients = acc_info.to_emails_throwaway
  53. header = {
  54. 'Authorization': token,
  55. 'Content-Type': 'application/json',
  56. 'X-LC-LISTING-VERSION': '1.3'
  57. }
  58. acc_summary_url = 'https://api.lendingclub.com/api/investor/v1/accounts/' + \
  59. str(inv_acc_id) + '/summary'
  60. order_url = 'https://api.lendingclub.com/api/investor/v1/accounts/' + \
  61. str(inv_acc_id) + '/orders'
  62. # check account money, how much money to deploy in loans
  63. summary_dict = json.loads(requests.get(
  64. acc_summary_url, headers=header).content)
  65. cash_to_invest = summary_dict['availableCash']
  66. n_to_pick = int(math.floor(cash_to_invest / inv_amt))
  67. # other constants
  68. western = pytz.timezone('US/Pacific')
  69. now = datetime.datetime.now(tz=pytz.UTC)
  70. # setup for model
  71. with open(os.path.join(config.data_dir, 'base_loan_info_dtypes.pkl'), 'rb') as f:
  72. base_loan_dtypes = pickle.load(f)
  73. cb_both = Model('catboost_both')
  74. # clf_wt_scorer will combine the regr and clf scores, with clf wt of 20%
  75. clf_wt_scorer = scr_util.combined_score(scr_util.clf_wt)
  76. # WAIT UNTIL LOANS RELEASED. I'm rate limited to 1 call a second
  77. inv_util.pause_until_time(test=test)
  78. # Start timings
  79. start = timeit.default_timer()
  80. # get loans from API, munge them to a form that matches training data
  81. api_loans, api_ids = inv_util.get_loans_and_ids(
  82. header, exclude_already=True)
  83. # time for getting loans
  84. t1 = timeit.default_timer()
  85. # match format of cr_line dates and emp_length, dti, dti_joint
  86. api_loans['earliest_cr_line'] = pd.to_datetime(api_loans['earliest_cr_line'].str[:10])
  87. api_loans['sec_app_earliest_cr_line'] = pd.to_datetime(api_loans['sec_app_earliest_cr_line'].str[:10])
  88. bins = [12*k for k in range(1,11)]
  89. bins = [-np.inf] + bins + [np.inf]
  90. labels = ['< 1 year','1 year','2 years','3 years','4 years','5 years','6 years','7 years','8 years','9 years','10+ years',]
  91. api_loans['emp_length'] = pd.cut(api_loans['emp_length'], bins=bins, labels=labels, right=False).astype(str).replace({'nan':'None'})
  92. # I think 9999 is supposed to be their value for nan. Not entirely sure
  93. api_loans['dti'] = api_loans['dti'].replace({9999:np.nan})
  94. api_loans['dti_joint'] = api_loans['dti_joint'].replace({9999:np.nan})
  95. api_loans = api_loans.astype(base_loan_dtypes)
  96. # time for finishing munging data to correct form
  97. t2 = timeit.default_timer()
  98. # make raw scores and combined scores
  99. _, api_loans['catboost_regr'], api_loans['catboost_clf'] = cb_both.score(api_loans, return_all=True)
  100. api_loans['catboost_regr_scl'] = scr_util.scale_cb_regr_score(api_loans)
  101. catboost_comb_col = f'catboost_comb_{int(scr_util.clf_wt*100)}'
  102. api_loans[catboost_comb_col] = clf_wt_scorer('catboost_clf', 'catboost_regr_scl', api_loans)
  103. # time for finishing the entire scorer
  104. t3 = timeit.default_timer()
  105. # get loans that pass the investing criteria
  106. investable_loans = api_loans.query(f"{catboost_comb_col} >= {scr_util.min_comb_score}")
  107. # investable_loans = investable_loans.sort_values('catboost_comb', ascending=False)
  108. # time for getting investable loans
  109. t4 = timeit.default_timer()
  110. # Set up order and submit order
  111. to_order_loan_ids = investable_loans.nlargest(n_to_pick, catboost_comb_col)['id']
  112. orders_dict = {'aid': inv_acc_id}
  113. orders_list = [{'loanId': int(loan_ids),
  114. 'requestedAmount': int(inv_amt),
  115. 'portfolioId': int(portfolio_id)} for loan_ids in to_order_loan_ids]
  116. orders_dict['orders'] = orders_list
  117. payload = json.dumps(orders_dict)
  118. # place order
  119. order_resp = inv_util.submit_lc_order(cash_to_invest, cash_limit, order_url, header, payload)
  120. # time for assembling and placing orders
  121. t5 = timeit.default_timer()
  122. # some date related columns to add before writing to db
  123. # convert existing date cols
  124. to_datify = [col for col in api_loans.columns if '_d' in col and api_loans[col].dtype == 'object']
  125. for col in to_datify:
  126. api_loans[col] = pd.to_datetime(api_loans[col], utc=True).dt.tz_convert(western)
  127. # add date cols: date, year, month, week of year, day, hour
  128. api_loans['last_seen_list_d'] = now
  129. api_loans['list_d_year'] = api_loans['list_d'].dt.year
  130. api_loans['list_d_month'] = api_loans['list_d'].dt.month
  131. api_loans['list_d_day'] = api_loans['list_d'].dt.day
  132. api_loans['list_d_week'] = api_loans['list_d'].dt.week
  133. api_loans['list_d_hour'] = api_loans['list_d'].dt.hour
  134. api_loans['last_seen_list_d_year'] = api_loans['last_seen_list_d'].dt.year
  135. api_loans['last_seen_list_d_month'] = api_loans['last_seen_list_d'].dt.month
  136. api_loans['last_seen_list_d_day'] = api_loans['last_seen_list_d'].dt.day
  137. api_loans['last_seen_list_d_week'] = api_loans['last_seen_list_d'].dt.week
  138. api_loans['last_seen_list_d_hour'] = api_loans['last_seen_list_d'].dt.hour
  139. msg = EmailMessage()
  140. order_time = now.strftime("%Y-%m-%d %H:%M:%S.%f")
  141. # email headers
  142. email_cols = ['id', 'int_rate', 'term', 'catboost_clf', 'catboost_regr', 'catboost_regr_scl', catboost_comb_col]
  143. msg['Subject'] = order_time + ' Investment Round'
  144. msg['From'] = 'justindlrig <{0}>'.format(my_gmail_account)
  145. msg['To'] = 'self <{0}>'.format(my_recipients[0])
  146. # set the plain text body
  147. msg_content = f"investment round \n LC API Response: {order_resp} \n Response Contents: {order_resp.content} \
  148. \n Time to get loans: {t1 - start} \n Time to munge loans: {t2 - t1} \n Time to finish scoring process: {t3 - t2} \
  149. \n Time to get investable loans: {t4 - t3} \n Time to assemble and place order {t5 - t4} \
  150. \n Time whole process {t5 - start} \n {investable_loans[email_cols]} \n {api_loans[email_cols]}"
  151. msg.set_content(msg_content)
  152. inv_util.send_emails(now, my_gmail_account, my_gmail_password, msg)
  153. # make the timing_df
  154. timing_df = pd.DataFrame({'start': start,
  155. 'api_get_loans': t1 - start,
  156. 'munge_api_loans': t2 - t1,
  157. 'finish_scoring': t3 - t2,
  158. 'get_investable': t4 - t3,
  159. 'assemble_place_order': t5 - t4,
  160. 'order_date': order_time,
  161. 'whole_process': t5 - start,
  162. }, index=[0])
  163. # write dataframes out to db
  164. disk_engine = create_engine(f'sqlite:///{config.lc_api_db}')
  165. handle_new_cols_to_sql(api_loans, 'lc_api_loans', disk_engine)
  166. handle_new_cols_to_sql(timing_df, 'order_timings', disk_engine)
  167. #api_loans.to_sql('lc_api_loans', disk_engine, if_exists='append', index=False,)
  168. #timing_df.to_sql('order_timings', disk_engine, if_exists='append', index=False,)
Tip!

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

Comments

Loading...