"""
15分钟时间框架测试
同一条确认逻辑，不同时间尺度
"""
import pandas as pd, numpy as np

df = pd.read_parquet("data/btc_multidim.parquet")
d = df.copy()  # 已经是15分钟
d.index.name = "ts"

O, H, L, C = d["open"], d["high"], d["low"], d["close"]
body = abs(C - O)
upper_shadow = H - np.maximum(O, C)
lower_shadow = np.minimum(O, C) - L
total_range = H - L
body_ratio = body / (total_range + 1e-9)
body1 = abs(C.shift(1) - O.shift(1))
O1, H1, L1, C1 = O.shift(1), H.shift(1), L.shift(1), C.shift(1)

# 关键位 (15min 尺度: 用96根=24小时)
LB = 96
prev_high = H.shift(1).rolling(LB).max()
prev_low = L.shift(1).rolling(LB).min()
near_support = (L - prev_low).abs() / (prev_low + 1e-9) < 0.005
near_resistance = (H - prev_high).abs() / (prev_high + 1e-9) < 0.005

# 形态识别
bullish_engulfing = (C1 < O1) & (C > O) & (O <= C1) & (C >= O1)
bearish_engulfing = (C1 > O1) & (C < O) & (O >= C1) & (C <= O1)

sweep_up = (H > prev_high) & (C < prev_high)
sweep_down = (L < prev_low) & (C > prev_low)

next_bull = (C.shift(-1) > O.shift(-1))
next_bear = (C.shift(-1) < O.shift(-1))

# 确认信号
long_sig = bullish_engulfing & near_support & next_bull
short_sig = sweep_up & near_resistance & next_bear

FEE = 0.001

def test(signal, direction, sl, tp, max_bars, label):
    mask = signal.values
    wins = losses = timeouts = 0
    rets = []
    for i in np.where(mask)[0]:
        if i + max_bars >= len(d): continue
        entry = d["close"].iloc[i]
        for j in range(1, max_bars + 1):
            if i+j >= len(d): break
            ret = (d["close"].iloc[i+j] / entry - 1) * direction
            if ret <= -sl:
                losses += 1; rets.append(-sl - FEE); break
            elif ret >= tp:
                wins += 1; rets.append(tp - FEE); break
        else:
            r = (d["close"].iloc[min(i+max_bars, len(d)-1)] / entry - 1) * direction
            timeouts += 1; rets.append(r - FEE)
    n = wins + losses + timeouts
    if n == 0: return None
    wr = wins/(wins+losses) if (wins+losses)>0 else 0
    cum = np.prod([1+r for r in rets])
    return {"label": label, "n": n, "wr": wr, "cum": cum, "avg": np.mean(rets)*10000}

# 只做关键的测试
configs = [
    # (sl, tp, max_bars_h)
    (0.01, 0.03, 192, "SL1% TP3% 48h"),      # 15min → 放长持有时间
    (0.01, 0.03, 384, "SL1% TP3% 96h"),
    (0.005, 0.015, 192, "SL0.5% TP1.5% 48h"), # 缩小止损
    (0.005, 0.02, 192, "SL0.5% TP2% 48h"),     # 不对称R:R
    (0.008, 0.024, 192, "SL0.8% TP2.4% 48h"),
]

print("="*60)
print("15分钟 蜡烛图确认策略")
print("="*60)

best_long = None
best_short = None

for sl, tp, bars, label in configs:
    rl = test(long_sig, 1, sl, tp, bars, label)
    rs = test(short_sig, -1, sl, tp, bars, label)
    
    if rl is None or rs is None: continue
    
    # 合并
    all_n = rl["n"] + rs["n"]
    all_cum = rl["cum"] * rs["cum"]
    all_wr = (rl["wr"] * rl["n"] + rs["wr"] * rs["n"]) / (rl["n"] + rs["n"]) if (rl["n"]+rs["n"])>0 else 0
    
    print(f"\n{label}:")
    print(f"  做多: {rl['n']:4d}笔 胜率{rl['wr']:.1%} 累计{rl['cum']:.4f}")
    print(f"  做空: {rs['n']:4d}笔 胜率{rs['wr']:.1%} 累计{rs['cum']:.4f}")
    print(f"  合并: {all_n:4d}笔 胜率{all_wr:.1%} 累计{all_cum:.4f} ({(all_cum-1)*100:+.1f}%)")
    
    if best_long is None or rl["cum"] > best_long[1]:
        best_long = (label, rl["cum"], rl)
    if best_short is None or rs["cum"] > best_short[1]:
        best_short = (label, rs["cum"], rs)

# 对比1H
print(f"\n{'='*60}")
print(f"vs 1H 最佳组合(吞没多+阳线@支撑 + 扫荡空+阴线@阻力)")
print(f"  SL1% TP3% 48H: 333笔 48%胜率 累计4.97 (+397%)")
