I have a dataframe containing a trading log. My problem is that I do not have any ID to match buy and sell of a stock. The stock could be traded many times and I would like to have an ID to match each finished trade. My original dataframe a sequential timeseries dataframe with timestamps. The below example illustrates my problem, I need to match and ID traded stock in sequential order. Very simplified example:
df1 = pd.DataFrame({'stock': ['A', 'B', 'C', 'A','C', 'A', 'A'],
'deal': ['buy', 'buy', 'buy', 'sell','sell', 'buy', 'sell']})
df1
Out[84]:
stock deal
0 A buy
1 B buy
2 C buy
3 A sell
4 C sell
5 A buy
6 A sell
Here is my desired output:
df1 = pd.DataFrame({'stock': ['A', 'B', 'C', 'A','C', 'A', 'A'],
'deal': ['buy', 'buy', 'buy', 'sell','sell', 'buy', 'sell'],
'ID': [1, 2, 3, 1,3, 4, 4]})
df1
Out[82]:
stock deal ID
0 A buy 1
1 B buy 2
2 C buy 3
3 A sell 1
4 C sell 3
5 A buy 4
6 A sell 4
Any ideas?