joyson072 commited on
Commit
ed8e2d0
·
1 Parent(s): b8eca19

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -0
app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ import yfinance as yf
5
+ from keras.models import Sequential
6
+ from sklearn.preprocessing import MinMaxScaler
7
+ from keras.layers.core import Dense,Dropout,Activation
8
+ from keras.layers.recurrent import LSTM
9
+ from datetime import date
10
+ import gradio as gr
11
+
12
+ def create_dataset(dataset,time_step=15):
13
+ x_ind,y_dep =[],[]
14
+ for i in range(len(dataset)-time_step-1):
15
+ a=dataset[i:(i+time_step),0]
16
+ x_ind.append(a)
17
+ y_dep.append(dataset[i+time_step,0])
18
+ return np.array(x_ind),np.array(y_dep)
19
+
20
+ def stockprice(stockname,number_of_samples):
21
+ df_yahoo = yf.download(stockname,start='2020-09-15',end=date.today(),interval = "1h",progress=False,auto_adjust=True)
22
+ df=df_yahoo
23
+ df.index.rename('Date', inplace=True)
24
+ df=df.sort_values(by=['Date'],ignore_index=True)
25
+ min_max_scaler=MinMaxScaler(feature_range=(0,1))
26
+ dataset=min_max_scaler.fit_transform(df['Close'].values.reshape(-1,1))
27
+ train_size=int(len(df)*0.8)
28
+ test_size=len(df)-train_size
29
+ Train=dataset[0:train_size,:]
30
+ Test=dataset[train_size:len(dataset),:]
31
+ x_train,y_train=create_dataset(Train,time_step=15)
32
+ x_test,y_test=create_dataset(Test,time_step=15)
33
+ x_train=np.reshape(x_train,(x_train.shape[0],1,x_train.shape[1]))
34
+ x_test=np.reshape(x_test,(x_test.shape[0],1,x_test.shape[1]))
35
+ time_step=15
36
+ model=Sequential()
37
+ model.add(LSTM(20,input_shape=(1,time_step)))
38
+ model.add(Dense(1))
39
+ model.compile(loss="mean_squared_error",optimizer='adam')
40
+ model.fit(x_train,y_train,epochs=100,verbose=0)
41
+ y_pred=model.predict(x_test)
42
+ y_pred_RNN=min_max_scaler.inverse_transform(y_pred)
43
+ y_test=np.expand_dims(y_test,axis=1)
44
+ y_test=min_max_scaler.inverse_transform(y_test)
45
+ df1=df.drop(["Volume","Open","High","Low"],axis=1)
46
+ a= int(number_of_samples)*15
47
+ new_data = df1[-(a+1):-1]
48
+ last60prices=np.array(new_data)
49
+ last60prices=last60prices.reshape(-1, 1)
50
+ X=min_max_scaler.transform(last60prices)
51
+ TimeSteps=int(15)
52
+ NumFeatures=int(1)
53
+ number_of_samples=int(number_of_samples)
54
+ X=X.reshape(number_of_samples, NumFeatures, TimeSteps)
55
+ predicted_Price = model.predict(X)
56
+ predicted_Price = min_max_scaler.inverse_transform(predicted_Price)
57
+ pred_df=pd.DataFrame(list(map(lambda x: x[0], predicted_Price)),columns=["PREDICTIONS"])
58
+
59
+ pred_df.reset_index(inplace=True)
60
+ pred_df = pred_df.rename(columns = {'index':'HOURS'})
61
+
62
+ plt.figure(figsize=(15, 6))
63
+ range_history = len(new_data)
64
+ range_future = list(range(range_history, range_history +len(predicted_Price)))
65
+ plt.plot(np.arange(range_history), np.array(new_data),label='History')
66
+ plt.plot(range_future, np.array(predicted_Price),label='Forecasted for RNN')
67
+ plt.legend(loc='upper right')
68
+ plt.xlabel('Time step (hour)')
69
+ plt.ylabel('Stock Price')
70
+
71
+
72
+ return pred_df,plt.gcf()
73
+
74
+ interface = gr.Interface(fn = stockprice,
75
+ inputs = [gr.inputs.Textbox(lines=1, placeholder="Enter STOCK-TICKER", default="FB", label="STOCKNAME"),
76
+ gr.inputs.Slider(minimum=0, maximum=150, step=1, default=5, label="Number of Sample to Predict")],
77
+ outputs = ["dataframe","plot"],
78
+ description="LSTM STOCK PREDICTION")
79
+
80
+ interface.launch()