{"spec_id":"histogram-returns-distribution","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\nhistogram-returns-distribution: Returns Distribution Histogram\nLibrary: matplotlib 3.10.9 | Python 3.13.13\nQuality: 90/100 | Updated: 2026-05-20\n\"\"\"\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Patch\nfrom scipy import stats\n\n\n# Theme tokens\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nELEVATED_BG = \"#FFFDF6\" if THEME == \"light\" else \"#242420\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\nINK_MUTED = \"#6B6A63\" if THEME == \"light\" else \"#A8A79F\"\n\nBRAND = \"#009E73\"  # Okabe-Ito pos 1 — main histogram bars\nTAIL_COLOR = \"#C475FD\"  # Okabe-Ito pos 2 — tail regions\nCURVE_COLOR = \"#4467A3\"  # Okabe-Ito pos 3 — normal distribution curve\n\n# Data — simulate daily stock returns with slight fat tails (t-distribution df=8)\nnp.random.seed(42)\nn_days = 252\nreturns = np.random.standard_t(df=8, size=n_days) * 0.012 + 0.0004  # ~1.2% daily vol\n\n# Key statistics\nmean_ret = np.mean(returns) * 100\nstd_ret = np.std(returns) * 100\nskewness = stats.skew(returns)\nkurtosis = stats.kurtosis(returns)\nreturns_pct = returns * 100\n\n# Tail thresholds (±2σ) and observation counts\nlower_tail = mean_ret - 2 * std_ret\nupper_tail = mean_ret + 2 * std_ret\nn_left = int(np.sum(returns_pct < lower_tail))\nn_right = int(np.sum(returns_pct > upper_tail))\nn_tail = n_left + n_right\ntail_pct = n_tail / n_days * 100\nexpected_tail_pct = (1 - stats.norm.cdf(2)) * 2 * 100  # ≈ 4.55% beyond ±2σ under normality\n\n# Normal distribution overlay range\nx_lo = returns_pct.min() - 0.5\nx_hi = returns_pct.max() + 0.5\nx_range = np.linspace(x_lo, x_hi, 300)\nnormal_pdf = stats.norm.pdf(x_range, mean_ret, std_ret)\n\n# Plot\nfig, ax = plt.subplots(figsize=(8, 4.5), dpi=400, facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\n# Histogram with density normalization\nn, bins, patches = ax.hist(\n    returns_pct, bins=35, density=True, color=BRAND, alpha=0.75, edgecolor=PAGE_BG, linewidth=0.8\n)\n\n# Color tail bins with distinct Okabe-Ito highlight\nfor i, patch in enumerate(patches):\n    bin_center = (bins[i] + bins[i + 1]) / 2\n    if bin_center < lower_tail or bin_center > upper_tail:\n        patch.set_facecolor(TAIL_COLOR)\n        patch.set_alpha(0.90)\n\n# Subtle axvspan background tinting for tail risk zones (below histogram bars)\nax.axvspan(x_lo, lower_tail, alpha=0.07, color=TAIL_COLOR, zorder=0)\nax.axvspan(upper_tail, x_hi, alpha=0.07, color=TAIL_COLOR, zorder=0)\n\n# Shade theoretical tail areas under the normal curve (fill_between)\nx_left = np.linspace(x_lo, lower_tail, 150)\nx_right = np.linspace(upper_tail, x_hi, 150)\nax.fill_between(x_left, stats.norm.pdf(x_left, mean_ret, std_ret), color=TAIL_COLOR, alpha=0.15)\nax.fill_between(x_right, stats.norm.pdf(x_right, mean_ret, std_ret), color=TAIL_COLOR, alpha=0.15)\n\n# Normal distribution overlay curve\n(normal_line,) = ax.plot(x_range, normal_pdf, color=CURVE_COLOR, linewidth=2.5, linestyle=\"--\", label=\"Normal fit\")\n\n# Vertical reference lines\nax.axvline(mean_ret, color=INK, linewidth=1.8, linestyle=\"-\", alpha=0.8, label=f\"Mean ({mean_ret:.3f}%)\")\nax.axvline(lower_tail, color=INK_MUTED, linewidth=1.5, linestyle=\":\", alpha=0.7)\nax.axvline(upper_tail, color=INK_MUTED, linewidth=1.5, linestyle=\":\", alpha=0.7)\n\n# Tail annotations with observation counts — fontsize=8 for mobile legibility\nax.annotate(\n    f\"Left tail\\n{n_left} obs ({n_left / n_days * 100:.1f}%)\",\n    xy=(lower_tail - 0.6, 0.02),\n    fontsize=8,\n    ha=\"center\",\n    color=INK_MUTED,\n)\nax.annotate(\n    f\"Right tail\\n{n_right} obs ({n_right / n_days * 100:.1f}%)\",\n    xy=(upper_tail + 0.7, 0.02),\n    fontsize=8,\n    ha=\"center\",\n    color=INK_MUTED,\n)\n\n# Statistics text box — includes actual vs expected tail % for fat-tail emphasis\nstats_text = (\n    f\"Mean:      {mean_ret:.3f}%\\n\"\n    f\"Std Dev:   {std_ret:.3f}%\\n\"\n    f\"Skewness: {skewness:.3f}\\n\"\n    f\"Kurtosis:  {kurtosis:.3f}\\n\"\n    f\"Fat tails: {tail_pct:.1f}% (norm: {expected_tail_pct:.1f}%)\"\n)\nax.text(\n    0.97,\n    0.97,\n    stats_text,\n    transform=ax.transAxes,\n    fontsize=8,\n    verticalalignment=\"top\",\n    horizontalalignment=\"right\",\n    family=\"monospace\",\n    color=INK,\n    bbox={\"boxstyle\": \"round,pad=0.5\", \"facecolor\": ELEVATED_BG, \"edgecolor\": INK_SOFT, \"alpha\": 0.9},\n)\n\n# Style\nax.set_xlabel(\"Daily Returns (%)\", fontsize=10, color=INK)\nax.set_ylabel(\"Density\", fontsize=10, color=INK)\nax.set_title(\n    \"histogram-returns-distribution · python · matplotlib · anyplot.ai\", fontsize=12, fontweight=\"medium\", color=INK\n)\nax.tick_params(axis=\"both\", labelsize=8, colors=INK_SOFT, labelcolor=INK_SOFT)\n\n# Spines\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nfor spine in (\"left\", \"bottom\"):\n    ax.spines[spine].set_color(INK_SOFT)\n\n# Grid (subtle, solid, y-axis only)\nax.set_axisbelow(True)\nax.yaxis.grid(True, alpha=0.12, linewidth=0.8, color=INK)\n\n# Legend with correct patch colors\nhist_patch = Patch(facecolor=BRAND, edgecolor=PAGE_BG, alpha=0.75, label=\"Returns\")\ntail_patch = Patch(facecolor=TAIL_COLOR, edgecolor=PAGE_BG, alpha=0.90, label=\"Tail Regions (>2σ)\")\nhandles, _ = ax.get_legend_handles_labels()\nleg = ax.legend(handles=[hist_patch, tail_patch] + handles, fontsize=8, loc=\"upper left\")\nleg.get_frame().set_facecolor(ELEVATED_BG)\nleg.get_frame().set_edgecolor(INK_SOFT)\nplt.setp(leg.get_texts(), color=INK_SOFT)\n\n# Layout — no bbox_inches='tight' on savefig per prompts/library/matplotlib.md\nfig.subplots_adjust(left=0.08, right=0.97, top=0.92, bottom=0.12)\n\n# Save\nplt.savefig(f\"plot-{THEME}.png\", dpi=400, facecolor=PAGE_BG)\nplt.close()\n"}