基于LSTM的股票未来60天预测异常问题求助
股票未来60天价格预测问题解决指南
问题诊断
当前代码仅完成了历史验证区间的价格拟合,未实现未来时序的迭代预测逻辑;同时训练轮次仅1轮,模型拟合程度极低,导致预测效果差。要实现2024年6月后的股价预测,需补充未来预测的核心循环逻辑,并优化模型训练流程。
解决方案步骤
1. 优化模型训练,提升拟合效果
增加训练轮次,加入早停和模型保存回调,避免过拟合同时保证模型收敛:
# 替换原训练代码部分 checkpoint = ModelCheckpoint('best_model.h5', monitor='loss', save_best_only=True) early_stop = EarlyStopping(monitor='loss', patience=5, restore_best_weights=True) model.fit(x_train, y_train, batch_size=32, epochs=20, callbacks=[checkpoint, early_stop])
2. 实现未来60天预测的核心逻辑
基于最新的60天历史数据,迭代预测每一天的价格,并将预测值作为下一天的输入特征,循环生成未来60天的预测结果:
# 获取最新60天的缩放后数据 last_60_days = scaled_data[-60:] future_predictions = [] for _ in range(60): # 重塑数据为模型输入格式 X_pred = last_60_days.reshape(1, 60, 1) # 预测当日价格 pred_price = model.predict(X_pred, verbose=0) # 将预测值加入列表 future_predictions.append(pred_price[0][0]) # 更新last_60_days,移除最早一天,加入最新预测值 last_60_days = np.append(last_60_days[1:], pred_price, axis=0) # 反缩放,还原真实价格 future_predictions = scaler.inverse_transform(np.array(future_predictions).reshape(-1,1))
3. 生成未来日期序列并可视化
创建未来60天的日期索引,将预测结果与历史数据合并后绘图:
# 生成未来60天日期 last_date = data.index[-1] future_dates = pd.date_range(start=last_date + pd.Timedelta(days=1), periods=60) # 创建预测结果DataFrame future_df = pd.DataFrame(future_predictions, index=future_dates, columns=['Future Predictions']) # 合并历史数据与预测数据 combined_data = pd.concat([data, future_df]) # 可视化 plt.figure(figsize=(16,8)) plt.title('腾讯股价历史走势与未来60天预测') plt.xlabel('日期', fontsize=18) plt.ylabel('收盘价', fontsize=18) plt.plot(combined_data['Close'], label='历史收盘价') plt.plot(combined_data['Future Predictions'], label='未来60天预测', linestyle='--', color='red') plt.legend(loc='lower right') plt.xticks(rotation=45) plt.show()
修改后的完整代码
import math import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates from mplfinance.original_flavor import candlestick_ohlc from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping # 假设Tencent2是已加载的数据集 # Tencent2 = pd.read_csv('your_data.csv') # 数据预处理 Tencent2['Date'] = pd.to_datetime(Tencent2['Date']) Tencent2.set_index('Date', inplace=True) data = Tencent2.filter(['Close']) dataset = data.values training_data_len = math.ceil(len(dataset) * 0.7) # 数据缩放 scaler = MinMaxScaler(feature_range=(0,1)) scaled_data = scaler.fit_transform(dataset) # 构建训练集 train_data = scaled_data[0:training_data_len, :] x_train, y_train = [], [] for i in range(60, len(train_data)): x_train.append(train_data[i-60:i, 0]) y_train.append(train_data[i, 0]) x_train, y_train = np.array(x_train), np.array(y_train) x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1)) # 构建LSTM模型 model = Sequential() model.add(LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], 1))) model.add(LSTM(50, return_sequences=False)) model.add(Dense(25)) model.add(Dense(1)) model.compile(optimizer='adam', loss='mean_squared_error') # 训练模型 checkpoint = ModelCheckpoint('best_model.h5', monitor='loss', save_best_only=True) early_stop = EarlyStopping(monitor='loss', patience=5, restore_best_weights=True) model.fit(x_train, y_train, batch_size=32, epochs=20, callbacks=[checkpoint, early_stop]) # 历史验证(可选) test_data = scaled_data[training_data_len - 60:] X_test = [] y_test = dataset[training_data_len:, :] for i in range(60, len(test_data)): X_test.append(test_data[i-60:i, 0]) X_test = np.array(X_test) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) predictions = model.predict(X_test) predictions = scaler.inverse_transform(predictions) # 未来60天预测 last_60_days = scaled_data[-60:] future_predictions = [] for _ in range(60): X_pred = last_60_days.reshape(1, 60, 1) pred_price = model.predict(X_pred, verbose=0) future_predictions.append(pred_price[0][0]) last_60_days = np.append(last_60_days[1:], pred_price, axis=0) future_predictions = scaler.inverse_transform(np.array(future_predictions).reshape(-1,1)) # 生成未来日期 last_date = data.index[-1] future_dates = pd.date_range(start=last_date + pd.Timedelta(days=1), periods=60) future_df = pd.DataFrame(future_predictions, index=future_dates, columns=['Future Predictions']) # 合并数据并可视化 combined_data = pd.concat([data, future_df]) plt.figure(figsize=(16,8)) plt.title('腾讯股价历史走势与未来60天预测') plt.xlabel('日期', fontsize=18) plt.ylabel('收盘价', fontsize=18) plt.plot(combined_data['Close'], label='历史收盘价') plt.plot(combined_data['Future Predictions'], label='未来60天预测', linestyle='--', color='red') plt.legend(loc='lower right') plt.xticks(rotation=45) plt.show()
内容的提问来源于stack exchange,提问作者Spatdy
相关产品推荐
相关产品推荐

