Home > Software design >  Pandas: calculating percentage change based on other criteria
Pandas: calculating percentage change based on other criteria

Time:01-03

In the following dataset, I have "cross up" and "cross down". I'd like to calculate percentage change from cross-down to the next cross-up.

E.g. the first row is "cross up" and the next three rows are "up" Their prices are 390.3800, 389.9000 389.9500 The cross down price is then 388.8600 I'd like for the three up rows to calculate the change until the cross down. So, pct_diff(388.8600, 390.3800) for the first row pct_diff(388.8600, 389.9000) for the second row pct_diff(388.8600, 389.9500) for the third row

2022-07-08 11:30:00  0.780577  0.730154  0.050422        up    cross up  390.3800
2022-07-08 11:45:00  0.798424  0.743808  0.054616        up           0  389.9000
2022-07-08 12:00:00  0.807296  0.756506  0.050790        up           0  389.9500
2022-07-08 12:15:00  0.718096  0.748824 -0.030728      down  cross down  388.8600
2022-07-08 12:30:00  0.569827  0.713024 -0.143197      down           0  387.9800
2022-07-08 12:45:00  0.412866  0.652993 -0.240127      down           0  387.5500
2022-07-08 13:00:00  0.255670  0.573528 -0.317858      down           0  387.1800
2022-07-08 13:15:00  0.176791  0.494181 -0.317390      down           0  387.7716
2022-07-08 13:30:00  0.155127  0.426370 -0.271243      down           0  388.3000
2022-07-08 13:45:00  0.145170  0.370130 -0.224960      down           0  388.4101
2022-07-08 14:00:00  0.141290  0.324362 -0.183072      down           0  388.4800
2022-07-08 14:15:00  0.174931  0.294476 -0.119545      down           0  388.9600
2022-07-08 14:30:00  0.247955  0.285171 -0.037217      down           0  389.5700
2022-07-08 14:45:00  0.350205  0.298178  0.052027        up    cross up  390.1700
2022-07-08 15:00:00  0.415148  0.321572  0.093576        up           0  390.0299
2022-07-08 15:15:00  0.462105  0.349679  0.112426        up           0  390.0400
2022-07-08 15:30:00  0.455337  0.370810  0.084527        up           0  389.5600
2022-07-08 15:45:00  0.436071  0.383862  0.052208        up           0  389.4500
2022-07-08 16:00:00  0.354582  0.378006 -0.023424      down  cross down  388.6800

CodePudding user response:

check if this works for you

def pct_diff(x, y):
    return (y - x) / x

for i, row in df.iterrows():
    if row['Direction'] == 'up':
        # Calculate percentage change to next cross-down price
        cross_down = df[i:][df['Direction'] == 'cross down'].iloc[0]['Price']
        df.loc[i, 'Pct Change'] = pct_diff(cross_down, row['Price'])
    elif row['Direction'] == 'cross down':
        # Reset cross-down price for next group of "up" rows
        cross_down = row['Price']
  • Related