# -*- coding: utf-8 -*- """邻域参数稳健性检验(导出 JSON 供绘图)——逻辑同 稳健性检验.py""" import os, importlib.util, itertools, json, statistics BASE = os.path.dirname(os.path.abspath(__file__)) spec = importlib.util.spec_from_file_location("v2", os.path.join(BASE, "均值回归_双向.py")) v2 = importlib.util.module_from_spec(spec); spec.loader.exec_module(v2) days = v2.load_days() cache = {N: v2.make_dev_cache(days, N) for N in (10, 15, 20, 30)} def score(pl, ps): tl = v2.run_side(cache[pl["N"]], "long", K=pl["K"], TP=pl["TP"], SL=pl["SL"], ED=pl["ED"], trend_filter=True, skip_open=5, max_per_day=2) ts = v2.run_side(cache[ps["N"]], "short", K=ps["K"], TP=ps["TP"], SL=ps["SL"], ED=ps["ED"], trend_filter=True, skip_open=5, max_per_day=2) q = {} for t in tl + ts: k = v2.quarter_key(t["date"]) q[k] = q.get(k, 0.0) + t["ret"] return q, sum(t["ret"] for t in tl), sum(t["ret"] for t in ts), len(tl) + len(ts) res = [] for ln, lk, lt, ls in itertools.product([10, 15, 20], [-0.2, -0.3, -0.4], [0.3, 0.5], [0.5, 1.0]): for sn, sk, st, ss in itertools.product([10, 15, 20], [0.3, 0.4, 0.5], [0.3, 0.5], [0.3, 0.5]): q, tl, ts, n = score({"N": ln, "K": lk, "TP": lt, "SL": ls, "ED": -0.1}, {"N": sn, "K": sk, "TP": st, "SL": ss, "ED": -0.1}) if len(q) < 12 or ts < 0 or tl < 5: continue res.append({"neg": sum(1 for x in q.values() if x < 0), "lo": min(q.values()), "tot": tl + ts, "n": n, "L": [ln, lk, lt, ls], "S": [sn, sk, st, ss]}) tots = [r["tot"] for r in res] los = [r["lo"] for r in res] negs = [r["neg"] for r in res] out = { "all": len(res), "ok12": sum(1 for r in res if r["neg"] == 0 and r["lo"] >= 0.2), "ok11": sum(1 for r in res if r["neg"] <= 1), "zero_neg": sum(1 for r in res if r["neg"] == 0), "tot_median": statistics.median(tots), "tot_mean": statistics.mean(tots), "tot_min": min(tots), "tot_max": max(tots), "lo_median": statistics.median(los), "lo_min": min(los), "lo_max": max(los), "neg_hist": {str(i): sum(1 for x in negs if x == i) for i in range(0, 13)}, "tots": tots, "los": los, "negs": negs, "top": sorted(res, key=lambda x: (x["neg"], -x["lo"], -x["tot"]))[:15], } json.dump(out, open(os.path.join(BASE, "稳健性检验结果.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1) print("有效组合 %d | 12季度全正 %d (%.0f%%) | 最多1个季度为负 %d (%.0f%%)" % (out["all"], out["ok12"], out["ok12"] / out["all"] * 100, out["ok11"], out["ok11"] / out["all"] * 100)) print("总增厚 中位%.2f%% 最小%.2f%% 最大%.2f%% | 最差季度 中位%+.2f%%" % (out["tot_median"], out["tot_min"], out["tot_max"], out["lo_median"])) print("负季度数分布:", out["neg_hist"])