"""
🔥 突破+高杠杆策略 v5.0 — 专为4-5U小资金设计
策略逻辑：
  入场：价格突破20根K线高点 + Taker买入占比>55% + 成交量放大1.5x
  出场：止盈3ATR / 止损1.5ATR (盈亏比2:1)
  杠杆：20x
  目标：每笔5-10%本金收益，一天2-3笔
"""
import pandas as pd
import numpy as np

print("🚀 加载真实Taker数据...")
df = pd.read_parquet('/root/quant_pipeline/data/btc_15m_binance_full.parquet')
print(f"数据量: {len(df):,} 根 K 线, 约 {len(df)/96:.0f} 天")

# ──────────────────────────────────────────────────────
# 计算指标
# ──────────────────────────────────────────────────────
df['ret'] = df['c'].pct_change() * 100
df['high_20'] = df['h'].rolling(20).max().shift(1)  # 前20根最高点
df['low_20'] = df['l'].rolling(20).min().shift(1)   # 前20根最低点
df['vol_ma20'] = df['v'].rolling(20).mean().shift(1)
df['taker_ratio'] = df['taker_buy_v'] / (df['v'] + 1e-9)

# ATR (14)
tr = np.maximum(df['h'] - df['l'], 
       np.maximum(np.abs(df['h'] - df['c'].shift(1)), 
                  np.abs(df['l'] - df['c'].shift(1))))
df['atr14'] = tr.rolling(14).mean()

# ──────────────────────────────────────────────────────
# 策略回测
# ──────────────────────────────────────────────────────
print("\n🔥 突破+高杠杆策略回测 (20x杠杆)")
print("="*80)

trades = []
cooldown = 0  # 冷却期，避免连续重复入场

for i in range(50, len(df) - 30):
    if cooldown > 0:
        cooldown -= 1
        continue
    
    # ── 做多信号 ──
    # 1. 价格突破前20根高点
    break_up = df['c'].iloc[i] > df['high_20'].iloc[i]
    
    # 2. Taker 买入占比 > 55%
    taker_bull = df['taker_ratio'].iloc[i] > 0.55
    
    # 3. 成交量放大 1.5x
    vol_surge = df['v'].iloc[i] > df['vol_ma20'].iloc[i] * 1.5
    
    # 4. 阳线确认
    is_bull = df['c'].iloc[i] > df['o'].iloc[i]
    
    if break_up and taker_bull and vol_surge and is_bull:
        entry = df['c'].iloc[i]
        atr = df['atr14'].iloc[i]
        
        if pd.isna(atr) or atr <= 0:
            continue
        
        sl_price = entry - atr * 1.5
        tp_price = entry + atr * 3.0
        
        # 模拟持仓 (最多24根=6小时)
        exit_price = None
        hit_sl = hit_tp = False
        exit_idx = i
        
        for j in range(i+1, min(i+24, len(df))):
            if df['h'].iloc[j] >= tp_price:
                exit_price = tp_price
                hit_tp = True
                exit_idx = j
                break
            elif df['l'].iloc[j] <= sl_price:
                exit_price = sl_price
                hit_sl = True
                exit_idx = j
                break
        
        if exit_price is None:
            exit_price = df['c'].iloc[min(i+24, len(df)-1)]
            exit_idx = min(i+24, len(df)-1)
        
        # 收益计算 (20x杠杆)
        raw_ret = (exit_price / entry - 1) * 100
        net_ret = raw_ret * 20 - 0.12  # 20x杠杆放大，减双边手续费
        
        trades.append({
            'time': df.index[i],
            'direction': 'LONG',
            'entry': entry,
            'exit': exit_price,
            'taker_ratio': df['taker_ratio'].iloc[i],
            'vol_ratio': df['v'].iloc[i] / (df['vol_ma20'].iloc[i] + 1e-9),
            'atr': atr,
            'raw_ret': raw_ret,
            'net_ret_20x': net_ret,
            'hit_tp': hit_tp,
            'hit_sl': hit_sl,
            'bars': exit_idx - i,
        })
        cooldown = 3  # 3根K线冷却
        continue
    
    # ── 做空信号 ──
    # 1. 价格跌破前20根低点
    break_down = df['c'].iloc[i] < df['low_20'].iloc[i]
    
    # 2. Taker 卖出占比 > 55% (即 taker_buy < 0.45)
    taker_bear = df['taker_ratio'].iloc[i] < 0.45
    
    # 3. 成交量放大 1.5x
    vol_surge = df['v'].iloc[i] > df['vol_ma20'].iloc[i] * 1.5
    
    # 4. 阴线确认
    is_bear = df['c'].iloc[i] < df['o'].iloc[i]
    
    if break_down and taker_bear and vol_surge and is_bear:
        entry = df['c'].iloc[i]
        atr = df['atr14'].iloc[i]
        
        if pd.isna(atr) or atr <= 0:
            continue
        
        sl_price = entry + atr * 1.5
        tp_price = entry - atr * 3.0
        
        exit_price = None
        hit_sl = hit_tp = False
        exit_idx = i
        
        for j in range(i+1, min(i+24, len(df))):
            if df['l'].iloc[j] <= tp_price:
                exit_price = tp_price
                hit_tp = True
                exit_idx = j
                break
            elif df['h'].iloc[j] >= sl_price:
                exit_price = sl_price
                hit_sl = True
                exit_idx = j
                break
        
        if exit_price is None:
            exit_price = df['c'].iloc[min(i+24, len(df)-1)]
            exit_idx = min(i+24, len(df)-1)
        
        raw_ret = (entry / exit_price - 1) * 100  # 做空收益
        net_ret = raw_ret * 20 - 0.12
        
        trades.append({
            'time': df.index[i],
            'direction': 'SHORT',
            'entry': entry,
            'exit': exit_price,
            'taker_ratio': df['taker_ratio'].iloc[i],
            'vol_ratio': df['v'].iloc[i] / (df['vol_ma20'].iloc[i] + 1e-9),
            'atr': atr,
            'raw_ret': raw_ret,
            'net_ret_20x': net_ret,
            'hit_tp': hit_tp,
            'hit_sl': hit_sl,
            'bars': exit_idx - i,
        })
        cooldown = 3

