在p-quant中,线性回归应该是最最最重要的统计方法了,没有之一;OLS又是线性回归中最常见的形式,在python中可以利用多个方法来实现
考虑线性回归如下形式
一、sklearn
from sklearn import linear_model
import numpy as np
factor_n = 3
sample_n = 50
np.random.seed(100)
x = np.random.rand(sample_n, factor_n)
sigma = np.random.normal(size=sample_n)
y = 5 * x[:, 0] + 10 * x[:, 1] - 8 * x[:, 2] + 0.5 * sigma
model = linear_model.LinearRegression().fit(x, y)
print("sklearn.linear_model")
print(model.intercept_)
print(model.coef_)
二、statasmodel
sklearn中会自动加常数项,statasmodel需要主动调用add_constant
import statsmodels.api as sm
x_add = sm.add_constant(x)
model = sm.OLS(y, x_add).fit()
print("statsmodel.api.OLS:", model.params[:])