简体   繁体   中英

calculate Exponential Moving average using sql

month   prices
10  $25.15
11  $41.53
12  $72.19
13  $33.16
14  $33.95
15  $43.87

I have to calculate exponential moving average using above data in sql . I have no idea how to do. TIA

PS: EMA(n)   =  EMA(n−1) + ( ( 2 / ( n + 1 ) ) × ( P(n) − EMA(n−1) ) )

above is the formula where we can take n = 6;

The most problematic part of your task is the calculation of aggregate Product in pure SQL (as FYI: there are many standard aggregate functions, like Sum(), Min(), Max(), etc. but no Product P()). One possible solution described in: Aggregate Product function extends SQL ( http://www.codeproject.com/Tips/137564/Aggregate-Product-function-extends-SQL ) is based on math equation:

N           N
P(Xi)= Exp(SUM(Log(Xi)))
i=1         i=1

which translated into following SQL statement:

SELECT Exp(Sum(IIf([Num]=0,0,Log([Num]))))*IIf(Min([Num])=0,0,1) AS P
FROM Table1

You can apply this solution to your problem. In order to calculate the running (moving) avg you may build the self-join of the data Table and apply the computation for all rows previous to the current. The actual implementation will depend on the particular Database you are using.

Hope this may help.

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