{"spec_id":"histogram-returns-distribution","library":"highcharts","language":"javascript","code":"// anyplot.ai\n// histogram-returns-distribution: Returns Distribution Histogram\n// Library: highcharts 12.6.0 | JavaScript 22.23.2\n// Quality: 92/100 | Created: 2026-09-02\n\nconst t = window.ANYPLOT_TOKENS;\n\n// --- Data (in-memory, deterministic LCG) ------------------------------------\nfunction makeLcg(seed) {\n  let state = seed >>> 0;\n  return function () {\n    state = (Math.imul(1103515245, state) + 12345) >>> 0;\n    return state / 4294967296;\n  };\n}\nconst rand = makeLcg(20260215);\n\n// Small math helpers (LCG sampler + normal PDF) are kept top-level since they\n// are pure functions reused by both the data generation and the fitted-curve\n// section below — inlining them would duplicate the Box-Muller/PDF formulas.\nfunction randNormal() {\n  const u1 = Math.max(rand(), 1e-9);\n  const u2 = rand();\n  return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n}\n\nconst nObs = 252; // one trading year of daily returns\nconst muDaily = 0.04; // % drift\nconst sigmaDaily = 1.1; // % daily vol\nconst returns = [];\nfor (let i = 0; i < nObs; i++) {\n  let z = randNormal();\n  if (i % 23 === 0) z -= 1.8; // rare drawdown days -> negative skew, fat left tail\n  if (i % 41 === 0) z += 1.3; // rare rally days\n  returns.push(muDaily + sigmaDaily * z);\n}\n\n// --- Sample statistics --------------------------------------------------\nconst mean = returns.reduce((a, b) => a + b, 0) / nObs;\nconst m2 = returns.reduce((a, b) => a + (b - mean) ** 2, 0) / nObs;\nconst std = Math.sqrt((returns.reduce((a, b) => a + (b - mean) ** 2, 0)) / (nObs - 1));\nconst m3 = returns.reduce((a, b) => a + (b - mean) ** 3, 0) / nObs;\nconst m4 = returns.reduce((a, b) => a + (b - mean) ** 4, 0) / nObs;\nconst skewness = m3 / Math.pow(m2, 1.5);\nconst kurtosis = m4 / (m2 * m2) - 3; // excess kurtosis\n\n// --- Histogram (density-normalized) --------------------------------------\nconst binCount = 30;\nconst minR = Math.min(...returns);\nconst maxR = Math.max(...returns);\nconst binWidth = (maxR - minR) / binCount;\nconst counts = new Array(binCount).fill(0);\nreturns.forEach((r) => {\n  let idx = Math.floor((r - minR) / binWidth);\n  if (idx >= binCount) idx = binCount - 1;\n  if (idx < 0) idx = 0;\n  counts[idx]++;\n});\nconst density = counts.map((c) => c / (nObs * binWidth));\nconst binCenters = density.map((_, i) => minR + (i + 0.5) * binWidth);\n\nconst tailLo = mean - 2 * std;\nconst tailHi = mean + 2 * std;\nconst bodyData = [];\nconst tailData = [];\nbinCenters.forEach((c, i) => {\n  if (c < tailLo || c > tailHi) {\n    tailData.push({ x: c, y: density[i] });\n    bodyData.push({ x: c, y: null });\n  } else {\n    bodyData.push({ x: c, y: density[i] });\n    tailData.push({ x: c, y: null });\n  }\n});\n\n// --- Fitted normal distribution curve ------------------------------------\nfunction normalPdf(x, mu, sigma) {\n  return Math.exp(-0.5 * ((x - mu) / sigma) ** 2) / (sigma * Math.sqrt(2 * Math.PI));\n}\nconst curvePoints = 100;\nconst curveData = [];\nfor (let i = 0; i <= curvePoints; i++) {\n  const x = minR + (i / curvePoints) * (maxR - minR);\n  curveData.push([x, normalPdf(x, mean, std)]);\n}\n\n// --- Chart -------------------------------------------------------------\nconst title = \"histogram-returns-distribution · javascript · highcharts · anyplot.ai\";\nconst tailSide = skewness < 0 ? \"left\" : \"right\";\nconst subtitle =\n  \"Skews \" + (skewness < 0 ? \"negative\" : \"positive\") + \" (skew \" + skewness.toFixed(2) +\n  \") — fat \" + tailSide + \" tail beyond ±2σ is the story here\";\n\nHighcharts.chart(\"container\", {\n  chart: {\n    type: \"column\",\n    backgroundColor: \"transparent\",\n    animation: false,\n    style: { fontFamily: \"inherit\" },\n    events: {\n      load: function () {\n        const chart = this;\n        const row = (label, value, valueColor) =>\n          '<div style=\"display:flex;justify-content:space-between;gap:18px;\">' +\n          '<span style=\"color:' + t.inkSoft + ';\">' + label + \"</span>\" +\n          '<b style=\"color:' + (valueColor || t.ink) + ';\">' + value + \"</b></div>\";\n        const statsText =\n          '<div style=\"font-weight:700;font-size:12px;letter-spacing:0.06em;' +\n          'text-transform:uppercase;color:' + t.ink + ';margin-bottom:6px;\">Statistics</div>' +\n          row(\"Mean\", mean.toFixed(2) + \"%\") +\n          row(\"Std Dev\", std.toFixed(2) + \"%\") +\n          row(\"Skewness\", skewness.toFixed(2), t.amber) +\n          row(\"Kurtosis\", kurtosis.toFixed(2));\n        chart.renderer\n          .label(statsText, chart.plotLeft + 12, chart.plotTop + 10, undefined, undefined, undefined, true)\n          .css({ color: t.inkSoft, fontSize: \"14px\", lineHeight: \"20px\" })\n          .attr({\n            fill: t.elevatedBg,\n            stroke: t.inkSoft,\n            \"stroke-width\": 1,\n            padding: 12,\n            r: 6,\n            zIndex: 5,\n            shadow: { color: \"#000000\", offsetX: 0, offsetY: 2, opacity: 0.18, width: 6 },\n          })\n          .add();\n      },\n    },\n  },\n  credits: { enabled: false },\n  colors: t.palette,\n  title: { text: title, style: { color: t.ink, fontSize: \"21px\", fontWeight: \"600\" } },\n  subtitle: { text: subtitle, style: { color: t.inkSoft, fontSize: \"14px\" } },\n  xAxis: {\n    title: { text: \"Daily Return (%)\", style: { color: t.inkSoft, fontSize: \"16px\" } },\n    lineColor: t.inkSoft,\n    tickColor: t.inkSoft,\n    gridLineColor: t.grid,\n    labels: { style: { color: t.inkSoft, fontSize: \"14px\" }, format: \"{value:.1f}%\" },\n    plotLines: [\n      {\n        value: tailLo,\n        color: t.inkSoft,\n        dashStyle: \"ShortDash\",\n        width: 1,\n        label: { text: \"-2σ\", style: { color: t.inkSoft, fontSize: \"14px\" }, y: -6 },\n      },\n      {\n        value: tailHi,\n        color: t.inkSoft,\n        dashStyle: \"ShortDash\",\n        width: 1,\n        label: { text: \"+2σ\", style: { color: t.inkSoft, fontSize: \"14px\" }, y: -6 },\n      },\n    ],\n  },\n  yAxis: {\n    title: { text: \"Density\", style: { color: t.inkSoft, fontSize: \"16px\" } },\n    gridLineColor: t.grid,\n    labels: { style: { color: t.inkSoft, fontSize: \"14px\" } },\n  },\n  legend: {\n    itemStyle: { color: t.inkSoft, fontSize: \"14px\" },\n    itemHoverStyle: { color: t.ink },\n  },\n  plotOptions: {\n    column: {\n      pointPadding: 0,\n      groupPadding: 0,\n      grouping: false,\n      borderWidth: 1,\n      borderColor: t.pageBg,\n      pointRange: binWidth,\n      animation: false,\n    },\n    series: { animation: false },\n  },\n  series: [\n    { name: \"Within ±2σ\", type: \"column\", data: bodyData, color: t.palette[0] },\n    {\n      name: \"Beyond ±2σ (tail)\",\n      type: \"column\",\n      data: tailData,\n      color: {\n        linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },\n        stops: [\n          [0, t.amber],\n          [1, Highcharts.color(t.amber).setOpacity(0.55).get(\"rgba\")],\n        ],\n      },\n    },\n    {\n      name: \"Normal Distribution\",\n      type: \"spline\",\n      data: curveData,\n      color: t.ink,\n      dashStyle: \"ShortDash\",\n      lineWidth: 2.5,\n      marker: { enabled: false },\n    },\n  ],\n});\n"}