"""Chapter 15: the alpha a five-stock portfolio needs to match an index fund.

Model
-----
Each stock's gross annual return is the index's gross return times an
independent multiplicative residual with mean one:

    G_i,t = G_M,t * X_i,t,     E[X_i,t] = 1

so every stock has a market beta of exactly 1 and the same arithmetic
expected return as the index. G_M,t is lognormal with arithmetic mean
1 + mu and standard deviation sigma_m. X_i,t is lognormal, sized so that the
stock's total arithmetic volatility is sigma; the residual variance in
arithmetic terms is then exactly sigma**2 - sigma_m**2. Residuals of
different stocks have log-correlation rho_eps.

The concentrated portfolio is n stocks, equal weight at the start, bought
and held for `years` years with no rebalancing. The index is bought and held
for the same period.

Break-even alpha is the constant annual arithmetic excess return per stock
at which the concentrated portfolio's CRRA certainty-equivalent terminal
wealth equals the index's. Alpha enters as a proportional boost to every
annual gross return, (1 + mu + alpha) / (1 + mu), so each stock's arithmetic
mean rises by exactly alpha. Because CRRA certainty equivalents are
homogeneous of degree one, the boost scales the certainty equivalent by
((1 + mu + alpha) / (1 + mu)) ** years and the break-even alpha has a closed
form given the simulated certainty equivalents. No root-finding is needed.

Shortcut used for speed (exact, not an approximation): with buy-and-hold and
i.i.d. lognormal annual returns, each stock's terminal wealth depends only on
the sum of its annual log returns, which is normal. `simulate` draws that sum
directly. `simulate_annual` steps year by year and exists only so the tests
can confirm the two agree.

Run:  python3 scripts/book-models/concentration.py
Writes scripts/book-models/out/concentration.md
"""

from __future__ import annotations

import math
from dataclasses import dataclass
from pathlib import Path

import numpy as np

OUT = Path(__file__).resolve().parent / "out"

# Base calibration used in chapter 16 and the appendix.
BASE = {
    "n": 5,
    "sigma": 0.40,  # total volatility of one stock
    "sigma_m": 0.16,  # index volatility
    "rho_eps": 0.0,  # correlation among residuals
    "mu": 0.06,  # arithmetic real expected return, index and every stock
    "years": 20,
    "paths": 200_000,
    "seed": 16,
}
GAMMAS = (1, 2, 3)
SIGMAS = (0.30, 0.40, 0.50)
RHOS = (0.0, 0.1, 0.2)


@dataclass
class Draws:
    """Terminal wealth per path at zero alpha (index and concentrated)."""

    w_index: np.ndarray
    w_conc: np.ndarray
    mu: float
    years: int


def _lognormal(mean_gross: float, sd: float) -> tuple[float, float]:
    """Return (m, s) of log G for a lognormal with the given mean and sd."""
    s2 = math.log(1.0 + (sd / mean_gross) ** 2)
    return math.log(mean_gross) - s2 / 2.0, math.sqrt(s2)


def residual_log_sd(sigma: float, sigma_m: float, mu: float) -> float:
    """Log-sd of the multiplicative residual giving total arithmetic vol sigma."""
    if sigma < sigma_m:
        raise ValueError("stock volatility below index volatility")
    a = (1.0 + mu) ** 2
    return math.sqrt(math.log((a + sigma**2) / (a + sigma_m**2)))


def simulate(
    n: int = BASE["n"],
    sigma: float = BASE["sigma"],
    sigma_m: float = BASE["sigma_m"],
    rho_eps: float = BASE["rho_eps"],
    mu: float = BASE["mu"],
    years: int = BASE["years"],
    paths: int = BASE["paths"],
    seed: int = BASE["seed"],
) -> Draws:
    """Terminal wealth of $1 in the index and in the n-stock portfolio."""
    rng = np.random.default_rng(seed)
    z_m = rng.standard_normal(paths)
    z_c = rng.standard_normal(paths)
    z_i = rng.standard_normal((paths, n))
    m_m, s_m = _lognormal(1.0 + mu, sigma_m)
    s_e = residual_log_sd(sigma, sigma_m, mu)
    rt = math.sqrt(years)
    log_wm = years * m_m + s_m * rt * z_m
    z = math.sqrt(rho_eps) * z_c[:, None] + math.sqrt(1.0 - rho_eps) * z_i
    log_x = -years * s_e**2 / 2.0 + s_e * rt * z
    w_m = np.exp(log_wm)
    w_c = w_m * np.exp(log_x).mean(axis=1)
    return Draws(w_m, w_c, mu, years)


