Variya
2026-03-11 f95cdc7e5df20d8a14be0322baaf4c7e17b70312
code/strategy/alpha_stock_selector.py
@@ -753,7 +753,7 @@
                       n_satellite: int = 2) -> Dict:
        """
        构建投资组合
        Args:
            selected_stocks: 选中的股票 DataFrame (index: stock_code)
            alpha_scores: α得分 Series
@@ -762,7 +762,7 @@
            cash_ratio: 现金比例
            n_core: 核心持仓数量
            n_satellite: 卫星持仓数量
        Returns:
            组合配置字典
        """
@@ -770,33 +770,53 @@
        selected_stocks = selected_stocks.copy()
        selected_stocks['alpha_score'] = alpha_scores
        selected_stocks = selected_stocks.sort_values('alpha_score', ascending=False)
        # 核心持仓: α得分最高的股票
        # 检查选股结果
        if len(selected_stocks) == 0:
            import logging
            logger = logging.getLogger(__name__)
            logger.warning("⚠️ 选股结果为空,无法构建投资组合")
            return None, {'core': [], 'satellite': [], 'cash': 1.0}
            return {'core': [], 'satellite': [], 'cash': 1.0, 'total': 1.0}
        core_holdings = selected_stocks.head(n_core)
        core_weight_per_stock = core_ratio / n_core if n_core > 0 else 0
        # 卫星持仓: 行业轮动股票 (可以按行业分散)
        satellite_holdings = selected_stocks.iloc[n_core:n_core + n_satellite]
        satellite_weight_per_stock = satellite_ratio / n_satellite if n_satellite > 0 else 0
        portfolio = {
            'core': [],
            'satellite': [],
            'cash': cash_ratio,
            'total': 1.0
        }
        # 股票代码映射表(修正错误代码)
        stock_code_mapping = {
            '001242': '601899',  # 紫金矿业
            '001008': '600938',  # 中国海油
            '000602': '600410',  # 华胜天成
            '001225': '601857',  # 中国石油
            '001040': '600989',  # 宝丰能源
            '001232': '601872',  # 招商轮船
            '003271': '002155',  # 湖南黄金
            '000648': '600489',  # 中金黄金
            '004556': '300502',  # 新易盛
            '000655': '600498'   # 烽火通信
        }
        # 添加核心持仓
        for idx, (stock_code, row) in enumerate(core_holdings.iterrows()):
            # 优先从列中获取stock_name,如果stock_code是索引,可能需要从其他列获取
            stock_name = row.get('stock_name', row.get('股票名称', row.get('name', str(stock_code))))
            # 如果stock_code是整数索引,尝试从列中获取真实的stock_code
            real_stock_code = row.get('stock_code', stock_code)
            # 修正股票代码
            real_stock_code = str(real_stock_code)
            if real_stock_code in stock_code_mapping:
                real_stock_code = stock_code_mapping[real_stock_code]
            portfolio['core'].append({
                'stock_code': real_stock_code,
                'stock_name': stock_name,
@@ -804,13 +824,17 @@
                'alpha_score': row['alpha_score'],
                'rank': idx + 1
            })
        # 添加卫星持仓
        for idx, (stock_code, row) in enumerate(satellite_holdings.iterrows()):
            # 优先从列中获取stock_name
            stock_name = row.get('stock_name', row.get('股票名称', row.get('name', str(stock_code))))
            # 如果stock_code是整数索引,尝试从列中获取真实的stock_code
            real_stock_code = row.get('stock_code', stock_code)
            # 修正股票代码
            real_stock_code = str(real_stock_code)
            if real_stock_code in stock_code_mapping:
                real_stock_code = stock_code_mapping[real_stock_code]
            portfolio['satellite'].append({
                'stock_code': real_stock_code,
                'stock_name': stock_name,
@@ -818,7 +842,7 @@
                'alpha_score': row['alpha_score'],
                'rank': n_core + idx + 1
            })
        return portfolio
    
    def select_stocks(self, stock_data: pd.DataFrame, 
@@ -826,34 +850,34 @@
                     apply_filters: bool = True) -> Tuple[pd.DataFrame, Dict]:
        """
        执行选股
        Args:
            stock_data: 股票数据 DataFrame (index: stock_code)
            n: 选股数量
            apply_filters: 是否应用"低估+高α"筛选
        Returns:
            (选中的股票DataFrame, 组合配置字典)
        """
        print("=" * 60)
        print("🔬 α因子选股")
        print("=" * 60)
        # 1. 选择有效因子
        factor_list = self.select_effective_factors(stock_data)
        # 2. 计算α得分
        print("\n📊 计算α因子得分...")
        alpha_scores = self.calculate_alpha_score(stock_data, factor_list)
        print(f"✓ α得分范围: {alpha_scores.min():.1f} - {alpha_scores.max():.1f}")
        # 3. 应用低估+高α筛选
        if apply_filters:
            print(f"\n🎯 应用“低估+高α”筛选...")
            print(f"  • α得分阈值: >80分")
            print(f"  • 流动性: 换手率>0.5%")
            print(f"  •市值限制: 排除>5000亿")
            filtered = self.filter_undervalued_high_alpha(
                stock_data, 
                alpha_scores, 
@@ -861,9 +885,9 @@
                min_turnover=0.5,
                max_market_cap=500000.0
            )
            print(f"✓ 筛选后剩余: {len(filtered)}只股票")
            if len(filtered) < n:
                print(f"⚠️ 筛选后股票数量({len(filtered)})少于选股数量({n})")
                # 如果筛选后股票太少,放宽条件
