盘它!!一步到位,Tensorflow 2的实战 !!LSTM下的股票预测(附详尽代码及数据集)
关键词: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--风控贷款年龄变量(附python代码)
python风控评分卡建模和风控常识(博客主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005214003&am ...
- 使用tensorflow的lstm网络进行时间序列预测
https://blog.csdn.net/flying_sfeng/article/details/78852816 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog. ...
- 第24月第30天 scrapy《TensorFlow机器学习项目实战》项目记录
1.Scrapy https://www.imooc.com/learn/1017 https://github.com/pythonsite/spider/tree/master/jobboleSp ...
- tensorflow笔记:多层LSTM代码分析
tensorflow笔记:多层LSTM代码分析 标签(空格分隔): tensorflow笔记 tensorflow笔记系列: (一) tensorflow笔记:流程,概念和简单代码注释 (二) ten ...
- Tensorflow实例:利用LSTM预测股票每日最高价(一)
RNN与LSTM 这一部分主要涉及循环神经网络的理论,讲的可能会比较简略. 什么是RNN RNN全称循环神经网络(Recurrent Neural Networks),是用来处理序列数据的.在传统的神 ...
- 使用TensorFlow的递归神经网络(LSTM)进行序列预测
本篇文章介绍使用TensorFlow的递归神经网络(LSTM)进行序列预测.作者在网上找到的使用LSTM模型的案例都是解决自然语言处理的问题,而没有一个是来预测连续值的. 所以呢,这里是基于历史观察数 ...
- Tensorflow 循环神经网络 基本 RNN 和 LSTM 网络 拟合、预测sin曲线
时序预测一直是比较重要的研究问题,在统计学中我们有各种的模型来解决时间序列问题,但是最近几年比较火的深度学习中也有能解决时序预测问题的方法,另外在深度学习领域中时序预测算法可以解决自然语言问题等. 在 ...
- 深度学习RNN实现股票预测实战(附数据、代码)
背景知识 最近再看一些量化交易相关的材料,偶然在网上看到了一个关于用RNN实现股票预测的文章,出于好奇心把文章中介绍的代码在本地跑了一遍,发现可以work.于是就花了两个晚上的时间学习了下代码,顺便把 ...
- [转载]实战Linux下VMware虚拟机根目录空间扩充
[转载]实战Linux下VMware虚拟机根目录空间扩充 (2011-07-31 21:34:34) 转载▼ 标签: 转载 原文地址:实战Linux下VMware虚拟机根目录空间扩充作者:shar ...
随机推荐
- H3C配置console口密码
方法一: [H3C]user-interface console 0 [H3C-ui-console0]authentication-mode password [H3C-ui-console0]se ...
- Qt4与Qt3的主要不同
Qt4与Qt3的主要不同 1)QT4 中提供了大量新控件,虽然它也保持了旧的控件,并命名为Qt3XXX,但是这样的控件没准在今后的哪个QT版本中就不被支持了,所以还是换吧,控件替换的 工作是巨大的,这 ...
- 【Linux】sed笔记
sed - stream editor for filtering and transforming text(用于过滤和转换文本的SED流编辑器),主要是以行为单位进行处理,可以将数据行进行替换. ...
- HMaster/HRegion Server 工作原理
1.HBase系统架构 2. HRegion Sever架构图 0.94之前的版本 0.96+的版本 WAL: 即Write Ahead Log, 是HDFS上一个文件,早期版本中称为 ...
- Deep Learning ——Yann LeCun,Yoshua Bengio&Geoffrey Hinton
引言: 深度学习的本质是用多层的神经网络找到一个可以被学习的复杂的函数实现语音识别,图像识别等功能. 多层神经网络的结构: 多层神经元的组成,每一层的输入都等于上一层的输出. 应用领域:cv,nlp ...
- Python3使用Pyintaller-打包成exe
Pyinstaller打包exe执行文件 安装Pyinstaller 使用pip安装Pyinstaller 用管理员模式运行cmd,输入命令: pip install pyinstaller 此方法会 ...
- java基础 -- 关键字final的用法
用法一(修饰变量): Final变量能被显式地初始化并且只能初始化一次.被声明为final的对象的引用不能指向不同的对象.但是final对象里的数据可以被改变.也就是说final对象的引用不能改变,但 ...
- DEVOPS技术实践_13:使用Jenkins持续传送设计-CD基础
1. 分支策略 持续集成中使用的分支策略包括以下三个: The master branch The integration branch The feature branch 而CD只在Integra ...
- Cocos Creator | 飞刀大乱斗开发教程系列(二)
预览效果 具体内容 ■ 这一期,主要讲解主页中间人物效果的实现.也就是,在下方列表选择不同人物,上方显示不同的人物,播放不同的效果,即下图的效果实现,此部分也是采用预制 Prefab 进行实现. 英雄 ...
- 洛谷P1147 连续自然数和 题解 枚举
题目链接:https://www.luogu.com.cn/problem/P1147 题目大意: 给你一个数 \(M\) ,求有多少对连续自然数对之和为 \(M\),输出这列连续自然数对的首项和末项 ...