{"spec_id":"indicator-macd","library":"muix","language":"javascript","code":"// anyplot.ai\n// indicator-macd: MACD Technical Indicator Chart\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 87/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\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\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 = \"MACD value\";\nconst FAST_EMA_PERIOD = 12;\nconst SLOW_EMA_PERIOD = 26;\nconst SIGNAL_EMA_PERIOD = 9;\nconst Y_PAD_SHARE = 0.1;\n\n// Columns: set these to your data's column names\nconst DATE = \"Trading date\"; // role: date\nconst CLOSE = \"Close price ($)\"; // role: close\nconst MACD = \"MACD (12, 26)\"; // role: macd\nconst SIGNAL = \"Signal (9)\"; // role: signal\nconst HISTOGRAM = \"MACD histogram\"; // role: histogram\n\n// Data: replace this block with your own records\nconst PERIODS = 120;\nlet lcgState = 42;\nconst isoDates: string[] = [];\nconst cursor = new Date(Date.UTC(2025, 0, 2));\nwhile (isoDates.length < PERIODS) {\n  const weekday = cursor.getUTCDay();\n  if (weekday !== 0 && weekday !== 6) {\n    isoDates.push(cursor.toISOString().slice(0, 10));\n  }\n  cursor.setUTCDate(cursor.getUTCDate() + 1);\n}\n\nconst rawCloses: number[] = [];\nlet price = 148;\nfor (let i = 0; i < PERIODS; i += 1) {\n  const trend = 0.55 * Math.sin(i / 16) + 0.15 * Math.sin(i / 5.5);\n  lcgState = (lcgState * 1664525 + 1013904223) % 4294967296;\n  const r = lcgState / 4294967296;\n  const noise = (r - 0.5) * 1.4;\n  price += trend + noise;\n  rawCloses.push(price);\n}\n\nconst fastK = 2 / (FAST_EMA_PERIOD + 1);\nconst slowK = 2 / (SLOW_EMA_PERIOD + 1);\nconst sigK = 2 / (SIGNAL_EMA_PERIOD + 1);\n\nconst ema12: number[] = [rawCloses[0]];\nconst ema26: number[] = [rawCloses[0]];\nconst rawMacd: number[] = [0];\nfor (let i = 1; i < PERIODS; i += 1) {\n  const e12 = rawCloses[i] * fastK + ema12[i - 1] * (1 - fastK);\n  const e26 = rawCloses[i] * slowK + ema26[i - 1] * (1 - slowK);\n  ema12.push(e12);\n  ema26.push(e26);\n  rawMacd.push(e12 - e26);\n}\n\nconst rawSignal: number[] = [rawMacd[0]];\nfor (let i = 1; i < PERIODS; i += 1) {\n  rawSignal.push(rawMacd[i] * sigK + rawSignal[i - 1] * (1 - sigK));\n}\n\nconst data: Array<{\n  [DATE]: string;\n  [CLOSE]: number;\n  [MACD]: number;\n  [SIGNAL]: number;\n  [HISTOGRAM]: number;\n}> = [];\n\nfor (let i = 0; i < PERIODS; i += 1) {\n  data.push({\n    [DATE]: isoDates[i],\n    [CLOSE]: rawCloses[i],\n    [MACD]: rawMacd[i],\n    [SIGNAL]: rawSignal[i],\n    [HISTOGRAM]: Number((rawMacd[i] - rawSignal[i]).toFixed(3)),\n  });\n}\n\n// Plot: reads only data and the constants above\nconst nPeriods = data.length;\nconst dateFormatter = new Intl.DateTimeFormat(\"en-US\", {\n  month: \"short\",\n  day: \"numeric\",\n  timeZone: \"UTC\",\n});\nconst formatIsoDate = (iso: string) =>\n  dateFormatter.format(new Date(`${iso}T00:00:00Z`));\n\nconst unitMatch = CLOSE.match(/\\(([^)]+)\\)/);\nconst closeUnit = unitMatch ? unitMatch[1] : \"\";\n\nconst dateValues = data.map((row) => row[DATE]);\nconst closes = data.map((row) => row[CLOSE]);\nconst macdLine = data.map((row) => row[MACD]);\nconst signalLine = data.map((row) => row[SIGNAL]);\nconst histogram = data.map((row) => row[HISTOGRAM]);\n\nlet lastCrossoverIndex: number | null = null;\nlet crossoverCount = 0;\nlet prevNonZeroSign = 0;\nfor (let i = 0; i < histogram.length; i += 1) {\n  const s = Math.sign(histogram[i]);\n  if (s === 0) continue;\n  if (prevNonZeroSign !== 0 && s !== prevNonZeroSign) {\n    lastCrossoverIndex = i;\n    crossoverCount += 1;\n  }\n  prevNonZeroSign = s;\n}\n\nconst allValues = [...macdLine, ...signalLine, ...histogram];\nconst rawMax = Math.max(...allValues);\nconst rawMin = Math.min(...allValues);\nconst pad = (rawMax - rawMin) * Y_PAD_SHARE;\nconst Y_MAX = rawMax + pad;\nconst Y_MIN = rawMin - pad;\n\nconst MACD_COLOR = t.palette[1];\nconst SIGNAL_COLOR = t.palette[2];\nconst HIST_POS_COLOR = t.palette[0];\nconst HIST_NEG_COLOR = t.palette[4];\n\nexport default function Chart() {\n  const W = window.ANYPLOT_SIZE.width;\n  const H = window.ANYPLOT_SIZE.height;\n  const HEADER_H = 84;\n  const LEGEND_H = 48;\n  const chartH = H - HEADER_H - LEGEND_H;\n\n  return (\n    <div\n      style={{\n        width: W,\n        height: H,\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: HEADER_H,\n          padding: \"14px 44px 4px 104px\",\n          display: \"flex\",\n          flexDirection: \"column\",\n          justifyContent: \"center\",\n          boxSizing: \"border-box\",\n        }}\n      >\n        <div\n          style={{\n            fontSize: 22,\n            fontWeight: 700,\n            color: t.ink,\n            lineHeight: 1.2,\n          }}\n        >\n          indicator-macd · 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          MACD ({FAST_EMA_PERIOD}, {SLOW_EMA_PERIOD}, {SIGNAL_EMA_PERIOD}) over{\" \"}\n          {nPeriods} periods ({formatIsoDate(dateValues[0])} to{\" \"}\n          {formatIsoDate(dateValues[dateValues.length - 1])}, close {closeUnit}\n          {closes[0].toFixed(1)} → {closeUnit}\n          {closes[closes.length - 1].toFixed(1)}) · {crossoverCount} signal{\" \"}\n          {crossoverCount === 1 ? \"crossover\" : \"crossovers\"}\n        </div>\n      </div>\n\n      <ChartsContainer\n        width={W}\n        height={chartH}\n        margin={{ top: 20, right: 32, bottom: 16, left: 20 }}\n        skipAnimation\n        series={[\n          {\n            type: \"bar\",\n            id: \"histogram\",\n            yAxisId: \"value-hist\",\n            data: histogram,\n            label: HISTOGRAM,\n            color: HIST_NEG_COLOR,\n          },\n          {\n            type: \"line\",\n            id: \"macd\",\n            yAxisId: \"value\",\n            data: macdLine,\n            label: MACD,\n            color: MACD_COLOR,\n            showMark: false,\n            curve: \"linear\",\n          },\n          {\n            type: \"line\",\n            id: \"signal\",\n            yAxisId: \"value\",\n            data: signalLine,\n            label: SIGNAL,\n            color: SIGNAL_COLOR,\n            showMark: false,\n            curve: \"linear\",\n          },\n        ]}\n        xAxis={[\n          {\n            id: \"dates\",\n            scaleType: \"band\",\n            data: dateValues,\n            height: 58,\n            categoryGapRatio: 0.15,\n            label: DATE,\n            valueFormatter: (v: string) => formatIsoDate(v),\n            labelStyle: { fontSize: 15, fill: t.ink, fontWeight: 600 },\n            tickLabelInterval: (_value: string, index: number) =>\n              index % 10 === 0,\n            tickLabelStyle: {\n              fontSize: 14,\n              fill: t.inkSoft,\n              fontFamily: MONO,\n            },\n            disableLine: true,\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"value\",\n            min: Y_MIN,\n            max: Y_MAX,\n            width: 84,\n            label: closeUnit ? `${Y_AXIS_LABEL} (${closeUnit})` : Y_AXIS_LABEL,\n            labelStyle: { fontSize: 15, fill: t.ink, fontWeight: 600 },\n            tickLabelStyle: {\n              fontSize: 14,\n              fill: t.inkSoft,\n              fontFamily: MONO,\n            },\n            valueFormatter: (v: number) =>\n              `${v >= 0 ? \"+\" : \"\"}${v.toFixed(1)}`,\n            disableLine: true,\n          },\n          {\n            id: \"value-hist\",\n            min: Y_MIN,\n            max: Y_MAX,\n            position: \"none\",\n            colorMap: {\n              type: \"piecewise\",\n              thresholds: [0],\n              colors: [HIST_NEG_COLOR, HIST_POS_COLOR],\n            },\n          },\n        ]}\n        sx={{\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n        }}\n      >\n        <ChartsGrid horizontal />\n        <BarPlot skipAnimation borderRadius={1} />\n        <LinePlot skipAnimation />\n        <ChartsReferenceLine\n          y={0}\n          axisId=\"value\"\n          lineStyle={{\n            stroke: t.ink,\n            strokeDasharray: \"6 4\",\n            strokeWidth: 1.5,\n          }}\n        />\n        {lastCrossoverIndex !== null && (\n          <ChartsReferenceLine\n            x={dateValues[lastCrossoverIndex]}\n            axisId=\"dates\"\n            label={`Latest crossover (${formatIsoDate(dateValues[lastCrossoverIndex])})`}\n            labelAlign=\"start\"\n            labelStyle={{\n              fontSize: 14,\n              fill: t.ink,\n              fontWeight: 600,\n              fontFamily: MONO,\n            }}\n            lineStyle={{\n              stroke: t.inkSoft,\n              strokeDasharray: \"3 4\",\n              strokeWidth: 1.5,\n              strokeOpacity: 0.75,\n            }}\n          />\n        )}\n        <ChartsXAxis axisId=\"dates\" />\n        <ChartsYAxis axisId=\"value\" />\n      </ChartsContainer>\n\n      <div\n        style={{\n          height: LEGEND_H,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 32,\n          fontSize: 15,\n          color: t.ink,\n        }}\n      >\n        <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n          <span\n            style={{\n              width: 24,\n              height: 3,\n              background: MACD_COLOR,\n              borderRadius: 2,\n              display: \"inline-block\",\n            }}\n          />\n          <span>{MACD}</span>\n        </div>\n        <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n          <span\n            style={{\n              width: 24,\n              height: 3,\n              background: SIGNAL_COLOR,\n              borderRadius: 2,\n              display: \"inline-block\",\n            }}\n          />\n          <span>{SIGNAL}</span>\n        </div>\n        <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n          <span\n            style={{\n              width: 14,\n              height: 14,\n              background: HIST_POS_COLOR,\n              borderRadius: 2,\n              display: \"inline-block\",\n            }}\n          />\n          <span>{HISTOGRAM} (&gt; 0, bullish)</span>\n        </div>\n        <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n          <span\n            style={{\n              width: 14,\n              height: 14,\n              background: HIST_NEG_COLOR,\n              borderRadius: 2,\n              display: \"inline-block\",\n            }}\n          />\n          <span>{HISTOGRAM} (&lt; 0, bearish)</span>\n        </div>\n      </div>\n    </div>\n  );\n}\n"}