-
Notifications
You must be signed in to change notification settings - Fork 0
/
yahoo_stats_scraper.py
167 lines (115 loc) · 4.73 KB
/
yahoo_stats_scraper.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
'''
NAME: Janit Sriganeshaelankovan
CREATED: July 3, 2018 - 21:36 (EDT)
GOAL: Yahoo Company Stats Scraper
ENVIRONMENT: Base
LAST UPDATE: January 13, 2019 - 22:40 (EDT)
'''
import re
import requests
from bs4 import BeautifulSoup as soup
import time
from collections import OrderedDict
import csv
import pandas as pd
''' YAHOO COMPANY STATISTICS '''
#GET THE METERICS
meterics = {}
with open('Yahoo_StatMeterics.txt', 'r') as f:
for x in f:
met = x.split(':')
meterics[met[0]] = met[1].strip('\n').strip(' ')
meterics = OrderedDict(sorted(meterics.items(), key=lambda t: t[0]))
meterics_keys = sorted(meterics.keys())
#GET THE INFO
def get_stats(tickers_list):
filename = 'company_stats'
for idx, ticker in enumerate(tickers_list):
time.sleep(1)
print('WORKING ON {}: {}'.format(idx, ticker))
resp = requests.get(r'https://ca.finance.yahoo.com/quote/{}/key-statistics'.format(ticker))
html = resp.text
page_soup = soup(html, 'lxml')
body = page_soup.body
data = str(body.find_all('script'))
values = data.split(r'"QuoteSummaryStore"')
with open('{}.txt'.format(filename), 'a', encoding='utf-8') as f:
f.write(ticker + ',')
try:
for key, val in meterics.items():
# print('{}, {}'.format(key, val))
pattern = '"%s":{(.*?)}' % (val,)
d = re.findall(pattern, values[1])
if d:
pattern2 = r'"fmt":(.*)'
value = re.findall(pattern2, d[0])
else:
value = d
if value:
v = value[0].split(',', 1)[0]
v = v.strip('""')
# print('{}: {}'.format(key, v))
f.write(v + ',')
else:
value_none = 'NAN'
# print('{}: {}'.format(key, value_none))
f.write(value_none + ',')
f.write('\n')
except Exception as e:
print('{} could not be found'.format(ticker))
f.write('NAN')
f.write('\n')
#CONVERT TXT FILE TO CSV
def converter(filename):
with open('{}.txt'.format(filename), 'r') as csvfile:
csvfile1 = csv.reader(csvfile, delimiter=',')
with open('{}.txt'.format(filename).replace('.txt','.csv'), 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for row in csvfile1:
writer.writerow(row)
def more_stats(filename):
df = pd.read_csv('{}.txt'.format(filename))
#print(df.columns.values)
df.set_index('Ticker', inplace=True)
#print(df.index.name)
#print(df.dtypes)
df = df.assign(Sector="", Industry="")
groups = {'Sector':"sector", 'Industry':"industry"}
ind = df.index.get_values()
len(ind)
for idx, i in enumerate(ind):
print('{}:{}'.format(idx, i))
resp = requests.get(r'https://ca.finance.yahoo.com/quote/{}'.format(i))
html = resp.text
page_soup = soup(html, 'lxml')
body = page_soup.body
data = str(body.find_all('script'))
values = data.split(r'"summaryProfile"')
try:
if values:
for key, val in groups.items():
sentence = values[1].split(r'"%s":' % (val, ))
matches = re.findall(r'\"(.+?)\"',sentence[1])
if matches[0]:
if key == 'Website':
try:
m = matches[0].split('www.')
df.loc[i, key] = m[1]
except:
m = matches[0].split('www.')
df.loc[i, key] = m[0]
else:
df.loc[i, key] = matches[0]
else:
print("NO {} INFO FOUND ON {}".format(key, i))
df.loc[i, key] = 'NAN'
else:
print("NO DATA FOUND ON {}".format(i))
df.loc[i, 'Sector'] = 'NAN'
df.loc[i, 'Industry'] = 'NAN'
# continue
except Exception as e:
print('{}:{}'.format(i, str(e)))
df.loc[i, 'Sector'] = 'NAN'
df.loc[i, 'Industry'] = 'NAN'
df.to_csv('{}_moreinfo.csv'.format(filename))