hrt / sim /robustness.py
dejanb's picture
Update run times
366cf14 verified
Raw History Blame Contribute Delete
6 kB
"""Stage 3: robustness of the Monte Carlo planners.
(a) Seeds: the one-step MC planner, the exhaustive tree and MCTS (1600 episodes) are rerun
on every asset with 20 independent random seeds; for each run we record the Sharpe
ratio (in excess of the T-bill rate), maximum drawdown, exposure, turnover and the
random-timing p-value.
(b) Sensitivity: the one-step MC planner on BTC and ETH with the prior strength kappa_0,
prior volatility s_0, half-life and risk aversion gamma changed one at a time.
Writes seeds.json, tables/seeds.tex and tables/sensitivity.tex. Takes about three hours on
seven cores (MCTS dominates); `python3 robustness.py --tables` only rewrites the tables.
"""
import json
import sys
import time
from multiprocessing import Pool
import numpy as np
import core
N_SEEDS = 20
SEED_SHIFTS = 1000 # random-timing shifts per seeded run
STRATS = ("mc", "tree", "mcts")
SENS = [("base", {}), ("kappa0", dict(kappa0=2.0)), ("kappa0", dict(kappa0=50.0)),
("s0", dict(s0_mult=0.5)), ("s0", dict(s0_mult=2.0)),
("half_life", dict(half_life=45)), ("half_life", dict(half_life=180)),
("gamma", dict(gamma=1.5)), ("gamma", dict(gamma=6.0))]
def setup(name):
cfg = core.ASSETS[name]
r = core.log_returns(core.load(name))
dates = core.load(name).index
W = cfg["warmup"]
rf = core.rf_daily(dates[W + 1:], cfg["ppy"])
return cfg, r, W, rf
def score(name, w_full, rng):
cfg, r, W, rf = setup(name)
ppy, cost = cfg["ppy"], cfg["cost"]
w, r_next = w_full[W:len(r) - 1], r[W + 1:]
ret = core.net_returns(w, r_next, cost, rf)
m = core.metrics(ret, w, ppy, rf)
t = core.shift_test(w, r_next, cost, ppy, cfg["window"], rng, SEED_SHIFTS, rf)
return dict(sharpe=m["sharpe"], maxdd=m["maxdd"], exposure=m["exposure"],
turnover=float(np.abs(np.diff(w)).sum() / (len(w) / ppy)), p=t["p_value"])
def seed_task(args):
name, strat, s = args
cfg, r, W, _ = setup(name)
post = core.posterior_path(r, cfg["s0"])
seed = [core.SEED, 1000 + s, list(core.ASSETS).index(name), STRATS.index(strat)]
t0 = time.time()
if strat == "mc":
w = core.mc_weights(post, cfg["cost"], seed, W - 1)
elif strat == "tree":
w = core.tree_weights(post, cfg["cost"], seed, W - 1)
else:
w = core.mcts_weights(post, cfg["cost"], seed, W - 1, core.TREE_SIMS)
out = score(name, w, np.random.default_rng(seed + [7]))
print(f"{name} {strat} seed {s} {time.time() - t0:.0f}s", flush=True)
return name, strat, s, out
def sens_task(args):
name, i = args
label, kw = SENS[i]
cfg, r, W, _ = setup(name)
post = core.posterior_path(r, cfg["s0"] * kw.get("s0_mult", 1.0),
kw.get("half_life", core.HALF_LIFE), kw.get("kappa0", core.KAPPA0))
seed = [core.SEED, 2000 + i, list(core.ASSETS).index(name)]
w = core.mc_weights(post, cfg["cost"], seed, W - 1, kw.get("gamma", core.GAMMA))
return name, i, score(name, w, np.random.default_rng(seed + [7]))
def summary(vals):
a = np.array(vals)
return dict(mean=float(a.mean()), sd=float(a.std(ddof=1)), min=float(a.min()), max=float(a.max()))
def tables(res):
res["sens"] = {n: {int(i): m for i, m in v.items()} for n, v in res["sens"].items()}
names = list(core.ASSETS)
lab = dict(mc="MC", tree="Tree", mcts="MCTS")
with open(core.ROOT / "tables" / "seeds.tex", "w") as f:
for n in names:
cells = []
for k in STRATS:
s = res["seeds"][n][k]
cells.append(f"{s['sharpe']['mean']:.2f} $\\pm$ {s['sharpe']['sd']:.2f}")
cells.append(f"[{s['sharpe']['min']:.2f}, {s['sharpe']['max']:.2f}]")
cells.append(f"{s['p']['min']:.2f}--{s['p']['max']:.2f}")
f.write(f"{n.upper()} & " + " & ".join(cells) + " \\\\\n")
if n == "ada":
f.write("\\midrule\n")
desc = dict(base="Base case", kappa0="$\\kappa_0$", s0="$s_0$", half_life="Half-life",
gamma="$\\gamma$")
val = ["", "2", "50", "$\\times 0.5$", "$\\times 2$", "45", "180", "1.5", "6"]
with open(core.ROOT / "tables" / "sensitivity.tex", "w") as f:
for i, (label, _) in enumerate(SENS):
row = []
for n in ("btc", "eth"):
m = res["sens"][n][i]
row += [f"{m['sharpe']:.2f}", f"{100 * m['maxdd']:.0f}\\%", f"{m['exposure']:.2f}",
f"{m['p']:.2f}"]
name = desc[label] + (f" $= {val[i]}$" if label in ("kappa0", "gamma") else
f" {val[i]}" if i else "")
f.write(f"{name} & " + " & ".join(row) + " \\\\\n")
if i == 0:
f.write("\\midrule\n")
if __name__ == "__main__" and sys.argv[1:] == ["--tables"]:
with open(core.ROOT / "seeds.json") as f:
tables(json.load(f))
elif __name__ == "__main__":
tasks = [(n, k, s) for k in ("mcts", "tree", "mc") for n in core.ASSETS for s in range(N_SEEDS)]
with Pool(7) as pool:
sens = pool.map(sens_task, [(n, i) for n in ("btc", "eth") for i in range(len(SENS))])
done = pool.map(seed_task, tasks, chunksize=1)
res = dict(n_seeds=N_SEEDS, seed_shifts=SEED_SHIFTS, seeds={}, runs={},
sens={n: {i: m for nn, i, m in sens if nn == n} for n in ("btc", "eth")},
sens_spec=[[l, kw] for l, kw in SENS])
for n in core.ASSETS:
res["seeds"][n], res["runs"][n] = {}, {}
for k in STRATS:
runs = [o for nn, kk, s, o in sorted(done, key=lambda x: x[2]) if nn == n and kk == k]
res["runs"][n][k] = runs
res["seeds"][n][k] = {m: summary([o[m] for o in runs]) for m in runs[0]}
res["seeds"][n][k]["share_p_below_05"] = float(np.mean([o["p"] <= 0.05 for o in runs]))
with open(core.ROOT / "seeds.json", "w") as f:
json.dump(res, f, indent=1)
tables(res)
print("done")