def simulate_annual(
    n: int = BASE["n"],
    sigma: float = BASE["sigma"],
    sigma_m: float = BASE["sigma_m"],
    rho_eps: float = BASE["rho_eps"],
    mu: float = BASE["mu"],
    years: int = BASE["years"],
    paths: int = 20_000,
    seed: int = 1,
) -> Draws:
    """Same model stepped year by year (slow; used to check `simulate`)."""
    rng = np.random.default_rng(seed)
    m_m, s_m = _lognormal(1.0 + mu, sigma_m)
    s_e = residual_log_sd(sigma, sigma_m, mu)
    w_m = np.ones(paths)
    stock = np.ones((paths, n))
    for _ in range(years):
        g_m = np.exp(m_m + s_m * rng.standard_normal(paths))
        z = math.sqrt(rho_eps) * rng.standard_normal(paths)[:, None] + math.sqrt(
            1.0 - rho_eps
        ) * rng.standard_normal((paths, n))
        x = np.exp(-(s_e**2) / 2.0 + s_e * z)
        w_m *= g_m
        stock *= g_m[:, None] * x
    return Draws(w_m, stock.mean(axis=1), mu, years)


def certainty_equivalent(w: np.ndarray, gamma: float) -> float:
    """CRRA certainty-equivalent wealth, computed in logs for stability."""
    lw = np.log(w)
    if gamma == 1:
        return float(math.exp(lw.mean()))
    e = (1.0 - gamma) * lw
    mx = e.max()
    log_mean = mx + math.log(np.exp(e - mx).mean())
    return float(math.exp(log_mean / (1.0 - gamma)))


def break_even_alpha(d: Draws, gamma: float) -> float:
    """Annual arithmetic alpha per stock that equates certainty equivalents."""
    ratio = certainty_equivalent(d.w_index, gamma) / certainty_equivalent(
        d.w_conc, gamma
    )
    return (1.0 + d.mu) * (ratio ** (1.0 / d.years) - 1.0)


def trail_share(d: Draws) -> float:
    """Share of paths in which the concentrated portfolio ends below the index."""
    return float((d.w_conc < d.w_index).mean())


def closed_form(
    gamma: float,
    n: int = BASE["n"],
    sigma: float = BASE["sigma"],
    sigma_m: float = BASE["sigma_m"],
    rho_eps: float = 0.0,
) -> float:
    """One-period mean-variance hurdle: gamma/2 * residual variance of the portfolio.

    Residual variance of an equal-weight portfolio is
    sigma_eps**2 * (HHI + rho * (1 - HHI)), HHI = 1/n. This is what a
    continuously rebalanced portfolio would need; buy-and-hold lets weights
    drift toward the winners, so the simulated hurdle is higher.
    """
    hhi = 1.0 / n
    return gamma / 2.0 * (sigma**2 - sigma_m**2) * (hhi + rho_eps * (1.0 - hhi))


def portfolio_vol(n: int, sigma: float, sigma_m: float, rho_eps: float = 0.0) -> float:
    """Single-period volatility of an equal-weight n-stock portfolio."""
    hhi = 1.0 / n
    resid = (sigma**2 - sigma_m**2) * (hhi + rho_eps * (1.0 - hhi))
    return math.sqrt(sigma_m**2 + resid)


def batch_se(gamma: float, batches: int = 10, **kw) -> float:
    """Standard error of the hurdle from independent batches of the base run."""
    paths = kw.pop("paths", BASE["paths"]) // batches
    vals = [
        break_even_alpha(simulate(paths=paths, seed=1000 + b, **kw), gamma)
        for b in range(batches)
    ]
    return float(np.std(vals, ddof=1) / math.sqrt(batches))


def pct(x: float, nd: int = 1) -> str:
    return f"{100 * x:.{nd}f}"


