Back to General

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

Calculate Running PnL Using Scan

Sign in to track your progress

Question

A trader's realized PnL for five trades is:

pnl:100 -20 50 -10 30

Calculate the cumulative PnL after each trade.

Expected result:

100 80 130 120 150

Solution

{x+y}\[0;pnl]

Alternative Solution

sums pnl

Explanation

The scan iterator:

\

returns the result of every iteration.

The expression:

{x+y}\[0;pnl]

starts with:

0

and then accumulates each value from the list:

0+100
100-20
80+50
130-10
120+30

producing:

100 80 130 120 150

Notice that every intermediate result is returned.

This is useful whenever a running total is required.

Examples include:

  • Running PnL
  • Running inventory
  • Running cash balance
  • Cumulative traded volume

The built-in function:

sums

is implemented using the same concept and produces the same result:

sums pnl

returns:

100 80 130 120 150