forked from dataman-git/codes_for_articles
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stock2.py
396 lines (316 loc) · 12.5 KB
/
stock2.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
371
372
373
374
375
376
377
378
379
380
381
382
# !pip3 install streamlit
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf # https://pypi.org/project/yfinance/
##############################
# Technical Analysis Classes #
##############################
# https://github.com/bukosabino/ta/blob/master/ta/utils.py
class IndicatorMixin:
"""Util mixin indicator class"""
_fillna = False
def _check_fillna(self, series: pd.Series, value: int = 0) -> pd.Series:
"""Check if fillna flag is True.
Args:
series(pandas.Series): dataset 'Close' column.
value(int): value to fill gaps; if -1 fill values using 'backfill' mode.
Returns:
pandas.Series: New feature generated.
"""
if self._fillna:
series_output = series.copy(deep=False)
series_output = series_output.replace([np.inf, -np.inf], np.nan)
if isinstance(value, int) and value == -1:
series = series_output.fillna(method="ffill").fillna(value=-1)
else:
series = series_output.fillna(method="ffill").fillna(value)
return series
@staticmethod
def _true_range(
high: pd.Series, low: pd.Series, prev_close: pd.Series
) -> pd.Series:
tr1 = high - low
tr2 = (high - prev_close).abs()
tr3 = (low - prev_close).abs()
true_range = pd.DataFrame(data={"tr1": tr1, "tr2": tr2, "tr3": tr3}).max(axis=1)
return true_range
def dropna(df: pd.DataFrame) -> pd.DataFrame:
"""Drop rows with "Nans" values"""
df = df.copy()
number_cols = df.select_dtypes("number").columns.to_list()
df[number_cols] = df[number_cols][df[number_cols] < math.exp(709)] # big number
df[number_cols] = df[number_cols][df[number_cols] != 0.0]
df = df.dropna()
return df
def _sma(series, periods: int, fillna: bool = False):
min_periods = 0 if fillna else periods
return series.rolling(window=periods, min_periods=min_periods).mean()
def _ema(series, periods, fillna=False):
min_periods = 0 if fillna else periods
return series.ewm(span=periods, min_periods=min_periods, adjust=False).mean()
def _get_min_max(series1: pd.Series, series2: pd.Series, function: str = "min"):
"""Find min or max value between two lists for each index"""
series1 = np.array(series1)
series2 = np.array(series2)
if function == "min":
output = np.amin([series1, series2], axis=0)
elif function == "max":
output = np.amax([series1, series2], axis=0)
else:
raise ValueError('"f" variable value should be "min" or "max"')
return pd.Series(output)
# https://github.com/bukosabino/ta/blob/master/ta/volatility.py
class BollingerBands(IndicatorMixin):
"""Bollinger Bands
https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_bands
Args:
close(pandas.Series): dataset 'Close' column.
window(int): n period.
window_dev(int): n factor standard deviation
fillna(bool): if True, fill nan values.
"""
def __init__(
self,
close: pd.Series,
window: int = 20,
window_dev: int = 2,
fillna: bool = False,
):
self._close = close
self._window = window
self._window_dev = window_dev
self._fillna = fillna
self._run()
def _run(self):
min_periods = 0 if self._fillna else self._window
self._mavg = self._close.rolling(self._window, min_periods=min_periods).mean()
self._mstd = self._close.rolling(self._window, min_periods=min_periods).std(
ddof=0
)
self._hband = self._mavg + self._window_dev * self._mstd
self._lband = self._mavg - self._window_dev * self._mstd
def bollinger_mavg(self) -> pd.Series:
"""Bollinger Channel Middle Band
Returns:
pandas.Series: New feature generated.
"""
mavg = self._check_fillna(self._mavg, value=-1)
return pd.Series(mavg, name="mavg")
def bollinger_hband(self) -> pd.Series:
"""Bollinger Channel High Band
Returns:
pandas.Series: New feature generated.
"""
hband = self._check_fillna(self._hband, value=-1)
return pd.Series(hband, name="hband")
def bollinger_lband(self) -> pd.Series:
"""Bollinger Channel Low Band
Returns:
pandas.Series: New feature generated.
"""
lband = self._check_fillna(self._lband, value=-1)
return pd.Series(lband, name="lband")
def bollinger_wband(self) -> pd.Series:
"""Bollinger Channel Band Width
From: https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_band_width
Returns:
pandas.Series: New feature generated.
"""
wband = ((self._hband - self._lband) / self._mavg) * 100
wband = self._check_fillna(wband, value=0)
return pd.Series(wband, name="bbiwband")
def bollinger_pband(self) -> pd.Series:
"""Bollinger Channel Percentage Band
From: https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_band_perce
Returns:
pandas.Series: New feature generated.
"""
pband = (self._close - self._lband) / (self._hband - self._lband)
pband = self._check_fillna(pband, value=0)
return pd.Series(pband, name="bbipband")
def bollinger_hband_indicator(self) -> pd.Series:
"""Bollinger Channel Indicator Crossing High Band (binary).
It returns 1, if close is higher than bollinger_hband. Else, it returns 0.
Returns:
pandas.Series: New feature generated.
"""
hband = pd.Series(
np.where(self._close > self._hband, 1.0, 0.0), index=self._close.index
)
hband = self._check_fillna(hband, value=0)
return pd.Series(hband, index=self._close.index, name="bbihband")
def bollinger_lband_indicator(self) -> pd.Series:
"""Bollinger Channel Indicator Crossing Low Band (binary).
It returns 1, if close is lower than bollinger_lband. Else, it returns 0.
Returns:
pandas.Series: New feature generated.
"""
lband = pd.Series(
np.where(self._close < self._lband, 1.0, 0.0), index=self._close.index
)
lband = self._check_fillna(lband, value=0)
return pd.Series(lband, name="bbilband")
# https://github.com/bukosabino/ta/blob/master/ta/momentum.py
class RSIIndicator(IndicatorMixin):
"""Relative Strength Index (RSI)
Compares the magnitude of recent gains and losses over a specified time
period to measure speed and change of price movements of a security. It is
primarily used to attempt to identify overbought or oversold conditions in
the trading of an asset.
https://www.investopedia.com/terms/r/rsi.asp
Args:
close(pandas.Series): dataset 'Close' column.
window(int): n period.
fillna(bool): if True, fill nan values.
"""
def __init__(self, close: pd.Series, window: int = 14, fillna: bool = False):
self._close = close
self._window = window
self._fillna = fillna
self._run()
def _run(self):
diff = self._close.diff(1)
up_direction = diff.where(diff > 0, 0.0)
down_direction = -diff.where(diff < 0, 0.0)
min_periods = 0 if self._fillna else self._window
emaup = up_direction.ewm(
alpha=1 / self._window, min_periods=min_periods, adjust=False
).mean()
emadn = down_direction.ewm(
alpha=1 / self._window, min_periods=min_periods, adjust=False
).mean()
relative_strength = emaup / emadn
self._rsi = pd.Series(
np.where(emadn == 0, 100, 100 - (100 / (1 + relative_strength))),
index=self._close.index,
)
def rsi(self) -> pd.Series:
"""Relative Strength Index (RSI)
Returns:
pandas.Series: New feature generated.
"""
rsi_series = self._check_fillna(self._rsi, value=50)
return pd.Series(rsi_series, name="rsi")
# https://github.com/bukosabino/ta/blob/master/ta/trend.py
class MACD(IndicatorMixin):
"""Moving Average Convergence Divergence (MACD)
Is a trend-following momentum indicator that shows the relationship between
two moving averages of prices.
https://school.stockcharts.com/doku.php?id=technical_indicators:moving_average_convergence_divergence_macd
Args:
close(pandas.Series): dataset 'Close' column.
window_fast(int): n period short-term.
window_slow(int): n period long-term.
window_sign(int): n period to signal.
fillna(bool): if True, fill nan values.
"""
def __init__(
self,
close: pd.Series,
window_slow: int = 26,
window_fast: int = 12,
window_sign: int = 9,
fillna: bool = False,
):
self._close = close
self._window_slow = window_slow
self._window_fast = window_fast
self._window_sign = window_sign
self._fillna = fillna
self._run()
def _run(self):
self._emafast = _ema(self._close, self._window_fast, self._fillna)
self._emaslow = _ema(self._close, self._window_slow, self._fillna)
self._macd = self._emafast - self._emaslow
self._macd_signal = _ema(self._macd, self._window_sign, self._fillna)
self._macd_diff = self._macd - self._macd_signal
def macd(self) -> pd.Series:
"""MACD Line
Returns:
pandas.Series: New feature generated.
"""
macd_series = self._check_fillna(self._macd, value=0)
return pd.Series(
macd_series, name=f"MACD_{self._window_fast}_{self._window_slow}"
)
def macd_signal(self) -> pd.Series:
"""Signal Line
Returns:
pandas.Series: New feature generated.
"""
macd_signal_series = self._check_fillna(self._macd_signal, value=0)
return pd.Series(
macd_signal_series,
name=f"MACD_sign_{self._window_fast}_{self._window_slow}",
)
def macd_diff(self) -> pd.Series:
"""MACD Histogram
Returns:
pandas.Series: New feature generated.
"""
macd_diff_series = self._check_fillna(self._macd_diff, value=0)
return pd.Series(
macd_diff_series, name=f"MACD_diff_{self._window_fast}_{self._window_slow}"
)
##################
# Set up sidebar #
##################
# Add in location to select image.
option = st.sidebar.selectbox('Select one symbol', ( 'AAPL', 'MSFT',"SPY",'WMT'))
import datetime
today = datetime.date.today()
before = today - datetime.timedelta(days=700)
start_date = st.sidebar.date_input('Start date', before)
end_date = st.sidebar.date_input('End date', today)
if start_date < end_date:
st.sidebar.success('Start date: `%s`\n\nEnd date:`%s`' % (start_date, end_date))
else:
st.sidebar.error('Error: End date must fall after start date.')
##############
# Stock data #
##############
# https://technical-analysis-library-in-python.readthedocs.io/en/latest/ta.html#momentum-indicators
df = yf.download(option,start= start_date,end= end_date, progress=False)
indicator_bb = BollingerBands(df['Close'])
bb = df
bb['bb_h'] = indicator_bb.bollinger_hband()
bb['bb_l'] = indicator_bb.bollinger_lband()
bb = bb[['Close','bb_h','bb_l']]
macd = MACD(df['Close']).macd()
rsi = RSIIndicator(df['Close']).rsi()
###################
# Set up main app #
###################
#st.write('Stock Bollinger Bands')
st.line_chart(bb)
progress_bar = st.progress(0)
# https://share.streamlit.io/daniellewisdl/streamlit-cheat-sheet/app.py
st.write('Stock Moving Average Convergence Divergence (MACD)')
st.area_chart(macd)
st.write('Stock RSI ')
st.line_chart(rsi)
st.write('Recent data ')
st.dataframe(df.tail(10))
################
# Download csv #
################
import base64
from io import BytesIO
def to_excel(df):
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
processed_data = output.getvalue()
return processed_data
def get_table_download_link(df):
"""Generates a link allowing the data in a given panda dataframe to be downloaded
in: dataframe
out: href string
"""
val = to_excel(df)
b64 = base64.b64encode(val) # val looks like b'...'
return f'<a href="data:application/octet-stream;base64,{b64.decode()}" download="download.xlsx">Download excel file</a>' # decode b'abc' => abc
st.markdown(get_table_download_link(df), unsafe_allow_html=True)