feat: add validated ML factor model training
2 files added
7 files modified
| | |
| | | scripts/reports/ |
| | | projects/ |
| | | |
| | | # 本机训练产物(模型及验证元数据,不上传) |
| | | models/ |
| | | |
| | | # 报告文件(运行时生成) |
| | | reports/ |
| | | !reports/.gitkeep |
| | |
| | | sys.path.insert(0, str(code_dir)) |
| | | sys.path.insert(0, str(project_root)) |
| | | |
| | | |
| | | def _configure_console_encoding(): |
| | | """避免Windows GBK控制台因特殊符号中断长任务。""" |
| | | for stream in (sys.stdout, sys.stderr): |
| | | reconfigure = getattr(stream, 'reconfigure', None) |
| | | if reconfigure is None: |
| | | continue |
| | | try: |
| | | reconfigure(errors='backslashreplace') |
| | | except (OSError, ValueError): |
| | | pass |
| | | |
| | | |
| | | _configure_console_encoding() |
| | | |
| | | |
| | | class Color: |
| | | """终端颜色""" |
| | | HEADER = '\033[95m' |
| | |
| | | def ml_factor_combiner(): |
| | | """ML因子组合器""" |
| | | print_header("ML因子组合器") |
| | | print_info("功能:使用机器学习方法组合多个因子") |
| | | print_info("功能:训练并验证每日主控使用的独立因子二次排序模型") |
| | | |
| | | try: |
| | | from code.strategy.ml_factor_combiner import MLFactorCombiner |
| | | from scripts.train_ml_factor_model import ( |
| | | load_model_summary, |
| | | train_and_save_model, |
| | | ) |
| | | |
| | | print("\n机器学习方法:") |
| | | print(" • 梯度提升树(默认)") |
| | | print(" • 随机森林") |
| | | print(" • XGBoost") |
| | | print(" • 神经网络") |
| | | print(" • Ridge线性模型") |
| | | |
| | | print("\n选择操作:") |
| | | print("1. 训练模型") |
| | | print("2. 因子重要性分析") |
| | | print("2. 查看模型验证结果和因子重要性") |
| | | print("0. 返回") |
| | | |
| | | choice = input("\n请选择 (0-2): ").strip() |
| | | |
| | | if choice == '1': |
| | | print_info("训练ML因子组合模型...") |
| | | combiner = MLFactorCombiner() |
| | | print_info("需要准备因子数据和标签") |
| | | print("\n选择训练方法:") |
| | | print("1. 梯度提升树(推荐)") |
| | | print("2. 随机森林") |
| | | print("3. Ridge线性模型") |
| | | print("0. 取消") |
| | | model_choice = input("\n请选择 (0-3): ").strip() |
| | | model_types = {'1': 'gbdt', '2': 'rf', '3': 'ridge'} |
| | | if model_choice == '0': |
| | | return |
| | | if model_choice not in model_types: |
| | | print_error("无效的训练方法") |
| | | return |
| | | |
| | | print_info("开始生成因子、时间切分并训练模型...") |
| | | print_info("模型和验证记录只保存在本机 models 目录,不会上传") |
| | | result = train_and_save_model(model_type=model_types[model_choice]) |
| | | metrics = result.get('metrics', {}) |
| | | if metrics: |
| | | ic_mean = metrics.get('ic_mean') |
| | | print("\n样本外验证:") |
| | | print( |
| | | f" IC均值: {ic_mean:.4f}" |
| | | if ic_mean is not None |
| | | else " IC均值: 不可用" |
| | | ) |
| | | print(f" 有效IC天数: {metrics.get('valid_ic_days', 0)}") |
| | | print(f" IC正向率: {metrics.get('ic_positive_rate', 0) or 0:.1%}") |
| | | print(f" MAE: {metrics.get('mae', 0):.6f}") |
| | | |
| | | if result.get('approved'): |
| | | print_success(result['message']) |
| | | print_info("下次运行每日主控时会自动加载该模型") |
| | | elif result.get('success'): |
| | | print_warning(result['message']) |
| | | print_info("候选模型已留在本机,未通过验证前不会参与每日排序") |
| | | if result.get('active_model_preserved'): |
| | | print_info("已有正式模型未被覆盖") |
| | | else: |
| | | print_error(result.get('message', '训练失败')) |
| | | elif choice == '2': |
| | | print_info("因子重要性分析...") |
| | | print("需要加载训练好的模型") |
| | | summary = load_model_summary() |
| | | if not summary: |
| | | print_warning("尚无训练记录,请先选择“训练模型”") |
| | | return |
| | | |
| | | artifact_name = ( |
| | | "正式模型" |
| | | if summary.get('artifact_kind') == 'active' |
| | | else "候选模型" |
| | | ) |
| | | validation = summary.get('validation', {}) |
| | | print(f"\n{artifact_name}:") |
| | | print(f" 方法: {summary.get('model_name', '未知')}") |
| | | print(f" 训练时间: {summary.get('trained_at', '未知')}") |
| | | print( |
| | | f" 验证区间: {summary.get('validation_start_date', '未知')}" |
| | | f" 至 {summary.get('validation_end_date', '未知')}" |
| | | ) |
| | | ic_mean = validation.get('ic_mean') |
| | | print( |
| | | f" 样本外IC均值: {ic_mean:.4f}" |
| | | if ic_mean is not None |
| | | else " 样本外IC均值: 不可用" |
| | | ) |
| | | print(f" 发布状态: {summary.get('promotion_status', '未知')}") |
| | | |
| | | importance = summary.get('feature_importance', {}) |
| | | print("\n重要性最高的因子:") |
| | | if not importance: |
| | | print(" 暂无因子重要性记录") |
| | | else: |
| | | ranked = sorted( |
| | | importance.items(), |
| | | key=lambda item: item[1], |
| | | reverse=True, |
| | | ) |
| | | for index, (factor, weight) in enumerate(ranked[:10], start=1): |
| | | print(f" {index:2d}. {factor}: {weight:.2%}") |
| | | elif choice != '0': |
| | | print_error("无效的选择") |
| | | |
| | | except Exception as e: |
| | | print_error(f"ML因子组合器启动失败: {e}") |
| | |
| | | 借鉴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 |
| | | 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] |
| | | |
| | | valid_mask = ~(np.isnan(X).any(axis=1) | np.isnan(y)) |
| | | X = X[valid_mask] |
| | | y = y[valid_mask] |
| | | 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]: |
| | | """ |
| | | 获取因子权重(基于特征重要性) |
| | |
| | | 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 |
| | | |
| | | selected_codes = [s['stock_code'] for s in 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 = [ |
| | | 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) |
| | |
| | | |
| | | df = df.sort_values(['stock_code', 'date']).reset_index(drop=True) |
| | | |
| | | # 5日收益(主要目标) |
| | | df['return_5d'] = df.groupby('stock_code')['close'].pct_change(5).shift(-5) |
| | | grouped_close = df.groupby('stock_code', sort=False)['close'] |
| | | |
| | | # 10日收益 |
| | | df['return_10d'] = df.groupby('stock_code')['close'].pct_change(10).shift(-10) |
| | | |
| | | # 20日收益 |
| | | df['return_20d'] = df.groupby('stock_code')['close'].pct_change(20).shift(-20) |
| | | # 未来收益必须在每只股票内部计算,避免股票边界串值。 |
| | | df['return_5d'] = grouped_close.transform( |
| | | lambda prices: prices.shift(-5) / prices - 1 |
| | | ) |
| | | df['return_10d'] = grouped_close.transform( |
| | | lambda prices: prices.shift(-10) / prices - 1 |
| | | ) |
| | | df['return_20d'] = grouped_close.transform( |
| | | lambda prices: prices.shift(-20) / prices - 1 |
| | | ) |
| | | |
| | | # 风险调整收益(5日收益/5日波动) |
| | | vol_5 = df.groupby('stock_code')['close'].pct_change().rolling(5).std().reset_index(0, drop=True) |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | """训练、验证并保存每日主控使用的独立ML因子组合模型。""" |
| | | |
| | | import argparse |
| | | import json |
| | | import os |
| | | import pickle |
| | | import sys |
| | | from datetime import datetime |
| | | from pathlib import Path |
| | | from typing import Dict, Optional |
| | | |
| | | import numpy as np |
| | | import pandas as pd |
| | | from sklearn.metrics import mean_absolute_error, mean_squared_error |
| | | |
| | | |
| | | PROJECT_ROOT = Path(__file__).resolve().parents[1] |
| | | sys.path.insert(0, str(PROJECT_ROOT)) |
| | | |
| | | from code.strategy.ml_factor_combiner import ( # noqa: E402 |
| | | DEFAULT_ML_FEATURES, |
| | | MLFactorCombiner, |
| | | ) |
| | | from scripts.enhanced_factor_system import EnhancedFactorSystem # noqa: E402 |
| | | |
| | | |
| | | DEFAULT_DATA_PATH = PROJECT_ROOT / 'data' / 'akshare_real_data_fixed.pkl' |
| | | DEFAULT_MODEL_PATH = PROJECT_ROOT / 'models' / 'ml_factor_combiner.pkl' |
| | | DEFAULT_METADATA_PATH = ( |
| | | PROJECT_ROOT / 'models' / 'ml_factor_combiner_metadata.json' |
| | | ) |
| | | DEFAULT_CANDIDATE_MODEL_PATH = ( |
| | | PROJECT_ROOT / 'models' / 'ml_factor_combiner_candidate.pkl' |
| | | ) |
| | | DEFAULT_CANDIDATE_METADATA_PATH = ( |
| | | PROJECT_ROOT / 'models' / 'ml_factor_combiner_candidate_metadata.json' |
| | | ) |
| | | TARGET_COLUMN = 'return_5d' |
| | | TARGET_HORIZON_DAYS = 5 |
| | | MODEL_NAMES = { |
| | | 'gbdt': '梯度提升树', |
| | | 'rf': '随机森林', |
| | | 'ridge': 'Ridge线性模型', |
| | | 'lasso': 'Lasso线性模型', |
| | | } |
| | | |
| | | |
| | | def _failure(message: str, **details) -> Dict: |
| | | return { |
| | | 'success': False, |
| | | 'approved': False, |
| | | 'message': message, |
| | | **details, |
| | | } |
| | | |
| | | |
| | | def _write_json_atomic(path: Path, payload: Dict) -> None: |
| | | path.parent.mkdir(parents=True, exist_ok=True) |
| | | temporary = path.with_name(f'{path.name}.tmp') |
| | | try: |
| | | with open(temporary, 'w', encoding='utf-8') as file: |
| | | json.dump(payload, file, ensure_ascii=False, indent=2) |
| | | os.replace(temporary, path) |
| | | finally: |
| | | if temporary.exists(): |
| | | temporary.unlink() |
| | | |
| | | |
| | | def load_market_data(data_path: Path = DEFAULT_DATA_PATH) -> pd.DataFrame: |
| | | """读取本地正式行情,不修改原始数据文件。""" |
| | | if not data_path.exists(): |
| | | raise FileNotFoundError(f'行情数据不存在: {data_path}') |
| | | with open(data_path, 'rb') as file: |
| | | data = pickle.load(file) |
| | | if not isinstance(data, pd.DataFrame) or data.empty: |
| | | raise ValueError('行情数据为空或格式不正确') |
| | | return data.copy() |
| | | |
| | | |
| | | def build_factor_dataset(data: pd.DataFrame) -> pd.DataFrame: |
| | | """在内存中生成模型特征和未来5日标签。""" |
| | | required = { |
| | | 'date', 'stock_code', 'close', 'high', 'low', 'volume', |
| | | 'amount', 'turnover', 'change_pct', |
| | | } |
| | | missing = sorted(required.difference(data.columns)) |
| | | if missing: |
| | | raise ValueError(f"行情数据缺少字段: {', '.join(missing)}") |
| | | |
| | | prepared = data.copy() |
| | | prepared['date'] = pd.to_datetime(prepared['date'], errors='coerce') |
| | | prepared['stock_code'] = ( |
| | | prepared['stock_code'].astype(str).str.extract(r'(\d+)', expand=False) |
| | | .fillna('').str.zfill(6) |
| | | ) |
| | | prepared = prepared.dropna(subset=['date']) |
| | | prepared = prepared[prepared['stock_code'].str.fullmatch(r'\d{6}')] |
| | | prepared = prepared.sort_values(['stock_code', 'date']).reset_index(drop=True) |
| | | |
| | | system = EnhancedFactorSystem() |
| | | prepared = system.calculate_target_returns(prepared) |
| | | prepared = system.calculate_quality_factors(prepared) |
| | | prepared = system.calculate_growth_factors(prepared) |
| | | prepared = system.calculate_sentiment_factors(prepared) |
| | | prepared = system.calculate_cross_sectional_factors(prepared) |
| | | return prepared |
| | | |
| | | |
| | | def _prepare_labeled_rows(factor_data: pd.DataFrame) -> pd.DataFrame: |
| | | missing = sorted(set(DEFAULT_ML_FEATURES).difference(factor_data.columns)) |
| | | if missing: |
| | | raise ValueError(f"因子计算结果缺少字段: {', '.join(missing)}") |
| | | |
| | | columns = ['date', 'stock_code', TARGET_COLUMN, *DEFAULT_ML_FEATURES] |
| | | labeled = factor_data[columns].copy() |
| | | labeled[TARGET_COLUMN] = pd.to_numeric( |
| | | labeled[TARGET_COLUMN], |
| | | errors='coerce', |
| | | ) |
| | | labeled[DEFAULT_ML_FEATURES] = ( |
| | | labeled[DEFAULT_ML_FEATURES] |
| | | .apply(pd.to_numeric, errors='coerce') |
| | | .replace([np.inf, -np.inf], np.nan) |
| | | ) |
| | | minimum_available = max(3, int(len(DEFAULT_ML_FEATURES) * 0.6)) |
| | | feature_coverage = labeled[DEFAULT_ML_FEATURES].notna().sum(axis=1) |
| | | labeled = labeled[ |
| | | labeled[TARGET_COLUMN].notna() |
| | | & labeled['date'].notna() |
| | | & (feature_coverage >= minimum_available) |
| | | ] |
| | | return labeled.sort_values(['date', 'stock_code']).copy() |
| | | |
| | | |
| | | def _temporal_split( |
| | | labeled: pd.DataFrame, |
| | | validation_ratio: float = 0.2, |
| | | purge_days: int = TARGET_HORIZON_DAYS, |
| | | ): |
| | | dates = list(pd.Index(labeled['date'].dropna().unique()).sort_values()) |
| | | if len(dates) < 60: |
| | | raise ValueError(f'有效交易日不足: {len(dates)},至少需要60日') |
| | | |
| | | validation_days = max(20, int(np.ceil(len(dates) * validation_ratio))) |
| | | validation_start = len(dates) - validation_days |
| | | training_end = validation_start - purge_days |
| | | if training_end < 30: |
| | | raise ValueError('训练区间不足,无法完成带隔离期的时间切分') |
| | | |
| | | training_dates = dates[:training_end] |
| | | validation_dates = dates[validation_start:] |
| | | training = labeled[labeled['date'].isin(training_dates)].copy() |
| | | validation = labeled[labeled['date'].isin(validation_dates)].copy() |
| | | return training, validation, training_dates, validation_dates |
| | | |
| | | |
| | | def _evaluate_holdout( |
| | | model: MLFactorCombiner, |
| | | validation: pd.DataFrame, |
| | | training_target: pd.Series, |
| | | ) -> Dict: |
| | | predictions = model.predict(validation[DEFAULT_ML_FEATURES]) |
| | | evaluated = validation[['date', TARGET_COLUMN]].copy() |
| | | evaluated['prediction'] = predictions |
| | | |
| | | daily_ic = [] |
| | | for _, group in evaluated.groupby('date'): |
| | | valid = group[[TARGET_COLUMN, 'prediction']].dropna() |
| | | if len(valid) < 20: |
| | | continue |
| | | ic = valid[TARGET_COLUMN].corr(valid['prediction'], method='spearman') |
| | | if pd.notna(ic): |
| | | daily_ic.append(float(ic)) |
| | | |
| | | actual = evaluated[TARGET_COLUMN].to_numpy() |
| | | predicted = evaluated['prediction'].to_numpy() |
| | | baseline = np.full(len(actual), float(training_target.median())) |
| | | ic_mean = float(np.mean(daily_ic)) if daily_ic else None |
| | | ic_std = float(np.std(daily_ic)) if daily_ic else None |
| | | return { |
| | | 'validation_samples': int(len(evaluated)), |
| | | 'valid_ic_days': int(len(daily_ic)), |
| | | 'ic_mean': ic_mean, |
| | | 'ic_std': ic_std, |
| | | 'ir': ( |
| | | float(ic_mean / ic_std) |
| | | if ic_mean is not None and ic_std not in (None, 0.0) |
| | | else None |
| | | ), |
| | | 'ic_positive_rate': ( |
| | | float(np.mean(np.asarray(daily_ic) > 0)) |
| | | if daily_ic |
| | | else None |
| | | ), |
| | | 'mse': float(mean_squared_error(actual, predicted)), |
| | | 'mae': float(mean_absolute_error(actual, predicted)), |
| | | 'baseline_mae': float(mean_absolute_error(actual, baseline)), |
| | | } |
| | | |
| | | |
| | | def train_and_save_model( |
| | | model_type: str = 'gbdt', |
| | | data_path: Path = DEFAULT_DATA_PATH, |
| | | model_path: Path = DEFAULT_MODEL_PATH, |
| | | metadata_path: Path = DEFAULT_METADATA_PATH, |
| | | minimum_samples: int = 1000, |
| | | ) -> Dict: |
| | | """运行无未来泄漏的训练流程,并仅发布通过样本外验证的模型。""" |
| | | if model_type not in MODEL_NAMES: |
| | | return _failure(f'不支持的模型类型: {model_type}') |
| | | |
| | | try: |
| | | print(f'读取本地行情: {data_path}') |
| | | raw_data = load_market_data(Path(data_path)) |
| | | print(f'生成训练因子,共 {len(raw_data):,} 条原始记录...') |
| | | factor_data = build_factor_dataset(raw_data) |
| | | labeled = _prepare_labeled_rows(factor_data) |
| | | if len(labeled) < minimum_samples: |
| | | return _failure( |
| | | f'有效训练样本不足: {len(labeled):,},至少需要{minimum_samples:,}条' |
| | | ) |
| | | |
| | | training, validation, training_dates, validation_dates = _temporal_split( |
| | | labeled |
| | | ) |
| | | if len(training) < 500 or len(validation) < 200: |
| | | return _failure( |
| | | f'时间切分后样本不足: 训练{len(training):,}条,' |
| | | f'验证{len(validation):,}条' |
| | | ) |
| | | |
| | | print( |
| | | f'时间切分: 训练 {len(training):,} 条,' |
| | | f'隔离 {TARGET_HORIZON_DAYS} 个交易日,' |
| | | f'验证 {len(validation):,} 条' |
| | | ) |
| | | evaluation_model = MLFactorCombiner(model_type=model_type) |
| | | fit_result = evaluation_model.fit( |
| | | training[DEFAULT_ML_FEATURES], |
| | | training[TARGET_COLUMN], |
| | | validate=False, |
| | | ) |
| | | if not fit_result.get('success'): |
| | | return _failure( |
| | | f"训练失败: {fit_result.get('message', '未知错误')}" |
| | | ) |
| | | |
| | | metrics = _evaluate_holdout( |
| | | evaluation_model, |
| | | validation, |
| | | training[TARGET_COLUMN], |
| | | ) |
| | | approved = ( |
| | | metrics['valid_ic_days'] >= 10 |
| | | and metrics['ic_mean'] is not None |
| | | and metrics['ic_mean'] > 0 |
| | | ) |
| | | |
| | | production_model = MLFactorCombiner(model_type=model_type) |
| | | production_fit = production_model.fit( |
| | | labeled[DEFAULT_ML_FEATURES], |
| | | labeled[TARGET_COLUMN], |
| | | validate=False, |
| | | ) |
| | | if not production_fit.get('success'): |
| | | return _failure( |
| | | f"全量重训失败: {production_fit.get('message', '未知错误')}" |
| | | ) |
| | | |
| | | metadata = { |
| | | 'artifact_version': 1, |
| | | 'trained_at': datetime.now().astimezone().isoformat(timespec='seconds'), |
| | | 'model_type': model_type, |
| | | 'model_name': MODEL_NAMES[model_type], |
| | | 'target': TARGET_COLUMN, |
| | | 'target_horizon_trading_days': TARGET_HORIZON_DAYS, |
| | | 'feature_names': list(DEFAULT_ML_FEATURES), |
| | | 'training_samples': int(len(training)), |
| | | 'all_labeled_samples': int(len(labeled)), |
| | | 'training_start_date': str(pd.Timestamp(training_dates[0]).date()), |
| | | 'training_end_date': str(pd.Timestamp(training_dates[-1]).date()), |
| | | 'validation_start_date': str( |
| | | pd.Timestamp(validation_dates[0]).date() |
| | | ), |
| | | 'validation_end_date': str( |
| | | pd.Timestamp(validation_dates[-1]).date() |
| | | ), |
| | | 'purge_trading_days': TARGET_HORIZON_DAYS, |
| | | 'validation': metrics, |
| | | 'promotion_status': 'approved' if approved else 'rejected', |
| | | 'promotion_rule': '有效IC日>=10且样本外IC均值>0', |
| | | 'feature_importance': production_model.get_factor_weights(), |
| | | } |
| | | production_model.training_metadata = metadata |
| | | |
| | | candidate_model_path = Path(model_path).with_name( |
| | | 'ml_factor_combiner_candidate.pkl' |
| | | ) |
| | | candidate_metadata_path = Path(metadata_path).with_name( |
| | | 'ml_factor_combiner_candidate_metadata.json' |
| | | ) |
| | | production_model.save(candidate_model_path) |
| | | _write_json_atomic(candidate_metadata_path, metadata) |
| | | |
| | | active_model_preserved = False |
| | | if approved: |
| | | production_model.save(Path(model_path)) |
| | | _write_json_atomic(Path(metadata_path), metadata) |
| | | else: |
| | | active_model_preserved = Path(model_path).exists() |
| | | |
| | | return { |
| | | 'success': True, |
| | | 'approved': approved, |
| | | 'message': ( |
| | | '训练完成并已发布为每日主控模型' |
| | | if approved |
| | | else '训练完成,但样本外验证未通过,未发布为每日主控模型' |
| | | ), |
| | | 'model_type': model_type, |
| | | 'model_name': MODEL_NAMES[model_type], |
| | | 'metrics': metrics, |
| | | 'metadata': metadata, |
| | | 'model_path': str(model_path) if approved else None, |
| | | 'candidate_model_path': str(candidate_model_path), |
| | | 'active_model_preserved': active_model_preserved, |
| | | } |
| | | except Exception as error: |
| | | return _failure(f'训练流程失败: {error}') |
| | | |
| | | |
| | | def load_model_summary( |
| | | metadata_path: Path = DEFAULT_METADATA_PATH, |
| | | ) -> Optional[Dict]: |
| | | """优先返回正式模型摘要;没有正式模型时返回最近候选摘要。""" |
| | | metadata_path = Path(metadata_path) |
| | | candidate_path = metadata_path.with_name( |
| | | 'ml_factor_combiner_candidate_metadata.json' |
| | | ) |
| | | for path, artifact_kind in ( |
| | | (metadata_path, 'active'), |
| | | (candidate_path, 'candidate'), |
| | | ): |
| | | if not path.exists(): |
| | | continue |
| | | try: |
| | | with open(path, 'r', encoding='utf-8') as file: |
| | | summary = json.load(file) |
| | | summary['artifact_kind'] = artifact_kind |
| | | summary['metadata_path'] = str(path) |
| | | return summary |
| | | except (OSError, ValueError, TypeError): |
| | | continue |
| | | return None |
| | | |
| | | |
| | | def main() -> int: |
| | | parser = argparse.ArgumentParser(description='训练ML因子组合模型') |
| | | parser.add_argument( |
| | | '--model', |
| | | choices=sorted(MODEL_NAMES), |
| | | default='gbdt', |
| | | help='模型类型,默认gbdt', |
| | | ) |
| | | parser.add_argument('--data', type=Path, default=DEFAULT_DATA_PATH) |
| | | args = parser.parse_args() |
| | | |
| | | result = train_and_save_model(model_type=args.model, data_path=args.data) |
| | | print(result['message']) |
| | | if result.get('metrics'): |
| | | metrics = result['metrics'] |
| | | ic = metrics.get('ic_mean') |
| | | print( |
| | | '样本外结果: ' |
| | | f"IC={ic:.4f}" if ic is not None else '样本外结果: IC不可用' |
| | | ) |
| | | print( |
| | | f"有效IC日={metrics.get('valid_ic_days', 0)}, " |
| | | f"MAE={metrics.get('mae', 0):.6f}" |
| | | ) |
| | | return 0 if result.get('approved') else 1 |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | raise SystemExit(main()) |
| | |
| | | sys.path.insert(0, str(PROJECT_ROOT)) |
| | | |
| | | a_stock_manager = importlib.import_module("a_stock_manager") |
| | | ml_trainer = importlib.import_module("scripts.train_ml_factor_model") |
| | | |
| | | |
| | | class AStockManagerRunScriptTests(unittest.TestCase): |
| | |
| | | args=["--full", "--n-stocks", "all", "--days", "730"], |
| | | ) |
| | | |
| | | def test_ml_menu_runs_real_training_entrypoint(self): |
| | | training_result = { |
| | | "success": True, |
| | | "approved": True, |
| | | "message": "训练完成并已发布", |
| | | "metrics": { |
| | | "ic_mean": 0.03, |
| | | "valid_ic_days": 20, |
| | | "ic_positive_rate": 0.6, |
| | | "mae": 0.01, |
| | | }, |
| | | } |
| | | with patch( |
| | | "builtins.input", |
| | | side_effect=["1", "3"], |
| | | ), patch.object( |
| | | ml_trainer, |
| | | "train_and_save_model", |
| | | return_value=training_result, |
| | | ) as train: |
| | | a_stock_manager.ml_factor_combiner() |
| | | |
| | | train.assert_called_once_with(model_type="ridge") |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | unittest.main() |
| | |
| | | "未应用(独立二次排序模型尚未训练)", |
| | | ) |
| | | |
| | | def test_trained_model_receives_only_recorded_features(self): |
| | | class TrainedCombiner: |
| | | is_fitted = True |
| | | feature_names = ["quality", "momentum"] |
| | | |
| | | def predict(self, factor_data): |
| | | self.received_columns = list(factor_data.columns) |
| | | return pd.Series( |
| | | [0.1, 0.2], |
| | | index=factor_data.index, |
| | | ) |
| | | |
| | | combiner = TrainedCombiner() |
| | | master = daily_master.DailyMaster.__new__(daily_master.DailyMaster) |
| | | master.ml_combiner = combiner |
| | | selected = [ |
| | | {"stock_code": "600001", "score": 0.8, "rank": 1}, |
| | | {"stock_code": "600002", "score": 0.7, "rank": 2}, |
| | | ] |
| | | factor_data = pd.DataFrame([ |
| | | { |
| | | "date": pd.Timestamp("2026-07-10"), |
| | | "stock_code": "600001", |
| | | "quality": 0.4, |
| | | "momentum": 0.3, |
| | | "return_5d": 999.0, |
| | | }, |
| | | { |
| | | "date": pd.Timestamp("2026-07-10"), |
| | | "stock_code": "600002", |
| | | "quality": 0.5, |
| | | "momentum": 0.2, |
| | | "return_5d": 999.0, |
| | | }, |
| | | ]) |
| | | |
| | | result = master.optimize_with_ml(factor_data, selected) |
| | | |
| | | self.assertEqual(combiner.received_columns, ["quality", "momentum"]) |
| | | self.assertTrue(master.ml_optimization_applied) |
| | | self.assertEqual(master.ml_optimization_status, "已应用") |
| | | self.assertTrue(all("ml_rank_score" in stock for stock in result)) |
| | | |
| | | |
| | | class EnhancedFactorPipelineTests(unittest.TestCase): |
| | | def test_cross_sectional_factors_can_be_recalculated(self): |
| New file |
| | |
| | | import importlib |
| | | import sys |
| | | import tempfile |
| | | import unittest |
| | | from pathlib import Path |
| | | from unittest.mock import patch |
| | | |
| | | import numpy as np |
| | | import pandas as pd |
| | | |
| | | |
| | | PROJECT_ROOT = Path(__file__).resolve().parents[1] |
| | | sys.path.insert(0, str(PROJECT_ROOT)) |
| | | |
| | | ml_module = importlib.import_module("code.strategy.ml_factor_combiner") |
| | | trainer = importlib.import_module("scripts.train_ml_factor_model") |
| | | enhanced_factors = importlib.import_module("scripts.enhanced_factor_system") |
| | | daily_master = importlib.import_module("scripts.daily_master") |
| | | |
| | | |
| | | class FutureReturnLabelTests(unittest.TestCase): |
| | | def test_future_returns_never_cross_stock_boundaries(self): |
| | | dates = pd.bdate_range("2026-01-01", periods=10) |
| | | data = pd.DataFrame( |
| | | [ |
| | | { |
| | | "date": date, |
| | | "stock_code": code, |
| | | "close": start + index, |
| | | } |
| | | for code, start in (("600001", 10.0), ("000001", 200.0)) |
| | | for index, date in enumerate(dates) |
| | | ] |
| | | ) |
| | | |
| | | result = enhanced_factors.EnhancedFactorSystem().calculate_target_returns( |
| | | data |
| | | ) |
| | | first_stock = result[result["stock_code"] == "600001"] |
| | | second_stock = result[result["stock_code"] == "000001"] |
| | | |
| | | self.assertTrue(first_stock.tail(5)["return_5d"].isna().all()) |
| | | self.assertAlmostEqual( |
| | | second_stock.iloc[0]["return_5d"], |
| | | 205.0 / 200.0 - 1, |
| | | ) |
| | | |
| | | |
| | | class MLArtifactTests(unittest.TestCase): |
| | | def test_saved_model_uses_recorded_feature_names(self): |
| | | rng = np.random.default_rng(42) |
| | | factors = pd.DataFrame( |
| | | rng.normal(size=(120, 3)), |
| | | columns=["quality", "momentum", "liquidity"], |
| | | ) |
| | | target = ( |
| | | factors["quality"] * 0.6 |
| | | + factors["momentum"] * 0.3 |
| | | + rng.normal(scale=0.01, size=len(factors)) |
| | | ) |
| | | combiner = ml_module.MLFactorCombiner(model_type="ridge") |
| | | result = combiner.fit(factors, target, validate=False) |
| | | self.assertTrue(result["success"]) |
| | | combiner.training_metadata = {"promotion_status": "approved"} |
| | | |
| | | with tempfile.TemporaryDirectory() as directory: |
| | | model_path = Path(directory) / "model.pkl" |
| | | combiner.save(model_path) |
| | | loaded = ml_module.MLFactorCombiner.load(model_path) |
| | | |
| | | reordered = factors[["liquidity", "quality", "momentum"]].copy() |
| | | reordered["unused"] = 1.0 |
| | | original_predictions = combiner.predict(factors) |
| | | loaded_predictions = loaded.predict(reordered) |
| | | np.testing.assert_allclose(original_predictions, loaded_predictions) |
| | | |
| | | with self.assertRaisesRegex(ValueError, "缺少模型因子列"): |
| | | loaded.predict(factors.drop(columns=["quality"])) |
| | | |
| | | def test_daily_loader_rejects_unapproved_artifact(self): |
| | | rng = np.random.default_rng(7) |
| | | factors = pd.DataFrame(rng.normal(size=(100, 2)), columns=["a", "b"]) |
| | | target = pd.Series(rng.normal(size=100)) |
| | | combiner = ml_module.MLFactorCombiner(model_type="ridge") |
| | | self.assertTrue(combiner.fit(factors, target, validate=False)["success"]) |
| | | combiner.training_metadata = {"promotion_status": "rejected"} |
| | | |
| | | with tempfile.TemporaryDirectory() as directory: |
| | | model_path = Path(directory) / "model.pkl" |
| | | combiner.save(model_path) |
| | | loaded, status = daily_master.load_approved_ml_combiner(model_path) |
| | | |
| | | self.assertIsNone(loaded) |
| | | self.assertIn("未通过样本外验证", status) |
| | | |
| | | |
| | | class TemporalTrainingTests(unittest.TestCase): |
| | | def test_temporal_split_has_five_day_purge(self): |
| | | dates = pd.bdate_range("2025-01-01", periods=100) |
| | | labeled = pd.DataFrame( |
| | | { |
| | | "date": np.repeat(dates, 2), |
| | | "stock_code": ["600001", "600002"] * len(dates), |
| | | } |
| | | ) |
| | | |
| | | _, _, training_dates, validation_dates = trainer._temporal_split(labeled) |
| | | training_end_position = dates.get_loc(pd.Timestamp(training_dates[-1])) |
| | | validation_start_position = dates.get_loc( |
| | | pd.Timestamp(validation_dates[0]) |
| | | ) |
| | | |
| | | self.assertEqual( |
| | | validation_start_position - training_end_position - 1, |
| | | trainer.TARGET_HORIZON_DAYS, |
| | | ) |
| | | |
| | | def test_strong_oos_model_is_published_locally(self): |
| | | rng = np.random.default_rng(11) |
| | | dates = pd.bdate_range("2025-01-01", periods=80) |
| | | rows = [] |
| | | for date in dates: |
| | | for stock_index in range(30): |
| | | signal = stock_index / 29.0 + rng.normal(scale=0.01) |
| | | row = { |
| | | "date": date, |
| | | "stock_code": f"{stock_index:06d}", |
| | | trainer.TARGET_COLUMN: signal * 0.02, |
| | | } |
| | | for feature_index, feature in enumerate( |
| | | ml_module.DEFAULT_ML_FEATURES |
| | | ): |
| | | row[feature] = ( |
| | | signal |
| | | if feature_index == 0 |
| | | else rng.normal(scale=0.1) |
| | | ) |
| | | rows.append(row) |
| | | factor_data = pd.DataFrame(rows) |
| | | |
| | | with tempfile.TemporaryDirectory() as directory: |
| | | model_path = Path(directory) / "ml_factor_combiner.pkl" |
| | | metadata_path = Path(directory) / "metadata.json" |
| | | with patch.object( |
| | | trainer, |
| | | "load_market_data", |
| | | return_value=pd.DataFrame([{"placeholder": 1}]), |
| | | ), patch.object( |
| | | trainer, |
| | | "build_factor_dataset", |
| | | return_value=factor_data, |
| | | ): |
| | | result = trainer.train_and_save_model( |
| | | model_type="ridge", |
| | | model_path=model_path, |
| | | metadata_path=metadata_path, |
| | | ) |
| | | |
| | | self.assertTrue(result["success"]) |
| | | self.assertTrue(result["approved"]) |
| | | self.assertTrue(model_path.exists()) |
| | | self.assertTrue(metadata_path.exists()) |
| | | loaded = ml_module.MLFactorCombiner.load(model_path) |
| | | self.assertEqual( |
| | | loaded.training_metadata["promotion_status"], |
| | | "approved", |
| | | ) |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | unittest.main() |