{"spec_id":"indicator-ema","library":"muix","language":"javascript","code":"// anyplot.ai\n// indicator-ema: Exponential Moving Average (EMA) 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 = \"Close (USD)\"; // role: close\nconst EMA_SHORT = \"12-day EMA (USD)\"; // role: ema_short\nconst EMA_LONG = \"26-day EMA (USD)\"; // role: ema_long\n\n// Data: replace this block with your own records, one object per trading day\n// 120 weekdays of a stock from 2 Jan 2024: a random walk with a mild upward drift.\n// Both EMAs are seeded with the first close and use the smoothing factor 2 / (period + 1).\nconst data = (() => {\n  const periods = 120;\n  let state = 42;\n  const rand = () => {\n    state = (state * 1103515245 + 12345) % 2147483648;\n    return state / 2147483648;\n  };\n  const round2 = (v: number) => Math.round(v * 100) / 100;\n\n  const days: string[] = [];\n  const cursor = new Date(Date.UTC(2024, 0, 2));\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: number[] = [];\n  let price = 148;\n  for (let i = 0; i < periods; i += 1) {\n    price += 0.15 + (rand() - 0.5) * 4.2;\n    close.push(round2(price));\n  }\n\n  const kShort = 2 / (12 + 1);\n  const kLong = 2 / (26 + 1);\n  const short = [close[0]];\n  const long = [close[0]];\n  for (let i = 1; i < periods; i += 1) {\n    short.push(close[i] * kShort + short[i - 1] * (1 - kShort));\n    long.push(close[i] * kLong + long[i - 1] * (1 - kLong));\n  }\n\n  return days.map((day, i) => ({\n    [DATE]: day,\n    [CLOSE]: close[i],\n    [EMA_SHORT]: round2(short[i]),\n    [EMA_LONG]: round2(long[i]),\n  }));\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[EMA_SHORT] ?? null);\nconst longs = rows.map((d) => d[EMA_LONG] ?? null);\n\n// A crossover is a change of side against the last day on which the two EMAs differed; its\n// mark sits where the two straight segments meet, or on the day they were equal\nconst crossovers: { time: number; value: number; bullish: boolean }[] = [];\nlet side = 0; // sign of the last non-zero difference short - long\nfor (let i = 1; i < n; i += 1) {\n  const s0 = shorts[i - 1];\n  const l0 = longs[i - 1];\n  const s1 = shorts[i];\n  const l1 = longs[i];\n  if (s0 == null || l0 == null || s1 == null || l1 == null) continue;\n  const before = s0 - l0;\n  const after = s1 - l1;\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    bullish: after > 0,\n  });\n}\nconst bullishCount = crossovers.filter((c) => c.bullish).length;\nconst bearishCount = crossovers.length - bullishCount;\n\nconst drawn = [...closes, ...shorts, ...longs].filter((v) => v != null);\nconst yLow = Math.min(...drawn);\nconst yHigh = Math.max(...drawn);\nconst yPad = (yHigh - yLow) * Y_PAD_SHARE;\n\nconst dayFormat = new Intl.DateTimeFormat(\"en-US\", { month: \"short\", day: \"numeric\" });\nconst fullFormat = new Intl.DateTimeFormat(\"en-US\", { month: \"short\", day: \"numeric\", year: \"numeric\" });\nconst shortName = EMA_SHORT.replace(/\\s*\\([^)]*\\)\\s*$/, \"\");\nconst longName = EMA_LONG.replace(/\\s*\\([^)]*\\)\\s*$/, \"\");\n\nconst TITLE = \"indicator-ema · javascript · muix · anyplot.ai\";\nconst SUBTITLE =\n  `${n} periods, ${fullFormat.format(dates[0])} – ${fullFormat.format(dates[n - 1])} · ` +\n  `▲ ${shortName} crosses above ${longName} (${bullishCount}×) · ▼ crosses below (${bearishCount}×)`;\nconst HEADER_H = 84;\nconst LEGEND_H = 44;\nconst MARK_PX = 8; // half the width of a crossover triangle\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.bullish ? -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        series={[\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: \"line\",\n          },\n          {\n            type: \"line\",\n            id: \"emaShort\",\n            data: shorts,\n            label: EMA_SHORT,\n            color: t.palette[1],\n            curve: \"linear\",\n            showMark: false,\n            labelMarkType: \"line\",\n          },\n          {\n            type: \"line\",\n            id: \"emaLong\",\n            data: longs,\n            label: EMA_LONG,\n            color: t.palette[2],\n            curve: \"linear\",\n            showMark: false,\n            labelMarkType: \"line\",\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) => dayFormat.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 sx={{ fontSize: 15, color: t.ink, gap: \"28px\" }} />\n          <ChartsSurface\n            sx={{\n              \"& .MuiLineChart-line\": { strokeWidth: 2 },\n              '& .MuiLineChart-line[data-series=\"close\"]': { strokeWidth: 3.5 },\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"}