Time Weighted Average Price¶
Source: adopted from here
Introduction¶
Time weighted average price (TWAP) has two practical uses in algorithmic trading: one is the average price over a time period and the other is the trading algorithm which executes a given amount of shares evenly within a given time period. This question focuses on the first use case.
Assuming the trade price time series is
and the corresponding timestamps of these prices are
Mathematically, TWAP over a \Delta t time period for trade i is defined as:
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";
:([]time:asc 09:30+n?"n"$06:30;price:20+0.01*sums?[n?1.<0.5;-1;1]);
};
trades:simTrade[];
Implement a function calcTwap[trades;secs]
to calculate the rolling TWAP for each tick of trade price. For example, calcTwap[trades;300]
calculates the rolling 5-minute TWAP price for each trade in the table.
Answer¶
The suggested answer is as follows:
calcTwap:{[data;secs]
w:neg[`second$(secs;0)]+\:exec time from data;
t:wj[w;`time;data;(
(select time,times:time,prices:price from data);
({1_x};`times);
({-1_x};`prices)
)];
t:update times:(first[w],'times) from t;
t:update durations:{1_deltas x} each times from t;
t:update twap:durations wavg' prices from t;
select time,price,twap from t
};
calcTwap[trades;300]