I am trying to find a way to find a matching value, given a specific column value, in the nearest preceding rows of two separate columns of a Pandas Dataframe, and subsequently indicate '1' if found in the column else '0'.
The Dataframe index is not sorted.
Data:
df = pd.DataFrame({
'datetime': [
'2020-11-16 01:39:06.22021017', '2020-11-16 01:39:06.22021020', '2020-11-16 01:39:06.22021022',
'2020-11-16 01:39:06.22021031', '2020-11-16 01:39:06.22021033', '2020-11-16 01:39:06.22021036'],
'type': ['Quote', 'Trade', 'Trade', 'Quote', 'Quote', 'Trade'],
'price': ['NaN', 7026.5, 7026.5, np.NaN, np.NaN, 7024.0],
'ask_price': [7026.5, 7026.5, 7026.0, 7026.5, 7026.0, 7026.5],
'bid_price': [7024.0, 7024.5, 7024.5, 7024.0, 7024.5, 7024.5]})
What I need:
When the type == 'Trade' I need to look back through the bid_price and ask_price, and find the first value that matches the column price. In the same row as the one with the trade I want two separate columns indicating whether the price was found in the nearest bid_price or ask_price columns.
Expected Output:
df = pd.DataFrame({
'datetime': [
'2020-11-16 01:39:06.22021017', '2020-11-16 01:39:06.22021020', '2020-11-16 01:39:06.22021022',
'2020-11-16 01:39:06.22021033', '2020-11-16 01:39:06.22021034', '2020-11-16 01:39:06.22021033'],
'type': ['Quote', 'Trade', 'Trade', 'Quote', 'Quote', 'Trade'],
'price': ['NaN', 7026.5, 7026.5, np.NaN, np.NaN, 7024.0],
'ask_price': [7026.5, 7026.5, 7026.0, 7026.5, 7026.0, 7026.5],
'bid_price': [7024.0, 7024.5, 7024.5, 7024.0, 7024.5, 7024.5],
'is_bid_trade': [0, 0, 0, 0, 0, 1],
'is_ask_trade': [1, 1, 0, 0, 0, 0]})
You can see that the first trade matches the quote in the preceding row in the ask_price column. The final trade matches in the bid_price column, but this is two rows behind the trade.
I have tried (and have been kindly helped by SO) but have yet to find a solution here.
The datetime column is sadly not 100% accurate, so cannot be relied upon to sort chronologically. I have also attempted to find the minimum index using df.index.get_loc(), but am unsure of how to apply this to two columns to search within.
All help very gratefully received.