Harsh23Kashyap commited on
Commit
755d6fb
·
1 Parent(s): 03332e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +198 -139
app.py CHANGED
@@ -7,6 +7,7 @@ import streamlit as st
7
  import requests
8
  from streamlit_lottie import st_lottie
9
  from keras.models import load_model
 
10
 
11
  st.set_page_config(
12
  page_title=" Stonks Trends Prediction", #The page title, shown in the browser tab.(should be Placement Details)
@@ -17,158 +18,216 @@ st.set_page_config(
17
  'About': 'https://www.linkedin.com/in/harsh-kashyap-79b87b193/', #A markdown string to show in the About dialog. Used my linkedIn id
18
  }
19
  )
 
 
 
 
 
20
 
21
  from datetime import date
22
  from datetime import timedelta
23
  today = date.today()
24
  # Yesterday date
25
  yesterday = today - timedelta(days = 1)
26
- start='2008-01-01'
27
  end=yesterday;
28
 
 
 
 
 
 
 
 
 
29
  st.title(":computer: Stock Market Predictor") #Title heading of the page
30
  st.markdown("##")
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
 
34
  st.subheader("Enter Stock Ticker")
35
  user_input=st.text_input('','AAPL')
36
- df=data.DataReader(user_input,'yahoo',start,end)
37
- date=df.index
38
-
39
- #Checks if which parameters in hsc_s which is named as branch in sidebar is checked or not and display results accordingly
40
- def load_lottieurl(url: str):
41
- r = requests.get(url) #Make a request to a web page, and return the status code:
42
- if r.status_code != 200: #200 is the HTTP status code for "OK", a successful response.
43
- return None
44
- return r.json() #return the animated gif
45
-
46
- left_column, right_column = st.columns(2) #Columns divided into two parts
47
- with left_column:
48
- dashboard1 = load_lottieurl("https://assets10.lottiefiles.com/packages/lf20_kuhijlvx.json") #get the animated gif from file
49
- st_lottie(dashboard1, key="Dashboard1", height=400) #change the size to height 400
50
- with right_column:
51
- dashboard2 = load_lottieurl("https://assets10.lottiefiles.com/packages/lf20_i2eyukor.json") #get the animated gif from file
52
- st_lottie(dashboard2, key="Dashboard2", height=400) #change the size to height 400
53
-
54
-
55
- st.markdown("""---""")
56
- #Describing data
57
- st.subheader('Data from 2008 to '+str(end.year))
58
- st.write(df.describe())
59
-
60
- st.markdown("""---""")
61
- #Visualisations
62
- st.subheader("Closing Price vs Time Chart of "+str(user_input)) #Header
63
- #plot a line graph
64
- fig_line = px.line(
65
- df,
66
- x = df.index,
67
- y = "Close",
68
- width=1400, #width of the chart
69
- height=750, #height of the chart
70
- )
71
- #remove the background of the back label
72
- fig_line.update_layout(
73
- plot_bgcolor="rgba(0,0,0,0)", #rgba means transparent
74
- xaxis=(dict(showgrid=False)) #dont show the grid
75
- )
76
- #plot the chart
77
- st.plotly_chart(fig_line, use_container_width=True)
78
- st.markdown("""---""")
79
-
80
-
81
- st.subheader("Closing Price vs Time with 100MA of "+str(user_input)) #Header
82
- ma100=df.Close.rolling(100).mean()
83
- #plot a line graph
84
- fig_line = px.line(
85
- ma100,
86
- x = df.index,
87
- y = ma100,
88
- width=1400, #width of the chart
89
- height=750, #height of the chart
90
- )
91
- #remove the background of the back label
92
- fig_line.update_layout(
93
- plot_bgcolor="rgba(0,0,0,0)", #rgba means transparent
94
- xaxis=(dict(showgrid=False)) #dont show the grid
95
- )
96
- #plot the chart
97
- st.plotly_chart(fig_line, use_container_width=True)
98
- st.markdown("""---""")
99
-
100
-
101
- st.subheader("Closing Price vs Time with 1 year moving average of "+str(user_input)) #Header
102
- ma365=df.Close.rolling(365).mean()
103
- #plot a line graph
104
- fig_line = px.line(
105
- ma365,
106
- x = df.index,
107
- y = ma365,
108
- width=1400, #width of the chart
109
- height=750, #height of the chart
110
- )
111
- #remove the background of the back label
112
- fig_line.update_layout(
113
- plot_bgcolor="rgba(0,0,0,0)", #rgba means transparent
114
- xaxis=(dict(showgrid=False)) #dont show the grid
115
- )
116
- #plot the chart
117
- st.plotly_chart(fig_line, use_container_width=True)
118
- st.markdown("""---""")
119
-
120
 
121
-
122
- #Splitting data into training and testing
123
-
124
- data_training= pd.DataFrame(df['Close'][0:int(len(df)*0.7)])
125
- data_testing= pd.DataFrame(df['Close'][int(len(df)*0.7):int(len(df))])
126
- ydate= date[int(len(df)*0.7):int(len(df))]
127
- print(data_training.shape)
128
- print(data_testing.shape)
129
-
130
- #normalising data
131
- from sklearn.preprocessing import MinMaxScaler
132
- scaler=MinMaxScaler(feature_range=(0,1))
133
-
134
- dataset_train = scaler.fit_transform(data_training)
135
- dataset_test = scaler.transform(data_testing)
136
-
137
- def create_dataset(df):
138
- x = []
139
- y = []
140
- for i in range(50, df.shape[0]):
141
- x.append(df[i-50:i, 0])
142
- y.append(df[i, 0])
143
- x = np.array(x)
144
- y = np.array(y)
145
- return x,y
146
-
147
- #Creating dataset
148
- x_train, y_train = create_dataset(dataset_train)
149
- x_test, y_test = create_dataset(dataset_test)
150
-
151
- x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
152
- x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
153
-
154
- #Load my model
155
- model=load_model('stock_prediction.h5')
156
-
157
- predictions = model.predict(x_test)
158
- predictions = scaler.inverse_transform(predictions)
159
- y_test_scaled = scaler.inverse_transform(y_test.reshape(-1, 1))
160
-
161
- cydate=ydate[50:]
162
- st.markdown("""---""")
163
- st.subheader("Actual Vs Predicted Price Graph for "+user_input)
164
- fig, ax = plt.subplots(figsize=(16,8))
165
- ax.set_facecolor('#000041')
166
- ax.plot(cydate,y_test_scaled, color='red', label='Original price')
167
- plt.plot(cydate,predictions, color='cyan', label='Predicted price')
168
- plt.xlabel("Date")
169
- plt.ylabel("Price")
170
- plt.title("Stocks for the company "+str(user_input))
171
- plt.legend()
172
- st.pyplot(fig)
173
-
174
- st.markdown("""---""")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  import requests
8
  from streamlit_lottie import st_lottie
9
  from keras.models import load_model
10
+ from sklearn.preprocessing import MinMaxScaler
11
 
12
  st.set_page_config(
13
  page_title=" Stonks Trends Prediction", #The page title, shown in the browser tab.(should be Placement Details)
 
18
  'About': 'https://www.linkedin.com/in/harsh-kashyap-79b87b193/', #A markdown string to show in the About dialog. Used my linkedIn id
19
  }
20
  )
21
+ def load_lottieurl(url: str):
22
+ r = requests.get(url) #Make a request to a web page, and return the status code:
23
+ if r.status_code != 200: #200 is the HTTP status code for "OK", a successful response.
24
+ return None
25
+ return r.json() #return the animated gif
26
 
27
  from datetime import date
28
  from datetime import timedelta
29
  today = date.today()
30
  # Yesterday date
31
  yesterday = today - timedelta(days = 1)
32
+ start='2010-01-01'
33
  end=yesterday;
34
 
