exponential moving average function for Q

911 views
Skip to first unread message

Wind

unread,
Apr 9, 2009, 11:10:17 PM4/9/09
to Kdb+ Personal Developers
I have found the ema function from the kxforums.com. But there is
some error. Maybe because of the difference between K and Q. Can
anybody help change the function for Q?

/ the original function for exponential moving average
[code:1]\ema:{a:2%x+1;b:1-a;c:(+/x#y)%x;((x-1)#0n),c{(a*y)+b*x}\x _ y}
[/code:1]

I have changed it to the following format, but the "/" maybe should
also be replaced:
ema:{[x;y] a:2%x+1;b:1-a;c:(+/x#y)%x;((x-1)#0n),c{(a*y)+b*x}\x _ y};

Thanks.

Wind

Niall Dalton

unread,
Apr 9, 2009, 11:46:07 PM4/9/09
to personal...@googlegroups.com
Untested, but something like ema:{[x;y]b:1-a:2%x+1;c:(sum x#y)%x;
((x-1)#0n),c,c{[a;b;c;d](a*d)+b*c}[a;b]\x _y} should provide a
starting point.

Aaron Davies

unread,
Apr 10, 2009, 12:26:10 AM4/10/09
to personal...@googlegroups.com
On Apr 10, 2009, at 11:10 AM, Wind wrote:

> ema:{a:2%x+1;b:1-a;c:(+/x#y)%x;((x-1)#0n),c{(a*y)+b*x}\x _ y}

here's a direct port from to k4:

k)ema:{a:2%x+1;b:1-a;c:(+/x#y)%x;((x-1)#0n),c{[a;b;x;y](a*y)+b*x}[a;b]
\x _ y}

k3 must have made locals available to nested lambdas

Wind

unread,
Apr 10, 2009, 1:58:05 AM4/10/09
to Kdb+ Personal Developers
I copied Nial's ema function directly. It works well and is exactly
what I need.
Thanks Niall and Aaron.

Attila Vrabecz

unread,
Apr 10, 2009, 4:30:34 AM4/10/09
to personal...@googlegroups.com
m:{((x-1)#0n),i,{z+x*y}\[i:avg x#y;1-a;(x _y)*a:2%1+x]}
is a bit faster

q)x:1000000?10f
q)\t ema[100;x]
750
q)\t m[100;x]
531
Attila

Xi Chen

unread,
Apr 10, 2009, 11:26:35 AM4/10/09
to personal...@googlegroups.com
if just want the first one as intial value, one can  use
ewma:{{y+x*z-y}[x:2%1+x]\[y]}
Xi

Wind

unread,
Apr 11, 2009, 8:13:56 AM4/11/09
to Kdb+ Personal Developers
I tried Xi and Attila's methods. All are perfect q codes.
Thanks again.



On Apr 10, 11:26 pm, Xi Chen <heydic...@gmail.com> wrote:
> if just want the first one as intial value, one can  use
> ewma:{{y+x*z-y}[x:2%1+x]\[y]}
> Xi
>
> On Fri, Apr 10, 2009 at 9:30 AM, Attila Vrabecz <attila.vrab...@gmail.com>wrote:
>
>
>
> > m:{((x-1)#0n),i,{z+x*y}\[i:avg x#y;1-a;(x _y)*a:2%1+x]}
> > is a bit faster
>
> > q)x:1000000?10f
> > q)\t ema[100;x]
> > 750
> > q)\t m[100;x]
> > 531
> >  Attila
>
Reply all
Reply to author
Forward
0 new messages