# Online algorithm for calculating EWMA at irregular intervals?

What is a fast online algorithm for calculating the EWMA (exponentially weighted moving average) of an input variable observed at irregular intervals?

I know the formula for when sampling at regular intervals:

Calculating alpha from halflife:

$$\alpha = 1 - e^{\frac{\ln{.5}}{H}}$$

Calculating the EWMA of x:

$$E = \alpha\cdot x + (1-\alpha)\cdot E_{-1}$$

What is an algorithm for doing the same where the sampling interval is irregular?

Edit:

I have found an algorithm online, which purports to achieve an irregular EWMA.

double operator()(double x)
{
if (isnan(prev_ewma_)) // we don't decay the first sample
{
prev_ewma_ = x;
prev_time_ = Time::now();
return x;
}

double time_decay = Time::now() - prev_time_;

double alpha = 1 - std::exp(-time_decay / halflife_);
double ewma  = alpha * x + (1 - alpha) * prev_ewma_;

prev_ewma_ = ewma;
prev_time_ = now;
return ewma;
}


Is this algorithm correct?

• Note that what is $\alpha$ in this code is $1-\alpha$ in your post (and vice versa). Other than that it looks OK to me. – noob2 Aug 31 '17 at 18:21
• @noob2 I think that's because alpha in the code is calculated as exp(...), whereas in the formula it is 1 - exp(...) – Steve Lorimer Aug 31 '17 at 18:24
• Besides this code you also need to decide what to do when you need EWMA value between observations. E.g. you observed a couple of values long ago and now need an up to date EWMA value. Do you decay them to zero or not. – LazyCat Aug 31 '17 at 18:44
• @LazyCat good point - I hadn't thought of that – Steve Lorimer Aug 31 '17 at 18:47
• @noob2 I've updated the code to reflect your comment – Steve Lorimer Aug 31 '17 at 18:49