# [R-SIG-Finance] Simple TWAP Algorithm in R, Part II

Brahm, David David.Brahm at geodecapital.com
Wed Jul 11 20:11:13 CEST 2007

```The [-1] in your tapply formula is what associates each spread with the
PRIOR time difference.  If you want to associate it with the NEXT time
difference, just chop off the last element instead of the first.

This function may be handy:
chop <- function(x) rev(rev(x)[-1])

Then:
twp <- tapply( diff(pricedata\$time), chop(pricedata\$spread), sum )

-- David Brahm (brahm at alum.mit.edu)

-----Original Message-----
From: r-sig-finance-bounces at stat.math.ethz.ch
[mailto:r-sig-finance-bounces at stat.math.ethz.ch] On Behalf Of Rory
Winston
Sent: Wednesday, July 11, 2007 7:25 AM
To: r-sig-finance at stat.math.ethz.ch
Subject: [R-SIG-Finance] Simple TWAP Algorithm in R, Part II

Hi all

I recently posted a question regarding a simple time-averaged
calculation in
R. I have an input data file which is a historical list of prices and
their
time:

1183480907.042 1.36150 1.36160
1183480919.045 1.36150 1.36170
1183480923.044 1.36150 1.36160
....

After some data conversion and spread calculations, I use R to calculate
a
time-weighted average (based on a clever tapply() command graciously
supplied by Patrick Burns):

twp <- tapply( diff(pricedata\$time), pricedata\$spread[-1], sum )

I can then calculate the time-weighted average by dividing twp by
sum(diff(pricedata\$time)).

When I compared my numbers with someone else who had done the
calculations,
it became apparent that I need to make a slight modification to the
tapply()
command : the current logic basically computes a running sum as spreads
[S_n] += T_{n} - T_{n-1}, whereas the correct calculation is spreads
[S_{n-1}] += T_{n} - T_{n-1}. In other words, I need to tell tapply()
somehow to offset the spread vector by one. I have fiddled around with
various permutations of tapply() trying to get it to do this, but with
no
success so far. I guess I could rebase the vector of spreads before
calculating, but this seems like an unecessary hassle. Does anyone out
there
know how I can get tapply() (or a similar command) to do what I want?

Thanks
Rory

[[alternative HTML version deleted]]

_______________________________________________
R-SIG-Finance at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-sig-finance
-- Subscriber-posting only.
-- If you want to post, subscribe first.

```