Some useful kdb Q commands
Here is a cheat sheet to help
Here is the official Reference doc
Recall in Q we work right to left !
? uses and some overloads
q)5?10 // 5 random numbers upto 10
8 1 9 5 4
q)5?til 20 // 5 random 1 to 20
6 1 5 4 13
q)5?10+ til 20
21 15 16 11 15
q)2?`a`b`c`d // deal 2 from list
`c`b
q)?[11011b;"black";"flock"] // binary check show where true left false right
"block"
the ? can also be a find
?[1 4 5 5 6 7;5] //first occurance of 5
1 4 5 5 6 7?5 //infix - where is the first occurance of 5 in this list
each left each right
q)"abcde",\:"XY" / Each Left
"aXY"
"bXY"
"cXY"
"dXY"
"eXY"
q)"abcde",/:"XY" / Each Right
"abcdeX"
"abcdeY"
Do and While
do[NoOfTimes;expression;...;expressionN]
\t do[10;a*a:til 100000]
\t:10 a*a:til 100000 //Same as above - an example of the more "q" way!
from the kx academy an example of do
while[condition;expression;...;expressionN]
r:1 1
x:10
while[x-:1;r,:sum -2#r]
r //you may recognise this as the Fibonacci sequence!
not to be confused with
{x, sum -2#x}\[10;1 1 ] // iterate 10 times starting with 1 1
@ trap
q)@[sin;`symbol;{[error] -2 "Error signal received:",error;}]
Error signal received:type
q)@[sin;1;{[error] -2 "Error signal received:",error;}]
0.841471
q)@[max; 1 1;{[error] -2 "Error signal received:",error;}]
1
the trap @ takes the function here sin or max and provides the arguments and an error function if there is a problem which takes only 1 arg the fun is in line ie: {[error] -2 "Error signal received:",error;}
@ find and @ amend
show L: 10?20 // 10 nuts 1 to 20
@[L; 1 2] //find index 1 and 2
@[L; ::; neg] //amend the list to apply single argument function
@[L; ::; + ; 2] //amend the list at the null index (all indexes) to add 2 to each
L
results are
-4 -12 -13 -1 -2 -17 -5 0 -1 -19
6 14 15 3 4 19 7 2 3 21
4 12 13 1 2 17 5 0 1 19
Also you can amend a list with @ and .
q))l: 1 2 3
q))@[l; 1; :; 55] // amend pos 1 with 55 the : is assigning 55 to pos 1
1 55 3
q))ll: (1 2 3; 100 200 300)
q)).[ll; 1 1 ; : ; 55 ] // amend pos 1 1 at depth as ll is matrix again assign : val 55
1 2 3
100 55 300
. and protected evaluation
Imagine you want to add two things and write to an err file if things go bad ie add symbol to int
LOG_HANDLE: hopen `:myLog.txt
protectedAdd:{.[+;(x;y);
{[err] errorMsg: string[.z.p],"| ERROR | protectedAdd failed with error:",err;
neg[LOG_HANDLE] errorMsg; 0b }]};
protectedAdd[1;2] //works fine without logging
protectedAdd[1;"123"] //returns 0b and we see a message in our file
read0 `:myLog.txt
We have a + and 2 args x,y and a single arg error function which writes to a file because it writes neg[handle] it adds a new line
this is similar to @ trap
' raise your own exceptions
q){[]a:10;b:`this; '"Bad types"; a+b }[]
'Bad types
[0] {[]a:10;b:`this; '"Bad types"; a+b }[]
^
The error was raised before the a+b which would have blown on type
if Example
x:10;
if[.z.t > 12:00:00 ;1"Evaluating within the if ... ";
x:x+1; //incrementing x
y:10; //defining new variable y
-1"Complete";
y] //note there is no value returned from an if!
x //checking if x is incrementing
Note 1".." write to console and -1"…" write to stdout if runs all statements in the if
If has to be wrapped in a function if you want to return something
Simple if-else
$[1b;upper string `hey;string `hey] //if[condition;ifTrueStatement;ifFalseStatement]
hsym/key
q)hsym `mypath //make symbol a path
`:mypath
q)key `:. //list files in .
`.DS_Store`Basics.q`README.md`a`hello.q`kc.lic`kc.lic.2022`kc.lic.old`kxpassw..
q)
Create a Path using sv
Given directory here . and date as string and symbol of trade table create a path
essentially given the symbols it will create one symbol with / to use as filename first symbol must start with :
q))` sv (`:.;`$"2022.01.01";`trade)
`:./2022.01.01/trade
pathToTable:{[dir;date;tab]
` sv (dir;`$string date;tab)}
pathToTable[`:.;2020.01.01;`trade]
Load and save table
q))mytable:([]x:`a`b`c;y:1 2 3 ) //create table
q))`:mytable set mytable // set saves table note the `:
`:mytable
q))res:get `:mytable //gets the table assigns : to res
q))res
x y
---
a 1
b 2
c 3
q))
xbar to Query around intervals
If you have a quote table with bud ask and time you can query in 1 hour intervals
show h: hopen 5050
h "select spread: avg ask-bid by 1 xbar time.hh from quote"
h "select spread: avg ask-bid by 0D01:00:00.000 xbar time from quote"
Select using a list of symbols
syList:`JPM`GE
show "select from trade where sym in ","`","`" sv string symList //as a string
h "select from trade where sym in ","`","`" sv string symList //sending to the remote process