I have a dataframe that looks like this
price signal
time
2017-10-28 13:54:00 293.18 buy
2017-11-02 17:13:04 285.30 sell
2017-11-02 18:40:04 283.24 buy
2017-11-03 08:40:06 291.23 sell
2017-11-03 12:38:06 294.26 buy
2017-11-05 13:33:06 296.52 sell
I want to create a profit column populated with the difference of the previous buy/sell pair
price signal profit
time
2017-10-28 13:54:00 293.18 buy
2017-11-02 17:13:04 285.30 sell -7.88
2017-11-02 18:40:04 283.24 buy
2017-11-03 08:40:06 291.23 sell 7.99
2017-11-03 12:38:06 294.26 buy
2017-11-05 13:33:06 296.52 sell 2.29
How might I best go about this?
Alternative or more efficient approaches to calculating profit also welcome
IIUC using cumsum
create the group key , then diff
df.groupby(df.signal.eq('buy').cumsum())['price'].diff()