from __future__ import annotations

from backend.features.screener.strategies import ADVANCED_CURATED_STRATEGIES
from backend.features.screener.signals import attach_strategy_validity


REGIMES = {
    "ice": "冰点",
    "repair": "修复",
    "fermentation": "发酵",
    "climax": "高潮",
    "divergence": "分化",
    "retreat": "退潮",
}

FACTOR_FIELDS = {
    "close": "收盘价",
    "pct_chg": "当日涨幅",
    "return_5d": "5日涨幅",
    "return_10d": "10日涨幅",
    "return_20d": "20日涨幅",
    "return_60d": "60日涨幅",
    "return_5d_rank": "5日涨幅排名",
    "momentum_60_5": "中期动量",
    "momentum_60_5_rank": "中期动量排名",
    "above_ma20": "站上20日线",
    "rsi_6": "RSI(6)",
    "ma60_slope": "60日线斜率",
    "ma20_slope_5d": "20日线5日斜率",
    "ma_bull_alignment": "均线多头排列",
    "drawdown_from_high_250": "距250日高点回撤",
    "donchian_breakout_pct": "唐奇安突破幅度",
    "range_20d": "20日振幅",
    "rs_high_120": "RS线120日新高",
    "excess_return_60d": "60日超额收益",
    "weekly_trend_signal": "周线趋势信号",
    "daily_buy_trigger": "日线买点",
    "weekly_amount_trend": "周成交趋势",
    "volume_ratio_5d": "5日量比",
    "turnover_5d": "5日累计换手",
    "volatility_10d": "10日波动率",
    "amount_billion": "成交额",
    "turnover_rate": "换手率",
    "circ_mv_billion": "流通市值",
    "net_flow_million": "主力净流入",
    "large_flow_million": "大单净流入",
    "net_flow_5d_million": "5日主力净流入",
    "flow_to_circ_mv_5d": "5日净流入占流通市值",
    "sector_strength": "板块强度",
    "sector_return_5d": "行业5日涨幅",
    "sector_return_20d": "行业20日涨幅",
    "sector_momentum_rank": "行业20日动量排名",
    "sector_stock_momentum_rank": "行业内个股动量排名",
    "sector_net_flow_5d_million": "行业5日主力净流入",
    "sector_flow_rank": "行业资金流排名",
    "sector_prosperity_rank": "行业景气度排名",
    "sector_trend_rank": "行业趋势排名",
    "sector_crowding_rank": "行业拥挤度排名",
    "sector_composite_score": "行业三维综合分",
    "sector_limit_count": "板块涨停数",
    "sector_up_count": "板块强势股数",
    "relative_strength": "相对强度",
    "limit_streak": "连板高度",
    "auction_change": "竞价涨幅",
    "auction_amount_million": "竞价成交额",
    "auction_turnover_rate": "竞价换手率",
    "auction_volume_ratio": "竞价量比",
    "total_mv_billion": "总市值",
    "pe_ttm": "市盈率TTM",
    "pb": "市净率",
    "ps_ttm": "市销率TTM",
    "dividend_yield_ttm": "股息率TTM",
    "dividend_years": "近年持续分红",
    "roe": "净资产收益率",
    "roa": "总资产收益率",
    "roic": "投入资本回报率",
    "gross_margin": "销售毛利率",
    "netprofit_yoy": "净利润同比",
    "revenue_yoy": "营业收入同比",
    "ocf_to_opincome": "经营现金流质量",
    "earnings_surprise_pct": "业绩超预期幅度",
    "earnings_days_since_announce": "业绩公告后天数",
    "earnings_event_quality": "业绩事件质量",
    "popularity_score": "人气榜热度",
    "popularity_rank_change": "人气排名跃升",
    "popularity_dual_source": "双榜共识",
    "institution_net_buy_million": "机构席位净买入",
    "institution_seat_count": "机构席位数",
    "style_size_fit": "大小盘风格匹配",
    "style_growth_fit": "成长价值风格匹配",
    "style_fit_score": "当前风格匹配度",
    "factor_value_score": "价值因子分",
    "factor_growth_score": "成长因子分",
    "factor_quality_score": "质量因子分",
    "factor_momentum_score": "动量因子分",
    "factor_sentiment_score": "交易情绪因子分",
    "multi_factor_composite": "动态多因子综合分",
    "relative_position_60": "60日相对位置",
    "max_abs_change_15d": "15日最大波动",
    "close_to_high_15d": "距15日高点",
    "close_to_high_60d": "距60日高点",
    "no_limit_30d": "近30日无涨停",
    "had_limit_80d": "近80日曾涨停",
    "previous_first_limit": "昨日首板",
    "previous_limit_signal": "昨日涨停或触板",
    "previous_limit_streak": "昨日连板高度",
    "previous_amount_billion": "昨日成交额",
    "is_limit_up_today": "当日涨停",
    "is_limit_down_today": "当日跌停",
    "sector_breadth_ma20": "行业20日线宽度",
    "no_limit_down_20d": "近20日无跌停",
    "financial_risk": "财务风险标记",
    "is_market_height": "当前市场最高板",
    "new_space_board": "新晋空间板",
    "max_continuous_board_10d": "近10日最高连板",
    "dragon_first_yin": "龙头首阴",
    "yin_day_pct": "首阴跌幅",
    "vol_vs_previous": "较前日量能",
    "broken_reversal": "断板反包",
    "days_since_broken": "断板后天数",
    "close_above_broken_high": "收复断板高点",
    "vol_vs_broken_day": "较断板日量能",
    "recent_limit_up_5d": "近5日涨停次数",
    "intraday_min_pct": "盘中最大跌幅",
    "lower_shadow_ratio": "下影线实体比",
}

