神经网络python源码分享


Posted in Python onDecember 15, 2017

神经网络的逻辑应该都是熟知的了,在这里想说明一下交叉验证

交叉验证方法:

神经网络python源码分享

看图大概就能理解了,大致就是先将数据集分成K份,对这K份中每一份都取不一样的比例数据进行训练和测试。得出K个误差,将这K个误差平均得到最终误差

这第一个部分是BP神经网络的建立

参数选取参照论文:基于数据挖掘技术的股价指数分析与预测研究_胡林林

import math
import random
import tushare as ts
import pandas as pd
random.seed(0)
def getData(id,start,end):
  df = ts.get_hist_data(id,start,end)
  DATA=pd.DataFrame(columns=['rate1', 'rate2','rate3','pos1','pos2','pos3','amt1','amt2','amt3','MA20','MA5','r'])
  P1 = pd.DataFrame(columns=['high','low','close','open','volume'])
  DATA2=pd.DataFrame(columns=['R'])
  DATA['MA20']=df['ma20']
  DATA['MA5']=df['ma5']
  P=df['close']
  P1['high']=df['high']
  P1['low']=df['low']
  P1['close']=df['close']
  P1['open']=df['open']
  P1['volume']=df['volume']

  DATA['rate1']=(P1['close'].shift(1)-P1['open'].shift(1))/P1['open'].shift(1)
  DATA['rate2']=(P1['close'].shift(2)-P1['open'].shift(2))/P1['open'].shift(2)
  DATA['rate3']=(P1['close'].shift(3)-P1['open'].shift(3))/P1['open'].shift(3)
  DATA['pos1']=(P1['close'].shift(1)-P1['low'].shift(1))/(P1['high'].shift(1)-P1['low'].shift(1))
  DATA['pos2']=(P1['close'].shift(2)-P1['low'].shift(2))/(P1['high'].shift(2)-P1['low'].shift(2))
  DATA['pos3']=(P1['close'].shift(3)-P1['low'].shift(3))/(P1['high'].shift(3)-P1['low'].shift(3))
  DATA['amt1']=P1['volume'].shift(1)/((P1['volume'].shift(1)+P1['volume'].shift(2)+P1['volume'].shift(3))/3)
  DATA['amt2']=P1['volume'].shift(2)/((P1['volume'].shift(2)+P1['volume'].shift(3)+P1['volume'].shift(4))/3)
  DATA['amt3']=P1['volume'].shift(3)/((P1['volume'].shift(3)+P1['volume'].shift(4)+P1['volume'].shift(5))/3)
  templist=(P-P.shift(1))/P.shift(1)
  tempDATA = []
  for indextemp in templist:
    tempDATA.append(1/(1+math.exp(-indextemp*100)))
  DATA['r'] = tempDATA
  DATA=DATA.dropna(axis=0)
  DATA2['R']=DATA['r']
  del DATA['r']
  DATA=DATA.T
  DATA2=DATA2.T
  DATAlist=DATA.to_dict("list")
  result = []
  for key in DATAlist:
    result.append(DATAlist[key])
  DATAlist2=DATA2.to_dict("list")
  result2 = []
  for key in DATAlist2:
    result2.append(DATAlist2[key])
  return result
