使用 Python 的 LSTM 进行股市预测
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM, Dense
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
# 示例股票价格数据
def load_data(filename):
with open(filename, 'r') as f:
data = f.read()
all_data = data.split('\n')
stock_data = np.array(all_data).astype(np.float)
return stock_data
# 将数据转换为LSTM模型需要的形状
def prepare_data(stock_data, seq_length, normalize_window=True):
X, y = [], []
for i in range(len(stock_data) - seq_length):
X.append(stock_data[i:i + seq_length])
y.append(stock_data[i + seq_length])
X = np.array(X).reshape((X.shape[0], seq_length, 1))
y = np.array(y).reshape((y.shape[0], 1))
if normalize_window:
scaler = MinMaxScaler(feature_range=(0, 1))
X_scaled = scaler.fit_transform(X.reshape((X.shape[0], X.shape[2])))
X = X_scaled.reshape((X.shape[0], X.shape[1], X.shape[2]))
return X, y
# 模型训练和评估函数
def train_and_evaluate_model(X_train, y_train, X_test, y_test, seq_length, n_features, batch_size, epochs):
model = Sequential()
model.add(LSTM(50, input_shape=(seq_length, n_features)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, verbose=2)
# 评估模型
_, ax = plt.subplots(figsize=(12, 4))
test_predict = model.predict(X_test)
ax.plot(test_predict, color='blue', label='Prediction')
ax.plot(y_test, color='red', label='Real Value')
ax.legend(loc='upper left')
ax.set_xlabel('Time')
ax.set_ylabel('Stock Price')
ax.set_title('Model Prediction vs. Real Stock Price')
plt.show()
# 计算平均平方误差
mse = mean_squared_error(y_test, test_predict)
return mse
# 示例使用
seq_length = 30 # 序列长度
batch_size = 1 # 批量大小
epochs = 500 # 训练轮数
n_features = 1 # 特征数量(单变量数据)
# 加载数据
stock_data = load_data('stock_data.txt')
# 准备数据
X_train, y_train = prepare_data(stock_data[:580], seq_length, normalize_window=True)
X_test, y_test = prepare_data(stock_data[580:], seq_length, normalize_window=True)
# 训练和评估模型
mse = train_and_evaluate_model(X_train, y_train, X_test, y_test, seq_length, n_features, batch_size, epochs)
print(f"Mean Squared Error: {mse}")
这段代码展示了如何加载股票价格数据,将其转换
评论已关闭