hrt / sim /experiments.py
dejanb's picture
Code, frozen data, and outputs for the paper
28673f9 verified
Raw History Blame Contribute Delete
21.6 kB
"""Stage 2: accounting, statistical tests, tables and figures from the cached positions.
Reads out/pos_<asset>.npz (written by positions.py); writes results.json, tables/*.tex
and fig/*.pdf.
"""
import json
import math
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
import core
from core import LABEL, net_returns, sharpe
MAIN = ("hold", "sma", "bayes", "mc", "tree", "mcts")
ACTIVE = MAIN[1:]
COSTS = (0.0, 0.0005, 0.0015, 0.003, 0.005, 0.01)
H1_IR = 0.5 # information ratio under the "skill" hypothesis of the monitor
TABLES = core.ROOT / "tables"
COLOR = dict(hold="#1f77b4", sma="#ff7f0e", bayes="#2ca02c", mc="#d62728", tree="#9467bd",
mcts="#8c564b", vol="#7f7f7f")
plt.rcParams.update({"font.size": 8, "axes.spines.top": False, "axes.spines.right": False})
def pct(x, d=1):
return f"{100 * x:.{d}f}\\%"
def evaluate(name):
cfg = core.ASSETS[name]
ppy, window, cost, W = cfg["ppy"], cfg["window"], cfg["cost"], cfg["warmup"]
z = np.load(core.OUT / f"pos_{name}.npz")
r = z["r"]
idx = slice(W, len(r) - 1) # decisions on days W..N-2
r_next = r[W + 1:]
dates = pd.to_datetime(z["dates"][W + 1:])
rng = np.random.default_rng([core.SEED, 99, list(core.ASSETS).index(name)])
post = core.posterior_path(r, cfg["s0"])
rf = core.rf_daily(dates, ppy) # cash earns the T-bill rate
pos = {k: z[k][idx] for k in MAIN}
pos["vol"] = core.vol_weights(post, core.match_exposure(post, idx, pos["mc"].mean()))[idx]
ret = {k: net_returns(w, r_next, cost, rf) for k, w in pos.items()}
ex = {k: v - rf for k, v in ret.items()} # excess returns: Sharpe ratios and tests
simple = np.expm1(r_next)
hold_wins = core.window_returns(ret["hold"], window)
res = {}
for k in pos:
m = core.metrics(ret[k], pos[k], ppy, rf)
wins = core.window_returns(ret[k], window)
m["win_frac"] = float((wins > 0).mean())
m["beat_hold_frac"] = float((wins > hold_wins).mean())
m["psr0"] = core.psr(ex[k])
if k != "hold":
m.update(core.shift_test(pos[k], r_next, cost, ppy, window, rng, rf=rf))
# same average exposure, no timing
const = m["exposure"] * simple + (1 - m["exposure"]) * rf
m["vs_hold"] = core.bootstrap_sharpe_diff(ex[k], ex["hold"], ppy, rng)
# sequential Bayesian monitor of skill: active return against constant mix
a = ret[k] - const
mu1 = H1_IR * a.std() / math.sqrt(ppy)
llr = np.cumsum(mu1 * a / a.var() - mu1 * mu1 / (2 * a.var()))
m["monitor_final"] = float(1 / (1 + math.exp(-llr[-1])))
m["monitor_path"] = (1 / (1 + np.exp(-llr))).tolist() if k in ("mc", "tree") else None
m["active_ir"] = sharpe(a, ppy)
res[k] = m
# tuning grid, deflated Sharpe ratio, walk-forward
gkeys = [k for k in z.files if k.startswith("grid_")]
gpos = {k: z[k][idx] for k in gkeys}
gret = {k: net_returns(w, r_next, cost, rf) - rf for k, w in gpos.items()} # excess
half = len(r_next) // 2
grid = [dict(key=k, sharpe_first=sharpe(gret[k][:half], ppy),
sharpe_second=sharpe(gret[k][half:], ppy), sharpe_full=sharpe(gret[k], ppy))
for k in gkeys]
chosen = max(grid, key=lambda g: g["sharpe_first"])
trials = [gret[k].mean() / gret[k].std() for k in gkeys] + \
[ex[k].mean() / ex[k].std() for k in ACTIVE]
sr_star = core.deflated_sr_threshold(trials)
for k in ACTIVE:
res[k]["dsr"] = core.psr(ex[k], sr_star)
# data snooping over all strategies and variants tried on the asset
allk = list(ACTIVE) + ["vol"]
mat = np.column_stack([ex[k] for k in allk] + [gret[k] for k in gkeys])
spa = core.spa_sharpe(mat, ex["hold"], ppy, np.random.default_rng([core.SEED, 31,
list(core.ASSETS).index(name)]))
spa["best_name"] = (allk + gkeys)[spa["best"]]
pbo = core.pbo_cscv(mat)
look, step = 2 * ppy, ppy // 2
w_wf = np.zeros(len(r_next))
for s in range(look, len(r_next), step):
best = max(gkeys, key=lambda k: sharpe(gret[k][s - look:s], ppy))
w_wf[s:s + step] = gpos[best][s:s + step]
ev = slice(look, None)
wf = dict(walk_forward=sharpe(net_returns(w_wf[ev], r_next[ev], cost, rf[ev]) - rf[ev], ppy),
fixed=sharpe(ex["bayes"][ev], ppy), hold=sharpe(ex["hold"][ev], ppy),
best_hindsight=max(sharpe(gret[k][ev], ppy) for k in gkeys),
median=float(np.median([sharpe(gret[k][ev], ppy) for k in gkeys])))
tuning = dict(n_variants=len(grid), best_full=max(g["sharpe_full"] for g in grid),
median_full=float(np.median([g["sharpe_full"] for g in grid])),
worst_full=min(g["sharpe_full"] for g in grid), chosen_on_first=chosen,
hold_first=sharpe(ex["hold"][:half], ppy),
hold_second=sharpe(ex["hold"][half:], ppy),
split_date=str(dates[half].date()), dsr_threshold_annual=sr_star * math.sqrt(ppy))
# calendar years
years = {}
for y in sorted(set(dates.year)):
msk = dates.year == y
years[int(y)] = {k: float(np.prod(1 + ret[k][msk]) - 1) for k in ("hold", "mc", "tree")}
years[int(y)]["mc_exposure"] = float(pos["mc"][msk].mean())
# sensitivity to trading costs (positions fixed, only accounting changes)
costs = {k: [sharpe(net_returns(pos[k], r_next, c, rf) - rf, ppy) for c in COSTS] for k in MAIN}
# MCTS computational budget
budget = {}
for k in sorted((k for k in z.files if k.startswith("mcts") and k != "mcts"),
key=lambda k: int(k[4:])):
w = z[k][idx]
m = core.metrics(net_returns(w, r_next, cost, rf), w, ppy, rf)
m["dist_to_tree"] = float(np.abs(w - pos["tree"]).mean())
m["turnover"] = float(np.abs(np.diff(w)).sum() / (len(w) / ppy))
budget[int(k[4:])] = m
for k in ("mc", "tree"):
res[k]["turnover"] = float(np.abs(np.diff(pos[k])).sum() / (len(r_next) / ppy))
res["mc"]["dist_to_tree"] = float(np.abs(pos["mc"] - pos["tree"]).mean())
period = dict(start=str(dates[0].date()), end=str(dates[-1].date()), days=len(r_next))
series = dict(dates=dates, ret=ret, rf=rf, pos=pos, price=np.exp(np.cumsum(r_next)))
return dict(period=period, strategies=res, tuning=tuning, grid=grid, walk_forward=wf,
years=years, costs=costs, budget=budget, spa=spa, pbo=pbo,
rf_annual=float(np.mean(rf) * ppy)), series
def breadth(series):
"""Portfolios of the same strategy across assets (inverse-volatility weights)."""
start = max(s["dates"][0] for s in series.values())
end = min(s["dates"][-1] for s in series.values())
cal = pd.date_range(start, end, freq="D")
frames = {k: pd.DataFrame({n: pd.Series(s["ret"][k], index=s["dates"]).reindex(cal).fillna(0.0)
for n, s in series.items()}) for k in ("hold", "mc", "tree")}
rff = pd.DataFrame({n: pd.Series(s["rf"], index=s["dates"]).reindex(cal).fillna(0.0)
for n, s in series.items()})
expo = pd.Series({n: s["pos"]["mc"].mean() for n, s in series.items()})
active = frames["mc"] - frames["hold"] * expo - rff * (1 - expo)
groups = dict(btc=["btc"], crypto=[n for n in series if core.ASSETS[n]["cls"] == "crypto"],
etf=[n for n in series if core.ASSETS[n]["cls"] == "etf"], all=list(series))
rng = np.random.default_rng([core.SEED, 77])
out = {}
for g, names in groups.items():
wts = 1.0 / frames["hold"][names].std()
wts /= wts.sum()
port = {k: (frames[k][names] * wts).sum(axis=1).to_numpy() for k in frames}
prf = (rff[names] * wts).sum(axis=1).to_numpy()
row = {k: dict(sharpe=sharpe(v - prf, 365), maxdd=core.metrics(v, np.ones(1), 365)["maxdd"],
cagr=core.metrics(v, np.ones(1), 365)["cagr"]) for k, v in port.items()}
row["mc_vs_hold"] = core.bootstrap_sharpe_diff(port["mc"] - prf, port["hold"] - prf, 365, rng)
if len(names) > 1:
c = active[names].corr().to_numpy()
ch = frames["hold"][names].corr().to_numpy()
off = ~np.eye(len(names), dtype=bool)
row["corr_active"], row["corr_hold"] = float(c[off].mean()), float(ch[off].mean())
row["n"] = len(names)
out[g] = row
out["period"] = dict(start=str(start.date()), end=str(end.date()))
return out
# ---------- theory: the paradox in numbers ----------
def theory():
T = np.array([1 / 12, 5 / 12, 1, 2, 5, 10])
S = [0.5, 1.0, 2.0, 5.0, 20.0]
rng = np.random.default_rng([core.SEED, 55])
out = dict(T_years=T.tolist(), p_profit={}, posterior={}, wald_years={}, z2_years={})
for s in S:
out["p_profit"][s] = stats.norm.cdf(s * np.sqrt(T)).tolist()
out["posterior"][s] = (0.1 * stats.norm.cdf(s * np.sqrt(T)) /
(0.1 * stats.norm.cdf(s * np.sqrt(T)) + 0.9 * 0.5)).tolist()
out["wald_years"][s] = 2 * math.log(19) / s ** 2
out["z2_years"][s] = (2 / s) ** 2
# check of P(profit after 5 months) with fat tails (Student t, 4 d.o.f.) and compounding
n, vol = 152, 0.035
x = stats.t.rvs(4, size=(100000, n), random_state=rng) / math.sqrt(2.0) * vol
out["fat_tail_check"] = {s: float(((x + s * vol / math.sqrt(365)).sum(axis=1) > 0).mean())
for s in (0.0, 1.0)}
# contest: probability that the same two finish 1st and 2nd, in that order, in all rounds
sig = np.array([0.0, 0.1, 0.2, 0.35, 0.5, 0.75, 1.0, 1.5, 2.0, 3.5, 5.0, 7.2, 10.0, 20.0])
contest = {}
for R in (3, 5, 10):
probs = []
for s in sig:
skill = rng.standard_normal((20000, 1, 10))
score = skill + s * rng.standard_normal((20000, R, 10))
order = np.argsort(-score, axis=2)[:, :, :2]
probs.append(float((order == order[:, :1, :]).all(axis=(1, 2)).mean()))
contest[R] = probs
out["contest"] = dict(noise=sig.tolist(), same_top2=contest)
return out
# ---------- tables ----------
def write_tables(res, br):
TABLES.mkdir(exist_ok=True)
def main_rows(name):
rows = []
for k in MAIN + ("vol",):
m = res[name]["strategies"][k]
p = "---" if k == "hold" else f"{m['p_value']:.2f}"
rows.append(f"{LABEL[k]} & {pct(m['cagr'])} & {pct(m['vol'], 0)} & {m['sharpe']:.2f} & "
f"{pct(m['maxdd'], 0)} & {m['exposure']:.2f} & {m['trades_per_year']:.0f} & "
f"{pct(m['win_frac'], 0)} & {p} \\\\")
return rows
with open(TABLES / "main.tex", "w") as f:
for name in ("btc", "eth"):
f.write(f"\\multicolumn{{9}}{{@{{}}l}}{{\\emph{{{name.upper()}}}}} \\\\\n")
f.write("\n".join(main_rows(name)) + "\n")
if name == "btc":
f.write("\\midrule\n")
with open(TABLES / "significance.tex", "w") as f:
for name in ("btc", "eth"):
f.write(f"\\multicolumn{{7}}{{@{{}}l}}{{\\emph{{{name.upper()}}}}} \\\\\n")
for k in ACTIVE + ("vol",):
m = res[name]["strategies"][k]
vh = m["vs_hold"]
dsr = f"{m['dsr']:.2f}" if "dsr" in m else "---"
f.write(f"{LABEL[k]} & {m['p_value']:.2f} & {vh['diff']:+.2f} & "
f"[{vh['lo']:+.2f}, {vh['hi']:+.2f}] & {vh['p_le0']:.2f} & "
f"{m['psr0']:.2f} & {dsr} \\\\\n")
if name == "btc":
f.write("\\midrule\n")
with open(TABLES / "assets.tex", "w") as f:
for name in res:
s = res[name]["strategies"]
f.write(f"{name.upper()} & {s['hold']['sharpe']:.2f} & {pct(s['hold']['maxdd'], 0)} & "
f"{s['mc']['sharpe']:.2f} & {pct(s['mc']['maxdd'], 0)} & {s['mc']['exposure']:.2f} & "
f"{s['mc']['p_value']:.2f} & {s['tree']['sharpe']:.2f} & {s['tree']['p_value']:.2f} & "
f"{s['mcts']['sharpe']:.2f} & {s['vol']['sharpe']:.2f} \\\\\n")
if name == "ada":
f.write("\\midrule\n")
with open(TABLES / "windows.tex", "w") as f:
for name in res:
s = res[name]["strategies"]
f.write(f"{name.upper()} & {pct(s['hold']['win_frac'], 0)} & {pct(s['mc']['win_frac'], 0)} & "
f"{pct(s['mc']['shift_win_frac_median'], 0)} & {pct(s['tree']['win_frac'], 0)} & "
f"{pct(s['tree']['shift_win_frac_median'], 0)} & {pct(s['mc']['beat_hold_frac'], 0)} \\\\\n")
if name == "ada":
f.write("\\midrule\n")
with open(TABLES / "years.tex", "w") as f:
for y, v in res["btc"]["years"].items():
f.write(f"{y} & {pct(v['hold'], 0)} & {pct(v['mc'], 0)} & {pct(v['tree'], 0)} & "
f"{v['mc_exposure']:.2f} \\\\\n")
with open(TABLES / "budget.tex", "w") as f:
for name in ("btc", "eth"):
f.write(f"\\multicolumn{{6}}{{@{{}}l}}{{\\emph{{{name.upper()}}}}} \\\\\n")
for b, m in res[name]["budget"].items():
f.write(f"MCTS, {b} episodes & {m['sharpe']:.2f} & {pct(m['maxdd'], 0)} & "
f"{m['turnover']:.0f} & {m['exposure']:.2f} & {m['dist_to_tree']:.2f} \\\\\n")
for k in ("mc", "tree"):
m = res[name]["strategies"][k]
d = f"{m['dist_to_tree']:.2f}" if k == "mc" else "0"
f.write(f"{LABEL[k]} & {m['sharpe']:.2f} & {pct(m['maxdd'], 0)} & "
f"{m['turnover']:.0f} & {m['exposure']:.2f} & {d} \\\\\n")
if name == "btc":
f.write("\\midrule\n")
with open(TABLES / "tuning.tex", "w") as f:
for name in res:
t, w = res[name]["tuning"], res[name]["walk_forward"]
c = t["chosen_on_first"]
f.write(f"{name.upper()} & {t['median_full']:.2f} & {t['best_full']:.2f} & "
f"{c['sharpe_first']:.2f} & {c['sharpe_second']:.2f} & {t['hold_second']:.2f} & "
f"{w['walk_forward']:.2f} & {w['fixed']:.2f} & {w['hold']:.2f} \\\\\n")
if name == "ada":
f.write("\\midrule\n")
with open(TABLES / "snooping.tex", "w") as f:
for name in res:
sp, pb = res[name]["spa"], res[name]["pbo"]
f.write(f"{name.upper()} & {sp['best_diff']:+.2f} & {sp['p_rc']:.2f} & {sp['p_spa']:.2f} & "
f"{pb['pbo']:.2f} \\\\\n")
if name == "ada":
f.write("\\midrule\n")
name_g = dict(btc="Bitcoin only", crypto="Six cryptocurrencies", etf="Four ETFs",
all="All ten assets")
with open(TABLES / "breadth.tex", "w") as f:
for g in ("btc", "crypto", "etf", "all"):
b = br[g]
ca = f"{b['corr_hold']:.2f} & {b['corr_active']:.2f}" if "corr_hold" in b else "--- & ---"
d = b["mc_vs_hold"]
f.write(f"{name_g[g]} & {b['hold']['sharpe']:.2f} & {pct(b['hold']['maxdd'], 0)} & "
f"{b['mc']['sharpe']:.2f} & {pct(b['mc']['maxdd'], 0)} & {b['tree']['sharpe']:.2f} & "
f"{ca} & [{d['lo']:+.2f}, {d['hi']:+.2f}] \\\\\n")
# ---------- figures ----------
def figures(res, series, th):
core.FIG.mkdir(exist_ok=True)
for name in ("btc", "eth"):
s = series[name]
fig, ax = plt.subplots(figsize=(6.6, 3.0))
for k in MAIN:
ax.plot(s["dates"], np.cumprod(1 + s["ret"][k]), label=LABEL[k], lw=1.0, color=COLOR[k])
ax.set_yscale("log")
ax.set_ylabel("wealth (log scale)")
ax.legend(frameon=False, fontsize=7, ncol=2)
fig.tight_layout()
fig.savefig(core.FIG / f"{name}_equity.pdf")
plt.close(fig)
s = series["btc"]
cfg = core.ASSETS["btc"]
fig, ax = plt.subplots(figsize=(6.6, 2.6))
bins = np.linspace(-0.8, 3.0, 60)
for k in ("hold", "mc"):
ax.hist(core.window_returns(s["ret"][k], cfg["window"]), bins=bins, alpha=0.5,
label=LABEL[k], density=True, color=COLOR[k])
ax.axvline(0, color="k", lw=0.8)
ax.set_xlabel("return over a five-month window")
ax.set_ylabel("density")
ax.legend(frameon=False)
fig.tight_layout()
fig.savefig(core.FIG / "btc_windows.pdf")
plt.close(fig)
# what the planner does: price and position
fig, (a1, a2) = plt.subplots(2, 1, figsize=(6.6, 3.4), sharex=True,
gridspec_kw=dict(height_ratios=[2, 1]))
a1.plot(s["dates"], s["price"] / s["price"][0], color="k", lw=0.8)
a1.set_yscale("log")
a1.set_ylabel("BTC price (start = 1)")
a2.fill_between(s["dates"], s["pos"]["mc"], step="post", color=COLOR["mc"], alpha=0.7, lw=0)
a2.set_ylabel("position")
a2.set_ylim(0, 1)
fig.tight_layout()
fig.savefig(core.FIG / "btc_position.pdf")
plt.close(fig)
# sequential monitor
fig, ax = plt.subplots(figsize=(6.6, 2.5))
for k in ("mc", "tree"):
ax.plot(s["dates"], res["btc"]["strategies"][k]["monitor_path"], label=LABEL[k],
color=COLOR[k], lw=1.0)
ax.axhline(0.95, color="k", lw=0.6, ls="--")
ax.axhline(0.5, color="k", lw=0.4)
ax.set_ylim(0, 1)
ax.set_ylabel("P(skill | data so far)")
ax.legend(frameon=False)
fig.tight_layout()
fig.savefig(core.FIG / "monitor.pdf")
plt.close(fig)
# costs
fig, axes = plt.subplots(1, 2, figsize=(6.6, 2.5), sharey=True)
for ax, name in zip(axes, ("btc", "eth")):
for k in MAIN:
ax.plot([100 * c for c in COSTS], res[name]["costs"][k], marker="o", ms=2.5,
lw=1.0, label=LABEL[k], color=COLOR[k])
ax.set_xlabel("cost per trade (% of traded amount)")
ax.set_title(name.upper(), fontsize=8)
axes[0].set_ylabel("Sharpe ratio")
axes[1].legend(frameon=False, fontsize=6.5)
fig.tight_layout()
fig.savefig(core.FIG / "costs.pdf")
plt.close(fig)
# MCTS budget
fig, axes = plt.subplots(1, 2, figsize=(6.6, 2.5))
for name, ls in (("btc", "-"), ("eth", "--")):
b = res[name]["budget"]
x = list(b)
axes[0].plot(x, [b[k]["turnover"] for k in x], marker="o", ms=3, ls=ls,
color=COLOR["mcts"], label=f"MCTS, {name.upper()}")
axes[0].axhline(res[name]["strategies"]["tree"]["turnover"], color=COLOR["tree"], ls=ls, lw=0.8)
axes[1].plot(x, [b[k]["sharpe"] for k in x], marker="o", ms=3, ls=ls, color=COLOR["mcts"])
axes[1].axhline(res[name]["strategies"]["tree"]["sharpe"], color=COLOR["tree"], ls=ls, lw=0.8)
for ax, lab in zip(axes, ("turnover (times wealth per year)", "Sharpe ratio")):
ax.set_xscale("log")
ax.set_xlabel("episodes per decision")
ax.set_ylabel(lab)
axes[0].set_yscale("log")
axes[0].legend(frameon=False, fontsize=7)
fig.tight_layout()
fig.savefig(core.FIG / "budget.pdf")
plt.close(fig)
# the paradox: probability of profit and posterior of skill
T = np.linspace(0.02, 10, 300)
fig, axes = plt.subplots(1, 2, figsize=(6.6, 2.6))
for sr, c in zip((0.0, 0.5, 1.0, 2.0, 5.0), ("k", "#1f77b4", "#2ca02c", "#ff7f0e", "#d62728")):
p = stats.norm.cdf(sr * np.sqrt(T))
axes[0].plot(T, p, color=c, lw=1.0, label=f"S = {sr:g}")
if sr > 0:
axes[1].plot(T, 0.1 * p / (0.1 * p + 0.9 * 0.5), color=c, lw=1.0)
for ax in axes:
ax.axvline(5 / 12, color="k", lw=0.5, ls=":")
ax.set_xscale("log")
ax.set_xlabel("length of track record (years)")
axes[0].set_ylabel("P(track record shows a profit)")
axes[1].set_ylabel("P(skill | profit), prior 10%")
axes[0].legend(frameon=False, fontsize=7)
fig.tight_layout()
fig.savefig(core.FIG / "paradox.pdf")
plt.close(fig)
# contest
fig, ax = plt.subplots(figsize=(6.6, 2.6))
c = th["contest"]
for R, ls in zip((3, 5, 10), ("-", "--", ":")):
ax.plot(c["noise"][1:], c["same_top2"][R][1:], ls=ls, color="k", lw=1.0, label=f"{R} rounds")
for x, lab in ((1.0, "1 year"), (3.5, "1 month"), (7.2, "1 week")):
ax.axvline(x, color="#d62728", lw=0.6)
ax.text(x * 1.05, 0.9, lab, color="#d62728", fontsize=7)
ax.set_xscale("log")
ax.set_xlabel("noise in one round relative to the spread of skill")
ax.set_ylabel("P(same two are 1st and 2nd\nin every round)")
ax.legend(frameon=False, loc="center left")
fig.tight_layout()
fig.savefig(core.FIG / "contest.pdf")
plt.close(fig)
def strip(o):
if isinstance(o, dict):
return {str(k): strip(v) for k, v in o.items() if k != "monitor_path"}
return o
if __name__ == "__main__":
res, series = {}, {}
for n in core.ASSETS:
res[n], series[n] = evaluate(n)
print(n, res[n]["period"], flush=True)
br, th = breadth(series), theory()
write_tables(res, br)
figures(res, series, th)
with open(core.ROOT / "results.json", "w") as f:
json.dump(strip(dict(assets=res, breadth=br, theory=th)), f, indent=1)
for n in ("btc", "eth"):
print(n)
for k, m in res[n]["strategies"].items():
print(f" {k:6s} " + " ".join(f"{a}={v:.3f}" for a, v in m.items()
if isinstance(v, float)))