Jason_L
Jason_L

Reputation: 589

KDB - Automatic function argument behavior with Iterators

I'm struggling to understand the behavior of the arguments in the below scan function. I understand the EWMA calc and have made an Excel worksheet to match in an attempt to try to understand but the kdb syntax is throwing me off in terms of what (and when) is x,y and z. I've referenced Q for Mortals, books and https://code.kx.com/q/ref/over/ and I do understand whats going on in the simpler examples provided.

I understand the EWMA formula based on the Excel calc but how is that translated into the function below? x = constant, y= passed in values (but also appears to be prior result?) and z= (prev period?)

ewma: {{(y*1-x)+(z*x)} [x]\[y]}; 
ewma [.25; 15 20 25 30 35f]
15 16.25 18.4375 21.32813 24.74609

Rearranging terms makes it easier to read but if I were write this in Excel, I would incorrectly reference the y value column in the addition operator instead of correctly referencing the prev EWMA value.

ewma: {{y+x*z-y} [x]\[y]};  
ewma [.25; 15 20 25 30 35f]
15 16.25 18.4375 21.32813 24.74609

EWMA in Excel formula for auditing Excel formula for EWMA

Upvotes: 0

Views: 183

Answers (1)

Michael McParland
Michael McParland

Reputation: 906

0N! is useful in these cases for determining variables passed. Simply add to start of function to display variable in console. EG. to show what z is being passed in as each run:

        q)ewma: {{0N!z;(y*1-x)+(z*x)} [x]\[y]};
        q)ewma [.25; 15 20 25 30 35f]
        15f
        16.25
        18.4375
        21.32812
        
        //Or multiple at once
        q)ewma: {{0N!(x;y;z);(y*1-x)+(z*x)} [x]\[y]};
        q)
        q)ewma [.25; 15 20 25 30 35f]
        0.25 15 20
        0.25 16.25 25
        0.25 18.4375 30
        0.25 21.32812 35

Edit:

To think about why z is holding 'y' values it is best to think about below simplified example using just x/y.

//two parameters specified in beginning. 
//x initialised as 1 then takes the function result for next run
//y takes value of next value in list
q){0N!(x;y);x+y}\[1;2 3 4]
1 2
3 3
6 4
3 6 10
//in this example only one parameter is passed
//but q takes first value in list as x in this special case
q){0N!(x;y);x+y}\[1 2 3 4]
1 2
3 3
6 4
1 3 6 10

A similar occurrence is happening in your example. x is not being passed to the the iterator and therefore will assume the same value in each run.

The inner function y value will be initilised taking the first value of the outer y variable (15f in this case) like above simplified example. Then the z takes the 2nd value of the list for it's initial run. y then takes the result of previous function run and z takes the next value in the list until how list has bee passed to function.

Upvotes: 2

Related Questions