简体   繁体   中英

mysql calculate 5 day exponential moving average

I have the following query which calculates a 5 day simple moving average. I want to change query to a 5 day exponential moving average

DROP TABLE IF EXISTS t; 
CREATE TABLE t (id int,item int, dt DATE, qty INT); 
INSERT INTO t VALUES 
(1,1,'2007-1-1',5), 
(2,1,'2007-1-2',6), 
(3,1,'2007-1-3',7), 
(4,1,'2007-1-4',8), 
(5,1,'2007-1-5',9), 
(6,1,'2007-1-6',10), 
(7,1,'2007-1-7',11), 
(8,1,'2007-1-8',12), 
(9,1,'2007-1-9',13), 
(10,2,'2007-1-1',6), 
(11,2,'2007-1-2',7), 
(12,2,'2007-1-3',8), 
(13,2,'2007-1-4',9), 
(14,2,'2007-1-5',10), 
(15,2,'2007-1-6',11), 
(16,2,'2007-1-7',12), 
(17,2,'2007-1-8',13), 
(18,2,'2007-1-9',14); 

SELECT  
t1.id,t1.item,t1.dt,t1.qty,
( SELECT SUM(t2.qty) / COUNT(t2.qty) 
  FROM t AS t2 
  WHERE t1.id - t2.id =4 
) AS '5daySMA' 
FROM t AS t1 
GROUP BY t1.item,t1.dt;

What should query be?

My stab at this:

select dt,
  @a := ( @a*.667 + qty*.333)  AS moving_avg
from t
Join (select @a := 0) as X
order by dt desc

.333 is k = 2/(N+1) where N is 5 day period

.667 is (1-k) as seen EMA formula

EMA = Price(t) * k + EMA(y) * (1 – k)

@a := 0 part should be changed to reasonable # otherwise there will be a skew in the beggining

Derived from this discussion, so you can look for more details there http://grokbase.com/t/mysql/mysql/127gbqzkyj/trouble-with-average

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM