imtherealbatman/programming_space
0
1import streamlit as st2import pandas as pd3import numpy as np4import yfinance as yf5import matplotlib.pyplot as plt6import tensorflow as tf7from tensorflow.keras.models import Sequential8from tensorflow.keras.layers import LSTM, Dense, Dropout9from sklearn.preprocessing import MinMaxScaler10 11# Streamlit App Title12st.title("๐ Stock Price Prediction App (LSTM Model)")13 14# Sidebar Inputs15st.sidebar.header("Stock Selection")16ticker = st.sidebar.text_input("Enter Stock Ticker (e.g., AAPL, TSLA, GOOGL)", value="AAPL").upper()17days_to_predict = st.sidebar.slider("Prediction Period (Days)", min_value=5, max_value=60, value=30, step=5)18 19# Load Stock Data20@st.cache_data21def load_data(ticker):22 stock_data = yf.download(ticker, period="5y")23 return stock_data24 25if ticker:26 try:27 df = load_data(ticker)28 29 if df.empty:30 st.error("Invalid Stock Ticker or No Data Available.")31 else:32 # Display Stock Data Overview33 st.write(f"### {ticker} Stock Data Overview")34 st.write(df.tail())35 36 # Plot Historical Stock Prices37 st.write("### ๐ Historical Stock Prices")38 fig, ax = plt.subplots()39 ax.plot(df.index, df['Close'], label='Closing Price', color='blue')40 ax.set_xlabel("Date")41 ax.set_ylabel("Price (USD)")42 ax.legend()43 st.pyplot(fig)44 45 # Prepare Data for LSTM46 scaler = MinMaxScaler(feature_range=(0, 1))47 df_scaled = scaler.fit_transform(df[['Close']])48 49 # Create Sequences for LSTM50 def create_sequences(data, seq_length):51 X, y = [], []52 for i in range(len(data) - seq_length - 1):53 X.append(data[i:i+seq_length])54 y.append(data[i+seq_length])55 return np.array(X), np.array(y)56 57 seq_length = 60 # Use last 60 days to predict the next58 X_train, y_train = create_sequences(df_scaled, seq_length)59 60 # Reshape Data for LSTM61 X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))62 63 # Build LSTM Model64 model = Sequential([65 LSTM(50, return_sequences=True, input_shape=(seq_length, 1)),66 Dropout(0.2),67 LSTM(50, return_sequences=False),68 Dropout(0.2),69 Dense(25),70 Dense(1)71 ])72 73 # Compile the Model74 model.compile(optimizer='adam', loss='mean_squared_error')75 76 # Train the Model (Use limited epochs for quick training)77 model.fit(X_train, y_train, epochs=5, batch_size=16, verbose=1)78 79 # Predict Future Prices80 last_days = df_scaled[-seq_length:] # Get last 60 days81 future_preds = []82 83 for _ in range(days_to_predict):84 input_seq = np.reshape(last_days, (1, seq_length, 1))85 predicted_price = model.predict(input_seq)[0, 0]86 future_preds.append(predicted_price)87 last_days = np.append(last_days[1:], predicted_price).reshape(-1, 1)88 89 # Convert Predictions Back to Original Scale90 future_preds = scaler.inverse_transform(np.array(future_preds).reshape(-1, 1))91 92 # Plot Prediction93 st.write("### ๐ฎ Stock Price Prediction for Next {} Days".format(days_to_predict))94 future_dates = pd.date_range(df.index[-1], periods=days_to_predict + 1)[1:]95 96 fig2, ax2 = plt.subplots()97 ax2.plot(df.index[-100:], df['Close'].values[-100:], label='Historical Price', color='blue')98 ax2.plot(future_dates, future_preds, label='Predicted Price', color='red', linestyle='dashed')99 ax2.set_xlabel("Date")100 ax2.set_ylabel("Price (USD)")101 ax2.legend()102 st.pyplot(fig2)103 104 except Exception as e:105 st.error(f"Error: {str(e)}")106 107 