Title may be misleading, not sure what this is called what I am aiming to do.
I want to calculate the difference between the first time I buy, at 79, until I sell, at 38, which I then calculate 38 until 34, where a buy happens again.
Please see the desired output for clarification.
Data for reproducibility:
df = pd.DataFrame([[1, 0], [1, 0], [1, 0],[1, 0],[1, 0],[1, 0],[0, 1],[0, 1],[0, 1],[0, 1],[0, 1],[0, 1],[1, 0],[1, 0],[1, 0],[1, 0],[1, 0],[1, 0],[1, 0],[0, 1],[0, 1],[0, 1],[0, 1],[0, 1],[1, 0],[1, 0],[1, 0],[1, 0],[1, 0]], columns=['BUY', 'SELL'])
df['Price'] = np.random.randint(30, 100, df.shape[0])
Current output.
Price BUY SELL
0 79 1 0
1 47 1 0
2 70 1 0
3 58 1 0
4 53 1 0
5 57 1 0
6 38 0 1
7 86 0 1
8 64 0 1
9 53 0 1
10 47 0 1
11 30 0 1
12 34 1 0
13 96 1 0
14 79 1 0
15 81 1 0
16 31 1 0
17 76 1 0
18 38 1 0
19 38 0 1
20 61 0 1
21 50 0 1
22 85 0 1
23 55 0 1
24 80 1 0
25 31 1 0
26 82 1 0
27 44 1 0
28 53 1 0
Desired output.
Price BUY SELL Buy_price Difference
0 79 1 0 79 0
1 47 1 0 79 -0.4050632911
2 70 1 0 79 -0.1139240506
3 58 1 0 79 -0.2658227848
4 53 1 0 79 -0.3291139241
5 57 1 0 79 -0.2784810127
6 38 0 1 38 0
7 86 0 1 38 1.263157895
8 64 0 1 38 0.6842105263
9 53 0 1 38 0.3947368421
10 47 0 1 38 0.2368421053
11 30 0 1 38 -0.2105263158
12 34 1 0 34 0
13 96 1 0 34 1.823529412
14 79 1 0 34 1.323529412
15 81 1 0 34 1.382352941
16 31 1 0 34 -0.08823529412
17 76 1 0 34 1.235294118
18 38 1 0 34 0.1176470588
19 38 0 1 38 0
20 61 0 1 38 0.6052631579
21 50 0 1 38 0.3157894737
22 85 0 1 38 1.236842105
23 55 0 1 38 0.4473684211
24 80 1 0 80 0
25 31 1 0 80 -0.6125
26 82 1 0 80 0.025
27 44 1 0 80 -0.45
28 53 1 0 80 -0.3375