用LSTM预测股票收盘价的代码python jupter
时间: 2024-12-08 10:21:28 浏览: 19
使用长短期记忆网络(Long Short-Term Memory,LSTM)预测股票收盘价通常涉及到时间序列分析和深度学习。在Python中,结合Jupyter Notebook编写这样的代码可以分为以下几个步骤:
1. 导入必要的库:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
```
2. 加载数据并预处理:
```python
# 假设你已经有了CSV文件,包含日期和收盘价
df = pd.read_csv('stock_data.csv')
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
data = df['Close'].values.reshape(-1, 1)
scaler = MinMaxScaler(feature_range=(0, 1))
data_scaled = scaler.fit_transform(data)
```
3. 划分训练集和测试集:
```python
train_size = int(len(data) * 0.8)
train_data, test_data = data_scaled[:train_size], data_scaled[train_size:]
```
4. 构建LSTM模型:
```python
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(train_data.shape[1], 1)))
model.add(LSTM(units=50))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mean_squared_error')
```
5. 训练模型:
```python
model.fit(train_data, epochs=100, batch_size=32)
```
6. 预测和评估:
```python
predictions = model.predict(test_data)
predictions = scaler.inverse_transform(predictions)
plt.plot(data, label='Original Data')
plt.plot(predictions, label='Predicted Data')
plt.legend()
plt.show()
# 可能会计算一些指标如MAE、MSE或RMSE来评估性能
```
阅读全文