@@ -877,7 +901,7 @@
                        max_market_cap=float('inf')
                    )
                    print(f"  → 放宽后剩余: {len(filtered)}只股票")
            stock_data = filtered
            alpha_scores = alpha_scores[filtered.index]
        else:
@@ -886,10 +910,11 @@
            stock_data['alpha_score'] = alpha_scores
            stock_data = stock_data.sort_values('alpha_score', ascending=False).head(n)
            alpha_scores = stock_data['alpha_score']
        # 4. 选择Top N
        selected = stock_data.head(n)
        # 4. 行业暴露控制
        print("\n🔒 行业暴露控制...")
        selected = self._control_industry_exposure(stock_data, alpha_scores, n)
        print(f"\n✓ 选定Top {len(selected)}只股票")
        print("\n📋 选股结果:")
        for idx, (stock_code, row) in enumerate(selected.iterrows(), 1):
@@ -897,13 +922,23 @@
            stock_name = row.get('stock_name', row.get('股票名称', row.get('name', str(stock_code))))
            # 获取真实的股票代码(如果stock_code是索引,可能需要从列中获取)
            real_stock_code = row.get('stock_code', stock_code)
            # 修正股票代码
            real_stock_code = str(real_stock_code)
            stock_code_mapping = {
                '001242': '601899', '001008': '600938', '000602': '600410',
                '001225': '601857', '001040': '600989', '001232': '601872',
                '003271': '002155', '000648': '600489', '004556': '300502',
                '000655': '600498'
            }
            if real_stock_code in stock_code_mapping:
                real_stock_code = stock_code_mapping[real_stock_code]
            alpha_score = row.get('alpha_score', 0) if 'alpha_score' in row.index else alpha_scores.get(stock_code, 0)
            print(f" {idx}. {stock_name}({real_stock_code}) - α得分: {alpha_score:.1f}")
            alpha_score = row.get('alpha_score', 0) if 'alpha_score' in row.index else alpha_scores[stock_code]
            industry = row.get('industry', row.get('行业', '未知'))
            print(f" {idx}. {stock_name}({real_stock_code}) - α得分: {alpha_score:.1f} - 行业: {industry}")
        print(f"\n💼 构建投资组合...")
        n_core = min(5, len(selected))
        n_satellite = min(2, len(selected) - n_core)
        portfolio_config = self.build_portfolio(
            selected, 
            alpha_scores,
@@ -913,21 +948,118 @@
            n_core=n_core,
            n_satellite=n_satellite
        )
        # 行业暴露分析
        self._analyze_industry_exposure(portfolio_config, selected)
        print(f"  • 核心持仓: {len(portfolio_config['core'])}只 (60%)")
        for holding in portfolio_config['core']:
            print(f"    - {holding['stock_name']}({holding['stock_code']}): {holding['weight']*100:.1f}%")
        print(f"  • 卫星持仓: {len(portfolio_config['satellite'])}只 (20%)")
        for holding in portfolio_config['satellite']:
            print(f"    - {holding['stock_name']}({holding['stock_code']}): {holding['weight']*100:.1f}%")
        print(f"  • 现金: 20%")
        print("=" * 60)
        return selected, portfolio_config
    def _control_industry_exposure(self, stock_data: pd.DataFrame, alpha_scores: pd.Series, n: int) -> pd.DataFrame:
        """
        控制行业暴露,确保单个行业权重不超过30%
        Args:
            stock_data: 股票数据
            alpha_scores: α得分
            n: 选股数量
        Returns:
            行业暴露控制后的股票DataFrame
        """
        # 按α得分排序
        sorted_stocks = stock_data.copy()
        sorted_stocks['alpha_score'] = alpha_scores
        sorted_stocks = sorted_stocks.sort_values('alpha_score', ascending=False)
        # 行业暴露控制
        selected = []
        industry_counts = {}
        max_industry_ratio = 0.3  # 单个行业最大比例
        max_industry_count = int(n * max_industry_ratio)
        for _, row in sorted_stocks.iterrows():
            industry = row.get('industry', row.get('行业', '未知'))
            current_count = industry_counts.get(industry, 0)
            if current_count < max_industry_count:
                selected.append(row)
                industry_counts[industry] = current_count + 1
                if len(selected) >= n:
                    break
        # 如果选不够,放宽行业限制
        if len(selected) < n:
            remaining = n - len(selected)
            for _, row in sorted_stocks.iterrows():
                if row.name not in [s.name for s in selected]:
                    selected.append(row)
                    remaining -= 1
                    if remaining <= 0:
                        break
        selected_df = pd.DataFrame(selected)
        if not selected_df.empty:
            selected_df = selected_df.set_index(selected_df.index)
        return selected_df
    def _analyze_industry_exposure(self, portfolio_config: Dict, selected_stocks: pd.DataFrame):
        """
        分析投资组合的行业暴露
        Args:
            portfolio_config: 组合配置
            selected_stocks: 选中的股票
        """
        industry_weights = {}
        total_weight = 0
        # 计算核心持仓行业权重
        for holding in portfolio_config['core']:
            stock_code = holding['stock_code']
            weight = holding['weight']
            if stock_code in selected_stocks.index:
                industry = selected_stocks.loc[stock_code].get('industry', selected_stocks.loc[stock_code].get('行业', '未知'))
                if industry not in industry_weights:
                    industry_weights[industry] = 0
                industry_weights[industry] += weight
                total_weight += weight
        # 计算卫星持仓行业权重
        for holding in portfolio_config['satellite']:
            stock_code = holding['stock_code']
            weight = holding['weight']
            if stock_code in selected_stocks.index:
                industry = selected_stocks.loc[stock_code].get('industry', selected_stocks.loc[stock_code].get('行业', '未知'))
                if industry not in industry_weights:
                    industry_weights[industry] = 0
                industry_weights[industry] += weight
                total_weight += weight
        # 计算行业占比
        industry_percentages = {}
        for industry, weight in industry_weights.items():
            if total_weight > 0:
                industry_percentages[industry] = (weight / total_weight) * 100
        print("\n📊 行业暴露分析:")
        for industry, percentage in sorted(industry_percentages.items(), key=lambda x: -x[1]):
            print(f"  • {industry}: {percentage:.1f}%")
            if percentage > 30:
                print(f"    ⚠️ 行业暴露超过30%上限")
# 测试代码
if __name__ == "__main__":