简单的神经网络拟合股票价格
步骤:
- 准备数据
- 分析涨跌情况
- 绘制不同颜色的股价折线图
- 归一化数据
- 计算输入层-隐藏层-输出层
- 计算loss
- 训练
- 预测
- 绘制预测股价的蓝色折线
# 简单的神经网络,非卷积网络
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# 股票开收盘: 9:00-15:00
# 1 准备数据 1~15一共15个数据
date = np.linspace(1, 15, 15)
endPrice = np.array([2511.90,2538.26,2510.68,2591.66,2732.98,2701.69,2701.29,2678.67,2726.50,2681.50,2739.17,2715.07,2823.58,2864.90,2919.08])
beginPrice = np.array([2438.71,2500.88,2534.95,2512.52,2594.04,2743.26,2697.47,2695.24,2678.23,2722.13,2674.93,2744.13,2717.46,2832.73,2877.40])
print(date)
# 2 分析涨跌情况
# 准备画板
plt.figure()
for i in range(0, 15):
# 柱状图
dateOne = np.zeros([2])
dateOne[0] = i
dateOne[1] = i
priceOne = np.zeros([2])
priceOne[0] = beginPrice[i]
priceOne[1] = endPrice[i]
# 3 绘制实际股价的折线图
if endPrice[i] > beginPrice[i]:
# 股价上涨
plt.plot(dateOne, priceOne, 'r', lw = 8)
else:
# 股价下跌
plt.plot(dateOne, priceOne, 'g', lw = 8)
# 最简单的神经网络
# 输入层(15*1)-> 隐藏层(1*10)-> 输出层(15*1) [矩阵]
# w1 w2 b1 b2
# 梯度下降法给出新的w1 w2 b1 b2,减少误差
# 终止条件:for count 或 误差满足要求
# 输入天数,输出每天股价
# A(15*1) * 权重w1(1*10) + 偏置b1(1*10) = B(15*10) b1: 1*10
# B(15*10) * 权重w2(10*1) + 偏置b2(15*1) = C(15*1)
# 4 归一化数据 date与price归一化为维度相对应
dateNormal = np.zeros([15, 1])
priceNormal = np.zeros([15, 1])
for i in range(0, 15): # 一共15天
# i+1行1列
dateNormal[i, 0] = i / 14.0
priceNormal[i, 0] = endPrice[i] / 3000.0
# 5 计算A、B、C三层
# A(15*1) B(15*10) C(15*1)
# A 输入层 N*1 设置x、y的占位符
x = tf.placeholder(tf.float32, [None, 1])
y = tf.placeholder(tf.float32, [None, 1])
# 变量,随机产生的均匀分布的1*10的矩阵,在0~10之间变化,
w1 = tf.Variable(tf.random_uniform([1, 10], 0, 1))
b1 = tf.Variable(tf.zeros([1, 10]))
# B 隐藏层
wb1 = tf.matmul(x, w1) + b1
layer1 = tf.nn.relu(wb1) # 激励函数
# C 输出层
w2 = tf.Variable(tf.random_uniform([10, 1], 0, 1))
b2 = tf.Variable(tf.zeros([15, 1]))
wb2 = tf.matmul(layer1, w2) + b2
# 6 计算loss
# 简单的映射
layer2 = tf.nn.relu(wb2)
# 计算标准差 求平方后求均值 reduce_mean:求沿某一维度上的平均值
loss = tf.reduce_mean(tf.square(y - layer2)) # y:真实值 layer2:计算值
# 7 train
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(0, 10000):
sess.run(train_step, feed_dict = {x:dateNormal, y: priceNormal})
# 8 预测
# w1w2 b1b2 A + wb-> layer2
pred = sess.run(layer2, feed_dict = {x:dateNormal})
predPrice = np.zeros([15, 1])
for i in range(0, 15):
predPrice[i, 0] = (pred * 3000)[i, 0]
# 9 绘制预测股价的蓝色折线
plt.plot(date, predPrice, 'b', lw = 1)
# 显示图表
plt.show()
日期数据与绘制的拟合实际数据的图表如下:
image.png
网友评论