用python写一段代码,基于lstm预测第二天股票数据
时间: 2024-01-25 18:04:09 浏览: 159
好的,以下是基于LSTM预测股票数据的Python代码示例:
```python
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import LSTM, Dense
from sklearn.preprocessing import MinMaxScaler
# 读取股票数据
df = pd.read_csv('stock_data.csv')
# 将数据转换为numpy数组
data = df.values
# 将数据归一化
scaler = MinMaxScaler()
data = scaler.fit_transform(data)
# 定义训练集和测试集
train_size = int(len(data) * 0.8)
test_size = len(data) - train_size
train_data, test_data = data[0:train_size,:], data[train_size:len(data),:]
# 构建数据集
def create_dataset(dataset, look_back=1):
X, Y = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
X.append(a)
Y.append(dataset[i + look_back, 0])
return np.array(X), np.array(Y)
look_back = 7
train_X, train_Y = create_dataset(train_data, look_back)
test_X, test_Y = create_dataset(test_data, look_back)
# 将数据转换为LSTM的输入格式
train_X = np.reshape(train_X, (train_X.shape[0], 1, train_X.shape[1]))
test_X = np.reshape(test_X, (test_X.shape[0], 1, test_X.shape[1]))
# 构建LSTM模型
model = Sequential()
model.add(LSTM(50, input_shape=(1, look_back)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(train_X, train_Y, epochs=100, batch_size=1, verbose=2)
# 预测测试集数据
test_predict = model.predict(test_X)
test_predict = scaler.inverse_transform(test_predict)
test_Y = scaler.inverse_transform([test_Y])
# 计算均方根误差
rmse = np.sqrt(np.mean((test_predict - test_Y)**2))
print('均方根误差:', rmse)
# 预测未来数据
last_data = data[-look_back:]
last_data = np.reshape(last_data, (1, 1, look_back))
future_predict = model.predict(last_data)
future_predict = scaler.inverse_transform(future_predict)
print('未来一天股票预测值:', future_predict)
```
请将股票数据保存在名为`stock_data.csv`的文件中,数据应该包含一列,表示每天的股票价格。在获得预测结果后,代码会输出均方根误差和预测的未来一天股票价格。请注意,这只是一个简单的示例,实际情况可能需要更复杂的模型和更多的特征。
阅读全文