Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
import matplotlib.pyplot as plt
|
|
@@ -8,6 +8,13 @@ from sklearn.preprocessing import MinMaxScaler
|
|
| 8 |
from sklearn.metrics import mean_squared_error
|
| 9 |
import tensorflow as tf
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
def create_dataset(dataset, look_back=1):
|
| 12 |
dataX, dataY = [], []
|
| 13 |
for i in range(len(dataset)-look_back-1):
|
|
@@ -17,48 +24,48 @@ def create_dataset(dataset, look_back=1):
|
|
| 17 |
return np.array(dataX), np.array(dataY)
|
| 18 |
|
| 19 |
def train_and_predict(file):
|
| 20 |
-
#
|
| 21 |
-
dataframe = pd.read_csv(file
|
| 22 |
dataset = dataframe.values.astype('float32')
|
| 23 |
|
| 24 |
-
#
|
| 25 |
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 26 |
dataset = scaler.fit_transform(dataset)
|
| 27 |
|
| 28 |
-
#
|
| 29 |
train_size = int(len(dataset) * 0.67)
|
| 30 |
test_size = len(dataset) - train_size
|
| 31 |
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
|
| 32 |
|
| 33 |
-
#
|
| 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 |
-
#
|
| 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 |
-
#
|
| 48 |
trainPredict = model.predict(trainX)
|
| 49 |
testPredict = model.predict(testX)
|
| 50 |
|
| 51 |
-
#
|
| 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 |
-
#
|
| 58 |
trainScore = np.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
|
| 59 |
testScore = np.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
|
| 60 |
|
| 61 |
-
#
|
| 62 |
trainPredictPlot = np.empty_like(dataset)
|
| 63 |
trainPredictPlot[:, :] = np.nan
|
| 64 |
trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict
|
|
@@ -66,31 +73,48 @@ def train_and_predict(file):
|
|
| 66 |
testPredictPlot[:, :] = np.nan
|
| 67 |
testPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
outputs=[
|
| 87 |
-
gr.Plot(label="Predictions Plot"),
|
| 88 |
-
gr.Textbox(label="Train Score"),
|
| 89 |
-
gr.Textbox(label="Test Score")
|
| 90 |
-
],
|
| 91 |
-
title="LSTM Stock Price Prediction",
|
| 92 |
-
description="Upload a CSV file with stock prices to train an LSTM model and see predictions."
|
| 93 |
-
)
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
import matplotlib.pyplot as plt
|
|
|
|
| 8 |
from sklearn.metrics import mean_squared_error
|
| 9 |
import tensorflow as tf
|
| 10 |
|
| 11 |
+
# 設置頁面配置
|
| 12 |
+
st.set_page_config(page_title="LSTM Stock Price Prediction", layout="wide")
|
| 13 |
+
|
| 14 |
+
# 標題
|
| 15 |
+
st.title("LSTM Stock Price Prediction")
|
| 16 |
+
|
| 17 |
+
# 函數定義
|
| 18 |
def create_dataset(dataset, look_back=1):
|
| 19 |
dataX, dataY = [], []
|
| 20 |
for i in range(len(dataset)-look_back-1):
|
|
|
|
| 24 |
return np.array(dataX), np.array(dataY)
|
| 25 |
|
| 26 |
def train_and_predict(file):
|
| 27 |
+
# 載入和預處理數據
|
| 28 |
+
dataframe = pd.read_csv(file, usecols=[1], engine='python', encoding="big5")
|
| 29 |
dataset = dataframe.values.astype('float32')
|
| 30 |
|
| 31 |
+
# 正規化數據集
|
| 32 |
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 33 |
dataset = scaler.fit_transform(dataset)
|
| 34 |
|
| 35 |
+
# 分割訓練集和測試集
|
| 36 |
train_size = int(len(dataset) * 0.67)
|
| 37 |
test_size = len(dataset) - train_size
|
| 38 |
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
|
| 39 |
|
| 40 |
+
# 重塑為 X=t 和 Y=t+1
|
| 41 |
look_back = 1
|
| 42 |
trainX, trainY = create_dataset(train, look_back)
|
| 43 |
testX, testY = create_dataset(test, look_back)
|
| 44 |
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
|
| 45 |
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
|
| 46 |
|
| 47 |
+
# 創建和訓練 LSTM 網絡
|
| 48 |
model = Sequential()
|
| 49 |
model.add(LSTM(4, input_shape=(1, look_back)))
|
| 50 |
model.add(Dense(1))
|
| 51 |
model.compile(loss='mean_squared_error', optimizer='adam')
|
| 52 |
model.fit(trainX, trainY, epochs=50, batch_size=1, verbose=0)
|
| 53 |
|
| 54 |
+
# 進行預測
|
| 55 |
trainPredict = model.predict(trainX)
|
| 56 |
testPredict = model.predict(testX)
|
| 57 |
|
| 58 |
+
# 反轉預測
|
| 59 |
trainPredict = scaler.inverse_transform(trainPredict)
|
| 60 |
trainY = scaler.inverse_transform([trainY])
|
| 61 |
testPredict = scaler.inverse_transform(testPredict)
|
| 62 |
testY = scaler.inverse_transform([testY])
|
| 63 |
|
| 64 |
+
# 計算 RMSE
|
| 65 |
trainScore = np.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
|
| 66 |
testScore = np.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
|
| 67 |
|
| 68 |
+
# 準備繪圖數據
|
| 69 |
trainPredictPlot = np.empty_like(dataset)
|
| 70 |
trainPredictPlot[:, :] = np.nan
|
| 71 |
trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict
|
|
|
|
| 73 |
testPredictPlot[:, :] = np.nan
|
| 74 |
testPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict
|
| 75 |
|
| 76 |
+
return scaler.inverse_transform(dataset), trainPredictPlot, testPredictPlot, trainScore, testScore
|
| 77 |
+
|
| 78 |
+
# 文件上傳
|
| 79 |
+
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
|
| 80 |
+
|
| 81 |
+
if uploaded_file is not None:
|
| 82 |
+
# 讀取文件並進行預測
|
| 83 |
+
original_data, train_predict, test_predict, train_score, test_score = train_and_predict(uploaded_file)
|
| 84 |
+
|
| 85 |
+
# 顯示結果
|
| 86 |
+
st.subheader("Prediction Results")
|
| 87 |
+
|
| 88 |
+
# 繪製圖表
|
| 89 |
+
fig, ax = plt.subplots(figsize=(12, 6))
|
| 90 |
+
ax.plot(original_data, label='Original Data', color='blue')
|
| 91 |
+
ax.plot(train_predict, label='Training Predictions', linestyle='--', color='green')
|
| 92 |
+
ax.plot(test_predict, label='Test Predictions', linestyle='--', color='red')
|
| 93 |
+
ax.set_xlabel('Time')
|
| 94 |
+
ax.set_ylabel('Stock Price')
|
| 95 |
+
ax.set_title('Original Data and Predictions')
|
| 96 |
+
ax.legend()
|
| 97 |
+
ax.grid(True, linestyle='--', alpha=0.7)
|
| 98 |
+
st.pyplot(fig)
|
| 99 |
|
| 100 |
+
# 顯示評分
|
| 101 |
+
col1, col2 = st.columns(2)
|
| 102 |
+
with col1:
|
| 103 |
+
st.metric("Train Score (RMSE)", f"{train_score:.2f}")
|
| 104 |
+
with col2:
|
| 105 |
+
st.metric("Test Score (RMSE)", f"{test_score:.2f}")
|
| 106 |
+
|
| 107 |
+
else:
|
| 108 |
+
st.info("Please upload a CSV file to start the prediction.")
|
| 109 |
+
|
| 110 |
+
# 添加一些說明文字
|
| 111 |
+
st.markdown("""
|
| 112 |
+
This application uses an LSTM (Long Short-Term Memory) neural network to predict stock prices based on historical data.
|
| 113 |
|
| 114 |
+
To use:
|
| 115 |
+
1. Upload a CSV file containing historical stock price data.
|
| 116 |
+
2. The app will train an LSTM model on this data and make predictions.
|
| 117 |
+
3. You'll see a graph showing the original data and predictions, along with RMSE scores for training and test sets.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
Note: The CSV file should have the stock prices in the second column.
|
| 120 |
+
""")
|