sidcww commited on
Commit
6ad1010
·
verified ·
1 Parent(s): d68c696

Create app.py

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