Operations on Lists (Iterators & Amend) · General · Practice Question
Calculate Running PnL Using Scan
Question
A trader's realized PnL for five trades is:
pnl:100 -20 50 -10 30Calculate the cumulative PnL after each trade.
Expected result:
100 80 130 120 150Solution
{x+y}\[0;pnl]Alternative Solution
sums pnlExplanation
The scan iterator:
\returns the result of every iteration.
The expression:
{x+y}\[0;pnl]starts with:
0and then accumulates each value from the list:
0+100
100-20
80+50
130-10
120+30producing:
100 80 130 120 150Notice 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:
sumsis implemented using the same concept and produces the same result:
sums pnlreturns:
100 80 130 120 150