关键词:tensorflow2、LSTM、时间序列、股票预测

Tensorflow 2.0发布已经有一段时间了,各种新API的确简单易用,除了官方文档以外能够找到的学习资料也很多,但是大都没有给出实战的部分找了好多量化分析中的博客和代码,发现在tensorflow方面大家都还是在用1.x的版本,始终没有找到关于2.x的代码,于是自己写了一段,与大家共勉。

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import tensorflow as tf
# from tensorflow.keras import layers
from sklearn.preprocessing import MinMaxScaler # Part 1 - Data Preprocessing
# Importing the libraries
dataset_train = pd.read_csv('NSE-TATAGLOBAL.csv')
training_set = dataset_train.iloc[:, 1:2].values
# print(dataset_train.head())
# Feature Scaling
sc = MinMaxScaler(feature_range=(0, 1))
training_set_scaled = sc.fit_transform(training_set)
# Creating a data structure with 60 timesteps and 1 output
X_train = []
y_train = []
for i in range(60, 2035):
X_train.append(training_set_scaled[i - 60:i, 0])
y_train.append(training_set_scaled[i, 0])
X_train, y_train = np.array(X_train), np.array(y_train)
# Reshaping
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) # Part 2 - Building the RNN
# Initialising the RNN
regressor = tf.keras.Sequential()
# Adding the first LSTM layer and some Dropout regularisation
regressor.add(tf.keras.layers.LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
regressor.add(tf.keras.layers.Dropout(0.2))
# Adding a second LSTM layer and some Dropout regularisation
regressor.add(tf.keras.layers.LSTM(units=50, return_sequences=True))
regressor.add(tf.keras.layers.Dropout(0.2))
# Adding a third LSTM layer and some Dropout regularisation
regressor.add(tf.keras.layers.LSTM(units=50, return_sequences=True))
regressor.add(tf.keras.layers.Dropout(0.2))
# Adding a fourth LSTM layer and some Dropout regularisation
regressor.add(tf.keras.layers.LSTM(units=50))
regressor.add(tf.keras.layers.Dropout(0.2))
# Adding the output layer
regressor.add(tf.keras.layers.Dense(units=1))
# Compiling the RNN
regressor.compile(optimizer='adam', loss='mean_squared_error')
# Fitting the RNN to the Training set
regressor.fit(X_train, y_train, epochs=100, batch_size=32) # Part 3 - Making the predictions and visualising the results
# Getting the real stock price of 2017
dataset_test = pd.read_csv('tatatest.csv')
real_stock_price = dataset_test.iloc[:, 1:2].values # Getting the predicted stock price of 2017
dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis=0)
inputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].values
inputs = inputs.reshape(-1, 1)
inputs = sc.transform(inputs)
X_test = []
for i in range(60, 76):
X_test.append(inputs[i - 60:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predicted_stock_price = regressor.predict(X_test)
predicted_stock_price = sc.inverse_transform(predicted_stock_price) # Visualising the results
plt.plot(real_stock_price, color='red', label='Real TATA Stock Price')
plt.plot(predicted_stock_price, color='blue', label='Predicted TAT Stock Price')
plt.title('TATA Stock Price Prediction')
plt.xlabel('Time')
plt.ylabel('TATA Stock Price')
plt.legend()
plt.show()

项目比较demo,但是凭借这个基本可以达到一个框架,另外我在其他随笔中也有相关的学习,欢迎大家讨论学习

使用的tata数据集是非常的难找(看了好多有代码没数据集索引),哭了,真的找了好久。

请移步https://www.cnblogs.com/xingnie/p/12219474.html

盘它!!一步到位,Tensorflow 2的实战 !!LSTM下的股票预测(附详尽代码及数据集)的更多相关文章

  1. 异常值检验实战1--风控贷款年龄变量(附python代码)

    python风控评分卡建模和风控常识(博客主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005214003&am ...

  2. 使用tensorflow的lstm网络进行时间序列预测

    https://blog.csdn.net/flying_sfeng/article/details/78852816 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog. ...

  3. 第24月第30天 scrapy《TensorFlow机器学习项目实战》项目记录

    1.Scrapy https://www.imooc.com/learn/1017 https://github.com/pythonsite/spider/tree/master/jobboleSp ...

  4. tensorflow笔记:多层LSTM代码分析

    tensorflow笔记:多层LSTM代码分析 标签(空格分隔): tensorflow笔记 tensorflow笔记系列: (一) tensorflow笔记:流程,概念和简单代码注释 (二) ten ...

  5. Tensorflow实例:利用LSTM预测股票每日最高价(一)

    RNN与LSTM 这一部分主要涉及循环神经网络的理论,讲的可能会比较简略. 什么是RNN RNN全称循环神经网络(Recurrent Neural Networks),是用来处理序列数据的.在传统的神 ...

  6. 使用TensorFlow的递归神经网络(LSTM)进行序列预测

    本篇文章介绍使用TensorFlow的递归神经网络(LSTM)进行序列预测.作者在网上找到的使用LSTM模型的案例都是解决自然语言处理的问题,而没有一个是来预测连续值的. 所以呢,这里是基于历史观察数 ...

  7. Tensorflow 循环神经网络 基本 RNN 和 LSTM 网络 拟合、预测sin曲线

    时序预测一直是比较重要的研究问题,在统计学中我们有各种的模型来解决时间序列问题,但是最近几年比较火的深度学习中也有能解决时序预测问题的方法,另外在深度学习领域中时序预测算法可以解决自然语言问题等. 在 ...

  8. 深度学习RNN实现股票预测实战(附数据、代码)

    背景知识 最近再看一些量化交易相关的材料,偶然在网上看到了一个关于用RNN实现股票预测的文章,出于好奇心把文章中介绍的代码在本地跑了一遍,发现可以work.于是就花了两个晚上的时间学习了下代码,顺便把 ...

  9. [转载]实战Linux下VMware虚拟机根目录空间扩充

    [转载]实战Linux下VMware虚拟机根目录空间扩充 (2011-07-31 21:34:34) 转载▼ 标签: 转载   原文地址:实战Linux下VMware虚拟机根目录空间扩充作者:shar ...

随机推荐

  1. HDU 6709“Fishing Master”(贪心+优先级队列)

    传送门 •参考资料 [1]:2019CCPC网络选拔赛 H.Fishing Master(思维+贪心) •题意 池塘里有 n 条鱼,捕捉一条鱼需要花费固定的 k 时间: 你有一个锅,每次只能煮一条鱼, ...

  2. Laravel报错Call to undefined function Illuminate\Encryption\openssl_cipher_iv_length()

    nginx: 在phpstudy中运行Laravel一键安装包时报错:Call to undefined function Illuminate\Encryption\openssl_cipher_i ...

  3. Pandas库之DataFrame

    Pandas库之DataFrame 1 简介 DataFrame是Python中Pandas库中的一种数据结构,它类似excel,是一种二维表. 或许说它可能有点像matlab的矩阵,但是matlab ...

  4. Vant-UI移动端时间选择框

    使用Vant input框时有时需要调用时间选择,时间选择框要结合弹出层使用 <div class="van-cell van-field"> <span cla ...

  5. 2018-6-15-win10-uwp-xaml-绑定接口

    title author date CreateTime categories win10 uwp xaml 绑定接口 lindexi 2018-6-15 21:7:19 +0800 2018-2-1 ...

  6. js三大框架出现的意义

    解决了原始html,css,js的UI与数据状态之间同步的难题,避免了大量的操作DOM代码. 使用了React,Angular和Vue,我们只需要定义一次 UI 界面,不再需要为每个操作编写特定的 U ...

  7. 洛谷4139 bzoj 3884 上帝与集合的正确用法

    传送门 •题意 求$2^{2^{2^{2^{2^{2^{...^{2}}}}}}}$ (无穷个2) 对p取模的值 •思路 设答案为f(p) $2^{2^{2^{2^{2^{2^{...^{2}}}}} ...

  8. 备战省赛组队训练赛第五场(UPC)

    中石油比赛链接 CF题目链接 E:博客 G:李继朋  博客 H:苗学林  贺振原 J:博客  苗学林 机房白给队全方位题解:A B E G I J

  9. Linux网络文件共享服务之FTP

    一.FTP介绍 ftp(File Transfer Protocol)是早期的三个应用级协议之一,基于C/S结构,双通道协议,数据和命令连接,数据传输格式默认是二进制,当然也支持文件方式传输.默认情况 ...

  10. CP防火墙备份与还原

    Step1:进入专家模式 ====================================================== 如果没有设置专家模式的密码,执行下面命令进行设置: BJ-OFF ...