利用神经网络实现股票预测 | 附Pyhon代码

神经网络(NeuralNetworks)是一种用训练数据拟合目标函数的黑箱模型,只要数据量足够大,它可以拟合出输入到输出之间的任意函数关系。

本篇教程我们将使用神经网络进行股市的预测,利用数据样本学习,得到相关因素预测股票走势。

01

问题描述

1)数据

首先我们预设一组数据,下图为股票上证指数2019年07月到2019年09月的30天开盘价格和收盘价格。

▍股票开盘和收盘价格

2)网络结构

设计三层神经网络,隐含层包括25个节点,利用所设计的神经网络来预测股票的收盘均价。

3)可视化

可建立一个30行2列的矩阵存储股票数据,矩阵的第一列输入上列数据中的股票开盘价格,第二列输入股票的收盘价格,如果股票的收盘价格高于开盘价格则用红色显示,反之则用绿色显示,可视化股票数据如下图所示。采用本实例所设计的神经网络预测股票收盘均价,并可视化预测结果。

▍股票价格柱形图

02

实现代码

Python实现代码如下所示:

importtensorflow as tf

importnumpy as np

importmatplotlib.pyplot as plt

date = np.linspace(1,30,30)

beginPrice = np.array([2923.19,2928.06,2943.92,2946.26,2944.40,2920.85,2861.33,2854.58,2776.69,2789.02,

2784.18,2805.59,2781.98,2798.05,2824.49,2762.34,2817.57,2835.52,2879.08,2875.47,

2887.66,2885.15,2851.02,2879.52,2901.63,2896.00,2907.38,2886.94,2925.94,2927.75])

endPrice = np.array([2937.36,2944.54,2941.01,2952.34,2932.51,2908.77,2867.84,2821.50,2777.56,2768.68,

2794.55,2774.75,2814.99,2797.26,2808.91,2815.80,2823.82,2883.10,2880.00,2880.33,

2883.44,2897.43,2863.57,2902.19,2893.76,2890.92,2886.24,2924.11,2930.15,2957.41])

for i in range(0,30): #画柱状图

dateOne = np.zeros([2])

dateOne[0] = i;

dateOne[1] = i;

priceOne = np.zeros([2])

priceOne[0] = beginPrice[i]

priceOne[1] = endPrice[i]

ifendPrice[i]>beginPrice[i]:

plt.plot(dateOne,priceOne,'r',lw=6)

else:

plt.plot(dateOne,priceOne,'g',lw=6)

plt.xlabel("date")

plt.ylabel("price")

# 网络结构:X(30x1)*w1(1x25)+b1(1*25) = hidden_layer(30x25)

# hidden_layer(30x25)*w2(25x1)+b2(30x1) = output(30x1)

# X->hidden_layer->output

dateNormal = np.zeros([30,1])

priceNormal = np.zeros([30,1])

#归一化

for i in range(0,30):

dateNormal[i,0] = i/29.0;

priceNormal[i,0] = endPrice[i]/3000.0;

x = tf.placeholder(tf.float32,[None,1])

y = tf.placeholder(tf.float32,[None,1])

# X->hidden_layer

w1 = tf.Variable(tf.random_uniform([1,25],0,1))

b1 = tf.Variable(tf.zeros([1,25]))

wb1 = tf.matmul(x,w1)+b1

layer1 = tf.nn.relu(wb1) # 激励函数

# hidden_layer->output

w2 = tf.Variable(tf.random_uniform([25,1],0,1))

b2 = tf.Variable(tf.zeros([30,1]))

wb2 = tf.matmul(layer1,w2)+b2

layer2 = tf.nn.relu(wb2)

loss = tf.reduce_mean(tf.square(y-layer2)) #y为真实数据, layer2为网络预测结果

#梯度下降

train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

withtf.Session() as sess:

sess.run(tf.global_variables_initializer())

for i in range(0,20000):

sess.run(train_step,feed_dict={x:dateNormal,y:priceNormal})

#预测, X w1w2 b1b2 -->layer2

pred = sess.run(layer2,feed_dict={x:dateNormal})

predPrice = np.zeros([30,1])

for i in range(0,30):

predPrice[i,0]=(pred*3000)[i,0]

plt.plot(date,predPrice,'b',lw=1)

plt.show()

03

运行结果

运行以上代码可视化神经网络的预测结果如下图所示。

▍可视化股票价格预测结果

04

扫码,微店限时优惠

猜你喜欢

转载自blog.csdn.net/weixin_46579013/article/details/129089979