# ──────────────────────────────────────────────────────
# 结果分析
# ──────────────────────────────────────────────────────
if not trades:
    print("❌ 没有产生信号！")
else:
    df_t = pd.DataFrame(trades)
    
    total = len(df_t)
    wins = (df_t['net_ret_20x'] > 0).sum()
    losses = (df_t['net_ret_20x'] <= 0).sum()
    win_rate = wins / total * 100
    avg_ret = df_t['net_ret_20x'].mean()
    avg_win = df_t[df_t['net_ret_20x'] > 0]['net_ret_20x'].mean()
    avg_loss = df_t[df_t['net_ret_20x'] <= 0]['net_ret_20x'].mean()
    
    # 复利
    pnl = df_t['net_ret_20x'].values / 100
    cum = (1 + pnl).prod()
    
    # 回撤
    eq = np.cumprod(1 + pnl)
    peak = np.maximum.accumulate(eq)
    max_dd = ((eq - peak) / peak).min() * 100
    
    # Sharpe
    sharpe = pnl.mean() / pnl.std() * np.sqrt(365*4) if pnl.std() > 0 else 0
    
    # 按天统计
    df_t['day'] = df_t['time'].dt.date
    daily = df_t.groupby('day')['net_ret_20x'].agg(['count', 'sum'])
    profit_days = (daily['sum'] > 0).sum()
    total_days = len(daily)
    
    print(f"\n{'='*80}")
    print(f"🔥 突破+高杠杆策略 (20x) 回测结果")
    print(f"{'='*80}")
    print(f"总交易次数: {total}")
    print(f"做多: {(df_t['direction']=='LONG').sum()} | 做空: {(df_t['direction']=='SHORT').sum()}")
    print(f"盈利: {wins} | 亏损: {losses}")
    print(f"✅ 胜率: {win_rate:.1f}%")
    print(f"平均单笔收益 (20x): {avg_ret:+.2f}%")
    print(f"平均盈利: {avg_win:+.2f}% | 平均亏损: {avg_loss:+.2f}%")
    print(f"盈亏比: {abs(avg_win/avg_loss):.2f}")
    print(f"复利倍数: {cum:.2f}x")
    print(f"最大回撤: {max_dd:.1f}%")
    print(f"Sharpe: {sharpe:.2f}")
    print(f"{'='*80}")
    
    # 5U模拟
    print(f"\n💰 5U本金模拟:")
    print(f"  起始: $5.00")
    print(f"  最终: ${5*cum:.2f}")
    print(f"  总收益: {(cum-1)*100:+.1f}%")
    
    # 日频统计
    print(f"\n📅 日频统计:")
    print(f"  交易天数: {total_days}")
    print(f"  盈利天数: {profit_days} ({profit_days/total_days*100:.0f}%)")
    print(f"  亏损天数: {total_days-profit_days} ({(total_days-profit_days)/total_days*100:.0f}%)")
    print(f"  平均日收益: {daily['sum'].mean():+.2f}%")
    print(f"  最佳日: {daily['sum'].max():+.2f}%")
    print(f"  最差日: {daily['sum'].min():+.2f}%")
    
    # 按月统计
    print(f"\n📅 月度收益:")
    df_t['month'] = df_t['time'].dt.to_period('M')
    monthly = df_t.groupby('month')['net_ret_20x'].agg(['count', 'sum']).round(1)
    for m, row in monthly.iterrows():
        tag = "🟢" if row['sum'] > 0 else "🔴"
        print(f"  {tag} {m}: {row['count']:>3.0f}笔, 月收益 {row['sum']:>+7.1f}%")
    
    # 展示前15笔
    print(f"\n📋 前15笔交易:")
    print(f"{'时间':<16} {'方向':>5} {'入场':>8} {'Taker':>6} {'收益20x':>8}")
    print(f"{'-'*48}")
    for _, t in df_t.head(15).iterrows():
        tag = "🟢" if t['net_ret_20x'] > 0 else "🔴"
        print(f"{t['time'].strftime('%m-%d %H:%M'):<16} {t['direction']:>5} {t['entry']:>8.0f} {t['taker_ratio']:>5.2f} {tag} {t['net_ret_20x']:>+6.1f}%")
    
    # 参数敏感性
    print(f"\n📊 Taker阈值敏感性:")
    for thresh in [0.50, 0.55, 0.60, 0.65]:
        sub = df_t[(df_t['taker_ratio'] >= thresh) | (df_t['taker_ratio'] <= 1-thresh)]
        if len(sub) > 5:
            wr = (sub['net_ret_20x'] > 0).mean() * 100
            avg = sub['net_ret_20x'].mean()
            print(f"  Taker>{thresh}: {len(sub)}笔, 胜率{wr:.0f}%, 平均{avg:+.1f}%")
