File size: 9,643 Bytes
03332e8
 
 
 
 
 
 
 
 
755d6fb
92864b7
cf30deb
 
 
 
 
 
 
 
 
 
03332e8
83c5f2b
03332e8
7cb2a9f
03332e8
 
 
 
 
 
 
755d6fb
 
 
 
 
03332e8
 
 
 
92864b7
 
 
 
 
 
 
03332e8
 
755d6fb
cf30deb
03332e8
755d6fb
 
 
 
 
 
 
 
03332e8
 
 
755d6fb
 
 
92864b7
 
cf30deb
 
92864b7
 
 
 
 
 
755d6fb
 
 
92864b7
 
cf30deb
92864b7
 
 
 
 
 
 
755d6fb
 
 
92864b7
 
cf30deb
92864b7
 
 
 
 
 
755d6fb
 
 
92864b7
 
cf30deb
92864b7
 
 
 
 
 
755d6fb
 
 
92864b7
 
cf30deb
92864b7
 
 
 
 
 
755d6fb
92864b7
755d6fb
92864b7
 
cf30deb
92864b7
 
 
 
 
 
755d6fb
 
 
92864b7
 
cf30deb
92864b7
 
 
 
 
 
755d6fb
92864b7
755d6fb
 
03332e8
 
 
98be78d
03332e8
755d6fb
 
cf30deb
755d6fb
 
 
 
 
 
 
 
 
 
98be78d
cf30deb
98be78d
 
755d6fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ae48dd
98be78d
0ae48dd
92864b7
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
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pandas_datareader as data
import plotly.express as px
import streamlit as st
import requests
from streamlit_lottie import st_lottie
from keras.models import load_model
from sklearn.preprocessing import MinMaxScaler
from tensorflow.python import tf2
from pandas_datareader import data as pdr
import yfinance as yf
yf.pdr_override()

y_symbols = ['AAPL']
from datetime import datetime
startdate = datetime(2022,12,1)
enddate = datetime(2022,12,2)
data = pdr.get_data_yahoo(y_symbols, start=startdate, end=enddate)['Close']
print(data)


st.set_page_config(
    page_title=" Stocks Market Predictor", #The page title, shown in the browser tab.(should be Placement Details)
    initial_sidebar_state="auto", #The way sidebar should start out. Auto shows it in desktop.
    page_icon=":computer:", #The page favicon. Use the computer emoji
    layout="wide", #The way page content should be laid out. "wide" uses the entire screen.
    menu_items={ #Configure the menu that appears on the top-right side of this app.
            'About': 'https://www.linkedin.com/in/harsh-kashyap-79b87b193/', #A markdown string to show in the About dialog. Used my linkedIn id
     }
)
def load_lottieurl(url: str):
        r = requests.get(url) #Make a request to a web page, and return the status code:
        if r.status_code != 200: #200 is the HTTP status code for "OK", a successful response.
            return None
        return r.json() #return the animated gif

from datetime import date
from datetime import timedelta
today = date.today()
import datetime
now = datetime.datetime.now()
weekend=today.strftime("%A")
if(weekend=="Saturday"):
    today=today-timedelta(days=1)
if(weekend=="Sunday"):
    today=today-timedelta(days=2)
# Yesterday date
yesterday = today - timedelta(days = 1)
start='2010-01-01'
end=yesterday


if(today.isoweekday()==1):
    current = yesterday = today - timedelta(days = 2)
else:  
    current = yesterday = today - timedelta(days = 1)
    


st.title(":computer:  Stock Market Predictor") #Title heading of the page
st.markdown("##") 

with st.sidebar:
    st.title("World Market")
    st.title("NIFTY")
    nifval=True
    try:
        nif = pdr.get_data_yahoo('^NSEI', start=current - timedelta(7), end=current)['Close'].tail(1)
        print(nif)
    except:
        nifval=False
    if nifval==True:
        st.header(nif.iloc[0].round(2))
    else: 
        st.write("Can't load right now")
    st.markdown("""---""")
    
    st.title("SENSEX")
    senval=True
    try:
        sen = pdr.get_data_yahoo('^BSESN', start=current - timedelta(7), end=current)['Close'].tail(1)
    except:
        senval=False
    if senval==True:
        st.header(sen.iloc[0].round(2))
    else: 
        st.write("Can't load right now")
   
    st.markdown("""---""")
    
    st.title("S&P FUTURES")
    spval=True
    try:
        sp = pdr.get_data_yahoo('ES=F', start=current - timedelta(7), end=current)['Close'].tail(1)
    except:
        spval=False
    if spval==True:
        st.header(sp.iloc[0].round(2))
    else: 
        st.write("Can't load right now")
    st.markdown("""---""")
    
    st.title("GOLD")
    goldval=True
    try:
        gold = pdr.get_data_yahoo('GC=F', start=current - timedelta(7), end=current)['Close'].tail(1)
    except:
        goldval=False
    if goldval==True:
        st.header(gold.iloc[0].round(2))
    else: 
        st.write("Can't load right now")
    st.markdown("""---""")
    
    st.title("DOW")
    dowval=True
    try:
        dow = pdr.get_data_yahoo('YM=F', start=current - timedelta(7), end=current)['Close'].tail(1)
    except:
        dowval=False
    if dowval==True:
        st.header(dow.iloc[0].round(2))
    else: 
        st.write("Can't load right now")
    
    st.markdown("""---""")
    st.title("NASDAQ")
    nasval=True
    try:
        nas = pdr.get_data_yahoo('NQ=F', start=current - timedelta(7), end=current)['Close'].tail(1)
    except:
        nasval=False
    if nasval==True:
        st.header(nas.iloc[0].round(2))
    else: 
        st.write("Can't load right now")
    st.markdown("""---""")
    
    st.title("CRUDE OIL")
    oilval=True
    try:
        oil = pdr.get_data_yahoo('CL=F', start=current - timedelta(7), end=current)['Close'].tail(1)
    except:
        oilval=False
    if oilval==True:
        st.header(oil.iloc[0].round(2))
    else: 
        st.write("Can't load right now")
    st.markdown("""---""")
    

   