FACTOR_GROUPS = {
    "行情动量": [
        "close", "pct_chg", "return_5d", "return_10d", "return_20d", "return_60d",
        "return_5d_rank", "momentum_60_5", "momentum_60_5_rank", "above_ma20",
        "rsi_6", "ma60_slope", "ma20_slope_5d", "ma_bull_alignment",
        "drawdown_from_high_250", "donchian_breakout_pct", "range_20d",
        "rs_high_120", "excess_return_60d", "weekly_trend_signal",
        "daily_buy_trigger", "weekly_amount_trend", "relative_strength",
        "relative_position_60", "close_to_high_15d", "close_to_high_60d",
    ],
    "量价交易": [
        "volume_ratio_5d", "turnover_5d", "volatility_10d", "amount_billion", "turnover_rate",
        "net_flow_million", "large_flow_million", "net_flow_5d_million",
        "flow_to_circ_mv_5d", "previous_amount_billion",
        "intraday_min_pct", "lower_shadow_ratio", "vol_vs_previous", "vol_vs_broken_day",
    ],
    "板块结构": [
        "sector_strength", "sector_return_5d", "sector_return_20d", "sector_momentum_rank",
        "sector_stock_momentum_rank", "sector_net_flow_5d_million", "sector_flow_rank",
        "sector_prosperity_rank", "sector_trend_rank", "sector_crowding_rank",
        "sector_composite_score",
        "sector_limit_count", "sector_up_count", "sector_breadth_ma20",
        "limit_streak", "previous_limit_streak", "previous_first_limit", "previous_limit_signal",
        "is_limit_up_today", "is_limit_down_today",
        "no_limit_30d", "had_limit_80d", "max_abs_change_15d", "no_limit_down_20d",
        "is_market_height", "new_space_board", "max_continuous_board_10d",
        "dragon_first_yin", "yin_day_pct", "broken_reversal", "days_since_broken",
        "close_above_broken_high", "recent_limit_up_5d",
    ],
    "竞价因子": [
        "auction_change", "auction_amount_million", "auction_turnover_rate", "auction_volume_ratio",
    ],
    "估值规模": [
        "circ_mv_billion", "total_mv_billion", "pe_ttm", "pb", "ps_ttm",
        "dividend_yield_ttm", "dividend_years",
    ],
    "财务质量": [
        "roe", "roa", "roic", "gross_margin", "netprofit_yoy", "revenue_yoy",
        "ocf_to_opincome", "financial_risk",
        "earnings_surprise_pct", "earnings_days_since_announce", "earnings_event_quality",
    ],
    "特色数据": [
        "popularity_score", "popularity_rank_change", "popularity_dual_source",
        "institution_net_buy_million", "institution_seat_count",
        "style_size_fit", "style_growth_fit", "style_fit_score",
        "factor_value_score", "factor_growth_score", "factor_quality_score",
        "factor_momentum_score", "factor_sentiment_score", "multi_factor_composite",
    ],
}

ALLOWED_OPERATORS = {">", ">=", "<", "<=", "==", "!=", "between", "in"}


