Percent Change: Each Step Against the One Before

Time SeriesEasy+10 XP+10

Percent Change: Each Step Against the One Before

A rise of 10 means something different on a series sitting at 20 than on one sitting at 20,000. Percent change removes the scale, reporting each step as a fraction of where it started:

pctt=xt−xt−1xt−1pct_t = \frac{x_t - x_{t-1}}{x_{t-1}}pctt​=xt−1​xt​−xt−1​​

Task: write percent_change(series) returning one value per step, each rounded to 4 decimal places.

  • The output is one shorter than the input — the first value has nothing before it to compare against.
  • Return the result as a fraction, not a percentage: a rise from 100 to 110 is 0.1, not 10.
  • Divide by the earlier value, never the later one. Dividing by the wrong end gives a number that looks nearly right for small moves and is badly wrong for large ones.
  • No value in the series is zero, so the division is always safe.
  • A flat step gives exactly 0.0; a fall gives a negative number.

The thing to notice is that these don't add up. Go up 50% and then down 50% and you are not back where you started — 1.5 × 0.5 = 0.75, a 25% loss. Percent changes multiply, which is exactly why cumulative returns are computed as a product of (1 + r) rather than a sum, and why a stock that halves needs to double to recover.

Examples

series = [100, 110, 99]
returns [0.1, -0.1]
series = [10, 5, 20]
returns [-0.5, 3.0]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run