def getDataR(id,start,end):
  df = ts.get_hist_data(id,start,end)
  DATA=pd.DataFrame(columns=['rate1', 'rate2','rate3','pos1','pos2','pos3','amt1','amt2','amt3','MA20','MA5','r'])
  P1 = pd.DataFrame(columns=['high','low','close','open','volume'])
  DATA2=pd.DataFrame(columns=['R'])
  DATA['MA20']=df['ma20'].shift(1)
  DATA['MA5']=df['ma5'].shift(1)
  P=df['close']
  P1['high']=df['high']
  P1['low']=df['low']
  P1['close']=df['close']
  P1['open']=df['open']
  P1['volume']=df['volume']

  DATA['rate1']=(P1['close'].shift(1)-P1['open'].shift(1))/P1['open'].shift(1)
  DATA['rate2']=(P1['close'].shift(2)-P1['open'].shift(2))/P1['open'].shift(2)
  DATA['rate3']=(P1['close'].shift(3)-P1['open'].shift(3))/P1['open'].shift(3)
  DATA['pos1']=(P1['close'].shift(1)-P1['low'].shift(1))/(P1['high'].shift(1)-P1['low'].shift(1))
  DATA['pos2']=(P1['close'].shift(2)-P1['low'].shift(2))/(P1['high'].shift(2)-P1['low'].shift(2))
  DATA['pos3']=(P1['close'].shift(3)-P1['low'].shift(3))/(P1['high'].shift(3)-P1['low'].shift(3))
  DATA['amt1']=P1['volume'].shift(1)/((P1['volume'].shift(1)+P1['volume'].shift(2)+P1['volume'].shift(3))/3)
  DATA['amt2']=P1['volume'].shift(2)/((P1['volume'].shift(2)+P1['volume'].shift(3)+P1['volume'].shift(4))/3)
  DATA['amt3']=P1['volume'].shift(3)/((P1['volume'].shift(3)+P1['volume'].shift(4)+P1['volume'].shift(5))/3)
  templist=(P-P.shift(1))/P.shift(1)
  tempDATA = []
  for indextemp in templist:
    tempDATA.append(1/(1+math.exp(-indextemp*100)))
  DATA['r'] = tempDATA
  DATA=DATA.dropna(axis=0)
  DATA2['R']=DATA['r']
  del DATA['r']
  DATA=DATA.T
  DATA2=DATA2.T
  DATAlist=DATA.to_dict("list")
  result = []
  for key in DATAlist:
    result.append(DATAlist[key])
  DATAlist2=DATA2.to_dict("list")
  result2 = []
  for key in DATAlist2:
    result2.append(DATAlist2[key])
  return result2
def rand(a, b):
  return (b - a) * random.random() + a
def make_matrix(m, n, fill=0.0):
  mat = []
  for i in range(m):
    mat.append([fill] * n)
  return mat
def sigmoid(x):
  return 1.0 / (1.0 + math.exp(-x))
def sigmod_derivate(x):
  return x * (1 - x)
