| | |
| | | logger = logging.getLogger(__name__) |
| | | |
| | | |
| | | def select_latest_complete_cross_section( |
| | | df: pd.DataFrame, |
| | | min_history_days: int = 60, |
| | | min_coverage_ratio: float = 0.8, |
| | | min_cross_section_stocks: int = 30, |
| | | ) -> Tuple[pd.DataFrame, Dict]: |
| | | """Select the latest date with broad universe coverage. |
| | | |
| | | Different providers can close at different times. In particular, Tencent |
| | | may already expose BSE rows while BaoStock still ends on the prior trading |
| | | day. Selecting the absolute maximum date would then create a BSE-only |
| | | universe. |
| | | """ |
| | | metadata = { |
| | | 'latest_observed_date': None, |
| | | 'selection_date': None, |
| | | 'latest_observed_stocks': 0, |
| | | 'selection_universe_stocks': 0, |
| | | 'minimum_required_stocks': 0, |
| | | 'history_filter_applied': False, |
| | | 'excluded_short_history_stocks': 0, |
| | | } |
| | | if df is None or len(df) == 0 or not {'date', 'stock_code'}.issubset(df.columns): |
| | | return pd.DataFrame() if df is None else df.copy(), metadata |
| | | |
| | | working = df.copy() |
| | | working['_selection_date'] = pd.to_datetime( |
| | | working['date'], errors='coerce' |
| | | ).dt.normalize() |
| | | working = working.dropna(subset=['_selection_date', 'stock_code']) |
| | | if len(working) == 0: |
| | | return working.drop(columns=['_selection_date']), metadata |
| | | |
| | | history_days = working.groupby('stock_code')['_selection_date'].nunique() |
| | | eligible_codes = history_days[history_days >= min_history_days].index |
| | | total_stocks = int(history_days.size) |
| | | minimum_history_universe = min(min_cross_section_stocks, total_stocks) |
| | | if len(eligible_codes) >= minimum_history_universe: |
| | | metadata['history_filter_applied'] = True |
| | | metadata['excluded_short_history_stocks'] = int( |
| | | total_stocks - len(eligible_codes) |
| | | ) |
| | | working = working[working['stock_code'].isin(eligible_codes)] |
| | | |
| | | daily_counts = working.groupby('_selection_date')['stock_code'].nunique().sort_index() |
| | | if daily_counts.empty: |
| | | return working.drop(columns=['_selection_date']), metadata |
| | | |
| | | latest_observed_date = daily_counts.index.max() |
| | | maximum_coverage = int(daily_counts.max()) |
| | | minimum_required = max( |
| | | int(np.ceil(maximum_coverage * min_coverage_ratio)), |
| | | min(min_cross_section_stocks, maximum_coverage), |
| | | ) |
| | | complete_dates = daily_counts[daily_counts >= minimum_required] |
| | | selection_date = ( |
| | | complete_dates.index.max() if not complete_dates.empty else latest_observed_date |
| | | ) |
| | | |
| | | metadata.update({ |
| | | 'latest_observed_date': latest_observed_date.strftime('%Y-%m-%d'), |
| | | 'selection_date': selection_date.strftime('%Y-%m-%d'), |
| | | 'latest_observed_stocks': int(daily_counts.loc[latest_observed_date]), |
| | | 'selection_universe_stocks': int(daily_counts.loc[selection_date]), |
| | | 'minimum_required_stocks': minimum_required, |
| | | }) |
| | | |
| | | cross_section = working[working['_selection_date'] == selection_date].copy() |
| | | return cross_section.drop(columns=['_selection_date']), metadata |
| | | |
| | | |
| | | class StockClassifier: |
| | | """股票分类器 - 按行业、市值分组""" |
| | | |
| | |
| | | else: |
| | | self.ml_combiner = None |
| | | logger.warning("⚠️ ML因子组合器不可用") |
| | | self.ml_optimization_applied = False |
| | | self.ml_optimization_status = ( |
| | | '未应用(模型尚未训练)' |
| | | if self.ml_combiner is not None |
| | | else '未应用(组件不可用)' |
| | | ) |
| | | |
| | | if DYNAMIC_WEIGHT_AVAILABLE: |
| | | self.dynamic_weight_system = DynamicFactorWeightSystem() |
| | |
| | | if len(df) == 0: |
| | | return [] |
| | | |
| | | # 先获取最新日期的数据 |
| | | if 'date' in df.columns: |
| | | latest_date = df['date'].max() |
| | | df = df[df['date'] == latest_date].copy() |
| | | logger.info(f"使用最新日期数据: {latest_date}") |
| | | # 数据源收盘时间可能不同,使用最近一个覆盖完整市场的交易日。 |
| | | selection_metadata = {} |
| | | if {'date', 'stock_code'}.issubset(df.columns): |
| | | df, selection_metadata = select_latest_complete_cross_section(df) |
| | | selection_date = selection_metadata.get('selection_date') |
| | | latest_observed_date = selection_metadata.get('latest_observed_date') |
| | | logger.info( |
| | | f"使用完整市场截面: {selection_date}, " |
| | | f"{selection_metadata.get('selection_universe_stocks', len(df))}只股票" |
| | | ) |
| | | if selection_date != latest_observed_date: |
| | | logger.warning( |
| | | f"⚠️ 最新日期{latest_observed_date}仅有" |
| | | f"{selection_metadata.get('latest_observed_stocks', 0)}只股票," |
| | | f"低于完整截面要求" |
| | | f"{selection_metadata.get('minimum_required_stocks', 0)}只;" |
| | | f"已回退到{selection_date}" |
| | | ) |
| | | excluded = selection_metadata.get('excluded_short_history_stocks', 0) |
| | | if excluded: |
| | | logger.info(f"已排除历史不足60个交易日的股票: {excluded}只") |
| | | |
| | | # 如果最新日期数据按股票分组后有多条记录,取最新一条 |
| | | if 'stock_code' in df.columns: |
| | |
| | | with open(self.selection_file, 'w', encoding='utf-8') as f: |
| | | json.dump({ |
| | | 'selected_stocks': unique_result, |
| | | 'timestamp': datetime.now().isoformat() |
| | | 'timestamp': datetime.now().isoformat(), |
| | | 'selection_metadata': selection_metadata, |
| | | }, f, indent=2, ensure_ascii=False) |
| | | |
| | | logger.info(f"✓ 选股完成,选出{len(unique_result)}只股票") |
| | |
| | | |
| | | def optimize_with_ml(self, df: pd.DataFrame, selected_stocks: List[Dict]) -> List[Dict]: |
| | | """使用ML因子组合优化选股结果""" |
| | | self.ml_optimization_applied = False |
| | | if self.ml_combiner is None: |
| | | logger.warning("⚠️ ML组合器不可用,跳过优化") |
| | | self.ml_optimization_status = '未应用(组件不可用)' |
| | | return selected_stocks |
| | | |
| | | if not getattr(self.ml_combiner, 'is_fitted', False): |
| | | logger.warning("⚠️ ML模型尚未训练,跳过二次优化并保留final_score排序") |
| | | self.ml_optimization_status = '未应用(模型尚未训练)' |
| | | return selected_stocks |
| | | |
| | | logger.info("🤖 ML因子组合优化...") |
| | |
| | | |
| | | if not factor_cols: |
| | | logger.warning("⚠️ 未找到因子列,跳过ML优化") |
| | | self.ml_optimization_status = '未应用(无可用因子)' |
| | | return selected_stocks |
| | | |
| | | selected_codes = [s['stock_code'] for s in selected_stocks] |
| | |
| | | |
| | | if len(factor_data) == 0: |
| | | logger.warning("⚠️ 因子数据为空,跳过ML优化") |
| | | self.ml_optimization_status = '未应用(因子数据为空)' |
| | | return selected_stocks |
| | | |
| | | factor_data = factor_data.set_index('stock_code') |
| | |
| | | for i, stock in enumerate(selected_stocks): |
| | | stock['rank'] = i + 1 |
| | | |
| | | self.ml_optimization_applied = True |
| | | self.ml_optimization_status = '已应用' |
| | | logger.info(f"✓ ML优化完成,已重新排序") |
| | | else: |
| | | self.ml_optimization_status = '未应用(预测结果为空)' |
| | | logger.warning("⚠️ ML预测结果为空,使用原始排序") |
| | | |
| | | except Exception as e: |
| | | self.ml_optimization_status = f'未应用({e})' |
| | | logger.error(f"❌ ML优化失败: {e}") |
| | | |
| | | return selected_stocks |
| | |
| | | logger.info("\n" + "="*70) |
| | | logger.info("✅ 每日主控流程完成") |
| | | logger.info(f" - 选股数量: {len(filtered_stocks)}") |
| | | logger.info(f" - ML优化: {'已启用' if self.ml_combiner else '未启用'}") |
| | | logger.info(f" - ML优化: {self.ml_optimization_status}") |
| | | logger.info(f" - 动态权重: {'已启用' if self.dynamic_weight_system else '未启用'}") |
| | | logger.info("="*70) |
| | | |