rollingCorrelation function

List<double> rollingCorrelation(
  1. List<num> x,
  2. List<num> y,
  3. int window
)

Pearson correlation of x and y over each sliding window of window.

x and y must be the same length and window must be at least 2 (a single point has no variance); both are enforced by assertions. The output has length x.length - window + 1, and is empty when the series is shorter than one window. Each entry is the correlation of the corresponding window, or NaN where a window has zero variance (a constant run) and correlation is undefined.

Example:

rollingCorrelation(<num>[1, 2, 3, 4], <num>[2, 4, 6, 8], 3); // [1.0, 1.0]

Audited: 2026-06-12 11:26 EDT

Implementation

List<double> rollingCorrelation(List<num> x, List<num> y, int window) {
  // Validate with if-throw, not assert: asserts are stripped from release
  // builds, so a mismatched-length or tiny-window call would silently read
  // out of bounds in production instead of failing fast.
  if (x.length != y.length) {
    throw ArgumentError('rollingCorrelation requires equal-length series');
  }
  if (window < 2) {
    throw ArgumentError.value(window, 'window', 'must be >= 2');
  }
  // No full window fits, so there are no correlations to emit.
  if (x.length < window) return <double>[];
  final List<double> out = <double>[];
  for (int start = 0; start + window <= x.length; start++) {
    out.add(_windowCorrelation(x, y, start, window));
  }
  return out;
}