Skip to content

Commit 8284797

Browse files
Merge pull request #1878 from Killer2OP/stock
[ADDED]: Stock-Price-Prediction
2 parents 34d6426 + 94d1fd3 commit 8284797

File tree

4 files changed

+335
-0
lines changed

4 files changed

+335
-0
lines changed

Stock-Price-Prediction/README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
2+
<h2 align=center> 📑 Stock Price Prediction </h2>
3+
4+
Machine learning has significant applications in the stock price prediction. In this machine learning project, we will be talking about predicting the returns on stocks. This is a very complex task and has uncertainties. We will develop this project into two parts:
5+
6+
First, we will predict stock price using the LSTM neural network.<br>
7+
Then we will build a dashboard using Plotly dash for stock analysis.
8+
9+
<h3>Datasets</h3>
10+
11+
To build the stock price prediction model, we will use the NSE TATA GLOBAL dataset. This is a dataset of Tata Beverages from Tata Global Beverages Limited, National Stock Exchange of India: Tata Global Dataset
12+
To develop the dashboard for stock analysis we will use another stock dataset with multiple stocks like Apple, Microsoft, Facebook: Stocks Dataset
13+
14+
![Alt text](Stock-Price-Prediction-project-dashboard-2.gif)
1.1 MB
Loading

