Bayhaqy commited on
Commit
798890b
1 Parent(s): 22f36b5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +337 -0
app.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ import pandas_datareader.data as web
5
+ import datetime as dt
6
+ import yfinance as yf
7
+ from sklearn.preprocessing import MinMaxScaler
8
+ from keras.models import load_model
9
+ import streamlit as st
10
+ import streamlit as st
11
+ import plotly.graph_objects as go
12
+ import base64
13
+ import plotly.express as px
14
+ from datetime import datetime
15
+
16
+ st.set_page_config(page_title='Regression Stocks Prediction', layout='wide', page_icon=':rocket:')
17
+
18
+ #this is the header
19
+
20
+
21
+ t1, t2 = st.columns((0.07,1))
22
+
23
+ t2.title("Stock Price Analysis and Prediction Using LSTM")
24
+ t2.markdown("Created by Bayhaqy")
25
+ t2.markdown("Using Dataset MAPI to Train and Test the Model")
26
+
27
+ # Add a dictonary of stock tickers and their company names and make a drop down menu to select the stock to predict
28
+
29
+ stock_tickers = {
30
+ "MAPI":"MAPI.JK","MAP Aktif": "MAPA.JK","MAP Boga": "MAPB.JK",
31
+ "Tesla": "TSLA", "Apple": "AAPL", "Microsoft": "MSFT", "Google": "GOOGL",
32
+ "Facebook": "FB", "Amazon": "AMZN", "Netflix": "NFLX", "Alphabet": "GOOG",
33
+ "Nvidia": "NVDA", "Paypal": "PYPL", "Adobe": "ADBE", "Intel": "INTC",
34
+ "Cisco": "CSCO", "Comcast": "CMCSA", "Pepsi": "PEP", "Costco": "COST",
35
+ "Starbucks": "SBUX", "Walmart": "WMT", "Disney": "DIS", "Visa": "V",
36
+ "Mastercard": "MA", "Boeing": "BA", "IBM": "IBM", "McDonalds": "MCD",
37
+ "Nike": "NKE", "Exxon": "XOM", "Chevron": "CVX", "Verizon": "VZ",
38
+ "AT&T": "T", "Home Depot": "HD", "Salesforce": "CRM", "Oracle": "ORCL",
39
+ "Qualcomm": "QCOM", "AMD": "AMD"
40
+ }
41
+
42
+ st.sidebar.title("Stock Option")
43
+ # Custom CSS to change the sidebar color
44
+ sidebar_css = """
45
+ <style>
46
+ div[data-testid="stSidebar"] > div:first-child {
47
+ width: 350px; # Adjust the width as needed
48
+ background-color: #FF6969;
49
+ }
50
+ </style>
51
+ """
52
+
53
+ # User Input
54
+ default_index = stock_tickers.keys().index("MAPI.JK") if "MAPI.JK" in stock_tickers.keys() else 0
55
+ #st.markdown(sidebar_css, unsafe_allow_html=True)
56
+ user_input = st.sidebar.selectbox("Select a Stock", list(stock_tickers.keys()), index=default_index , key="main_selectbox")
57
+ stock_name = user_input
58
+ user_input = stock_tickers[user_input]
59
+
60
+ # User input for start and end dates using calendar widget
61
+ start_date = st.sidebar.date_input("Select start date:", datetime(2010, 1, 1))
62
+ end_date = st.sidebar.date_input("Select end date:", datetime(2023, 1, 1))
63
+ # End of User Input
64
+
65
+
66
+
67
+ # Enhanced title with larger font size and a different color
68
+ title = f"<h1 style='color: red; font-size: 25px; text-align: center; '>{stock_name}'s Stock Analysis</h1>"
69
+ st.markdown(title, unsafe_allow_html=True)
70
+
71
+ # Describing the data
72
+ st.subheader(f'Data from {start_date} - {end_date}')
73
+ data = yf.download(user_input, start_date, end_date)
74
+
75
+ # Reset the index to add the date column
76
+ data = data.reset_index()
77
+
78
+ # Display data in a Plotly table
79
+ fig = go.Figure(data=[go.Table(
80
+ header=dict(values=list(data.columns),
81
+ font=dict(size=12, color='white'),
82
+ fill_color='#264653',
83
+ line_color='rgba(255,255,255,0.2)',
84
+ align=['left', 'center'],
85
+ height=20),
86
+ cells=dict(values=[data[k].tolist() for k in data.columns],
87
+ font=dict(size=12),
88
+ align=['left', 'center'],
89
+ line_color='rgba(255,255,255,0.2)',
90
+ height=20))])
91
+
92
+ fig.update_layout(title_text=f"Data for {stock_name}", title_font_color='#264653', title_x=0, margin=dict(l=0, r=10, b=10, t=30))
93
+
94
+ st.plotly_chart(fig, use_container_width=True)
95
+
96
+
97
+ st.markdown(f"<h2 style='text-align: center; color: #264653;'>Data Overview for {stock_name}</h2>", unsafe_allow_html=True)
98
+ # Get the description of the data
99
+ description = data.describe()
100
+
101
+ # Dictionary of columns and rows to highlight
102
+ highlight_dict = {
103
+ "Open": ["mean", "min", "max", "std"],
104
+ "High": ["mean", "min", "max", "std"],
105
+ "Low": ["mean", "min", "max", "std"],
106
+ "Close": ["mean", "min", "max", "std"],
107
+ "Adj Close": ["mean", "min", "max", "std"]
108
+ }
109
+
110
+ # Colors for specific rows
111
+ color_dict = {
112
+ "mean": "lightgreen",
113
+ "min": "salmon",
114
+ "max": "lightblue",
115
+ "std": "lightyellow"
116
+ }
117
+
118
+ # Function to highlight specific columns and rows based on the dictionaries
119
+ def highlight_specific_cells(val, col_name, row_name):
120
+ if col_name in highlight_dict and row_name in highlight_dict[col_name]:
121
+ return f'background-color: {color_dict[row_name]}'
122
+ return ''
123
+
124
+ styled_description = description.style.apply(lambda row: [highlight_specific_cells(val, col, row.name) for col, val in row.items()], axis=1)
125
+
126
+ # Display the styled table in Streamlit
127
+ st.table(styled_description)
128
+
129
+ ### ............................................... ##
130
+ # Stock Price Over Time
131
+ g1, g2, g3 = st.columns((1.2,1.2,1))
132
+
133
+ fig1 = px.line(data, x='Date', y='Close', template='seaborn')
134
+ fig1.update_traces(line_color='#264653')
135
+ fig1.update_layout(title_text="Stock Price Over Time", title_x=0, margin=dict(l=20, r=20, b=20, t=30), yaxis_title=None, xaxis_title=None, height=400, width=700)
136
+ g1.plotly_chart(fig1, use_container_width=True)
137
+
138
+ # Volume of Stocks Traded Over Time
139
+ fig2 = px.bar(data, x='Date', y='Volume', template='seaborn')
140
+ fig2.update_traces(marker_color='#7A9E9F')
141
+ fig2.update_layout(title_text="Volume of Stocks Traded Over Time", title_x=0, margin=dict(l=20, r=20, b=20, t=30), yaxis_title=None, xaxis_title=None, height=400, width=700)
142
+ g2.plotly_chart(fig2, use_container_width=True)
143
+
144
+ # Moving Averages
145
+ short_window = 40
146
+ long_window = 100
147
+ data['Short_MA'] = data['Close'].rolling(window=short_window).mean()
148
+ data['Long_MA'] = data['Close'].rolling(window=long_window).mean()
149
+ fig3 = px.line(data, x='Date', y='Close', template='seaborn')
150
+ fig3.add_scatter(x=data['Date'], y=data['Short_MA'], mode='lines', line=dict(color="red"), name=f'Short {short_window}D MA')
151
+ fig3.add_scatter(x=data['Date'], y=data['Long_MA'], mode='lines', line=dict(color="blue"), name=f'Long {long_window}D MA')
152
+ fig3.update_layout(title_text="Stock Price with Moving Averages", title_x=0, margin=dict(l=20, r=20, b=20, t=30), yaxis_title=None, xaxis_title=None, legend=dict(orientation="h", yanchor="bottom", y=0.9, xanchor="right", x=0.99), height=400, width=700)
153
+ g3.plotly_chart(fig3, use_container_width=True)
154
+
155
+ ## ............................................... ##
156
+ # Daily Returns
157
+ g4, g5, g6 = st.columns((1,1,1))
158
+ data['Daily_Returns'] = data['Close'].pct_change()
159
+ fig4 = px.line(data, x='Date', y='Daily_Returns', template='seaborn')
160
+ fig4.update_traces(line_color='#E76F51')
161
+ fig4.update_layout(title_text="Daily Returns", title_x=0, margin=dict(l=0, r=10, b=10, t=30), yaxis_title=None, xaxis_title=None)
162
+ g4.plotly_chart(fig4, use_container_width=True)
163
+
164
+ # Cumulative Returns
165
+ data['Cumulative_Returns'] = (1 + data['Daily_Returns']).cumprod()
166
+ fig5 = px.line(data, x='Date', y='Cumulative_Returns', template='seaborn')
167
+ fig5.update_traces(line_color='#2A9D8F')
168
+ fig5.update_layout(title_text="Cumulative Returns", title_x=0, margin=dict(l=0, r=10, b=10, t=30), yaxis_title=None, xaxis_title=None)
169
+ g5.plotly_chart(fig5, use_container_width=True)
170
+ # Stock Price Distribution
171
+ fig6 = px.histogram(data, x='Close', template='seaborn', nbins=50)
172
+ fig6.update_traces(marker_color='#F4A261')
173
+ fig6.update_layout(title_text="Stock Price Distribution", title_x=0, margin=dict(l=0, r=10, b=10, t=30), yaxis_title=None, xaxis_title=None)
174
+ g6.plotly_chart(fig6, use_container_width=True)
175
+
176
+ ## ............................................... ##
177
+
178
+ # Bollinger Bands
179
+ g7, g8, g9 = st.columns((1,1,1))
180
+ rolling_mean = data['Close'].rolling(window=20).mean()
181
+ rolling_std = data['Close'].rolling(window=20).std()
182
+ data['Bollinger_Upper'] = rolling_mean + (rolling_std * 2)
183
+ data['Bollinger_Lower'] = rolling_mean - (rolling_std * 2)
184
+ fig7 = px.line(data, x='Date', y='Close', template='seaborn')
185
+ fig7.add_scatter(x=data['Date'], y=data['Bollinger_Upper'], mode='lines', line=dict(color="green"), name='Upper Bollinger Band')
186
+ fig7.add_scatter(x=data['Date'], y=data['Bollinger_Lower'], mode='lines', line=dict(color="red"), name='Lower Bollinger Band')
187
+ fig7.update_layout(title_text="Bollinger Bands", title_x=0, margin=dict(l=0, r=10, b=10, t=30), yaxis_title=None, xaxis_title=None)
188
+ g7.plotly_chart(fig7, use_container_width=True)
189
+
190
+ # Stock Price vs. Volume
191
+ fig8 = px.line(data, x='Date', y='Close', template='seaborn')
192
+ fig8.add_bar(x=data['Date'], y=data['Volume'], name='Volume')
193
+ fig8.update_layout(title_text="Stock Price vs. Volume", title_x=0, margin=dict(l=0, r=10, b=10, t=30), yaxis_title=None, xaxis_title=None)
194
+ g8.plotly_chart(fig8, use_container_width=True)
195
+
196
+ # MACD
197
+ data['12D_EMA'] = data['Close'].ewm(span=12, adjust=False).mean()
198
+ data['26D_EMA'] = data['Close'].ewm(span=26, adjust=False).mean()
199
+ data['MACD'] = data['12D_EMA'] - data['26D_EMA']
200
+ data['Signal_Line'] = data['MACD'].ewm(span=9, adjust=False).mean()
201
+ fig9 = px.line(data, x='Date', y='MACD', template='seaborn', title="MACD")
202
+ fig9.add_scatter(x=data['Date'], y=data['Signal_Line'], mode='lines', line=dict(color="orange"), name='Signal Line')
203
+ fig9.update_layout(title_text="MACD", title_x=0, margin=dict(l=0, r=10, b=10, t=30), yaxis_title=None, xaxis_title=None)
204
+ g9.plotly_chart(fig9, use_container_width=True)
205
+
206
+ ### ............................................... ##
207
+
208
+ # Relative Strength Index (RSI)
209
+ g10, g11, g12 = st.columns((1,1,1))
210
+ delta = data['Close'].diff()
211
+ gain = (delta.where(delta > 0, 0)).fillna(0)
212
+ loss = (-delta.where(delta < 0, 0)).fillna(0)
213
+ avg_gain = gain.rolling(window=14).mean()
214
+ avg_loss = loss.rolling(window=14).mean()
215
+ rs = avg_gain / avg_loss
216
+ data['RSI'] = 100 - (100 / (1 + rs))
217
+ fig10 = px.line(data, x='Date', y='RSI', template='seaborn')
218
+ fig10.update_layout(title_text="Relative Strength Index (RSI)", title_x=0, margin=dict(l=0, r=10, b=10, t=30), yaxis_title=None, xaxis_title=None)
219
+ g10.plotly_chart(fig10, use_container_width=True)
220
+
221
+ # Candlestick Chart
222
+ fig11 = go.Figure(data=[go.Candlestick(x=data['Date'],
223
+ open=data['Open'],
224
+ high=data['High'],
225
+ low=data['Low'],
226
+ close=data['Close'])])
227
+ fig11.update_layout(title_text="Candlestick Chart", title_x=0, margin=dict(l=0, r=10, b=10, t=30))
228
+ g11.plotly_chart(fig11, use_container_width=True)
229
+
230
+ # Correlation Matrix
231
+ corr_matrix = data[['Open', 'High', 'Low', 'Close', 'Volume']].corr()
232
+ fig12 = px.imshow(corr_matrix, template='seaborn')
233
+ fig12.update_layout(title_text="Correlation Matrix", title_x=0, margin=dict(l=0, r=10, b=10, t=30))
234
+ g12.plotly_chart(fig12, use_container_width=True)
235
+
236
+ ### ............................................... ##
237
+ # Price Rate of Change (ROC)
238
+ g13, g14, g15 = st.columns((1,1,1))
239
+ n = 12
240
+ data['ROC'] = ((data['Close'] - data['Close'].shift(n)) / data['Close'].shift(n)) * 100
241
+ fig13 = px.line(data, x='Date', y='ROC', template='seaborn')
242
+ fig13.update_layout(title_text="Price Rate of Change (ROC)", title_x=0, margin=dict(l=0, r=10, b=10, t=30), yaxis_title=None, xaxis_title=None)
243
+ g13.plotly_chart(fig13, use_container_width=True)
244
+
245
+ # Stochastic Oscillator
246
+ low_min = data['Low'].rolling(window=14).min()
247
+ high_max = data['High'].rolling(window=14).max()
248
+ data['%K'] = (100 * (data['Close'] - low_min) / (high_max - low_min))
249
+ data['%D'] = data['%K'].rolling(window=3).mean()
250
+ fig14 = px.line(data, x='Date', y='%K', template='seaborn')
251
+ fig14.add_scatter(x=data['Date'], y=data['%D'], mode='lines', line=dict(color="orange"), name='%D (3-day SMA of %K)')
252
+ fig14.update_layout(title_text="Stochastic Oscillator", title_x=0, margin=dict(l=0, r=10, b=10, t=30), yaxis_title=None, xaxis_title=None)
253
+ g14.plotly_chart(fig14, use_container_width=True)
254
+
255
+ # Historical Volatility
256
+ data['Log_Return'] = np.log(data['Close'] / data['Close'].shift(1))
257
+ data['Historical_Volatility'] = data['Log_Return'].rolling(window=252).std() * np.sqrt(252)
258
+ fig15 = px.line(data, x='Date', y='Historical_Volatility', template='seaborn')
259
+ fig15.update_layout(title_text="Historical Volatility (252-day)", title_x=0, margin=dict(l=0, r=10, b=10, t=30), yaxis_title=None, xaxis_title=None)
260
+ g15.plotly_chart(fig15, use_container_width=True)
261
+
262
+ ### ............................................... ##
263
+
264
+ # Visualizing the data and want to get the data when hovering over the graph
265
+ st.subheader('Closing Price vs Time Chart')
266
+ fig1 = go.Figure()
267
+ fig1.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close'))
268
+ fig1.layout.update(hovermode='x')
269
+ # Display the figure in Streamlit
270
+ st.plotly_chart(fig1,use_container_width=True)
271
+
272
+ st.subheader('Closing Price vs Time Chart with 100MA')
273
+ ma100 = data['Close'].rolling(100).mean()
274
+ fig2 = go.Figure()
275
+ # Add traces for 100MA and Closing Price
276
+ fig2.add_trace(go.Scatter(x=data.index, y=ma100, mode='lines', name='100MA'))
277
+ fig2.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Closing Price'))
278
+ fig2.layout.update(hovermode='x')
279
+ # Display the figure in Streamlit
280
+ st.plotly_chart(fig2,use_container_width=True)
281
+
282
+ st.subheader('Closing Price vs Time Chart with 100MA and 200MA')
283
+ ma100 = data['Close'].rolling(100).mean()
284
+ ma200 = data['Close'].rolling(200).mean()
285
+ fig3 = go.Figure()
286
+ # Add traces for 100MA and Closing Price
287
+ fig3.add_trace(go.Scatter(x=data.index, y=ma100, mode='lines', name='100MA'))
288
+ fig3.add_trace(go.Scatter(x=data.index, y=ma200, mode='lines', name='200MA'))
289
+ fig3.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Closing Price'))
290
+ fig3.layout.update(hovermode='x')
291
+
292
+ # Display the figure in Streamlit
293
+ st.plotly_chart(fig3,use_container_width=True)
294
+
295
+ # Splitting the data into training and testing data
296
+ data_training = pd.DataFrame(data['Close'][0:int(len(data)*0.70)])
297
+ data_testing = pd.DataFrame(data['Close'][int(len(data)*0.70): int(len(data))])
298
+
299
+ # Scaling the data
300
+ scaler = MinMaxScaler(feature_range=(0,1))
301
+ data_training_array = scaler.fit_transform(data_training)
302
+
303
+ # load the model
304
+ model = load_model('best_model_MAPI.h5')
305
+
306
+ # Testing the model
307
+ past_100_days = data_training.tail(100)
308
+ final_df = pd.concat([past_100_days,data_testing], ignore_index=True)
309
+ input_data = scaler.fit_transform(final_df)
310
+
311
+ x_test = []
312
+ y_test = []
313
+ for i in range(100, input_data.shape[0]):
314
+ x_test.append(input_data[i-100:i])
315
+ y_test.append(input_data[i,0])
316
+
317
+ x_test, y_test = np.array(x_test), np.array(y_test)
318
+
319
+ y_predicted = model.predict(x_test)
320
+
321
+ scaler = scaler.scale_
322
+ scale_factor = 1/scaler[0]
323
+ y_predicted = y_predicted * scale_factor
324
+ y_test = y_test * scale_factor
325
+
326
+ # Visualizing the results
327
+ st.subheader('Predictions vs Actual')
328
+ fig4 = go.Figure()
329
+ # Add traces for Actual and Predicted Price
330
+ fig4.add_trace(go.Scatter(x=data.index[-len(y_test):], y=y_test, mode='lines', name='Actual Price'))
331
+ fig4.add_trace(go.Scatter(x=data.index[-len(y_predicted):], y=y_predicted[:,0], mode='lines', name='Predicted Price'))
332
+ fig4.layout.update(hovermode='x')
333
+ # Display the figure in Streamlit
334
+ st.plotly_chart(fig4,use_container_width=True)
335
+
336
+ st.sidebar.markdown("----")
337
+ st.sidebar.markdown("© 2023 Stocks Prediction App")