exponentialMovingAverage function

List<double> exponentialMovingAverage(
  1. List<double> data, {
  2. required double alpha,
})

Computes the exponential moving average of a series.

data is the input time series. alpha is the smoothing factor (0 < alpha <= 1). Higher alpha gives more weight to recent values.

Returns a list of the same length as data.

Implementation

List<double> exponentialMovingAverage(
  List<double> data, {
  required double alpha,
}) {
  if (alpha <= 0 || alpha > 1) {
    throw ArgumentError('Alpha must be in (0, 1]');
  }
  if (data.isEmpty) {
    return [];
  }

  final result = List<double>.filled(data.length, 0);
  result[0] = data[0];

  for (int i = 1; i < data.length; i++) {
    result[i] = alpha * data[i] + (1 - alpha) * result[i - 1];
  }

  return result;
}