In [ ]:
# Returns two extra columns for the DataFrame: Mid_Price and VWAP
def tca(tradeSymbol, tradeTime):
    
    # Filter quotes for matching symbols and times before trade
    newQuotes = quotes[(quotes.Symbol == tradeSymbol) & \
                       (quotes.Time <= np.datetime64(tradeTime))]
    
    # Set last value equal to mid
    mid = (newQuotes.Mid_Price[-1:].values[0]).as_py()
    
    # Filter trades for matching symbols and 
    # times within 15min window before trade
    vwapFilter = ((tradesAll.Symbol == tradeSymbol) & \
                  (tradesAll.Time <= np.datetime64(tradeTime)) & \
                  (tradesAll.Time >= (np.datetime64(tradeTime) - \
                                      np.timedelta64(15, 'm'))))
    vwapTrades = tradesAll[(vwapFilter)]
    
    # Use these trades to find vwap
    vwap = (vwapTrades.Trade_Price * vwapTrades.Trade_Volume).sum()\
    / vwapTrades.Trade_Volume.sum()
    
    return round(mid,2), round(vwap,2)
In [ ]:
# Call tca using apply
trades[['Mid_Price','VWAP']] = \
trades.apply(lambda df: tca(df.Symbol, df.Time),\
             axis=1, result_type='expand')