{"spec_id":"histogram-returns-distribution","library":"muix","language":"javascript","code":"// anyplot.ai\n// histogram-returns-distribution: Returns Distribution Histogram\n// Library: muix 7.29.1 | JavaScript 22.23.2\n// Quality: 93/100 | Created: 2026-09-02\nimport { ChartContainer } from \"@mui/x-charts/ChartContainer\";\nimport { BarPlot } from \"@mui/x-charts/BarChart\";\nimport { LinePlot } from \"@mui/x-charts/LineChart\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { ChartsTooltip } from \"@mui/x-charts/ChartsTooltip\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// --- Data: one trading year of daily returns (fixed-seed LCG, deterministic) -\nlet seed = 42;\nfunction rand() {\n  seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n  return seed / 0x7fffffff;\n}\nfunction randNormal() {\n  const u1 = Math.max(rand(), 1e-12);\n  const u2 = rand();\n  return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n}\n\nconst N_DAYS = 252;\nconst DAILY_VOL = 1.15; // percent\nconst DRIFT = 0.04; // percent, slight positive drift\nconst dailyReturns = [];\nfor (let i = 0; i < N_DAYS; i += 1) {\n  let r = DRIFT + randNormal() * DAILY_VOL;\n  // Occasional volatility shock days give the distribution a fat, negatively\n  // skewed left tail — the \"crash risk\" pattern real equity returns show.\n  if (rand() < 0.06) {\n    r -= Math.abs(randNormal()) * DAILY_VOL * 2.2;\n  }\n  dailyReturns.push(r);\n}\n\nconst n = dailyReturns.length;\nconst mean = dailyReturns.reduce((a, b) => a + b, 0) / n;\nconst variance = dailyReturns.reduce((a, b) => a + (b - mean) ** 2, 0) / n;\nconst std = Math.sqrt(variance);\nconst skewness = dailyReturns.reduce((a, b) => a + ((b - mean) / std) ** 3, 0) / n;\nconst excessKurtosis =\n  dailyReturns.reduce((a, b) => a + ((b - mean) / std) ** 4, 0) / n - 3;\n\n// --- Histogram bins, density-normalized so the normal curve is comparable ---\nconst BIN_COUNT = 26;\nconst minReturn = Math.min(...dailyReturns);\nconst maxReturn = Math.max(...dailyReturns);\nconst binWidth = (maxReturn - minReturn) / BIN_COUNT;\nconst binCounts = new Array(BIN_COUNT).fill(0);\ndailyReturns.forEach((r) => {\n  const idx = Math.min(BIN_COUNT - 1, Math.max(0, Math.floor((r - minReturn) / binWidth)));\n  binCounts[idx] += 1;\n});\nconst binCenters = binCounts.map((_, i) => minReturn + binWidth * (i + 0.5));\nconst density = binCounts.map((c) => c / (n * binWidth));\n\nfunction normalPdf(x, mu, sigma) {\n  return Math.exp(-0.5 * ((x - mu) / sigma) ** 2) / (sigma * Math.sqrt(2 * Math.PI));\n}\nconst normalCurve = binCenters.map((c) => normalPdf(c, mean, std));\n\n// Tail regions beyond +/-2 standard deviations get a distinct color. Both bar\n// series are stacked so, per bin, only the applicable one contributes height —\n// this renders as a single two-tone histogram rather than grouped bars.\nconst lowerTail = mean - 2 * std;\nconst upperTail = mean + 2 * std;\nconst coreDensity = density.map((d, i) => (binCenters[i] < lowerTail || binCenters[i] > upperTail ? 0 : d));\nconst tailDensity = density.map((d, i) => (binCenters[i] < lowerTail || binCenters[i] > upperTail ? d : 0));\n\n// Band scale reference lines need an exact category value, so snap to the bin\n// center closest to the mean.\nconst meanBinCenter = binCenters.reduce((closest, c) =>\n  Math.abs(c - mean) < Math.abs(closest - mean) ? c : closest\n);\n\nconst pct = (v) => `${v.toFixed(1)}%`;\n\n// --- Chart (default-exported component — the harness mounts it) -------------\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const titleHeight = 56;\n  const chartHeight = height - titleHeight;\n\n  return (\n    <div style={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <div\n        style={{\n          height: titleHeight,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          fontSize: 22,\n          fontWeight: 600,\n          color: t.ink,\n        }}\n      >\n        histogram-returns-distribution · javascript · muix · anyplot.ai\n      </div>\n\n      <div style={{ position: \"relative\", width, height: chartHeight }}>\n        <ChartContainer\n          width={width}\n          height={chartHeight}\n          margin={{ top: 90, right: 40, bottom: 70, left: 90 }}\n          series={[\n            {\n              type: \"bar\",\n              data: coreDensity,\n              stack: \"bins\",\n              color: t.palette[0],\n              label: \"Within ±2σ\",\n              valueFormatter: (v) => (v ? v.toFixed(3) : null),\n            },\n            {\n              type: \"bar\",\n              data: tailDensity,\n              stack: \"bins\",\n              color: t.amber,\n              label: \"Beyond ±2σ (tail)\",\n              valueFormatter: (v) => (v ? v.toFixed(3) : null),\n            },\n            {\n              type: \"line\",\n              data: normalCurve,\n              color: t.ink,\n              label: \"Normal fit\",\n              showMark: false,\n              curve: \"natural\",\n              valueFormatter: (v) => v.toFixed(3),\n            },\n          ]}\n          xAxis={[\n            {\n              scaleType: \"band\",\n              data: binCenters,\n              categoryGapRatio: 0.05,\n              valueFormatter: pct,\n              label: \"Daily Return (%)\",\n              labelStyle: { fill: t.ink, fontSize: 16 },\n              tickLabelStyle: { fill: t.inkSoft, fontSize: 14 },\n              tickLabelInterval: (_, i) => i % 3 === 0,\n            },\n          ]}\n          yAxis={[\n            {\n              label: \"Density\",\n              labelStyle: { fill: t.ink, fontSize: 16 },\n              tickLabelStyle: { fill: t.inkSoft, fontSize: 14 },\n              valueFormatter: (v) => v.toFixed(2),\n            },\n          ]}\n        >\n          <ChartsGrid horizontal />\n          <BarPlot skipAnimation borderRadius={2} />\n          <LinePlot skipAnimation />\n          <ChartsReferenceLine\n            x={meanBinCenter}\n            label=\"Mean\"\n            labelStyle={{ fill: t.inkSoft, fontSize: 13 }}\n            lineStyle={{ stroke: t.ink, strokeDasharray: \"6 4\", strokeWidth: 1.5 }}\n          />\n          <ChartsXAxis />\n          <ChartsYAxis />\n          <ChartsLegend position={{ vertical: \"top\", horizontal: \"right\" }} direction=\"row\" />\n          <ChartsTooltip trigger=\"item\" />\n        </ChartContainer>\n\n        <div\n          style={{\n            position: \"absolute\",\n            top: 16,\n            left: 100,\n            background: t.elevatedBg,\n            border: `1px solid ${t.grid}`,\n            borderRadius: 8,\n            padding: \"12px 18px\",\n            fontSize: 15,\n            lineHeight: 1.6,\n            color: t.ink,\n            minWidth: 190,\n          }}\n        >\n          <div style={{ fontWeight: 600, marginBottom: 4 }}>Return statistics</div>\n          <div style={{ color: t.inkSoft }}>Mean: {pct(mean)}</div>\n          <div style={{ color: t.inkSoft }}>Std dev: {pct(std)}</div>\n          <div style={{ color: t.inkSoft }}>Skewness: {skewness.toFixed(2)}</div>\n          <div style={{ color: t.inkSoft }}>Kurtosis: {excessKurtosis.toFixed(2)}</div>\n        </div>\n      </div>\n    </div>\n  );\n}\n"}