Stock-Price-Prediction/stock_app.py

Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
import dash
2+
import dash_core_components as dcc
3+
import dash_html_components as html
4+
import pandas as pd
5+
import plotly.graph_objs as go
6+
from dash.dependencies import Input, Output
7+
from keras.models import load_model
8+
from sklearn.preprocessing import MinMaxScaler
9+
import numpy as np
10+
11+
12+
app = dash.Dash()
13+
server = app.server
14+
15+
scaler=MinMaxScaler(feature_range=(0,1))
16+
17+
18+
19+
df_nse = pd.read_csv("./NSE-TATA.csv")
20+
21+
df_nse["Date"]=pd.to_datetime(df_nse.Date,format="%Y-%m-%d")
22+
df_nse.index=df_nse['Date']
23+
24+
25+
data=df_nse.sort_index(ascending=True,axis=0)
26+
new_data=pd.DataFrame(index=range(0,len(df_nse)),columns=['Date','Close'])
27+
28+
for i in range(0,len(data)):
29+
new_data["Date"][i]=data['Date'][i]
30+
new_data["Close"][i]=data["Close"][i]
31+
32+
new_data.index=new_data.Date
33+
new_data.drop("Date",axis=1,inplace=True)
34+
35+
dataset=new_data.values
36+
37+
train=dataset[0:987,:]
38+
valid=dataset[987:,:]
39+
40+
scaler=MinMaxScaler(feature_range=(0,1))
41+
scaled_data=scaler.fit_transform(dataset)
42+
43+
x_train,y_train=[],[]
44+
45+
for i in range(60,len(train)):
46+
x_train.append(scaled_data[i-60:i,0])
47+
y_train.append(scaled_data[i,0])
48+
49+
x_train,y_train=np.array(x_train),np.array(y_train)
50+
51+
x_train=np.reshape(x_train,(x_train.shape[0],x_train.shape[1],1))
52+
53+
model=load_model("saved_model.h5")
54+
55+
inputs=new_data[len(new_data)-len(valid)-60:].values
56+
inputs=inputs.reshape(-1,1)
57+
inputs=scaler.transform(inputs)
58+
59+
X_test=[]
60+
for i in range(60,inputs.shape[0]):
61+
X_test.append(inputs[i-60:i,0])
62+
X_test=np.array(X_test)
63+
64+
X_test=np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1))
65+
closing_price=model.predict(X_test)
66+
closing_price=scaler.inverse_transform(closing_price)
67+
68+
train=new_data[:987]
69+
valid=new_data[987:]
70+
valid['Predictions']=closing_price
71+
72+
73+
74+
df= pd.read_csv("./stock_data.csv")
75+
76+
app.layout = html.Div([
77+
78+
html.H1("Stock Price Analysis Dashboard", style={"textAlign": "center"}),
79+
80+
dcc.Tabs(id="tabs", children=[
81+
82+
dcc.Tab(label='NSE-TATAGLOBAL Stock Data',children=[
83+
html.Div([
84+
html.H2("Actual closing price",style={"textAlign": "center"}),
85+
dcc.Graph(
86+
id="Actual Data",
87+
figure={
88+
"data":[
89+
go.Scatter(
90+
x=train.index,
91+
y=valid["Close"],
92+
mode='markers'
93+
)
94+
95+
],
96+
"layout":go.Layout(
97+
title='scatter plot',
98+
xaxis={'title':'Date'},
99+
yaxis={'title':'Closing Rate'}
100+
)
101+
}
102+
103+
),
104+
html.H2("LSTM Predicted closing price",style={"textAlign": "center"}),
105+
dcc.Graph(
106+
id="Predicted Data",
107+
figure={
108+
"data":[
109+
go.Scatter(
110+
x=valid.index,
111+
y=valid["Predictions"],
112+
mode='markers'
113+
)
114+
115+
],
116+
"layout":go.Layout(
117+
title='scatter plot',
118+
xaxis={'title':'Date'},
119+
yaxis={'title':'Closing Rate'}
120+
)
121+
}
122+
123+
)
124+
])
125+
126+
127+
]),
128+
dcc.Tab(label='Facebook Stock Data', children=[
129+
html.Div([
130+
html.H1("Stocks High vs Lows",
131+
style={'textAlign': 'center'}),
132+
133+
dcc.Dropdown(id='my-dropdown',
134+
options=[{'label': 'Tesla', 'value': 'TSLA'},
135+
{'label': 'Apple','value': 'AAPL'},
136+
{'label': 'Facebook', 'value': 'FB'},
137+
{'label': 'Microsoft','value': 'MSFT'}],
138+
multi=True,value=['FB'],
139+
style={"display": "block", "margin-left": "auto",
140+
"margin-right": "auto", "width": "60%"}),
141+
dcc.Graph(id='highlow'),
142+
html.H1("Stocks Market Volume", style={'textAlign': 'center'}),
143+
144+
dcc.Dropdown(id='my-dropdown2',
145+
options=[{'label': 'Tesla', 'value': 'TSLA'},
146+
{'label': 'Apple','value': 'AAPL'},
147+
{'label': 'Facebook', 'value': 'FB'},
148+
{'label': 'Microsoft','value': 'MSFT'}],
149+
multi=True,value=['FB'],
150+
style={"display": "block", "margin-left": "auto",
151+
"margin-right": "auto", "width": "60%"}),
152+
dcc.Graph(id='volume')
153+
], className="container"),
154+
])
155+
156+
157+
])
158+
])
159+
160+
161+
162+
163+
164+
165+
166+
@app.callback(Output('highlow', 'figure'),
167+
[Input('my-dropdown', 'value')])
168+
def update_graph(selected_dropdown):
169+
dropdown = {"TSLA": "Tesla","AAPL": "Apple","FB": "Facebook","MSFT": "Microsoft",}
170+
trace1 = []
171+
trace2 = []
172+
for stock in selected_dropdown:
173+
trace1.append(
174+
go.Scatter(x=df[df["Stock"] == stock]["Date"],
175+
y=df[df["Stock"] == stock]["High"],
176+
mode='lines', opacity=0.7,
177+
name=f'High {dropdown[stock]}',textposition='bottom center'))
178+
trace2.append(
179+
go.Scatter(x=df[df["Stock"] == stock]["Date"],
180+
y=df[df["Stock"] == stock]["Low"],
181+
mode='lines', opacity=0.6,
182+
name=f'Low {dropdown[stock]}',textposition='bottom center'))
183+
traces = [trace1, trace2]
184+
data = [val for sublist in traces for val in sublist]
185+
figure = {'data': data,
186+
'layout': go.Layout(colorway=["#5E0DAC", '#FF4F00', '#375CB1',
187+
'#FF7400', '#FFF400', '#FF0056'],
188+
height=600,
189+
title=f"High and Low Prices for {', '.join(str(dropdown[i]) for i in selected_dropdown)} Over Time",
190+
xaxis={"title":"Date",
191+
'rangeselector': {'buttons': list([{'count': 1, 'label': '1M',
192+
'step': 'month',
193+
'stepmode': 'backward'},
194+
{'count': 6, 'label': '6M',
195+
'step': 'month',
196+
'stepmode': 'backward'},
197+
{'step': 'all'}])},
198+
'rangeslider': {'visible': True}, 'type': 'date'},
199+
yaxis={"title":"Price (USD)"})}
200+
return figure
201+
202+
203+
@app.callback(Output('volume', 'figure'),
204+
[Input('my-dropdown2', 'value')])
205+
def update_graph(selected_dropdown_value):
206+
dropdown = {"TSLA": "Tesla","AAPL": "Apple","FB": "Facebook","MSFT": "Microsoft",}
207+
trace1 = []
208+
for stock in selected_dropdown_value:
209+
trace1.append(
210+
go.Scatter(x=df[df["Stock"] == stock]["Date"],
211+
y=df[df["Stock"] == stock]["Volume"],
212+
mode='lines', opacity=0.7,
213+
name=f'Volume {dropdown[stock]}', textposition='bottom center'))
214+
traces = [trace1]
215+
data = [val for sublist in traces for val in sublist]
216+
figure = {'data': data,
217+
'layout': go.Layout(colorway=["#5E0DAC", '#FF4F00', '#375CB1',
218+
'#FF7400', '#FFF400', '#FF0056'],
219+
height=600,
220+
title=f"Market Volume for {', '.join(str(dropdown[i]) for i in selected_dropdown_value)} Over Time",
221+
xaxis={"title":"Date",
222+
'rangeselector': {'buttons': list([{'count': 1, 'label': '1M',
223+
'step': 'month',
224+
'stepmode': 'backward'},
225+
{'count': 6, 'label': '6M',
226+
'step': 'month',
227+
'stepmode': 'backward'},
228+
{'step': 'all'}])},
229+
'rangeslider': {'visible': True}, 'type': 'date'},
230+
yaxis={"title":"Transactions Volume"})}
231+
return figure
232+
233+
234+
235+
if __name__=='__main__':
236+
app.run_server(debug=True)

