LSTM预测股票

【深度学习】基于LSTM时间序列的股票价格预测_myaijarvis的博客-CSDN博客_lstm预测股价

股票数据

链接:https://pan.baidu.com/s/1rUFUOTPV9JzwZwiIUFtyXw?pwd=1166 
提取码:1166 
--来自百度网盘超级会员V8的分享

000001SZ_10Y.csv

 

import numpy as np
import tushare as t1
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout, GRU
from tensorflow.keras.optimizers import SGD # 可以忽略警告错误

#st=StandardScaler()
#t1.set_token('8fa17c450ce70d9d2997013997afaf7502c643095e3f3ebfe1c31525')
#ts = t1.pro_api()



def data_set(dataset, lookback):
   """
   :param dataset: ndarray
   :param lookback: 单个序列的长度
   :return:
   """
   dataX, dataY = [], []
   for i in range(0, len(dataset) - lookback - 1):
      temp = dataset[i: i + lookback]  # 前 lookback步
      dataX.append(temp)
      dataY.append(dataset[i + lookback])  # 第 lookback步
   return np.array(dataX), np.array(dataY)


def plot_predictions(test_result, predict_restult):
   """
   test_result: 真实值
   predict_result: 预测值
   """
   plt.plot(test_result, color='red', label='test')
   plt.plot(predict_restult, color='blue', label="prdict")
   plt.xlabel("Time")
   plt.ylabel("Close Price")
   plt.legend()  # 给图加上图例
   plt.show()



# Press the green button in the gutter to run the script.
if __name__ == '__main__':
   data = pd.read_csv('000001SZ_10Y.CSV')
   df = pd.DataFrame(data,columns=['trade_date','close'])
   df.head(5)
   print(df)
   plt.plot(df['trade_date'], df['close'])
   plt.show()
   dataset = df["close"].values
   print(dataset)
   dataset_st = st.fit_transform(X=dataset.reshape(-1, 1))
   print(dataset_st)
   print(dataset_st.shape)
   train_size = int(len(dataset_st) * 0.7)
   test_size = int(len(dataset_st)) - train_size
   print(train_size)
   print(test_size)
   train, test = dataset_st[0:train_size], dataset_st[train_size:]
   print(train.shape)

   lookback = 2
   trainX, trainY = data_set(train, lookback)
   testX, testY = data_set(test, lookback)
   print(trainX.shape)
   print(trainY.shape)
   print(testX.shape)


   model = Sequential()
   # LSTM 第一层
   model.add(LSTM(128, return_sequences=True,  # 是返回输出序列中的最后一个输出,还是全部序列True。
                  input_shape=(trainX.shape[1], 1)))  # (sequence_length, features)
   model.add(Dropout(0.2))

   # LSTM 第二层
   model.add(LSTM(128, return_sequences=True))
   model.add(Dropout(0.2))

   # LSTM 第三层
   model.add(LSTM(128))
   model.add(Dropout(0.2))

   # Dense层
   model.add(Dense(units=1))

   # 模型编译
   model.compile(optimizer='rmsprop', loss='mse')

   # 模型训练
   model.fit(trainX, trainY, epochs=20, batch_size=32)

   pred_st = model.predict(testX)
   pred = st.inverse_transform(pred_st)  # 进行反归一化
   testY2 = st.inverse_transform(testY)  # 进行反归一化 因为前面进行了归一化
   plot_predictions(testY2, pred)  # 画出图像

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值