利用线性回归方程的最小二乘函数对一个或多个自变量和因变量之间的关系进行建模的方法。
线性回归代价函数 |损失函数
库
from sklearn.linear_model import LinearRegression
from sklearn import preprocessing
训练 & 评估
lr = LinearRegression()
lr.fit(X_train, y_train)
lr.score(X_test, y_test) # 使用绝对系数 R^2
预测
Forecast = lr.predict(X_Predict)
股票预测
预处理:
库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime as dt
获取数据
import tushare as ts
df = ts.get_hist_data('000001') #平安银行代码 000001
df.to_csv('000001.csv')
df = pd.read_csv('./000001.csv')
股票数据的特征
将每一个数据的键值的类型从字符串转为日期
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')
# 按照时间升序排列
df.sort_values(by=['date'], inplace=True, ascending=True)
缺失值检测
df.dropna(axis=0 , inplace=True)
df.isna().sum()
绘制K线图:
Min_date = df.index.min()
Max_date = df.index.max()
print ("First date is",Min_date)
print ("Last date is",Max_date)
print (Max_date - Min_date)
from plotly import tools
from plotly.graph_objs import *
from plotly.offline import init_notebook_mode, iplot, iplot_mpl
init_notebook_mode()
import plotly.plotly as py
import plotly.graph_objs as go
trace = go.Ohlc(x=df.index, open=df['open'], high=df['high'], low=df['low'], close=df['close'])
data = [trace]
iplot(data, filename='simple_ohlc')
线性回归部分 库
from sklearn.linear_model import LinearRegression
from sklearn import preprocessing
创建新的列, 包含预测值, 根据当前的数据预测5天以后的收盘价
num = 5 # 预测5天后的情况
df['label'] = df['close'].shift(-num) # 预测值
丢弃 label
, price_change
, p_change
, 不需要它们做预测
Data = df.drop(['label', 'price_change', 'p_change'],axis=1)
X = Data.values
X = preprocessing.scale(X)
X = X[:-num]
df.dropna(inplace=True)#去掉缺失值所在的行
Target = df.label
y = Target.values
将数据分为训练数据和测试数据
X_train, y_train = X[0:550, :], y[0:550]
X_test, y_test = X[550:, -51:], y[550:606]
训练 & 评估
lr = LinearRegression()
lr.fit(X_train, y_train)
lr.score(X_test, y_test) #训练好的lr 投喂 X_test得到 pred_test 与 y_test 做评估,越大越好
# 预测
X_Predict = X[-num:] #取最后 num 条数据
Forecast = lr.predict(X_Predict)
画图 预测结果 预测 2019-05-13 到 2019-05-17 , 一共 5 天的收盘价
trange = pd.date_range('2019-05-13', periods=num, freq='d')
产生预测值
Predict_df = pd.DataFrame(Forecast, index=trange)
Predict_df.columns = ['forecast']
将预测值添加到原始
df = pd.read_csv('./000001.csv')
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')
按照时间升序排列
df.sort_values(by=['date'], inplace=True, ascending=True)
df_concat = pd.concat([df, Predict_df], axis=1)
df_concat = df_concat[df_concat.index.isin(Predict_df.index)]
df_concat.tail(num)
画预测值和实际值
df_concat['close'].plot(color='green', linewidth=1)
df_concat['forecast'].plot(color='orange', linewidth=3)
plt.xlabel('Time')
plt.ylabel('Price')
plt.show()
理解模型
for idx, col_name in enumerate(['open', 'high', 'close', 'low', 'volume', 'ma5', 'ma10', 'ma20', 'v_ma5', 'v_ma10', 'v_ma20']):
print("The coefficient for {} is {}".format(col_name, lr.coef_[idx]))