BUILTIN_STRATEGIES = [
    {
        "name": "冰点抗跌先手",
        "description": "寻找冰点中保持相对强度、低波动且有板块承接的个股，允许无结果。",
        "regimes": ["ice"],
        "formula": {
            "universe": {"exclude_st": True, "listed_days_min": 120},
            "filters": [
                {"field": "pct_chg", "op": "between", "value": [-3, 7]},
                {"field": "return_5d", "op": ">=", "value": -5},
                {"field": "amount_billion", "op": ">=", "value": 1},
                {"field": "volatility_10d", "op": "<=", "value": 7},
            ],
            "score": [
                {"field": "relative_strength", "weight": 0.30, "direction": "desc"},
                {"field": "sector_strength", "weight": 0.25, "direction": "desc"},
                {"field": "volume_ratio_5d", "weight": 0.20, "direction": "desc"},
                {"field": "volatility_10d", "weight": 0.15, "direction": "asc"},
                {"field": "amount_billion", "weight": 0.10, "direction": "desc"},
            ],
            "limit": 12,
            "min_score": 0.58,
        },
    },
    {
        "name": "修复先锋",
        "description": "筛选率先站回趋势、温和放量并获得板块共振的修复前排。",
        "regimes": ["repair"],
        "formula": {
            "universe": {"exclude_st": True, "listed_days_min": 120},
            "filters": [
                {"field": "pct_chg", "op": "between", "value": [1, 9.7]},
                {"field": "return_5d", "op": ">", "value": 0},
                {"field": "above_ma20", "op": "==", "value": 1},
                {"field": "volume_ratio_5d", "op": ">=", "value": 1.05},
            ],
            "score": [
                {"field": "sector_strength", "weight": 0.28, "direction": "desc"},
                {"field": "relative_strength", "weight": 0.24, "direction": "desc"},
                {"field": "volume_ratio_5d", "weight": 0.18, "direction": "desc"},
                {"field": "net_flow_million", "weight": 0.16, "direction": "desc"},
                {"field": "amount_billion", "weight": 0.14, "direction": "desc"},
            ],
            "limit": 15,
            "min_score": 0.54,
        },
    },
    {
        "name": "主线发酵跟随",
        "description": "在主线扩散期寻找趋势、成交承载和板块涨停梯队共同增强的个股。",
        "regimes": ["fermentation"],
        "formula": {
            "universe": {"exclude_st": True, "listed_days_min": 120},
            "filters": [
                {"field": "pct_chg", "op": "between", "value": [0, 9.8]},
                {"field": "return_5d", "op": ">=", "value": 3},
                {"field": "above_ma20", "op": "==", "value": 1},
                {"field": "amount_billion", "op": ">=", "value": 2},
            ],
            "score": [
                {"field": "sector_limit_count", "weight": 0.25, "direction": "desc"},
                {"field": "sector_strength", "weight": 0.24, "direction": "desc"},
                {"field": "return_10d", "weight": 0.20, "direction": "desc"},
                {"field": "amount_billion", "weight": 0.16, "direction": "desc"},
                {"field": "large_flow_million", "weight": 0.15, "direction": "desc"},
            ],
            "limit": 15,
            "min_score": 0.55,
        },
    },
    {
        "name": "高潮核心去后排",
        "description": "高潮阶段只保留容量、趋势和辨识度较高的核心，降低后排跟风权重。",
        "regimes": ["climax"],
        "formula": {
            "universe": {"exclude_st": True, "listed_days_min": 120},
            "filters": [
                {"field": "pct_chg", "op": "between", "value": [-2, 7]},
                {"field": "return_10d", "op": ">=", "value": 5},
                {"field": "above_ma20", "op": "==", "value": 1},
                {"field": "amount_billion", "op": ">=", "value": 5},
            ],
            "score": [
                {"field": "amount_billion", "weight": 0.28, "direction": "desc"},
                {"field": "sector_strength", "weight": 0.22, "direction": "desc"},
                {"field": "relative_strength", "weight": 0.20, "direction": "desc"},
                {"field": "volatility_10d", "weight": 0.15, "direction": "asc"},
                {"field": "limit_streak", "weight": 0.15, "direction": "desc"},
            ],
            "limit": 10,
            "min_score": 0.62,
        },
    },
    {
        "name": "分化承接回流",
        "description": "寻找分化中仍有趋势承接、板块强度和资金回流的核心候选。",
        "regimes": ["divergence"],
        "formula": {
            "universe": {"exclude_st": True, "listed_days_min": 120},
            "filters": [
                {"field": "pct_chg", "op": "between", "value": [-3, 7]},
                {"field": "return_5d", "op": ">", "value": 0},
                {"field": "above_ma20", "op": "==", "value": 1},
                {"field": "volume_ratio_5d", "op": "between", "value": [0.7, 3.5]},
            ],
            "score": [
                {"field": "relative_strength", "weight": 0.28, "direction": "desc"},
                {"field": "sector_strength", "weight": 0.24, "direction": "desc"},
                {"field": "net_flow_million", "weight": 0.20, "direction": "desc"},
                {"field": "volatility_10d", "weight": 0.16, "direction": "asc"},
                {"field": "amount_billion", "weight": 0.12, "direction": "desc"},
            ],
            "limit": 12,
            "min_score": 0.57,
        },
    },
    {
        "name": "退潮防守观察",
        "description": "退潮期采用高门槛防守筛选，结果为空代表当前不宜主动出击。",
        "regimes": ["retreat"],
        "formula": {
            "universe": {"exclude_st": True, "listed_days_min": 180},
            "filters": [
                {"field": "pct_chg", "op": "between", "value": [-2, 4]},
                {"field": "return_5d", "op": ">=", "value": -2},
                {"field": "above_ma20", "op": "==", "value": 1},
                {"field": "volatility_10d", "op": "<=", "value": 4.5},
                {"field": "amount_billion", "op": ">=", "value": 2},
            ],
            "score": [
                {"field": "volatility_10d", "weight": 0.30, "direction": "asc"},
                {"field": "relative_strength", "weight": 0.25, "direction": "desc"},
                {"field": "amount_billion", "weight": 0.20, "direction": "desc"},
                {"field": "sector_strength", "weight": 0.15, "direction": "desc"},
                {"field": "net_flow_million", "weight": 0.10, "direction": "desc"},
            ],
            "limit": 8,
            "min_score": 0.68,
        },
    },
    {
        "name": "竞价强势确认",
        "description": "用竞价涨幅、成交承载和量比确认修复或发酵阶段的主动进攻标的。",
        "regimes": ["repair", "fermentation", "divergence"],
        "formula": {
            "universe": {"exclude_st": True, "listed_days_min": 120},
            "filters": [
                {"field": "auction_change", "op": "between", "value": [1, 7]},
                {"field": "auction_amount_million", "op": ">=", "value": 3},
                {"field": "auction_volume_ratio", "op": ">=", "value": 0.8},
                {"field": "amount_billion", "op": ">=", "value": 1},
            ],
            "score": [
                {"field": "auction_amount_million", "weight": 0.26, "direction": "desc"},
                {"field": "auction_volume_ratio", "weight": 0.22, "direction": "desc"},
                {"field": "auction_change", "weight": 0.18, "direction": "desc"},
                {"field": "sector_strength", "weight": 0.18, "direction": "desc"},
                {"field": "relative_strength", "weight": 0.16, "direction": "desc"},
            ],
            "limit": 15,
            "min_score": 0.56,
        },
    },
]

