components/tanstack-charts/line/lag-autocorrelation.tsx
import { type ChartPoint, defineChart, dot, first, 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 } from "d3-scale";
import { Activity } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface StockDatum {
Date: Date;
Close: number;
}
interface LagRow {
Date: Date;
Close: number;
PreviousClose: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateDemoData(): StockDatum[] {
const results: StockDatum[] = [];
let price = 150;
for (let i = 0; i < 90; i++) {
const date = new Date(Date.UTC(2024, 0, 1 + i));
price += (Math.random() - 0.48) * 3;
price = Math.max(130, Math.min(200, price));
results.push({ Date: date, Close: Number(price.toFixed(2)) });
}
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as LagRow;
if (!d || d.PreviousClose === undefined) return { title: "", rows: [] };
return {
title: d.Date.toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" }),
rows: [
{ label: "Previous Close (t-1)", value: `$${d.PreviousClose.toFixed(2)}`, color: "var(--chart-2)" },
{ label: "Current Close (t)", value: `$${d.Close.toFixed(2)}`, color: "var(--chart-1)" },
],
};
}
export function LagAutocorrelation() {
const rawData = useMemo(() => generateDemoData(), []);
const lagRows = useMemo(() => {
return rollingWindow(rawData, {
size: 2,
orderBy: "Date",
partial: false,
outputs: { PreviousClose: { value: "Close", reduce: first } },
}) as unknown as LagRow[];
}, [rawData]);
const identityLine = useMemo(
() => [
{ PreviousClose: 130, Close: 130 },
{ PreviousClose: 200, Close: 200 },
],
[],
);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
lineY(identityLine, {
x: "PreviousClose",
y: "Close",
stroke: "var(--muted-foreground)",
strokeDasharray: "5,4",
}),
dot(lagRows, {
x: "PreviousClose",
y: "Close",
fill: "var(--chart-1)",
fillOpacity: 0.8,
r: 4,
}),
],
scales: {
x: {
scale: scaleLinear().domain([130, 200]),
grid: true,
axis: { label: "Previous Close $ (t-1)" },
},
y: {
scale: scaleLinear().domain([130, 200]),
grid: true,
axis: { label: "Current Close $ (t)" },
},
},
margin: { top: 24, right: 24, bottom: 32, left: 45 },
theme: {
foreground: "var(--muted-foreground)",
grid: "var(--border)",
background: "transparent",
},
},
{
keyboard: true,
tooltip: {
use: tooltip,
className:
"font-sans shadow-none rounded-md bg-popover text-popover-foreground border p-2 text-xs",
anchor: "pointer",
placement: "auto",
content: (points) => shadcnTooltipContent(points),
},
},
),
[lagRows, identityLine],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Lag-One Autocorrelation Scatter</CardTitle>
<CardDescription>Scatter plot comparing current value t against previous timestep t-1</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Lag-One Autocorrelation Scatter Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Strong linear clustering along identity 45° line <Activity className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
High lag-1 autocorrelation confirms persistent daily stock price inertia
</div>
</CardFooter>
</Card>
);
}
export default LagAutocorrelation;