"""
v6.0 1小时突破策略 — 10x杠杆, 只做多, 趋势过滤
用真实Taker数据, 1H级别过滤假突破
"""
import pandas as pd
import numpy as np

print("🚀 加载数据...")
df = pd.read_parquet('/root/quant_pipeline/data/btc_15m_binance_full.parquet')

# 重采样到1小时
df['time'] = df.index
df_1h = df.resample('1h').agg({
    'o': 'first', 'h': 'max', 'l': 'min', 'c': 'last',
    'v': 'sum', 'taker_buy_v': 'sum',
    'taker_buy_quote': 'sum', 'quote_volume': 'sum',
}).dropna()
df_1h.rename(columns={'o':'open','h':'high','l':'low','c':'close','v':'volume'}, inplace=True)
df_1h['taker_ratio'] = df_1h['taker_buy_v'] / (df_1h['volume'] + 1e-9)

print(f"1H数据: {len(df_1h):,} 根, 约 {len(df_1h)/24:.0f} 天")

# 指标
df_1h['high_20'] = df_1h['high'].rolling(20).max().shift(1)
df_1h['vol_ma20'] = df_1h['volume'].rolling(20).mean().shift(1)
tr = np.maximum(df_1h['high'] - df_1h['low'], 
       np.maximum(np.abs(df_1h['high'] - df_1h['close'].shift(1)), 
                  np.abs(df_1h['low'] - df_1h['close'].shift(1))))
df_1h['atr14'] = tr.rolling(14).mean()
# 4H趋势：EMA21 > EMA50 (在1H上等于4H趋势)
df_1h['ema21'] = df_1h['close'].ewm(span=21).mean()
df_1h['ema50'] = df_1h['close'].ewm(span=50).mean()

LEVERAGE = 10
trades = []
cooldown = 0

c = df_1h['close'].values
h = df_1h['high'].values
l = df_1h['low'].values
o = df_1h['open'].values
v = df_1h['volume'].values
taker = df_1h['taker_ratio'].values
high20 = df_1h['high_20'].values
volma20 = df_1h['vol_ma20'].values
atr = df_1h['atr14'].values
ema21 = df_1h['ema21'].values
ema50 = df_1h['ema50'].values
N = len(df_1h)

for i in range(50, N - 24):
    if cooldown > 0:
        cooldown -= 1
        continue

    # 1. 趋势过滤：EMA21 > EMA50
    if ema21[i] < ema50[i]:
        continue

    # 2. 突破前20根高点
    if c[i] <= high20[i] or np.isnan(high20[i]):
        continue

    # 3. Taker > 0.55
    if taker[i] <= 0.55:
        continue

    # 4. 成交量放大1.5x
    if v[i] <= volma20[i] * 1.5 or np.isnan(volma20[i]):
        continue

    # 5. 阳线
    if c[i] <= o[i]:
        continue

    entry = c[i]
    a = atr[i]
    if np.isnan(a) or a <= 0:
        continue

    sl_price = entry - a * 1.5
    tp_price = entry + a * 3.0

    # 持仓最多12根1H (12小时)
    exit_price = None
    hit_tp = hit_sl = False
    exit_idx = i
    for j in range(i+1, min(i+12, N)):
        if h[j] >= tp_price:
            exit_price = tp_price; hit_tp = True; exit_idx = j; break
        if l[j] <= sl_price:
            exit_price = sl_price; hit_sl = True; exit_idx = j; break
    if exit_price is None:
        exit_price = c[min(i+12, N-1)]
        exit_idx = min(i+12, N-1)

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

    trades.append({
        'time': df_1h.index[i], 'entry': entry, 'exit': exit_price,
        'taker': taker[i], 'net': net,
        'hit_tp': hit_tp, 'hit_sl': hit_sl,
        'bars': exit_idx - i, 'atr': a,
    })
    cooldown = 2  # 2根1H冷却

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*24) if pnl.std() > 0 else 0

    print(f"\n{'='*70}")
    print(f"🔥 v6.0 1小时突破策略 (10x, 只做多, 趋势过滤)")
    print(f"{'='*70}")
    print(f"总交易: {total}笔 ({total/3.5:.0f}笔/年)")
    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"年化: {(cum**(1/3.5)-1)*100:.1f}%")
    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}%")

    # 月度
    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}%")

    # 前15笔
    print(f"\n📋 前15笔:")
    for _, t in df_t.head(15).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}%")

    # 止盈止损统计
    print(f"\n📊 止盈止损统计:")
    print(f"  止盈命中: {df_t['hit_tp'].sum()} ({df_t['hit_tp'].sum()/total*100:.0f}%)")
    print(f"  止损命中: {df_t['hit_sl'].sum()} ({df_t['hit_sl'].sum()/total*100:.0f}%)")
    print(f"  超时出场: {(~df_t['hit_tp'] & ~df_t['hit_sl']).sum()} ({(~df_t['hit_tp'] & ~df_t['hit_sl']).sum()/total*100:.0f}%)")