class BPNeuralNetwork:
  def __init__(self):
    self.input_n = 0
    self.hidden_n = 0
    self.output_n = 0
    self.input_cells = []
    self.hidden_cells = []
    self.output_cells = []
    self.input_weights = []
    self.output_weights = []
    self.input_correction = []
    self.output_correction = []

  def setup(self, ni, nh, no):
    self.input_n = ni + 1
    self.hidden_n = nh
    self.output_n = no
    # init cells
    self.input_cells = [1.0] * self.input_n
    self.hidden_cells = [1.0] * self.hidden_n
    self.output_cells = [1.0] * self.output_n
    # init weights
    self.input_weights = make_matrix(self.input_n, self.hidden_n)
    self.output_weights = make_matrix(self.hidden_n, self.output_n)
    # random activate
    for i in range(self.input_n):
      for h in range(self.hidden_n):
        self.input_weights[i][h] = rand(-0.2, 0.2)
    for h in range(self.hidden_n):
      for o in range(self.output_n):
        self.output_weights[h][o] = rand(-2.0, 2.0)
    # init correction matrix
    self.input_correction = make_matrix(self.input_n, self.hidden_n)
    self.output_correction = make_matrix(self.hidden_n, self.output_n)

  def predict(self, inputs):
    # activate input layer
    for i in range(self.input_n - 1):
      self.input_cells[i] = inputs[i]
    # activate hidden layer
    for j in range(self.hidden_n):
      total = 0.0
      for i in range(self.input_n):
        total += self.input_cells[i] * self.input_weights[i][j]
      self.hidden_cells[j] = sigmoid(total)
    # activate output layer
    for k in range(self.output_n):
      total = 0.0
      for j in range(self.hidden_n):
        total += self.hidden_cells[j] * self.output_weights[j][k]
      self.output_cells[k] = sigmoid(total)
    return self.output_cells[:]
  def back_propagate(self, case, label, learn, correct):
    # feed forward
    self.predict(case)
    # get output layer error
    output_deltas = [0.0] * self.output_n
    for o in range(self.output_n):
      error = label[o] - self.output_cells[o]
      output_deltas[o] = sigmod_derivate(self.output_cells[o]) * error
    # get hidden layer error
    hidden_deltas = [0.0] * self.hidden_n
    for h in range(self.hidden_n):
      error = 0.0
      for o in range(self.output_n):
        error += output_deltas[o] * self.output_weights[h][o]
      hidden_deltas[h] = sigmod_derivate(self.hidden_cells[h]) * error
    # update output weights
    for h in range(self.hidden_n):
      for o in range(self.output_n):
        change = output_deltas[o] * self.hidden_cells[h]
        self.output_weights[h][o] += learn * change + correct * self.output_correction[h][o]
        self.output_correction[h][o] = change
    # update input weights
    for i in range(self.input_n):
      for h in range(self.hidden_n):
        change = hidden_deltas[h] * self.input_cells[i]
        self.input_weights[i][h] += learn * change + correct * self.input_correction[i][h]
        self.input_correction[i][h] = change
    # get global error
    error = 0.0
    for o in range(len(label)):
      error += 0.5 * (label[o] - self.output_cells[o]) ** 2
    return error
  def train(self, cases, labels, limit=10000, learn=0.05, correct=0.1):
    for i in range(limit):
      error = 0.0
      for i in range(len(cases)):
        label = labels[i]
        case = cases[i]
        error += self.back_propagate(case, label, learn, correct)
  def test(self,id):
    result=getData("000001", "2015-01-05", "2015-01-09")
    result2=getDataR("000001", "2015-01-05", "2015-01-09")
    self.setup(11, 5, 1)
    self.train(result, result2, 10000, 0.05, 0.1)
    for t in resulttest:
      print(self.predict(t))

下面是选取14-15年数据进行训练,16年数据作为测试集,调仓周期为20个交易日,大约1个月,对上证50中的股票进行预测,选取预测的涨幅前10的股票买入,对每只股票分配一样的资金,初步运行没有问题,但就是太慢了,等哪天有空了再运行

import BPnet
import tushare as ts
import pandas as pd
import math
import xlrd
import datetime as dt
import time

#
#nn =BPnet.BPNeuralNetwork()
#nn.test('000001')
#for i in ts.get_sz50s()['code']:
holdList=pd.DataFrame(columns=['time','id','value'])
share=ts.get_sz50s()['code']
time2=ts.get_k_data('000001')['date']
newtime = time2[400:640]
newcount=0
for itime in newtime:
  print(itime)
  if newcount % 20 == 0:
        sharelist = pd.DataFrame(columns=['time','id','value'])
    for ishare in share:
      backwardtime = time.strftime('%Y-%m-%d',time.localtime(time.mktime(time.strptime(itime,'%Y-%m-%d'))-432000*4))
      trainData = BPnet.getData(ishare, '2014-05-22',itime)
      trainDataR = BPnet.getDataR(ishare, '2014-05-22',itime)
      testData = BPnet.getData(ishare, backwardtime,itime)
      try:
        print(testData)
        testData = testData[-1]
        print(testData)
        nn = BPnet.BPNeuralNetwork()
        nn.setup(11, 5, 1)
        nn.train(trainData, trainDataR, 10000, 0.05, 0.1)
        value = nn.predict(testData)
        newlist= pd.DataFrame({'time':itime,"id":ishare,"value":value},index=["0"])
        sharelist = sharelist.append(newlist,ignore_index=True)
      except: 
        pass
    sharelist=sharelist.sort(columns ='value',ascending=False)
    sharelist = sharelist[:10]
    holdList=holdList.append(sharelist,ignore_index=True)
  newcount+=1
  print(holdList)

总结

