import streamlit as st import yfinance as yf # Set the page layout st.set_page_config(layout="wide") import matplotlib.pyplot as plt import numpy as np import base64 import pandas as pd import time from keras.models import load_model from sklearn.preprocessing import MinMaxScaler if "framework" not in st.session_state: st.session_state.framework = "gen" # Initialize state if "show_modal" not in st.session_state: st.session_state.show_modal = False if "show_overlay" not in st.session_state: st.session_state.show_overlay = False if "model" not in st.session_state: st.session_state.model = "best_bilstm_model.h5" # Loading model @st.cache_resource def load_lstm_model(path): return load_model(path) @st.cache_resource def load_data(): data = yf.download("AMZN", period="4y", multi_level_index=False) data.reset_index(inplace=True) return data ################################################################################################# def predict_future_prices( df: pd.DataFrame, n_future_days: int, model_path: str = st.session_state.model ) -> tuple[plt.Figure, pd.DataFrame]: # Ensure DataFrame is sorted and clean df = df.sort_values("Date").dropna(subset=["Close"]) df = df.reset_index(drop=True) # Scale data scaler = MinMaxScaler() prices = df["Close"].values.reshape(-1, 1) scaled_prices = scaler.fit_transform(prices) # Load model and get timesteps model = load_lstm_model(model_path) n_steps = model.input_shape[1] # --- Calculate validation error (historical residuals) --- X_hist, y_hist = [], [] for i in range(n_steps, len(scaled_prices)): X_hist.append(scaled_prices[i - n_steps : i]) y_hist.append(scaled_prices[i]) X_hist = np.array(X_hist) y_hist = np.array(y_hist) # Predict historical values hist_predictions = model.predict(X_hist, verbose=0) # Calculate residuals (error) hist_prices_rescaled = scaler.inverse_transform(y_hist.reshape(-1, 1)).flatten() hist_preds_rescaled = scaler.inverse_transform( hist_predictions.reshape(-1, 1) ).flatten() residuals = hist_prices_rescaled - hist_preds_rescaled error_std = np.std(residuals) # Key metric for confidence interval # --- Predict future values --- last_sequence = scaled_prices[-n_steps:] predicted = [] current_sequence = last_sequence.copy() for _ in range(n_future_days): pred = model.predict(current_sequence.reshape(1, n_steps, 1), verbose=0) predicted.append(pred[0, 0]) current_sequence = np.append(current_sequence[1:], [[pred[0, 0]]], axis=0) # Rescale predictions predicted_prices = scaler.inverse_transform( np.array(predicted).reshape(-1, 1) ).flatten() future_dates = pd.date_range( df["Date"].iloc[-1] + pd.Timedelta(days=1), periods=n_future_days ) prediction_df = pd.DataFrame( {"Date": future_dates, "Predicted Price": predicted_prices} ) # --- Plotting with confidence interval --- plt.rcParams["font.family"] = "Times New Roman " fig, ax = plt.subplots(figsize=(10, 6), facecolor="none") ax.patch.set_alpha(0) fig.patch.set_alpha(0) # Historical data ax.plot(df["Date"], df["Close"], label="Historical", color="cyan", linewidth=2) # Confidence interval (expanding uncertainty) days = np.arange(1, n_future_days + 1) expanding_std = error_std * np.sqrt(days) upper = predicted_prices + 1.96 * expanding_std # 95% CI lower = predicted_prices - 1.96 * expanding_std ax.fill_between( prediction_df["Date"], lower, upper, color="lightblue", alpha=0.3, label="95% Confidence Interval", ) # Predicted points (magenta dots) ax.plot( prediction_df["Date"], prediction_df["Predicted Price"], label=f"Next {n_future_days} Days Forecast", color="magenta", linestyle="None", marker=".", markersize=5, ) # ---- NEW: Trend line spanning historical + forecasted data ---- # Combine historical and predicted dates/prices all_dates = np.concatenate([df["Date"].values, prediction_df["Date"].values]) all_prices = np.concatenate( [df["Close"].values, prediction_df["Predicted Price"].values] ) # Calculate rolling mean (smoothing) window_size = 30 # Adjust based on your data frequency trend_line = pd.Series(all_prices).rolling(window=window_size, min_periods=1).mean() # Plot the trend line (blue dashed) ax.plot( all_dates, trend_line, color="blue", linestyle="--", linewidth=1.5, label="Long-Term Trend", ) # Style ax.set_title( f"📈 Stock Price Forecast ({st.session_state.model})", fontsize=14, fontweight="bold", ) ax.set_xlabel("Date", fontsize=12) ax.set_ylabel("Price", fontsize=12) ax.legend(loc="upper left") ax.grid(True, linestyle="--", alpha=0.6) return fig, prediction_df ##################################################################################################### # Function to load data # Load the data # data = load_data() # import matplotlib.pyplot as plt # Path to your logo image encoded_logo = "tensorflow.png" main_bg_ext = "png" main_bg = "Picture3.png" if st.session_state.framework == "lstm": bg_color = "#FF5733" # For example, a warm red/orange bg_color_iv = "orange" # For example, a warm red/orange text_h1 = "BI-DIRECTIONAL" text_i = "Long short term memory" model = "TENSORFLOW" st.session_state.model = "best_bilstm_model.h5" if st.session_state.framework == "gru": bg_color = "#FF5733" # For example, a warm red/orange bg_color_iv = "orange" # For example, a warm red/orange text_h1 = "GATED RECURRENT UNIT" text_i = "Recurrent Neural Network" model = "TENSORFLOW" st.session_state.model = "best_gru_model.h5" if st.session_state.framework == "gen": bg_color = "#FF5733" # For example, a warm red/orange bg_color_iv = "orange" # For example, a warm red/orange text_h1 = "Amazon Stock Predictor" text_i = "21 Days Ahead of the Market" model = "TENSORFLOW" st.markdown( f""" """, unsafe_allow_html=True, ) # Overlay container st.markdown( f""" """, unsafe_allow_html=True, ) if st.session_state.show_overlay: with st.container(key="logo-text-containers"): if st.button("✕", key="close-btn"): st.session_state.show_overlay = False st.session_state.framework = "gen" st.rerun() with st.spinner("Downloading and processing the Data..."): progress_bar = st.progress(0) for i in range(1, 11): time.sleep(0.6) progress_bar.progress(i * 10) with st.container(key="content"): days = st.slider( "Amazon Stock Insight: Predictive Analytics Over 21 Days", 1, 21, 7, key="days_slider", ) col1, col2 = st.columns([2.5, 3]) data = load_data() if data is not None and not data.empty: fig, future_data = predict_future_prices( data, days+1, st.session_state.model ) with col1: with st.container(key="col1"): future_data["Date"] = future_data["Date"].dt.strftime("%Y-%m-%d") future_data = future_data[1:] styled_html = ( future_data.style.set_table_attributes('class="glass-table"') .set_table_styles( [ { "selector": "th", "props": [ ("padding", "12px"), ("color", "#000"), ( "background-color", "rgba(255, 255, 255, 0.15)", ), ], }, { "selector": "td", "props": [ ("padding", "10px"), ("color", "#000"), ("border-bottom", "1px solid rgba(0,0,0,0.1)"), ], }, { "selector": "table", "props": [ ("width", "100%"), ("border-collapse", "collapse"), ], }, ] ) .to_html() ) # Glassmorphism CSS + vertical scroll + black text glass_css = """ """ st.markdown(glass_css, unsafe_allow_html=True) st.markdown( f"""
{styled_html}
""", unsafe_allow_html=True, ) with col2: with st.container(key="divider-col"): st.pyplot(fig) else: st.error("No data loaded. Please check your internet connection.") # Show overlay if triggered st.markdown( f"""
Uploaded Image

{text_h1}

{ text_i}
""", unsafe_allow_html=True, ) st.markdown( f"""
Uploaded Image


ACTIONS
TREND ANALYTICS

A deep learning-powered tool that analyzes Amazon's stock trends.
the models(BI-Direcional Lstm and GRU) predicts future market
actions based on past trends, providing a confidence score to
help users interpret the data more accurately and take timely actions.
""", unsafe_allow_html=True, ) with st.container(): col1, col2 = st.columns([1.5, 10.5]) with col1: if st.button(" BIDIR-LSTM"): st.session_state.framework = "lstm" st.session_state.show_overlay = True st.rerun() with col2: if st.button("GRU"): st.session_state.framework = "gru" st.session_state.show_overlay = True st.rerun()