From 2fa3e25841826aa4e8f95d988024f16149793368 Mon Sep 17 00:00:00 2001
From: log
Date: Sat, 11 Jul 2026 08:44:15 +0800
Subject: [PATCH] fix: make daily factor calculation repeatable

---
 scripts/daily_master.py |  144 +++++++++++++++++++++++++++++++++++++++++++----
 1 files changed, 131 insertions(+), 13 deletions(-)

diff --git a/scripts/daily_master.py b/scripts/daily_master.py
index 8843e97..35a1a54 100644
--- a/scripts/daily_master.py
+++ b/scripts/daily_master.py
@@ -57,6 +57,77 @@
 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:
     """股票分类器 - 按行业、市值分组"""
     
@@ -820,6 +891,13 @@
         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 '未应用(组件不可用)'
+        )
+        self.enhanced_factor_status = '未运行'
         
         if DYNAMIC_WEIGHT_AVAILABLE:
             self.dynamic_weight_system = DynamicFactorWeightSystem()
@@ -863,7 +941,7 @@
             logger.error(f"❌ 数据管道执行失败: {e}")
             return None
     
-    def _run_advanced_factor_system(self, df: pd.DataFrame) -> pd.DataFrame:
+    def _run_advanced_factor_system(self, df: pd.DataFrame) -> Optional[pd.DataFrame]:
         """运行增强因子系统"""
         try:
             from scripts.enhanced_factor_system import EnhancedFactorSystem
@@ -903,6 +981,7 @@
                 pickle.dump(df, f)
             
             effective_count = sum(1 for r in results.values() if r.get('effective', False))
+            self.enhanced_factor_status = '已完成'
             logger.info(f"✓ 增强因子系统执行完成,有效因子: {effective_count}/{len(results)}")
             
             if ml_metrics:
@@ -910,12 +989,14 @@
             
             return df
             
-        except ImportError:
-            logger.warning("⚠️ 增强因子系统模块不可用")
-            return df
+        except ImportError as e:
+            self.enhanced_factor_status = f'失败(模块不可用: {e})'
+            logger.error(f"❌ 增强因子系统模块不可用: {e}")
+            return None
         except Exception as e:
-            logger.error(f"❌ 增强因子系统执行失败: {e}")
-            return df
+            self.enhanced_factor_status = f'失败({e})'
+            logger.error(f"❌ 增强因子系统执行失败: {e}", exc_info=True)
+            return None
     
     def load_data(self) -> pd.DataFrame:
         """加载数据"""
@@ -958,11 +1039,27 @@
         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:
@@ -1023,7 +1120,8 @@
         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)}只股票")
@@ -1031,8 +1129,15 @@
     
     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因子组合优化...")
@@ -1044,6 +1149,7 @@
             
             if not factor_cols:
                 logger.warning("⚠️ 未找到因子列,跳过ML优化")
+                self.ml_optimization_status = '未应用(无可用因子)'
                 return selected_stocks
             
             selected_codes = [s['stock_code'] for s in selected_stocks]
@@ -1058,6 +1164,7 @@
             
             if len(factor_data) == 0:
                 logger.warning("⚠️ 因子数据为空,跳过ML优化")
+                self.ml_optimization_status = '未应用(因子数据为空)'
                 return selected_stocks
             
             factor_data = factor_data.set_index('stock_code')
@@ -1080,11 +1187,15 @@
                 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
@@ -1267,6 +1378,12 @@
             
             # 运行高级因子系统改进因子
             df = self._run_advanced_factor_system(df)
+            if df is None:
+                logger.error(
+                    "❌ 增强因子计算未完成,已停止本次选股,"
+                    "避免沿用旧final_score生成报告"
+                )
+                return False
             
             factor_evaluation, dynamic_weights = self.evaluate_factors(df)
             
@@ -1307,7 +1424,8 @@
             logger.info("\n" + "="*70)
             logger.info("✅ 每日主控流程完成")
             logger.info(f"  - 选股数量: {len(filtered_stocks)}")
-            logger.info(f"  - ML优化: {'已启用' if self.ml_combiner else '未启用'}")
+            logger.info(f"  - 增强因子: {self.enhanced_factor_status}")
+            logger.info(f"  - ML优化: {self.ml_optimization_status}")
             logger.info(f"  - 动态权重: {'已启用' if self.dynamic_weight_system else '未启用'}")
             logger.info("="*70)
             

--
Gitblit v1.8.0