Volume Weighted Average Price (n-tick)¶
Source: adopted from here
Introduction¶
The Volume Weighted Average Price (VWAP) is one of the most common benchmark prices in execution algorithms and rolling VWAP is one classical analytics in a Complex Event Processing (CEP) engine. The formula to calculate the VWAP of N trades is as follows:
where p_i and v_i is the trade price and volume of i^{th} trade, respectively.
The rolling n-tick VWAP price at tick i is the VWAP of the previous n trades, including the current trade i. 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";
times:asc 09:30+n?"n"$06:30;
syms:n?`AAPL`C`IBM;
prices:20+0.01*sums?[n?1.<0.5;-1;1];
sizes:n?10000;
:([] time:times;sym:syms;price:prices;volume:sizes);
};
trades:simTrade[];
Implement a function rollingVwap[trades;n]
to calculate the rolling n-tick VWAP for each tick of trade price by symbol. For example, rollingVwap[trades;10]
calculates the rolling 10-tick VWAP price for each trade in the table.
Answer¶
The moving sum function msum[x;y]
calculates the x
-item moving sum of the list y
, with nulls replaced by zero. The rolling n-tick VWAP is simply the ratio of n-tick moving sum of notional divided by the corresponding moving sum of shares traded.
rollingVwap:{[trades;n]
update nTickVwap:msum[n;price*volume]%msum[n;volume] by sym from trades
};
rollingVwap[trades;10]