Back to General

Operations on Lists (Iterators & Amend) · General · Practice Question

Calculate Price Changes Using Each-Prior

Sign in to track your progress

Question

Given the following sequence of trade prices:

prices:103.20 103.21 103.22 103.15 102.15 101.95

Calculate the change in price between each trade and the previous trade.

Expected result:

0n 0.01 0.01 -0.07 -1 -0.2

Solution

{x-y}':[prices]

Alternative Solution

prices-prev prices

Explanation

The each-prior iterator:

':

allows a two-argument function to be applied to each item in a list together with its previous item.

In the expression:

{x-y}':[prices]

the function:

{x-y}

is applied as follows:

103.20 - 0n
103.21 - 103.20
103.22 - 103.21
103.15 - 103.22
102.15 - 103.15
101.95 - 102.15

producing:

0n 0.01 0.01 -0.07 -1 -0.2

The first result is null because there is no previous value for the first element, so the lambda receives a null as its y. (The built-in deltas is similar, but returns the first price itself as its first item: deltas prices gives 103.2 0.01 0.01 -0.07 -1 -0.2.)

This pattern is commonly used in finance to calculate:

  • Tick-to-tick price changes
  • Spread changes
  • Position changes
  • Inventory deltas

The alternative solution:

prices-prev prices

produces the same result using the built-in prev function.