"""
v5.1 修复版：10x杠杆 + 只做多 + 1H趋势过滤
"""
import pandas as pd
import numpy as np

df = pd.read_parquet('/root/quant_pipeline/data/btc_15m_binance_full.parquet')
print(f"数据: {len(df):,} 根 K 线")

df['ret'] = df['c'].pct_change() * 100
df['high_20'] = df['h'].rolling(20).max().shift(1)
df['vol_ma20'] = df['v'].rolling(20).mean().shift(1)
df['taker_ratio'] = df['taker_buy_v'] / (df['v'] + 1e-9)
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()
# 1H趋势：EMA84 > EMA168
df['ema84'] = df['c'].ewm(span=84).mean()
df['ema168'] = df['c'].ewm(span=168).mean()

LEVERAGE = 10
trades = []
cooldown = 0

for i in range(200, len(df) - 30):
    if cooldown > 0:
        cooldown -= 1
        continue

    # 趋势过滤：只做1H向上
    if df['ema84'].iloc[i] < df['ema168'].iloc[i]:
        continue

    # 突破前20根高点
    if df['c'].iloc[i] <= df['high_20'].iloc[i]:
        continue

    # Taker > 0.55
    if df['taker_ratio'].iloc[i] <= 0.55:
        continue

    # 成交量放大1.5x
    if df['v'].iloc[i] <= df['vol_ma20'].iloc[i] * 1.5:
        continue

    # 阳线
    if df['c'].iloc[i] <= df['o'].iloc[i]:
        continue

    entry = df['c'].iloc[i]
    atr = df['atr14'].iloc[i]
    if pd.isna(atr) or atr <= 0:
        continue

    sl = entry - atr * 1.5
    tp = entry + atr * 3.0

    exit_price = None
    hit_tp = hit_sl = False
    for j in range(i+1, min(i+24, len(df))):
        if df['h'].iloc[j] >= tp:
            exit_price = tp; hit_tp = True; break
        if df['l'].iloc[j] <= sl:
            exit_price = sl; hit_sl = True; break
    if exit_price is None:
        exit_price = df['c'].iloc[min(i+24, len(df)-1)]

    raw = (exit_price / entry - 1) * 100
    net = raw * LEVERAGE - 0.12

    trades.append({
        'time': df.index[i], 'entry': entry, 'exit': exit_price,
        'taker': df['taker_ratio'].iloc[i], 'net': net,
        'hit_tp': hit_tp, 'hit_sl': hit_sl,
    })
    cooldown = 6  # 6根冷却=1.5小时

if not trades:
    print("❌ 无信号")
else:
    df_t = pd.DataFrame(trades)
    total = len(df_t)
    wins = (df_t['net'] > 0).sum()
    wr = wins / total * 100
    avg = df_t['net'].mean()
    avg_win = df_t[df_t['net'] > 0]['net'].mean()
    avg_loss = df_t[df_t['net'] <= 0]['net'].mean()
    pnl = df_t['net'].values / 100
    cum = (1 + pnl).prod()
    eq = np.cumprod(1 + pnl)
    peak = np.maximum.accumulate(eq)
    max_dd = ((eq - peak) / peak).min() * 100
    sharpe = pnl.mean() / pnl.std() * np.sqrt(365*4) if pnl.std() > 0 else 0

    print(f"\n{'='*70}")
    print(f"🔥 v5.1 修复版 (10x, 只做多, 1H趋势)")
    print(f"{'='*70}")
    print(f"总交易: {total}笔")
    print(f"胜率: {wr:.1f}%")
    print(f"平均收益: {avg:+.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"\n💰 5U模拟: $5 → ${5*cum:.2f}")

    # 日频
    df_t['day'] = df_t['time'].dt.date
    daily = df_t.groupby('day')['net'].agg(['count', 'sum'])
    pd_count = (daily['sum'] > 0).sum()
    td = len(daily)
    print(f"\n📅 日频: {td}天交易, {pd_count}天盈利 ({pd_count/td*100:.0f}%)")
    print(f"平均日收益: {daily['sum'].mean():+.2f}%")
    print(f"最佳日: {daily['sum'].max():+.2f}% | 最差日: {daily['sum'].min():+.2f}%")

    # 月度
    df_t['month'] = df_t['time'].dt.to_period('M')
    monthly = df_t.groupby('month')['net'].agg(['count', 'sum']).round(1)
    print(f"\n📅 月度:")
    for m, row in monthly.iterrows():
        tag = "🟢" if row['sum'] > 0 else "🔴"
        print(f"  {tag} {m}: {row['count']:.0f}笔, {row['sum']:+.1f}%")

    # 前10笔
    print(f"\n📋 前10笔:")
    for _, t in df_t.head(10).iterrows():
        tag = "🟢" if t['net'] > 0 else "🔴"
        print(f"  {t['time'].strftime('%m-%d %H:%M')} 入场{t['entry']:.0f} Taker{t['taker']:.2f} {tag} {t['net']:+.1f}%")
