基于 lstm 的股票收盘价预测 -- python
开始导入 MinMaxScaler 时会报错 “from . import _arpack ImportError: DLL load failed: 找不到指定的程序。” (把sklearn更新下)和“AttributeError: module 'numpy' has no attribute 'testing'”,然后把numpy卸载重装(pip uninstall numpy; pip install numpy),问题解决。
#import datetime
import pandas as pd
import numpy as np
#from numpy import row_stack,column_stack
import tushare as ts
#import matplotlib
import matplotlib.pyplot as plt
#from matplotlib.pylab import date2num
#from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY,YEARLY
#from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc
from sklearn.preprocessing import MinMaxScaler
#https://scikit-learn.org/stable/auto_examples/preprocessing/plot_all_scaling.html#sphx-glr-auto-examples-preprocessing-plot-all-scaling-py
from keras.models import Sequential
from keras.layers import LSTM, Dense, Activation df=ts.get_hist_data('601857',start='2016-06-15',end='2018-01-12')
dd=df[['open','high','low','close']] #print(dd.values.shape[0]) dd1=dd .sort_index() dd2=dd1.values.flatten() dd3=pd.DataFrame(dd1['close']) def load_data(df, sequence_length=10, split=0.8): #df = pd.read_csv(file_name, sep=',', usecols=[1])
#data_all = np.array(df).astype(float) data_all = np.array(df).astype(float)
scaler = MinMaxScaler()
data_all = scaler.fit_transform(data_all)
data = []
for i in range(len(data_all) - sequence_length - 1):
data.append(data_all[i: i + sequence_length + 1])
reshaped_data = np.array(data).astype('float64')
#np.random.shuffle(reshaped_data)
# 对x进行统一归一化,而y则不归一化
x = reshaped_data[:, :-1]
y = reshaped_data[:, -1]
split_boundary = int(reshaped_data.shape[0] * split)
train_x = x[: split_boundary]
test_x = x[split_boundary:] train_y = y[: split_boundary]
test_y = y[split_boundary:] return train_x, train_y, test_x, test_y, scaler def build_model():
# input_dim是输入的train_x的最后一个维度,train_x的维度为(n_samples, time_steps, input_dim)
model = Sequential()
model.add(LSTM(input_dim=1, output_dim=6, return_sequences=True))
#model.add(LSTM(6, input_dim=1, return_sequences=True))
#model.add(LSTM(6, input_shape=(None, 1),return_sequences=True)) """
#model.add(LSTM(input_dim=1, output_dim=6,input_length=10, return_sequences=True))
#model.add(LSTM(6, input_dim=1, input_length=10, return_sequences=True))
model.add(LSTM(6, input_shape=(10, 1),return_sequences=True))
"""
print(model.layers)
#model.add(LSTM(100, return_sequences=True))
#model.add(LSTM(100, return_sequences=True))
model.add(LSTM(100, return_sequences=False))
model.add(Dense(output_dim=1))
model.add(Activation('linear')) model.compile(loss='mse', optimizer='rmsprop')
return model def train_model(train_x, train_y, test_x, test_y):
model = build_model() try:
model.fit(train_x, train_y, batch_size=512, nb_epoch=300, validation_split=0.1)
predict = model.predict(test_x)
predict = np.reshape(predict, (predict.size, ))
except KeyboardInterrupt:
print(predict)
print(test_y)
print(predict)
print(test_y)
try:
fig = plt.figure(1)
plt.plot(predict, 'r:')
plt.plot(test_y, 'g-')
plt.legend(['predict', 'true'])
except Exception as e:
print(e)
return predict, test_y if __name__ == '__main__':
#train_x, train_y, test_x, test_y, scaler = load_data('international-airline-passengers.csv')
train_x, train_y, test_x, test_y, scaler =load_data(dd3, sequence_length=10, split=0.8)
train_x = np.reshape(train_x, (train_x.shape[0], train_x.shape[1], 1))
test_x = np.reshape(test_x, (test_x.shape[0], test_x.shape[1], 1))
predict_y, test_y = train_model(train_x, train_y, test_x, test_y)
predict_y = scaler.inverse_transform([[i] for i in predict_y])
test_y = scaler.inverse_transform(test_y)
fig2 = plt.figure(2)
plt.plot(predict_y, 'g:')
plt.plot(test_y, 'r-')
plt.show()
参考资料:
基于 lstm 的股票收盘价预测 -- python的更多相关文章
- 实现基于股票收盘价的时间序列的统计(用Python实现)
时间序列是按时间顺序的一组真实的数字,比如股票的交易数据.通过分析时间序列,能挖掘出这组序列背后包含的规律,从而有效地预测未来的数据.在这部分里,将讲述基于时间序列的常用统计方法. 1 用rollin ...
- Python中利用LSTM模型进行时间序列预测分析
时间序列模型 时间序列预测分析就是利用过去一段时间内某事件时间的特征来预测未来一段时间内该事件的特征.这是一类相对比较复杂的预测建模问题,和回归分析模型的预测不同,时间序列模型是依赖于事件发生的先后顺 ...
- 基于 Keras 用 LSTM 网络做时间序列预测
目录 基于 Keras 用 LSTM 网络做时间序列预测 问题描述 长短记忆网络 LSTM 网络回归 LSTM 网络回归结合窗口法 基于时间步的 LSTM 网络回归 在批量训练之间保持 LSTM 的记 ...
- 深度学习|基于LSTM网络的黄金期货价格预测--转载
深度学习|基于LSTM网络的黄金期货价格预测 前些天看到一位大佬的深度学习的推文,内容很适用于实战,争得原作者转载同意后,转发给大家.之后会介绍LSTM的理论知识. 我把code先放在我github上 ...
- 在我的新书里,尝试着用股票案例讲述Python爬虫大数据可视化等知识
我的新书,<基于股票大数据分析的Python入门实战>,预计将于2019年底在清华出版社出版. 如果大家对大数据分析有兴趣,又想学习Python,这本书是一本不错的选择.从知识体系上来看, ...
- 语法设计——基于LL(1)文法的预测分析表法
实验二.语法设计--基于LL(1)文法的预测分析表法 一.实验目的 通过实验教学,加深学生对所学的关于编译的理论知识的理解,增强学生对所学知识的综合应用能力,并通过实践达到对所学的知识进行验证.通过对 ...
- 使用TensorFlow的递归神经网络(LSTM)进行序列预测
本篇文章介绍使用TensorFlow的递归神经网络(LSTM)进行序列预测.作者在网上找到的使用LSTM模型的案例都是解决自然语言处理的问题,而没有一个是来预测连续值的. 所以呢,这里是基于历史观察数 ...
- 使用tensorflow的lstm网络进行时间序列预测
https://blog.csdn.net/flying_sfeng/article/details/78852816 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog. ...
- 基于 Keras 用深度学习预测时间序列
目录 基于 Keras 用深度学习预测时间序列 问题描述 多层感知机回归 多层感知机回归结合"窗口法" 改进方向 扩展阅读 本文主要参考了 Jason Brownlee 的博文 T ...
随机推荐
- 机器学习--用PCA算法实现三维样本降到二维
对于维数比较多的数据,首先需要做的事就是在尽量保证数据本质的前提下将数据中的维数降低.降维是一种数据集预处理技术,往往在数据应用在其他算法之前使用,它可以去除掉数据的一些冗余信息和噪声,使数据变得更加 ...
- flask之web网关、三件套、配置、路由(参数、转化器及自定义转化器)、cbv、模板语言、session
目录 1.wsgiref.py 2.werzeug.py 3.三件套 4.配置文件 5.路由本质 6.cbv.py 7.路由转化器 8.自定义转化器 9.模板语言 10.session原理 11.te ...
- 机器学习模型| 监督学习| KNN | 决策树
分类模型 K近邻 逻辑斯谛回归 决策树 K近邻(KNN) 最简单最初级的分类器,就是将全部的训练数据所对应的类别都记录下来,当测试对象的属性和某个训练对象的属性完全匹配时,便可以对其进行分类K近邻(k ...
- saltstack--史上最细致安装攻略!亲测无坑
准备一台虚拟机node1: [root@linux-node1 pillar]# ifconfig ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAS ...
- 利用shell脚本快速定位日志
我们平时查日志,在测试环境,日志文件只有几个的情况下,我们可以通过找时间接近的文件然后根据关键词定位报错位置,大不了都查一遍,这都可以忍受.但是在实际的生产环境下,服务器集群部署,每天的日志非常多非常 ...
- [转]使用IConfigureNamedOptions和ConfigureAll配置命名选项
这是我上一篇关于在ASP.NET Core 2.x中使用多个强类型设置实例的后续文章.在文章的结尾,我介绍了命名选项的概念,该选项已添加到ASP.NET Core 2.0中.在本文中,我将详细介绍如何 ...
- CSP-S 爆零记
抱歉,这么晚才更. 事实是:我都没有去 所以爆零了 QwQ
- python基础(20):序列化、json模块、pickle模块
1. 序列化 什么叫序列化——将原本的字典.列表等内容转换成一个字符串的过程就叫做序列化. 1.1 为什么要有序列化 为什么要把其他数据类型转换成字符串?因为能够在网络上传输的只能是bytes,而能够 ...
- Java生鲜电商平台-商品基础业务架构设计-商品设计
Java生鲜电商平台-商品基础业务架构设计-商品设计 在生鲜电商的商品中心,在电子商务公司一般是后台管理商品的地方.在前端而言,是商家为了展示商品信息给用户的地方,它是承担了商品的数据,订单,营销活动 ...
- Java性能之synchronized锁的优化
synchronized / Lock 1.JDK 1.5之前,Java通过synchronized关键字来实现锁功能 synchronized是JVM实现的内置锁,锁的获取和释放都是由JVM隐式实现 ...