{"spec_id":"histogram-returns-distribution","library":"muix","language":"javascript","code":"// anyplot.ai\n// histogram-returns-distribution: Returns Distribution Histogram\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 85/100 | Updated: 2026-10-24\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\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\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst FONT = '\"Plus Jakarta Sans\", \"Inter\", -apple-system, BlinkMacSystemFont, sans-serif';\nconst MONO = '\"JetBrains Mono\", \"SFMono-Regular\", Menlo, monospace';\nconst Y_AXIS_LABEL = \"Probability density\";\nconst CORE_SERIES_LABEL = \"Within ±2σ\";\nconst TAIL_SERIES_LABEL = \"Beyond ±2σ (tail)\";\nconst NORMAL_SERIES_LABEL = \"Normal fit\";\n\nconst BIN_COUNT = 26;\nconst TAIL_SIGMA_MULT = 2.0;\nconst Y_TOP_PAD_SHARE = 0.14;\n\n// Columns: set these to your data's column names\nconst DATE = \"Trading date\"; // role: date\nconst RETURNS = \"Daily return (%)\"; // role: returns\n\n// Data: replace this block with your own records\nconst N_DAYS = 252;\nconst DAILY_VOL = 1.15;\nconst DRIFT = 0.04;\n\nlet seed = 42;\nconst data: Array<{\n  [DATE]: string;\n  [RETURNS]: number;\n}> = [];\n\nconst baseMs = Date.UTC(2025, 0, 2);\nfor (let i = 0; i < N_DAYS; i += 1) {\n  seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n  const u1 = Math.max(seed / 0x7fffffff, 1e-12);\n  seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n  const u2 = seed / 0x7fffffff;\n  const z1 = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n\n  let r = DRIFT + z1 * DAILY_VOL;\n\n  seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n  const shockRoll = seed / 0x7fffffff;\n  if (shockRoll < 0.06) {\n    seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n    const su1 = Math.max(seed / 0x7fffffff, 1e-12);\n    seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n    const su2 = seed / 0x7fffffff;\n    const sz = Math.sqrt(-2 * Math.log(su1)) * Math.cos(2 * Math.PI * su2);\n    r -= Math.abs(sz) * DAILY_VOL * 2.2;\n  }\n\n  const weekIdx = Math.floor(i / 5);\n  const dayInWeek = i % 5;\n  const dateStr = new Date(baseMs + (weekIdx * 7 + dayInWeek) * 86400000)\n    .toISOString()\n    .slice(0, 10);\n\n  data.push({\n    [DATE]: dateStr,\n    [RETURNS]: r,\n  });\n}\n\n// Plot: reads only data and the constants above\nconst unitMatch = RETURNS.match(/\\(([^)]+)\\)/);\nconst returnUnit = unitMatch ? unitMatch[1] : \"\";\n\nconst periodReturns = data.map((row) => row[RETURNS]);\nconst periodDates = data.map((row) => row[DATE]);\nconst startDate = periodDates[0];\nconst endDate = periodDates[periodDates.length - 1];\n\nconst n = periodReturns.length;\nconst mean = periodReturns.reduce((a, b) => a + b, 0) / n;\nconst variance = periodReturns.reduce((a, b) => a + (b - mean) ** 2, 0) / n;\nconst std = Math.sqrt(variance);\nconst skewness =\n  periodReturns.reduce((a, b) => a + ((b - mean) / std) ** 3, 0) / n;\nconst excessKurtosis =\n  periodReturns.reduce((a, b) => a + ((b - mean) / std) ** 4, 0) / n - 3;\n\nconst minReturn = Math.min(...periodReturns);\nconst maxReturn = Math.max(...periodReturns);\nconst binWidth = (maxReturn - minReturn) / BIN_COUNT;\nconst binCounts = new Array<number>(BIN_COUNT).fill(0);\nfor (let i = 0; i < n; i += 1) {\n  const r = periodReturns[i];\n  const idx = Math.min(\n    BIN_COUNT - 1,\n    Math.max(0, Math.floor((r - minReturn) / binWidth)),\n  );\n  binCounts[idx] += 1;\n}\n\nconst binCenters = binCounts.map((_, i) => minReturn + binWidth * (i + 0.5));\nconst density = binCounts.map((c) => c / (n * binWidth));\nconst normalCurve = binCenters.map(\n  (c) =>\n    Math.exp(-0.5 * ((c - mean) / std) ** 2) / (std * Math.sqrt(2 * Math.PI)),\n);\n\nconst lowerTail = mean - TAIL_SIGMA_MULT * std;\nconst upperTail = mean + TAIL_SIGMA_MULT * std;\nconst coreDensity = density.map((d, i) =>\n  binCenters[i] < lowerTail || binCenters[i] > upperTail ? 0 : d,\n);\nconst tailDensity = density.map((d, i) =>\n  binCenters[i] < lowerTail || binCenters[i] > upperTail ? d : 0,\n);\nconst tailPeriodCount = periodReturns.filter(\n  (r) => r < lowerTail || r > upperTail,\n).length;\n\nconst maxDensity = Math.max(...density, ...normalCurve);\nconst yMax = maxDensity * (1 + Y_TOP_PAD_SHARE);\n\nconst CORE_COLOR = t.palette[0];\nconst TAIL_COLOR = t.palette[1];\nconst NORMAL_COLOR = t.ink;\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const headerHeight = 84;\n  const chartHeight = height - headerHeight;\n\n  return (\n    <div\n      style={{\n        width,\n        height,\n        background: t.pageBg,\n        color: t.ink,\n        fontFamily: FONT,\n        display: \"flex\",\n        flexDirection: \"column\",\n        boxSizing: \"border-box\",\n      }}\n    >\n      <div\n        style={{\n          height: headerHeight,\n          padding: \"14px 44px 4px 104px\",\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"space-between\",\n          boxSizing: \"border-box\",\n        }}\n      >\n        <div>\n          <div\n            style={{\n              fontSize: 22,\n              fontWeight: 700,\n              color: t.ink,\n              lineHeight: 1.2,\n            }}\n          >\n            histogram-returns-distribution · javascript · muix · anyplot.ai\n          </div>\n          <div\n            style={{\n              fontSize: 14,\n              color: t.inkSoft,\n              marginTop: 4,\n              fontFamily: MONO,\n            }}\n          >\n            {n} periods ({startDate} to {endDate}) · {tailPeriodCount} tail\n            periods beyond ±{TAIL_SIGMA_MULT.toFixed(0)}σ (\n            {lowerTail.toFixed(2)}\n            {returnUnit} / +{upperTail.toFixed(2)}\n            {returnUnit})\n          </div>\n        </div>\n\n        <div\n          style={{\n            display: \"flex\",\n            alignItems: \"center\",\n            gap: 24,\n            fontSize: 15,\n            color: t.ink,\n          }}\n        >\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <span\n              style={{\n                width: 16,\n                height: 14,\n                borderRadius: 3,\n                background: CORE_COLOR,\n                display: \"inline-block\",\n              }}\n            />\n            <span>{CORE_SERIES_LABEL}</span>\n          </div>\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <span\n              style={{\n                width: 16,\n                height: 14,\n                borderRadius: 3,\n                background: TAIL_COLOR,\n                display: \"inline-block\",\n              }}\n            />\n            <span>{TAIL_SERIES_LABEL}</span>\n          </div>\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <span\n              style={{\n                width: 24,\n                height: 3,\n                borderRadius: 2,\n                background: NORMAL_COLOR,\n                display: \"inline-block\",\n              }}\n            />\n            <span>{NORMAL_SERIES_LABEL}</span>\n          </div>\n        </div>\n      </div>\n\n      <div style={{ position: \"relative\", width, height: chartHeight }}>\n        <ChartsContainer\n          width={width}\n          height={chartHeight}\n          skipAnimation\n          margin={{ top: 20, right: 40, bottom: 20, left: 20 }}\n          series={[\n            {\n              type: \"bar\",\n              data: coreDensity,\n              stack: \"bins\",\n              color: CORE_COLOR,\n              label: CORE_SERIES_LABEL,\n              valueFormatter: (v: number | null) =>\n                v ? v.toFixed(3) : null,\n            },\n            {\n              type: \"bar\",\n              data: tailDensity,\n              stack: \"bins\",\n              color: TAIL_COLOR,\n              label: TAIL_SERIES_LABEL,\n              valueFormatter: (v: number | null) =>\n                v ? v.toFixed(3) : null,\n            },\n            {\n              type: \"line\",\n              data: normalCurve,\n              color: NORMAL_COLOR,\n              label: NORMAL_SERIES_LABEL,\n              showMark: false,\n              curve: \"natural\",\n              valueFormatter: (v: number | null) =>\n                v !== null ? v.toFixed(3) : \"\",\n            },\n          ]}\n          xAxis={[\n            {\n              scaleType: \"band\",\n              data: binCenters,\n              height: 60,\n              categoryGapRatio: 0.04,\n              valueFormatter: (v: number) =>\n                Math.abs(v) < 0.05\n                  ? `0.0${returnUnit}`\n                  : `${v.toFixed(1)}${returnUnit}`,\n              label: RETURNS,\n              labelStyle: { fill: t.ink, fontSize: 16, fontWeight: 600 },\n              tickLabelStyle: {\n                fill: t.inkSoft,\n                fontSize: 14,\n                fontFamily: MONO,\n              },\n              tickLabelInterval: (_: unknown, i: number) => i % 3 === 0,\n            },\n          ]}\n          yAxis={[\n            {\n              min: 0,\n              max: yMax,\n              width: 84,\n              label: Y_AXIS_LABEL,\n              labelStyle: { fill: t.ink, fontSize: 16, fontWeight: 600 },\n              tickLabelStyle: {\n                fill: t.inkSoft,\n                fontSize: 14,\n                fontFamily: MONO,\n              },\n              valueFormatter: (v: number) => v.toFixed(2),\n            },\n          ]}\n        >\n          <ChartsGrid horizontal />\n          <BarPlot skipAnimation borderRadius={2} />\n          <LinePlot skipAnimation />\n          <ChartsXAxis />\n          <ChartsYAxis />\n        </ChartsContainer>\n\n        <div\n          style={{\n            position: \"absolute\",\n            top: 28,\n            left: 124,\n            background: t.elevatedBg,\n            border: `1px solid ${t.grid}`,\n            borderRadius: 8,\n            padding: \"12px 18px\",\n            fontSize: 15,\n            lineHeight: 1.65,\n            color: t.ink,\n            minWidth: 210,\n            fontFamily: MONO,\n          }}\n        >\n          <div\n            style={{\n              fontWeight: 700,\n              marginBottom: 4,\n              fontFamily: FONT,\n              fontSize: 15,\n            }}\n          >\n            Return statistics\n          </div>\n          <div style={{ color: t.inkSoft }}>\n            Mean: {mean.toFixed(2)}\n            {returnUnit}\n          </div>\n          <div style={{ color: t.inkSoft }}>\n            Std dev: {std.toFixed(2)}\n            {returnUnit}\n          </div>\n          <div style={{ color: t.inkSoft }}>\n            Skewness: {skewness.toFixed(2)}\n          </div>\n          <div style={{ color: t.inkSoft }}>\n            Excess kurtosis: {excessKurtosis.toFixed(2)}\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n"}