File Parsing · General · Practice Question
Decode Text
Question
A trader starts the day with a position of 125 lots in a futures contract.
Throughout the trading session, position updates are recorded in a text file as a single semicolon-separated string:
U10;D5;U20;D15;D10;U25;D5;U30Each update consists of a direction and a quantity:
Uindicates the trader's position increased by the specified number of lots.Dindicates the trader's position decreased by the specified number of lots.
Write a q expression to read the file and calculate the trader's final position.
Solution
txt:first read0 `:file.txt
items:";" vs txt
sign:(1 -1) "UD"?1#'items
qty:"J"$1_'items
125 + sum sign * qtyAlternative Solution
txt:first read0 `:file.txt
125 + sum value ssr/[txt;("U";"D";";");(" ";"-";",")]Explanation
First, read the contents of the file:
txt:first read0 `:file.txtThis returns:
"U10;D5;U20;D15;D10;U25;D5;U30"Next, split the string into individual updates:
items:";" vs txtResult:
"U10"
"D5"
"U20"
"D15"
"D10"
"U25"
"D5"
"U30"Extract the direction from each update and convert it into a sign:
sign:(1 -1) "UD"?1#'itemsExtract the numeric quantities:
qty:"J"$1_'itemsMultiply each quantity by its sign and calculate the total change:
sum sign * qtyResult:
50Finally, add the net change to the trader's starting position:
125 + 50Result:
175The alternative solution uses ssr to rewrite the original text into a q expression:
ssr/[txt;("U";"D";";");(" ";"-";",")]This converts:
"U10;D5;U20;D15;D10;U25;D5;U30"into:
" 10,-5, 20,-15,-10, 25,-5, 30"Then value evaluates the string as a numeric list, and sum calculates the net position change.
The trader's final position is 175 lots.