forked from ericlighthofmann/EdgarScrape
-
Notifications
You must be signed in to change notification settings - Fork 0
/
edgar_email.py
370 lines (345 loc) · 16.2 KB
/
edgar_email.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import smtplib
import datetime
from twilio.rest import TwilioRestClient
import feedparser
import openpyxl
import xml.etree.ElementTree as ET
import requests
import bs4
import time
import io
import itertools as IT
CompanyNameList = []
TickerList = []
ProcessedList = []
ReportingOwnerRelationshipList = []
TransactionSharesList = []
PricePerShareList = []
TotalValueList = []
transactionCodeList = []
DorIList = []
portfolio = []
bought_price = []
stocks_sent = []
checked = []
#----------------------------------------------------------------------------------#
#PULL FROM STOCK SCREEN EXCEL AND CURRENT PORTFOLIO
wb = openpyxl.load_workbook(filename = 'stock_screenv2.xlsx')
sheet = wb.active
print('Getting info from cells...')
for row in range(2, sheet.max_row + 1):
company_name = sheet['A' + str(row)].value
ticker = sheet['B' + str(row)].value
CompanyNameList.append(company_name)
TickerList.append(ticker)
wb.save('stock_screenv2.xlsx')
with open('portfolio.txt', 'r') as f:
stocks = f.readlines()
for item in stocks:
item = item.strip()
portfolio.append(item)
with open('bought_price.txt', 'r') as f:
price = f.readlines()
for item in price:
item = item.strip()
bought_price.append(item)
#----------------------------------------------------------------------------------#
#COMMUNICATION FUNCTIONS
def email(tradingSymbol, link):
today = datetime.datetime.today()
today = today.strftime('%m/%d/%Y %I:%M %p')
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('******************@gmail.com', '***************')
print(smtpObj.sendmail('******************@gmail.com',\
'******************@gmail.com',\
'Subject: ' + str(today) + ' | Stock order: ' + str(tradingSymbol) + '.\nBuy this stock and heres the address + ' + str(link) + '\n'))
smtpObj.quit()
def text_phone(tradingSymbol):
accountSID = '***************'
authToken = '***************'
twilioCli = TwilioRestClient(accountSID, authToken)
myTwilioNumber = '***************'
myCellPhone = '+***************'
message = twilioCli.messages.create(body='Yo, buy this stock: ' + str(tradingSymbol), from_=myTwilioNumber, to=myCellPhone)
def text_error(link):
accountSID = '***************'
authToken = '***************'
twilioCli = TwilioRestClient(accountSID, authToken)
myTwilioNumber = '***************'
myCellPhone = '+***************'
message = twilioCli.messages.create(body='There was an error on Python at this address: ' + str(link), from_=myTwilioNumber, to=myCellPhone)
def text_scott(tradingSymbol):
accountSID = '***************'
authToken = '***************'
twilioCli = TwilioRestClient(accountSID, authToken)
myTwilioNumber = '***************'
myCellPhone = '+***************'
message = twilioCli.messages.create(body='Yo, buy this stock: ' + str(tradingSymbol), from_=myTwilioNumber, to=myCellPhone)
def text_carl(tradingSymbol):
accountSID = '***************'
authToken = '***************'
twilioCli = TwilioRestClient(accountSID, authToken)
myTwilioNumber = '***************'
myCellPhone = '+***************'
message = twilioCli.messages.create(body='Yo, buy this stock: ' + str(tradingSymbol), from_=myTwilioNumber, to=myCellPhone)
#----------------------------------------------------------------------------------#
#SCAN EDGAR AND SCRAPE XML
def scrape_xml(link):
TotalValue = 0
transactionCodeList = []
DorIList = []
TitleList = []
today = datetime.datetime.today()
today = today.strftime('%m/%d/%Y %I:%M %p')
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36",
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"accept-encoding": "gzip, deflate, sdch",
"accept-language": "en-US,en;q=0.8",
}
res = requests.get(link, headers=headers)
time.sleep(2)
soup = bs4.BeautifulSoup(res.text, 'html.parser')
time.sleep(2)
#try:
for a in soup.find_all('a'):
if a.getText()[-4:] == '.xml':
address = 'http://www.sec.gov' + a['href']
print ('Scraping XML on ' + str(today) + ' at ' + str(link))
res = requests.get(address, headers=headers, timeout=None)
tree = ET.fromstring(res.content)
if tree.find('reportingOwner/reportingOwnerRelationship/isOfficer')== None:
isOfficer = ''
elif tree.find('reportingOwner/reportingOwnerRelationship/isOfficer').text == 'true':
isOfficer = '1'
elif tree.find('reportingOwner/reportingOwnerRelationship/isOfficer').text == 'false':
isOfficer = '0'
else:
isOfficer = tree.find('reportingOwner/reportingOwnerRelationship/isOfficer')
isOfficer = isOfficer.text
transactionCode = tree.findall('nonDerivativeTable/nonDerivativeTransaction/transactionCoding/transactionCode')
if transactionCode == None:
transactionCode = []
tradingSymbol = tree.find('issuer/issuerTradingSymbol')
transactionShares = tree.findall('nonDerivativeTable/nonDerivativeTransaction/transactionAmounts/transactionShares/value')
if transactionShares == None:
transactionShares = []
transactionPricePerShare = tree.findall('nonDerivativeTable/nonDerivativeTransaction/transactionAmounts/transactionPricePerShare/value')
if transactionShares == None:
transactionShares = []
DorI = tree.findall('nonDerivativeTable/nonDerivativeTransaction/ownershipNature/directOrIndirectOwnership/value')
if DorI == None:
DorI = []
for price, shares, direct, code in zip(transactionPricePerShare, transactionShares, DorI, transactionCode):
if direct.text == 'D' and code.text == 'P':
TotalValue = TotalValue + float(shares.text)*float(price.text)
else:
pass
for code in transactionCode:
transactionCodeList.append(code.text)
for item in DorI:
DorIList.append(item.text)
print ('Officer is: ' + str(isOfficer))
print('Transaction codes are: ' + str(transactionCodeList))
print ('TotalValue is: ' + str(TotalValue))
print ('Direct or Indirect list is ' + str(DorIList))
print ('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
if isOfficer == str(1) and 'P' in transactionCodeList and TotalValue > 10000 and 'D' in DorIList and tradingSymbol.text not in portfolio:
print ('Officer is: ' + str(isOfficer))
print('Transaction codes are: ' + str(transactionCodeList))
print ('TotalValue is: ' + str(TotalValue))
print ('Direct or Indirect list is ' + str(DorIList))
print ('Stock found.')
print (today)
print (tradingSymbol.text)
with open('portfolio.txt', 'a') as f:
f.write(tradingSymbol.text + '\n')
ticker = tradingSymbol.text.lower()
res = requests.get('http://finance.yahoo.com/q?s=' + ticker)
soup = bs4.BeautifulSoup(res.text, 'html.parser')
elems = soup.select('#yfs_l84_'+str(ticker))
current_price = elems[0].getText()
with open('bought_price.txt', 'a') as f:
f.write(current_price + '\n')
email (tradingSymbol.text, link)
text_phone (tradingSymbol.text)
text_scott (tradingSymbol.text)
text_carl (tradingSymbol.text)
print ('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
## except Exception as e:
## print (address)
## print (e)
## print (datetime.datetime.today())
## text_error(link)
## print ('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
def edgar_feed(url):
try:
d = feedparser.parse(url)
time.sleep(2)
#d = feedparser.parse(r'feed_example.txt')
lower = [x.lower() for x in CompanyNameList]
lower = [x.replace('.', '') for x in lower]
lower = [x.replace(',', '') for x in lower]
for entry in range(0,99):
company_name = d.entries[entry].title.lower()
company_name = company_name.split('- ')
company_name = company_name[1].split(' (')
company_name = company_name[0]
company_name = company_name.replace('.', '')
company_name = company_name.replace(',', '')
if '&' in company_name:
company_name = company_name.replace('&', '&')
if company_name in lower and d.entries[entry].title[0:1:] == '4':
link = d.entries[entry].link
last50 = slice(-50, None)
if link[last50] not in stocks_sent:
scrape_xml(link)
stocks_sent.append(link[last50])
else:
pass
except Exception as e:
print (e)
print (datetime.datetime.today())
pass
def check_price():
for stock, price in zip(portfolio, bought_price):
try:
ticker = stock.lower()
res = requests.get('http://finance.yahoo.com/q?s=' + ticker)
soup = bs4.BeautifulSoup(res.text, 'html.parser')
elems = soup.select('#yfs_l84_'+str(ticker))
current_price = elems[0].getText()
ticker = stock.upper()
if float(current_price) > 1.02*float(price) and stock not in checked:
#Email
today = datetime.datetime.today()
today = today.strftime('%m/%d/%Y %I:%M %p')
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('******************@gmail.com', '***************')
print(smtpObj.sendmail('******************@gmail.com',\
'******************@gmail.com',\
'Subject: ' + str(today) + ' | Stock to sell after 2% gains: ' + str(ticker) + '.\nSell this stock' + '\n'))
smtpObj.quit()
#Text me
accountSID = '***************'
authToken = '***************'
twilioCli = TwilioRestClient(accountSID, authToken)
myTwilioNumber = '***************'
myCellPhone = '+***************'
message = twilioCli.messages.create(body='Yo, sell this stock (2% gain): ' + str(ticker), from_=myTwilioNumber, to=myCellPhone)
#Text Scott
accountSID = '***************'
authToken = '***************'
twilioCli = TwilioRestClient(accountSID, authToken)
myTwilioNumber = '***************'
myCellPhone = '+***************'
message = twilioCli.messages.create(body='Yo, sell this stock (2% gain): ' + str(ticker), from_=myTwilioNumber, to=myCellPhone)
#Text Carl
accountSID = '***************'
authToken = '***************'
twilioCli = TwilioRestClient(accountSID, authToken)
myTwilioNumber = '***************'
myCellPhone = '+***************'
message = twilioCli.messages.create(body='Yo, sell this stock (2% gain): ' + str(ticker), from_=myTwilioNumber, to=myCellPhone)
#remove from portfolio
portfolio.remove(stock)
bought_price.remove(price)
checked.append(stock)
f = open("portfolio.txt","r+")
d = f.readlines()
f.seek(0)
for i in d:
if i != str(stock + '\n'):
f.write(i)
f.truncate()
f.close()
f = open("bought_price.txt","r+")
d = f.readlines()
f.seek(0)
for i in d:
if i != str(price + '\n'):
f.write(i)
f.truncate()
f.close()
checked.append(stock)
elif float(current_price) < .95*float(price) and stock not in checked:
#Email
today = datetime.datetime.today()
today = today.strftime('%m/%d/%Y %I:%M %p')
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('******************@gmail.com', '***************')
print(smtpObj.sendmail('******************@gmail.com',\
'******************@gmail.com',\
'Subject: ' + str(today) + ' | Stock to sell after 5% losses: ' + str(ticker) + '.\nSell this stock' + '\n'))
smtpObj.quit()
#Text me
accountSID = '***************'
authToken = '***************'
twilioCli = TwilioRestClient(accountSID, authToken)
myTwilioNumber = '+***************'
myCellPhone = '+***************'
message = twilioCli.messages.create(body='Yo, sell this stock (5% loss): ' + str(ticker), from_=myTwilioNumber, to=myCellPhone)
#Text Scott
accountSID = '***************'
authToken = '***************'
twilioCli = TwilioRestClient(accountSID, authToken)
myTwilioNumber = '***************'
myCellPhone = '+***************'
message = twilioCli.messages.create(body='Yo, sell this stock (5% loss): ' + str(ticker), from_=myTwilioNumber, to=myCellPhone)
#Text Carl
accountSID = '***************'
authToken = '***************'
twilioCli = TwilioRestClient(accountSID, authToken)
myTwilioNumber = '***************'
myCellPhone = '+***************'
message = twilioCli.messages.create(body='Yo, sell this stock (5% loss): ' + str(ticker), from_=myTwilioNumber, to=myCellPhone)
#Remove from portfolio
portfolio.remove(stock)
bought_price.remove(price)
stock = stock.upper()
f = open("portfolio.txt","r+")
d = f.readlines()
f.seek(0)
for i in d:
if i != str(stock + '\n'):
f.write(i)
f.truncate()
f.close()
f = open("bought_price.txt","r+")
d = f.readlines()
f.seek(0)
for i in d:
if i != str(price + '\n'):
f.write(i)
f.truncate()
f.close()
checked.append(stock)
else:
pass
except Exception as e:
print (e)
pass
#-------------------------------------------------------------------------------------#
#SCRIPT BODY
#Stock screen: Market Cap < $500m, D/E < 1.5, P/E < 1.5
url = 'http://www.sec.gov/cgi-bin/browse-edgar?action=getcurrent&type=&company=&dateb=&owner=only&start=0&count=100&output=atom'
print ('monitoring feed...')
run_counter = 0
def job():
global run_counter
time.sleep(5)
run_counter += 1
if run_counter % 100 == 0:
print ('Completed ' + str(run_counter) + ' passes.')
print ('--------------')
edgar_feed(url)
check_price()
while True:
job()