for _strategy in BUILTIN_STRATEGIES:
    _strategy["formula"].setdefault("meta", {
        "library": "smart", "category": "周期策略", "quality": "系统",
        "frequency": "每日", "risk": "随市场阶段", "data_group": "行情因子",
    })


CURATED_STRATEGIES = [
    {
        "name": "连续分红质量",
        "description": "寻找持续派息、盈利质量稳定且波动可控的长期现金回报型公司。",
        "regimes": list(REGIMES),
        "formula": {
            "meta": {"library": "curated", "category": "红利价值", "quality": "A", "frequency": "月度", "risk": "中低", "data_group": "估值与财务"},
            "universe": {"exclude_st": True, "listed_days_min": 1095},
            "filters": [
                {"field": "dividend_years", "op": ">=", "value": 4},
                {"field": "dividend_yield_ttm", "op": ">=", "value": 2},
                {"field": "roe", "op": ">=", "value": 6},
                {"field": "pb", "op": "between", "value": [0.1, 4]},
            ],
            "score": [
                {"field": "dividend_yield_ttm", "weight": 0.30, "direction": "desc"},
                {"field": "roe", "weight": 0.24, "direction": "desc"},
                {"field": "ocf_to_opincome", "weight": 0.18, "direction": "desc"},
                {"field": "volatility_10d", "weight": 0.16, "direction": "asc"},
                {"field": "total_mv_billion", "weight": 0.12, "direction": "desc"},
            ], "limit": 20, "min_score": 0.52,
        },
    },
    {
        "name": "ROIC质量低波",
        "description": "以投入资本回报、毛利率和估值为核心，寻找低波动的高质量公司。",
        "regimes": ["ice", "repair", "divergence", "retreat"],
        "formula": {
            "meta": {"library": "curated", "category": "质量价值", "quality": "A-", "frequency": "月度", "risk": "中低", "data_group": "估值与财务"},
            "universe": {"exclude_st": True, "listed_days_min": 730},
            "filters": [
                {"field": "roic", "op": ">=", "value": 6},
                {"field": "gross_margin", "op": ">=", "value": 15},
                {"field": "pe_ttm", "op": "between", "value": [1, 45]},
                {"field": "amount_billion", "op": ">=", "value": 1},
            ],
            "score": [
                {"field": "roic", "weight": 0.28, "direction": "desc"},
                {"field": "gross_margin", "weight": 0.22, "direction": "desc"},
                {"field": "ps_ttm", "weight": 0.18, "direction": "asc"},
                {"field": "volatility_10d", "weight": 0.18, "direction": "asc"},
                {"field": "total_mv_billion", "weight": 0.14, "direction": "desc"},
            ], "limit": 20, "min_score": 0.54,
        },
    },
    {
        "name": "低估值现金流白马",
        "description": "筛选估值克制、经营现金流健康、资产回报稳定的大中型公司。",
        "regimes": ["ice", "repair", "divergence", "retreat"],
        "formula": {
            "meta": {"library": "curated", "category": "现金流价值", "quality": "A-", "frequency": "月度", "risk": "中低", "data_group": "估值与财务"},
            "universe": {"exclude_st": True, "listed_days_min": 730},
            "filters": [
                {"field": "pb", "op": "between", "value": [0.1, 1.8]},
                {"field": "roa", "op": ">=", "value": 3},
                {"field": "ocf_to_opincome", "op": ">", "value": 0},
                {"field": "netprofit_yoy", "op": ">=", "value": -15},
                {"field": "total_mv_billion", "op": ">=", "value": 100},
            ],
            "score": [
                {"field": "roa", "weight": 0.26, "direction": "desc"},
                {"field": "ocf_to_opincome", "weight": 0.24, "direction": "desc"},
                {"field": "pb", "weight": 0.20, "direction": "asc"},
                {"field": "total_mv_billion", "weight": 0.16, "direction": "desc"},
                {"field": "volatility_10d", "weight": 0.14, "direction": "asc"},
            ], "limit": 20, "min_score": 0.53,
        },
    },
    {
        "name": "高增长合理估值",
        "description": "在收入和利润同步增长的公司中，优先选择估值合理、趋势得到确认的标的。",
        "regimes": ["repair", "fermentation", "divergence"],
        "formula": {
            "meta": {"library": "curated", "category": "成长质量", "quality": "B+", "frequency": "月度", "risk": "中", "data_group": "估值与财务"},
            "universe": {"exclude_st": True, "listed_days_min": 365},
            "filters": [
                {"field": "pe_ttm", "op": "between", "value": [1, 35]},
                {"field": "revenue_yoy", "op": ">=", "value": 10},
                {"field": "netprofit_yoy", "op": ">=", "value": 15},
                {"field": "roe", "op": ">=", "value": 5},
                {"field": "amount_billion", "op": ">=", "value": 1},
            ],
            "score": [
                {"field": "netprofit_yoy", "weight": 0.27, "direction": "desc"},
                {"field": "revenue_yoy", "weight": 0.23, "direction": "desc"},
                {"field": "roe", "weight": 0.20, "direction": "desc"},
                {"field": "pe_ttm", "weight": 0.16, "direction": "asc"},
                {"field": "relative_strength", "weight": 0.14, "direction": "desc"},
            ], "limit": 20, "min_score": 0.55,
        },
    },
    {
        "name": "行业宽度主线",
        "description": "从行业站上20日线的覆盖率和板块强度出发，筛选主线中的强势个股。",
        "regimes": ["repair", "fermentation", "climax", "divergence"],
        "formula": {
            "meta": {"library": "curated", "category": "行业轮动", "quality": "B+", "frequency": "每周", "risk": "中", "data_group": "行情与行业"},
            "universe": {"exclude_st": True, "listed_days_min": 180},
            "filters": [
                {"field": "sector_breadth_ma20", "op": ">=", "value": 55},
                {"field": "sector_strength", "op": ">=", "value": 55},
                {"field": "above_ma20", "op": "==", "value": 1},
                {"field": "amount_billion", "op": ">=", "value": 2},
            ],
            "score": [
                {"field": "sector_breadth_ma20", "weight": 0.28, "direction": "desc"},
                {"field": "sector_strength", "weight": 0.24, "direction": "desc"},
                {"field": "relative_strength", "weight": 0.20, "direction": "desc"},
                {"field": "sector_limit_count", "weight": 0.16, "direction": "desc"},
                {"field": "amount_billion", "weight": 0.12, "direction": "desc"},
            ], "limit": 20, "min_score": 0.56,
        },
    },
    {
        "name": "首板低开",
        "description": "昨日首板且位置不高，次日竞价温和低开并具备成交承载时进入候选。",
        "regimes": ["ice", "repair", "divergence"],
        "formula": {
            "meta": {"library": "curated", "category": "短线竞价", "quality": "B+", "frequency": "每日9:25", "risk": "高", "data_group": "行情与竞价"},
            "universe": {"exclude_st": True, "listed_days_min": 250},
            "filters": [
                {"field": "previous_first_limit", "op": "==", "value": 1},
                {"field": "auction_change", "op": "between", "value": [-4.5, -2.5]},
                {"field": "relative_position_60", "op": "<=", "value": 0.55},
                {"field": "previous_amount_billion", "op": ">=", "value": 1},
            ],
            "score": [
                {"field": "auction_amount_million", "weight": 0.28, "direction": "desc"},
                {"field": "previous_amount_billion", "weight": 0.24, "direction": "desc"},
                {"field": "relative_position_60", "weight": 0.20, "direction": "asc"},
                {"field": "sector_strength", "weight": 0.16, "direction": "desc"},
                {"field": "auction_volume_ratio", "weight": 0.12, "direction": "desc"},
            ], "limit": 12, "min_score": 0.50,
        },
    },
    {
        "name": "小碎步临界突破",
        "description": "寻找近期窄幅爬升、接近阶段高点且具备历史活跃记忆的突破候选。",
        "regimes": ["repair", "fermentation", "divergence"],
        "formula": {
            "meta": {"library": "curated", "category": "形态突破", "quality": "B+", "frequency": "每日", "risk": "中高", "data_group": "历史行情"},
            "universe": {"exclude_st": True, "listed_days_min": 250},
            "filters": [
                {"field": "no_limit_30d", "op": "==", "value": 1},
                {"field": "had_limit_80d", "op": "==", "value": 1},
                {"field": "max_abs_change_15d", "op": "<=", "value": 3},
                {"field": "close_to_high_15d", "op": ">=", "value": 0.98},
                {"field": "close_to_high_60d", "op": ">=", "value": 0.90},
            ],
            "score": [
                {"field": "close_to_high_15d", "weight": 0.26, "direction": "desc"},
                {"field": "volume_ratio_5d", "weight": 0.22, "direction": "desc"},
                {"field": "relative_strength", "weight": 0.20, "direction": "desc"},
                {"field": "max_abs_change_15d", "weight": 0.18, "direction": "asc"},
                {"field": "circ_mv_billion", "weight": 0.14, "direction": "asc"},
            ], "limit": 15, "min_score": 0.54,
        },
    },
    {
        "name": "连板龙头",
        "description": "从昨日连板梯队中按高度、板块热度和成交承载筛选辨识度前排。",
        "regimes": ["fermentation", "climax", "divergence"],
        "formula": {
            "meta": {"library": "curated", "category": "连板接力", "quality": "B", "frequency": "每日", "risk": "很高", "data_group": "涨停结构"},
            "universe": {"exclude_st": True, "listed_days_min": 120},
            "filters": [
                {"field": "previous_limit_streak", "op": ">=", "value": 2},
                {"field": "previous_amount_billion", "op": ">=", "value": 1},
            ],
            "score": [
                {"field": "previous_limit_streak", "weight": 0.34, "direction": "desc"},
                {"field": "sector_limit_count", "weight": 0.24, "direction": "desc"},
                {"field": "previous_amount_billion", "weight": 0.18, "direction": "desc"},
                {"field": "turnover_rate", "weight": 0.14, "direction": "desc"},
                {"field": "sector_strength", "weight": 0.10, "direction": "desc"},
            ], "limit": 10, "min_score": 0.50,
        },
    },
    {
        "name": "微盘三正",
        "description": "以正估值、正盈利和正经营现金流约束微盘暴露，保留明确风险提示。",
        "regimes": ["repair", "fermentation"],
        "formula": {
            "meta": {"library": "curated", "category": "小盘质量", "quality": "B", "frequency": "每周", "risk": "高", "data_group": "估值与财务"},
            "universe": {"exclude_st": True, "listed_days_min": 365},
            "filters": [
                {"field": "pb", "op": ">", "value": 0},
                {"field": "roe", "op": ">", "value": 0},
                {"field": "ocf_to_opincome", "op": ">", "value": 0},
                {"field": "circ_mv_billion", "op": "between", "value": [5, 100]},
                {"field": "amount_billion", "op": ">=", "value": 0.5},
            ],
            "score": [
                {"field": "circ_mv_billion", "weight": 0.32, "direction": "asc"},
                {"field": "roe", "weight": 0.24, "direction": "desc"},
                {"field": "ocf_to_opincome", "weight": 0.20, "direction": "desc"},
                {"field": "turnover_rate", "weight": 0.14, "direction": "desc"},
                {"field": "relative_strength", "weight": 0.10, "direction": "desc"},
            ], "limit": 20, "min_score": 0.52,
        },
    },
    {
        "name": "首板高开弱转强",
        "description": "昨日涨停或触板后，使用9:25最终竞价涨幅、量比和板块承接确认强度。",
        "regimes": ["repair", "fermentation", "divergence"],
        "formula": {
            "meta": {"library": "curated", "category": "短线竞价", "quality": "B-", "frequency": "每日9:25", "risk": "高", "data_group": "行情与竞价"},
            "universe": {"exclude_st": True, "listed_days_min": 120},
            "filters": [
                {"field": "previous_limit_signal", "op": "==", "value": 1},
                {"field": "auction_change", "op": "between", "value": [1, 6]},
                {"field": "auction_volume_ratio", "op": ">=", "value": 0.8},
                {"field": "previous_amount_billion", "op": "between", "value": [3, 25]},
            ],
            "score": [
                {"field": "auction_amount_million", "weight": 0.28, "direction": "desc"},
                {"field": "auction_volume_ratio", "weight": 0.24, "direction": "desc"},
                {"field": "auction_change", "weight": 0.18, "direction": "desc"},
                {"field": "sector_strength", "weight": 0.17, "direction": "desc"},
                {"field": "relative_strength", "weight": 0.13, "direction": "desc"},
            ], "limit": 15, "min_score": 0.52,
        },
    },
]

