python
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Bidirectional, LSTM, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping
# 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. 定義時間步長(序列長度)
TIME_STEPS = 60 # 例如,使用過去60天的數據來預測下一天
# 5. 構建序列數據
def create_sequences(data, time_steps):
X = []
y = []
for i in range(time_steps, len(data)):
X.append(data[i-time_steps:i])
y.append(data[i, 3]) # 'Closing Price' 的索引是假設為3,根據實際調整
return np.array(X), np.array(y)
X, y = create_sequences(scaled_data, TIME_STEPS)
# 6. 拆分訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, shuffle=False
)
print(f"訓練集大小: {X_train.shape}")
print(f"測試集大小: {X_test.shape}")
# 7. 建立 BiLSTM 模型
model = Sequential()
# 第一層 BiLSTM
model.add(Bidirectional(LSTM(units=50, return_sequences=True), input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dropout(0.2))
# 第二層 BiLSTM
model.add(Bidirectional(LSTM(units=50, return_sequences=False)))
model.add(Dropout(0.2))
# 全連接層
model.add(Dense(units=25))
model.add(Dense(units=1)) # 輸出層
# 8. 編譯模型
model.compile(
optimizer='adam',
loss='mean_squared_error',
metrics=[tf.keras.metrics.MeanAbsolutePercentageError(name='mape')]
)
model.summary()
# 9. 設置早停
early_stop = EarlyStopping(
monitor='val_loss',
patience=10,
restore_best_weights=True
)
# 10. 訓練模型
history = model.fit(
X_train,
y_train,
epochs=100,
batch_size=32,
validation_data=(X_test, y_test),
callbacks=[early_stop],
verbose=1
)
# 11. 評估模型
loss, mape = model.evaluate(X_test, y_test, verbose=0)
print(f"測試集 - 損失: {loss:.4f}, MAPE: {mape:.4f}")
# 12. 預測並反縮放
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(np.concatenate((X_test[:, -1, :-1], predictions), axis=1))[:, -1]
actual = scaler.inverse_transform(np.concatenate((X_test[:, -1, :-1], y_test.reshape(-1,1)), axis=1))[:, -1]
# 13. 繪製結果
import matplotlib.pyplot as plt
plt.figure(figsize=(14,5))
plt.plot(actual, color='blue', label='實際收盤價')
plt.plot(predictions, color='red', label='預測收盤價')
plt.title('股票收盤價預測')
plt.xlabel('時間')
plt.ylabel('價格')
plt.legend()
plt.show()