基于 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 ...
随机推荐
- X短期项目总结
刚退出了一个项目,简称为X项目.这个项目中,还是遇到了不少问题,也解决了部分问题,还是挺有收获的,所以总结一下. 虽然标题说是短期项目总结,但其实这个项目并不短, 持续了约3年时间. 所谓的短,只是我 ...
- R基础绘图
本节内容 0:小知识 1:绘图系统散点图的特征 2:基础绘图函数 3:基础绘图参数 4:图形设备 5:案例操作5个图形 0:小知识 summary() ## 对数据框或者向量进行描述性数据 read. ...
- java(二)变量
基础数据类型: 数值型:整型(byte.short.int.long).浮点型(float.double)java各整数类型有固定的表数范围和字段长度,不受具体os的影响,以保持java的可移植性:j ...
- Android常用adb命令总结(一)
ADB是android sdk里的一个工具,用这个工具可以直接操作管理android模拟器或者真实的andriod设备. ADB是一个客户端-服务器端程序,其中客户端是你用来操作的电脑,服务器端是an ...
- 避免python二维列表append一维列表时浅拷贝问题
原始问题: 由于浅拷贝原因,使得当a列表变动时,b列表也发生变动 解决办法: 如上图所示,添加的时候添加新列即可,类似新建一个列表,使得与原有列表a不共用同一个内存
- jQuery 源码分析(十一) 队列模块 Queue详解
队列是常用的数据结构之一,只允许在表的前端(队头)进行删除操作(出队),在表的后端(队尾)进行插入操作(入队).特点是先进先出,最先插入的元素最先被删除. 在jQuery内部,队列模块为动画模块提供基 ...
- python3在mac下配置
目的 https://github.com/VonSdite/Plane_Wars 可以本地跑起来. 下载并安装python3 https://www.python.org/downloads/mac ...
- 如何查看laravel门脸类包含方法的源码
以Route门脸类为例,我们定义路由时使用的就是Route门脸类,例如我们在web.php中定义的路由 use Illuminate\Support\Facades\Route; Route::get ...
- Leakcanary原理浅析
LeakCanary是Android内存泄漏的框架,作为一个"面试常见问题",它一定有值得学习的地方,今天我们就讲一下它.作为一名开发,我觉得给人讲框架或者库的原理,最好先把大概思 ...
- wpf button style IsMouseOver
<Style x:Key="workButtonStyle" TargetType="{x:Type Button}"> <Style.Tri ...