'cumsum() on running streak of data

i'm attempting to determine the sum of a column for a running period where there is a negative gain - ie i want to determine the total for a loosing streak.

i've set up a column that provides the numerical number of days where its been loosing (Consecutive Losses), but i wish to sum up the same for the total loss throughout the streak. what i have (Aggregate Consecutive Loss) 1) doesn't work (because it just cumsums() without resetting to zero at each streak) and 2) is incorrectly as i should in fact take the Open value at the start of the streak and Close value at the end.

how can i correctly setup this Aggregate Consecutive Loss value in pandas?

import pandas as pd
import numpy as np
import yfinance as yf

def get( symbols, group_by_ticker=False, **kwargs ):
    if not isinstance(symbols, list):
        symbols = [ symbols, ]
    kwargs['auto_adjust'] = True
    kwargs['prepost'] = True
    kwargs['threads'] = True
    df = None
    if group_by_ticker:
        kwargs['group_by'] = 'ticker'

    df = yf.download( symbols, **kwargs)

    for t in symbols:

        df["Change Percent",t] = df["Close",t].pct_change() * 100
        df["Gain",t] = np.where( df['Change Percent',t] > 0, True, False ).astype('bool')
        
        a = df['Gain',t] != True
        df['Consecutive Losses',t] = a.cumsum() - a.cumsum().where(~a).ffill().fillna(0).astype(int)
        
        x = df['Change Percent',t].where( df['Consecutive Losses',t] > 0 )
        df['Aggregate Consecutive Loss',t] = x.cumsum() - x.cumsum().where(~a).ffill().fillna(0).astype(float)

    return df

data = get( ["DOW", "IDX"], period="6mo")
data[['Change Percent','Gain','Consecutive Losses','Aggregate Consecutive Loss']].head(50)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source