{"spec_id":"stock-event-flags","library":"muix","language":"javascript","code":"// anyplot.ai\n// stock-event-flags: Stock Chart with Event Flags\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 90/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport { useXScale, useYScale, useDrawingArea } 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\n// Flag icons per event type, stroked paths in a 16 x 16 box; other types get a ring\nconst EVENT_ICONS: Record<string, string> = {\n  Earnings: \"M2.5 15.5V9 M8 15.5V4.5 M13.5 15.5V1\",\n  Dividend:\n    \"M11.8 4.4C11.2 3 9.8 2.3 8 2.3 5.8 2.3 4.4 3.4 4.4 5 4.4 6.7 5.9 7.4 8 8 10.1 8.6 11.6 9.3 11.6 11.1 11.6 12.7 10.1 13.7 8 13.7 6 13.7 4.7 13 4.1 11.6 M8 0.4V15.6\",\n  \"Stock split\": \"M8 15.5V8 M8 8L2.5 2.2 M8 8L13.5 2.2 M2.5 2.2H6 M2.5 2.2V5.7 M13.5 2.2H10 M13.5 2.2V5.7\",\n  News: \"M8 1L10.1 5.5 15 6 11.3 9.3 12.3 14.2 8 11.7 3.7 14.2 4.7 9.3 1 6 5.9 5.5Z\",\n};\nconst ICON_FALLBACK = \"M8 2.5A5.5 5.5 0 1 0 8.01 2.5Z\";\nconst Y_PAD_LOW_SHARE = 0.3; // room below the price for downward flags\nconst Y_PAD_HIGH_SHARE = 0.3; // room above the price for upward flags\nconst FLAG_GAP_PX = 24; // clearance between a flag and the price line or a neighbouring flag\nconst FLAG_H = 56;\n// Palette positions event types never take: brand green carries the price, and matte red is the\n// semantic anchor for loss and error, which no event category means\nconst RESERVED_SLOTS = [0, 4];\n\n// Columns: set these to your data's column names\nconst DATE = \"Trading date\"; // role: date\nconst CLOSE = \"Close (USD)\"; // role: close\nconst EVENT_DATE = \"Event date\"; // role: event_date\nconst EVENT_TYPE = \"Event type\"; // role: event_type\nconst EVENT_LABEL = \"Event\"; // role: event_label\n\n// Data: replace this block with your own records, one object per row\n// A year of daily closes for a technology share, with quarterly earnings,\n// ex-dividend dates, a share split and a product launch; earnings move the\n// price on the day, dividends and the (already adjusted) split do not.\nconst tradingDates: Date[] = [];\nfor (const cursor = new Date(2024, 0, 2); tradingDates.length < 220; cursor.setDate(cursor.getDate() + 1)) {\n  if (cursor.getDay() !== 0 && cursor.getDay() !== 6) tradingDates.push(new Date(cursor));\n}\nconst eventDays = [\n  { day: 18, type: \"News\", label: \"New product line\", shock: 0.03 },\n  { day: 42, type: \"Earnings\", label: \"Q1 earnings beat\", shock: 0.06 },\n  { day: 63, type: \"Dividend\", label: \"Ex-dividend $0.24\", shock: 0 },\n  { day: 96, type: \"Earnings\", label: \"Q2 earnings miss\", shock: -0.07 },\n  { day: 124, type: \"Dividend\", label: \"Ex-dividend $0.24\", shock: 0 },\n  { day: 152, type: \"Stock split\", label: \"4-for-1 split\", shock: 0 },\n  { day: 176, type: \"Earnings\", label: \"Q3 earnings beat\", shock: 0.05 },\n  { day: 208, type: \"Earnings\", label: \"Q4 earnings beat\", shock: 0.04 },\n];\nconst events = eventDays.map((e) => ({\n  [EVENT_DATE]: tradingDates[e.day],\n  [EVENT_TYPE]: e.type,\n  [EVENT_LABEL]: e.label,\n}));\nlet seed = 42;\nlet price = 148;\nconst data = tradingDates.map((date, i) => {\n  seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n  const shock = eventDays.find((e) => e.day === i)?.shock ?? 0;\n  price = Math.max(20, price * (1 + 0.0009 + (seed / 0x7fffffff - 0.5) * 0.024 + shock));\n  return { [DATE]: date, [CLOSE]: Number(price.toFixed(2)) };\n});\n\n// Plot: reads only data and the constants above\nconst prices = data\n  .filter((d) => d[DATE] != null)\n  .sort((a, b) => (a[DATE] as Date).getTime() - (b[DATE] as Date).getTime());\nconst dates = prices.map((d) => d[DATE] as Date);\nconst closes = prices.map((d) => d[CLOSE] as number | null);\nconst closeValues = closes.filter((v): v is number => v != null);\nconst minClose = Math.min(...closeValues);\nconst maxClose = Math.max(...closeValues);\nconst closeRange = maxClose - minClose;\nconst yMin = minClose - closeRange * Y_PAD_LOW_SHARE;\nconst yMax = maxClose + closeRange * Y_PAD_HIGH_SHARE;\n\n// One tick at the first trading day of every month\nconst monthStarts = new Set(\n  dates.map((d, i) => (i === 0 || d.getMonth() !== dates[i - 1].getMonth() ? i : -1)).filter((i) => i >= 0),\n);\nconst DAY_FORMAT: Intl.DateTimeFormatOptions = { month: \"short\", day: \"numeric\" };\nconst YEAR_FORMAT: Intl.DateTimeFormatOptions = { month: \"short\", day: \"numeric\", year: \"numeric\" };\n\n// Each event snaps to the first trading day on or after its date; flags alternate above and below\nconst eventTypes = [...new Set(events.map((e) => e[EVENT_TYPE] as string))];\n// Event types are unordered categories: the free palette positions in canonical order, by first appearance\nconst typeColors = t.palette.filter((_, i) => !RESERVED_SLOTS.includes(i));\nconst flags = events\n  .filter((e) => e[EVENT_DATE] != null)\n  .sort((a, b) => (a[EVENT_DATE] as Date).getTime() - (b[EVENT_DATE] as Date).getTime())\n  .map((e) => ({ e, idx: dates.findIndex((d) => d.getTime() >= (e[EVENT_DATE] as Date).getTime()) }))\n  .filter(({ idx }) => idx >= 0 && closes[idx] != null)\n  .map(({ e, idx }, k) => {\n    const type = e[EVENT_TYPE] as string;\n    const label = e[EVENT_LABEL] as string;\n    const detail = `${type} · ${dates[idx].toLocaleDateString(\"en-US\", DAY_FORMAT)}`;\n    return {\n      key: `${idx}-${k}`,\n      date: dates[idx],\n      close: closes[idx] as number,\n      up: k % 2 === 0,\n      label,\n      detail,\n      icon: EVENT_ICONS[type] ?? ICON_FALLBACK,\n      color: typeColors[eventTypes.indexOf(type)],\n      width: 54 + Math.max(label.length * 8.6, detail.length * 7.6),\n    };\n  });\n\nconst TITLE = \"stock-event-flags · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${prices.length} trading days, ${dates[0].toLocaleDateString(\"en-US\", YEAR_FORMAT)} to ${dates[dates.length - 1].toLocaleDateString(\"en-US\", YEAR_FORMAT)} · ${flags.length} events`;\nconst HEADER_H = 76;\nconst LEGEND_H = 56;\n\n// Flags: each box sits beyond the price extremes under its own span (above or below, alternating),\n// clear of earlier boxes on the same side, with a dashed pole down or up to the close on its day\nfunction EventFlags() {\n  const xScale = useXScale() as (v: Date) => number;\n  const yScale = useYScale() as (v: number) => number;\n  const { left, top, width, height } = useDrawingArea();\n  const priceXs = dates.map((d) => xScale(d));\n  const priceYs = closes.map((c) => (c == null ? null : yScale(c)));\n  const placed: { up: boolean; x0: number; x1: number; y0: number; y1: number }[] = [];\n  const layout = flags.map((f) => {\n    const x = xScale(f.date);\n    const y = yScale(f.close);\n    const boxX = Math.min(Math.max(x, left + f.width / 2 + 4), left + width - f.width / 2 - 4) - f.width / 2;\n    const spanYs = priceYs.filter((py, i): py is number => py != null && priceXs[i] >= boxX && priceXs[i] <= boxX + f.width);\n    let boxY = f.up ? Math.min(y, ...spanYs) - FLAG_GAP_PX - FLAG_H : Math.max(y, ...spanYs) + FLAG_GAP_PX;\n    for (const p of placed) {\n      const overlaps = p.up === f.up && p.x0 < boxX + f.width && boxX < p.x1 && p.y0 < boxY + FLAG_H && boxY < p.y1;\n      if (overlaps) boxY = f.up ? p.y0 - FLAG_GAP_PX - FLAG_H : p.y1 + FLAG_GAP_PX;\n    }\n    boxY = Math.min(Math.max(boxY, top + 4), top + height - FLAG_H - 4);\n    placed.push({ up: f.up, x0: boxX, x1: boxX + f.width, y0: boxY, y1: boxY + FLAG_H });\n    return { f, x, y, boxX, boxY };\n  });\n\n  return (\n    <g>\n      {layout.map(({ f, x, y, boxX, boxY }) => {\n        const edgeY = f.up ? boxY + FLAG_H : boxY;\n        return (\n          <g key={f.key}>\n            <line x1={x} y1={y} x2={x} y2={edgeY} stroke={f.color} strokeWidth={1.6} strokeDasharray=\"4 3\" />\n            <rect x={boxX} y={boxY} width={f.width} height={FLAG_H} rx={7} fill={t.elevatedBg} stroke={f.color} strokeWidth={1.5} />\n            <rect x={boxX} y={boxY} width={5} height={FLAG_H} rx={2} fill={f.color} />\n            <path\n              d={f.icon}\n              transform={`translate(${boxX + 16}, ${boxY + FLAG_H / 2 - 8})`}\n              fill=\"none\"\n              stroke={f.color}\n              strokeWidth={2.2}\n              strokeLinejoin=\"round\"\n            />\n            <text x={boxX + 42} y={boxY + 24} fontSize={15} fontWeight={600} fill={t.ink}>\n              {f.label}\n            </text>\n            <text x={boxX + 42} y={boxY + 44} fontSize={14} fill={t.inkSoft}>\n              {f.detail}\n            </text>\n            <circle cx={x} cy={y} r={5} fill={t.pageBg} stroke={f.color} strokeWidth={2.2} />\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width: W, height: H } = window.ANYPLOT_SIZE;\n\n  return (\n    <Box sx={{ width: W, height: H, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <Box\n        sx={{\n          height: HEADER_H,\n          display: \"flex\",\n          flexDirection: \"column\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: \"6px\",\n        }}\n      >\n        <Typography sx={{ color: t.ink, fontSize: 22, fontWeight: 600, lineHeight: 1.2 }}>{TITLE}</Typography>\n        <Typography sx={{ color: t.inkSoft, fontSize: 15, lineHeight: 1.2 }}>{SUBTITLE}</Typography>\n      </Box>\n      <LineChart\n        width={W}\n        height={H - HEADER_H - LEGEND_H}\n        skipAnimation\n        hideLegend\n        grid={{ horizontal: true }}\n        margin={{ top: 8, right: 36, bottom: 8, left: 24 }}\n        series={[\n          {\n            id: \"close\",\n            data: closes,\n            label: CLOSE,\n            color: t.palette[0],\n            showMark: false,\n            curve: \"linear\",\n            area: true,\n            valueFormatter: (v: number | null) => (v == null ? \"\" : v.toFixed(2)),\n          },\n        ]}\n        xAxis={[\n          {\n            data: dates,\n            scaleType: \"point\",\n            label: DATE,\n            height: 64,\n            valueFormatter: (d: Date, ctx) =>\n              d.toLocaleDateString(\"en-US\", ctx.location === \"tick\" ? { month: \"short\" } : DAY_FORMAT),\n            tickInterval: (_d: Date, i: number) => monthStarts.has(i),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: yMin,\n            max: yMax,\n            label: CLOSE,\n            width: 76,\n            valueFormatter: (v: number) => v.toFixed(0),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        sx={{\n          \"& .MuiLineChart-line\": { strokeWidth: 2.5 },\n          \"& .MuiLineChart-area\": { fillOpacity: 0.12 },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n        }}\n      >\n        <EventFlags />\n      </LineChart>\n      <Box sx={{ height: LEGEND_H, display: \"flex\", alignItems: \"center\", justifyContent: \"center\", gap: \"14px\" }}>\n        {eventTypes.map((type, i) => (\n          <Box\n            key={type}\n            sx={{\n              display: \"flex\",\n              alignItems: \"center\",\n              gap: \"8px\",\n              padding: \"6px 14px\",\n              borderRadius: \"999px\",\n              border: `1px solid ${t.grid}`,\n              bgcolor: t.elevatedBg,\n            }}\n          >\n            <svg width={16} height={16} viewBox=\"0 0 16 16\">\n              <path d={EVENT_ICONS[type] ?? ICON_FALLBACK} fill=\"none\" stroke={typeColors[i]} strokeWidth={2.2} strokeLinejoin=\"round\" />\n            </svg>\n            <Typography sx={{ color: t.inkSoft, fontSize: 15, fontWeight: 500 }}>{type}</Typography>\n          </Box>\n        ))}\n      </Box>\n    </Box>\n  );\n}\n"}