{"spec_id":"indicator-rsi","library":"muix","language":"javascript","code":"// anyplot.ai\n// indicator-rsi: RSI Technical Indicator Chart\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 88/100 | Updated: 2026-10-24\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\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\";\nimport { useDrawingArea, useYScale } from \"@mui/x-charts/hooks\";\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 = \"Relative Strength Index (RSI)\";\nconst LOOKBACK = 14;\nconst RSI_MIN = 0;\nconst RSI_MAX = 100;\nconst OVERBOUGHT_THRESHOLD = 70;\nconst NEUTRAL_THRESHOLD = 50;\nconst OVERSOLD_THRESHOLD = 30;\n\n// Columns: set these to your data's column names\nconst DATE = \"Trading date\"; // role: date\nconst CLOSE = \"Close price ($)\"; // role: close\nconst RSI = \"RSI (14-period)\"; // role: rsi\n\n// Data: replace this block with your own records\nconst RSI_PERIODS = 120;\nlet lcgState = 7;\nconst totalDays = RSI_PERIODS + LOOKBACK;\nconst isoDates: string[] = [];\nconst cursor = new Date(Date.UTC(2025, 0, 2));\nwhile (isoDates.length < totalDays + 1) {\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 allCloses: number[] = [];\nlet price = 62;\nfor (let i = 0; i <= totalDays; i += 1) {\n  const trend = 0.55 * Math.sin(i / 14) + 0.18 * Math.sin(i / 4.5);\n  lcgState = (lcgState * 1664525 + 1013904223) % 4294967296;\n  const r = lcgState / 4294967296;\n  const noise = (r - 0.5) * 1.9;\n  price += trend + noise;\n  allCloses.push(price);\n}\n\nconst gains: number[] = [];\nconst losses: number[] = [];\nfor (let i = 1; i < allCloses.length; i += 1) {\n  const change = allCloses[i] - allCloses[i - 1];\n  gains.push(Math.max(change, 0));\n  losses.push(Math.max(-change, 0));\n}\n\nlet avgGain =\n  gains.slice(0, LOOKBACK).reduce((a, b) => a + b, 0) / LOOKBACK;\nlet avgLoss =\n  losses.slice(0, LOOKBACK).reduce((a, b) => a + b, 0) / LOOKBACK;\nconst rawRsi: number[] = [\n  avgLoss === 0 ? 100 : 100 - 100 / (1 + avgGain / avgLoss),\n];\n\nfor (let i = LOOKBACK; i < gains.length; i += 1) {\n  avgGain = (avgGain * (LOOKBACK - 1) + gains[i]) / LOOKBACK;\n  avgLoss = (avgLoss * (LOOKBACK - 1) + losses[i]) / LOOKBACK;\n  rawRsi.push(avgLoss === 0 ? 100 : 100 - 100 / (1 + avgGain / avgLoss));\n}\n\nconst visibleDates = isoDates.slice(isoDates.length - RSI_PERIODS);\nconst visibleCloses = allCloses.slice(allCloses.length - RSI_PERIODS);\nconst visibleRsi = rawRsi.slice(rawRsi.length - RSI_PERIODS);\n\nconst data: Array<{\n  [DATE]: string;\n  [CLOSE]: number;\n  [RSI]: number;\n}> = [];\n\nfor (let i = 0; i < RSI_PERIODS; i += 1) {\n  data.push({\n    [DATE]: visibleDates[i],\n    [CLOSE]: visibleCloses[i],\n    [RSI]: Number(visibleRsi[i].toFixed(2)),\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 rsiValues = data.map((row) => row[RSI]);\n\nconst overboughtPeriods = rsiValues.filter(\n  (v) => v >= OVERBOUGHT_THRESHOLD,\n).length;\nconst oversoldPeriods = rsiValues.filter(\n  (v) => v <= OVERSOLD_THRESHOLD,\n).length;\n\nconst RSI_COLOR = t.palette[0];\nconst OVERBOUGHT_COLOR = t.inkSoft;\nconst OVERSOLD_COLOR = t.inkSoft;\nconst ZONE_OPACITY = 0.12;\n\nfunction RsiZonesLayer() {\n  const { left, width } = useDrawingArea();\n  const yScale = useYScale(\"rsi-axis\") as (v: number) => number;\n\n  const y100 = yScale(RSI_MAX);\n  const y70 = yScale(OVERBOUGHT_THRESHOLD);\n  const y30 = yScale(OVERSOLD_THRESHOLD);\n  const y0 = yScale(RSI_MIN);\n\n  return (\n    <g>\n      <rect\n        x={left}\n        y={y100}\n        width={width}\n        height={Math.max(0, y70 - y100)}\n        fill={OVERBOUGHT_COLOR}\n        fillOpacity={ZONE_OPACITY}\n      />\n      <rect\n        x={left}\n        y={y30}\n        width={width}\n        height={Math.max(0, y0 - y30)}\n        fill={OVERSOLD_COLOR}\n        fillOpacity={ZONE_OPACITY}\n      />\n    </g>\n  );\n}\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-rsi · 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          Wilder&apos;s {LOOKBACK}-period RSI over {nPeriods} periods (\n          {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)}) · {overboughtPeriods}{\" \"}\n          overbought (&ge;{OVERBOUGHT_THRESHOLD}) &amp; {oversoldPeriods}{\" \"}\n          oversold (&le;{OVERSOLD_THRESHOLD}) periods\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: \"line\",\n            id: \"rsi\",\n            yAxisId: \"rsi-axis\",\n            data: rsiValues,\n            label: RSI,\n            color: RSI_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: \"rsi-axis\",\n            min: RSI_MIN,\n            max: RSI_MAX,\n            width: 84,\n            tickNumber: 6,\n            label: 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            disableLine: true,\n          },\n        ]}\n        sx={{\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n        }}\n      >\n        <RsiZonesLayer />\n        <ChartsGrid horizontal />\n        <LinePlot skipAnimation />\n        <ChartsReferenceLine\n          y={OVERBOUGHT_THRESHOLD}\n          axisId=\"rsi-axis\"\n          label={`Overbought (${OVERBOUGHT_THRESHOLD})`}\n          labelAlign=\"end\"\n          labelStyle={{\n            fontSize: 14,\n            fill: t.ink,\n            fontWeight: 600,\n            fontFamily: MONO,\n          }}\n          lineStyle={{\n            stroke: OVERBOUGHT_COLOR,\n            strokeWidth: 1.75,\n            strokeDasharray: \"6 4\",\n          }}\n        />\n        <ChartsReferenceLine\n          y={NEUTRAL_THRESHOLD}\n          axisId=\"rsi-axis\"\n          label={`Neutral (${NEUTRAL_THRESHOLD})`}\n          labelAlign=\"end\"\n          labelStyle={{\n            fontSize: 14,\n            fill: t.inkSoft,\n            fontWeight: 600,\n            fontFamily: MONO,\n          }}\n          lineStyle={{\n            stroke: t.inkSoft,\n            strokeDasharray: \"4 4\",\n            strokeOpacity: 0.65,\n          }}\n        />\n        <ChartsReferenceLine\n          y={OVERSOLD_THRESHOLD}\n          axisId=\"rsi-axis\"\n          label={`Oversold (${OVERSOLD_THRESHOLD})`}\n          labelAlign=\"end\"\n          labelStyle={{\n            fontSize: 14,\n            fill: t.ink,\n            fontWeight: 600,\n            fontFamily: MONO,\n          }}\n          lineStyle={{\n            stroke: OVERSOLD_COLOR,\n            strokeWidth: 1.75,\n            strokeDasharray: \"6 4\",\n          }}\n        />\n        <ChartsXAxis axisId=\"dates\" />\n        <ChartsYAxis axisId=\"rsi-axis\" />\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: RSI_COLOR,\n              borderRadius: 2,\n              display: \"inline-block\",\n            }}\n          />\n          <span>{RSI}</span>\n        </div>\n        <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n          <span\n            style={{\n              width: 16,\n              height: 14,\n              background: OVERBOUGHT_COLOR,\n              opacity: ZONE_OPACITY,\n              borderRadius: 2,\n              display: \"inline-block\",\n            }}\n          />\n          <span>Overbought zone (&gt; {OVERBOUGHT_THRESHOLD})</span>\n        </div>\n        <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n          <span\n            style={{\n              width: 16,\n              height: 14,\n              background: OVERSOLD_COLOR,\n              opacity: ZONE_OPACITY,\n              borderRadius: 2,\n              display: \"inline-block\",\n            }}\n          />\n          <span>Oversold zone (&lt; {OVERSOLD_THRESHOLD})</span>\n        </div>\n      </div>\n    </div>\n  );\n}\n"}