"""
缠论笔级交易 v2: 调整参数 + 大级别过滤
"""
import pandas as pd, numpy as np
from chanlun_engine import merge_candles, identify_fenxing, identify_bi

df_raw = pd.read_parquet("data/btc_multidim.parquet")
d1h = df_raw.resample("1h").agg({"open":"first","high":"max","low":"min","close":"last"}).dropna()

# 大级别
d4h = df_raw.resample("4h").agg({"close":"last"}).dropna()
d4h["ma50"] = d4h["close"].rolling(50).mean()
d4h["trend_up"] = d4h["close"] > d4h["ma50"]
d1h["htf_up"] = d4h["trend_up"].reindex(d1h.index, method="ffill").fillna(True)

def test_params(sl, tp, max_bars, use_htf, label):
    all_trades = []
    
    for i in range(0, len(d1h) - 24*30, 24*7):  # 每周滑动
        chunk = d1h.iloc[i:i+24*90]
        if len(chunk) < 200: continue
        
        try:
            df_m = merge_candles(chunk)
            fx = identify_fenxing(df_m)
            bi = identify_bi(fx, df_m)
        except: continue
        if len(bi) < 3: continue
        
        last_bi = bi[-1]
        prev_fx_type = last_bi["start_type"]
        prev_fx_idx = last_bi["start_idx"]
        
        for j in range(prev_fx_idx + 1, min(prev_fx_idx + 15, len(df_m))):
            price = df_m["close"].iloc[j]
            
            if prev_fx_type == "底":
                fx_low = df_m["low"].iloc[prev_fx_idx]
                if abs(price - fx_low) / fx_low > 0.01: continue
                direction = 1
            elif prev_fx_type == "顶":
                fx_high = df_m["high"].iloc[prev_fx_idx]
                if abs(price - fx_high) / fx_high > 0.01: continue
                direction = -1
            else:
                continue
            
            # 大级别过滤
            if use_htf:
                htf_idx = chunk.index[j] if j < len(chunk.index) else chunk.index[-1]
                if htf_idx in d1h.index:
                    if direction == 1 and not d1h.loc[htf_idx, "htf_up"]:
                        continue
                    if direction == -1 and d1h.loc[htf_idx, "htf_up"]:
                        continue
            
            entry = price
            win, loss = False, False
            for k in range(1, min(max_bars, len(df_m) - j - 1)):
                exit_px = df_m["close"].iloc[j + k]
                ret = (exit_px / entry - 1) * direction
                if ret <= -sl:
                    all_trades.append(ret - FEE); loss = True; break
                elif ret >= tp:
                    all_trades.append(tp - FEE); win = True; break
            if not win and not loss:
                ep = df_m["close"].iloc[min(j+max_bars, len(df_m)-1)]
                all_trades.append((ep/entry-1)*direction - FEE)
    
    if len(all_trades) < 10: return None
    wr = sum(1 for r in all_trades if r > 0) / len(all_trades)
    cum = np.prod([1+r for r in all_trades])
    return {"label": label, "n": len(all_trades), "wr": wr, "cum": cum, "avg": np.mean(all_trades)*10000}

FEE = 0.001
configs = [
    (0.01, 0.03, 48, False, "SL1% TP3% 48h"),
    (0.015, 0.045, 72, False, "SL1.5% TP4.5% 72h"),
    (0.02, 0.06, 96, False, "SL2% TP6% 96h"),
    (0.01, 0.03, 48, True, "SL1% TP3% +4H过滤"),
    (0.015, 0.045, 72, True, "SL1.5% TP4.5% +4H过滤"),
    (0.02, 0.06, 96, True, "SL2% TP6% +4H过滤"),
]

print("="*56)
print("缠论 笔级交易 v2")
print("="*56)
print(f"{'参数':25s} {'笔数':>5s} {'胜率':>7s} {'均益bps':>9s} {'累计':>8s}")
print("-"*56)
for sl, tp, mb, htf, label in configs:
    r = test_params(sl, tp, mb, htf, label)
    if r:
        print(f"{label:25s} {r['n']:5d} {r['wr']:6.1%} {r['avg']:+8.0f} {r['cum']:8.4f}")
