{"spec_id":"indicator-sma","library":"muix","language":"javascript","code":"// anyplot.ai\n// indicator-sma: Simple Moving Average (SMA) Indicator Chart\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsTooltip } from \"@mui/x-charts/ChartsTooltip\";\nimport { ChartsAxisHighlight } from \"@mui/x-charts/ChartsAxisHighlight\";\nimport { LinePlot } from \"@mui/x-charts/LineChart\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst Y_PAD_SHARE = 0.06; // share of the price range added above and below the outermost line\n\n// Columns: set these to your data's column names\nconst DATE = \"Trading date\"; // role: date\nconst CLOSE = \"AURA close (USD)\"; // role: close\nconst SMA_SHORT = \"SMA 20 (USD)\"; // role: sma_short\nconst SMA_MEDIUM = \"SMA 50 (USD)\"; // role: sma_medium\nconst SMA_LONG = \"SMA 200 (USD)\"; // role: sma_long\n\n// Data: replace this block with your own records, one object per trading day\n// 300 weekdays of a stock from 1 Jun 2023: a steady uptrend, a choppy pullback (days 110-189)\n// that gives back about 12 % of the price, and a recovery. Each SMA averages the last 20, 50\n// or 200 closes and stays empty until its window is full.\nconst data = (() => {\n  const periods = 300;\n  let seed = 42;\n  const rand = () => {\n    seed = (seed * 1664525 + 1013904223) % 4294967296;\n    return seed / 4294967296;\n  };\n  const gaussian = () => Math.sqrt(-2 * Math.log(Math.max(rand(), 1e-9))) * Math.cos(2 * Math.PI * rand());\n  const round2 = (v: number) => Math.round(v * 100) / 100;\n\n  const days: string[] = [];\n  const cursor = new Date(Date.UTC(2023, 5, 1));\n  while (days.length < periods) {\n    if (cursor.getUTCDay() % 6 !== 0) days.push(cursor.toISOString().slice(0, 10));\n    cursor.setUTCDate(cursor.getUTCDate() + 1);\n  }\n\n  const close = [68];\n  for (let i = 1; i < periods; i += 1) {\n    const pullback = i >= 110 && i < 190;\n    const changePct = (pullback ? -0.3 : 0.09) + (pullback ? 1.3 : 0.9) * gaussian();\n    close.push(close[i - 1] * (1 + changePct / 100));\n  }\n\n  // Running sums over the last 20, 50 and 200 closes\n  let sumShort = 0;\n  let sumMedium = 0;\n  let sumLong = 0;\n  const rows = [];\n  for (let i = 0; i < periods; i += 1) {\n    sumShort += close[i] - (i >= 20 ? close[i - 20] : 0);\n    sumMedium += close[i] - (i >= 50 ? close[i - 50] : 0);\n    sumLong += close[i] - (i >= 200 ? close[i - 200] : 0);\n    rows.push({\n      [DATE]: days[i],\n      [CLOSE]: round2(close[i]),\n      [SMA_SHORT]: i >= 19 ? round2(sumShort / 20) : null,\n      [SMA_MEDIUM]: i >= 49 ? round2(sumMedium / 50) : null,\n      [SMA_LONG]: i >= 199 ? round2(sumLong / 200) : null,\n    });\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\n// ISO dates are read as local midnight, the frame the time axis places its ticks in\nconst rows = [...data].sort((a, b) => Date.parse(a[DATE]) - Date.parse(b[DATE]));\nconst n = rows.length;\nconst dates = rows.map((d) => new Date(`${d[DATE]}T00:00:00`));\nconst closes = rows.map((d) => d[CLOSE] ?? null);\nconst shorts = rows.map((d) => d[SMA_SHORT] ?? null);\nconst mediums = rows.map((d) => d[SMA_MEDIUM] ?? null);\nconst longs = rows.map((d) => d[SMA_LONG] ?? null);\n\n// A crossover of the short over the medium SMA is a change of side against the last day on\n// which the two differed; its mark sits where the two straight segments meet, or on the day\n// they were equal\nconst crossovers: { time: number; value: number; upward: boolean }[] = [];\nlet side = 0; // sign of the last non-zero difference short - medium\nfor (let i = 1; i < n; i += 1) {\n  const s0 = shorts[i - 1];\n  const m0 = mediums[i - 1];\n  const s1 = shorts[i];\n  const m1 = mediums[i];\n  if (s0 == null || m0 == null || s1 == null || m1 == null) continue;\n  const before = s0 - m0;\n  const after = s1 - m1;\n  if (before !== 0) side = Math.sign(before);\n  if (after === 0 || side === 0 || Math.sign(after) === side) continue;\n  const f = before / (before - after); // 0 when the two were equal on the day before\n  crossovers.push({\n    time: dates[i - 1].getTime() + f * (dates[i].getTime() - dates[i - 1].getTime()),\n    value: s0 + f * (s1 - s0),\n    upward: after > 0,\n  });\n}\nconst upwardCount = crossovers.filter((c) => c.upward).length;\nconst downwardCount = crossovers.length - upwardCount;\n\nconst drawn = [...closes, ...shorts, ...mediums, ...longs].filter((v) => v != null);\nconst yLow = Math.min(...drawn);\nconst yHigh = Math.max(...drawn);\nconst yPad = (yHigh - yLow) * Y_PAD_SHARE;\n\nconst monthFormat = new Intl.DateTimeFormat(\"en-US\", { month: \"short\", year: \"numeric\" });\nconst fullFormat = new Intl.DateTimeFormat(\"en-US\", { month: \"short\", day: \"numeric\", year: \"numeric\" });\nconst shortName = SMA_SHORT.replace(/\\s*\\([^)]*\\)\\s*$/, \"\");\nconst mediumName = SMA_MEDIUM.replace(/\\s*\\([^)]*\\)\\s*$/, \"\");\n\nconst TITLE = \"indicator-sma · javascript · muix · anyplot.ai\";\nconst SUBTITLE =\n  `${n} periods, ${fullFormat.format(dates[0])} – ${fullFormat.format(dates[n - 1])} · ` +\n  `▲ ${shortName} crosses above ${mediumName} (${upwardCount}×) · ▼ crosses below (${downwardCount}×)`;\nconst HEADER_H = 84;\nconst LEGEND_H = 44;\nconst MARK_PX = 8; // half the width of a crossover triangle\n\n// One stroke style per series, shared by the plotted line and its legend sample\nconst STROKES = {\n  close: { width: 3, dash: undefined },\n  smaShort: { width: 2, dash: \"8 5\" },\n  smaMedium: { width: 2.75, dash: \"2 4\" },\n  smaLong: { width: 2.25, dash: undefined },\n};\nconst SAMPLE_W = 40;\nconst SAMPLE_H = 10;\n\n// The built-in \"line\" mark is a short solid bar; this sample carries the series' dash pattern\nconst lineSample = ({ width, dash }: { width: number; dash?: string }) =>\n  function LineSample({ color }: { color: string }) {\n    return (\n      <svg viewBox={`0 0 ${SAMPLE_W} ${SAMPLE_H}`}>\n        <line x1={1} y1={SAMPLE_H / 2} x2={SAMPLE_W - 1} y2={SAMPLE_H / 2} stroke={color} strokeWidth={width} strokeDasharray={dash} />\n      </svg>\n    );\n  };\nconst lineStyle = (id: keyof typeof STROKES) => ({ strokeWidth: STROKES[id].width, strokeDasharray: STROKES[id].dash });\n\nfunction CrossoverMarks() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g>\n      {crossovers.map((c) => {\n        const x = xScale(new Date(c.time));\n        const y = yScale(c.value);\n        const tip = c.upward ? -1.15 * MARK_PX : 1.15 * MARK_PX;\n        return (\n          <path\n            key={c.time}\n            d={`M${x},${y + tip}L${x + MARK_PX},${y - tip * 0.6}L${x - MARK_PX},${y - tip * 0.6}Z`}\n            fill={t.ink}\n            stroke={t.pageBg}\n            strokeWidth={1.5}\n          />\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <Box sx={{ width, height, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\", overflow: \"hidden\" }}>\n      <Box sx={{ height: HEADER_H, pt: \"14px\", textAlign: \"center\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.3 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.6 }}>{SUBTITLE}</Typography>\n      </Box>\n      <ChartsDataProvider\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        margin={{ top: 12, right: 40, bottom: 8, left: 20 }}\n        skipAnimation\n        // The averages come first so the close is drawn on top of them; the legend reverses\n        // this order so it reads close, then the SMAs by ascending period\n        series={[\n          {\n            type: \"line\",\n            id: \"smaLong\",\n            data: longs,\n            label: SMA_LONG,\n            color: t.palette[3],\n            curve: \"linear\",\n            showMark: false,\n            labelMarkType: lineSample(STROKES.smaLong),\n          },\n          {\n            type: \"line\",\n            id: \"smaMedium\",\n            data: mediums,\n            label: SMA_MEDIUM,\n            color: t.palette[2],\n            curve: \"linear\",\n            showMark: false,\n            labelMarkType: lineSample(STROKES.smaMedium),\n          },\n          {\n            type: \"line\",\n            id: \"smaShort\",\n            data: shorts,\n            label: SMA_SHORT,\n            color: t.palette[1],\n            curve: \"linear\",\n            showMark: false,\n            labelMarkType: lineSample(STROKES.smaShort),\n          },\n          {\n            type: \"line\",\n            id: \"close\",\n            data: closes,\n            label: CLOSE,\n            color: t.palette[0],\n            curve: \"linear\",\n            showMark: false,\n            labelMarkType: lineSample(STROKES.close),\n          },\n        ]}\n        xAxis={[\n          {\n            scaleType: \"time\",\n            data: dates,\n            domainLimit: \"strict\",\n            label: DATE,\n            height: 64,\n            tickNumber: 10,\n            valueFormatter: (v: Date, context) =>\n              context.location === \"tick\" ? monthFormat.format(v) : fullFormat.format(v),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: yLow - yPad,\n            max: yHigh + yPad,\n            width: 84,\n            label: CLOSE,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n      >\n        <ChartsWrapper legendPosition={{ vertical: \"top\", horizontal: \"center\" }} legendDirection=\"horizontal\">\n          <ChartsLegend\n            sx={{\n              fontSize: 15,\n              color: t.ink,\n              gap: \"28px\",\n              flexDirection: \"row-reverse\",\n              \"& .MuiChartsLegend-mark\": { width: SAMPLE_W, height: SAMPLE_H },\n            }}\n          />\n          <ChartsSurface\n            sx={{\n              '& .MuiLineChart-line[data-series=\"close\"]': lineStyle(\"close\"),\n              '& .MuiLineChart-line[data-series=\"smaShort\"]': lineStyle(\"smaShort\"),\n              '& .MuiLineChart-line[data-series=\"smaMedium\"]': lineStyle(\"smaMedium\"),\n              '& .MuiLineChart-line[data-series=\"smaLong\"]': lineStyle(\"smaLong\"),\n              \"& .MuiChartsGrid-line\": { stroke: t.grid },\n            }}\n          >\n            <ChartsGrid horizontal />\n            <LinePlot skipAnimation />\n            <CrossoverMarks />\n            <ChartsAxisHighlight x=\"line\" />\n            <ChartsXAxis />\n            <ChartsYAxis />\n          </ChartsSurface>\n          <ChartsTooltip trigger=\"axis\" />\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </Box>\n  );\n}\n"}