File size: 17,437 Bytes
28673f9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | """Models, strategies, accounting and statistical tests for the HRT paradox paper.
Strategies decide a position w_t in [0, 1] (long or cash, no leverage) at the close of
day t, using only data up to t; the position earns the return of day t+1, minus costs.
hold buy and hold
sma trend baseline: long when SMA(50) > SMA(200)
bayes Bayesian drift: P(mu > 0 | data) from a discounted Normal-Inverse-Gamma model
mc one-step Bayesian Monte Carlo planning: sample 20-day futures from the posterior,
pick the position with the highest expected CRRA utility net of trading costs
mcts Bayes-adaptive Monte Carlo tree search: same model and utility, but the agent
can rebalance every 5 days within the 20-day horizon, reacting to whether the
price went down, sideways or up (UCT with root sampling and common random
numbers at the root)
tree the same 4-step decision tree searched exhaustively by backward induction on a
fixed scenario set (the limit that MCTS approximates)
All hyperparameters are fixed here, before any run on the data they are applied to.
"""
import math
from pathlib import Path
import numpy as np
import pandas as pd
from scipy import stats
ROOT = Path(__file__).resolve().parent.parent
DATA, FIG, OUT = ROOT / "data", ROOT / "fig", ROOT / "out"
# periods per year, evaluation window ("five months"), cost per unit of turnover,
# prior daily volatility, warm-up length
CRYPTO = dict(ppy=365, window=152, cost=0.0015, s0=0.04, warmup=365, cls="crypto")
ETF = dict(ppy=252, window=105, cost=0.0005, s0=0.012, warmup=252, cls="etf")
ASSETS = dict(btc=CRYPTO, eth=CRYPTO, bnb=CRYPTO, xrp=CRYPTO, ltc=CRYPTO, ada=CRYPTO,
spy=ETF, qqq=ETF, gld=ETF, tlt=ETF)
HALF_LIFE = 90 # discounting of old data, in observations
ENTER, EXIT = 0.55, 0.45
KAPPA0, ALPHA0 = 10.0, 2.0
MC_PATHS, MC_HORIZON, GAMMA = 2000, 20, 3.0
MC_GRID = [0.0, 0.25, 0.5, 0.75, 1.0]
TREE_SIMS, TREE_STEP, TREE_DEPTH, UCT_C = 1600, 5, 4, 1.0 # 4 decisions x 5 days = 20
N_SHIFTS = 5000
SEED = 2026
LABEL = dict(hold="Buy and hold", sma="SMA 50/200", bayes="Bayesian drift",
mc="Bayesian MC (1 step)", tree="Bayesian tree (4 steps)", mcts="Bayes-adaptive MCTS", vol="Volatility timing",
const="Constant mix")
def load(name):
df = pd.read_csv(DATA / f"{name}.csv", parse_dates=["date"]).set_index("date")
return df["close"]
def log_returns(price):
return np.log(price).diff().fillna(0.0).to_numpy()
def rf_daily(dates, ppy):
"""Risk-free rate per period on the given dates: 13-week US Treasury bill yield
(Yahoo ^IRX, annual percent), carried forward to days without a quote."""
y = load("irx")
y = y.reindex(y.index.union(pd.DatetimeIndex(dates))).ffill().bfill()
y = y.reindex(pd.DatetimeIndex(dates)).to_numpy()
return (1.0 + y / 100.0) ** (1.0 / ppy) - 1.0
# ---------- Bayesian model ----------
def posterior_path(r, s0, half_life=HALF_LIFE, kappa0=KAPPA0):
"""Discounted NIG posterior after each day: columns mu_n, kappa_n, alpha_n, beta_n."""
d = 0.5 ** (1.0 / half_life)
b0 = ALPHA0 * s0 * s0
n = s1 = s2 = 0.0
out = np.empty((len(r), 4))
for t, x in enumerate(r):
n, s1, s2 = d * n + 1.0, d * s1 + x, d * s2 + x * x
kn = kappa0 + n
xbar = s1 / n
out[t, 0] = s1 / kn # prior mean is zero
out[t, 1] = kn
out[t, 2] = ALPHA0 + n / 2.0
out[t, 3] = b0 + 0.5 * max(s2 - s1 * s1 / n, 0.0) + kappa0 * n * xbar * xbar / (2.0 * kn)
return out
def prob_positive(post):
mn, kn, an, bn = post.T
return stats.t.cdf(mn / np.sqrt(bn / (an * kn)), df=2.0 * an)
def predictive_vol(post):
"""Posterior mean of sigma (daily)."""
return np.sqrt(post[:, 3] / np.maximum(post[:, 2] - 1.0, 0.5))
# ---------- strategies ----------
def sma_weights(price):
fast, slow = price.rolling(50).mean(), price.rolling(200).mean()
return (fast > slow).astype(float).to_numpy()
def bayes_weights(post, enter=ENTER, exit_=None):
exit_ = 1.0 - enter if exit_ is None else exit_
p = prob_positive(post)
w, cur = np.zeros(len(p)), 0.0
for t in range(len(p)):
if cur == 0.0 and p[t] > enter:
cur = 1.0
elif cur == 1.0 and p[t] < exit_:
cur = 0.0
w[t] = cur
return w
def crra(wealth, gamma=GAMMA):
return (np.maximum(wealth, 1e-6) ** (1.0 - gamma) - 1.0) / (1.0 - gamma)
def mc_weights(post, cost, seed, start=0, gamma=GAMMA):
rng = np.random.default_rng(seed)
grid = np.array(MC_GRID)
w, cur = np.zeros(len(post)), 0.0
for t in range(start, len(post)):
mn, kn, an, bn = post[t]
sig2 = bn / rng.gamma(an, 1.0, MC_PATHS) # sigma^2 ~ InvGamma
mu = mn + np.sqrt(sig2 / kn) * rng.standard_normal(MC_PATHS)
R = MC_HORIZON * mu + np.sqrt(MC_HORIZON * sig2) * rng.standard_normal(MC_PATHS)
wealth = 1.0 + grid[None, :] * np.expm1(R)[:, None] - cost * np.abs(grid - cur)[None, :]
cur = grid[np.argmax(crra(wealth, gamma).mean(axis=0))]
w[t] = cur
return w
def mcts_decide(post_t, cur, cost, sims, rng):
"""One decision of Bayes-adaptive MCTS (root sampling, as in BAMCP).
Each scenario draws a market (mu, sigma^2) from the posterior and a 20-day price
path from it. Tree nodes are histories of (action, observed move), where the move
over each 5-day step is bucketed into down / sideways / up, so later decisions can
react to what the simulated market did. Below the root, actions are chosen by UCT;
a history seen for the first time is added to the tree and the episode is finished
with the default policy (keep the position). At the root, every scenario is played
once for each action (common random numbers), which removes most sampling noise
from the comparison of root actions. `sims` counts episodes."""
mn, kn, an, bn = post_t
n_act, n_scen = len(MC_GRID), sims // len(MC_GRID)
sig2 = bn / rng.gamma(an, 1.0, n_scen)
mu = mn + np.sqrt(sig2 / kn) * rng.standard_normal(n_scen)
R = TREE_STEP * mu[:, None] + np.sqrt(TREE_STEP * sig2)[:, None] * \
rng.standard_normal((n_scen, TREE_DEPTH))
thr = 0.5 * math.sqrt(TREE_STEP * bn / max(an - 1.0, 0.5))
bucket = np.where(R < -thr, 0, np.where(R > thr, 2, 1)).tolist()
gross = np.expm1(R).tolist()
tree, one_g = {}, 1.0 - GAMMA
root_tot = [0.0] * n_act
su = suu = 0.0
k = 0
for s in range(n_scen):
g_s, b_s = gross[s], bucket[s]
c = UCT_C * math.sqrt(max(suu / k - (su / k) ** 2, 1e-12)) if k > 10 else 0.1
for a0 in range(n_act):
w_prev = MC_GRID[a0]
wealth = 1.0 + w_prev * g_s[0] - cost * abs(w_prev - cur)
h, path = a0 * 3 + b_s[0] + 1, []
for d in range(1, TREE_DEPTH):
node = tree.get(h)
if node is None: # expansion, then default policy
node = tree[h] = ([0] * n_act, [0.0] * n_act)
path.append((node[0], node[1], MC_GRID.index(w_prev)))
for dd in range(d, TREE_DEPTH):
wealth *= 1.0 + w_prev * g_s[dd]
break
cnt, tot = node
untried = [i for i in range(n_act) if cnt[i] == 0]
if untried: # nearest position first
a = min(untried, key=lambda i: abs(MC_GRID[i] - w_prev))
else:
logn = math.log(sum(cnt))
a, best = 0, -1e300
for i in range(n_act):
v = tot[i] / cnt[i] + c * math.sqrt(logn / cnt[i])
if v > best:
a, best = i, v
w = MC_GRID[a]
wealth *= 1.0 + w * g_s[d] - cost * abs(w - w_prev)
path.append((cnt, tot, a))
h = h * 16 + a * 3 + b_s[d] + 1
w_prev = w
u = (max(wealth, 1e-6) ** one_g - 1.0) / one_g
root_tot[a0] += u
su += u
suu += u * u
k += 1
for cnt, tot, a in path:
cnt[a] += 1
tot[a] += u
return MC_GRID[max(range(n_act), key=root_tot.__getitem__)]
def mcts_weights(post, cost, seed, start=0, sims=TREE_SIMS):
rng = np.random.default_rng(seed)
w, cur = np.zeros(len(post)), 0.0
for t in range(start, len(post)):
cur = mcts_decide(post[t], cur, cost, sims, rng)
w[t] = cur
return w
def tree_weights(post, cost, seed, start=0):
"""Exhaustive search of the same 4-step decision tree by backward induction on a
fixed set of sampled scenarios (the limit that MCTS approximates by sampling).
State before each decision: current position and the bucketed price history.
Every action sequence is evaluated on the same scenarios, so comparisons are paired."""
rng = np.random.default_rng(seed)
grid = np.array(MC_GRID)
n_act, one_g = len(grid), 1.0 - GAMMA
switch = np.abs(grid[None, :] - grid[:, None]) # [from, to]
w, cur = np.zeros(len(post)), 0
for t in range(start, len(post)):
mn, kn, an, bn = post[t]
sig2 = bn / rng.gamma(an, 1.0, MC_PATHS)
mu = mn + np.sqrt(sig2 / kn) * rng.standard_normal(MC_PATHS)
R = TREE_STEP * mu[:, None] + np.sqrt(TREE_STEP * sig2)[:, None] * \
rng.standard_normal((MC_PATHS, TREE_DEPTH))
thr = 0.5 * math.sqrt(TREE_STEP * bn / max(an - 1.0, 0.5))
bucket = np.where(R < -thr, 0, np.where(R > thr, 2, 1))
gross = np.expm1(R)
v = np.ones((MC_PATHS, n_act)) # value after the last step
for d in range(TREE_DEPTH - 1, -1, -1):
# f[n, from, to]: wealth factor of step d, raised to 1 - gamma
f = 1.0 + grid[None, None, :] * gross[:, d, None, None] - cost * switch[None]
q = np.maximum(f, 1e-6) ** one_g * v[:, None, :]
if d == 0:
cur = int(np.argmin(q[:, cur, :].mean(axis=0))) # gamma > 1: minimize
break
code = np.zeros(MC_PATHS, dtype=int) # history of moves before d
for j in range(d):
code = code * 3 + bucket[:, j]
onehot = np.zeros((MC_PATHS, 3 ** d))
onehot[np.arange(MC_PATHS), code] = 1.0
sums = onehot.T @ q.reshape(MC_PATHS, -1) # [group, from * to]
best = sums.reshape(-1, n_act, n_act).argmin(axis=2) # [group, from]
v = np.take_along_axis(q, best[code][:, :, None], axis=2)[:, :, 0]
w[t] = grid[cur]
return w
def vol_weights(post, target):
"""Volatility timing without any view on direction: w = min(1, target / sigma_hat)."""
return np.minimum(1.0, target / predictive_vol(post))
def match_exposure(post, sl, exposure):
"""Target volatility for which vol_weights has the given mean exposure on slice sl."""
lo, hi = 1e-5, 1.0
for _ in range(60):
mid = 0.5 * (lo + hi)
if vol_weights(post, mid)[sl].mean() < exposure:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
# ---------- accounting ----------
def net_returns(w, r_next, cost, rf=0.0):
"""w[t] earns the simple return of day t+1, the cash part 1 - w[t] earns the
risk-free rate rf; cost is paid on changes of position. Returns total returns."""
turn = np.abs(np.diff(np.concatenate([[0.0], w])))
return w * np.expm1(r_next) + (1.0 - w) * rf - cost * turn
def sharpe(ret, ppy):
s = ret.std()
return float(ret.mean() / s * math.sqrt(ppy)) if s > 0 else 0.0
def metrics(ret, w, ppy, rf=0.0):
"""ret: total returns; the Sharpe ratio is computed on returns in excess of rf."""
eq = np.cumprod(1.0 + ret)
years = len(ret) / ppy
dd = 1.0 - eq / np.maximum.accumulate(eq)
return dict(
total=float(eq[-1] - 1.0),
cagr=float(eq[-1] ** (1 / years) - 1.0),
vol=float(ret.std() * math.sqrt(ppy)),
sharpe=sharpe(ret - rf, ppy),
maxdd=float(dd.max()),
exposure=float(w.mean()),
trades_per_year=float((np.abs(np.diff(w)) > 0).sum() / years),
)
def window_returns(ret, n):
eq = np.concatenate([[1.0], np.cumprod(1.0 + ret)])
return eq[n:] / eq[:-n] - 1.0
# ---------- statistical tests ----------
def shift_test(w, r_next, cost, ppy, window, rng, n_shifts=N_SHIFTS, rf=0.0):
"""Random-timing benchmark: circularly shift the position series against returns.
Keeps exposure, turnover and holding periods; destroys any timing skill."""
n, base = len(w), sharpe(net_returns(w, r_next, cost, rf) - rf, ppy)
sh, win = np.empty(n_shifts), np.empty(n_shifts)
for i, k in enumerate(rng.integers(window, n - window, n_shifts)):
ret = net_returns(np.roll(w, k), r_next, cost, rf)
sh[i] = sharpe(ret - rf, ppy)
win[i] = (window_returns(ret, window) > 0).mean()
return dict(p_value=float((1 + (sh >= base).sum()) / (1 + n_shifts)),
shift_sharpe_median=float(np.median(sh)),
shift_win_frac_median=float(np.median(win)))
def stationary_bootstrap_idx(n, mean_block, rng):
new = rng.random(n) < 1.0 / mean_block
new[0] = True
start_pos = np.maximum.accumulate(np.where(new, np.arange(n), 0))
starts = rng.integers(0, n, n)
return (starts[start_pos] + np.arange(n) - start_pos) % n
def bootstrap_sharpe_diff(ret_a, ret_b, ppy, rng, n_boot=2000, mean_block=20):
"""Paired stationary bootstrap of Sharpe(a) - Sharpe(b)."""
n, diffs = len(ret_a), np.empty(n_boot)
for i in range(n_boot):
idx = stationary_bootstrap_idx(n, mean_block, rng)
diffs[i] = sharpe(ret_a[idx], ppy) - sharpe(ret_b[idx], ppy)
lo, hi = np.percentile(diffs, [2.5, 97.5])
return dict(diff=sharpe(ret_a, ppy) - sharpe(ret_b, ppy), lo=float(lo), hi=float(hi),
p_le0=float((diffs <= 0).mean()))
def spa_sharpe(ex, bench, ppy, rng, n_boot=2000, mean_block=20):
"""Hansen's (2005) test for superior predictive ability, applied to Sharpe-ratio
differences against a benchmark. ex: [T, K] excess returns of K strategies;
bench: [T] excess returns of the benchmark. H0: no strategy has a higher Sharpe
ratio than the benchmark. Studentized with bootstrap standard errors; returns the
consistent p-value (SPA_c) and White's reality-check p-value (no studentization,
least favorable recentering)."""
T, K = ex.shape
def sr(x):
return x.mean(axis=0) / x.std(axis=0) * math.sqrt(ppy)
d = sr(ex) - sr(bench[:, None])
boot = np.empty((n_boot, K))
for b in range(n_boot):
idx = stationary_bootstrap_idx(T, mean_block, rng)
boot[b] = sr(ex[idx]) - sr(bench[idx][:, None])
se = np.maximum(boot.std(axis=0), 1e-12)
stat = max(float((d / se).max()), 0.0)
keep = d / se >= -math.sqrt(2.0 * math.log(math.log(T)))
cen = boot - np.where(keep, d, 0.0) # SPA_c recentering
p_spa = float((np.maximum((cen / se).max(axis=1), 0.0) >= stat).mean())
rc_stat = float(d.max())
p_rc = float(((boot - d).max(axis=1) >= rc_stat).mean())
return dict(p_spa=p_spa, p_rc=p_rc, best=int(np.argmax(d)), best_diff=float(d.max()), k=K)
def pbo_cscv(ex, n_blocks=16):
"""Probability of backtest overfitting by combinatorially symmetric cross-validation
(Bailey et al. 2017). ex: [T, N] excess returns of N variants. For every split of
the n_blocks blocks into two halves, the variant with the best in-sample Sharpe
ratio is ranked out of sample; PBO is the share of splits in which it falls in the
bottom half."""
from itertools import combinations
T, N = ex.shape
L = T // n_blocks
x = ex[:L * n_blocks].reshape(n_blocks, L, N)
s1, s2 = x.sum(axis=1), (x * x).sum(axis=1) # [blocks, N]
logits, oos_best = [], []
for c in combinations(range(n_blocks), n_blocks // 2):
m = np.zeros(n_blocks, dtype=bool)
m[list(c)] = True
def sr(mask):
n = mask.sum() * L
mu = s1[mask].sum(axis=0) / n
return mu / np.sqrt(np.maximum(s2[mask].sum(axis=0) / n - mu * mu, 1e-18))
is_, oos = sr(m), sr(~m)
best = int(np.argmax(is_))
omega = (stats.rankdata(oos)[best]) / (N + 1)
logits.append(math.log(omega / (1 - omega)))
logits = np.array(logits)
return dict(pbo=float((logits <= 0).mean()), n_splits=len(logits), n_variants=N)
def psr(ret, sr_star=0.0):
"""Probabilistic Sharpe ratio (Bailey and Lopez de Prado); sr_star per period."""
n, sr = len(ret), ret.mean() / ret.std()
g3, g4 = stats.skew(ret), stats.kurtosis(ret, fisher=False)
den = math.sqrt(max(1.0 - g3 * sr + (g4 - 1.0) / 4.0 * sr * sr, 1e-12))
return float(stats.norm.cdf((sr - sr_star) * math.sqrt(n - 1) / den))
def deflated_sr_threshold(trial_sharpes_per_period):
"""Expected maximum per-period Sharpe among N unskilled trials."""
n, v = len(trial_sharpes_per_period), np.var(trial_sharpes_per_period, ddof=1)
em = 0.5772156649
z = (1 - em) * stats.norm.ppf(1 - 1.0 / n) + em * stats.norm.ppf(1 - 1.0 / (n * math.e))
return float(math.sqrt(v) * z)
|