35
+
36
+ if(today.isoweekday()==1):
37
+ current = yesterday = today - timedelta(days = 2)
38
+ else:
39
+ current = yesterday = today - timedelta(days = 1)
40
+
41
+
42
+
43
  st.title(":computer: Stock Market Predictor") #Title heading of the page
44
  st.markdown("##")
45
 
46
+ with st.sidebar:
47
+ st.title("World Market")
48
+ st.title("NIFTY")
49
+ nif = data.DataReader('^NSEI','yahoo',current)['Close']
50
+ st.header(nif.iloc[0].round(2))
51
+ st.markdown("""---""")
52
+
53
+ st.title("SENSEX")
54
+ sen = data.DataReader('^BSESN','yahoo',current)['Close']
55
+ st.header(sen.iloc[0].round(2))
56
+ st.markdown("""---""")
57
+
58
+ st.title("S&P FUTURES")
59
+ sp = data.DataReader('ES=F','yahoo',current)['Close']
60
+ st.header(sp.iloc[0].round(2))
61
+ st.markdown("""---""")
62
+
63
+ st.title("GOLD")
64
+ gold = data.DataReader('GC=F','yahoo',current)['Close']
65
+ st.header(gold.iloc[0].round(2))
66
+ st.markdown("""---""")
67
+
68
+ st.title("DOW")
69
+ dow = data.DataReader('YM=F','yahoo',current)['Close']
70
+ st.header(dow.iloc[0].round(2))
71
+ st.markdown("""---""")
72
+
73
+ st.title("NASDAQ")
74
+ nas = data.DataReader('NQ=F','yahoo',current)['Close']
75
+ st.header(nas.iloc[0].round(2))
76
+ st.markdown("""---""")
77
+
78
+ st.title("CRUDE OIL")
79
+ gold = data.DataReader('CL=F','yahoo',current)['Close']
80
+ st.header(gold.iloc[0].round(2))
81
+ st.markdown("""---""")
82
+
83
+
84
 
85
 
86
  st.subheader("Enter Stock Ticker")
87
  user_input=st.text_input('','AAPL')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
