computeMA static method

List<double?> computeMA(
  1. List<CandleData> data, [
  2. int period = 7
])

Implementation

static List<double?> computeMA(List<CandleData> data, [int period = 7]) {
  // If data is not at least twice as long as the period, return nulls.
  if (data.length < period * 2) return List.filled(data.length, null);

  final List<double?> result = [];
  // Skip the first [period] data points. For example, skip 7 data points.
  final firstPeriod =
      data.take(period).map((d) => d.close).whereType<double>();
  double ma = firstPeriod.reduce((a, b) => a + b) / firstPeriod.length;
  result.addAll(List.filled(period, null));

  // Compute the moving average for the rest of the data points.
  for (int i = period; i < data.length; i++) {
    final curr = data[i].close;
    final prev = data[i - period].close;
    if (curr != null && prev != null) {
      ma = (ma * period + curr - prev) / period;
      result.add(ma);
    } else {
      result.add(null);
    }
  }
  return result;
}