问题:
使用yfinance获取微软(MSFT)2022年日频收盘价数据,完成以下任务:
Python答题框架:
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等):
Python答题框架:
from sklearn.linear_model import Ridge, Lasso
# 获取多资产数据
symbols = ['AAPL','MSFT','GOOG','SPY',...]
data = yf.download(...)[...]
returns = (...计算收益率...)
# 设置特征和标签
X = (...SPY和其他个股收益率...)
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():
(...训练并记录R²...)
# 系数对比可视化
(...绘制系数绝对值柱状图...)
数据示例说明:
多因子模型输入矩阵示例:
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参数