Screen daily metrics by linear trend slope, scale-free rate of change and R-squared
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `trend_slope_screen(df)` for a DataFrame indexed by a daily `DatetimeIndex` with several numeric columns. For each column, fit `np.polyfit(x, y, 1)` with `x` the positional index `0, 1, ..., n-1`, so calendar gaps are ignored, and return a per-metric screening table that ranks metrics by how fast they trend relative to their own level.
The table must follow these rules:
- Columns, in order: `metric` (object, the column name), `slope` (float64, change per row, rounded to 6 decimals), `pct_change_per_day` (float64, `slope / column mean`, rounded to 6 decimals), `direction` (object), `r_squared` (float64, rounded to 4 decimals).
- Compute `pct_change_per_day` from the unrounded slope and round only at the end. It is a fraction, so 0.4 means the metric moves by 40% of its mean per day.
- `direction` is `'up'` if the reported slope is greater than 0, `'down'` if it is less than 0, and `'flat'` otherwise. Using the rounded slope keeps floating-point noise on a flat series from reading as a trend.
- `r_squared = 1 - SS_res / SS_tot`, where `SS_res` is the residual sum of squares of the fitted line and `SS_tot` the total sum of squares around the mean. For a constant column `SS_tot` is 0; report `r_squared` as 0.0.
- If a column's mean is 0, `pct_change_per_day` is NaN, and that row sorts after every row with a defined value.
- Sort by `abs(pct_change_per_day)` descending, then `metric` ascending, then `reset_index(drop=True)`.
Example:
```python
idx = pd.date_range('2024-01-01', periods=4, freq='D')
df = pd.DataFrame({
'a': [1, 2, 3, 4],
'b': [10, 9, 8, 7],
'c': [5, 5, 5, 5],
'd': [2, 4, 3, 5],
}, index=idx)
trend_slope_screen(df)
```
Expected result:
| | metric | slope | pct_change_per_day | direction | r_squared |
|---|---|---|---|---|---|
| 0 | a | 1.0 | 0.400000 | up | 1.0000 |
| 1 | d | 0.8 | 0.228571 | up | 0.6400 |
| 2 | b | -1.0 | -0.117647 | down | 1.0000 |
| 3 | c | 0.0 | 0.000000 | flat | 0.0000 |
`a` rises by 1 per day on a mean of 2.5, so its rate is 0.4. `d` has slope 0.8 on a mean of 3.5 (rate 0.228571), but its points scatter around the line, so only 64% of its variance is explained. `b` falls by 1 per day on a mean of 8.5. `c` is constant, so it is flat with `r_squared` 0.0 and sorts last.
```hint Floating-point zeros
A fitted slope on a flat series is rarely exactly 0. Decide which value the direction rule should read so the `direction` and `slope` columns never disagree.
```
```hint Degenerate columns
Before writing the loop, work out what each formula does for a constant column and for a column whose mean is 0.
```
### Constraints & Assumptions
- The index is a daily `DatetimeIndex` sorted ascending, with at least 2 rows.
- Every column is numeric and has no missing values.
- `x` is positional, so `slope` is the change per row. It equals the change per day only when the index has no gaps.
### What a Strong Answer Covers
- Fitting each column against the positional axis and reading the slope from the correct coefficient of `np.polyfit`.
- Computing `r_squared` from the residual and total sums of squares, with the constant column handled.
- Normalizing by the mean so metrics in different units are comparable, without crashing or corrupting the sort when the mean is 0.
- Rounding, a `direction` that agrees with the reported slope, the required dtypes, and the two-key sort on a fresh index.
### Follow-up Questions
- What goes wrong with `pct_change_per_day` when a column's mean is close to zero or negative, and what would you use instead?
- One metric has a high `r_squared` and a tiny slope, another a low `r_squared` and a large slope. Which one is trending, and how would the screen combine the two?
- How would you make the slope resistant to outliers or weekly seasonality?
- If the index has calendar gaps, how would you report a true per-calendar-day slope?
Overview: Write a pandas and NumPy function that fits a linear trend to each metric in a daily DataFrame and ranks the metrics by slope relative to their mean. It tests np.polyfit, R-squared, floating-point care around zero slopes, constant and zero-mean columns, and deterministic sorting.