From 4ab857aa892499fedce46f94fc2d8d2a91f4314f Mon Sep 17 00:00:00 2001
From: log
Date: Fri, 10 Jul 2026 12:13:54 +0800
Subject: [PATCH] fix: select latest complete market cross-section

---
 scripts/daily_master.py      |  100 +++++++++++++++++++++++++++++++--
 tests/test_data_update_v2.py |    6 +-
 tests/test_daily_master.py   |   72 ++++++++++++++++++++++++
 3 files changed, 169 insertions(+), 9 deletions(-)

diff --git a/scripts/daily_master.py b/scripts/daily_master.py
index 8843e97..c2d9697 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:
     """股票分类器 - 按行业、市值分组"""
     
@@ -958,11 +1029,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 +1110,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)}只股票")
diff --git a/tests/test_daily_master.py b/tests/test_daily_master.py
new file mode 100644
index 0000000..ad4d447
--- /dev/null
+++ b/tests/test_daily_master.py
@@ -0,0 +1,72 @@
+import importlib
+import sys
+import unittest
+from pathlib import Path
+
+import pandas as pd
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(PROJECT_ROOT))
+
+daily_master = importlib.import_module("scripts.daily_master")
+
+
+class LatestCompleteCrossSectionTests(unittest.TestCase):
+    def test_bse_only_latest_date_falls_back_to_full_market_date(self):
+        full_market_date = pd.Timestamp("2026-07-09")
+        latest_bse_date = pd.Timestamp("2026-07-10")
+        history_dates = pd.bdate_range(end=full_market_date, periods=60)
+        stock_codes = ["600001", "000001", "300001", "688001", "920001", "920002"]
+
+        rows = []
+        for code in stock_codes:
+            rows.extend(
+                {"date": date, "stock_code": code, "final_score": 0.5}
+                for date in history_dates
+            )
+        rows.extend([
+            {"date": latest_bse_date, "stock_code": "920001", "final_score": 0.9},
+            {"date": latest_bse_date, "stock_code": "920002", "final_score": 1.0},
+        ])
+
+        result, metadata = daily_master.select_latest_complete_cross_section(
+            pd.DataFrame(rows),
+            min_history_days=60,
+            min_coverage_ratio=0.8,
+            min_cross_section_stocks=3,
+        )
+
+        self.assertEqual(metadata["latest_observed_date"], "2026-07-10")
+        self.assertEqual(metadata["selection_date"], "2026-07-09")
+        self.assertEqual(metadata["latest_observed_stocks"], 2)
+        self.assertEqual(metadata["selection_universe_stocks"], 6)
+        self.assertEqual(set(result["stock_code"]), set(stock_codes))
+
+    def test_short_history_stocks_are_excluded(self):
+        latest_date = pd.Timestamp("2026-07-09")
+        long_history = pd.bdate_range(end=latest_date, periods=60)
+        short_history = pd.bdate_range(end=latest_date, periods=20)
+        rows = [
+            {"date": date, "stock_code": code, "final_score": 0.5}
+            for code in ["600001", "000001", "300001"]
+            for date in long_history
+        ]
+        rows.extend(
+            {"date": date, "stock_code": "920999", "final_score": 1.0}
+            for date in short_history
+        )
+
+        result, metadata = daily_master.select_latest_complete_cross_section(
+            pd.DataFrame(rows),
+            min_history_days=60,
+            min_cross_section_stocks=3,
+        )
+
+        self.assertTrue(metadata["history_filter_applied"])
+        self.assertEqual(metadata["excluded_short_history_stocks"], 1)
+        self.assertNotIn("920999", set(result["stock_code"]))
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/tests/test_data_update_v2.py b/tests/test_data_update_v2.py
index fc97210..1bcb637 100644
--- a/tests/test_data_update_v2.py
+++ b/tests/test_data_update_v2.py
@@ -573,9 +573,9 @@
 
         with patch.dict(sys.modules, {"baostock": fake_bs}):
             with patch.object(
-                data_update_v2,
-                "fetch_real_stock_data_from_akshare_only",
-                return_value=None,
+                data_update_v2, "fetch_stock_list_from_akshare", return_value=None
+            ), patch.object(
+                data_update_v2, "fetch_real_stock_data_from_akshare_only", return_value=None
             ):
                 result = data_update_v2.fetch_real_stock_data_from_akshare(
                     n_stocks=1, days=10

--
Gitblit v1.8.0