请完成以下任务:
import yfinance as yf
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
# 因子数据获取(五因子模型)
ff5 = yf.download('F-F_Research_Data_5_Factors_2x3', start='2020-01-01', end='2023-12-31')['Adj Close']
# 个股数据获取
tech_stocks = yf.download(['BABA', 'NVDA'], start='2020-01-01', end='2023-12-31')['Adj Close']
tech_returns = tech_stocks.pct_change().dropna()
# 数据对齐处理(注意时区问题)
combined_data = pd.concat([tech_returns, ff5], axis=1).dropna()
请实现以下要求:
from scipy.optimize import minimize
import numpy as np
# 获取因子暴露数据示例
factor_exposures = pd.DataFrame({
'AAPL': [1.2, 0.8],
'MSFT': [0.9, 0.6],
'TSLA': [1.5, 1.1]
}, index=['Mkt-RF', 'Mom']).T
def multi_factor_neutral(benchmark_exposures):
n_assets = len(factor_exposures)
init_weights = np.ones(n_assets)/n_assets
def objective(w):
return np.sum(w**2) # 最小化组合波动
constraints = (
{'type': 'eq', 'fun': lambda w: w @ factor_exposures.values - benchmark_exposures},
{'type': 'eq', 'fun': lambda w: np.sum(w)-1}
)
bounds = [(0,0.4) for _ in range(n_assets)]
res = minimize(objective, init_weights,
constraints=constraints, bounds=bounds)
return res.x
# 目标因子暴露(全市场中性)
target_exposures = [0, 0] # 市场因子和动量因子均为中性