+ val=True
90
+ try:
91
+ df = data.DataReader(user_input,'yahoo',start,end)
92
+ except:
93
+ val=False
94
+ st.write("Wrong ticker. Select again")
95
+ st.markdown("""---""")
96
+ error = load_lottieurl("https://assets9.lottiefiles.com/packages/lf20_k1rx9jox.json") #get the animated gif from file
97
+ st_lottie(error, key="Dashboard1", height=400) #change the size to height 400
98
+
99
+ if val==True:
100
+ date=df.index
101
+
102
+ #Checks if which parameters in hsc_s which is named as branch in sidebar is checked or not and display results accordingly
103
+
104
+
105
+ left_column, right_column = st.columns(2) #Columns divided into two parts
106
+ with left_column:
107
+ dashboard1 = load_lottieurl("https://assets10.lottiefiles.com/packages/lf20_kuhijlvx.json") #get the animated gif from file
108
+ st_lottie(dashboard1, key="Dashboard1", height=400) #change the size to height 400
109
+ with right_column:
110
+ dashboard2 = load_lottieurl("https://assets10.lottiefiles.com/packages/lf20_i2eyukor.json") #get the animated gif from file
111
+ st_lottie(dashboard2, key="Dashboard2", height=400) #change the size to height 400
112
+
113
+
114
+ st.markdown("""---""")
115
+ #Describing data
116
+ st.subheader('Data from 2008 to '+str(end.year))
117
+ st.write(df.describe())
118
+
119
+ st.markdown("""---""")
120
+ #Visualisations
121
+ st.subheader("Closing Price vs Time Chart of "+str(user_input)) #Header
122
+ #plot a line graph
123
+ fig_line = px.line(
124
+ df,
125
+ x = df.index,
126
+ y = "Close",
127
+ width=1400, #width of the chart
128
+ height=750, #height of the chart
129
+ )
130
+ #remove the background of the back label
131
+ fig_line.update_layout(
132
+ plot_bgcolor="rgba(0,0,0,0)", #rgba means transparent
133
+ xaxis=(dict(showgrid=False)) #dont show the grid
134
+ )
135
+ #plot the chart
136
+ st.plotly_chart(fig_line, use_container_width=True)
137
+ st.markdown("""---""")
138
+
139
+
140
+ st.subheader("Closing Price vs Time with 100MA of "+str(user_input)) #Header
141
+ ma100=df.Close.rolling(100).mean()
142
+ #plot a line graph
143
+ fig_line = px.line(
144
+ ma100,
145
+ x = df.index,
146
+ y = ma100,
147
+ width=1400, #width of the chart
148
+ height=750, #height of the chart
149
+ )
150
+ #remove the background of the back label
151
+ fig_line.update_layout(
152
+ plot_bgcolor="rgba(0,0,0,0)", #rgba means transparent
153
+ xaxis=(dict(showgrid=False)) #dont show the grid
154
+ )
155
+ #plot the chart
156
+ st.plotly_chart(fig_line, use_container_width=True)
157
+ st.markdown("""---""")
158
+
159
+
160
+ st.subheader("Closing Price vs Time with 1 year moving average of "+str(user_input)) #Header
161
+ ma365=df.Close.rolling(365).mean()
162
+ #plot a line graph
163
+ fig_line = px.line(
164
+ ma365,
165
+ x = df.index,
166
+ y = ma365,
167
+ width=1400, #width of the chart
168
+ height=750, #height of the chart
169
+ )
170
+ #remove the background of the back label
171
+ fig_line.update_layout(
172
+ plot_bgcolor="rgba(0,0,0,0)", #rgba means transparent
173
+ xaxis=(dict(showgrid=False)) #dont show the grid
174
+ )
175
+ #plot the chart
176
+ st.plotly_chart(fig_line, use_container_width=True)
177
+ st.markdown("""---""")
178
+
179
+
180
+
181
+ #Splitting data into training and testing
182
+
183
+ data_training= pd.DataFrame(df['Close'][0:int(len(df)*0.7)])
184
+ data_testing= pd.DataFrame(df['Close'][int(len(df)*0.7):int(len(df))])
185
+ ydate= date[int(len(df)*0.7):int(len(df))]
186
+ print(data_training.shape)
187
+ print(data_testing.shape)
188
+
189
+ #normalising data
190
+
191
+ scaler=MinMaxScaler(feature_range=(0,1))
192
+
193
+ dataset_train = scaler.fit_transform(data_training)
194
+ dataset_test = scaler.transform(data_testing)
195
+
196
+ def create_dataset(df):
197
+ x = []
198
+ y = []
199
+ for i in range(50, df.shape[0]):
200
+ x.append(df[i-50:i, 0])
201
+ y.append(df[i, 0])
202
+ x = np.array(x)
203
+ y = np.array(y)
204
+ return x,y
205
+
206
+ #Creating dataset
207
+ x_train, y_train = create_dataset(dataset_train)
208
+ x_test, y_test = create_dataset(dataset_test)
209
+
210
+ x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
211
+ x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
212
+
213
+ #Load my model
214
+ model=load_model('stock_prediction.h5')
215
+
216
+ predictions = model.predict(x_test)
217
+ predictions = scaler.inverse_transform(predictions)
218
+ y_test_scaled = scaler.inverse_transform(y_test.reshape(-1, 1))
219
+
220
+ cydate=ydate[50:]
221
+ st.markdown("""---""")
222
+ st.subheader("Actual Vs Predicted Price Graph for "+user_input)
223
+ fig, ax = plt.subplots(figsize=(16,8))
224
+ ax.set_facecolor('#000041')
225
+ ax.plot(cydate,y_test_scaled, color='red', label='Original price')
226
+ plt.plot(cydate,predictions, color='cyan', label='Predicted price')
227
+ plt.xlabel("Date")
228
+ plt.ylabel("Price")
229
+ plt.title("Stocks for the company "+str(user_input))
230
+ plt.legend()
231
+ st.pyplot(fig)
232
+
233
+ st.markdown("""---""")