"""主动推理 v3：宽阈值 + 多组参数对比
修正v2减仓过激进的问题，调宽误差容忍度
"""
import pandas as pd, numpy as np

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

dd = df_raw.resample("1D").agg({"close":"last"}).dropna()
dd["ma20"] = dd["close"].rolling(20).mean()
dd["trend_up"] = dd["close"] > dd["ma20"]

O,H,L,C,V = d["open"].values,d["high"].values,d["low"].values,d["close"].values,d["volume"].values
n = len(d)

tr = np.maximum(H-L, np.maximum(abs(H-np.roll(C,1)), abs(L-np.roll(C,1))))
atr_pct = pd.Series(tr).rolling(14).mean().values / C * 100

O1=np.roll(O,1);H1=np.roll(H,1);L1=np.roll(L,1);C1=np.roll(C,1)

bull = (C1<O1) & (C>O) & (O<=C1) & (C>=O1)
near_s = abs(L-pd.Series(L).shift(1).rolling(20).min().values) / (pd.Series(L).shift(1).rolling(20).min().values+1e-9) < 0.005
nbull = np.roll(C,-1) > np.roll(O,-1)
long_sig = bull & near_s & nbull

swup = (H>pd.Series(H).shift(1).rolling(20).max().values) & (C<pd.Series(H).shift(1).rolling(20).max().values)
near_r = abs(H-pd.Series(H).shift(1).rolling(20).max().values) / (pd.Series(H).shift(1).rolling(20).max().values+1e-9) < 0.005
nbear = np.roll(C,-1) < np.roll(O,-1)
short_sig = swup & near_r & nbear

d_ts = d.index
trend_1h = np.array([
    dd["trend_up"].reindex([ts], method="ffill").values[0]
    if ts >= dd.index[0] else True
    for ts in d_ts
])

lsig = long_sig & trend_1h
ssig = short_sig & (~trend_1h)

split = int(n * 0.67)
SL, TP, MB = 0.015, 0.045, 48


def backtest(lsig, ssig, mode, params=None):
    """
    mode: 'fixed' or 'active'
    params: (add_thresh, reduce_thresh, add_size, reduce_size, max_add, eval_interval)
        add_thresh: error > -add_thresh → 加仓
        reduce_thresh: error < -reduce_thresh → 减仓
        add_size: 每次加仓量
        reduce_size: 每次减仓量
        max_add: 最大加仓次数
        eval_interval: 评估间隔(K线根数)
    """
    results = {"in": [], "out": []}
    stats = {"add": 0, "reduce": 0, "hold": 0, "early_close": 0}
    
    if params is None:
        params = (0.001, 0.004, 0.3, 0.3, 2, 3)
    add_thresh, reduce_thresh, add_size, reduce_size, max_add, eval_interval = params
    
    for period, st, en in [("in", 0, split), ("out", split, n)]:
        for mask, dirc in [(lsig, 1), (ssig, -1)]:
            for i in range(st, min(en, n)):
                if not mask[i]: continue
                if i + MB >= n: continue
                
                entry = C[i]
                closed = False
                pos_size = 1.0
                add_count = 0
                last_eval = 0
                
                for j in range(1, MB + 1):
                    if i + j >= n: break
                    ret = (C[i+j] / entry - 1) * dirc
                    
                    # 主动推理
                    if mode == "active" and j % eval_interval == 0 and j != last_eval:
                        last_eval = j
                        atr_val = atr_pct[i+j] if not np.isnan(atr_pct[i+j]) else 0.3
                        expected = 0.0005 * j + atr_val * 0.002 * j
                        expected = min(expected, TP * 0.8)
                        error = ret - expected
                        
                        if error > -add_thresh:  # 接近或超过预期 → 加仓
                            if add_count < max_add and pos_size < 2.0:
                                pos_size = min(2.0, pos_size + add_size)
                                add_count += 1
                                stats["add"] += 1
                            else:
                                stats["hold"] += 1
                        elif error > -reduce_thresh:  # 轻微偏离 → 保持
                            stats["hold"] += 1
                        else:  # 严重偏离 → 减仓
                            pos_size = max(0.0, pos_size - reduce_size)
                            stats["reduce"] += 1
                            if pos_size <= 0.1:
                                results[period].append(ret * 0.1 - 0.001)
                                stats["early_close"] += 1
                                closed = True; break
                    
                    # TP/SL
                    if ret >= TP:
                        results[period].append(TP * pos_size - 0.001)
                        closed = True; break
                    if ret <= -SL:
                        results[period].append(-SL * pos_size - 0.001)
                        closed = True; break
                
                if not closed:
                    final_ret = (C[min(i+MB, n-1)] / entry - 1) * dirc
                    results[period].append(final_ret * pos_size - 0.001)
    
    return results, stats


def print_stats(results, stats, label):
    print(f"\n▶ {label}")
    print(f"  [推理] 加仓={stats['add']} 保持={stats['hold']} 减仓={stats['reduce']} 早退={stats['early_close']}")
    for nm, key in [("样本内", "in"), ("样本外", "out")]:
        tr = results[key]
        if len(tr) < 5: print(f"  {nm}: 仅{len(tr)}笔"); continue
        wr = sum(1 for r in tr if r > 0) / len(tr)
        cum = np.prod([1 + r for r in tr])
        ch = [tr[i:i+5] for i in range(0, len(tr), 5)]
        pw = sum(1 for c in ch if sum(c) > 0) / len(ch) if ch else 0
        avg = np.mean(tr) * 100
        running = 1.0; peak = 1.0; mdd = 0
        for r in tr:
            running *= (1 + r); peak = max(peak, running)
            mdd = min(mdd, (running - peak) / peak)
        sharpe = np.mean(tr) / (np.std(tr) + 1e-9) * np.sqrt(365*24/MB) if np.std(tr) > 0 else 0
        print(f"  {nm}: {len(tr)}笔 wr={wr:.1%} cum={cum:.3f} avg={avg:+.2f}% "
              f"周盈≈{pw:.1%} MDD={mdd:.1%} Sharpe={sharpe:.2f}")


print("=" * 80)
print("主动推理 v3：多组参数对比")
print("=" * 80)
print(f"SL={SL} TP={TP} MB={MB}h  数据: BTC 1H {n}根")

# 原版
r0, s0 = backtest(lsig, ssig, "fixed")
print_stats(r0, s0, "固定止损（原版）")

# 参数组：(加仓阈值, 减仓阈值, 加仓量, 减仓量, 最大加仓次数, 评估间隔)
param_sets = [
    ("宽松(加0.001/减0.008/3h)", (0.001, 0.008, 0.3, 0.3, 2, 3)),
    ("中宽(加0.002/减0.006/3h)", (0.002, 0.006, 0.3, 0.3, 2, 3)),
    ("中(加0.001/减0.005/4h)",   (0.001, 0.005, 0.3, 0.3, 2, 4)),
    ("宽松+慢评估(加0.001/减0.008/6h)", (0.001, 0.008, 0.3, 0.3, 2, 6)),
    ("只加不减(加0.002/减1.0/4h)", (0.002, 1.0, 0.3, 0.0, 3, 4)),  # 永不减仓只加仓
    ("只减不加(加1.0/减0.006/4h)", (1.0, 0.006, 0.0, 0.3, 0, 4)),  # 永不加仓只减仓
]

for name, params in param_sets:
    r, s = backtest(lsig, ssig, "active", params)
    print_stats(r, s, name)