[R-SIG-Finance] efficient yearly return on a monthly basis

Brian G. Peterson brian at braverock.com
Mon Mar 22 15:41:27 CET 2010


Fabrizio Pollastri wrote:
> 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.
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

-- 
Brian G. Peterson
http://braverock.com/brian/
Ph: 773-459-4973
IM: bgpbraverock



More information about the R-SIG-Finance mailing list