當然,我可以協助你使用 GRU(Gated Recurrent Unit)模型來預測股票收盤價。以下是一個完整的步驟,包括資料預處理、建立 GRU 模型、訓練及評估模型。假設你使用的是 Python 和 Keras(TensorFlow 後端),以下是詳細的實現步驟:
1. 匯入必要的庫
首先,請確保你已經匯入了所有必要的庫:
python Copy code
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import GRU, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
2. 讀取並檢查資料
你已經完成了資料的讀取和初步檢查。接下來,我們將進行資料的預處理。
python Copy code
# 讀取資料
file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\enhanced_stock_price_ma.csv"
data = pd.read_csv(file_path)
# 檢查資料
print(data.head())
print(data.isnull().sum())
# 選擇特徵和目標
features = ['Opening Price', 'Highest Price', 'Lowest Price', 'Closing Price','MA_5','MA_20']
target = 'Closing Price'
data = data[features]
# 處理缺失值(如果有)
data = data.dropna()
3. 特徵縮放
GRU 模型對於輸入資料的範圍較為敏感,因此建議將資料進行縮放。這裡我們使用 MinMaxScaler 將資料縮放到 [0, 1] 範圍。
python Copy code
# 特徵縮放
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
4. 建立時序資料
GRU 模型需要輸入形狀為(三維)的資料,通常為 (樣本數, 時間步長, 特徵數)。我們這裡使用過去 60 天的資料來預測下一天的收盤價。
python Copy code
def create_sequences(data, seq_length):
X = []
y = []
for i in range(seq_length, len(data)):
X.append(data[i - seq_length:i, :-1]) # 特徵
y.append(data[i, -1]) # 目標(收盤價)
return np.array(X), np.array(y)
SEQ_LENGTH = 60 # 使用過去 60 天的資料
X, y = create_sequences(scaled_data, SEQ_LENGTH)
# 分割訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
5. 建立 GRU 模型
使用 Keras 建立 GRU 模型。這裡我們使用兩層 GRU,並在每層後加入 Dropout 層以防止過度擬合。
python Copy code
# 建立 GRU 模型
model = Sequential()
# 第一層 GRU,返回序列以便堆疊多個 RNN 層
model.add(GRU(units=50, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dropout(0.2))
# 第二層 GRU
model.add(GRU(units=50, return_sequences=False))
model.add(Dropout(0.2))
# 全連接層
model.add(Dense(units=25))
model.add(Dense(units=1)) # 預測下一天的收盤價
# 編譯模型
model.compile(optimizer='adam', loss='mean_squared_error')
# 查看模型摘要
model.summary()
6. 訓練模型
使用早停法(Early Stopping)來避免過度擬合,並訓練模型。
python Copy code
# 訓練模型
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
history = model.fit(
X_train, y_train,
epochs=100,
batch_size=32,
validation_data=(X_test, y_test),
callbacks=[early_stop],
verbose=1
)
7. 評估模型
模型訓練完成後,我們可以使用測試集進行預測並評估模型表現。
python Copy code
# 預測
predictions = model.predict(X_test)
# 將預測結果轉換回原始尺度
predictions = scaler.inverse_transform(
np.concatenate((np.zeros((predictions.shape[0], scaled_data.shape[1]-1)), predictions), axis=1)
)[:, -1]
# 原始的收盤價
y_test_scaled = y_test.reshape(-1, 1)
y_test_original = scaler.inverse_transform(
np.concatenate((np.zeros((y_test_scaled.shape[0], scaled_data.shape[1]-1)), y_test_scaled), axis=1)
)[:, -1]
# 繪製結果
plt.figure(figsize=(14,5))
plt.plot(y_test_original, color='blue', label='實際收盤價')
plt.plot(predictions, color='red', label='預測收盤價')
plt.title('股票收盤價預測')
plt.xlabel('時間')
plt.ylabel('價格')
plt.legend()
plt.show()
# 計算均方誤差
mse = mean_squared_error(y_test_original, predictions)
print(f'均方誤差: {mse}')
8. 完整程式碼
將上述所有步驟結合在一起,形成完整的程式碼:
python Copy code
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import GRU, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
# 1. 讀取資料
file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\enhanced_stock_price_ma.csv"
data = pd.read_csv(file_path)
# 檢查資料
print(data.head())
print(data.isnull().sum())
# 2. 選擇特徵和目標
features = ['Opening Price', 'Highest Price', 'Lowest Price', 'Closing Price','MA_5','MA_20']
target = 'Closing Price'
data = data[features]
# 處理缺失值
data = data.dropna()
# 3. 特徵縮放
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# 4. 建立時序資料
def create_sequences(data, seq_length):
X = []
y = []
for i in range(seq_length, len(data)):
X.append(data[i - seq_length:i, :-1])
y.append(data[i, -1])
return np.array(X), np.array(y)
SEQ_LENGTH = 60
X, y = create_sequences(scaled_data, SEQ_LENGTH)
# 分割訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
# 5. 建立 GRU 模型
model = Sequential()
model.add(GRU(units=50, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dropout(0.2))
model.add(GRU(units=50, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(units=25))
model.add(Dense(units=1))
# 編譯模型
model.compile(optimizer='adam', loss='mean_squared_error')
# 查看模型摘要
model.summary()
# 6. 訓練模型
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
history = model.fit(
X_train, y_train,
epochs=100,
batch_size=32,
validation_data=(X_test, y_test),
callbacks=[early_stop],
verbose=1
)
# 7. 評估模型
# 預測
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(
np.concatenate((np.zeros((predictions.shape[0], scaled_data.shape[1]-1)), predictions), axis=1)
)[:, -1]
# 原始的收盤價
y_test_scaled = y_test.reshape(-1, 1)
y_test_original = scaler.inverse_transform(
np.concatenate((np.zeros((y_test_scaled.shape[0], scaled_data.shape[1]-1)), y_test_scaled), axis=1)
)[:, -1]
# 繪製結果
plt.figure(figsize=(14,5))
plt.plot(y_test_original, color='blue', label='實際收盤價')
plt.plot(predictions, color='red', label='預測收盤價')
plt.title('股票收盤價預測')
plt.xlabel('時間')
plt.ylabel('價格')
plt.legend()
plt.show()
# 計算均方誤差
mse = mean_squared_error(y_test_original, predictions)
print(f'均方誤差: {mse}')
補充說明
時間步長(SEQ_LENGTH) : 使用過去多少天的資料來預測下一天的收盤價。這個參數可以根據資料特性調整。
模型參數調整 : 你可以調整 GRU 層的單元數(units)、Dropout 比例、Dense 層的結構等,以優化模型性能。
評估指標 : 除了均方誤差(MSE),還可以考慮使用均方根誤差(RMSE)、平均絕對誤差(MAE)等。
特徵選擇 : 根據資料的特性,可以嘗試加入更多的技術指標或外部因素來提升模型的預測能力。
超參數優化 : 使用如 Grid Search 或其他方法來尋找最佳的超參數組合。
希望這些步驟能夠幫助你順利建立並訓練 GRU 模型來預測股票收盤價。如果有任何疑問或需要進一步的協助,請隨時提問!