-
Notifications
You must be signed in to change notification settings - Fork 10
/
stock-radar.py
executable file
·217 lines (187 loc) · 6.93 KB
/
stock-radar.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
#!/usr/bin/env python3
# append to a dataframe a.append(pd.DataFrame({'close':99.99},index=[datetime.datetime.now()])
import pandas as pd
import os
import argparse
from filelock import FileLock
from bs4 import BeautifulSoup
# Lock timeout is 5 minutes
lockTimeout = 5 * 60
def DebugSave(filepath, data):
with FileLock(filepath + '.lock', timeout=lockTimeout):
with open(filepath, 'w+') as f:
f.write(data)
def GetHTMLElement(content, element, elementClasses):
''' Get HTML element from data.'''
soup = BeautifulSoup(content, 'lxml')
selectionText = str(
soup.find(element, class_=elementClasses))
# Correct selection links to add basename
# selectionText = re.sub("href=\"\/", "href=\"%s/" %
# (self.hostname), selectionText)
return selectionText
def BiznesRadarParse(content):
''' Parse file HTML content to get stocks table '''
table = GetHTMLElement(content, 'table', 'qTableFull')
#DebugSave('table.html', table)
data = pd.read_html(table, thousands=' ', decimal='.',
displayed_only=False)[0]
# Remove separator lines
data = data[data.ROE != 'ROE']
data = data.reset_index()
data = data.rename(columns={'Cena / Wartość księgowa': 'C/WK',
'Cena / Przychody ze sprzedaży': 'C/P',
'Cena / Zysk': 'C/Z',
'Aktualny kurs': 'Kurs',
'Średni obrót z 5 sesji [zł]': 'Obrot',
'Piotroski F-Score': 'Piotroski',
'Trend 6m': 'T6M',
'Trend 12m': 'T12M',
'Trend 24m': 'T24M',
'Zmiana kursu 3m [%]': 'Z3',
'Zmiana kursu 6m [%]': 'Z6',
'Zmiana kursu 12m [%]': 'Z12'
})
# Convert string values to float/int values
for i in (range(len(data['Profil']))):
data['ROE'][i] = float(data['ROE'][i].replace(' ', '').strip('%'))
data['ROA'][i] = float(data['ROA'][i].replace(' ', '').strip('%'))
data['C/WK'][i] = float(data['C/WK'][i])
data['C/P'][i] = float(data['C/P'][i])
data['C/Z'][i] = float(data['C/Z'][i])
data['Kurs'][i] = float(data['Kurs'][i])
data['Obrot'][i] = int(data['Obrot'][i])
data['Piotroski'][i] = int(data['Piotroski'][i])
data['Z3'][i] = float(data['Z3'][i].replace(' ', '').strip('%'))
data['Z6'][i] = float(data['Z6'][i].replace(' ', '').strip('%'))
data['Z12'][i] = float(data['Z12'][i].replace(' ', '').strip('%'))
return data
def Filter(stocks):
'''
Filter and sort stocks from pandas dataframe.
Each rating is scaled to 0..100% and sumed up.
Each commentary could be :
- worst,
- bad,
- good,
- great,
'''
ratings = []
comments = []
# Add column with spasz value
for i in (range(len(stocks['Profil']))):
commentary = ''
rating = 0
if 'ROE' in stocks:
# Normalize
if (stocks['ROE'][i] > 100):
stocks['ROE'][i] = 100
rating += stocks['ROE'][i]*1.5
if 'ROA' in stocks:
# Normalize
if (stocks['ROA'][i] > 100):
stocks['ROA'][i] = 100
rating += stocks['ROA'][i]*1.5
if 'Piotroski' in stocks:
rating += ((stocks['Piotroski'][i]*100)/9)
# C/P
if 'C/P' in stocks:
value = stocks['C/P'][i]
if (value < 1):
rating += 100 - 25*value
elif (value < 10):
rating += 80 - 5*value
elif (value < 100):
rating += 33.3 - 0.33*value
else:
rating += 0
# C/Z
if 'C/Z' in stocks:
value = stocks['C/Z'][i]
if (value < 1):
commentary += 'great C/Z,'
rating += 100 - 25*value
elif (value < 10):
commentary += 'good C/Z,'
rating += 80 - 5*value
elif (value < 100):
commentary += 'bad C/Z,'
rating += 33.3 - 0.33*value
else:
commentary += 'worst C/Z,'
rating += 0
# C/WK
if 'C/WK' in stocks:
c_wk = stocks['C/WK'][i]
if (c_wk < 1):
rating += 100 - 25*c_wk
elif (c_wk < 10):
rating += 80 - 5*c_wk
elif (c_wk < 100):
rating += 33.3 - 0.33*c_wk
else:
rating += 0
# Obrot
if 'Obrot' in stocks:
obrot = stocks['Obrot'][i]
if (obrot < 1000):
commentary += 'worst Obrot,'
rating += 0
elif (obrot < 10000):
commentary += 'bad Obrot,'
rating += 20
elif (obrot < 100000):
commentary += 'good Obrot,'
rating += 60
else:
commentary += 'great Obrot,'
rating += 100
# Zmiany
if 'Z3' in stocks:
change = stocks['Z3'][i]
change = min(100, change)
rating += change * 0.33
if 'Z6' in stocks:
change = stocks['Z6'][i]
change = min(100, change)
rating += change * 0.33
if 'Z12' in stocks:
change = stocks['Z12'][i]
change = min(100, change)
rating += change * 0.33
ratings.append(rating)
comments.append(commentary)
stocks['Rating'] = ratings
stocks['Comments'] = comments
stocks = stocks.sort_values(by=['Rating'], ascending=False)
return stocks
# Const objects
# #####################################################
# Varaables
# #####################################################
# Arguments and config
# #####################################################
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', type=str,
required=True, help='Input HTML file')
parser.add_argument('-o', '--output', type=str,
required=False, help='Output xlsx file')
parser.add_argument('-u', '--url', type=str,
required=False, help='URL to fetch. Not implemented!')
parser.add_argument('-g', '--plotToFile', action='store_true',
required=False, help='Plot to file')
args = parser.parse_args()
# TODO :
# - find kwartał
# - move at the end previous kwartał values
# Open input HTML file
filepath = args.input
if os.path.isfile(filepath):
with open(filepath, 'r') as f:
content = f.read()
stocks = BiznesRadarParse(content)
stocks = Filter(stocks)
# show data
print(stocks)
if (args.output is not None):
stocks.to_excel(args.output)