I have the following dataframe:
indicator = ["buy"] + ["hold"]*3 + ["sell"] + ["hold"]*4 + ["buy"] + ["hold"] * 2
values = np.random.randn(len(indicator)) / 100
df = pd.DataFrame({"indicator": indicator, "values": values})
df
OUTPUT
indicator values
0 buy 0.001810
1 hold 0.011779
2 hold -0.003350
3 hold 0.010311
4 sell -0.010846
5 hold -0.013635
6 hold 0.003794
7 hold -0.003792
8 hold 0.006421
9 buy -0.019779
10 hold 0.007123
11 hold 0.025983
I want to cumulate column values based on the following logic of column indicator:
- when
buycumulate for all rows untilsell - when
sellcumulate for all rows untilbuy
Also, I want to length of the buy or sell periods.
The expected output is something like this:
indicator values period Cumsum
0 buy 0.004730 1 0.004730
1 hold -0.006814 1 -0.002084
2 hold 0.002424 1 0.000340
3 hold -0.017007 1 -0.016667
4 sell 0.007531 2 0.007531
5 hold -0.015347 2 -0.007816
6 hold 0.000051 2 -0.007765
7 hold -0.001202 2 -0.008967
8 hold -0.008070 2 -0.017037
9 buy 0.028718 3 0.028718
10 hold -0.005978 3 0.022740
11 hold 0.004725 3 0.027465
How can I do this conditional cumulation. Once I have the column period I can do .groupby("period"). But what is a pandas way to generate this column?