I am looking for a quick way to reconstruct the order book at the time of each new limit order creation.
The data I have is order creation and completion:
OrderID | time_created | time_completed | price |
---|---|---|---|
a | 1 | 2 | 10 |
b | 1 | 6 | 11 |
c | 3 | 8 | 9 |
d | 4 | 5 | 8 |
e | 9 | 10 | 7 |
(Volume can be ignored here.) I would like to quickly find out the existing orders in the order book upon each new order's creation, and calculate distribution parameters based on them.
For example, for OrderID d, I would first find out that only orders b and c are still on the order book, because at time of order d's creation (t=4), a has been filled, b and c have been created but not filled, and e has not yet been created.
From there I would calculate distribution parameters, such as mean, median, percentiles etc. In the case of order d, the mean price of outstanding orders would be (11 + 9) / 2 = 10.
The most straightforward way that I can think of is to create a function that filters for the data of the unfilled orders, then extracts the distribution parameters. This function would then be iteratively applied to each row in the dataframe. For example:
def get_params(ser):
unfilled_orders = df[(df['time_created'] < ser['time_created']) & (df['time_completed'] > ser['time_created'])]
mean = unfilled_orders['price'].mean()
25perc = unfilled_orders['price'].quantile(0.25)
return pd.Series([mean, 25perc])
df.apply(get_params, axis=1)
However, the problem of this implementation is that it is too slow. Each row's result is highly related to the previous row's results, but this implementation does not make use of it. I am thinking if there is a faster solution, perhaps a solution based on a rolling (if we consider orders too old irrelevant) or expanding window? Thanks.