1,线性预测
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
import matplotlib.dates as md
# 日期转换函数
def dmy2ymd(dmy):
dmy = str(dmy, encoding='utf-8')
time = dt.datetime.strptime(dmy, '%d-%m-%Y').date()
t = time.strftime('%Y-%m-%d')
return t
# 加载文件
dates, opening_prices, highest_prices, lowest_prices, closing_prices = \
np.loadtxt('data/da_data/aapl.csv',
delimiter=',',
usecols=(1, 3, 4, 5, 6),
dtype='M8[D], f8, f8, f8, f8',
unpack=True,
converters={1: dmy2ymd} # 日期转换
)
# print(dates)
plt.figure('aapl', facecolor='grey')
plt.title('aapl', fontsize=20)
plt.grid(linestyle=':')
plt.xlabel('date', fontsize=14)
plt.ylabel('closing_prices', fontsize=14)
ax = plt.gca()
# 刻度主定位器
ax.xaxis.set_major_locator(md.WeekdayLocator(byweekday=md.MO))
ax.xaxis.set_major_formatter(md.DateFormatter('%Y/%m/%d'))
# # 刻度次定位器
ax.xaxis.set_minor_locator(md.DayLocator())
plt.tick_params(labelsize=8)
dates = dates.astype(md.datetime.datetime)
plt.plot(dates, closing_prices, linewidth=2, linestyle='--', label='closing_price')
# 线性预测,三元
N = 3
pred = np.zeros(closing_prices.size-2*N)
for j in range(pred.size):
A = np.zeros((N, N))
for i in range(3):
A[i:] = closing_prices[i+j: i+j+N]
B = closing_prices[j+N: j+N*2]
# 采用最小二乘求参
x = np.linalg.lstsq(A, B)[0]
# print(x)
pred[j] = B.dot(x)
# print(pred[j], closing_prices[5+j])
plt.plot(dates[2*N:], pred, 'o-', label='pred')
plt.gcf().autofmt_xdate()
plt.legend()
plt.show()
2.线性拟合
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
import matplotlib.dates as md
# 日期转换函数
def dmy2ymd(dmy):
dmy = str(dmy, encoding='utf-8')
time = dt.datetime.strptime(dmy, '%d-%m-%Y').date()
t = time.strftime('%Y-%m-%d')
return t
# 加载文件
dates, opening_prices, highest_prices, lowest_prices, closing_prices = \
np.loadtxt('data/da_data/aapl.csv',
deli