-
Notifications
You must be signed in to change notification settings - Fork 2
/
crawl_report.py
213 lines (159 loc) · 6.04 KB
/
crawl_report.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
import time
import requests
import datetime
import numpy as np
import pandas as pd
from io import StringIO
def load_csv(year, month, type):
if type == 'monthly':
df = pd.read_csv('data/monthly/%d_%d.csv' % (year, month))
elif type == 'seasonal':
df = pd.read_csv('data/seasonal/營益分析彙總表/%d_%d.csv' % (year, month))
else:
print('get 404, wrong type')
return df
def monthly(year, month):
# 假如是西元,轉成民國
if year > 1990:
year -= 1911
url = 'https://mops.twse.com.tw/nas/t21/sii/t21sc03_' + \
str(year)+'_'+str(month)+'_0.html'
if year <= 98:
url = 'https://mops.twse.com.tw/nas/t21/sii/t21sc03_' + \
str(year)+'_'+str(month)+'.html'
# 偽瀏覽器
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
# 下載該年月的網站,並用pandas轉換成 dataframe
r = requests.get(url, headers=headers)
r.encoding = 'big5'
dfs = pd.read_html(StringIO(r.text), encoding='big-5')
df = pd.concat([df for df in dfs if df.shape[1] <= 11 and df.shape[1] > 5])
if 'levels' in dir(df.columns):
df.columns = df.columns.get_level_values(1)
else:
df = df[list(range(0, 10))]
column_index = df.index[(df[0] == '公司代號')][0]
df.columns = df.iloc[column_index]
df['當月營收'] = pd.to_numeric(df['當月營收'], 'coerce')
df = df[~df['當月營收'].isnull()]
df = df[df['公司代號'] != '合計']
return df
def seasonal(year, season, type='營益分析彙總表'):
# 假如是西元,轉成民國
if year > 1990:
year -= 1911
if type == '營益分析彙總表':
url = 'https://mops.twse.com.tw/mops/web/ajax_t163sb06'
r = requests.post(url, {
'encodeURIComponent': 1,
'step': 1,
'firstin': 1,
'off': 1,
'TYPEK': 'sii',
'year': str(year),
'season': str(season),
})
r.encoding = 'utf8'
dfs = pd.read_html(r.text)
for i, df in enumerate(dfs):
df.columns = df.iloc[0]
dfs[i] = df.iloc[1:]
df = pd.concat(dfs, sort=False).applymap(
lambda x: x if x != '--' else np.nan)
df = df[df['公司代號'] != '公司代號']
df = df[~df['公司代號'].isnull()]
elif type == '綜合損益彙總表':
url = 'https://mops.twse.com.tw/mops/web/ajax_t163sb04'
r = requests.post(url, {
'encodeURIComponent': 1,
'step': 1,
'firstin': 1,
'off': 1,
'TYPEK': 'sii',
'year': str(year),
'season': str(season),
})
r.encoding = 'utf8'
dfs = pd.read_html(r.text)
df = pd.concat([df for df in dfs if df.shape[1] > 10], sort=False)
df.columns = df.columns.get_level_values(0)
df['營業利益(損失)'] = pd.to_numeric(df['營業利益(損失)'], 'coerce')
df['營業外收入及支出'] = pd.to_numeric(df['營業外收入及支出'], 'coerce')
df['基本每股盈餘(元)'] = pd.to_numeric(df['基本每股盈餘(元)'], 'coerce')
df = df[~df['營業利益(損失)'].isnull()]
df = df[~df['營業外收入及支出'].isnull()]
df = df[~df['基本每股盈餘(元)'].isnull()]
# elif type == '資產負債彙總表':
# url = 'https://mops.twse.com.tw/mops/web/ajax_t163sb05'
else:
print('type does not match')
return df
def cast_n_months(n_months, load_report, save_report):
data = {}
now = datetime.datetime.now()
year = now.year
month = now.month
# 獲取近n個月的資料
while len(data) < n_months:
print('parsing', year, month)
if load_report:
try:
data['%d-%d-01' %
(year, month)] = load_csv(year, month, type='monthly')
except:
print('get 404, please check if the revenues are not revealed')
else:
try:
data['%d-%d-01' % (year, month)] = monthly(year, month)
if save_report:
data['%d-%d-01' % (year, month)].to_csv('data/monthly/%d_%d.csv' %
(year, month), encoding='utf-8', index=False)
except:
print('get 404, please check if the revenues are not revealed')
# 減一個月
month -= 1
if month == 0:
month = 12
year -= 1
time.sleep(10)
return data
def cast_n_seasons(n_seasons, load_report, save_report):
data = {}
now = datetime.datetime.now()
year = now.year
month = now.month
if month <= 3:
season = 1
elif month <= 6:
season = 2
elif month <= 9:
season = 3
elif month <= 12:
season = 4
else:
print('get 404, please check if the season is conrrect')
# 獲取近n個季的資料
while len(data) < n_seasons:
print('parsing', year, season)
if load_report:
try:
data['%d-%d-01' %
(year, season)] = load_csv(year, season, type='seasonal')
except:
print('get 404, please check if the financial reports are not revealed')
else:
try:
data['%d-%d-01' % (year, season)] = seasonal(year, season, type='營益分析彙總表')
if save_report:
data['%d-%d-01' % (year, season)].to_csv('data/seasonal/營益分析彙總表/%d_%d.csv' %
(year, season), encoding='utf-8', index=False)
except:
print('get 404, please check if the financial reports are not revealed')
# 減一季
season -= 1
if season == 0:
season = 4
year -= 1
time.sleep(10)
return data