Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 5 |
+
from sklearn.metrics import mean_squared_error
|
| 6 |
+
from tensorflow.keras.models import Sequential
|
| 7 |
+
from tensorflow.keras.layers import Dense, LSTM
|
| 8 |
+
import tensorflow as tf
|
| 9 |
+
import streamlit as st
|
| 10 |
+
|
| 11 |
+
def predict_stock(csv_file):
|
| 12 |
+
# Load and preprocess data
|
| 13 |
+
dataset = pd.read_csv(csv_file, usecols=[1], engine='python', encoding="big5")
|
| 14 |
+
dataset = dataset.values.astype('float32')
|
| 15 |
+
|
| 16 |
+
# Normalize the dataset
|
| 17 |
+
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 18 |
+
dataset = scaler.fit_transform(dataset)
|
| 19 |
+
|
| 20 |
+
# Split into train and test sets
|
| 21 |
+
train_size = int(len(dataset) * 0.8)
|
| 22 |
+
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
|
| 23 |
+
|
| 24 |
+
# Create dataset function
|
| 25 |
+
def create_dataset(dataset, look_back=1):
|
| 26 |
+
dataX, dataY = [], []
|
| 27 |
+
for i in range(len(dataset)-look_back-1):
|
| 28 |
+
a = dataset[i:(i+look_back), 0]
|
| 29 |
+
dataX.append(a)
|
| 30 |
+
dataY.append(dataset[i + look_back, 0])
|
| 31 |
+
return np.array(dataX), np.array(dataY)
|
| 32 |
+
|
| 33 |
+
# Prepare data for LSTM
|
| 34 |
+
look_back = 1
|
| 35 |
+
trainX, trainY = create_dataset(train, look_back)
|
| 36 |
+
testX, testY = create_dataset(test, look_back)
|
| 37 |
+
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
|
| 38 |
+
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
|
| 39 |
+
|
| 40 |
+
# Create and fit the LSTM network
|
| 41 |
+
model = Sequential()
|
| 42 |
+
model.add(LSTM(4, input_shape=(1, look_back)))
|
| 43 |
+
model.add(Dense(1))
|
| 44 |
+
model.compile(loss='mean_squared_error', optimizer='adam')
|
| 45 |
+
model.fit(trainX, trainY, epochs=50, batch_size=1, verbose=0)
|
| 46 |
+
|
| 47 |
+
# Make predictions
|
| 48 |
+
trainPredict = model.predict(trainX)
|
| 49 |
+
testPredict = model.predict(testX)
|
| 50 |
+
|
| 51 |
+
# Invert predictions
|
| 52 |
+
trainPredict = scaler.inverse_transform(trainPredict)
|
| 53 |
+
trainY = scaler.inverse_transform([trainY])
|
| 54 |
+
testPredict = scaler.inverse_transform(testPredict)
|
| 55 |
+
testY = scaler.inverse_transform([testY])
|
| 56 |
+
|
| 57 |
+
# Calculate RMSE
|
| 58 |
+
trainScore = np.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
|
| 59 |
+
testScore = np.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
|
| 60 |
+
|
| 61 |
+
# Prepare plot data
|
| 62 |
+
trainPredictPlot = np.empty_like(dataset)
|
| 63 |
+
trainPredictPlot[:, :] = np.nan
|
| 64 |
+
trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict
|
| 65 |
+
testPredictPlot = np.empty_like(dataset)
|
| 66 |
+
testPredictPlot[:, :] = np.nan
|
| 67 |
+
testPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict
|
| 68 |
+
|
| 69 |
+
# Create plot
|
| 70 |
+
fig, ax = plt.subplots(figsize=(12, 8))
|
| 71 |
+
ax.plot(scaler.inverse_transform(dataset), label='Original Data', color='blue')
|
| 72 |
+
ax.plot(trainPredictPlot, label='Training Predictions', linestyle='--', color='green')
|
| 73 |
+
ax.plot(testPredictPlot, label='Test Predictions', linestyle='--', color='red')
|
| 74 |
+
ax.set_xlabel('Time')
|
| 75 |
+
ax.set_ylabel('Stock Price')
|
| 76 |
+
ax.set_title('Stock Price Prediction')
|
| 77 |
+
ax.legend()
|
| 78 |
+
ax.grid(True, linestyle='--', alpha=0.7)
|
| 79 |
+
|
| 80 |
+
return fig, trainScore, testScore
|
| 81 |
+
|
| 82 |
+
# Streamlit UI
|
| 83 |
+
st.set_page_config(page_title="Stock Price Prediction with LSTM", layout="wide")
|
| 84 |
+
|
| 85 |
+
st.title("Stock Price Prediction with LSTM")
|
| 86 |
+
st.write("Upload the 2330TW.csv file to predict stock prices using LSTM.")
|
| 87 |
+
|
| 88 |
+
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
|
| 89 |
+
|
| 90 |
+
if uploaded_file is not None:
|
| 91 |
+
with st.spinner('Predicting...'):
|
| 92 |
+
fig, train_score, test_score = predict_stock(uploaded_file)
|
| 93 |
+
|
| 94 |
+
st.pyplot(fig)
|
| 95 |
+
|
| 96 |
+
col1, col2 = st.columns(2)
|
| 97 |
+
with col1:
|
| 98 |
+
st.metric("Train Score (RMSE)", f"{train_score:.2f}")
|
| 99 |
+
with col2:
|
| 100 |
+
st.metric("Test Score (RMSE)", f"{test_score:.2f}")
|
| 101 |
+
|
| 102 |
+
st.markdown("---")
|
| 103 |
+
st.write("Created with ❤️ using Streamlit")
|