"""0000: SPY daily return histogram with normal overlay (live data, issue #6).

Snapshot values cited in lesson 0000 (as of 2026-08-20): mean 0.063%/day,
std 1.132%/day, 2511 trading days (2016-08-20 to 2026-08-20).
"""
import sys

import matplotlib.pyplot as plt
import numpy as np

sys.path.insert(0, ".")
import course_style as cs

cs.apply_style()

import yfinance as yf

df = yf.download("SPY", start="2016-08-20", end="2026-08-20", interval="1d", auto_adjust=True)
px = df["Close"].iloc[:, 0].dropna()
r = px.pct_change().dropna() * 100  # percent

mu, sd = r.mean(), r.std(ddof=1)

fig, ax = plt.subplots(figsize=(5, 3.3))
ax.hist(r, bins=60, color=cs.PRIMARY, alpha=0.75, edgecolor="none", density=True)

x = np.linspace(r.min(), r.max(), 400)
y = (1 / (sd * np.sqrt(2 * np.pi))) * np.exp(-0.5 * ((x - mu) / sd) ** 2)
ax.plot(x, y, color=cs.CONTRAST, linewidth=2, label="Normal fit")

ax.set_title("SPY daily returns, 10 years")
ax.set_xlabel("Daily return (percent)")
ax.set_ylabel("Density")
ax.axvline(mu, color=cs.TICK, linewidth=1, linestyle="--")
ax.annotate(
    f"mean {mu:.3f}%",
    xy=(mu, ax.get_ylim()[1] * 0.95),
    xytext=(mu + 0.4, ax.get_ylim()[1] * 0.88),
    fontfamily=cs.MONO[0],
    fontsize=8,
    color=cs.INK,
)
ax.text(
    0.98,
    0.97,
    f"std {sd:.3f}%  n = {len(r)}",
    transform=ax.transAxes,
    ha="right",
    va="top",
    fontfamily=cs.MONO[0],
    fontsize=8,
    color=cs.LABEL,
)
ax.legend(loc="upper left")
ax.grid(True, axis="y")
cs.save_fig(fig, "0000-return-histogram.png")
