Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save requaos/a5ffd522fa372b452773c756d7553ba3 to your computer and use it in GitHub Desktop.
Save requaos/a5ffd522fa372b452773c756d7553ba3 to your computer and use it in GitHub Desktop.
-- From: https://stackoverflow.com/questions/8871426/how-to-calculate-an-exponential-moving-average-on-postgres
start transaction;
create or replace function ema_func(state numeric, inval numeric, alpha numeric)
returns numeric
language plpgsql as $$
begin
return case
when state is null then inval
else alpha * inval + (1-alpha) * state
end;
end
$$;
drop aggregate if exists ema(numeric, numeric);
create aggregate ema(numeric, numeric) (sfunc = ema_func, stype = numeric);
commit transaction;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment