开始导入 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()

  

参考资料:

基于keras 的lstm 股票收盘价预测

RNN,LSTM,GRU基本原理的个人理解

  

基于 lstm 的股票收盘价预测 -- python的更多相关文章

  1. 实现基于股票收盘价的时间序列的统计(用Python实现)

    时间序列是按时间顺序的一组真实的数字,比如股票的交易数据.通过分析时间序列,能挖掘出这组序列背后包含的规律,从而有效地预测未来的数据.在这部分里,将讲述基于时间序列的常用统计方法. 1 用rollin ...

  2. Python中利用LSTM模型进行时间序列预测分析

    时间序列模型 时间序列预测分析就是利用过去一段时间内某事件时间的特征来预测未来一段时间内该事件的特征.这是一类相对比较复杂的预测建模问题,和回归分析模型的预测不同,时间序列模型是依赖于事件发生的先后顺 ...

  3. 基于 Keras 用 LSTM 网络做时间序列预测

    目录 基于 Keras 用 LSTM 网络做时间序列预测 问题描述 长短记忆网络 LSTM 网络回归 LSTM 网络回归结合窗口法 基于时间步的 LSTM 网络回归 在批量训练之间保持 LSTM 的记 ...

  4. 深度学习|基于LSTM网络的黄金期货价格预测--转载

    深度学习|基于LSTM网络的黄金期货价格预测 前些天看到一位大佬的深度学习的推文,内容很适用于实战,争得原作者转载同意后,转发给大家.之后会介绍LSTM的理论知识. 我把code先放在我github上 ...

  5. 在我的新书里,尝试着用股票案例讲述Python爬虫大数据可视化等知识

    我的新书,<基于股票大数据分析的Python入门实战>,预计将于2019年底在清华出版社出版. 如果大家对大数据分析有兴趣,又想学习Python,这本书是一本不错的选择.从知识体系上来看, ...

  6. 语法设计——基于LL(1)文法的预测分析表法

    实验二.语法设计--基于LL(1)文法的预测分析表法 一.实验目的 通过实验教学,加深学生对所学的关于编译的理论知识的理解,增强学生对所学知识的综合应用能力,并通过实践达到对所学的知识进行验证.通过对 ...

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

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

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

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

  9. 基于 Keras 用深度学习预测时间序列

    目录 基于 Keras 用深度学习预测时间序列 问题描述 多层感知机回归 多层感知机回归结合"窗口法" 改进方向 扩展阅读 本文主要参考了 Jason Brownlee 的博文 T ...

随机推荐

  1. misc-3-1

    无后缀,用winhex发现是rar,添加后缀解压,依据是无后缀,丢到kali,是一个流量数据包 TCP追踪流在第五个数据包发现flag.rar 导出对象 选择HTTP 找到flag.rar 然后丢到你 ...

  2. python连接MySQL pymysql模块,游标,SQL注入问题,增删改查操作

    pymysql模块 pymysql是用python控制终端对MySQL数据库进行操作的第三方模块 import pymysql # 1.连接数据库 client = pymysql.connect( ...

  3. Java连载46-Java中的多态

    一.多态的语法 1.关于多态中涉及到几个概念 (1)向上转型(upcasting) 子类型转换为父类型,又被称为自动类型转换 (2)向下转型(downcasting) 父类型转换为子类型,又被称为强制 ...

  4. 使用paramiko模块进行封装,远程操作linux主机

    import time import paramiko class HandleParamiko: ''' 定义一个linux处理类 ''' def __init__(self, hostname, ...

  5. Mysql优化之Explain查询计划查看

    我们经常说到mysql优化,优化中一种常见的方式就是对于经常查询的字段创建索引.那么mysql中有哪些索引类型呢? 一.索引分类1.普通索引:即一个索引只包含单个列,一个表可以有多个单列索引 2.唯一 ...

  6. char.IsWhiteSpace(str,num),TimeSpan

    IsWhiteSpace(String, Int32) 指示指定字符串中位于指定位置处的字符是否属于空格类别. TimeSpan TimeSpan ts=new TimeSpan(4,30,0); C ...

  7. 动软生成Model(dapper.common)

    <#@ template language="c#" HostSpecific="True" #><#@ output extension= ...

  8. MySQL学习——查看数据库信息

    MySQL学习——查看数据库信息 摘要:本文主要学习了查看数据库信息的方法. 查询指定表的索引 语法 show index from 表名; 示例 mysql> show index from ...

  9. The method newInstance() from the type Class is deprecated since version 9

    newInstance()在 java9中已被弃用 JAVA9之前用法 Class.forName("类的全限定名").newInstance(); JAVA9之后用法 Class ...

  10. JavaScript继承的最初设想

    JavaScript没有真正的类(class)和实例(instance),而是靠一种奇特的原型链模式,来实现继承. 在Brendan Eich设计之初,Javascript里面都是对象,必须有一种机制 ...