Dear all guru,
I am trying to handle the Stock Closeprice data and unfortunately the kdb+ does not have exponential moving average built-in function. I found this thread very useful: https://groups.google.com/forum/?fromgroups=#!topic/personal-kdbplus/G7FgxzzKfnc/discussion And I found three ways to write the ema:
1. ema:{a:2%x+1;b:1-a;c:(+/x#y)%x;((x-1)#0n),c{a;b;x;y+b*x}[a;b]
- ema:{((x-1)#0n),i,{z+x*y}[i:avg x#y;1-a;(x _y)*a:2%1+x]}
3. ewma:{{y+x*z-y}[x:2%1+x][y]}
I am a newbie and do not understand the definition of all these three. But I certainly know the definition of EMA(StockPriceToday, nDay) = (StockPrice*2 + (nday - 1)*PreviousEMA) /(nDays + 1)
First of all, May some one explain how to simply READ the logic of three functions above? If you do not have time, may you share some links of documents about defining function with same level of complexity?
Secondly, May you have a a quick look and tell me which one consists with the definition I listed about EMA?
Thanks in advance.
Have a nice Weekend!!
Wenhao.SHE
I don’t have much info regarding which forms of EMA these functions
are taking but as for some info on how to read the logic:
//take this one for example
x:10000?10f
m:{((N-1)#0n),i,{z+x*y}[i:avg N#y;1-a;(N _y)*a:2%1+N]}
// first step is to break it down into basics
//reading right to left the output is a list comprising of
{…}[…] appended to
i appended to
((N-1)#0n)
//note the behaviour of scan "" for triadic functions
q){(x;y;z)}[1;2;3 4 5 6]
1 2 3
1 2 3 2 4
(1 2 3;2;4) 2 5
((1 2 3;2;4);2;5) 2 6
//starts with inputs 1,2,3 //initial calculation
//then the output is sent back into the function as the x param while
2 is again the y param and 4 becomes the z param
//then the output is sent back into the function as the x param while
2 is again the y param and 5 becomes the z param
// etc etc until all of the list 3 4 5 6 has been used up
//then breaking the function down to little pieces and reconstructing
using a while loop we would have something like
ma:{[N;data]
firstNdata:N#data;
dataExceptFirstN:(N _data);
i:avg firstNdata;
a:2%1+N;
index:1;
output:first[dataExceptFirstN*a]+i*1-a; //initial calculation
while[index output:output,((dataExceptFirstN*a) index)+last[output]*1-a;
index:index+1;
];
((N-1)#0n),i,output
}
q)m[100;x]~ma[100;x]
1b
Obviously, this version is not at all efficient! Do not use, it’s just
for demonstration purposes.
The other functions could be broken down similarly