Search code examples
loopsfor-loopkdb

kdb/q For/Do Loop with multiple variable inputs


I have a function created below:

// Country Date -> Date
// given a country and a date, provides the next business day
// ex. fNextBDay[`US; 2024.02.02] -> 2024.02.05
fNextBDay:{[c; d] ...}

I am trying to loop this function so that it gives me the next x number of business days.

I'm able to loop with just one variable:

{x; fNextBDay[`US; x]} \ [5; 2024.02.02]
// output: 2024.02.02 2024.02.05 2024.02.06 2024.02.07 2024.02.08 2024.02.09

However, I don't know how I can then abstract the country variable. I tried these lines:

1. {x y; fNextBDay[x;y]} \ [5; `US 2024.02.02] -> gives me an error at `US
2. {x y; fNextBDay[x;y]} \ [5; (`US;2024.02.02)] -> gives me this error: "Cannot write to handle 5. OS reports: The request is not supported."
3. {x; fNextBDay[x]} \ [5; (`XNSE;2024.02.06)] -> just returns the function's code

Does anyone know how I can abstract out both variables in the loop? I'm thinking it's a syntax issue that I'm not getting.


Solution

  • You can project the country variable into the function prior to the iterator \, e.g

    q)fNextBDay:{y+1+`US<>x};
    q){x; fNextBDay[y;x]}[;`US]\ [5; 2024.02.02]
    2024.02.02 2024.02.03 2024.02.04 2024.02.05 2024.02.06 2024.02.07
    q){x; fNextBDay[y;x]}[;`FR]\ [5; 2024.02.02]
    2024.02.02 2024.02.04 2024.02.06 2024.02.08 2024.02.10 2024.02.12
    
    or more simply
    q)fNextBDay[`US]\[5;2024.02.02]
    2024.02.02 2024.02.03 2024.02.04 2024.02.05 2024.02.06 2024.02.07
    q)fNextBDay[`FR]\[5;2024.02.02]
    2024.02.02 2024.02.04 2024.02.06 2024.02.08 2024.02.10 2024.02.12