Keras预测股票
#!/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预测股票的更多相关文章
- 基于Spark Streaming预测股票走势的例子(一)
最近学习Spark Streaming,不知道是不是我搜索的姿势不对,总找不到具体的.完整的例子,一怒之下就决定自己写一个出来.下面以预测股票走势为例,总结了用Spark Streaming开发的具体 ...
- 通过机器学习的线性回归算法预测股票走势(用Python实现)
在本人的新书里,将通过股票案例讲述Python知识点,让大家在学习Python的同时还能掌握相关的股票知识,所谓一举两得.这里给出以线性回归算法预测股票的案例,以此讲述通过Python的sklearn ...
- AI金融:LSTM预测股票
第一部分:从RNN到LSTM 1.什么是RNN RNN全称循环神经网络(Recurrent Neural Networks),是用来处理序列数据的.在传统的神经网络模型中,从输入层到隐含层再到输出层, ...
- 20岁少年小伙利用Python_SVM预测股票趋势月入十万!
在做数据预处理的时候,超额收益率是股票行业里的一个专有名词,指大于无风险投资的收益率,在我国无风险投资收益率即是银行定期存款. pycharm + anaconda3.6开发,涉及到的第三方库有p ...
- Tensorflow实例:利用LSTM预测股票每日最高价(一)
RNN与LSTM 这一部分主要涉及循环神经网络的理论,讲的可能会比较简略. 什么是RNN RNN全称循环神经网络(Recurrent Neural Networks),是用来处理序列数据的.在传统的神 ...
- Tensflow预测股票实例
import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf #———— ...
- 基于Spark Streaming预测股票走势的例子(二)
上一篇博客中,已经对股票预测的例子做了简单的讲解,下面对其中的几个关键的技术点再作一些总结. 1.updateStateByKey 由于在1.6版本中有一个替代函数,据说效率比较高,所以作者就顺便研究 ...
- AI金融:利用LSTM预测股票每日最高价
第一部分:从RNN到LSTM 1.什么是RNN RNN全称循环神经网络(Recurrent Neural Networks),是用来处理序列数据的.在传统的神经网络模型中,从输入层到隐含层再到输出层, ...
- 如何预测股票分析--长短期记忆网络(LSTM)
在上一篇中,我们回顾了先知的方法,但是在这个案例中表现也不是特别突出,今天介绍的是著名的l s t m算法,在时间序列中解决了传统r n n算法梯度消失问题的的它这一次还会有令人杰出的表现吗? 长短期 ...
随机推荐
- 建立SSH的信任关系
1.在Client上root用户执行ssh-keygen命令,生成建立安全信任关系的证书. Client端 # ssh-keygen -t rsa Generating public/private ...
- Bootstrap(6)辅组类和响应式工具
一.辅助类 Bootstrap 在布局方面提供了一些细小的辅组样式,用于文字颜色以及背景色的设置.显示关闭图标等等. 1.情景文本颜色 各种色调的字体 <p class="text-m ...
- HTTP协议介绍(POST、GET、Content-Type)
什么是HTTP?超文本传输协议(HyperText Transfer Protocol -- HTTP)是一个设计来使客户端和服务器顺利进行通讯的协议.HTTP/1.1 协议规定的 HTTP 请求方法 ...
- html5新添加的表单类型和属性
email类型: <input type="email"> url类型: <input type="url"> date类型: < ...
- python 基本数据类型 之 字符串
字符串数据出现的意义 掌握字符串的定义和特性 能熟练掌握字符串常用操作,并了解其他工厂方法 字符串的定义和创建 字符串是一个有序的字符集合,用于存储和表示基本的文本信息, 用引号“ ...
- Charles基本使用
Charles使用 查找电脑IP,菜单选项helpàLocal IP Addresses 手机连接代理 手机打开WiFi,把代理模式设置为手动,设置主机名为Charles所在机器的ip,端口号为Cha ...
- C# oracle to_date 日期型 参数传值
C#操作oracle,date字段,使用参数传值 例子一,获取三小时前的记录 public static DataTable Query() { const string sSql = &qu ...
- (转)Eclipse导入EPF配置文件
为了美化Eclipse大家可以从 http://www.eclipsecolorthemes.org/ 下载EPF配置文件,使用方法如下 (1)从File菜单 选择Import (2) 选择Gen ...
- where
(二)WHERE //where不单独使用,与match,optional match,start,with搭配 where 与match,optional match 一起用,表示约束 where ...
- sql求倒数第二大的数,效率不高,但写法新颖
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...