"""Chapter 4: when does holding a low-basis employer-stock position break even?

The household compares two choices for a position worth $1 today:

* hold the position, or
* sell it now, pay capital-gains tax on the embedded gain, and put the
  after-tax proceeds in a diversified beta-1 portfolio.

Two quantities, both stated per dollar of the position and per year.

Volatility cost. The stock has beta 1, total volatility sigma and residual
variance sigma_eps**2 = sigma**2 - sigma_m**2. If the position is a share w of
household financial wealth F, and the household also holds non-financial human
capital H = h * F (total wealth W = (1 + h) * F), holding it adds
w**2 * sigma_eps**2 / (1 + h)**2 of diversifiable variance to total wealth.
With CRRA utility and lognormal returns, a constant-weight portfolio's
certainty-equivalent return is its mean less gamma/2 times its variance, so the
annual cost on total wealth (1 + h) * F is
gamma/2 * sigma_eps**2 * w**2 / (1 + h) of financial wealth, or
gamma/2 * sigma_eps**2 * w / (1 + h) per dollar of the position. With h = 0
(retired or financial-wealth-only benchmark), this simplifies to
gamma/2 * w * sigma_eps**2.

Paycheck exposure. If part of human capital also moves one-for-one with the
company's residual return, let phi be that exposed human capital as a share of
financial wealth F (with phi <= h when total human capital is h * F). Holding
the position raises company-specific exposure from phi to w + phi, so the extra
cost per dollar of the position is
gamma/2 * sigma_eps**2 * (w + 2 * phi) / (1 + h). When h > 0, safe or portable
human capital in the denominator (1 + h) dilutes portfolio risk even while
company-linked pay phi raises it in the numerator.

Deferral benefit. The value of not paying the tax today, expressed as the
annual pre-tax return the held position could give up and still leave the
household with the same after-tax wealth as selling, for two cases:

(a) liquidate: both the held position and the diversified portfolio are sold
    at the horizon and taxed;
(b) step-up: neither is sold; both pass at death at the horizon with a basis
    step-up, so no capital-gains tax is ever paid on the later growth or on
    the held position's embedded gain. Note that the annualized step-up benefit
    scales inversely with years to death: large over a 10-year late-life
    horizon (~1.49%/yr), much smaller over a 30-year (~0.50%/yr) or 40-year
    (~0.37%/yr) mid-career horizon.

Break-even annual alpha on the position = volatility cost - deferral benefit.
A negative hurdle means holding wins even with no expected outperformance.

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

from __future__ import annotations

from pathlib import Path

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

BASE = {
    "gain_share": 0.55,  # embedded gain as a share of market value
    "tax": 0.238,  # 20% federal long-term rate + 3.8% NIIT
    "years": 10,
    "r": 0.07,  # nominal expected return, stock and diversified portfolio
    "sigma": 0.33,  # stock volatility
    "sigma_m": 0.16,  # diversified portfolio (market) volatility
}
WEIGHTS = (0.10, 0.25, 0.50, 1.00)
GAMMAS = (1, 2, 3)
PHI_ILLUSTRATIVE = 0.20


def after_tax_values(
    gain_share: float = BASE["gain_share"],
    tax: float = BASE["tax"],
    years: int = BASE["years"],
    r: float = BASE["r"],
    case: str = "liquidate",
) -> tuple[float, float]:
    """After-tax wealth at the horizon from $1 today: (hold, sell now)."""
    growth = (1.0 + r) ** years
    basis = 1.0 - gain_share
    proceeds = 1.0 - tax * gain_share  # sell now, reinvest, basis = proceeds
    if case == "liquidate":
        hold = growth - tax * (growth - basis)
        sell = proceeds * (growth - tax * (growth - 1.0))
    elif case == "step_up":
        hold = growth
        sell = proceeds * growth
    else:
        raise ValueError(case)
    return hold, sell


def deferral_benefit(
    gain_share: float = BASE["gain_share"],
    tax: float = BASE["tax"],
    years: int = BASE["years"],
    r: float = BASE["r"],
    case: str = "liquidate",
) -> float:
    """Annual pre-tax return the held position can give up and still tie selling.

    Solves for delta in: after-tax value of holding, growing at r - delta,
    equals after-tax value of selling now and growing at r.
    """
    _, sell = after_tax_values(gain_share, tax, years, r, case)
    basis = 1.0 - gain_share
    growth_needed = (sell - tax * basis) / (1.0 - tax) if case == "liquidate" else sell
    return (1.0 + r) - growth_needed ** (1.0 / years)


def deferral_alternatives(**kw) -> dict[str, float]:
    """Other ways to annualize the same deferral, for comparison in the appendix."""
    case = kw.get("case", "liquidate")
    r = kw.get("r", BASE["r"])
    years = kw.get("years", BASE["years"])
    tax = kw.get("tax", BASE["tax"])
    g = kw.get("gain_share", BASE["gain_share"])
    hold, sell = after_tax_values(g, tax, years, r, case)
    ratio = (hold / sell) ** (1.0 / years) - 1.0
    # Extra pre-tax return the diversified portfolio would need to tie holding.
    proceeds = 1.0 - tax * g
    if case == "liquidate":
        grow = (hold / proceeds - tax) / (1.0 - tax)
    else:
        grow = hold / proceeds
    diversified_side = grow ** (1.0 / years) - (1.0 + r)
    return {
        "position_side": deferral_benefit(g, tax, years, r, case),
        "wealth_ratio": ratio,
        "diversified_side": diversified_side,
    }


def volatility_cost(
    w: float,
    gamma: float,
    sigma: float = BASE["sigma"],
    sigma_m: float = BASE["sigma_m"],
    phi: float = 0.0,
    h: float = 0.0,
) -> float:
    """Annual certainty-equivalent cost per dollar of the position.

    h is total human capital as a multiple of financial wealth F (so total
    wealth is (1 + h) * F). phi is the employer-linked slice of human capital
    as a multiple of F.
    """
    resid = sigma**2 - sigma_m**2
    return gamma / 2.0 * resid * (w + 2.0 * phi) / (1.0 + h)


def hold_hurdle(
    w: float,
    gamma: float,
    case: str = "liquidate",
    phi: float = 0.0,
    h: float = 0.0,
    sigma: float = BASE["sigma"],
    sigma_m: float = BASE["sigma_m"],
    **tax_kw,
) -> float:
    """Break-even annual alpha on the position for holding to tie selling."""
    return volatility_cost(w, gamma, sigma, sigma_m, phi, h) - deferral_benefit(
        case=case, **tax_kw
    )


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


def _table(
    case: str, phi: float, h: float = 0.0, years: int = BASE["years"]
) -> list[str]:
    rows = [
        "| position share of financial wealth | gamma 1 | gamma 2 | gamma 3 |",
        "|---:|---:|---:|---:|",
    ]
    for w in WEIGHTS:
        vals = [
            pct(hold_hurdle(w, g, case=case, phi=phi, h=h, years=years)) for g in GAMMAS
        ]
        rows.append(f"| {pct(w, 0)}% | " + " | ".join(vals) + " |")
    return rows


def build_report() -> str:
    b = BASE
    resid = b["sigma"] ** 2 - b["sigma_m"] ** 2
    lines = [
        "# Chapter 4 model: the hold hurdle for a low-basis position",
        "",
        "Generated by `scripts/book-models/hold_hurdle.py`. Do not edit by hand.",
        "",
        f"Inputs: embedded gain {pct(b['gain_share'], 0)}% of market value; "
        f"tax {pct(b['tax'])}% (20% federal + 3.8% NIIT); horizon {b['years']} "
        f"years (plus 30- and 40-year step-up horizons); expected return "
        f"{pct(b['r'], 0)}% nominal for the stock and the diversified "
        f"portfolio; stock volatility {pct(b['sigma'], 0)}%, beta 1; "
        f"diversified volatility {pct(b['sigma_m'], 0)}%; residual variance "
        f"{resid:.4f}.",
        "",
        "## Deferral benefit (percentage points a year)",
        "",
        "| case | used in hurdle: return the held position can give up | "
        "after-tax wealth ratio, annualized | extra return the diversified "
        "portfolio would need |",
        "|:---|---:|---:|---:|",
    ]
    for case, yrs, label in (
        ("liquidate", 10, "(a) both sold at year 10"),
        ("step_up", 10, "(b1) neither sold; step-up at death in year 10 (late life)"),
        ("step_up", 30, "(b2) neither sold; step-up at death in year 30 (mid-career)"),
        (
            "step_up",
            40,
            "(b3) neither sold; step-up at death in year 40 (early/mid-career)",
        ),
    ):
        alt = deferral_alternatives(case=case, years=yrs)
        lines.append(
            f"| {label} | {pct(alt['position_side'], 2)} | "
            f"{pct(alt['wealth_ratio'], 2)} | {pct(alt['diversified_side'], 2)} |"
        )
    lines += [
        "",
        "## Volatility cost per dollar of the position (points a year, h = 0)",
        "",
        "| position share | gamma 1 | gamma 2 | gamma 3 |",
        "|---:|---:|---:|---:|",
    ]
    for w in WEIGHTS:
        vals = [pct(volatility_cost(w, g)) for g in GAMMAS]
        lines.append(f"| {pct(w, 0)}% | " + " | ".join(vals) + " |")

    for case, yrs, label in (
        ("liquidate", 10, "(a) both positions sold at year 10"),
        ("step_up", 10, "(b1) held to death at year 10 (late life) with step-up"),
        ("step_up", 30, "(b2) held to death at year 30 (mid-career) with step-up"),
    ):
        lines += [
            "",
            f"## Break-even alpha, {label}, financial wealth only (phi = 0, h = 0)",
            "",
        ]
        lines += _table(case, phi=0.0, h=0.0, years=yrs)

    for h_val, h_desc in (
        (1.0, "total wealth W = 2F (h = 1.0, mid-career)"),
        (2.0, "total wealth W = 3F (h = 2.0, earlier career)"),
        (0.0, "financial wealth denominator only (h = 0.0, retired/upper bound)"),
    ):
        lines += [
            "",
            f"## Break-even alpha, (a) sold at year 10, paycheck exposure phi = {PHI_ILLUSTRATIVE:.2f}, {h_desc}",
            "",
        ]
        lines += _table("liquidate", phi=PHI_ILLUSTRATIVE, h=h_val, years=10)

    lines += [
        "",
        f"phi = {PHI_ILLUSTRATIVE:.2f} is illustrative, not estimated: a "
        "company-specific fall that halves the share price also cuts the present "
        "value of future pay by an amount equal to 10% of financial wealth. "
        "Dividing by (1 + h) accounts for total wealth W = F + H.",
        "",
        "## Sensitivity: case (a), position 25% of wealth, gamma 2, phi 0, h 0",
        "",
        "| change | deferral benefit | hurdle |",
        "|:---|---:|---:|",
    ]
    base_h = hold_hurdle(0.25, 2)
    lines.append(f"| base | {pct(deferral_benefit(), 2)} | {pct(base_h, 2)} |")
    for label, kw, vol in (
        ("embedded gain 25%", {"gain_share": 0.25}, b["sigma"]),
        ("embedded gain 85%", {"gain_share": 0.85}, b["sigma"]),
        ("horizon 5 years", {"years": 5}, b["sigma"]),
        ("horizon 20 years", {"years": 20}, b["sigma"]),
        ("tax 15%", {"tax": 0.15}, b["sigma"]),
        ("stock vol 25%", {}, 0.25),
        ("stock vol 40%", {}, 0.40),
    ):
        h = hold_hurdle(0.25, 2, sigma=vol, **kw)
        lines.append(f"| {label} | {pct(deferral_benefit(**kw), 2)} | {pct(h, 2)} |")
    lines.append("")
    return "\n".join(lines)


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


if __name__ == "__main__":
    main()
