~/problems / Trading systems / Market and strategy simulations

Basics: position, cash and PnL from fills

easy basics ~10 min

Every trading simulation keeps the same three numbers up to date: your position (shares held; negative means short), your cash, and your PnL (profit and loss). Get this bookkeeping right first; strategies and backtests are built on top of it.

Implement mark_to_market(fills, last_price):

  • You start flat: position 0, cash 0.
  • fills is a list of (side, qty, price) tuples in the order they happened. side is "buy" or "sell"; qty and price are positive integers.
    • A buy of qty at price adds qty to your position and pays qty * price out of cash.
    • A sell does the opposite. Selling more than you hold is allowed and leaves you short.
    • Cash may go negative (think of it as borrowed).
  • last_price is the current market price. PnL values what you hold at that price: pnl = cash + position * last_price.
  • Return the tuple (position, cash, pnl).
fills = [("buy", 10, 100), ("buy", 5, 102), ("sell", 8, 105)]
mark_to_market(fills, 104)
# position = 10 + 5 - 8 = 7
# cash     = -1000 - 510 + 840 = -670
# pnl      = -670 + 7 * 104 = 58
# -> (7, -670, 58)

mark_to_market([("sell", 3, 50)], 45)   # (-3, 150, 15): a short gains when the price falls

Constraints: 0 <= len(fills) <= 10^5; qty, price and last_price are integers in 1..10^6. Use integers throughout; money in floats picks up rounding errors.

Show hint

keep two running totals (position and cash) with the sign set by the side, then value the leftover position at the last price.

Topic: Market and strategy simulations. Execution, backtests, allocation rules: careful state and event ordering.

0:00
Ctrl ' run · Ctrl ↵ submit
esc