# Stock Range Finder

> Prices move. One stretch had the widest gap.

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

Domain: Python · Difficulty: medium · Seniority: L3

## Problem

The market-data team dumps end-of-day OHLCV bars as a list of CSV rows, one string per ticker per trading day in the form `Date,Ticker,Open,High,Low,Close,Volume` (no header row). A trader wants a quick volatility snapshot for one symbol: the day it had the widest intraday swing (High minus Low, earliest Date on ties) and its average daily Volume over the dump. Implement `analyze_ticker(lines, ticker)` that returns a dict with keys `max_range` (float, the largest High-Low value), `max_range_date` (str, the date of that day), and `avg_volume` (float, the mean Volume across the symbol's rows). Return an empty dict if the symbol never traded.

## Example

Input:

```
lines = ["2024-01-15,AAPL,180.0,185.0,178.0,183.0,50000","2024-01-15,GOOG,140.0,142.0,139.0,141.0,30000","2024-01-16,AAPL,183.0,190.0,182.0,189.0,60000","2024-01-17,AAPL,189.0,191.0,188.0,190.0,40000"], ticker = "AAPL"
```

Output:

```
{"max_range":8,"avg_volume":50000,"max_range_date":"2024-01-16"}
```

## Worked solution and explanation

### Why this problem exists in real interviews

Parsing CSV data, filtering by a key, and computing aggregate statistics tests **end-to-end data pipeline thinking**: string parsing, type conversion, filtering, and aggregation in a single function.

---

### Break down the requirements

#### Step 1: Parse CSV rows into structured fields

Split each row string by comma and map to Date, Ticker, Open, High, Low, Close, Volume.

#### Step 2: Filter for the target ticker

Only process rows matching the requested ticker.

#### Step 3: Find the date with the largest High minus Low range

Track the maximum range and the corresponding date as you iterate.

#### Step 4: Compute the average volume

Accumulate total volume and count to compute the average. Return an empty dict if no rows matched.

---

### The solution

**CSV parsing with filter, range tracking, and average**

```python
def analyze_ticker(lines, ticker):
    max_range = 0.0
    max_range_date = ''
    total_volume = 0
    count = 0
    for line in lines:
        parts = line.split(',')
        if parts[1] != ticker:
            continue
        date = parts[0]
        high = float(parts[3])
        low = float(parts[4])
        volume = int(parts[6])
        day_range = high - low
        if day_range > max_range:
            max_range = day_range
            max_range_date = date
        total_volume += volume
        count += 1
    if count == 0:
        return {}
    avg_volume = total_volume / count
    result = {
        'max_range': max_range,
        'max_range_date': max_range_date,
        'avg_volume': avg_volume
    }
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the number of CSV rows. Single pass through the data.
> 
> Space: O(1) beyond the input. Only tracking variables, no additional data structures.

> **Interviewers Watch For**
>
> Combining parsing, filtering, and multiple aggregations in a single pass rather than loading everything into a list of dicts first. Single-pass processing shows pipeline thinking.

> **Common Pitfall**
>
> Forgetting the empty-result case. If the symbol never traded, `count` stays 0 and dividing `total_volume` by count raises ZeroDivisionError. Guard with an early `return {}` before computing the average. A strict `>` comparison also keeps the earliest date on ties.

---

## Common follow-up questions

- What if the CSV is too large to load as a list? _(Tests reading line by line from a file handle rather than holding the whole list in memory.)_
- How would you handle malformed rows? _(Tests try/except around parsing with a skip-and-log strategy.)_
- What if you needed to compute these statistics for all tickers at once? _(Tests grouping by ticker in a dict of accumulators.)_
- How would you do this with pandas? _(Tests `df.groupby('Ticker').agg({'Range': 'max', 'Volume': 'mean'})` equivalent.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/stock_range_finder)
- [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). DataDriven is the data engineering interview community. Live code execution in SQL, Python, and Spark sandboxes. Every feature is open to every member.