From 048ea1585b4e1b89ef1f547844869ef9a74accd8 Mon Sep 17 00:00:00 2001
From: log
Date: Thu, 09 Jul 2026 18:36:34 +0800
Subject: [PATCH] fix: abort akshare history after repeated failures

---
 code/strategy/alpha_stock_selector.py |  254 ++++++++++++++++++++++++++++++++++++++++----------
 1 files changed, 203 insertions(+), 51 deletions(-)

diff --git a/code/strategy/alpha_stock_selector.py b/code/strategy/alpha_stock_selector.py
index eb58a92..147e309 100644
--- a/code/strategy/alpha_stock_selector.py
+++ b/code/strategy/alpha_stock_selector.py
@@ -402,20 +402,34 @@
         Returns:
             有效因子列表
         """
-        # 验证因子
         validation_results = self.validate_factors(data)
         
-        # 选择有效的因子
         valid_factors = [name for name, result in validation_results.items() 
                         if result['valid']]
         
         if not valid_factors:
-            # 如果没有有效因子,使用所有因子(放宽条件)
             print("⚠️ 没有通过IC/IR验证的因子,使用所有可用因子")
             valid_factors = [f.name for f in self.alpha_factors 
                            if f.name in data.columns]
         
-        print(f"✓ 使用因子: {', '.join(valid_factors)}")
+        if not valid_factors:
+            print("⚠️ 没有财务因子,使用技术因子作为替代")
+            fallback_factors = [
+                'final_score', 'ml_score', 'ml_score_return_5d',
+                'momentum_20', 'momentum_60', 'volatility_20',
+                'turnover', 'amount', 'rsi_14', 'rel_momentum',
+                'industry_rank', 'market_rank', 'trend_strength'
+            ]
+            valid_factors = [f for f in fallback_factors if f in data.columns]
+            
+            if not valid_factors:
+                numeric_cols = data.select_dtypes(include=[np.number]).columns.tolist()
+                exclude_cols = ['date', 'stock_code', 'open', 'close', 'high', 'low', 
+                               'volume', 'amount', 'change_pct', 'return_1d', 'return_5d',
+                               'return_10d', 'return_20d']
+                valid_factors = [c for c in numeric_cols if c not in exclude_cols][:10]
+        
+        print(f"✓ 使用因子: {', '.join(valid_factors[:10])}")
         
         return valid_factors
     
@@ -612,49 +626,49 @@
         if factor_list is None:
             factor_list = self.select_effective_factors(stock_data)
         
-        # 如果没有可用因子,返回空Series
         if not factor_list:
             return pd.Series(0.0, index=stock_data.index)
         
-        # 标准化因子
         normalized_scores = pd.Series(0.0, index=stock_data.index)
+        valid_factor_count = 0
         
         for factor_name in factor_list:
             if factor_name not in stock_data.columns:
                 continue
             
-            # 找到对应的因子定义
-            factor_def = next((f for f in self.alpha_factors if f.name == factor_name), None)
-            if factor_def is None:
-                continue
-            
             factor_data = stock_data[factor_name]
             
-            # 移除NaN
             factor_data = factor_data.fillna(factor_data.median())
             
-            # 标准化 (Z-score)
             mean = factor_data.mean()
             std = factor_data.std()
             
             if std > 0:
                 normalized = (factor_data - mean) / std
             else:
-                normalized = pd.Series(0, index=stock_data.index)
+                continue
             
-            # 根据因子方向调整得分
-            if factor_def.direction == 'negative':
+            factor_def = next((f for f in self.alpha_factors if f.name == factor_name), None)
+            
+            if factor_def is not None and factor_def.direction == 'negative':
                 normalized = -normalized
             
             normalized_scores += normalized
+            valid_factor_count += 1
         
-        # 归一化到0-100分
+        if valid_factor_count == 0:
+            return pd.Series(50.0, index=stock_data.index)
+        
+        normalized_scores = normalized_scores / valid_factor_count
+        
         if len(normalized_scores) > 0:
             min_score = normalized_scores.min()
             max_score = normalized_scores.max()
             
             if max_score > min_score:
                 normalized_scores = (normalized_scores - min_score) / (max_score - min_score) * 100
+            else:
+                normalized_scores = pd.Series(50.0, index=stock_data.index)
         
         return normalized_scores
     
@@ -753,7 +767,7 @@
                        n_satellite: int = 2) -> Dict:
         """
         构建投资组合
-        
+
         Args:
             selected_stocks: 选中的股票 DataFrame (index: stock_code)
             alpha_scores: α得分 Series
@@ -762,7 +776,7 @@
             cash_ratio: 现金比例
             n_core: 核心持仓数量
             n_satellite: 卫星持仓数量
-            
+
         Returns:
             组合配置字典
         """
@@ -770,33 +784,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 +838,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 +856,7 @@
                 'alpha_score': row['alpha_score'],
                 'rank': n_core + idx + 1
             })
-        
+
         return portfolio
     
     def select_stocks(self, stock_data: pd.DataFrame, 
@@ -826,34 +864,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,23 +899,29 @@
                 min_turnover=0.5,
                 max_market_cap=500000.0
             )
-            
+
             print(f"✓ 筛选后剩余: {len(filtered)}只股票")
-            
+
             if len(filtered) < n:
                 print(f"⚠️ 筛选后股票数量({len(filtered)})少于选股数量({n})")
-                # 如果筛选后股票太少,放宽条件
                 if len(filtered) == 0:
-                    print("  → 放宽α得分阈值至70分")
+                    print("  → 放宽α得分阈值至60分")
                     filtered = self.filter_undervalued_high_alpha(
                         stock_data,
                         alpha_scores,
-                        alpha_threshold=70.0,
+                        alpha_threshold=60.0,
                         min_turnover=0.0,
                         max_market_cap=float('inf')
                     )
                     print(f"  → 放宽后剩余: {len(filtered)}只股票")
-            
+                    
+                if len(filtered) == 0:
+                    print("  → 直接按α得分排序选股")
+                    sorted_idx = alpha_scores.nlargest(n).index
+                    filtered = stock_data.loc[sorted_idx].copy()
+                    filtered['alpha_score'] = alpha_scores[sorted_idx]
+                    print(f"  → 直接选股: {len(filtered)}只")
+
             stock_data = filtered
             alpha_scores = alpha_scores[filtered.index]
         else:
@@ -886,10 +930,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 +942,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 +968,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__":

--
Gitblit v1.8.0