| | |
| | | 借鉴Qlib的机器学习因子组合方法 |
| | | """ |
| | | |
| | | import pandas as pd |
| | | import os |
| | | import pickle |
| | | from pathlib import Path |
| | | from typing import Dict, List |
| | | |
| | | import numpy as np |
| | | from typing import Dict, List, Optional, Tuple |
| | | import pandas as pd |
| | | from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor |
| | | from sklearn.linear_model import Ridge, Lasso |
| | | from sklearn.model_selection import TimeSeriesSplit, cross_val_score |
| | | from sklearn.pipeline import make_pipeline |
| | | from sklearn.preprocessing import StandardScaler |
| | | from sklearn.metrics import mean_squared_error, mean_absolute_error |
| | | import warnings |
| | | warnings.filterwarnings('ignore') |
| | | |
| | | |
| | | MODEL_ARTIFACT_VERSION = 1 |
| | | |
| | | # 只允许使用当日及历史行情可计算的特征,禁止把未来收益、标签或标识列带入模型。 |
| | | DEFAULT_ML_FEATURES = [ |
| | | 'earnings_stability', 'downside_risk_inv', 'drawdown_recovery', |
| | | 'vol_quality', 'vol_stability', 'sharpe_proxy', |
| | | 'momentum_accel', 'momentum_accel_2', 'ma_slope_20', 'ma_slope_60', |
| | | 'price_above_ma20', 'price_above_ma60', 'price_position_20', |
| | | 'price_position_60', 'breakout_20', 'breakout_60', |
| | | 'vol_trend_short', 'vol_trend_long', 'rel_strength_ma60', |
| | | 'turnover_zscore', 'turnover_abnormal', 'amount_zscore', |
| | | 'amount_rel_change', 'amplitude_rel', 'consec_up', 'consec_down', |
| | | 'momentum_20_rank', 'volatility_rank', 'amount_rank', |
| | | 'excess_ret_market', 'excess_ret_industry', 'industry_strength', |
| | | ] |
| | | |
| | | |
| | | class MLFactorCombiner: |
| | |
| | | self.model = None |
| | | self.scaler = StandardScaler() |
| | | self.feature_importance = {} |
| | | self.feature_names = [] |
| | | self.feature_medians = {} |
| | | self.training_metadata = {} |
| | | self.is_fitted = False |
| | | |
| | | def _create_model(self): |
| | |
| | | Returns: |
| | | 训练结果字典 |
| | | """ |
| | | if not isinstance(factor_exposures, pd.DataFrame): |
| | | return {'success': False, 'message': '因子数据格式错误'} |
| | | if factor_exposures.columns.duplicated().any(): |
| | | return {'success': False, 'message': '因子列存在重复名称'} |
| | | |
| | | common_index = factor_exposures.index.intersection(future_returns.index) |
| | | |
| | | if len(common_index) < 50: |
| | | return {'success': False, 'message': '样本量不足'} |
| | | |
| | | X = factor_exposures.loc[common_index].values |
| | | y = future_returns.loc[common_index].values |
| | | |
| | | valid_mask = ~(np.isnan(X).any(axis=1) | np.isnan(y)) |
| | | X = X[valid_mask] |
| | | y = y[valid_mask] |
| | | factor_frame = factor_exposures.loc[common_index].copy() |
| | | target = pd.to_numeric( |
| | | future_returns.loc[common_index], |
| | | errors='coerce', |
| | | ).replace([np.inf, -np.inf], np.nan) |
| | | valid_target = target.notna() |
| | | factor_frame = factor_frame.loc[valid_target] |
| | | target = target.loc[valid_target] |
| | | |
| | | factor_frame = factor_frame.apply(pd.to_numeric, errors='coerce') |
| | | factor_frame = factor_frame.replace([np.inf, -np.inf], np.nan) |
| | | medians = factor_frame.median(axis=0).fillna(0.0) |
| | | factor_frame = factor_frame.fillna(medians).fillna(0.0) |
| | | |
| | | X = factor_frame.values |
| | | y = target.values |
| | | |
| | | if len(X) < 30: |
| | | return {'success': False, 'message': '有效样本不足'} |
| | | |
| | | self.feature_names = list(factor_frame.columns) |
| | | self.feature_medians = { |
| | | name: float(medians[name]) |
| | | for name in self.feature_names |
| | | } |
| | | |
| | | X_scaled = self.scaler.fit_transform(X) |
| | | |
| | |
| | | if validate and len(X) >= 100: |
| | | tscv = TimeSeriesSplit(n_splits=5) |
| | | cv_scores = cross_val_score( |
| | | self.model, X_scaled, y, |
| | | make_pipeline(StandardScaler(), self._create_model()), |
| | | X, |
| | | y, |
| | | cv=tscv, |
| | | scoring='neg_mean_squared_error' |
| | | ) |
| | |
| | | |
| | | if hasattr(self.model, 'feature_importances_'): |
| | | self.feature_importance = dict(zip( |
| | | factor_exposures.columns, |
| | | self.feature_names, |
| | | self.model.feature_importances_ |
| | | )) |
| | | elif hasattr(self.model, 'coef_'): |
| | | self.feature_importance = dict(zip( |
| | | factor_exposures.columns, |
| | | self.feature_names, |
| | | np.abs(self.model.coef_) |
| | | )) |
| | | |
| | |
| | | """ |
| | | if not self.is_fitted: |
| | | raise ValueError("模型尚未训练") |
| | | |
| | | X = factor_exposures.values |
| | | |
| | | if not isinstance(factor_exposures, pd.DataFrame): |
| | | raise TypeError("因子数据必须是DataFrame") |
| | | missing = [ |
| | | name for name in self.feature_names |
| | | if name not in factor_exposures.columns |
| | | ] |
| | | if missing: |
| | | raise ValueError(f"缺少模型因子列: {', '.join(missing)}") |
| | | |
| | | prepared = factor_exposures[self.feature_names].copy() |
| | | prepared = prepared.apply(pd.to_numeric, errors='coerce') |
| | | prepared = prepared.replace([np.inf, -np.inf], np.nan) |
| | | prepared = prepared.fillna(pd.Series(self.feature_medians)).fillna(0.0) |
| | | |
| | | X = prepared.values |
| | | X_scaled = self.scaler.transform(X) |
| | | |
| | | predictions = self.model.predict(X_scaled) |
| | | |
| | | return pd.Series(predictions, index=factor_exposures.index) |
| | | |
| | | def save(self, model_path) -> Path: |
| | | """原子保存本机模型产物。模型目录应被版本控制忽略。""" |
| | | if not self.is_fitted or self.model is None or not self.feature_names: |
| | | raise ValueError("模型尚未完成训练,不能保存") |
| | | |
| | | destination = Path(model_path) |
| | | destination.parent.mkdir(parents=True, exist_ok=True) |
| | | temporary = destination.with_name(f"{destination.name}.tmp") |
| | | payload = { |
| | | 'artifact_version': MODEL_ARTIFACT_VERSION, |
| | | 'combiner': self, |
| | | } |
| | | try: |
| | | with open(temporary, 'wb') as file: |
| | | pickle.dump(payload, file, protocol=pickle.HIGHEST_PROTOCOL) |
| | | os.replace(temporary, destination) |
| | | finally: |
| | | if temporary.exists(): |
| | | temporary.unlink() |
| | | return destination |
| | | |
| | | @classmethod |
| | | def load(cls, model_path): |
| | | """加载由本系统在本机生成的受信任模型文件。""" |
| | | source = Path(model_path) |
| | | with open(source, 'rb') as file: |
| | | payload = pickle.load(file) |
| | | |
| | | if not isinstance(payload, dict): |
| | | raise ValueError("模型文件格式无效") |
| | | if payload.get('artifact_version') != MODEL_ARTIFACT_VERSION: |
| | | raise ValueError("模型文件版本不兼容,请重新训练") |
| | | |
| | | combiner = payload.get('combiner') |
| | | if not isinstance(combiner, cls): |
| | | raise ValueError("模型文件类型无效") |
| | | if ( |
| | | not combiner.is_fitted |
| | | or combiner.model is None |
| | | or not combiner.feature_names |
| | | ): |
| | | raise ValueError("模型文件不完整,请重新训练") |
| | | return combiner |
| | | |
| | | def get_factor_weights(self) -> Dict[str, float]: |
| | | """ |