今天,梅朵和大家分享用Python实现LSTM股价预测,仅用于技术学习交流,不作为投资建议。 1.导入依赖库 主要是安装相关的依赖库。本文实现的环境为:python 3.7。 # 导入依赖库 import sklearn import numpy as np import pandas as pd import matplotlib.pyplot as plt from keras.optimizers import Adam from keras.models import Sequential from keras.layers import LSTM, Dense from sklearn.preprocessing import MinMaxScaler
2.读取股价数据并归一化 读取股价数据文件,并对数据进行归一化处理。 # 读取股票价格数据 data = pd.read_csv('stock_data.csv') prices = data['Close'].values
# 数据预处理:归一化 scaler = MinMaxScaler() prices = scaler.fit_transform(prices.reshape(-1, 1))
3.划分训练集和测试集并确定模型输入和输出数据 划分数据的训练集和测试集,并确定模型输入库数据和输出数据。 # 划分数据集为训练集和测试集 train_size = int(len(prices) * 0.75) train_data, test_data = prices[:train_size], prices[train_size:]
#确定模型输入和输出数据 in_out_length = 12 train_sequences = [] for i in range(len(train_data) - in_out_length): train_sequences.append(train_data[i:i+in_out_length]) X_train = np.array(train_sequences) y_train = train_data[in_out_length:] test_sequences = [] for i in range(len(test_data) - in_out_length): test_sequences.append(test_data[i:i+in_out_length]) X_test = np.array(test_sequences) y_test = test_data[in_out_length:]
4.创建LSTM模型并训练模型 创建LSTM模型并进行模型训练。 # 创建LSTM模型 model = Sequential() model.add(LSTM(50, input_shape=(in_out_length, 1))) model.add(Dense(1)) learning_rate=0.002 model.compile(loss='mean_squared_error', optimizer=Adam(learning_rate))
# 训练模型 model.fit(X_train, y_train, epochs=50, batch_size=64)
3.利用LSTM模型预测股价 利用训练好的LSTM模型进行预测。 # 预测未来股价 predicted_prices = model.predict(X_test) predicted_prices = scaler.inverse_transform(predicted_prices) y_test = scaler.inverse_transform(y_test)
完整源代码
# 导入依赖库 import sklearn import numpy as np import pandas as pd import matplotlib.pyplot as plt from keras.optimizers import Adam from keras.models import Sequential from keras.layers import LSTM, Dense from sklearn.preprocessing import MinMaxScaler
if __name__=='__main__': # 读取股票价格数据 data = pd.read_csv('stock_data.csv') prices = data['Close'].values
# 数据预处理:归一化 scaler = MinMaxScaler() prices = scaler.fit_transform(prices.reshape(-1, 1))
# 划分数据集为训练集和测试集 train_size = int(len(prices) * 0.75) train_data, test_data = prices[:train_size], prices[train_size:]
#确定模型输入和输出数据 in_out_length = 12 train_sequences = [] for i in range(len(train_data) - in_out_length): train_sequences.append(train_data[i:i+in_out_length]) X_train = np.array(train_sequences) y_train = train_data[in_out_length:] test_sequences = [] for i in range(len(test_data) - in_out_length): test_sequences.append(test_data[i:i+in_out_length]) X_test = np.array(test_sequences) y_test = test_data[in_out_length:]
# 创建LSTM模型 model = Sequential() model.add(LSTM(50, input_shape=(in_out_length, 1))) model.add(Dense(1)) learning_rate=0.002 model.compile(loss='mean_squared_error', optimizer=Adam(learning_rate))
# 训练模型 model.fit(X_train, y_train, epochs=50, batch_size=64)
# 预测未来股价 predicted_prices = model.predict(X_test) predicted_prices = scaler.inverse_transform(predicted_prices) y_test = scaler.inverse_transform(y_test)
# 绘制预测结果 plt.plot(y_test, label='True_Prices') plt.plot(predicted_prices, label='Predicted_Prices') plt.legend() plt.xlabel('Time_Steps') plt.ylabel('Stock_Price') plt.title('LSTM Stock Price Prediction') plt.show()
|