多项式回归过拟合诊断#
问题:
使用yfinance获取微软(MSFT)2022年日频收盘价数据,完成以下任务:
-
将时间序列转换为特征矩阵(时间戳数值化处理)
-
拟合3次和9次多项式回归模型预测股价
-
绘制学习曲线分析模型过拟合情况
-
计算两个模型的样本外MAPE误差(向前预测10天)
Python答题框架:
code
import yfinance as yf
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_absolute_percentage_error
# 数据获取与处理
msft = yf.download(...)[...]
dates = (...)
prices = (...)
# 划分训练集和测试集
split_idx = int(len(dates)*0.8)
X_train, X_test = (...)
y_train, y_test = (...)
# 多项式特征转换
poly3 = PolynomialFeatures(degree=3)
X_poly3 = poly3.fit_transform(...)
poly9 = PolynomialFeatures(degree=9)
X_poly9 = poly9.fit_transform(...)
# 模型训练
model3 = LinearRegression().fit(...)
model9 = (...)正则化效果对比#
问题:
使用标普500成分股中10只科技股2023年数据(AAPL/MSFT/GOOG等):
-
以SPY收益率为基准,构建个股收益率的多因子模型
-
分别使用OLS、Ridge、Lasso回归拟合模型
-
比较三种方法在训练集和测试集的R²差异
-
可视化各模型系数绝对值大小
Python答题框架:
code
from sklearn.linear_model import Ridge, Lasso
# 获取多资产数据
symbols = ['AAPL','MSFT','GOOG','SPY',...]
data = yf.download(...)[...]
returns = (...)
# 设置特征和标签
X = (...)
y = (...)
# 划分数据集
X_train, X_test, y_train, y_test = (...)
# 模型训练
models = {
'OLS': LinearRegression(),
'Ridge': Ridge(alpha=0.5),
'Lasso': Lasso(alpha=0.1)
}
for name, model in models.items():
...
# 系数对比可视化
...数据示例说明:
多因子模型输入矩阵示例:
| Date | SPY_ret | AAPL_ret | MSFT_ret | ... |
|---|---|---|---|---|
| 2023-01-03 | 0.012 | 0.018 | -0.005 | ... |
| 2023-01-04 | -0.007 | 0.003 | 0.011 | ... |
正则化模型系数输出示例:
| 股票代码 | OLS系数 | Ridge系数 | Lasso系数 |
|---|---|---|---|
| AAPL | 1.32 | 1.28 | 0.95 |
| MSFT | 0.87 | 0.83 | 0.00 |
提示:Lasso回归会产生稀疏解,注意设置合适的alpha参数