关键词: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. P1053 第K小的取法

    题目描述 给定一个含n个数的数组.现在从中取出一些数.并把这些数相加得出一个和,如果有多种取法的和相同,则视为多种取法.求所有取法对应的和中第K小的和. 输入格式 第一行包括两个正整数n(n<= ...

  2. P1039 大规模间谍入侵

    题目描述 爱丽丝魔法王国成立10周年,于是决定矩形国庆大阅兵. 在国庆大阅兵期间,为了防止暗黑王国的间谍乔装成平民混入,需要对每一个进城的人做检测. 因为暗黑王国的人长得和爱丽丝魔法王国的人长得很像, ...

  3. python调用java代码,jpype简单使用

  4. dotnet core 通过 frp 发布自己的网站

    很多时候写出来的网站只能自己内网访问,本文告诉大家如何通过 Frp 将自己的 asp dotnet core 网站发布到外网,让小伙伴访问自己的网站 通过 frp 的方式,可以解决自己的服务器性能太差 ...

  5. win2d 通过 CanvasActiveLayer 画出透明度和裁剪

    本文告诉大家如果在 UWP 的 win2d 通过 CanvasActiveLayer 创建一层,在这里画出的图片有透明度或者裁剪 在 win2d 如果需要对某个元素裁剪,可以使用很多方法,本文只是告诉 ...

  6. H3C配置console口密码

    方法一: [H3C]user-interface console 0 [H3C-ui-console0]authentication-mode password [H3C-ui-console0]se ...

  7. 2018-2-13-win10-uwp-判断设备类型

    title author date CreateTime categories win10 uwp 判断设备类型 lindexi 2018-2-13 17:23:3 +0800 2018-2-13 1 ...

  8. 2016湖南省赛 I Tree Intersection(线段树合并,树链剖分)

    2016湖南省赛 I Tree Intersection(线段树合并,树链剖分) 传送门:https://ac.nowcoder.com/acm/contest/1112/I 题意: 给你一个n个结点 ...

  9. Netty小结

    前言 在实际开发中,netty的开发使用相对较小,why?在企业中涉及网络编程的部分比重较小,在这大环境内,企业会优先使用简单的http,udp等基础的通讯协议工具,如果不能满足需求,会考虑基于rpc ...

  10. SQLite3的使用(封装很长,直接使用sqlite3_open函数,LIBS += sqlite3.dll 即可)good

    1.下载sqlite3相关文件sqlite3.dll.sqlite3.h(可从http://download.csdn.net/detail/mingxia_sui/5249070下载),添加到工程的 ...