StockOracle / app.py
mircanboncea's picture
implement
a473b60
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)