I am trying to build a small stock trading reporting in pandas. It's getting a little complicated because of subsequent buys and sells. Assuming I have my buys and sells in a dataframe:
import pandas as pd
data = pd.read_csv("ticker1.csv", delimiter=";")
data['cumsum']=data['quantity'].cumsum(axis=0)
data
Date qty price cumsum
0 2018-01-20 80 20.70 80
1 2018-02-14 90 20.82 170
2 2018-02-19 -100 20.62 70
3 2018-02-27 -70 20.55 0
4 2018-03-13 30 19.80 30
5 2018-03-14 10 19.55 40
6 2018-03-30 -20 20.92 20
7 2018-04-01 -10 20.95 10
8 2018-04-10 -10 21.03 0
9 2018-05-04 25 19.77 25
10 2018-05-31 -10 20.22 15
So there can be "completed" cycles of buying and selling whenever cumsum =0 (no short-selling). In this example, there would be an open position of 15 at the end. In order to analyze the trades, I'd like to group them like this:
Date qty price cumsum group
0 2018-01-20 80 20.70 80 1
1 2018-02-14 90 20.82 170 1
2 2018-02-19 -100 20.62 70 1
3 2018-02-27 -70 20.55 0 1
4 2018-03-13 30 19.80 30 2
5 2018-03-14 10 19.55 40 2
6 2018-03-30 -20 20.92 20 2
7 2018-04-01 -10 20.95 10 2
8 2018-04-10 -10 21.03 0 2
9 2018-05-04 25 19.77 25 3
10 2018-05-31 -10 20.22 15 3
I am trying to group the transactions until the next time cumsum =0. Then I could loop over the groupings for further analysis (eg see if it was a winning or losing trade, # days between first buy and last sale etc.) and I would be able to see that in this case there is an open position at the moment (if last value for cumsum != 0).
Could someone please give me a hint how I could realize the grouping?
Thanks
Coincidentally, one solution is to apply Series.cumsum()
on the column named cumsum
:
df['group'] = (df['cumsum'].shift() == 0).astype(int).cumsum() + 1
df
Date qty price cumsum group
0 2018-01-20 80 20.70 80 1
1 2018-02-14 90 20.82 170 1
2 2018-02-19 -100 20.62 70 1
3 2018-02-27 -70 20.55 0 1
4 2018-03-13 30 19.80 30 2
5 2018-03-14 10 19.55 40 2
6 2018-03-30 -20 20.92 20 2
7 2018-04-01 -10 20.95 10 2
8 2018-04-10 -10 21.03 0 2
9 2018-05-04 25 19.77 25 3
10 2018-05-31 -10 20.22 15 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.