title: How can I calculate a time-weighted average in kdb?
body: <p>Calculating weighted averages is easy in kdb thanks to the wavg function. How can I calculate the delay between two consecutive row times and use those values as the weightings parameter to wavg?</p>
  
  <p>Something like:</p>
  
  <pre><code>`date`ts xasc select date,ts,mytw:(next ts - ts) wavg mycolumnval from pmd where date=2013.05.22
  </code></pre>
  
  <p><code>next</code> gives the following row column in the query, but I can't figure how to subtract the two ts values and use them in <code>wavg</code>.</p>
  
  <p><strong>UPDATE</strong>
  The solution was to use parenthesis: <code>((next ts) - ts)</code>. Note that I can't use <code>deltas[ts]</code>. This would produce different weights:</p>
  
  <pre><code>08:15:19.811    00:00:00.000
  08:15:19.811    00:00:00.001
  08:15:19.812    00:00:00.014
  08:15:19.826    00:00:07.305
  08:15:27.131    NULL
  </code></pre>
  
  <p>This is <code>deltas[ts]</code>:</p>
  
  <pre><code>08:15:19.811    08:15:19.811
  08:15:19.811    00:00:00.000
  08:15:19.812    00:00:00.001
  08:15:19.826    00:00:00.014
  08:15:27.131    00:00:07.305
  </code></pre>