Skip to content

Time Weighted Average Price

image 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

p_0,\cdots,p_{i-3},p_{i-2},p_{i-1},p_i,p_{i+1},p_{i+2},p_{i+3},\cdots

and the corresponding timestamps of these prices are

t_0,\cdots,t_{i-3},t_{i-2},t_{i-1},t_i,t_{i+1},t_{i+2},t_{i+3},\cdots

Mathematically, TWAP over a \Delta t time period for trade i is defined as:

TWAP_{i;\Delta t} = \sum_{j=0}^{i-1} \frac{max(t_{i-j},t_i-\Delta t)-max(t_{i-j-1},t_i-\Delta t)}{\Delta t}\cdot p_{i-j-1}

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]