log
2026-07-23 8e0ca9e4e2dc7bd766f7ec26598d7a1a217b98c3
scripts/daily_master.py
@@ -24,6 +24,7 @@
import logging
import json
import pickle
from pathlib import Path
import pandas as pd
import numpy as np
from typing import Dict, List, Tuple, Optional
@@ -46,15 +47,188 @@
except ImportError:
    FACTOR_RISK_AVAILABLE = False
PROJECT_ROOT = Path(__file__).resolve().parents[1]
LOG_DIR = PROJECT_ROOT / 'logs'
LOG_DIR.mkdir(parents=True, exist_ok=True)
def _configure_console_encoding() -> None:
    """Keep Windows GBK consoles from aborting on symbols or emoji."""
    for stream in (sys.stdout, sys.stderr):
        reconfigure = getattr(stream, 'reconfigure', None)
        if reconfigure is None:
            continue
        try:
            reconfigure(errors='backslashreplace')
        except (OSError, ValueError):
            pass
_configure_console_encoding()
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('logs/daily_master.log'),
        logging.FileHandler(LOG_DIR / 'daily_master.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)
DEFAULT_MIN_LIQUIDITY_QUANTILE = 0.20
DEFAULT_MAX_BSE_RATIO = 0.30
DEFAULT_CANDIDATE_COUNT = 20
DEFAULT_FINAL_SELECTION_COUNT = 10
DEFAULT_MAX_DRAWDOWN_PCT = -40.0
def infer_stock_market(stock_code: str) -> str:
    """Classify normalized A-share codes into a broad listing market."""
    code = ''.join(ch for ch in str(stock_code) if ch.isdigit()).zfill(6)
    if code.startswith(('4', '8', '92')):
        return '北交所'
    if code.startswith('6'):
        return '上交所'
    return '深交所'
def filter_tradable_universe(
    df: pd.DataFrame,
    min_liquidity_quantile: float = DEFAULT_MIN_LIQUIDITY_QUANTILE,
) -> Tuple[pd.DataFrame, Dict]:
    """Remove special-treatment, delisting and illiquid rows before ranking."""
    working = df.copy()
    metadata = {
        'universe_before_filters': int(len(working)),
        'excluded_special_treatment': 0,
        'excluded_invalid_price': 0,
        'excluded_low_liquidity': 0,
        'liquidity_amount_threshold': None,
    }
    if 'stock_name' in working.columns:
        names = working['stock_name'].fillna('').astype(str)
    elif '股票名称' in working.columns:
        names = working['股票名称'].fillna('').astype(str)
    else:
        names = pd.Series('', index=working.index, dtype='object')
    upper_names = names.str.upper()
    special_treatment = upper_names.str.contains('ST', regex=False) | names.str.contains(
        '退', regex=False
    )
    metadata['excluded_special_treatment'] = int(special_treatment.sum())
    invalid_price = pd.Series(False, index=working.index)
    if 'close' in working.columns:
        prices = pd.to_numeric(working['close'], errors='coerce')
        invalid_price = prices.isna() | (prices <= 0)
    metadata['excluded_invalid_price'] = int(invalid_price.sum())
    low_liquidity = pd.Series(False, index=working.index)
    if 'amount' in working.columns:
        amounts = pd.to_numeric(working['amount'], errors='coerce')
        positive_amounts = amounts[amounts > 0]
        if len(positive_amounts) >= 20:
            threshold = float(positive_amounts.quantile(min_liquidity_quantile))
            low_liquidity = amounts.isna() | (amounts < threshold)
            metadata['liquidity_amount_threshold'] = threshold
        else:
            low_liquidity = amounts.isna() | (amounts <= 0)
    metadata['excluded_low_liquidity'] = int(low_liquidity.sum())
    excluded = special_treatment | invalid_price | low_liquidity
    working = working.loc[~excluded].copy()
    working['market'] = working['stock_code'].map(infer_stock_market)
    metadata['universe_after_filters'] = int(len(working))
    metadata['excluded_total'] = int(excluded.sum())
    return working, metadata
def calculate_dynamic_cross_section_score(
    df: pd.DataFrame,
    weights: Dict[str, float],
    evaluation: Dict[str, Dict],
) -> Tuple[pd.Series, List[str]]:
    """Calculate an IC-directed percentile score for one market cross-section."""
    usable = [
        factor
        for factor, weight in weights.items()
        if factor in df.columns and float(weight) > 0
    ]
    if not usable:
        return pd.Series(np.nan, index=df.index, dtype=float), []
    normalized_weights = {
        factor: float(weights[factor])
        for factor in usable
    }
    total_weight = sum(normalized_weights.values())
    if total_weight <= 0:
        return pd.Series(np.nan, index=df.index, dtype=float), []
    normalized_weights = {
        factor: weight / total_weight
        for factor, weight in normalized_weights.items()
    }
    score = pd.Series(0.0, index=df.index, dtype=float)
    applied = []
    for factor, weight in normalized_weights.items():
        values = pd.to_numeric(df[factor], errors='coerce')
        if values.notna().sum() < 2:
            continue
        factor_score = values.rank(pct=True, method='average')
        if evaluation.get(factor, {}).get('ic_mean', 0) < 0:
            factor_score = 1.0 - factor_score
        score += factor_score.fillna(0.5) * weight
        applied.append(factor)
    if not applied:
        return pd.Series(np.nan, index=df.index, dtype=float), []
    score_min = score.min()
    score_max = score.max()
    if score_max > score_min:
        score = (score - score_min) / (score_max - score_min)
    else:
        score[:] = 0.5
    return score, applied
def select_market_balanced_rows(
    df: pd.DataFrame,
    score_col: str,
    limit: int,
    max_bse_ratio: float = DEFAULT_MAX_BSE_RATIO,
) -> pd.DataFrame:
    """Select ranked rows while enforcing the BSE cap on every prefix."""
    if df is None or len(df) == 0 or limit <= 0:
        return pd.DataFrame(columns=df.columns if df is not None else None)
    ranked = df.sort_values(score_col, ascending=False, kind='mergesort').copy()
    if 'market' not in ranked.columns:
        ranked['market'] = ranked['stock_code'].map(infer_stock_market)
    remaining = list(ranked.index)
    selected_indices = []
    bse_count = 0
    while remaining and len(selected_indices) < limit:
        slot = len(selected_indices) + 1
        max_bse_for_prefix = int(np.ceil(slot * max_bse_ratio))
        chosen_position = None
        for position, index in enumerate(remaining):
            is_bse = ranked.at[index, 'market'] == '北交所'
            if not is_bse or bse_count < max_bse_for_prefix:
                chosen_position = position
                break
        if chosen_position is None:
            break
        index = remaining.pop(chosen_position)
        selected_indices.append(index)
        if ranked.at[index, 'market'] == '北交所':
            bse_count += 1
    return ranked.loc[selected_indices].copy()
def select_latest_complete_cross_section(
@@ -280,8 +454,7 @@
        advanced_factors = [
            'rel_momentum', 'rel_industry_momentum', 'industry_rank', 'market_rank',
            'industry_strength', 'vol_change', 'vol_ma_ratio', 'vol_price_trend',
            'downside_vol', 'reversal_5', 'reversal_10', 'price_position',
            'ml_score', 'final_score'
            'downside_vol', 'reversal_5', 'reversal_10', 'price_position'
        ]
        
        # 增强因子(来自enhanced_factor_system v4.0)
@@ -359,20 +532,24 @@
    
    def update_dynamic_weights(self, evaluation: Dict):
        """基于评估结果更新动态权重"""
        total_ic = sum(abs(f['ic_mean']) for f in evaluation.values() if f['effective'])
        weights = {}
        if total_ic > 0:
            for factor, result in evaluation.items():
                if result['effective']:
                    weights[factor] = abs(result['ic_mean']) / total_ic
                else:
                    weights[factor] = 0.01
        else:
            n = len(evaluation)
            if n > 0:
                equal_weight = 1.0 / n
                weights = {f: equal_weight for f in evaluation.keys()}
        effective = {
            factor: abs(result['ic_mean'])
            for factor, result in evaluation.items()
            if result.get('effective') and abs(result.get('ic_mean', 0)) > 0
        }
        if not effective:
            effective = {
                factor: abs(result.get('ic_mean', 0))
                for factor, result in evaluation.items()
                if abs(result.get('ic_mean', 0)) > 0
            }
        total_ic = sum(effective.values())
        weights = (
            {factor: value / total_ic for factor, value in effective.items()}
            if total_ic > 0
            else {}
        )
        
        with open(self.factor_weights_file, 'w', encoding='utf-8') as f:
            json.dump({
@@ -658,7 +835,8 @@
                            dynamic_weights: Dict,
                            portfolio: Dict,
                            backtest_results: Dict,
                            risk_signals: List[Dict]) -> str:
                            risk_signals: List[Dict],
                            factor_risk_analysis: Optional[Dict] = None) -> str:
        """生成完整报告"""
        now = datetime.now()
        
@@ -666,7 +844,7 @@
        lines.append('🦞 A股量化日报 - 盘前推送(增强版)')
        lines.append('━━━━━━━━━━━━━━━━━━━━━━━━')
        lines.append(f'📅 推送时间: {now.strftime("%Y-%m-%d %H:%M")}')
        lines.append(f'📌 类型: 实盘推送(含因子评估、风险控制)')
        lines.append('📌 类型: 量化研究候选(非交易指令)')
        lines.append('')
        
        lines.append('📊 因子有效性评估')
@@ -687,21 +865,26 @@
            for factor, result in sorted(factor_evaluation.items(), 
                                         key=lambda x: abs(x[1]['ic_mean']), reverse=True)[:6]:
                status = '✅' if result['effective'] else '⚠️'
                lines.append(f'{status} {factor}: IC={result["ic_mean"]:.3f}, IR={result["ir"]:.2f}')
                label = (
                    f'{factor}(样本外)'
                    if factor == 'ml_score_return_5d'
                    else factor
                )
                lines.append(f'{status} {label}: IC={result["ic_mean"]:.3f}, IR={result["ir"]:.2f}')
        else:
            lines.append('暂无因子评估数据')
        lines.append('')
        
        lines.append('⚖️ 动态因子权重')
        lines.append('⚖️ 已应用动态因子权重')
        lines.append('────────────────────')
        if dynamic_weights:
            for factor, weight in sorted(dynamic_weights.items(), key=lambda x: -x[1]):
                lines.append(f'  • {factor}: {weight*100:.1f}%')
        else:
            lines.append('使用默认等权')
            lines.append('本次未应用动态权重')
        lines.append('')
        
        lines.append('🎯 今日推荐')
        lines.append('🎯 今日研究候选')
        lines.append('────────────────────')
        
        stock_name_map = {}
@@ -712,6 +895,9 @@
            except:
                pass
        
        if not selected_stocks:
            lines.append('今日无满足交易池与风险约束的候选股票')
        for i, stock in enumerate(selected_stocks[:10], 1):
            code = stock.get('stock_code', stock.get('code', 'N/A'))
            name = stock.get('stock_name', stock.get('name', 'N/A'))
@@ -721,16 +907,37 @@
                code_num = code.replace('sh', '').replace('sz', '').replace('bj', '')
                name = stock_name_map.get(code_num, name)
            
            price = self._get_stock_price(code)
            try:
                price = float(stock.get('price', 0) or 0)
            except (TypeError, ValueError):
                price = 0.0
            if price <= 0:
                price = self._get_stock_price(code)
            price_str = f'¥{price:.2f}' if price > 0 else '价格未知'
            
            lines.append(f'{i}. {name}({code}) - α得分: {score:.2f} | {price_str}')
            market = stock.get('market', infer_stock_market(code))
            lines.append(f'{i}. {name}({code}) [{market}] - 综合得分: {score:.2f} | {price_str}')
            backtest = backtest_results.get(str(code), {})
            if backtest:
                lines.append(f'   📈 回测: 收益{backtest.get("total_return_pct", 0):.1f}% | '
                lines.append(f'   📈 近60日观察: 收益{backtest.get("total_return_pct", 0):.1f}% | '
                            f'夏普{backtest.get("sharpe_ratio", 0):.2f} | '
                            f'回撤{backtest.get("max_drawdown_pct", 0):.1f}% | '
                            f'胜率{backtest.get("win_rate_pct", 0):.0f}%')
        lines.append('')
        lines.append('🛡️ 因子风险暴露')
        lines.append('────────────────────')
        factor_risk_analysis = factor_risk_analysis or {}
        exposures = factor_risk_analysis.get('portfolio_exposure', {})
        if factor_risk_analysis.get('status') == 'ok' and exposures:
            for factor, exposure in sorted(
                exposures.items(), key=lambda item: abs(item[1]), reverse=True
            )[:5]:
                lines.append(f'  • {factor}: {exposure:+.2f}σ')
            alerts = factor_risk_analysis.get('exposure_alerts', [])
            lines.append(f'暴露预警: {len(alerts)}项' if alerts else '未触发暴露预警')
        else:
            lines.append(f'未形成有效风险暴露分析({factor_risk_analysis.get("status", "无数据")})')
        lines.append('')
        
        lines.append('💼 当前持仓')
@@ -753,7 +960,7 @@
                            f'{pnl_text} | '
                            f'¥{pos["current_value"]:,.0f}')
        else:
            lines.append('当前无持仓,建议按今日推荐建仓')
            lines.append('当前无模拟持仓')
        lines.append('')
        
        if risk_signals:
@@ -764,9 +971,9 @@
                lines.append(f'{emoji} {signal["stock_name"]}({signal["stock_code"]}): {signal["reason"]}')
            lines.append('')
            
            lines.append('📢 今日交易指令')
            lines.append('📢 模拟组合调整提示')
            lines.append('────────────────────')
            lines.append('【卖出指令】')
            lines.append('【模拟卖出提示】')
            sell_amount = 0
            for signal in risk_signals:
                if signal['type'] == 'stop_loss':
@@ -805,7 +1012,7 @@
            lines.append(f'操作后现金: ¥{cash_after:,.0f}')
            lines.append('')
            
            lines.append('【买入指令】')
            lines.append('【模拟买入观察】')
            if selected_stocks:
                industries = {}
                for i, stock in enumerate(selected_stocks[:5], 1):
@@ -815,7 +1022,12 @@
                        code_num = code.replace('sh', '').replace('sz', '').replace('bj', '')
                        name = stock_name_map.get(code_num, name)
                    
                    price = self._get_stock_price(code)
                    try:
                        price = float(stock.get('price', 0) or 0)
                    except (TypeError, ValueError):
                        price = 0.0
                    if price <= 0:
                        price = self._get_stock_price(code)
                    alloc_amount = cash_after * 0.12
                    
                    if price > 0:
@@ -859,15 +1071,15 @@
                lines.append('• 关注市场变化')
                lines.append('')
            else:
                lines.append('📢 今日操作建议')
                lines.append('📢 今日研究结论')
                lines.append('────────────────────')
                lines.append('• 当前无持仓,建议按今日推荐建仓')
                lines.append('• 分批买入,每只股票10-12%仓位')
                lines.append('• 保留25%现金应对加仓机会')
                lines.append('• 当前无模拟持仓,本报告仅保留候选观察')
                lines.append('• 未经过完整走样回测和交易成本验证,不生成实盘指令')
                lines.append('')
        
        lines.append('━━━━━━━━━━━━━━━━━━━━━━')
        lines.append('📊 数据来源: AKShare + 动态因子模型')
        lines.append('📊 数据来源: AKShare/BaoStock/腾讯行情 + 动态因子模型')
        lines.append('⚠️ 仅供量化研究与模拟验证,不构成投资建议')
        lines.append(f'🦞 A股量化系统 v3.1 | {now.strftime("%Y-%m-%d")}')
        
        return '\n'.join(lines)
@@ -893,11 +1105,14 @@
            logger.warning("⚠️ ML因子组合器不可用")
        self.ml_optimization_applied = False
        self.ml_optimization_status = (
            '未应用(模型尚未训练)'
            '未应用(独立二次排序模型尚未训练)'
            if self.ml_combiner is not None
            else '未应用(组件不可用)'
        )
        self.enhanced_factor_status = '未运行'
        self.enhanced_ml_metrics = {}
        self.dynamic_weight_status = '未应用'
        self.latest_selection_metadata = {}
        
        if DYNAMIC_WEIGHT_AVAILABLE:
            self.dynamic_weight_system = DynamicFactorWeightSystem()
@@ -982,10 +1197,11 @@
            
            effective_count = sum(1 for r in results.values() if r.get('effective', False))
            self.enhanced_factor_status = '已完成'
            self.enhanced_ml_metrics = ml_metrics
            logger.info(f"✓ 增强因子系统执行完成,有效因子: {effective_count}/{len(results)}")
            
            if ml_metrics:
                logger.info(f"  ML模型IR: {ml_metrics.get('ir', 0):.2f}")
                logger.info(f"  ML样本外IR: {ml_metrics.get('ir', 0):.2f}")
            
            return df
            
@@ -1032,14 +1248,17 @@
        logger.info(f"✓ 因子评估完成,有效因子{sum(1 for f in evaluation.values() if f['effective'])}个")
        return evaluation, dynamic_weights
    
    def select_stocks(self, df: pd.DataFrame) -> List[Dict]:
        """差异化选股"""
    def select_stocks(
        self,
        df: pd.DataFrame,
        dynamic_weights: Optional[Dict[str, float]] = None,
        factor_evaluation: Optional[Dict[str, Dict]] = None,
    ) -> List[Dict]:
        """Build a tradable, liquid and market-balanced candidate pool."""
        logger.info("🎯 执行差异化选股...")
        if len(df) == 0:
            return []
        # 数据源收盘时间可能不同,使用最近一个覆盖完整市场的交易日。
        selection_metadata = {}
        if {'date', 'stock_code'}.issubset(df.columns):
            df, selection_metadata = select_latest_complete_cross_section(df)
@@ -1053,79 +1272,114 @@
                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}"
                    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:
            df = df.groupby('stock_code').last().reset_index()
        logger.info(f"有{len(df)}只股票数据")
        # 检查是否有综合得分列(优先使用final_score)
        df, filter_metadata = filter_tradable_universe(df)
        selection_metadata.update(filter_metadata)
        logger.info(
            f"可交易股票池: {len(df)}只;排除ST/退市"
            f"{filter_metadata['excluded_special_treatment']}只,"
            f"低流动性{filter_metadata['excluded_low_liquidity']}只"
        )
        if len(df) == 0:
            logger.error("❌ 交易池过滤后无可选股票")
            self.latest_selection_metadata = selection_metadata
            return []
        score_col = None
        for col in ['final_score', 'alpha_score', 'score', '综合得分']:
            if col in df.columns:
                score_col = col
                break
        # 如果没有得分列,使用amount作为排序依据
        dynamic_weights = dynamic_weights or {}
        factor_evaluation = factor_evaluation or {}
        if dynamic_weights and factor_evaluation:
            dynamic_score, applied_factors = calculate_dynamic_cross_section_score(
                df,
                dynamic_weights,
                factor_evaluation,
            )
            if applied_factors:
                df['dynamic_score'] = dynamic_score
                score_col = 'dynamic_score'
                self.dynamic_weight_status = f'已应用({len(applied_factors)}个因子)'
                selection_metadata['applied_dynamic_factors'] = applied_factors
                logger.info(f"✓ 动态权重已参与排序: {len(applied_factors)}个因子")
        if score_col is None:
            if 'amount' in df.columns:
                df['temp_score'] = df['amount'] / df['amount'].max() if df['amount'].max() > 0 else 1.0
            for col in ['final_score', 'alpha_score', 'score', '综合得分']:
                if col in df.columns:
                    score_col = col
                    break
            if score_col is not None:
                self.dynamic_weight_status = '未应用(使用静态综合得分)'
                logger.warning(f"⚠️ 动态权重未应用,回退使用{score_col}")
            elif 'amount' in df.columns:
                max_amount = pd.to_numeric(df['amount'], errors='coerce').max()
                df['temp_score'] = (
                    pd.to_numeric(df['amount'], errors='coerce') / max_amount
                    if max_amount > 0
                    else 1.0
                )
                score_col = 'temp_score'
                logger.info("使用成交额作为排序依据")
                self.dynamic_weight_status = '未应用(使用成交额)'
                logger.warning("⚠️ 无综合得分,回退使用成交额排序")
            else:
                logger.error("❌ 无可用排序依据")
                return []
        if score_col == 'final_score':
            logger.info("使用高级因子系统final_score作为排序依据")
        # 按股票分组去重,然后按得分排序选取前20只不同股票
        unique_stocks = df.drop_duplicates(subset=['stock_code'])
        selected = unique_stocks.nlargest(20, score_col).copy()
        # 确保选出的股票不重复
        selected = selected.drop_duplicates(subset=['stock_code'])
        selected = select_market_balanced_rows(
            df.drop_duplicates(subset=['stock_code']),
            score_col,
            DEFAULT_CANDIDATE_COUNT,
        )
        result = []
        for idx, (_, row) in enumerate(selected.iterrows()):
            code = row.get('stock_code', '')
            # 确保股票代码为字符串
            if not isinstance(code, str):
                code = str(code)
            code = str(row.get('stock_code', '')).zfill(6)
            try:
                price = float(row.get('close', 0) or 0)
            except (TypeError, ValueError):
                price = 0.0
            result.append({
                'rank': idx + 1,
                'stock_code': code,
                'stock_name': row.get('stock_name', row.get('股票名称', f'股票{idx+1}')),
                'score': round(float(row.get(score_col, 0)), 4),
                'industry': row.get('industry', row.get('行业', '未知'))
                'industry': row.get('industry', row.get('行业', '未知')),
                'market': row.get('market', infer_stock_market(code)),
                'price': round(price, 4) if np.isfinite(price) and price > 0 else 0.0,
            })
        # 去重结果
        seen_codes = set()
        unique_result = []
        for item in result:
            if item['stock_code'] not in seen_codes:
                seen_codes.add(item['stock_code'])
                unique_result.append(item)
        bse_count = sum(stock['market'] == '北交所' for stock in result)
        selection_metadata.update({
            'score_method': score_col,
            'candidate_count': len(result),
            'candidate_bse_count': bse_count,
            'max_bse_ratio': DEFAULT_MAX_BSE_RATIO,
        })
        self.latest_selection_metadata = selection_metadata
        logger.info(
            f"✓ 生成{len(result)}只候选,北交所{bse_count}只"
            f"(上限{DEFAULT_MAX_BSE_RATIO:.0%})"
        )
        return result
    def save_selection_result(
        self,
        selected_stocks: List[Dict],
        candidate_stocks: Optional[List[Dict]] = None,
    ) -> None:
        """Persist final risk-approved selections as the primary result."""
        with open(self.selection_file, 'w', encoding='utf-8') as f:
            json.dump({
                'selected_stocks': unique_result,
                'selected_stocks': selected_stocks,
                'candidate_stocks': candidate_stocks or [],
                'timestamp': datetime.now().isoformat(),
                'selection_metadata': selection_metadata,
                'selection_metadata': self.latest_selection_metadata,
            }, f, indent=2, ensure_ascii=False)
        logger.info(f"✓ 选股完成,选出{len(unique_result)}只股票")
        return unique_result[:10]
    
    def optimize_with_ml(self, df: pd.DataFrame, selected_stocks: List[Dict]) -> List[Dict]:
        """使用ML因子组合优化选股结果"""
@@ -1136,8 +1390,8 @@
            return selected_stocks
        if not getattr(self.ml_combiner, 'is_fitted', False):
            logger.warning("⚠️ ML模型尚未训练,跳过二次优化并保留final_score排序")
            self.ml_optimization_status = '未应用(模型尚未训练)'
            logger.warning("⚠️ 独立ML二次排序模型尚未训练,保留动态因子排序")
            self.ml_optimization_status = '未应用(独立二次排序模型尚未训练)'
            return selected_stocks
        
        logger.info("🤖 ML因子组合优化...")
@@ -1220,53 +1474,82 @@
        """分析因子风险和暴露"""
        if self.factor_risk_model is None:
            logger.warning("⚠️ 因子风险模型不可用")
            return {}
            return {'status': 'unavailable'}
        if not selected_stocks:
            return {'status': 'no_selection'}
        
        logger.info("📊 分析因子风险暴露...")
        
        try:
            selected_codes = [s['stock_code'] for s in selected_stocks]
            factor_cols = [col for col in df.columns if col in [
                'pe_ratio', 'pb_ratio', 'roe', 'roa', 'debt_ratio',
                'current_ratio', 'gross_margin', 'net_margin',
                'revenue_growth', 'profit_growth', 'momentum_1m',
                'momentum_3m', 'volatility_20d', 'turnover_rate'
            ]]
            if len(factor_cols) == 0:
            selected_codes = [str(s['stock_code']).zfill(6) for s in selected_stocks]
            factor_candidates = [
                'momentum_20', 'momentum_60', 'volatility_20',
                'turnover_zscore', 'amount_zscore', 'amount_rank',
                'rel_strength_ma60', 'industry_strength', 'sharpe_proxy',
            ]
            factor_cols = [col for col in factor_candidates if col in df.columns]
            if not factor_cols:
                logger.warning("⚠️ 无可用因子数据")
                return {}
            latest_df = df
                return {'status': 'no_factors'}
            risk_columns = ['stock_code'] + factor_cols
            if 'date' in df.columns:
                latest_date = df['date'].max()
                latest_df = df[df['date'] == latest_date]
            factor_data = latest_df[latest_df['stock_code'].isin(selected_codes)][factor_cols].fillna(0)
            if len(factor_data) == 0:
                return {}
            portfolio_exposure = self.factor_risk_model.calculate_portfolio_exposure(
                factor_data.values,
                weights=None
                normalized_dates = pd.to_datetime(df['date'], errors='coerce').dt.normalize()
                selection_date = self.latest_selection_metadata.get('selection_date')
                target_date = (
                    pd.Timestamp(selection_date).normalize()
                    if selection_date
                    else normalized_dates.max()
                )
                latest_df = df.loc[
                    normalized_dates == target_date,
                    risk_columns,
                ].copy()
            else:
                latest_df = df[risk_columns].copy()
            latest_df['stock_code'] = latest_df['stock_code'].astype(str).str.zfill(6)
            latest_df = latest_df.drop_duplicates('stock_code').set_index('stock_code')
            exposures = pd.DataFrame(index=latest_df.index)
            for factor in factor_cols:
                values = pd.to_numeric(latest_df[factor], errors='coerce')
                std = values.std()
                if pd.notna(std) and std > 0:
                    exposures[factor] = (values - values.mean()) / std
            exposures = exposures.fillna(0.0)
            selected_codes = [code for code in selected_codes if code in exposures.index]
            if not selected_codes or exposures.empty:
                logger.warning("⚠️ 候选股票缺少风险暴露数据")
                return {'status': 'no_exposure'}
            position_weight = 1.0 / len(selected_codes)
            positions = {code: position_weight for code in selected_codes}
            portfolio_exposure = self.factor_risk_model.calculate_portfolio_factor_exposure(
                positions,
                exposures,
            )
            exposure_alerts = self.factor_exposure_monitor.check_exposure(
                portfolio_exposure
            )
            risk_attribution = self.factor_risk_model.risk_attribution(
                factor_data.values,
                weights=None
            )
            total_abs_exposure = float(portfolio_exposure.abs().sum())
            risk_attribution = {
                factor: (
                    abs(float(value)) / total_abs_exposure
                    if total_abs_exposure > 0
                    else 0.0
                )
                for factor, value in portfolio_exposure.items()
            }
            result = {
                'portfolio_exposure': portfolio_exposure,
                'status': 'ok',
                'portfolio_exposure': {
                    factor: round(float(value), 4)
                    for factor, value in portfolio_exposure.items()
                },
                'exposure_alerts': exposure_alerts,
                'risk_attribution': risk_attribution,
                'factor_names': factor_cols
                'factor_names': list(exposures.columns),
            }
            
            if exposure_alerts:
@@ -1277,12 +1560,12 @@
            return result
            
        except Exception as e:
            logger.error(f"❌ 因子风险分析失败: {e}")
            return {}
            logger.error(f"❌ 因子风险分析失败: {e}", exc_info=True)
            return {'status': 'error', 'error': str(e)}
    def validate_stocks(self, df: pd.DataFrame, selected_stocks: List[Dict]) -> Tuple[Dict, List[Dict]]:
        """回实验证选中的股票"""
        logger.info("📊 回实验证选中股票...")
        """Apply a recent-history risk screen to candidate stocks."""
        logger.info("📊 检查候选股票近60日风险...")
        validator = StockBacktestValidator(df)
        
        results = {}
@@ -1290,16 +1573,16 @@
            code = str(stock['stock_code'])
            results[code] = validator.quick_backtest(code)
        
        # 风险过滤:排除回撤>-50%的股票
        filtered_stocks = []
        for stock in selected_stocks:
            code = str(stock['stock_code'])
            backtest = results.get(code, {})
            max_drawdown = backtest.get('max_drawdown_pct', 0)
            # 只保留回撤<=50%的股票
            if max_drawdown >= -50:
            is_reliable = backtest.get('is_reliable', False)
            if is_reliable and max_drawdown >= DEFAULT_MAX_DRAWDOWN_PCT:
                filtered_stocks.append(stock)
            elif not is_reliable:
                logger.warning(f"⚠️ 股票{code}历史数据不足,已排除")
            else:
                logger.warning(f"⚠️ 股票{code}回撤过大({max_drawdown:.1f}%),已排除")
        
@@ -1307,7 +1590,7 @@
        if len(filtered_stocks) < len(selected_stocks):
            logger.warning(f"⚠️ 风险过滤后剩余{len(filtered_stocks)}只股票(原{len(selected_stocks)}只)")
        
        logger.info("✓ 回实验证完成")
        logger.info("✓ 历史风险检查完成")
        return results, filtered_stocks
    
    def update_portfolio(self, df: pd.DataFrame, selected_stocks: List[Dict]):
@@ -1331,19 +1614,28 @@
        
        portfolio = self.portfolio_tracker.state
        if not portfolio['positions']:
            logger.info("📝 无持仓,推送将提供建仓建议")
            logger.info("📝 无模拟持仓,报告仅提供研究候选")
        
        logger.info("✓ 持仓更新完成")
        return portfolio, risk_signals
    
    def generate_and_save_report(self, selected_stocks, factor_evaluation,
                                dynamic_weights, portfolio, backtest_results, risk_signals):
    def generate_and_save_report(
        self,
        selected_stocks,
        factor_evaluation,
        dynamic_weights,
        portfolio,
        backtest_results,
        risk_signals,
        factor_risk_analysis=None,
    ):
        """生成并保存报告"""
        logger.info("📝 生成报告...")
        try:
            report = self.report_generator.generate_full_report(
                selected_stocks, factor_evaluation, dynamic_weights, 
                portfolio, backtest_results, risk_signals
                portfolio, backtest_results, risk_signals,
                factor_risk_analysis=factor_risk_analysis,
            )
            
            os.makedirs('reports', exist_ok=True)
@@ -1396,37 +1688,80 @@
                logger.warning(f"   平均IC: {avg_ic:.4f}")
                logger.warning("   建议:检查数据质量或调整因子参数")
            
            dynamic_factor_weights = self.apply_dynamic_weights(df)
            if dynamic_factor_weights:
                logger.info(f"  动态权重: {list(dynamic_factor_weights.items())[:3]}...")
            selected_stocks = self.select_stocks(df)
            candidate_stocks = self.select_stocks(
                df,
                dynamic_weights=dynamic_weights,
                factor_evaluation=factor_evaluation,
            )
            
            if effective_count == 0:
                logger.warning("⚠️ 因子无效,选股结果仅供参考")
            
            selected_stocks = self.optimize_with_ml(df, selected_stocks)
            factor_risk_analysis = self.analyze_factor_risk(df, selected_stocks)
            backtest_results, filtered_stocks = self.validate_stocks(df, selected_stocks)
            if len(filtered_stocks) == 0:
                logger.warning("⚠️ 风险过滤后无股票可选,使用原始选股结果")
                filtered_stocks = selected_stocks
            portfolio, risk_signals = self.update_portfolio(df, filtered_stocks)
            report, report_file = self.generate_and_save_report(
                filtered_stocks, factor_evaluation, dynamic_weights,
                portfolio, backtest_results, risk_signals
            candidate_stocks = self.optimize_with_ml(df, candidate_stocks)
            backtest_results, risk_approved = self.validate_stocks(df, candidate_stocks)
            if risk_approved:
                approved_df = pd.DataFrame(risk_approved)
                ranking_col = (
                    'combined_score'
                    if 'combined_score' in approved_df.columns
                    else 'score'
                )
                final_df = select_market_balanced_rows(
                    approved_df,
                    ranking_col,
                    DEFAULT_FINAL_SELECTION_COUNT,
                )
                selected_stocks = final_df.to_dict('records')
            else:
                logger.warning("⚠️ 风险过滤后无股票可选,本次输出空候选")
                selected_stocks = []
            for rank, stock in enumerate(selected_stocks, start=1):
                stock['rank'] = rank
            final_bse_count = sum(
                stock.get('market') == '北交所' for stock in selected_stocks
            )
            self.latest_selection_metadata.update({
                'risk_approved_count': len(risk_approved),
                'final_selection_count': len(selected_stocks),
                'final_bse_count': final_bse_count,
            })
            self.save_selection_result(selected_stocks, candidate_stocks)
            factor_risk_analysis = self.analyze_factor_risk(df, selected_stocks)
            portfolio, risk_signals = self.update_portfolio(df, selected_stocks)
            applied_factor_names = set(
                self.latest_selection_metadata.get('applied_dynamic_factors', [])
            )
            report_weights = {
                factor: weight
                for factor, weight in dynamic_weights.items()
                if factor in applied_factor_names
            }
            report_weight_total = sum(report_weights.values())
            if report_weight_total > 0:
                report_weights = {
                    factor: weight / report_weight_total
                    for factor, weight in report_weights.items()
                }
            report, report_file = self.generate_and_save_report(
                selected_stocks, factor_evaluation, report_weights,
                portfolio, backtest_results, risk_signals,
                factor_risk_analysis=factor_risk_analysis,
            )
            if report is None:
                return False
            
            logger.info("\n" + "="*70)
            logger.info("✅ 每日主控流程完成")
            logger.info(f"  - 选股数量: {len(filtered_stocks)}")
            logger.info(f"  - 选股数量: {len(selected_stocks)}")
            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(f"  - ML二次排序: {self.ml_optimization_status}")
            logger.info(f"  - 动态权重: {self.dynamic_weight_status}")
            logger.info(
                f"  - 因子风险: {factor_risk_analysis.get('status', 'unknown')}"
            )
            logger.info("="*70)
            
            return True