Spaces:
Build error
Build error
import time | |
import warnings | |
# import SessionState | |
import numpy as np | |
import pandas as pd | |
import datetime as dt | |
import streamlit as st | |
import tensorflow as tf | |
import plotly.express as px | |
import pandas_datareader as pdr | |
import matplotlib.pyplot as plt | |
from PIL import Image | |
from st_aggrid.shared import GridUpdateMode | |
from sklearn.preprocessing import MinMaxScaler | |
from tensorflow.keras.models import load_model | |
from st_aggrid import AgGrid, GridOptionsBuilder | |
icon = Image.open('bitcoin.png') | |
st.set_page_config( | |
page_title="FANG Stock Prediction", | |
page_icon=icon, | |
layout="wide" | |
) | |
st.write("# Welcome to Stock Prediction Dashboard :man: :coffee:") | |
company_ticker = ['FB', 'AAPL', 'TSLA', 'GOOG', 'NVDA'] | |
start_date = dt.datetime(2010, 10, 29) | |
end_date = dt.datetime(2021, 12, 31) | |
data_FB = pdr.DataReader(company_ticker[0], 'yahoo', start_date, end_date) | |
data_AAPL = pdr.DataReader(company_ticker[1], 'yahoo', start_date, end_date) | |
data_TSLA = pdr.DataReader(company_ticker[2], 'yahoo', start_date, end_date) | |
data_GOOG = pdr.DataReader(company_ticker[3], 'yahoo', start_date, end_date) | |
data_NVDA = pdr.DataReader(company_ticker[4], 'yahoo', start_date, end_date) | |
scaler_tesla = MinMaxScaler() | |
scaler_google = MinMaxScaler() | |
scaler_nvidia = MinMaxScaler() | |
prediction_days = 89 | |
test_start = dt.datetime(2021, 12, 31) | |
test_end = dt.datetime.now() | |
test_data_FB = pdr.DataReader(company_ticker[0], 'yahoo', test_start, test_end) | |
test_data_AAPL = pdr.DataReader(company_ticker[1], 'yahoo', test_start, test_end) | |
test_data_TSLA = pdr.DataReader(company_ticker[2], 'yahoo', test_start, test_end) | |
test_data_GOOG = pdr.DataReader(company_ticker[3], 'yahoo', test_start, test_end) | |
test_data_NVDA = pdr.DataReader(company_ticker[4], 'yahoo', test_start, test_end) | |
total_dataset_tesla = pd.concat((data_TSLA['Adj Close'], test_data_TSLA['Adj Close']), axis=0) | |
total_dataset_google = pd.concat((data_GOOG['Adj Close'], test_data_GOOG['Adj Close']), axis=0) | |
total_dataset_nvidia = pd.concat((data_NVDA['Adj Close'], test_data_NVDA['Adj Close']), axis=0) | |
model_inputs_tesla = total_dataset_tesla[len(total_dataset_tesla) - len(test_data_TSLA) - prediction_days:].values | |
model_inputs_tesla = model_inputs_tesla.reshape(-1, 1) | |
model_inputs_tesla = scaler_tesla.fit_transform(model_inputs_tesla) | |
model_inputs_google = total_dataset_google[len(total_dataset_google) - len(test_data_GOOG) - prediction_days:].values | |
model_inputs_google = model_inputs_google.reshape(-1, 1) | |
model_inputs_google = scaler_google.fit_transform(model_inputs_google) | |
model_inputs_nvidia = total_dataset_nvidia[len(total_dataset_nvidia) - len(test_data_NVDA) - prediction_days:].values | |
model_inputs_nvidia = model_inputs_nvidia.reshape(-1, 1) | |
model_inputs_nvidia = scaler_nvidia.fit_transform(model_inputs_nvidia) | |
def test_data_predict(lstm_model, model_inputs, scaler): | |
X_test = [] | |
for x in range(prediction_days, len(model_inputs)): | |
X_test.append(model_inputs[x-prediction_days:x, 0]) | |
X_test = np.array(X_test) | |
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) | |
prediction_prices = lstm_model.predict(X_test) | |
prediction_prices = scaler.inverse_transform(prediction_prices) | |
return prediction_prices | |
lstm_tsla = load_model("tsla_stock_prediction.h5") | |
lstm_goog = load_model("fang_stock_prediction.h5") | |
lstm_nvda = load_model("nvda_stock_prediction.h5") | |
tsla_predict_prices = test_data_predict(lstm_model=lstm_tsla, model_inputs=model_inputs_tesla, scaler=scaler_tesla) | |
goog_predict_prices = test_data_predict(lstm_model=lstm_goog, model_inputs=model_inputs_google, scaler=scaler_google) | |
nvda_predict_prices = test_data_predict(lstm_model=lstm_nvda, model_inputs=model_inputs_nvidia, scaler=scaler_nvidia) | |
# actual_aapl = pd.DataFrame(test_data_AAPL) | |
actual_tsla = pd.DataFrame(test_data_TSLA) | |
actual_goog = pd.DataFrame(test_data_GOOG) | |
actual_nvda = pd.DataFrame(test_data_NVDA) | |
valid_tesla = pd.DataFrame() | |
valid_tesla['Actual'] = test_data_TSLA.filter(['Adj Close']) | |
valid_tesla['Predictions'] = tsla_predict_prices | |
valid_google = pd.DataFrame() | |
valid_google['Actual'] = test_data_GOOG.filter(['Adj Close']) | |
valid_google['Predictions'] = goog_predict_prices | |
valid_nvidia = pd.DataFrame() | |
valid_nvidia['Actual'] = test_data_NVDA.filter(['Adj Close']) | |
valid_nvidia['Predictions'] = nvda_predict_prices | |
st.write("#### Actual Stock Value of Tesla 2021 - Now (in Billion USD)") | |
tsla_col1, tsla_col2, tsla_col3 = st.columns(3) | |
tsla_col1.metric("Open Stock Value", f"{np.round(actual_tsla['Open'][len(actual_tsla)-1], 3)}", | |
"{}".format(np.round(actual_tsla['Open'][len(test_data_TSLA)-1] - actual_tsla['Open'][len(test_data_TSLA)-2]), 3)) | |
tsla_col2.metric("Open Stock Value", f"{np.round(actual_tsla['Close'][len(actual_tsla)-1], 3)}", | |
"{}".format(np.round(actual_tsla['Close'][len(test_data_TSLA)-1] - actual_tsla['Close'][len(test_data_TSLA)-2]), 3)) | |
tsla_col3.metric("Open Stock Value", f"{np.round(actual_tsla['Adj Close'][len(actual_tsla)-1], 3)}", | |
"{}".format(np.round(actual_tsla['Adj Close'][len(test_data_TSLA)-1] - actual_tsla['Adj Close'][len(test_data_TSLA)-2]), 3)) | |
st.write("#### Actual Stock Value of Google 2021 - Now (in Billion USD)") | |
goog_col1, goog_col2, goog_col3 = st.columns(3) | |
goog_col1.metric("Open Stock Value", f"{np.round(actual_goog['Open'][len(actual_goog)-1], 3)}", | |
"{}".format(np.round(actual_goog['Open'][len(test_data_GOOG)-1] - actual_goog['Open'][len(test_data_GOOG)-2]), 3)) | |
goog_col2.metric("Close Stock Value", f"{np.round(actual_goog['Close'][len(actual_goog)-1], 3)}", | |
"{}".format(np.round(actual_goog['Close'][len(test_data_GOOG)-1] - actual_goog['Close'][len(test_data_GOOG)-2]), 3)) | |
goog_col3.metric("Adjusted Close Value", f"{np.round(actual_goog['Adj Close'][len(actual_goog)-1], 3)}", | |
"{}".format(np.round(actual_goog['Adj Close'][len(test_data_GOOG)-1] - actual_goog['Adj Close'][len(test_data_GOOG)-2]), 3)) | |
st.write("#### Actual Stock Value of NVIDIA 2021 - Now (in Billion USD)") | |
nvda_col1, nvda_col2, nvda_col3 = st.columns(3) | |
nvda_col1.metric("Open Stock Value", f"{np.round(actual_nvda['Open'][len(actual_nvda)-1], 3)}", | |
"{}".format(np.round(actual_nvda['Open'][len(test_data_NVDA)-1] - actual_nvda['Open'][len(test_data_NVDA)-2]), 3)) | |
nvda_col2.metric("Close Stock Value", f"{np.round(actual_nvda['Close'][len(actual_nvda)-1], 3)}", | |
"{}".format(np.round(actual_nvda['Close'][len(test_data_NVDA)-1] - actual_nvda['Close'][len(test_data_NVDA)-2]), 3)) | |
nvda_col3.metric("Adjusted Close Value", f"{np.round(actual_nvda['Adj Close'][len(actual_nvda)-1], 3)}", | |
"{}".format(np.round(actual_nvda['Adj Close'][len(test_data_NVDA)-1] - actual_nvda['Adj Close'][len(test_data_NVDA)-2]), 3)) | |
def aggrid_interactive_table(df: pd.DataFrame): | |
"""Creates an st-aggrid interactive table based on a dataframe. | |
Args: | |
df (pd.DataFrame]): Source dataframe | |
Returns: | |
dict: The selected row | |
""" | |
options = GridOptionsBuilder.from_dataframe( | |
df, enableRowGroup=True, enableValue=True, enablePivot=True | |
) | |
options.configure_side_bar() | |
options.configure_selection("single") | |
selection = AgGrid( | |
df, | |
enable_enterprise_modules=True, | |
gridOptions=options.build(), | |
theme="dark", | |
update_mode=GridUpdateMode.MODEL_CHANGED, | |
allow_unsafe_jscode=True, | |
fit_columns_on_grid_load=True | |
) | |
return selection | |
google_stock = pd.DataFrame(data_GOOG.drop('Volume', axis=1)) | |
comp_name = ['Tesla', 'Google', 'NVIDIA'] | |
st.write("#### Actual and Prediction of Tesla, Google, and NVIDIA Stock Price (Scaled Data Using Min-Max Scaler) 2007 - Now") | |
stock_df = pd.DataFrame() | |
st.text('Start Time') | |
from_col1, from_col2, from_col3 = st.columns(3) | |
from_date = from_col1.slider('Date', 1, 31, 1) | |
from_month = from_col2.slider('Month', 1, 12, 1) | |
from_year = from_col3.slider('Year', 2010, 2021, 2011) | |
st.text('End Time') | |
to_col1, to_col2, to_col3 = st.columns(3) | |
to_date = to_col1.slider('Date', 1, 31, 31) | |
to_month = to_col2.slider('Month', 1, 12, 12) | |
to_year = to_col3.slider('Year', 2010, 2021, 2021) | |
stock_df['Tesla'] = pdr.DataReader(company_ticker[2], 'yahoo', | |
dt.datetime(from_year, from_month, from_date), | |
dt.datetime(to_year, to_month, to_date)).filter(['Adj Close']) | |
stock_df['Google'] = pdr.DataReader(company_ticker[3], 'yahoo', | |
dt.datetime(from_year, from_month, from_date), | |
dt.datetime(to_year, to_month, to_date)).filter(['Adj Close']) | |
stock_df['NVIDIA'] = pdr.DataReader(company_ticker[4], 'yahoo', | |
dt.datetime(from_year, from_month, from_date), | |
dt.datetime(to_year, to_month, to_date)).filter(['Adj Close']) | |
actual_df = pd.DataFrame() | |
actual_df['Tesla'] = test_data_TSLA.filter(['Adj Close']) | |
actual_df['Google'] = test_data_GOOG.filter(['Adj Close']) | |
actual_df['NVIDIA'] = test_data_NVDA.filter(['Adj Close']) | |
st.line_chart(stock_df) | |
comp_df = st.selectbox("Select Company Data", comp_name) | |
if comp_df == 'Tesla': | |
aggrid_tesla = aggrid_interactive_table(df=valid_tesla) | |
stock_col1, stock_col2 = st.columns(2) | |
fig = px.scatter( | |
x=valid_tesla["Actual"], | |
y=valid_tesla["Predictions"] | |
) | |
fig.update_layout( | |
xaxis_title="Actual Stock Price of Tesla Company", | |
yaxis_title="Predicted Value", | |
modebar_remove=["pan", "zoom", "lasso", "toimage", "zoomin", "zoomout", "autoscale", "resetviews", "select", "resetscale"] | |
) | |
stock_col1.write(f"##### Linearity of Actual and Predicted Stock Price of {comp_df} (in Billion) 2021 - Now") | |
stock_col1.write(fig) | |
stock_col2.write(f"##### Comparison Between Actual and Predicted Stock Price of {comp_df} (in Billion) 2021 - Now") | |
stock_col2.line_chart(valid_tesla) | |
if comp_df == 'Google': | |
aggrid_google = aggrid_interactive_table(df=valid_google) | |
stock_col1, stock_col2 = st.columns(2) | |
fig = px.scatter( | |
x=valid_google["Actual"], | |
y=valid_google["Predictions"] | |
) | |
fig.update_layout( | |
xaxis_title="Actual Stock Price of Tesla Company", | |
yaxis_title="Predicted Value", | |
modebar_remove=["pan", "zoom", "lasso", "toimage", "zoomin", "zoomout", "autoscale", "resetviews", "select", "resetscale"] | |
) | |
stock_col1.write(f"##### Linearity of Actual and Predicted Stock Price of {comp_df} (in Billion) 2021 - Now") | |
stock_col1.write(fig) | |
stock_col2.write(f"##### Comparison Between Actual and Predicted Stock Price of {comp_df} (in Billion) 2021 - Now") | |
stock_col2.line_chart(valid_google) | |
if comp_df == 'NVIDIA': | |
aggrid_nvidia = aggrid_interactive_table(df=valid_nvidia) | |
stock_col1, stock_col2 = st.columns(2) | |
fig = px.scatter( | |
x=valid_nvidia["Actual"], | |
y=valid_nvidia["Predictions"] | |
) | |
fig.update_layout( | |
xaxis_title="Actual Stock Price of Tesla Company", | |
yaxis_title="Predicted Value", | |
modebar_remove=["pan", "zoom", "lasso", "toimage", "zoomin", "zoomout", "autoscale", "resetviews", "select", "resetscale"] | |
) | |
stock_col1.write(f"##### Linearity of Actual and Predicted Stock Price of {comp_df} (in Billion) 2021 - Now") | |
stock_col1.write(fig) | |
stock_col2.write(f"##### Comparison Between Actual and Predicted Stock Price of {comp_df} (in Billion) 2021 - Now") | |
stock_col2.line_chart(valid_nvidia) | |
def real_data_prediction(lstm_model, model_inputs, scaler): | |
real_data = [model_inputs[len(model_inputs) - prediction_days:len(model_inputs) + 2, 0]] | |
real_data = np.array(real_data) | |
real_data = np.reshape(real_data, (real_data.shape[0], real_data.shape[1], 1)) | |
real_prediction = lstm_model.predict(real_data) | |
real_prediction = scaler.inverse_transform(real_prediction) | |
return np.round(real_prediction, 3) | |
real_predict_tesla = real_data_prediction(lstm_tsla, model_inputs_tesla, scaler_tesla)[0][0] | |
real_predict_google = real_data_prediction(lstm_goog, model_inputs_google, scaler_google)[0][0] | |
real_predict_nvidia = real_data_prediction(lstm_nvda, model_inputs_nvidia, scaler_nvidia)[0][0] | |
st.write("#### Company's Tomorrow Stock Price Prediction") | |
real_col1, real_col2, real_col3 = st.columns(3) | |
real_col1.metric("Tesla's Tomorrow Stock Price Predction", f"{real_predict_tesla}", | |
f"{np.round(real_predict_tesla - actual_tsla['Adj Close'][len(test_data_TSLA)-1], 3)}") | |
real_col2.metric("Google's Tomorrow Stock Price Predction", f"{real_predict_google}", | |
f"{np.round(real_predict_google - actual_goog['Adj Close'][len(test_data_GOOG)-1], 3)}") | |
real_col3.metric("NVIDIA's Tomorrow Stock Price Predction", f"{real_predict_nvidia}", | |
f"{np.round(real_predict_nvidia - actual_nvda['Adj Close'][len(test_data_NVDA)-1], 3)}") |