1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
| def complete_stock_prediction_example(): """ 完整的股价预测案例,包含所有组件 """ import yfinance as yf print("=" * 60) print("步骤1: 数据获取") print("=" * 60) try: ticker = "AAPL" stock_data = yf.download(ticker, start="2015-01-01", end="2024-12-31") prices = stock_data['Close'].values.flatten() print(f"成功获取 {ticker} 股票数据") print(f"数据范围: {len(prices)} 天") except: prices = generate_stock_price_data(num_days=2000) print("使用模拟股票数据") print("\n" + "=" * 60) print("步骤2: 特征工程") print("=" * 60) features = add_technical_indicators(prices) feature_names = ['price', 'ma_5', 'ma_10', 'ma_20', 'ema_12', 'ema_26', 'macd', 'rsi', 'bb_mid', 'bb_std', 'bb_upper', 'bb_lower', 'returns', 'log_returns', 'volume', 'volatility'] print(f"特征数量: {len(feature_names)}") print(f"特征列表: {feature_names}") print("\n" + "=" * 60) print("步骤3: 数据预处理") print("=" * 60) scaler = MinMaxScaler() scaled_features = scaler.fit_transform(features) window_size = 60 pred_steps = 5 X, y = [], [] for i in range(window_size, len(scaled_features) - pred_steps): X.append(scaled_features[i-window_size:i]) y.append(scaled_features[i:i+pred_steps, 0]) X = np.array(X) y = np.array(y) print(f"输入形状: {X.shape}") print(f"输出形状: {y.shape}") train_ratio = 0.7 val_ratio = 0.15 train_idx = int(len(X) * train_ratio) val_idx = int(len(X) * (train_ratio + val_ratio)) X_train, X_val, X_test = X[:train_idx], X[train_idx:val_idx], X[val_idx:] y_train, y_val, y_test = y[:train_idx], y[train_idx:val_idx], y[val_idx:] print(f"训练集: {X_train.shape[0]} 样本") print(f"验证集: {X_val.shape[0]} 样本") print(f"测试集: {X_test.shape[0]} 样本") X_train_t = torch.FloatTensor(X_train) y_train_t = torch.FloatTensor(y_train) X_val_t = torch.FloatTensor(X_val) y_val_t = torch.FloatTensor(y_val) X_test_t = torch.FloatTensor(X_test) y_test_t = torch.FloatTensor(y_test) train_dataset = torch.utils.data.TensorDataset(X_train_t, y_train_t) val_dataset = torch.utils.data.TensorDataset(X_val_t, y_val_t) test_dataset = torch.utils.data.TensorDataset(X_test_t, y_test_t) train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True) val_loader = DataLoader(val_dataset, batch_size=64, shuffle=False) test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False) print("\n" + "=" * 60) print("步骤4: 模型构建") print("=" * 60) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(f"使用设备: {device}") input_size = X_train.shape[2] hidden_size = 128 num_layers = 2 output_size = pred_steps model = LSTMModel( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, output_size=output_size, dropout=0.3 ).to(device) print(f"模型结构:\n{model}") print("\n" + "=" * 60) print("步骤5: 模型训练") print("=" * 60) criterion = nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( optimizer, mode='min', factor=0.5, patience=5 ) epochs = 100 best_val_loss = float('inf') patience_counter = 0 early_stopping_patience = 15 for epoch in range(epochs): model.train() train_loss = 0 for batch_x, batch_y in train_loader: batch_x, batch_y = batch_x.to(device), batch_y.to(device) optimizer.zero_grad() outputs = model(batch_x) loss = criterion(outputs, batch_y) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() train_loss += loss.item() train_loss /= len(train_loader) model.eval() val_loss = 0 with torch.no_grad(): for batch_x, batch_y in val_loader: batch_x, batch_y = batch_x.to(device), batch_y.to(device) outputs = model(batch_x) loss = criterion(outputs, batch_y) val_loss += loss.item() val_loss /= len(val_loader) scheduler.step(val_loss) if val_loss < best_val_loss: best_val_loss = val_loss patience_counter = 0 torch.save(model.state_dict(), 'best_stock_model.pth') else: patience_counter += 1 if patience_counter >= early_stopping_patience: print(f"早停触发于 epoch {epoch+1}") break if (epoch + 1) % 10 == 0: print(f"Epoch {epoch+1:3d}/{epochs} | " f"Train Loss: {train_loss:.6f} | " f"Val Loss: {val_loss:.6f}") print("\n" + "=" * 60) print("步骤6: 测试评估") print("=" * 60) model.load_state_dict(torch.load('best_stock_model.pth')) model.eval() all_preds = [] all_targets = [] with torch.no_grad(): for batch_x, batch_y in test_loader: batch_x = batch_x.to(device) outputs = model(batch_x) all_preds.append(outputs.cpu().numpy()) all_targets.append(batch_y.numpy()) predictions = np.vstack(all_preds) targets = np.vstack(all_targets) mse = np.mean((predictions - targets) ** 2) rmse = np.sqrt(mse) mae = np.mean(np.abs(predictions - targets)) print("\n各预测步的评估指标:") print("-" * 50) print(f"{'预测步':<10} {'MSE':<15} {'RMSE':<15} {'MAE':<15}") print("-" * 50) for step in range(pred_steps): step_mse = np.mean((predictions[:, step] - targets[:, step]) ** 2) step_rmse = np.sqrt(step_mse) step_mae = np.mean(np.abs(predictions[:, step] - targets[:, step])) print(f"Step {step+1:<6} {step_mse:<15.6f} {step_rmse:<15.6f} {step_mae:<15.6f}") print("-" * 50) print(f"{'总体':<10} {mse:<15.6f} {rmse:<15.6f} {mae:<15.6f}") print("\n" + "=" * 60) print("步骤7: 结果可视化") print("=" * 60) vis_len = 50 vis_preds = predictions[:vis_len, 0] vis_targets = targets[:vis_len, 0] plt.figure(figsize=(14, 10)) plt.subplot(2, 2, 1) plt.plot(vis_targets, label='实际价格', linewidth=2) plt.plot(vis_preds, label='预测价格', linewidth=2, alpha=0.8) plt.title('股价预测对比(第一步预测)') plt.xlabel('时间步') plt.ylabel('归一化价格') plt.legend() plt.grid(True, alpha=0.3) plt.subplot(2, 2, 2) plt.plot(vis_targets, label='实际', linewidth=2, marker='o', markersize=3) for step in range(pred_steps): plt.plot(predictions[:vis_len, step], label=f'预测+{step+1}步', alpha=0.7, linestyle='--') plt.title('多步预测对比') plt.xlabel('时间步') plt.ylabel('归一化价格') plt.legend() plt.grid(True, alpha=0.3) plt.subplot(2, 2, 3) errors = predictions[:, 0] - targets[:, 0] plt.hist(errors, bins=50, edgecolor='black', alpha=0.7) plt.axvline(x=0, color='r', linestyle='--', label='零误差') plt.title('预测误差分布') plt.xlabel('预测误差') plt.ylabel('频数') plt.legend() plt.grid(True, alpha=0.3) plt.subplot(2, 2, 4) plt.scatter(targets[:, 0], predictions[:, 0], alpha=0.5, s=10) plt.plot([0, 1], [0, 1], 'r--', linewidth=2, label='理想预测线') plt.title('实际值 vs 预测值') plt.xlabel('实际值') plt.ylabel('预测值') plt.legend() plt.grid(True, alpha=0.3) plt.tight_layout() plt.savefig('stock_forecast_results.png', dpi=150) print("可视化结果已保存到 stock_forecast_results.png") return model, scaler
if __name__ == "__main__": model, scaler = complete_stock_prediction_example()
|