# Portfolio Profit Calculator

> Portfolio gain from purchase history and current prices.

Canonical URL: <https://datadriven.io/problems/portfolio_profit_calculator>

Domain: Python · Difficulty: medium · Seniority: L6

## Problem

Given purchases (list of [date, shares] pairs) and prices (dict mapping date to price), compute total_cost = sum(shares * prices[date]) across purchases. Compute current_value = total_shares * latest_price where latest_price is prices for the latest date key (sorted). Return current_value - total_cost.

## Worked solution and explanation

### Why this problem exists in real interviews

Computing portfolio P&L across multiple purchases tests **aggregation by key** and **dict lookup** for current prices. It checks whether you can accumulate total cost and total shares per ticker, then compute the profit.

---

### Break down the requirements

#### Step 1: Accumulate total cost and total shares per ticker

For each purchase, add `shares * buy_price` to total cost and `shares` to total shares for that ticker.

#### Step 2: Compute current value using the prices dict

Multiply total shares per ticker by the current price.

#### Step 3: Return the difference: current value minus total cost

A positive result is profit; negative is loss.

---

### The solution

**Aggregated cost basis vs. current market value**

```python
def portfolio_profit(purchases, prices):
    total_cost = 0.0
    shares_by_ticker = {}
    for purchase in purchases:
        ticker = purchase[0]
        shares = purchase[1]
        buy_price = purchase[2]
        total_cost += shares * buy_price
        if ticker not in shares_by_ticker:
            shares_by_ticker[ticker] = 0
        shares_by_ticker[ticker] += shares
    current_value = 0.0
    for ticker in shares_by_ticker:
        current_value += shares_by_ticker[ticker] * prices[ticker]
    profit = current_value - total_cost
    return profit
```

> **Time and Space Complexity**
>
> **Time:** O(n + k) where n is the number of purchases and k is the number of unique tickers.
> 
> **Space:** O(k) for the shares-by-ticker dict.

> **Interviewers Watch For**
>
> Aggregating shares per ticker before computing current value, not computing profit per individual purchase. The per-purchase approach gives the same total but shows less understanding of the aggregation pattern.

> **Common Pitfall**
>
> Floating-point rounding. For financial calculations, `round()` or `Decimal` may be needed. The prompt likely accepts float arithmetic, but mentioning precision awareness scores points.

---

## Common follow-up questions

- What if you needed per-ticker profit breakdown? _(Tests returning a dict of profit per ticker instead of a single total.)_
- How would you handle dividends in the P&L calculation? _(Tests adding a dividend income stream alongside capital gains.)_
- What if prices are time-series and you need historical P&L? _(Tests computing unrealized P&L at each date point using the corresponding price.)_
- What about short positions? _(Tests handling negative share counts and the reversed profit logic.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/portfolio_profit_calculator)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.