{"spec_id":"drawdown-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// drawdown-basic: Drawdown Chart\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 89/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\nimport { useXScale, useYScale, useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst LOSS = t.palette[4]; // drawdown in the loss red, as the Notes ask\nconst VALUE_COLOR = t.palette[0]; // first palette position not taken by the loss colour\nconst RECOVERY_MARK_SHARE = 0.1; // recoveries are marked for drawdowns at least this share as deep as the maximum\nconst Y_PAD = 0.05; // share of each axis span left free beyond the outermost values\nconst ZERO_PAD = 0.08; // share of the deepest drawdown left free above the zero line, where the period is named\nconst DATE_TICKS = 8; // target count of date ticks; the time scale rounds the step to whole calendar units\n// The value series gets its own panel above the drawdown on the same date axis, so the two lines never cross\nconst VALUE_PANEL_SHARE = 0.3; // share of the chart height for the value panel\nconst Y_AXIS_W = 84; // both panels share this axis width and the margins, so their dates line up\nconst PANEL_MARGIN_X = 24;\nconst DAY_MS = 86400000;\nconst TITLE = \"drawdown-basic · javascript · muix · anyplot.ai\";\nconst HEADER_H = 84;\nconst FOOT_H = 16;\n\n// Columns: set these to your data's column names\nconst DATE = \"Date\"; // role: date\nconst NAV = \"NAV per share (USD)\"; // role: value\n\n// Data: replace this block with your own records, one object per row\n// Simulated daily NAV of a fund over 500 trading days: a mild correction, a sharp bear-market crash,\n// a strong recovery and a calm finish\nconst data = (() => {\n  const dates = [];\n  const cursor = new Date(2024, 0, 2);\n  while (dates.length < 500) {\n    if (cursor.getDay() !== 0 && cursor.getDay() !== 6) dates.push(new Date(cursor));\n    cursor.setDate(cursor.getDate() + 1);\n  }\n  let state = 42;\n  let nav = 100;\n  return dates.map((date, i) => {\n    state = (state * 1103515245 + 12345) % 2147483648;\n    const drift = i < 120 ? 0.0004 : i < 150 ? -0.0045 : i < 260 ? 0.0006 : i < 300 ? -0.0105 : i < 410 ? 0.0068 : 0.0004;\n    nav *= 1 + drift + (state / 2147483648 - 0.5) * 0.018;\n    return { [DATE]: date, [NAV]: Math.round(nav * 100) / 100 };\n  });\n})();\n\n// Plot: reads only data and the constants above\nconst rows = data.filter((d) => Number.isFinite(d[NAV])).sort((a, b) => a[DATE] - b[DATE]);\nconst dates = rows.map((d) => d[DATE]);\nconst values = rows.map((d) => d[NAV]);\n\n// Drawdown from the running maximum, in percent: 0 at every new high\nlet runningMax = -Infinity;\nconst drawdown = values.map((v) => {\n  runningMax = Math.max(runningMax, v);\n  return ((v - runningMax) / runningMax) * 100;\n});\n\n// Drawdown episodes: from the last high before the curve leaves zero to the first return to zero\nconst episodes = [];\nlet open = null;\ndrawdown.forEach((dd, i) => {\n  if (dd < 0 && open === null) open = { peak: Math.max(0, i - 1), trough: i, recovery: -1 };\n  if (open !== null && dd < drawdown[open.trough]) open.trough = i;\n  if (dd === 0 && open !== null) {\n    open.recovery = i;\n    episodes.push(open);\n    open = null;\n  }\n});\nif (open !== null) episodes.push(open);\n\nconst worst = episodes.reduce((a, b) => (drawdown[b.trough] < drawdown[a.trough] ? b : a));\nconst maxDrawdown = drawdown[worst.trough];\n// The marking threshold is rounded once, so the legend states exactly the rule the marks follow\nconst markDepth = Math.round(-maxDrawdown * RECOVERY_MARK_SHARE * 10) / 10;\nconst marked = episodes.filter((e) => e.recovery > -1 && -drawdown[e.trough] >= markDepth);\n\nconst fmtDate = new Intl.DateTimeFormat(\"en-US\", { month: \"short\", day: \"numeric\", year: \"numeric\" }).format;\nconst declineDays = Math.round((dates[worst.trough] - dates[worst.peak]) / DAY_MS);\nconst recoveryText =\n  worst.recovery > -1\n    ? `recovery ${Math.round((dates[worst.recovery] - dates[worst.trough]) / DAY_MS)} days (to ${fmtDate(dates[worst.recovery])})`\n    : \"not yet recovered\";\nconst stats = `Max drawdown ${maxDrawdown.toFixed(1)}% · decline ${declineDays} days (${fmtDate(dates[worst.peak])} → ${fmtDate(dates[worst.trough])}) · ${recoveryText}`;\n\nconst yMin = maxDrawdown * (1 + Y_PAD);\nconst yMax = -maxDrawdown * ZERO_PAD;\nconst valueLow = Math.min(...values);\nconst valueHigh = Math.max(...values);\nconst valueMin = valueLow - (valueHigh - valueLow) * Y_PAD;\nconst valueMax = valueHigh + (valueHigh - valueLow) * Y_PAD;\n\n// Marker-only series: a value at the trough and at each marked recovery, null elsewhere\nconst recoveryIdx = new Set(marked.map((e) => e.recovery));\nconst troughSeries = drawdown.map((dd, i) => (i === worst.trough ? dd : null));\nconst recoverySeries = drawdown.map((dd, i) => (recoveryIdx.has(i) ? dd : null));\n\n// The maximum drawdown period, shaded in both panels; the drawdown panel also names it and labels the trough\nfunction MaxDrawdownPeriod({ annotate }: { annotate: boolean }) {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const { left, top, width, height } = useDrawingArea();\n  const x0 = xScale(dates[worst.peak]);\n  const x1 = xScale(dates[worst.recovery > -1 ? worst.recovery : dates.length - 1]);\n  const tx = xScale(dates[worst.trough]);\n  const ty = yScale(maxDrawdown);\n  const troughRight = tx < left + width * 0.7;\n  return (\n    <g>\n      <rect x={x0} y={top} width={x1 - x0} height={height} fill={t.inkSoft} fillOpacity={0.08} />\n      {annotate && (\n        <g>\n          <text x={x0 + 10} y={top + 18} fontSize={14} fill={t.inkSoft}>\n            Max drawdown period\n          </text>\n          <text x={troughRight ? tx + 16 : tx - 16} y={ty + 5} textAnchor={troughRight ? \"start\" : \"end\"} fontSize={15} fontWeight={600} fill={t.ink}>\n            {`${maxDrawdown.toFixed(1)}% on ${fmtDate(dates[worst.trough])}`}\n          </text>\n        </g>\n      )}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const valuePanelH = Math.round((height - HEADER_H - FOOT_H) * VALUE_PANEL_SHARE);\n  const drawdownPanelH = height - HEADER_H - FOOT_H - valuePanelH;\n  const axisStyle = {\n    \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n    \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n    \"& .MuiChartsGrid-line\": { stroke: t.grid },\n  };\n  return (\n    <div style={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: HEADER_H, padding: \"22px 40px 0\", boxSizing: \"border-box\" }}>\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft, marginTop: 6 }}>{stats}</div>\n      </div>\n      <LineChart\n        width={width}\n        height={valuePanelH}\n        skipAnimation\n        hideLegend\n        grid={{ horizontal: true }}\n        margin={{ top: 12, right: PANEL_MARGIN_X, bottom: 4, left: PANEL_MARGIN_X }}\n        xAxis={[{ data: dates, scaleType: \"time\", position: \"none\" }]}\n        yAxis={[\n          {\n            id: \"value\",\n            label: NAV,\n            min: valueMin,\n            max: valueMax,\n            tickNumber: 4,\n            width: Y_AXIS_W,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={[\n          {\n            id: \"value\",\n            data: values,\n            label: NAV,\n            color: VALUE_COLOR,\n            showMark: false,\n          },\n        ]}\n        sx={{ '& .MuiLineChart-line[data-series=\"value\"]': { strokeWidth: 2.5 }, ...axisStyle }}\n      >\n        <MaxDrawdownPeriod annotate={false} />\n      </LineChart>\n      <LineChart\n        width={width}\n        height={drawdownPanelH}\n        skipAnimation\n        grid={{ horizontal: true }}\n        margin={{ top: 8, right: PANEL_MARGIN_X, bottom: 8, left: PANEL_MARGIN_X }}\n        xAxis={[\n          {\n            data: dates,\n            scaleType: \"time\",\n            label: DATE,\n            height: 64,\n            tickNumber: DATE_TICKS,\n            valueFormatter: (d) => d.toLocaleDateString(\"en-US\", { month: \"short\", year: \"numeric\" }),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"drawdown\",\n            min: yMin,\n            max: yMax,\n            label: \"Drawdown from running peak (%)\",\n            width: Y_AXIS_W,\n            valueFormatter: (v) => `${v.toFixed(0)}%`,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={[\n          {\n            id: \"drawdown\",\n            yAxisId: \"drawdown\",\n            data: drawdown,\n            label: \"Drawdown (%)\",\n            color: LOSS,\n            area: true,\n            showMark: false,\n            valueFormatter: (v) => `${v.toFixed(1)}%`,\n          },\n          {\n            id: \"trough\",\n            yAxisId: \"drawdown\",\n            data: troughSeries,\n            label: \"Maximum drawdown\",\n            color: LOSS,\n            showMark: true,\n            shape: \"circle\",\n            labelMarkType: \"circle\",\n          },\n          {\n            id: \"recovery\",\n            yAxisId: \"drawdown\",\n            data: recoverySeries,\n            label: `Recovery from a drawdown of ${markDepth.toFixed(1)}% or more`,\n            color: t.ink,\n            showMark: true,\n            shape: \"circle\",\n            labelMarkType: \"circle\",\n          },\n        ]}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"top\", horizontal: \"end\" },\n            sx: { fontSize: 15, color: t.inkSoft, pr: 4 },\n          },\n        }}\n        sx={{\n          '& .MuiLineChart-area[data-series=\"drawdown\"]': { fillOpacity: 0.35 },\n          '& .MuiLineChart-line[data-series=\"drawdown\"]': { strokeWidth: 2.5 },\n          '& .MuiLineChart-mark[data-series=\"trough\"]': { r: 8, fill: LOSS, stroke: t.pageBg, strokeWidth: 2.5 },\n          '& .MuiLineChart-mark[data-series=\"recovery\"]': { r: 7, fill: t.ink, stroke: t.pageBg, strokeWidth: 2.5 },\n          ...axisStyle,\n        }}\n      >\n        <ChartsReferenceLine y={0} axisId=\"drawdown\" lineStyle={{ stroke: t.ink, strokeWidth: 1.5 }} />\n        <MaxDrawdownPeriod annotate />\n      </LineChart>\n    </div>\n  );\n}\n"}