线性模型分为两种:线性预测和线性拟合,这两种都可以起到预测走势和数据点的作用,当然,预测是存在一定误差的,因此这种预测图像仅供参考。
一、线性预测
1、基本概念
线性预测(a*x=b)
/a b c\ /A\ / d \
|b c d| X | B | = | e |
\c d e/ \C/ \ f /
2、numpy进行预测的函数
- numpy.linalg.lstsq(a, b)
需要预测的就是x
3、价格预测案例
import datetime as dt
import numpy as np
import matplotlib.pylab as mp
import matplotlib.dates as md
import pandas as pd # 日期计算
def dmy2ymd(dmy):
dmy = str(dmy, encoding='utf-8') # 转码dmy日期
date = dt.datetime.strptime(dmy, '%d-%m-%Y').date() # 获取时间对象
ymd = date.strftime('%Y-%m-%d')
return ymd
dates, closing_prices = np.loadtxt(
'0=数据源/beer_price.csv', delimiter=',',
usecols=(0, 4), unpack=True,
dtype=np.dtype('M8[D], f8'),
converters={
0: dmy2ymd}
)
'''
收盘价格预测
'''
N = 5 # 最开始是数组是2*N个,
# 初始化预测价格
pred_prices = np.zeros(closing_prices.size - 2*N + 1) # 2*N是表示无法预测的
# 给预测价格数组填入职
for i in range(pred_prices.size):
a = np.zeros((N, N)) # 初始化N*N的矩阵
# a[0, ] = closing_prices[0: 5] # a的第0行,对应收盘价的0到5个元素
# a[1, ] = closing_prices[1: 6]
# a[2, ] = closing_prices[2: 7]
# 得到a矩阵:用循环表示以上的效果
for j in range(N):
a[j, ] = closing_prices[i+j: i+j+N] # +i表示跟上起点位置
# 得到b向量
b = closing_prices[i+N: i+N*2]
x = np.linalg.lstsq(a, b)[0] # 第0个值才是解方程的根
pred_prices[i] = b.dot(x)