| | |
| | | DEFAULT_CANDIDATE_COUNT = 20 |
| | | DEFAULT_FINAL_SELECTION_COUNT = 10 |
| | | DEFAULT_MAX_DRAWDOWN_PCT = -40.0 |
| | | DEFAULT_ML_MODEL_PATH = PROJECT_ROOT / 'models' / 'ml_factor_combiner.pkl' |
| | | |
| | | |
| | | def load_approved_ml_combiner( |
| | | model_path: Path = DEFAULT_ML_MODEL_PATH, |
| | | ): |
| | | """加载本机已通过样本外验证的独立二次排序模型。""" |
| | | if not ML_COMBINER_AVAILABLE: |
| | | return None, '组件不可用' |
| | | |
| | | model_path = Path(model_path) |
| | | if not model_path.exists(): |
| | | return None, '未找到已通过验证的模型,请先训练' |
| | | |
| | | try: |
| | | combiner = MLFactorCombiner.load(model_path) |
| | | promotion_status = getattr( |
| | | combiner, |
| | | 'training_metadata', |
| | | {}, |
| | | ).get('promotion_status') |
| | | if promotion_status != 'approved': |
| | | return None, '模型未通过样本外验证,请重新训练' |
| | | return combiner, '模型已加载,等待二次排序' |
| | | except Exception as error: |
| | | logger.warning(f"⚠️ 独立ML模型加载失败: {error}") |
| | | return None, f'模型加载失败: {error}' |
| | | |
| | | |
| | | def infer_stock_market(stock_code: str) -> str: |
| | |
| | | df = df.copy() |
| | | if 'date' in df.columns: |
| | | df = df.sort_values(['stock_code', 'date']) |
| | | # 主要使用5日收益 |
| | | df['return_1d'] = df.groupby('stock_code')['close'].pct_change().shift(-1) |
| | | df['return_5d'] = df.groupby('stock_code')['close'].pct_change(5).shift(-5) |
| | | grouped_close = df.groupby('stock_code', sort=False)['close'] |
| | | # 在每只股票内部直接计算未来收益,避免股票边界串值。 |
| | | df['return_1d'] = grouped_close.transform( |
| | | lambda prices: prices.shift(-1) / prices - 1 |
| | | ) |
| | | df['return_5d'] = grouped_close.transform( |
| | | lambda prices: prices.shift(-5) / prices - 1 |
| | | ) |
| | | df['return_target'] = df['return_5d'] # 默认使用5日收益 |
| | | return df |
| | | |
| | |
| | | self.report_generator = EnhancedReportGenerator() |
| | | |
| | | if ML_COMBINER_AVAILABLE: |
| | | self.ml_combiner = MLFactorCombiner(model_type='gbdt') |
| | | logger.info("✓ ML因子组合器已加载") |
| | | self.ml_combiner, model_status = load_approved_ml_combiner() |
| | | if self.ml_combiner is not None: |
| | | logger.info("✓ 已加载通过样本外验证的ML因子组合模型") |
| | | else: |
| | | logger.warning(f"⚠️ {model_status}") |
| | | else: |
| | | self.ml_combiner = None |
| | | model_status = '组件不可用' |
| | | logger.warning("⚠️ ML因子组合器不可用") |
| | | self.ml_model_status = model_status |
| | | self.ml_optimization_applied = False |
| | | self.ml_optimization_status = ( |
| | | '未应用(独立二次排序模型尚未训练)' |
| | | if self.ml_combiner is not None |
| | | else '未应用(组件不可用)' |
| | | ) |
| | | self.ml_optimization_status = f'未应用({model_status})' |
| | | self.enhanced_factor_status = '未运行' |
| | | self.enhanced_ml_metrics = {} |
| | | self.dynamic_weight_status = '未应用' |
| | |
| | | """使用ML因子组合优化选股结果""" |
| | | self.ml_optimization_applied = False |
| | | if self.ml_combiner is None: |
| | | logger.warning("⚠️ ML组合器不可用,跳过优化") |
| | | self.ml_optimization_status = '未应用(组件不可用)' |
| | | model_status = getattr( |
| | | self, |
| | | 'ml_model_status', |
| | | '组件不可用', |
| | | ) |
| | | logger.warning(f"⚠️ {model_status},跳过ML优化") |
| | | self.ml_optimization_status = f'未应用({model_status})' |
| | | return selected_stocks |
| | | |
| | | if not getattr(self.ml_combiner, 'is_fitted', False): |
| | |
| | | logger.info("🤖 ML因子组合优化...") |
| | | |
| | | try: |
| | | factor_cols = [col for col in df.columns if col not in |
| | | ['date', 'stock_code', 'stock_name', 'close', 'open', 'high', 'low', |
| | | 'volume', 'amount', 'return_1d', 'return_5d', 'return_20d']] |
| | | |
| | | factor_cols = list(getattr(self.ml_combiner, 'feature_names', [])) |
| | | if not factor_cols: |
| | | logger.warning("⚠️ 未找到因子列,跳过ML优化") |
| | | self.ml_optimization_status = '未应用(无可用因子)' |
| | | logger.warning("⚠️ 模型未记录因子结构,跳过ML优化") |
| | | self.ml_optimization_status = '未应用(模型因子结构缺失)' |
| | | return selected_stocks |
| | | |
| | | missing_factors = [ |
| | | factor for factor in factor_cols |
| | | if factor not in df.columns |
| | | ] |
| | | if missing_factors: |
| | | logger.warning( |
| | | f"⚠️ 当日数据缺少{len(missing_factors)}个模型因子,跳过ML优化" |
| | | ) |
| | | self.ml_optimization_status = ( |
| | | f'未应用(缺少模型因子: {", ".join(missing_factors[:3])})' |
| | | ) |
| | | return selected_stocks |
| | | |
| | | selected_codes = [s['stock_code'] for s in selected_stocks] |
| | | selected_codes = [ |
| | | str(s['stock_code']).zfill(6) |
| | | for s in selected_stocks |
| | | ] |
| | | working_df = df.copy() |
| | | working_df['stock_code'] = ( |
| | | working_df['stock_code'].astype(str).str.zfill(6) |
| | | ) |
| | | latest_date = df['date'].max() if 'date' in df.columns else None |
| | | |
| | | if latest_date: |
| | | latest_df = df[df['date'] == latest_date] |
| | | if latest_date is not None and pd.notna(latest_date): |
| | | latest_df = working_df[working_df['date'] == latest_date] |
| | | else: |
| | | latest_df = df |
| | | latest_df = working_df |
| | | |
| | | factor_data = latest_df[latest_df['stock_code'].isin(selected_codes)][['stock_code'] + factor_cols] |
| | | factor_data = latest_df[ |
| | | latest_df['stock_code'].isin(selected_codes) |
| | | ][['stock_code'] + factor_cols] |
| | | |
| | | if len(factor_data) == 0: |
| | | logger.warning("⚠️ 因子数据为空,跳过ML优化") |
| | | self.ml_optimization_status = '未应用(因子数据为空)' |
| | | return selected_stocks |
| | | |
| | | factor_data = factor_data.set_index('stock_code') |
| | | factor_data = factor_data.fillna(0) |
| | | factor_data = ( |
| | | factor_data.drop_duplicates(subset=['stock_code'], keep='last') |
| | | .set_index('stock_code') |
| | | ) |
| | | |
| | | ml_scores = self.ml_combiner.predict(factor_data) |
| | | |
| | | if ml_scores is not None and len(ml_scores) > 0: |
| | | ml_rank_scores = ml_scores.rank(method='average', pct=True) |
| | | for stock in selected_stocks: |
| | | code = stock['stock_code'] |
| | | code = str(stock['stock_code']).zfill(6) |
| | | if code in ml_scores.index: |
| | | stock['ml_score'] = float(ml_scores.loc[code]) |
| | | stock['combined_score'] = 0.6 * stock.get('score', 0) + 0.4 * stock.get('ml_score', 0) |
| | | stock['ml_rank_score'] = float(ml_rank_scores.loc[code]) |
| | | stock['combined_score'] = ( |
| | | 0.6 * stock.get('score', 0) |
| | | + 0.4 * stock['ml_rank_score'] |
| | | ) |
| | | else: |
| | | stock['ml_score'] = 0 |
| | | stock['ml_rank_score'] = 0 |
| | | stock['combined_score'] = stock.get('score', 0) |
| | | |
| | | selected_stocks = sorted(selected_stocks, key=lambda x: x.get('combined_score', 0), reverse=True) |