"""Fixed-horizon checks of a claimed annualized Sharpe ratio."""

from math import ceil, sqrt
from statistics import NormalDist


def flat_probability(k, sharpe=8):
    """P(cumulative P&L <= 0) under independent normal daily P&Ls."""
    if k < 1 or sharpe <= 0:
        raise ValueError("Use k >= 1 and a positive annualized Sharpe.")
    return NormalDist().cdf(-sharpe * sqrt(k / 252))


def first_day(sharpe=8, two_sided=False):
    """First integer horizon at which zero P&L rejects at the 5% level."""
    if sharpe <= 0:
        raise ValueError("Use a positive annualized Sharpe.")
    lower_tail = 0.025 if two_sided else 0.05
    critical = NormalDist().inv_cdf(1 - lower_tail)
    return ceil(252 * (critical / sharpe) ** 2)


if __name__ == "__main__":
    for k in (10, 11, 15, 16):
        p = flat_probability(k)
        print(f"k={k:2d}: lower-tail p={p:.6f}, two-sided p={2 * p:.6f}")
    print(f"Sharpe 8: one-sided={first_day()} days, "
          f"two-sided={first_day(two_sided=True)} days")
    print(f"Sharpe 1: one-sided={first_day(1)} days")
