Spaces:
Sleeping
Sleeping
| import pandas as pd | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| from sklearn.preprocessing import MinMaxScaler | |
| from sklearn.metrics import mean_squared_error | |
| from tensorflow.keras.models import Sequential | |
| from tensorflow.keras.layers import Dense, LSTM | |
| import tensorflow as tf | |
| import streamlit as st | |
| def predict_stock(csv_file): | |
| # Load and preprocess data | |
| dataset = pd.read_csv(csv_file, usecols=[1], engine='python', encoding="big5") | |
| dataset = dataset.values.astype('float32') | |
| # Normalize the dataset | |
| scaler = MinMaxScaler(feature_range=(0, 1)) | |
| dataset = scaler.fit_transform(dataset) | |
| # Split into train and test sets | |
| train_size = int(len(dataset) * 0.8) | |
| train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:] | |
| # Create dataset function | |
| def create_dataset(dataset, look_back=1): | |
| dataX, dataY = [], [] | |
| for i in range(len(dataset)-look_back-1): | |
| a = dataset[i:(i+look_back), 0] | |
| dataX.append(a) | |
| dataY.append(dataset[i + look_back, 0]) | |
| return np.array(dataX), np.array(dataY) | |
| # Prepare data for LSTM | |
| look_back = 1 | |
| trainX, trainY = create_dataset(train, look_back) | |
| testX, testY = create_dataset(test, look_back) | |
| trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1])) | |
| testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1])) | |
| # Create and fit the LSTM network | |
| model = Sequential() | |
| model.add(LSTM(4, input_shape=(1, look_back))) | |
| model.add(Dense(1)) | |
| model.compile(loss='mean_squared_error', optimizer='adam') | |
| model.fit(trainX, trainY, epochs=50, batch_size=1, verbose=0) | |
| # Make predictions | |
| trainPredict = model.predict(trainX) | |
| testPredict = model.predict(testX) | |
| # Invert predictions | |
| trainPredict = scaler.inverse_transform(trainPredict) | |
| trainY = scaler.inverse_transform([trainY]) | |
| testPredict = scaler.inverse_transform(testPredict) | |
| testY = scaler.inverse_transform([testY]) | |
| # Calculate RMSE | |
| trainScore = np.sqrt(mean_squared_error(trainY[0], trainPredict[:,0])) | |
| testScore = np.sqrt(mean_squared_error(testY[0], testPredict[:,0])) | |
| # Prepare plot data | |
| trainPredictPlot = np.empty_like(dataset) | |
| trainPredictPlot[:, :] = np.nan | |
| trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict | |
| testPredictPlot = np.empty_like(dataset) | |
| testPredictPlot[:, :] = np.nan | |
| testPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict | |
| # Create plot | |
| fig, ax = plt.subplots(figsize=(12, 8)) | |
| ax.plot(scaler.inverse_transform(dataset), label='Original Data', color='blue') | |
| ax.plot(trainPredictPlot, label='Training Predictions', linestyle='--', color='green') | |
| ax.plot(testPredictPlot, label='Test Predictions', linestyle='--', color='red') | |
| ax.set_xlabel('Time') | |
| ax.set_ylabel('Stock Price') | |
| ax.set_title('Stock Price Prediction') | |
| ax.legend() | |
| ax.grid(True, linestyle='--', alpha=0.7) | |
| return fig, trainScore, testScore | |
| # Streamlit UI | |
| st.set_page_config(page_title="Stock Price Prediction with LSTM", layout="wide") | |
| st.title("Stock Price Prediction with LSTM") | |
| st.write("Upload the 2330TW.csv file to predict stock prices using LSTM.") | |
| uploaded_file = st.file_uploader("Choose a CSV file", type="csv") | |
| if uploaded_file is not None: | |
| with st.spinner('Predicting...'): | |
| fig, train_score, test_score = predict_stock(uploaded_file) | |
| st.pyplot(fig) | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.metric("Train Score (RMSE)", f"{train_score:.2f}") | |
| with col2: | |
| st.metric("Test Score (RMSE)", f"{test_score:.2f}") | |
| st.markdown("---") | |
| st.write("Created with ❤️ using Streamlit") |