Compute the day-over-day fractional price change of a pandas Series
Quick Overview
Write a pandas function that returns the day-over-day fractional change of a daily price series, with the first value left as NaN and the original DatetimeIndex kept. It tests relative change calculations, how missing prices and calendar gaps are handled, and position-based versus date-based comparisons.
Compute the day-over-day fractional price change of a pandas Series
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `daily_pct_change(s: pd.Series) -> pd.Series` that takes prices indexed by a daily `DatetimeIndex` and returns the day-over-day fractional change using `s.pct_change()`.
Requirements:
- Return fractions (for example `0.05` for a 5% rise). Do not multiply by 100.
- The first element is `NaN`.
- Preserve the original `DatetimeIndex`.
For example:
```python
s = pd.Series([100.0, 105.0, 105.0, 84.0],
index=pd.to_datetime(["2026-01-01", "2026-01-02",
"2026-01-03", "2026-01-04"]))
daily_pct_change(s)
# 2026-01-01 NaN
# 2026-01-02 0.05
# 2026-01-03 0.00
# 2026-01-04 -0.20
# dtype: float64
```
```hint Missing prices
Ask what `pct_change` does when a price in the middle of the series is `NaN`, and whether that behavior has changed across pandas versions.
```
### What a Strong Answer Covers
- The formula behind the fractional change and why the first value is `NaN`
- Returning fractions on the original index, with no rescaling, dropping or resetting
- How a missing price is treated and which behavior the answer chooses
- That the comparison is by row position, so sort order and calendar gaps matter
- Edge cases such as a zero price
### Follow-up Questions
- How would you compute the change over the previous `n` days instead of one?
- What if the index has gaps or is unsorted?
- How would you turn the daily fractional changes into a cumulative return for the whole period?
Overview: Write a pandas function that returns the day-over-day fractional change of a daily price series, with the first value left as NaN and the original DatetimeIndex kept. It tests relative change calculations, how missing prices and calendar gaps are handled, and position-based versus date-based comparisons.
Implement daily_pct_change(s: pd.Series) -> pd.Series that takes prices indexed by a daily DatetimeIndex and returns the day-over-day fractional change using s.pct_change().
Requirements:
Return fractions (for example
0.05
for a 5% rise). Do not multiply by 100.