log
2026-07-23 c9a0711438d32f33b65ffa29d8efd7aa37d61bdc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#!/usr/bin/env python3
"""
ML因子组合模块
借鉴Qlib的机器学习因子组合方法
"""
 
import os
import pickle
from pathlib import Path
from typing import Dict, List
 
import numpy as np
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:
    """机器学习因子组合器"""
    
    def __init__(
        self,
        model_type: str = 'gbdt',
        n_estimators: int = 100,
        max_depth: int = 3,
        learning_rate: float = 0.1,
        regularization: float = 0.1
    ):
        """
        初始化ML因子组合器
        
        Args:
            model_type: 模型类型 ('gbdt', 'rf', 'ridge', 'lasso')
            n_estimators: 树模型数量
            max_depth: 树最大深度
            learning_rate: 学习率
            regularization: 正则化系数
        """
        self.model_type = model_type
        self.n_estimators = n_estimators
        self.max_depth = max_depth
        self.learning_rate = learning_rate
        self.regularization = regularization
        
        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):
        """创建模型"""
        if self.model_type == 'gbdt':
            return GradientBoostingRegressor(
                n_estimators=self.n_estimators,
                max_depth=self.max_depth,
                learning_rate=self.learning_rate,
                subsample=0.8,
                random_state=42
            )
        elif self.model_type == 'rf':
            return RandomForestRegressor(
                n_estimators=self.n_estimators,
                max_depth=self.max_depth,
                random_state=42,
                n_jobs=-1
            )
        elif self.model_type == 'ridge':
            return Ridge(alpha=self.regularization)
        elif self.model_type == 'lasso':
            return Lasso(alpha=self.regularization)
        else:
            return GradientBoostingRegressor(
                n_estimators=self.n_estimators,
                max_depth=self.max_depth,
                learning_rate=self.learning_rate,
                random_state=42
            )
    
    def fit(
        self,
        factor_exposures: pd.DataFrame,
        future_returns: pd.Series,
        validate: bool = True
    ) -> Dict:
        """
        训练模型
        
        Args:
            factor_exposures: 因子暴露 DataFrame (index: stock_code, columns: factors)
            future_returns: 未来收益率 Series
            validate: 是否进行交叉验证
            
        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': '样本量不足'}
        
        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)
        
        self.model = self._create_model()
        
        cv_scores = []
        if validate and len(X) >= 100:
            tscv = TimeSeriesSplit(n_splits=5)
            cv_scores = cross_val_score(
                make_pipeline(StandardScaler(), self._create_model()),
                X,
                y,
                cv=tscv, 
                scoring='neg_mean_squared_error'
            )
            cv_scores = -cv_scores
        
        self.model.fit(X_scaled, y)
        self.is_fitted = True
        
        if hasattr(self.model, 'feature_importances_'):
            self.feature_importance = dict(zip(
                self.feature_names,
                self.model.feature_importances_
            ))
        elif hasattr(self.model, 'coef_'):
            self.feature_importance = dict(zip(
                self.feature_names,
                np.abs(self.model.coef_)
            ))
        
        y_pred = self.model.predict(X_scaled)
        mse = mean_squared_error(y, y_pred)
        mae = mean_absolute_error(y, y_pred)
        
        return {
            'success': True,
            'n_samples': len(X),
            'mse': round(mse, 6),
            'mae': round(mae, 6),
            'cv_mse_mean': round(np.mean(cv_scores), 6) if len(cv_scores) > 0 else None,
            'cv_mse_std': round(np.std(cv_scores), 6) if len(cv_scores) > 0 else None,
            'feature_importance': self.feature_importance
        }
    
    def predict(self, factor_exposures: pd.DataFrame) -> pd.Series:
        """
        预测收益率
        
        Args:
            factor_exposures: 因子暴露 DataFrame
            
        Returns:
            预测收益率 Series
        """
        if not self.is_fitted:
            raise ValueError("模型尚未训练")
 
        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]:
        """
        获取因子权重(基于特征重要性)
        
        Returns:
            因子权重字典
        """
        if not self.feature_importance:
            return {}
        
        total = sum(self.feature_importance.values())
        if total == 0:
            return {k: 1.0/len(self.feature_importance) for k in self.feature_importance}
        
        return {k: v/total for k, v in self.feature_importance.items()}
 
 
class EnsembleFactorCombiner:
    """集成因子组合器"""
    
    def __init__(self, models: List[str] = None):
        """
        初始化集成因子组合器
        
        Args:
            models: 模型类型列表
        """
        self.models = models or ['gbdt', 'rf', 'ridge']
        self.combiners = {}
        self.weights = {}
        
        for model_type in self.models:
            self.combiners[model_type] = MLFactorCombiner(model_type=model_type)
    
    def fit(
        self,
        factor_exposures: pd.DataFrame,
        future_returns: pd.Series
    ) -> Dict:
        """
        训练所有模型
        
        Args:
            factor_exposures: 因子暴露
            future_returns: 未来收益率
            
        Returns:
            训练结果
        """
        results = {}
        performances = {}
        
        for model_type, combiner in self.combiners.items():
            result = combiner.fit(factor_exposures, future_returns)
            results[model_type] = result
            
            if result['success']:
                performances[model_type] = result.get('cv_mse_mean', result.get('mse', 1))
        
        if performances:
            min_perf = min(performances.values())
            inv_perfs = {k: min_perf/v for k, v in performances.items()}
            total = sum(inv_perfs.values())
            self.weights = {k: v/total for k, v in inv_perfs.items()}
        else:
            self.weights = {model: 1.0/len(self.models) for model in self.models}
        
        return {
            'model_results': results,
            'ensemble_weights': self.weights
        }
    
    def predict(self, factor_exposures: pd.DataFrame) -> pd.Series:
        """
        集成预测
        
        Args:
            factor_exposures: 因子暴露
            
        Returns:
            预测收益率
        """
        predictions = pd.Series(0.0, index=factor_exposures.index)
        
        for model_type, combiner in self.combiners.items():
            if combiner.is_fitted:
                pred = combiner.predict(factor_exposures)
                predictions += self.weights[model_type] * pred
        
        return predictions
    
    def get_factor_weights(self) -> Dict[str, float]:
        """
        获取集成因子权重
        
        Returns:
            因子权重字典
        """
        all_weights = {}
        
        for model_type, combiner in self.combiners.items():
            if combiner.is_fitted:
                weights = combiner.get_factor_weights()
                for factor, weight in weights.items():
                    if factor not in all_weights:
                        all_weights[factor] = 0
                    all_weights[factor] += self.weights[model_type] * weight
        
        return all_weights
 
 
if __name__ == "__main__":
    print("=" * 60)
    print("ML因子组合模块测试")
    print("=" * 60)
    
    np.random.seed(42)
    n_stocks = 200
    n_factors = 10
    
    factor_data = pd.DataFrame(
        np.random.randn(n_stocks, n_factors),
        columns=[f'factor_{i}' for i in range(n_factors)],
        index=[f'stock_{i:04d}' for i in range(n_stocks)]
    )
    
    true_weights = np.random.randn(n_factors)
    returns = factor_data.values @ true_weights + np.random.randn(n_stocks) * 0.1
    future_returns = pd.Series(returns, index=factor_data.index)
    
    combiner = MLFactorCombiner(model_type='gbdt')
    result = combiner.fit(factor_data, future_returns)
    
    print(f"\n【训练结果】")
    print(f"  成功: {result['success']}")
    print(f"  样本量: {result['n_samples']}")
    print(f"  MSE: {result['mse']}")
    print(f"  MAE: {result['mae']}")
    
    print(f"\n【因子权重】")
    weights = combiner.get_factor_weights()
    for factor, weight in sorted(weights.items(), key=lambda x: -x[1]):
        print(f"  {factor}: {weight:.4f}")
    
    print("\n【集成模型测试】")
    ensemble = EnsembleFactorCombiner(models=['gbdt', 'rf', 'ridge'])
    ensemble_result = ensemble.fit(factor_data, future_returns)
    
    print(f"  模型权重: {ensemble_result['ensemble_weights']}")
    print(f"  集成因子权重: {ensemble.get_factor_weights()}")