用python写一个利用LSTM模型预测股价的代码
时间: 2023-02-07 07:11:18 浏览: 133
LSTM预测股价代码
好的,这是一个使用 LSTM 模型预测股价的 Python 代码示例:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 导入股价数据
df = pd.read_csv('stock_prices.csv')
# 将日期转换为时间戳
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
# 将股价数据转换为 numpy 数组
data = df.values
# 设置训练集和测试集
train_data = data[:int(data.shape[0]*0.8)]
test_data = data[int(data.shape[0]*0.8):]
# 标准化数据
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
train_data = scaler.fit_transform(train_data)
test_data = scaler.transform(test_data)
# 准备训练和测试数据
def create_dataset(data, look_back=1):
dataX, dataY = [], []
for i in range(len(data)-look_back-1):
a = data[i:(i+look_back), 0]
dataX.append(a)
dataY.append(data[i + look_back, 0])
return np.array(dataX), np.array(dataY)
look_back = 1
X_train, Y_train = create_dataset(train_data, look_back)
X_test, Y_test = create_dataset(test_data, look_back)
# 将输入转换为 LSTM 需要的三维格式
X_train = np.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))
X_test = np.reshape(X_test, (X_test.shape[0], 1, X_test.shape[1]))
# 建立 LSTM 模型
from keras.models import Sequential
from keras.layers import LSTM, Dense
model = Sequential()
model.add(LSTM(50, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
# 训练模型
history = model.fit(X_train, Y_train, epochs=
阅读全文