def build_report() -> str:
    b = BASE
    lines = [
        "# Chapter 15 model: break-even alpha for a concentrated portfolio",
        "",
        "Generated by `scripts/book-models/concentration.py`. Do not edit by hand.",
        "",
        "Inputs: n = {n} stocks, equal weight, buy and hold, no rebalancing; "
        "beta 1; index volatility {sm}%; arithmetic real expected return "
        "{mu}% a year for the index and every stock; lognormal annual returns; "
        "{T} years; {P:,} paths; seed {seed}.".format(
            n=b["n"],
            sm=pct(b["sigma_m"], 0),
            mu=pct(b["mu"], 0),
            T=b["years"],
            P=b["paths"],
            seed=b["seed"],
        ),
        "",
        "Break-even alpha is in percentage points a year per stock. "
        "`closed form` is gamma/2 x residual variance x (HHI + rho(1 - HHI)), "
        "the continuously rebalanced one-period value.",
        "",
        "## Break-even alpha by stock volatility, residual correlation and gamma",
        "",
        "| stock vol | rho_eps | gamma 1 | gamma 2 | gamma 3 | closed form "
        "g=1/2/3 | share of paths trailing at zero alpha |",
        "|---:|---:|---:|---:|---:|:---:|---:|",
    ]
    grid = {}
    for s in SIGMAS:
        for r in RHOS:
            d = simulate(sigma=s, rho_eps=r)
            h = [break_even_alpha(d, g) for g in GAMMAS]
            cf = [closed_form(g, sigma=s, rho_eps=r) for g in GAMMAS]
            grid[(s, r)] = (h, trail_share(d))
            lines.append(
                f"| {pct(s, 0)}% | {r:.1f} | {pct(h[0])} | {pct(h[1])} | "
                f"{pct(h[2])} | {pct(cf[0])} / {pct(cf[1])} / {pct(cf[2])} | "
                f"{trail_share(d):.2f} |"
            )
    lines += [
        "",
        "## Monte Carlo standard error, base case (10 batches of 20,000 paths)",
        "",
        "| gamma | hurdle | standard error |",
        "|---:|---:|---:|",
    ]
    for g in GAMMAS:
        h = grid[(b["sigma"], 0.0)][0][g - 1]
        lines.append(f"| {g} | {pct(h, 2)} | {pct(batch_se(g), 2)} |")

    lines += [
        "",
        "## Number of stocks (stock vol 40%, rho_eps 0)",
        "",
        "| n | one-period portfolio vol | gamma 2 | gamma 3 | closed form "
        "gamma 2 / 3 | trailing share |",
        "|---:|---:|---:|---:|:---:|---:|",
    ]
    for n in (1, 5, 10, 30, 500):
        paths = b["paths"] if n <= 30 else 20_000
        d = simulate(n=n, paths=paths)
        lines.append(
            f"| {n} | {pct(portfolio_vol(n, b['sigma'], b['sigma_m']))}% | "
            f"{pct(break_even_alpha(d, 2), 2)} | {pct(break_even_alpha(d, 3), 2)} | "
            f"{pct(closed_form(2, n=n), 2)} / {pct(closed_form(3, n=n), 2)} | "
            f"{trail_share(d):.2f} |"
        )

    lines += [
        "",
        "## Horizon and expected return (stock vol 40%, rho_eps 0, n = 5)",
        "",
        "| years | mu | gamma 2 | gamma 3 | trailing share |",
        "|---:|---:|---:|---:|---:|",
    ]
    for yrs, mu in ((10, 0.06), (20, 0.06), (30, 0.06), (20, 0.04), (20, 0.08)):
        d = simulate(years=yrs, mu=mu)
        lines.append(
            f"| {yrs} | {pct(mu, 0)}% | {pct(break_even_alpha(d, 2))} | "
            f"{pct(break_even_alpha(d, 3))} | {trail_share(d):.2f} |"
        )

    lines += [
        "",
        "## Single-period volatility table used in Chapter 15 (rho_eps 0)",
        "",
        "| portfolio | volatility |",
        "|:---|---:|",
    ]
    for n, label in (
        (1, "One stock"),
        (5, "Five stocks"),
        (10, "Ten stocks"),
        (30, "Thirty stocks"),
    ):
        lines.append(
            f"| {label} | {pct(portfolio_vol(n, b['sigma'], b['sigma_m']))}% |"
        )
    lines.append(f"| Broad market | {pct(b['sigma_m'])}% |")
    lines.append("")
    return "\n".join(lines)


def main() -> None:
    OUT.mkdir(exist_ok=True)
    report = build_report()
    (OUT / "concentration.md").write_text(report)
    print(report)


if __name__ == "__main__":
    main()
