| | |
| | | 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: |
| | | """股票分类器 - 按行业、市值分组""" |
| | | |
| | |
| | | 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)}只股票") |