# Trial budget of a data length. Null strategies (true Sharpe 0), iid normal daily returns, 365 bars a year.
# 1) direct simulation of daily returns (small N) to confirm the closed form, 2) closed form for the rest.
import numpy as np, json, math
from math import erf, sqrt
rng = np.random.default_rng(20261115)
PPY = 365
def Phi(x): return 0.5*(1+erf(x/sqrt(2)))
def ann_sharpe(r):  # r: (..., n) daily returns
    return r.mean(-1)/r.std(-1, ddof=1)*sqrt(PPY)

# 1) direct simulation: E[max of N sample Sharpes] and P(max >= 0.7)
def direct(T, N, sims):
    n = int(round(T*PPY)); out = np.empty(sims)
    for s in range(sims):
        out[s] = ann_sharpe(rng.standard_normal((N, n))).max()
    return out
check = {}
for T, N, sims in [(7.5, 10, 4000), (7.5, 40, 2000), (13.7, 40, 1000)]:
    m = direct(T, N, sims)
    check[f"{T}y_{N}"] = dict(emax=float(m.mean()), p07=float((m >= 0.7).mean()), sims=sims)

# 2) closed form with sd = 1/sqrt(T): max of N iid normals
from statistics import NormalDist
nd = NormalDist()
def emax_closed(N, sd):
    # E[max of N N(0,1)] by numerical integration of N*x*phi(x)*Phi(x)^(N-1)
    xs = np.linspace(-8, 8, 160001); dx = xs[1]-xs[0]
    phi = np.exp(-xs**2/2)/sqrt(2*math.pi)
    Phis = np.array([nd.cdf(x) for x in xs[::100]])
    Phis = np.interp(xs, xs[::100], Phis)
    return float((N*xs*phi*Phis**(N-1)).sum()*dx)*sd
def p_best_ge(s, N, T):
    p = 1-nd.cdf(s*sqrt(T)); return 1-(1-p)**N
Ts = [3, 7.5, 13.7, 20]; Ns = [1, 5, 10, 40, 80, 100, 1000]
table = {str(T): {str(N): dict(emax=emax_closed(N, 1/sqrt(T)), p07=p_best_ge(0.7, N, T)) for N in Ns} for T in Ts}
# largest N with <=5% chance that the best null reaches 0.7
def nmax(T, s=0.7, a=0.05):
    p = 1-nd.cdf(s*sqrt(T)); return math.log(1-a)/math.log(1-p)
nmax_tab = {str(T): nmax(T) for T in Ts}
# correlated trials (parameter sweeps of one idea): equicorrelated sample Sharpes
def corr_emax(N, T, rho, sims=20000):
    sd = 1/sqrt(T)
    z0 = rng.standard_normal((sims, 1)); z = rng.standard_normal((sims, N))
    return float((sd*(sqrt(rho)*z0+sqrt(1-rho)*z)).max(1).mean())
corr = {str(rho): corr_emax(40, 7.5, rho) for rho in [0, 0.25, 0.5, 0.75, 0.9]}
res = dict(check_direct=check, table=table, nmax=nmax_tab, corr_N40_T7p5=corr)
json.dump(res, open('sim_results.json', 'w'), indent=1)
print(json.dumps(res, indent=1))
