{"spec_id":"indicator-bollinger","library":"d3","language":"javascript","code":"// anyplot.ai\n// indicator-bollinger: Bollinger Bands Indicator Chart\n// Library: d3 7.9.0 | JavaScript 22.23.2\n// Quality: 94/100 | Created: 2026-09-02\n\nconst t = window.ANYPLOT_TOKENS;\nconst { width, height } = window.ANYPLOT_SIZE;\nconst margin = { top: 100, right: 240, bottom: 80, left: 100 };\nconst iw = width - margin.left - margin.right;\nconst ih = height - margin.top - margin.bottom;\n\n// --- Data (in-memory, deterministic) ----------------------------------------\n// 120 trading days of a synthetic equity close price, generated with a fixed-\n// seed LCG random walk. A 20-day SMA + 2 stdev Bollinger envelope is computed\n// on top, with a deliberate volatility squeeze mid-series (day 55-70) so the\n// band-width contraction/expansion pattern called out in the spec is visible.\nlet seed = 20260902;\nfunction lcg() {\n  seed = (seed * 1664525 + 1013904223) % 4294967296;\n  return seed / 4294967296;\n}\n\nconst WINDOW = 20;\nconst N = 120;\nconst startDate = new Date(2024, 2, 1);\nconst dates = Array.from({ length: N }, (_, i) => {\n  const d = new Date(startDate);\n  d.setDate(d.getDate() + i);\n  return d;\n});\n\nconst close = [186.4];\nfor (let i = 1; i < N; i += 1) {\n  const squeeze = i >= 55 && i < 70 ? 0.35 : 1; // narrower shocks during the squeeze window\n  const drift = 0.12 + 0.35 * Math.sin(i / 22);\n  const shock = (lcg() - 0.5) * 5.5 * squeeze;\n  close.push(Math.max(60, close[i - 1] + drift + shock));\n}\n\nconst sma = new Array(N).fill(null);\nconst upper = new Array(N).fill(null);\nconst lower = new Array(N).fill(null);\nfor (let i = WINDOW - 1; i < N; i += 1) {\n  const windowSlice = close.slice(i - WINDOW + 1, i + 1);\n  const mean = d3.mean(windowSlice);\n  const std = d3.deviation(windowSlice);\n  sma[i] = mean;\n  upper[i] = mean + 2 * std;\n  lower[i] = mean - 2 * std;\n}\n\nconst data = dates.map((date, i) => ({ date, close: close[i], sma: sma[i], upper: upper[i], lower: lower[i] }));\nconst bandData = data.filter((d) => d.sma !== null);\n\n// --- SVG mount ---------------------------------------------------------------\nconst svg = d3.select(\"#container\").append(\"svg\").attr(\"width\", width).attr(\"height\", height);\nconst g = svg.append(\"g\").attr(\"transform\", `translate(${margin.left},${margin.top})`);\n\n// --- Scales --------------------------------------------------------------------\nconst x = d3.scaleTime().domain(d3.extent(dates)).range([0, iw]);\nconst y = d3\n  .scaleLinear()\n  .domain([d3.min(bandData, (d) => d.lower), d3.max(bandData, (d) => d.upper)])\n  .nice()\n  .range([ih, 0]);\n\n// --- Volatility squeeze annotation (spec-sanctioned callout) -------------------\n// The narrowed-shock window (day 55-69) feeds a trailing 20-day rolling stdev,\n// so the band itself doesn't visibly pinch until that window is fully inside\n// the trailing lookback — around day 67-77. Highlight where the band is\n// actually visibly narrow, not where the underlying shocks were dampened.\nconst squeezeX0 = x(dates[67]);\nconst squeezeX1 = x(dates[77]);\ng.append(\"rect\")\n  .attr(\"x\", squeezeX0)\n  .attr(\"y\", 0)\n  .attr(\"width\", squeezeX1 - squeezeX0)\n  .attr(\"height\", ih)\n  .attr(\"fill\", t.ink)\n  .attr(\"fill-opacity\", 0.05);\n\ng.append(\"text\")\n  .attr(\"x\", (squeezeX0 + squeezeX1) / 2)\n  .attr(\"y\", 18)\n  .attr(\"text-anchor\", \"middle\")\n  .attr(\"fill\", t.inkSoft)\n  .style(\"font-size\", \"13px\")\n  .style(\"font-style\", \"italic\")\n  .text(\"Volatility squeeze\");\n\n// --- Gridlines -----------------------------------------------------------------\ng.append(\"g\")\n  .attr(\"class\", \"grid\")\n  .call(d3.axisLeft(y).tickSize(-iw).tickFormat(\"\"))\n  .call((sel) => sel.select(\".domain\").remove())\n  .selectAll(\"line\")\n  .attr(\"stroke\", t.grid);\n\n// --- Band fill (semi-transparent, same color for both edges) -------------------\nconst bandCurve = d3.curveMonotoneX;\nconst area = d3\n  .area()\n  .x((d) => x(d.date))\n  .y0((d) => y(d.lower))\n  .y1((d) => y(d.upper))\n  .curve(bandCurve);\n\ng.append(\"path\").datum(bandData).attr(\"fill\", t.palette[1]).attr(\"fill-opacity\", 0.16).attr(\"d\", area);\n\nconst upperLine = d3.line().x((d) => x(d.date)).y((d) => y(d.upper)).curve(bandCurve);\ng.append(\"path\")\n  .datum(bandData)\n  .attr(\"fill\", \"none\")\n  .attr(\"stroke\", t.palette[1])\n  .attr(\"stroke-width\", 2.25)\n  .attr(\"d\", upperLine);\n\nconst lowerLine = d3.line().x((d) => x(d.date)).y((d) => y(d.lower)).curve(bandCurve);\ng.append(\"path\")\n  .datum(bandData)\n  .attr(\"fill\", \"none\")\n  .attr(\"stroke\", t.palette[1])\n  .attr(\"stroke-width\", 2.25)\n  .attr(\"d\", lowerLine);\n\n// --- Middle band (20-day SMA), dashed, ink-neutral reference line --------------\nconst smaLine = d3.line().x((d) => x(d.date)).y((d) => y(d.sma)).curve(bandCurve);\ng.append(\"path\")\n  .datum(bandData)\n  .attr(\"fill\", \"none\")\n  .attr(\"stroke\", t.ink)\n  .attr(\"stroke-width\", 2)\n  .attr(\"stroke-dasharray\", \"7,5\")\n  .attr(\"d\", smaLine);\n\n// --- Close price line (brand green, most prominent series) ---------------------\nconst closeLine = d3\n  .line()\n  .x((d) => x(d.date))\n  .y((d) => y(d.close))\n  .curve(d3.curveMonotoneX);\n\ng.append(\"path\").datum(data).attr(\"fill\", \"none\").attr(\"stroke\", t.palette[0]).attr(\"stroke-width\", 3).attr(\"d\", closeLine);\n\n// --- Axes ------------------------------------------------------------------\nconst xAxis = g\n  .append(\"g\")\n  .attr(\"transform\", `translate(0,${ih})`)\n  .call(d3.axisBottom(x).ticks(d3.timeWeek.every(2)).tickFormat(d3.timeFormat(\"%b %d\")));\nconst yAxis = g.append(\"g\").call(d3.axisLeft(y).ticks(6).tickFormat((d) => `$${d}`));\n\nfor (const ax of [xAxis, yAxis]) {\n  ax.selectAll(\"text\").attr(\"fill\", t.inkSoft).style(\"font-size\", \"14px\");\n  ax.selectAll(\"line\").attr(\"stroke\", t.inkSoft);\n  ax.select(\".domain\").attr(\"stroke\", t.inkSoft);\n}\nxAxis.selectAll(\"text\").attr(\"dy\", \"1.4em\");\n\n// --- Axis labels -------------------------------------------------------------\ng.append(\"text\")\n  .attr(\"x\", iw / 2)\n  .attr(\"y\", ih + 60)\n  .attr(\"text-anchor\", \"middle\")\n  .attr(\"fill\", t.inkSoft)\n  .style(\"font-size\", \"16px\")\n  .text(\"Trading Date\");\n\ng.append(\"text\")\n  .attr(\"transform\", \"rotate(-90)\")\n  .attr(\"x\", -ih / 2)\n  .attr(\"y\", -72)\n  .attr(\"text-anchor\", \"middle\")\n  .attr(\"fill\", t.inkSoft)\n  .style(\"font-size\", \"16px\")\n  .text(\"Closing Price (USD)\");\n\n// --- Legend --------------------------------------------------------------------\nconst legendItems = [\n  { label: \"Close price\", color: t.palette[0], dash: null },\n  { label: \"20-day SMA\", color: t.ink, dash: \"7,5\" },\n  { label: \"±2σ band\", color: t.palette[1], dash: null },\n];\n\nconst legend = svg.append(\"g\").attr(\"transform\", `translate(${margin.left + iw + 30}, ${margin.top + 20})`);\n\nconst legendRows = legend\n  .selectAll(\"g\")\n  .data(legendItems)\n  .join(\"g\")\n  .attr(\"transform\", (_, i) => `translate(0, ${i * 36})`);\n\nlegendRows\n  .append(\"line\")\n  .attr(\"x1\", 0)\n  .attr(\"x2\", 30)\n  .attr(\"y1\", 0)\n  .attr(\"y2\", 0)\n  .attr(\"stroke\", (d) => d.color)\n  .attr(\"stroke-width\", 3)\n  .attr(\"stroke-dasharray\", (d) => d.dash);\n\nlegendRows\n  .append(\"text\")\n  .attr(\"x\", 38)\n  .attr(\"y\", 5)\n  .attr(\"fill\", t.ink)\n  .style(\"font-size\", \"15px\")\n  .text((d) => d.label);\n\n// --- Title ---------------------------------------------------------------------\nconst title = \"indicator-bollinger · javascript · d3 · anyplot.ai\";\nconst titleFontSize = Math.round(22 * Math.min(1, 67 / title.length));\nsvg\n  .append(\"text\")\n  .attr(\"x\", width / 2)\n  .attr(\"y\", 50)\n  .attr(\"text-anchor\", \"middle\")\n  .attr(\"fill\", t.ink)\n  .style(\"font-size\", `${titleFontSize}px`)\n  .style(\"font-weight\", \"600\")\n  .style(\"letter-spacing\", \"0.3px\")\n  .text(title);\n\n// Brand-green accent rule under the title, echoing the primary close-price series\nsvg\n  .append(\"line\")\n  .attr(\"x1\", width / 2 - 42)\n  .attr(\"x2\", width / 2 + 42)\n  .attr(\"y1\", 66)\n  .attr(\"y2\", 66)\n  .attr(\"stroke\", t.palette[0])\n  .attr(\"stroke-width\", 3)\n  .attr(\"stroke-linecap\", \"round\");\n"}