-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdashboard.py
306 lines (275 loc) · 10.1 KB
/
dashboard.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
import streamlit as st
import yfinance as yf
import requests
import json
import numpy as np
import pandas_datareader as pdr
import yahoo_fin.stock_info as yfs
import pandas as pd
import matplotlib as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
from datetime import datetime, timedelta
from iex import IEXStocks
from iex import YahooStocks
from Strategy.class_Strategy import ShortTermStrategy
from Strategy.class_Strategy import LongTermStrategy
from Strategy.class_Strategy import TrendStrategy
## Setting ##
st.set_option('deprecation.showPyplotGlobalUse', False)
symbol = st.sidebar.text_input("Symbol", value="AAPL")
name_index = st.sidebar.text_input("Index", value="dow")
day = st.sidebar.text_input('Day', value='2020-1-1')
symbol_list = ['^IXIC', symbol]
dow_list = yfs.tickers_dow()
filename = ''
if name_index =='dow':
dow_list = yfs.tickers_dow()
elif stock_list == 'sp500':
filename = 'sp500'
dow_list = yfs.tickers_sp500()
elif stock_list == 'nasdaq':
filename = 'nasdaq'
dow_list = yfs.tickers_nasdaq()
elif stock_list == 'other':
filename = 'other'
dow_list = yfs.tickers_other()
elif stock_list == 'selected':
filename = 'selected'
url = '/Users/hanseopark/Work/stock/data_ForTrading/selected_ticker.json'
temp_pd = pd.read_json(url)
temp_pd = temp_pd['Ticker']
dow_list = temp_pd.values.tolist()
#############################################################
# Time #
#############################################################
# start_day = datetime(2020,4,1)
#temp = datetime.strptime(start_day, '%Y-%m-%d')
start_day = datetime.strptime(day, '%Y-%m-%d')
end_day = datetime(2020,1,1)
now_day = datetime.now()
#############################################################
# For using API from IEX ,YahooFinance and mine
#############################################################
with open('config/stream.json', 'r') as f:
config = json.load(f)
TOKEN_KEY = config['DEFAULT']['SECRET_KEY']
SANDBOX_KEY = config['TEST']['TEST_KEY']
#stock_IEX = IEXStocks(SANDBOX_KEY, symbol)
stock_IEX = IEXStocks(TOKEN_KEY, symbol)
# stock_Yahoo = YahooStocks(symbollist, start_day, now_day)
stock_Yahoo = YahooStocks(symbol_list, start_day, now_day)
#############################################################
screen = st.sidebar.selectbox("view", ('Overview', 'Short Term Strategy','Long Term Strategy', 'Select','Google Trend', 'News', 'Fundamentals', 'Ownership', 'Technicals', 'Test'))
st.title(screen)
if screen == 'Overview':
strategy_short = ShortTermStrategy(symbol, start_day, now_day)
df_price = strategy_short.get_price_data()
df_info = yf.Ticker(symbol).info
# For Beta using linear modeling
# price_change = df_price.pct_change() # Percentage Change Calculator
# df_ForBeta = price_change.drop(price_change.index[0])
# x = np.array(df_ForBeta['^IXIC']).reshape([-1,1])
# y = np.array(df_ForBeta[symbol])
# model = LinearRegression().fit(x, y)
col1, col2 = st.beta_columns(2)
with col1:
st.subheader("{0}'s Price".format(symbol))
st.line_chart(df_price['Adj Close'])
st.subheader('Industry')
st.write(df_info['industry'])
with col2:
st.subheader('Description')
st.write(df_info['longBusinessSummary'])
if screen == 'Short Term Strategy':
from Strategy.PlotStrategy import main as splt
#strategy = ShortTermStrategy(symbol, start_day, now_day)
st.subheader('Bonliner Band: ')
fig_BB = splt(symbol, offline_test=False, SelectStrategy = 'BB', day_init = start_day, today = now_day)
st.pyplot(fig_BB)
st.subheader('RSI: ')
fig_RSI = splt(symbol, offline_test=False, SelectStrategy = 'RSI', day_init = start_day, today = now_day)
st.pyplot(fig_RSI)
if screen == 'Long Term Strategy':
from Strategy.runStrategy import main as srun
st.subheader(name_index)
st.subheader('Low PER: ')
df_lowper = srun(symbol, stock_list=name_index, stats='PER', Limit = 20)
st.write(df_lowper)
st.subheader('Low PBR: ')
df_lowpbr = srun(symbol, stock_list=name_index, stats='PBR', Limit = 20)
st.write(df_lowpbr)
st.subheader('ML: ')
df_pred = srun(symbol, stock_list=name_index, stats='ML')
st.write(df_pred)
if screen == 'Select':
url_selected = '/Users/hanseopark/Work/stock/data_ForTrading/selected_ticker.json'
df_selected = pd.read_json(url_selected)
for ticker in df_selected['Ticker']:
strategy_short = ShortTermStrategy(ticker, start_day, now_day)
df_price = strategy_short.get_price_data()
df_info = yf.Ticker(ticker).info
col1, col2 = st.beta_columns((2,1))
with col1:
st.subheader("{0}'s Price".format(ticker))
st.line_chart(df_price['Adj Close'])
with col2:
try:
st.subheader('Sector')
st.write(df_info['sector'])
except:
st.write('Null')
try:
st.subheader('PER [Trai]')
st.write(df_info['trailingPE'])
except:
st.write('Null')
try:
st.subheader('Volume, AveVolume')
st.write(df_info['volume'], df_info['averageVolume'])
except:
st.write('Null')
if screen == 'Google Trend':
strategy_Trend = TrendStrategy(symbol, start=start_day, end=now_day)
df_price = strategy_Trend.get_price_data(nomalization = True)
df_trend_symbol = strategy_Trend.get_trend_data()
df = pd.concat([df_price, df_trend_symbol], axis=1)
st.line_chart(df)
if screen == 'News':
from yahoo_fin import news as ynews
news = ynews.get_yf_rss(symbol)
#st.write(news[0].keys())
"""
# Summary
"""
for i, v in enumerate (news):
st.subheader(v['title'])
st.write(v['summary'])
st.write(v['link'])
st.write(v['published'])
#st.write(v['summary_detail'])
#st.write(v['links'])
if screen == 'Fundamentals':
pass
st.subheader('After corona')
st.subheader('Beta')
# st.write(df_nasdaq_symbol.astype('object'))
# st.write(ticker_list[0])
# st.line_chart(df2['Adj Close'])
# st.write(df_quote['trailingPE']) # Price earing ratio (PER)
# df = pdr.DataReader(symbol,'yahoo',start_day,end_day)
# st.write(df)
# st.dataframe(df)
# stats = stock_IEX.get_statsj()
# chartj = stock_IEX.get_chart('1y')
# st.write(chart)
# for i in range
# st.write(chart[0]['close'])
# st.write(stats)
# for i in range (10):
# st.write('Headline')
# st.write(news[i]['headline'])
# st.write('Summary')
# st.write(news[i]['summary'])
# st.write(news[0])
# st.write(news)
if screen == 'Test':
pass
# # For NASDAQ ... about above 10000
# # df_nasdaq_symbol = pdr.nasdaq_trader.get_nasdaq_symbols()
# # ticker_list = df_nasdaq_symbol['NASDAQ Symbol'].values.tolist()
# # stock_Yahoo_list = YahooStocks(ticker_list[200], start_day, now_day)
# # df2 = stock_Yahoo_list.get_price_data()
# # df_quote = pdr.get_quote_yahoo(symbol)
#
#
# # For S&P500 ... about 500
# url = 'https://raw.githubusercontent.com/datasets/s-and-p-500-companies/master/data/constituents.csv'
#df_sp500 = pd.read_csv(url)
# # pers_10 = pd.DataFrame({'PER':['']}, index=['Company'])
# # pers_20 = pd.DataFrame({'PER':['']}, index=['Company'])
# # error_symbols_per = []
# # for c in df_sp500['Symbol']:
# # try:
# # per = pdr.get_quote_yahoo(c)['trailingPE']
# # if per[c]<20:
# # pers_20.loc[c] = per[c]
## if per[c]<10:
## pers_10.loc[c] = per[c]
## except:
# # error_symbols_per.append(c)
#
# # st.subheader('Low PER Strategy')
# # st.text('PER < 10')
# # st.write(pers_10)
# # st.text('PER < 20')
# # st.write(pers_20)
#
# # For S%P5000 low PBR(price to book ratio)
# df = pd.DataFrame({'PER':[], 'PBR':[], 'sector':[], 'Adj Close':[], 'DailyReturn':[]})
# error_symbols_pbr =[]
# for c in df_sp500['Symbol']:
# try:
# pass
# # FOR REAL
# # For pandas-datareader, the datatype is dataframe
# df_quote = pdr.get_quote_yahoo(c)
# per = df_quote['trailingPE']
# # pbr = df_quote['priceToBookk']
#
# # df_value = pdr.get_data_yahoo(c, start_day, nowday)
# # Stock_value = df_value['Adj Close'] # index is times
# # Stock_value_daily = Stock_value.pct_change()
# # Stock_value_weekly = Stock.value.resample('7D').ffill().pct_channge
# # Stock_value_weekly = Stock.value.resample('M').ffill().pct_channge
#
# # # For yfinance, the datatype is dictionary
# # dc_info = yf.Ticker(c).info
# # GISD = dc_info['sector']
#
# # # To make dataframe adding panadas-datareader+yfinance
# # df.loc[c, 'PER'] = per[c]
# # df.loc[c, 'PBR'] = pbr[c]
# # df.loc[c, 'sector'] = GISD
#
#
# # FOR TEST
## if per[c] < 10:
## df_value = pdr.get_data_yahoo(c, start_day, now_day)
## Stock_value = df_value['Adj Close'] # index is times
## Stock_value_daily = Stock_value.pct_change()
## Stock_value_weekly = Stock.value.resample('7D').ffill().pct_channge
## Stock_value_monthly = Stock.value.resample('M').ffill().pct_channge
## daily_std = Stock_value_daily.std()* 252 ** 0.5
## weekly_std = Stock_value_weekly.std() * 52 ** 0.5
## monthly_std = Stock_value_monthly.std() * 12 ** 0.5
##
## df.loc[c, 'PER'] = per[c]
## df.loc[c, 'DailyReturn'] = daily_std
## df.loc[c, 'WeeklyReturn'] = weekly_std
## df.loc[c, 'MonthlyReturn'] = monthly_std
##
## except:
## error_symbols_pbr.append(c)
##
#
# # df_value = pdr.get_data_yahoo(symbol, start_day, now_day)
# # Stock_value = df_value['Adj Close'] # index is times
# # Stock_value_daily = Stock_value.pct_change()
# # daily_std = Stock_value_daily.std()* 252 ** 0.5
# # df.loc[symbol, 'DailyReturn'] = daily_std
#
# # st.subheader('Low PBR Strategy')
# # pbrs = df['PER'].sort_values(by=['PBR'], axis=0)
# # pbrs = pbrs.head(30)
# # st.write(pbrs)
#
# # list_GISD = []
# # for c in pbrs.index:
# # # df_GISD = yf.Ticker(c).info['sector']
# # list_GISD.append(yf.Ticer(c).infor['sector'])
# # # df.loc[c] =
# # # df_GISD = yf.Ticker(pbrs).info('sector')
# # st.write(df_GISD)
# # st.write(df)
# #st.write()