Skip to content

efficient yearly return on a monthly basis

3 messages · Fabrizio Pollastri, Brian G. Peterson, Jeff Ryan

#
The following code computes yearly returns every month on the xts seqence s.

s=xts(1:1000,as.Date(0:999))
yret_by_month = diff(s,lag=365)/lag(s,k=365)[endpoints(s,on="months")]

There is a more efficient way to avoid diff and lag to perform 
computations over the whole sequence? Thanks in advance for any help.


Regards,
F. Pollastri
#
Fabrizio Pollastri wrote:
It is of course unlikely that you have daily returns for 365 days of the 
year, but thanks for providing a reproducible example.

The first issue I see with your code is that you are calculating for 
every day, but only care about "extracting" the monthly endpoints.  So 
you're doing (in this example) ~30x more calculation than required (and 
~22x more than required on likely real data).
 
diff and Lag are pretty efficient, but I suspect that you can calculate 
log (or simple) returns on the daily or monthly series, then use runSum 
on a x-days or 12-month window to get your rolling annual return.

  - Brian
#
Forgetting 'coding' efficiency, I don't see how this is slow:
user  system elapsed
  0.008   0.000   0.007
An ?xts? object from 1970-01-31 to 2011-01-25 containing:
  Data: num [1:493, 1] NA NA NA NA NA NA NA NA NA NA ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr "e1"
  Indexed by objects of class: [Date] TZ: America/Chicago
  xts Attributes:
 NULL

That is 40 years of daily data, in 7 MILLISECONDS on a laptop.

Where is the problem?

Additionally lag/diff in xts are memcpy at the C level, so you won't
really be able to beat this in many languages (any!... maybe someone
can post a Kx comparison for kicks ;-) ) without some assembly in the
mix.

HTH
Jeff
On Mon, Mar 22, 2010 at 9:41 AM, Brian G. Peterson <brian at braverock.com> wrote: