Spaces:
Running
Running
File size: 5,925 Bytes
a473b60 | 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 | import pandas as pd
import pandas_datareader as data
import numpy as np
import plotly.graph_objects as go
import streamlit as st
import yfinance as yf
import datetime as dt
from pandas_datareader import data as pdr
from keras.models import load_model
from sklearn.preprocessing import MinMaxScaler
from tensorflow.python import tf2
from datetime import timedelta
default_ticker = 'NVDA'
yf.pdr_override()
st.set_page_config(
page_title="Future Stock Price Prediction",
initial_sidebar_state="auto",
page_icon=":computer:",
layout="wide",
)
today = dt.date.today()
def create_dataset(df, days):
x = []
y = []
for i in range(days, df.shape[0]):
x.append(df[i-days:i, 0])
y.append(df[i, 0])
x = np.array(x)
y = np.array(y)
return x,y
def predict(model_file, x_data, y_data):
model = load_model(model_file)
predictions = model.predict(x_data)
predictions = scaler.inverse_transform(predictions)
y_data_scaled = scaler.inverse_transform(y_data.reshape(-1, 1))
df_y_data_scaled = pd.DataFrame(y_data_scaled, columns = ['Close'])
df_predictions = pd.DataFrame(predictions, columns = ['Close'])
return df_y_data_scaled, df_predictions
def prediction_chart(model_file, x_data, original_y_data, predicted_y_data):
chart = go.Figure()
chart.add_trace(go.Scatter(x = x_data, y = original_y_data.Close, name='Price',
mode='lines', marker_color='black'))
chart.add_trace(go.Scatter(x = x_data, y = predicted_y_data.Close, name='Prediction',
mode='lines', marker_color='red'))
chart.update_layout(title='Stock Price vs Predicted Price with loaded model: ' + model_file,
xaxis_title='Date',
yaxis_title='Price')
chart.show()
st.plotly_chart(chart, use_container_width=True)
def show_prediction(model_file, x_data, dataset_test, days):
#Creating dataset
x_test, y_test = create_dataset(dataset_test, days)
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
#Load model and predict
original_y_data, predicted_y_data = predict(model_file, x_test, y_test)
prediction_chart(model_file, x_data[days:], original_y_data, predicted_y_data)
with st.sidebar:
user_input = st.text_input("Ticker", default_ticker)
user_date = st.date_input("Prediction start date", dt.date(2021, 1, 1))
ticker=True
try:
df = pdr.get_data_yahoo(user_input, start=user_date, end=today).reset_index()
current_price = df['Close'].tail(1)
except:
ticker=False
if ticker==True:
st.header(current_price.iloc[0].round(2))
else:
st.write("Wrong ticker. Select again")
st.markdown("""---""")
st.title("S&P FUTURES")
spval=True
try:
sp = pdr.get_data_yahoo('ES=F', start=today - timedelta(7), end=today)['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("NASDAQ")
nasval=True
try:
nas = pdr.get_data_yahoo('NQ=F', start=today - timedelta(7), end=today)['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("DOW")
dowval=True
try:
dow = pdr.get_data_yahoo('YM=F', start=today - timedelta(7), end=today)['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("GOLD")
goldval=True
try:
gold = pdr.get_data_yahoo('GC=F', start=today - timedelta(7), end=today)['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("CRUDE OIL")
oilval=True
try:
oil = pdr.get_data_yahoo('CL=F', start=today - timedelta(7), end=today)['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("""---""")
if ticker==True:
date = df.Date
close = df.Close.fillna(method='ffill')
fig = go.Figure()
fig.add_trace(go.Scatter(x = date, y = close, name='Price',
mode='lines', marker_color='black'))
ma1 = close.ewm(span=100, adjust=False).mean()
fig.add_trace(go.Scatter(x = date, y = ma1, name='MA 100',
mode='lines', marker_color='red'))
ma2 = close.ewm(span=365, adjust=False).mean()
fig.add_trace(go.Scatter(x = date, y = ma2, name='MA 365',
mode='lines', marker_color='blue'))
fig.update_layout(title='Stock Price vs Moving averages',
xaxis_title='Date',
yaxis_title='Price')
fig.show()
st.plotly_chart(fig, use_container_width=True)
#Start prediction
data_training = pd.DataFrame(close[0:int(len(close)*0.7)])
data_testing = pd.DataFrame(close[int(len(close)*0.7):int(len(close))])
x_data = date[int(len(date)*0.7):int(len(date))].reset_index(drop=True)
#normalising data
scaler = MinMaxScaler(feature_range=(0,1))
dataset_train = scaler.fit_transform(data_training)
dataset_test = scaler.transform(data_testing)
show_prediction('stock_prediction.h5', x_data, dataset_test, 50)
show_prediction('stock_prediction_test.h5', x_data, dataset_test, 7)
show_prediction('stock_prediction_longer_train.h5', x_data, dataset_test, 7)
|