以上就是本文关于神经网络python源码分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Python 相关文章推荐
Python内置的HTTP协议服务器SimpleHTTPServer使用指南
Mar 30 Python
python 地图经纬度转换、纠偏的实例代码
Aug 06 Python
python散点图实例之随机漫步
Aug 27 Python
Django中自定义admin Xadmin的实现代码
Aug 09 Python
关于python字符串方法分类详解
Aug 20 Python
Python多线程Threading、子线程与守护线程实例详解
Mar 24 Python
Python tempfile模块生成临时文件和临时目录
Sep 30 Python
解决selenium+Headless Chrome实现不弹出浏览器自动化登录的问题
Jan 09 Python
将不规则的Python多维数组拉平到一维的方法实现
Jan 11 Python
Python办公自动化之教你如何用Python将任意文件转为PDF格式
Jun 28 Python
Pandas搭配lambda组合使用详解
Jan 22 Python
Python3的进程和线程你了解吗
Mar 16 Python
神经网络理论基础及Python实现详解
Dec 15 #Python
浅谈机器学习需要的了解的十大算法
Dec 15 #Python
python实现协同过滤推荐算法完整代码示例
Dec 15 #Python
python3大文件解压和基本操作
Dec 15 #Python
Python数据结构与算法之常见的分配排序法示例【桶排序与基数排序】
Dec 15 #Python
numpy自动生成数组详解
Dec 15 #Python
Python3实现发送QQ邮件功能(附件)
Dec 23 #Python
You might like
WINDOWS下php5.2.4+mysql6.0+apache2.2.4+ZendOptimizer-3.3.0配置
2008/03/28 PHP
PHP测试程序运行时间的类
2012/02/05 PHP
yii2使用ajax返回json的实现方法
2016/05/14 PHP
php写app用的框架整理
2019/09/29 PHP
jquery 必填项判断表单是否为空的方法
2008/09/14 Javascript
jqueryUI里拖拽排序示例分析
2015/02/26 Javascript
JS简单实现动画弹出层效果
2015/05/05 Javascript
深入探究使JavaScript动画流畅的一些方法
2015/06/30 Javascript
JavaScript中的原型继承基础学习教程
2016/05/06 Javascript
基于JavaScript实现轮播图代码
2016/07/14 Javascript
JavaScript生成验证码并实现验证功能
2016/09/24 Javascript
Javascript实现数组中的元素上下移动
2017/04/28 Javascript
解决Vue axios post请求,后台获取不到数据的问题方法
2018/08/11 Javascript
使用vuepress搭建静态博客的示例代码
2019/02/14 Javascript
通过实例讲解JS如何防抖动
2019/06/15 Javascript
Vue formData实现图片上传
2019/08/20 Javascript
vue+koa2实现session、token登陆状态验证的示例
2019/08/30 Javascript
python 字符串split的用法分享
2013/03/23 Python
简单介绍Python中的JSON使用
2015/04/28 Python
Python爬取京东的商品分类与链接
2016/08/26 Python
TensorFlow内存管理bfc算法实例
2020/02/03 Python
linux centos 7.x 安装 python3.x 替换 python2.x的过程解析
2020/12/14 Python
CSS3改变浏览器滚动条样式
2019/01/04 HTML / CSS
中科创达面试题
2016/12/28 面试题
最热门的自我评价
2013/12/30 职场文书
告诉你怎样写创业计划书
2014/01/27 职场文书
国庆促销活动总结
2014/08/29 职场文书
励志广播稿300字(5篇)
2014/09/15 职场文书
无财产离婚协议书范本
2014/10/28 职场文书
办公室岗位职责
2015/02/04 职场文书
市场总监岗位职责
2015/02/11 职场文书
歌舞青春观后感
2015/06/10 职场文书
奖学金申请个人主要事迹材料
2015/11/04 职场文书
2016年三八节红领巾广播稿
2015/12/17 职场文书
使用Python+OpenCV进行卡类型及16位卡号数字的OCR功能
2021/08/30 Python
css中有哪些方式可以隐藏页面元素及区别
2022/06/16 HTML / CSS