盘它!!一步到位,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 ...
随机推荐
- 714 - Copying Books——[贪心、二分查找]
Before the invention of book-printing, it was very hard to make a copy of a book. All the contents h ...
- linux进程延迟
#include <linux/wait.h> long wait_event_interruptible_timeout(wait_queue_head_t *q, condition, ...
- 百度人脸识别集成错误:Build command failed. Error while executing process F:\dev\Android\Sdk\cmake\3.6.4111459\bin\cmake.exe with arguments
大概是这么个错误 Build command failed. Error while executing process F:\dev\Android\Sdk\cmake\3.6.4111459\bi ...
- iDrac6 虚拟控制台 连接失败
最近给公司的服务器升级硬件(其实是服务器要淘汰了,公司就不管了,爱怎么折腾就怎么折腾,只要不坏就行) 服务器配置:Dell PowerEdge R610,E5606 x2(双路2.13G 4核4线程) ...
- 【Linux】awk笔记
awk是一种处理文本文件的语言,是一个强大的文本分析工具. 实例 ①显示文件行中匹配项 # 每行按空格或TAB分割,输出文本中的1.4项 yunduo@yunduo-ThinkCentre-XXXX: ...
- 理解C/C++的复杂声明
理解C/C++的复杂声明 曾经碰到过让你迷惑不解.类似于int * (* (*fp1) (int) ) [10];这样的变量声明吗?本文将由易到难,一步一步教会你如何理解这种复C/C ...
- 清晰架构(Clean Architecture)的Go微服务: 设计原则
我最近写了一个Go微服务应用程序,这个程序的设计来自三个灵感: 清晰架构"Clean Architecture"¹ and SOLID (面向对象设计)² 设计 原则³ Sprin ...
- 0002 认识HTML(骨架、DOCTYPE、lang、charset)
学习目标 理解 1.HTML的概念 2.HTML标签的分类 3.HTML标签的关系 4.HTML标签的语义化 应用 1.HTML骨架格式 2.sublime基本使用 1. HTML 初识 HTML 指 ...
- 一篇长文说 git 基础
版本管理在产品级开发中是非常重要的一个部分,它涉及到团队协作,且影响到产品最终的发布.上线以及测试环节,当前最流行的版本控制系统是 git.git 内容非常多,本文尽量克制地来介绍 git 的基础内容 ...
- vue-awesome-swiper手动滑动后不再自动轮播的问题
<swiper :options="swiperOption" ref="mySwiper" > <!--轮播图内容--> </s ...