# Second part: critical Sharpe after N trials, years needed to detect a true 0.7 after paying for N trials,
# the curves for the cover, and direct-simulation checks of the critical value and of the power.
import numpy as np, json, math
from math import sqrt
from statistics import NormalDist
nd = NormalDist(); PPY = 365; SR = 0.7
rng = np.random.default_rng(20261116)
def zN(N, a=0.05): return nd.inv_cdf((1-a)**(1/N))      # one-sided level per trial so that P(any of N nulls passes) = a
def crit(N, T): return zN(N)/sqrt(T)                    # annual Sharpe the best of N null trials stays under 95% of the time
def years_detect(N, power=0.8): return ((zN(N)+nd.inv_cdf(power))/SR)**2
def emax_closed(N, T):
    xs = np.linspace(-8, 8, 160001); dx = xs[1]-xs[0]
    phi = np.exp(-xs**2/2)/sqrt(2*math.pi)
    cdf = np.interp(xs, xs[::100], [nd.cdf(x) for x in xs[::100]])
    return float((N*xs*phi*cdf**(N-1)).sum()*dx)/sqrt(T) if N > 1 else 0.0
Ts = [3, 7.5, 13.7, 20]; Ns = [1, 10, 40, 80, 100]
out = {}
out['crit'] = {str(T): {str(N): crit(N, T) for N in Ns} for T in Ts}
out['years_detect'] = {str(N): years_detect(N) for N in Ns}
curveN = [1, 2, 5, 10, 20, 40, 80, 160, 320, 640, 1000]
out['curve_emax'] = {str(T): {str(N): emax_closed(N, T) for N in curveN} for T in [7.5, 13.7, 20]}
# direct checks
def sharpes(n_days, mu_ann, N, sims):
    n = int(round(n_days)); mu_d = mu_ann/PPY; sd_d = 1/sqrt(PPY)  # daily sd chosen so that annual sd = 1
    r = rng.standard_normal((sims, N, n))*sd_d + mu_d
    return r.mean(-1)/r.std(-1, ddof=1)*sqrt(PPY)
chk = {}
# critical value: 95th percentile of the max of N null sample Sharpes
for T, N, sims in [(13.7, 10, 3000), (13.7, 80, 600), (7.5, 40, 2000)]:
    m = np.array([sharpes(T*PPY, 0.0, N, 1)[0].max() for _ in range(sims)])
    chk[f'crit_T{T}_N{N}'] = dict(sim95=float(np.quantile(m, 0.95)), closed=crit(N, T), sims=sims)
# power: a true 0.7 strategy beats the critical value of N trials at the stated years
for N in [1, 10, 80]:
    T = years_detect(N); c = crit(N, T)
    s = np.array([sharpes(T*PPY, SR, 1, 1)[0, 0] for _ in range(3000 if N < 80 else 1500)])
    chk[f'power_N{N}'] = dict(years=T, threshold=c, power=float((s >= c).mean()), sims=len(s))
out['checks'] = chk
json.dump(out, open('sim2_results.json', 'w'), indent=1)
for k, v in out['crit'].items(): print('crit T', k, {n: round(x, 3) for n, x in v.items()})
print('years_detect', {n: round(x, 1) for n, x in out['years_detect'].items()})
for k, v in out['curve_emax'].items(): print('emax T', k, {n: round(x, 2) for n, x in v.items()})
print(json.dumps(chk, indent=1))
