#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 18 21:22:29 2017 @author: luogan
""" from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY,YEARLY
from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc
#import matplotlib
import tushare as ts
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.pylab import date2num
import datetime
import numpy as np
from pandas import DataFrame
from numpy import row_stack,column_stack df=ts.get_hist_data('',start='2016-06-15',end='2017-11-06')
dd=df[['open','high','low','close']] #print(dd.values.shape[0]) dd1=dd .sort_index() dd2=dd1.values.flatten() g1=dd2[::-1] g2=g1[0:120] g3=g2[::-1] gg=DataFrame(g3) gg.T.to_excel('gg.xls') #dd3=pd.DataFrame(dd2)
#dd3.T.to_excel('d8.xls') g=dd2[0:140]
for i in range(dd.values.shape[0]-34): s=dd2[i*4:i*4+140]
g=row_stack((g,s)) fg=DataFrame(g) print(fg)
fg.to_excel('fg.xls') #-*- coding: utf-8 -*-
#建立、训练多层神经网络,并完成模型的检验
#from __future__ import print_function
import pandas as pd inputfile1='fg.xls' #训练数据
testoutputfile = 'test_output_data.xls' #测试数据模型输出文件
data_train = pd.read_excel(inputfile1) #读入训练数据(由日志标记事件是否为洗浴)
data_mean = data_train.mean()
data_std = data_train.std()
data_train1 = (data_train-data_mean)/5 #数据标准化 y_train = data_train1.iloc[:,120:140].as_matrix() #训练样本标签列
x_train = data_train1.iloc[:,0:120].as_matrix() #训练样本特征
#y_test = data_test.iloc[:,4].as_matrix() #测试样本标签列 from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation model = Sequential() #建立模型
model.add(Dense(input_dim = 120, output_dim = 240)) #添加输入层、隐藏层的连接
model.add(Activation('relu')) #以Relu函数为激活函数
model.add(Dense(input_dim = 240, output_dim = 120)) #添加隐藏层、隐藏层的连接
model.add(Activation('relu')) #以Relu函数为激活函数
model.add(Dense(input_dim = 120, output_dim = 120)) #添加隐藏层、隐藏层的连接
model.add(Activation('relu')) #以Relu函数为激活函数
model.add(Dense(input_dim = 120, output_dim = 20)) #添加隐藏层、输出层的连接
model.add(Activation('sigmoid')) #以sigmoid函数为激活函数
#编译模型,损失函数为binary_crossentropy,用adam法求解
model.compile(loss='mean_squared_error', optimizer='adam') model.fit(x_train, y_train, nb_epoch = 100, batch_size = 8) #训练模型
model.save_weights('net.model') #保存模型参数 inputfile2='gg.xls' #预测数据
pre = pd.read_excel(inputfile2) pre_mean = data_mean[0:120]
pre_std = pre.std()
pre1 = (pre-pre_mean)/5 #数据标准化 pre2 = pre1.iloc[:,0:120].as_matrix() #预测样本特征
r = pd.DataFrame(model.predict(pre2))
rt=r*5+data_mean[120:140].as_matrix()
print(rt.round(2)) rt.to_excel('rt.xls') #print(r.values@data_train.iloc[:,116:120].std().values+data_mean[116:120].as_matrix()) a=list(df.index[0:-1]) b=a[0] c= datetime.datetime.strptime(b,'%Y-%m-%d') d = date2num(c) c1=[d+i+1 for i in range(5)]
c2=np.array([c1]) r1=rt.values.flatten()
r2=r1[0:4]
for i in range(4): r3=r1[i*4+4:i*4+8]
r2=row_stack((r2,r3)) c3=column_stack((c2.T,r2))
r5=DataFrame(c3) if len(c3) == 0:
raise SystemExit fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2) #ax.xaxis.set_major_locator(mondays)
#ax.xaxis.set_minor_locator(alldays)
#ax.xaxis.set_major_formatter(mondayFormatter)
#ax.xaxis.set_minor_formatter(dayFormatter) #plot_day_summary(ax, quotes, ticksize=3)
candlestick_ohlc(ax, c3, width=0.6, colorup='r', colordown='g') ax.xaxis_date()
ax.autoscale_view()
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') ax.grid(True)
#plt.title('000002')
plt.show()

Keras预测股票的更多相关文章

  1. 基于Spark Streaming预测股票走势的例子(一)

    最近学习Spark Streaming,不知道是不是我搜索的姿势不对,总找不到具体的.完整的例子,一怒之下就决定自己写一个出来.下面以预测股票走势为例,总结了用Spark Streaming开发的具体 ...

  2. 通过机器学习的线性回归算法预测股票走势(用Python实现)

    在本人的新书里,将通过股票案例讲述Python知识点,让大家在学习Python的同时还能掌握相关的股票知识,所谓一举两得.这里给出以线性回归算法预测股票的案例,以此讲述通过Python的sklearn ...

  3. AI金融:LSTM预测股票

    第一部分:从RNN到LSTM 1.什么是RNN RNN全称循环神经网络(Recurrent Neural Networks),是用来处理序列数据的.在传统的神经网络模型中,从输入层到隐含层再到输出层, ...

  4. 20岁少年小伙利用Python_SVM预测股票趋势月入十万!

      在做数据预处理的时候,超额收益率是股票行业里的一个专有名词,指大于无风险投资的收益率,在我国无风险投资收益率即是银行定期存款. pycharm + anaconda3.6开发,涉及到的第三方库有p ...

  5. Tensorflow实例:利用LSTM预测股票每日最高价(一)

    RNN与LSTM 这一部分主要涉及循环神经网络的理论,讲的可能会比较简略. 什么是RNN RNN全称循环神经网络(Recurrent Neural Networks),是用来处理序列数据的.在传统的神 ...

  6. Tensflow预测股票实例

    import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf #———— ...

  7. 基于Spark Streaming预测股票走势的例子(二)

    上一篇博客中,已经对股票预测的例子做了简单的讲解,下面对其中的几个关键的技术点再作一些总结. 1.updateStateByKey 由于在1.6版本中有一个替代函数,据说效率比较高,所以作者就顺便研究 ...

  8. AI金融:利用LSTM预测股票每日最高价

    第一部分:从RNN到LSTM 1.什么是RNN RNN全称循环神经网络(Recurrent Neural Networks),是用来处理序列数据的.在传统的神经网络模型中,从输入层到隐含层再到输出层, ...

  9. 如何预测股票分析--长短期记忆网络(LSTM)

    在上一篇中,我们回顾了先知的方法,但是在这个案例中表现也不是特别突出,今天介绍的是著名的l s t m算法,在时间序列中解决了传统r n n算法梯度消失问题的的它这一次还会有令人杰出的表现吗? 长短期 ...

随机推荐

  1. Android自定义view(一):制作一个最最最简单的自定义view

    转载:https://blog.csdn.net/wsyizmao/article/details/78491422 浅谈安卓自定义view(一):制作一个最最最简单的自定义view 对于安卓程序员来 ...

  2. sqljdbc4.jar的安装

    自己项目环境(idea+jdk1.8+tomcat8),在搭建maven项目时,由于本地数据库是使用了sqlserver,所以需要项目与sqlserver之间建立连接,但是网上查的资料都说微软不允许以 ...

  3. centos7 二进制版本安装 mysql8.0.13

    一.下载mysql二进制安装包 mysql官网: https://dev.mysql.com/downloads/mysql/ 由于国内网络问题,个人建议使用国内开源镜像站下载: http://mir ...

  4. gRPC的.netClient客户端第一次连接出现StatusCode=Unavailable的解决办法?

    1.问题还原: The service does not automatically connect, free after a period of time, the first call will ...

  5. mongodb导入csv结构化数据

    csv数据样本 "103238704","","-jmyuncker@aol.com-","-r4Vp5iL2VbM=-" ...

  6. prototype.js的Ajax对IE8兼容问题解决方案

    你是否遇到过这样的问题?在使用protype.js的Ajax应用时,会出现这样的问题:只要调用了Ajax.Request,然后点该页面右键,查看“属性”就弹出“IE停止工作”的对话框,然后强制重新加载 ...

  7. 9.28 h5日记

    9.28 1.transparent 透明的 颜色 2.placeholder 提示语 在input中使用 跟velue不同 3.写页面需要注意的 (1)页面一定要有层次,分清层次 (2)保证元素模块 ...

  8. “windows的批处理”与“Linux的shell script”的类比学习

    从2005年开始,做了将近10年的系统维护,先是做网络接入管理,然后做网络安全与审计,然后做服务器管理等整个网络系统的运营管理:现在又兼着做一些Linux下的视频监控系统的软硬件维护.过程中遇到太多重 ...

  9. laravel框架一次请求的生命周期

    第一件事所有的请求都会被web服务器(Apache/Nginx)导向public/index.php文件.index.php文件载入Composer生成的自动加载设置,然后从bootstrap/app ...

  10. mysql 查两个表之间的数据差集

    需要查两个表之间的差集 首先,想到的是主键直接not in select mailbox_id from co_user where mailbox_id not in (select mailbox ...