movingAverage function
Computes the simple moving average of a series.
data is the input time series.
window is the size of the moving window.
center if true, centers the window around each point (default: false).
Returns a list of the same length as data, with null for positions
where the window doesn't fit (at the edges).
Implementation
List<double?> movingAverage(
List<double> data, {
required int window,
bool center = false,
}) {
if (window < 1) {
throw ArgumentError('Window size must be at least 1');
}
if (data.isEmpty) {
return [];
}
final result = List<double?>.filled(data.length, null);
if (center) {
final halfWindow = window ~/ 2;
for (int i = halfWindow; i < data.length - (window - 1 - halfWindow); i++) {
double sum = 0;
for (int j = i - halfWindow; j < i - halfWindow + window; j++) {
sum += data[j];
}
result[i] = sum / window;
}
} else {
// Trailing window
for (int i = window - 1; i < data.length; i++) {
double sum = 0;
for (int j = i - window + 1; j <= i; j++) {
sum += data[j];
}
result[i] = sum / window;
}
}
return result;
}