Skip to content

Instantly share code, notes, and snippets.

@spestana
Created February 15, 2024 16:36
Show Gist options
  • Save spestana/1ca615fcae79d7b07d2b8a28cd77eff4 to your computer and use it in GitHub Desktop.
Save spestana/1ca615fcae79d7b07d2b8a28cd77eff4 to your computer and use it in GitHub Desktop.
Computes the cumulative gains and losses for a timeseries dataset
import numpy as np
def cumulative_gain_loss(x: np.ndarray, y: np.ndarray):
"""
Computes the cumulative gains and losses for a timeseries dataset
Parameters
------------
x: numpy.ndarray
time dimension
y: numpy.ndarray
variable of interest
Returns
-----------
x_gains: numpy.ndarray
x coordinates of positive changes (gains) in y
gains: numpy.ndarray
cumulative sum of positive changes (gains) in y
x_losses: numpy.ndarray
x coordinates of negative changes (losses) in y
losses: numpy.ndarray
cumulative sum of negative changes (losses) in y
"""
# calculate the difference in y values between each time step x
delta_y = np.diff(y)
# calculate the cumulative sum for all delta_y where the change was positive
gains = np.cumsum(delta_y[delta_y > 0])
# get the time steps (x coordinates) when those positive changes happened
x_gains = x[1:][delta_y > 0]
# calculate the cumulative sum for all delta_y where the change was negative
losses = np.cumsum(delta_y[delta_y < 0])
# get the time steps (x coordinates) when those negative changes happened
x_losses = x[1:][delta_y < 0]
return x_gains, gains, x_losses, losses
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment