components/tanstack-charts/area/bollinger-band.tsx
import { type ChartPoint, areaY, defineChart, deviation, lineY, rollingWindow } from "@tanstack/charts";
import { motion } from "@tanstack/charts/motion";
import { tooltip } from "@tanstack/charts/tooltip";
import { Chart } from "@tanstack/react-charts/core";
import { useMemo } from "react";
import { scaleLinear, scaleUtc } from "d3-scale";
import { Activity } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface StockCloseDatum {
Date: Date;
Close: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateDemoData(): StockCloseDatum[] {
const baseDate = new Date(2025, 0, 1);
return Array.from({ length: 40 }, (_, i) => {
const d = new Date(baseDate);
d.setDate(baseDate.getDate() + i);
const close = 180 + Math.sin(i * 0.3) * 15 + Math.cos(i * 0.7) * 8 + i * 0.5;
return { Date: d, Close: close };
});
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as any;
if (!d) return { title: "", rows: [] };
const dateStr = d.Date ? d.Date.toLocaleDateString("en-US", { month: "short", day: "numeric" }) : "";
const mean = d.meanClose ? d.meanClose.toFixed(2) : "0.00";
const dev = d.closeDeviation ? (d.closeDeviation * 2).toFixed(2) : "0.00";
return {
title: dateStr,
rows: [
{ label: "20-day SMA", value: `$${mean}`, color: "var(--chart-1)" },
{ label: "Volatility Band (±2σ)", value: `±$${dev}`, color: "var(--chart-2)" },
],
};
}
export function BollingerBand() {
const rawData = useMemo(() => generateDemoData(), []);
const data = useMemo(() => {
return rollingWindow(rawData, {
size: 20,
orderBy: "Date",
anchor: "end",
partial: false,
outputs: {
meanClose: { value: "Close", reduce: "mean" },
closeDeviation: { value: "Close", reduce: deviation },
},
});
}, [rawData]);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
areaY(data, {
id: "bollinger-band-area",
x: "Date",
y1: (row: any) => row.meanClose - row.closeDeviation * 2,
y2: (row: any) => row.meanClose + row.closeDeviation * 2,
fill: "var(--chart-1)",
fillOpacity: 0.18,
}),
lineY(data, {
id: "bollinger-mean-line",
x: "Date",
y: "meanClose",
stroke: "var(--chart-1)",
strokeWidth: 2.25,
}),
],
scales: {
x: {
scale: scaleUtc,
axis: {
line: false,
label: "Date",
ticks: {
size: 0,
padding: 10,
format: (d: Date) =>
d.toLocaleDateString("en-US", { month: "short", day: "numeric" }),
},
},
},
y: {
scale: scaleLinear().domain([160, 220]),
grid: true,
axis: {
line: false,
label: "Price ($)",
ticks: { size: 0 },
},
},
},
margin: { top: 24, right: 24, bottom: 32, left: 45 },
theme: {
foreground: "var(--muted-foreground)",
grid: "var(--border)",
background: "transparent",
},
},
{
focus: "group-x",
tooltip: {
use: tooltip,
className:
"font-sans shadow-none rounded-md bg-popover text-popover-foreground border p-2 text-xs",
anchor: "group-center",
placement: "auto",
content: (points) => shadcnTooltipContent(points),
},
},
),
[data],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Bollinger Volatility Bands</CardTitle>
<CardDescription>20-day simple moving average bounded by ±2 standard deviation bands</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Bollinger Volatility Bands Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Asset price trades securely within 2-sigma volatility envelope{" "}
<Activity className="h-4 w-4 text-purple-500" />
</div>
<div className="text-muted-foreground leading-none">
Band width expands during high volatility and contracts during consolidation
</div>
</CardFooter>
</Card>
);
}
export default BollingerBand;