PromQL Exponential Moving Average (EMA)
package main import ( "fmt" "math" "time" ) // calculateEMA computes the Exponential Moving Average (EMA) for a given series of values. // EMA is calculated using the formula: EMA_today = (Value_today * alpha) + (EMA_yesterday * (1 - alpha)) // where alpha is the smoothing factor...
This Go program calculates the Exponential Moving Average (EMA) for a series of numerical data points, optionally associated with timestamps. EMA is a type of moving average that places a greater weight and significance...
The `calculateEMA` function computes the EMA for a slice of float64 values given a `period`. It first validates that the `period` is positive. If the input `values` slice is empty, it returns an empty slice. The smoothing factor `alpha` is calculated as `2 / (period + 1)`. The first EMA value is initialized with the first data point. Subsequent EMA values are calculated iteratively using the formula: `EMA_today = (Value_today * alpha) + (EMA_yesterday * (1 - alpha))`. The `calculateEMAWithTimestamps` function is a helper that sorts data points by timestamp before applying the core EMA calculation, returning the results mapped back to their original timestamps. The time complexity for `calculateEMA` is O(N), where N is the number of data points, due to a single pass. The `calculateEMAWithTimestamps` function adds O(N log N) for sorting timestamps. Space complexity for `calculateEMA` is O(N) for the result slice, and for `calculateEMAWithTimestamps` it's O(N) for storing sorted timestamps, values, and the result map.
FUNCTION calculateEMA(values, period): IF period <= 0 THEN RETURN error "Period must be positive" END IF IF values is empty THEN RETURN empty list END IF alpha = 2.0 / (period + 1). emaResults = list of same size as valu...