Closing Bell
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L6
- Asked in
- Amazon
Problem
A brokerage export gives you prices, a dict keyed by ISO date string mapping to that day's close, and purchases, a list of [date, quantity] buy records where quantity is a whole number of shares. Mark every lot to the price on the latest date in the history and return the portfolio's total gain, where each buy contributes its quantity times how far the price has moved since the day it was bought.
Every share you own, priced at today's close. Tally the gains.
Example 1
Input:
prices = {"2024-01-01":100,"2024-01-15":110,"2024-02-01":120}, purchases = [["2024-01-01",10],["2024-01-15",5]]Output:
250
Example 2
Input:
prices = {"2024-03-01":50,"2024-03-15":45}, purchases = [["2024-03-01",20]]Output:
-100
Worked solution and explanation
Marking a position to market is 2 lookups into the same dict: one fixed reference price, the close on the latest date, and one price per buy, the close on the day it was bought. Everything else is multiplication and a running sum. The work is in getting the reference price right and in treating purchases as a list of separate lots.
Which close is the latest
prices is keyed by ISO date strings, and zero-padded year-month-day text sorts in calendar order under plain string comparison. Iterating a dict yields its keys, so max(prices) hands you the latest date with no parsing. One more lookup, prices[latest_date], turns that date into the mark.
- Last value in the dict
list(prices.values())[-1]returns whatever the export wrote last. Example 1 passes only because its keys arrive in date order. List '2024-02-01' first and the mark becomes 110.0, so the function returns 100.0.- `max(prices)` on the keys
max(prices)compares the date strings themselves, so insertion order stops mattering. The same shuffled dict still marks to 120.0 and returns 250.0.
One pass over the buy records
Step 1: Fix the mark once
Every lot is valued against the same close, so compute latest_price before the loop. Calling max(prices) per record would give the same number and rescan every date for each buy.
Step 2: Price each lot on its own date
Split each record into date and quantity, then read prices[date] for the buy price. The gain is quantity * (latest_price - buy_price), and the sign takes care of itself: Example 2 gives 20 * (45.0 - 50.0), a loss of 100.0.
Step 3: Add lots, keep them separate
Accumulate into total_profit, which starts at 0.0. Each record is its own lot, so 2 buys on one date both get added, and a buy on the latest date itself adds 0.0.
def portfolio_profit_calculator(prices, purchases):
latest_date = max(prices)
latest_price = prices[latest_date]
total_profit = 0.0
for date, quantity in purchases:
buy_price = prices[date]
total_profit += quantity * (latest_price - buy_price)
return total_profitNear misses on the mark and the lots
def portfolio_profit_calculator(prices, purchases):
latest_price = max(prices.values()) # highest close, not the latest one
total_profit = 0.0
for date, quantity in purchases:
total_profit += quantity * (latest_price - prices[date])
return total_profitReturns 250.0 on Example 1 and 0.0 on Example 2, where the graded answer is -100.0.
Common follow-up questions
- A buy is dated on a Saturday and
priceshas no close for it. What should happen?As written,
prices[date]raisesKeyError, and failing loudly is the right default until the business says to use the prior trading day's close, which you would find withbisectover the sorted dates. Real price histories skip weekends and holidays, and buy records still get dated on them. - The next export writes dates as '1/5/2024'. Does
max(prices)survive?No: as text '9/1/2023' ranks above '10/1/2024', so you would pass
maxakeythat parses each string withdatetime.strptime. Date formats change between vendors more often than schemas do. - Which tests would you write first?
A falling price, a dict whose keys are out of date order, 2 buys on the same date, and a buy on the latest date itself, which must contribute 0.0. Each one fails a different near-miss version of this function.
- The total is off by a fraction of a cent against the broker's statement. Why?
Binary floats cannot hold most decimal prices exactly and the error accumulates across the sum, so a ledger-grade version carries prices as
Decimalbuilt from strings. Reconciliation compares to the cent, and a drift like this gets flagged as a break.