Volume Weighted Average Price (time-window)¶
Source: adopted from here
Introduction¶
Last week, we discussed the n-tick rolling Volume Weighted Average Price (VWAP). We continue along this thread to calculate the time-window VWAP, i.e. the VWAP over a sliding window, say, 5 minutes.
The rolling time-window VWAP price at time t is the VWAP of the previous trades within the time window [t-w;t], including the current trade at time t. Mathematically,
Question¶
The function simTrade
simulates the price and timestamp of each trade in the continuous trading session from 09:30 to 16:00.
simTrade:{
n:100000;
system "S -314159";
syms:n?`AAPL`C`IBM;
times:asc 09:30+n?"n"$06:30;
prices:20+0.01*sums?[n?1.<0.5;-1;1];
sizes:n?10000;
:([] sym:syms;time:times;price:prices;volume:sizes);
};
trades:simTrade[];
Implement a function rollingTimeWindowVwap[trades;w]
to calculate the rolling time-window VWAP for each tick of trade price by symbol. For example, rollingTimeWindowVwap[trades;00:05]
calculates the rolling 5-minute window VWAP price for each trade in the table.
Answer¶
The suggested answer is as follows.
rollingTimeWindowVwap:{[trades;wl]
// Sort the input table by sym and time.
// This will make the window join below much faster.
t:`sym`time xasc trades;
// Create a list of timestamps from the given trade table
times:exec time from t;
// Create a time window for the window join.
// The time window is a two-element list and each element itself is also a list.
// The first element is the start time and the corresponding item from the second element is the end time.
w:(neg[wl]+\:times;times);
// Calculate the notional traded and share quantity traded for each rolling window
t2:select sym,time,notionalTraded:volume*price,sharesTraded:volume from t;
res:wj[w;`sym`time;t;(t2;(sum;`notionalTraded);(sum;`sharesTraded))];
// Define the rolling vwap as the ratio of notional traded to shares traded
select sym,time,price,volume,rollingVwap:notionalTraded%sharesTraded from res
};
rollingTimeWindowVwap[trades;00:05]