CURATED_STRATEGIES.extend(ADVANCED_CURATED_STRATEGIES)

STRATEGY_ENVIRONMENT_NOTES = {
    "连续分红质量": (
        "防守市、低利率环境与中长期配置窗口",
        "风险偏好快速上升时，稳健资产的价格弹性通常落后",
    ),
    "ROIC质量低波": (
        "震荡偏弱、重视盈利质量与回撤控制的市场",
        "主题快速扩散或高弹性行情中，低波筛选可能错过进攻方向",
    ),
    "低估值现金流白马": (
        "估值修复、价值回归及防守配置阶段",
        "低估值可能来自基本面持续走弱，需警惕价值陷阱",
    ),
    "高增长合理估值": (
        "业绩驱动、成长风格占优且趋势获得确认的阶段",
        "增长预期下修或估值快速收缩时，回撤可能明显放大",
    ),
    "行业宽度主线": (
        "主线清晰、行业内部多数个股同步走强的行情",
        "板块快速轮动时，宽度信号容易在确认后迅速衰减",
    ),
    "首板低开": (
        "情绪修复期的分歧转一致与首板次日承接",
        "退潮加速或低开缺少量能承接时，弱势可能继续扩大",
    ),
    "小碎步临界突破": (
        "趋势蓄势、波动收敛后临近突破的结构市",
        "无量突破或指数剧烈震荡时，容易形成冲高回落",
    ),
    "连板龙头": (
        "高度拓展、题材梯队完整且接力情绪活跃的阶段",
        "亏钱效应扩散或高位股集中退潮时，接力风险很高",
    ),
    "微盘三正": (
        "小盘风格活跃、流动性宽松且风险偏好较高的行情",
        "风格切向大盘或微盘流动性收缩时，组合波动会显著上升",
    ),
    "首板高开弱转强": (
        "竞价承接明确、短线情绪修复或主线发酵阶段",
        "高开缺乏板块共振时，竞价强势可能转为盘中兑现",
    ),
    "中期动量·强者恒强": (
        "趋势延续、主升段及强弱分化清晰的行情",
        "无趋势震荡或快速轮动中，动量信号容易反复失效",
    ),
    "强者回调": (
        "主升趋势未破、强势股完成良性回踩的窗口",
        "趋势已反转时，回调信号可能演变为下跌中继",
    ),
    "超跌反转": (
        "急跌后恐慌释放充分、市场进入修复预期的阶段",
        "单边下跌初段容易过早介入，超跌不等于止跌",
    ),
    "相对强度新高": (
        "指数偏弱但结构性主线明确，或机构抱团强化的行情",
        "基准快速补涨或强势方向瓦解时，相对优势可能迅速消失",
    ),
    "均线多头排列": (
        "中期趋势向上、回撤有序的趋势市与主升段",
        "高位趋势末端或宽幅震荡中，均线信号通常反应滞后",
    ),
    "唐奇安通道突破": (
        "整理末端、放量突破并启动新趋势的行情",
        "无量突破和宽幅震荡环境中，假突破出现概率较高",
    ),
    "周线趋势·日线买点": (
        "中期趋势稳定、日线回踩或再启动的多周期共振阶段",
        "周线拐点尚未确认时，日线信号可能只是短暂反抽",
    ),
    "空间板": (
        "市场高度持续拓展、板块梯队完整的强接力环境",
        "高度压缩或亏钱效应扩散时，最高板的补跌风险极高",
    ),
    "龙头首阴": (
        "主线龙头仍有辨识度、首次分歧后存在回流预期的阶段",
        "题材退潮或龙头地位被替代后，首阴可能只是下跌起点",
    ),
    "断板反包": (
        "强势题材分歧后快速修复、核心股重新获得资金承接时",
        "板块强度不足或反包缩量时，形态持续性通常较弱",
    ),
    "核按钮反核": (
        "恐慌释放后出现明确承接、短线情绪转暖的窗口",
        "系统性退潮中深水拉回可能只是日内脉冲，隔日风险较高",
    ),
    "行业动量轮动": (
        "主线相对清晰、行业趋势能够延续两周以上的结构市",
        "行业轮动速度过快或前三名差距很小时，动量优势容易迅速衰减",
    ),
    "主力资金行业流入": (
        "板块轮动初期、资金先于价格形成连续净流入的阶段",
        "资金流口径可能受大宗交易和短期对倒影响，单日突增不代表趋势",
    ),
    "景气-趋势-拥挤三维行业打分": (
        "行业景气与价格趋势同向、但交易拥挤尚未达到极端的结构市",
        "财务披露存在滞后，行业快速反转时三维综合分可能反应偏慢",
    ),
    "大小盘/成长价值风格切换(元策略)": (
        "大小盘或成长价值风格形成持续相对强弱的阶段",
        "风格快速往返切换时，近20日相对表现容易产生滞后信号",
    ),
    "业绩超预期漂移(SUE/PEAD)": (
        "业绩披露窗口中，快报相对预告继续上修且价格尚未充分兑现时",
        "预告与快报口径可能不同，公告后高开兑现会削弱漂移效应",
    ),
    "多因子综合打分(IC动态加权)": (
        "因子表现具备一定延续性、市场并非由单一极端主题主导时",
        "近期有效因子可能快速失效，动态权重不能消除风格突变风险",
    ),
    "热度突增潜伏(另类数据)": (
        "人气快速抬升但股价尚未明显启动的题材萌芽与扩散初期",
        "榜单热度可能由短期讨论驱动，缺少价格确认时误报率较高",
    ),
    "机构榜溢价": (
        "机构专用席位在相对低位形成明确净买入、且成交承载正常时",
        "高位机构榜可能对应兑现或对倒，席位净买入不等于持续锁仓",
    ),
}

for strategy in CURATED_STRATEGIES:
    suitable_environment, failure_risk = STRATEGY_ENVIRONMENT_NOTES[strategy["name"]]
    strategy["formula"]["meta"].update(
        {
            "suitable_environment": suitable_environment,
            "failure_risk": failure_risk,
        }
    )

BUILTIN_STRATEGIES.extend(CURATED_STRATEGIES)

for strategy in BUILTIN_STRATEGIES:
    attach_strategy_validity(strategy)
