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, cash0. fillsis a list of(side, qty, price)tuples in the order they happened.sideis"buy"or"sell";qtyandpriceare positive integers.- A buy of
qtyatpriceaddsqtyto your position and paysqty * priceout 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).
- A buy of
last_priceis 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.