Stock-Price-Prediction/stock_pred.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import pandas as pd
2+
import numpy as np
3+
4+
import matplotlib.pyplot as plt
5+
%matplotlib inline
6+
7+
from matplotlib.pylab import rcParams
8+
rcParams['figure.figsize']=20,10
9+
10+
from sklearn.preprocessing import MinMaxScaler
11+
scaler=MinMaxScaler(feature_range=(0,1))
12+
13+
df=pd.read_csv("NSE-TATA.csv")
14+
df.head()
15+
16+
df["Date"]=pd.to_datetime(df.Date,format="%Y-%m-%d")
17+
df.index=df['Date']
18+
19+
plt.figure(figsize=(16,8))
20+
plt.plot(df["Close"],label='Close Price history')
21+
22+
from keras.models import Sequential
23+
from keras.layers import LSTM,Dropout,Dense
24+
25+
data=df.sort_index(ascending=True,axis=0)
26+
new_dataset=pd.DataFrame(index=range(0,len(df)),columns=['Date','Close'])
27+
28+
for i in range(0,len(data)):
29+
new_dataset["Date"][i]=data['Date'][i]
30+
new_dataset["Close"][i]=data["Close"][i]
31+
32+
33+
new_dataset.index=new_dataset.Date
34+
new_dataset.drop("Date",axis=1,inplace=True)
35+
36+
final_dataset=new_dataset.values
37+
38+
train_data=final_dataset[0:987,:]
39+
valid_data=final_dataset[987:,:]
40+
41+
scaler=MinMaxScaler(feature_range=(0,1))
42+
scaled_data=scaler.fit_transform(final_dataset)
43+
44+
x_train_data,y_train_data=[],[]
45+
46+
for i in range(60,len(train_data)):
47+
x_train_data.append(scaled_data[i-60:i,0])
48+
y_train_data.append(scaled_data[i,0])
49+
50+
x_train_data,y_train_data=np.array(x_train_data),np.array(y_train_data)
51+
52+
x_train_data=np.reshape(x_train_data,(x_train_data.shape[0],x_train_data.shape[1],1))
53+
54+
lstm_model=Sequential()
55+
lstm_model.add(LSTM(units=50,return_sequences=True,input_shape=(x_train_data.shape[1],1)))
56+
lstm_model.add(LSTM(units=50))
57+
lstm_model.add(Dense(1))
58+
59+
60+
61+
62+
lstm_model.compile(loss='mean_squared_error',optimizer='adam')
63+
lstm_model.fit(x_train_data,y_train_data,epochs=1,batch_size=1,verbose=2)
64+
65+
inputs_data=new_dataset[len(new_dataset)-len(valid_data)-60:].values
66+
inputs_data=inputs_data.reshape(-1,1)
67+
inputs_data=scaler.transform(inputs_data)
68+
69+
70+
X_test=[]
71+
for i in range(60,inputs_data.shape[0]):
72+
X_test.append(inputs_data[i-60:i,0])
73+
X_test=np.array(X_test)
74+
75+
X_test=np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1))
76+
closing_price=model.predict(X_test)
77+
closing_price=scaler.inverse_transform(closing_price)
78+
79+
lstm_model.save("saved_lstm_model.h5")
80+
81+
train_data=new_dataset[:987]
82+
valid_data=new_dataset[987:]
83+
valid_data['Predictions']=prediction_closing
84+
plt.plot(train_data["Close"])
85+
plt.plot(valid_data[['Close',"Predictions"]])

0 commit comments

Comments
 (0)