st.subheader("Enter Stock Ticker")
user_input=st.text_input('','HDFCBANK.BO')

val=True
try:
    df = pdr.get_data_yahoo(user_input, start=start, end=end)
except:
    val=False
    st.write("Wrong ticker. Select again")
    st.markdown("""---""")
    error = load_lottieurl("https://assets9.lottiefiles.com/packages/lf20_k1rx9jox.json") #get the animated gif from file
    st_lottie(error, key="Dashboard1", height=400) #change the size to height 400

if val==True:
    date=df.index

    st.header("Recent Price")
    curr = pdr.get_data_yahoo(user_input, start=current - timedelta(7), end=current)['Close'].tail(1)
    st.header(curr.iloc[0].round(2))
    st.markdown("""---""")   

    left_column, right_column = st.columns(2) #Columns divided into two parts
    with left_column:
        dashboard1 = load_lottieurl("https://assets10.lottiefiles.com/packages/lf20_kuhijlvx.json") #get the animated gif from file
        st_lottie(dashboard1, key="Dashboard1", height=400) #change the size to height 400
    with right_column:
        dashboard2 = load_lottieurl("https://assets10.lottiefiles.com/packages/lf20_i2eyukor.json") #get the animated gif from file
        st_lottie(dashboard2, key="Dashboard2", height=400) #change the size to height 400


    st.markdown("""---""")
    #Describing data 
    st.subheader('Data from 2008 to '+str(end.year))
    st.write(df.describe())

    st.markdown("""---""")
    #Visualisations
    st.subheader("Closing Price vs Time Chart of "+str(user_input)) #Header
    #plot a line graph
    fig_line = px.line(
        df,  
        x = df.index,  
        y = "Close", 
        width=1400, #width of the chart
        height=750, #height of the chart
    )
    #remove the background of the back label
    fig_line.update_layout(
        plot_bgcolor="rgba(0,0,0,0)",  #rgba means transparent
        xaxis=(dict(showgrid=False)) #dont show the grid
    )
    #plot the chart
    st.plotly_chart(fig_line, use_container_width=True)
    st.markdown("""---""")


    st.subheader("Closing Price vs Time with 100MA of "+str(user_input)) #Header
    ma100=df.Close.rolling(100).mean()
    #plot a line graph
    fig_line = px.line( 
        ma100,
        x = df.index,  
        y = ma100, 
        width=1400, #width of the chart
        height=750, #height of the chart
    )
    #remove the background of the back label
    fig_line.update_layout(
        plot_bgcolor="rgba(0,0,0,0)",  #rgba means transparent
        xaxis=(dict(showgrid=False)) #dont show the grid
    )
    #plot the chart
    st.plotly_chart(fig_line, use_container_width=True)
    st.markdown("""---""")


    st.subheader("Closing Price vs Time with 1 year moving average of  "+str(user_input)) #Header
    ma365=df.Close.rolling(365).mean()
    #plot a line graph
    fig_line = px.line( 
        ma365,
        x = df.index,  
        y = ma365, 
        width=1400, #width of the chart
        height=750, #height of the chart
    )
    #remove the background of the back label
    fig_line.update_layout(
        plot_bgcolor="rgba(0,0,0,0)",  #rgba means transparent
        xaxis=(dict(showgrid=False)) #dont show the grid
    )
    #plot the chart
    st.plotly_chart(fig_line, use_container_width=True)
    st.markdown("""---""")



    #Splitting data into training and testing

    data_training= pd.DataFrame(df['Close'][0:int(len(df)*0.7)])
    data_testing= pd.DataFrame(df['Close'][int(len(df)*0.7):int(len(df))])
    ydate= date[int(len(df)*0.7):int(len(df))]
    print(data_training.shape)
    print(data_testing.shape)

    #normalising data
    
    scaler=MinMaxScaler(feature_range=(0,1))

    dataset_train = scaler.fit_transform(data_training)
    dataset_test = scaler.transform(data_testing)

    def create_dataset(df):
        x = []
        y = []
        for i in range(50, df.shape[0]):
            x.append(df[i-50:i, 0])
            y.append(df[i, 0])
        x = np.array(x)
        y = np.array(y)
        return x,y

    #Creating dataset
    x_train, y_train = create_dataset(dataset_train)
    x_test, y_test = create_dataset(dataset_test)

    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))

    #Load my model
    model=load_model('stock_prediction.h5')

    predictions = model.predict(x_test)
    predictions = scaler.inverse_transform(predictions)
    y_test_scaled = scaler.inverse_transform(y_test.reshape(-1, 1))

    cydate=ydate[50:]
    st.markdown("""---""")
    st.subheader("Actual Vs Predicted Price Graph for "+user_input)
    fig, ax = plt.subplots(figsize=(16,8))
    ax.set_facecolor('#000041')
    ax.plot(cydate,y_test_scaled, color='red', label='Original price')
    plt.plot(cydate,predictions, color='cyan', label='Predicted price')
    plt.xlabel("Date")
    plt.ylabel("Price")
    plt.title("Stocks for the company "+str(user_input))
    plt.legend()
    st.pyplot(fig)

    
    

st.markdown("<br><hr><center>Made with ❤️ by <a href='https://www.linkedin.com/in/harsh-kashyap/'><strong>Harsh Kashyap</strong></a></center><hr>", unsafe_allow_html=True)