[R-SIG-Finance] XTS - endpoints omits price changes

Josh Ulrich josh.m.ulrich at gmail.com
Thu Jul 17 00:12:02 CEST 2008


Hi James,

period.apply works *within* the given interval, so it will not use the
previous month's values in any calculation.  The diff function omits
the first value for each month by default, which are your missing
days' returns.

To achieve your desired result you could calculate daily returns
before calling period.apply:
period.apply(diff(log(x$Close),na.pad=TRUE), INDEX=endpoints(x,
'months'), FUN=sum)
# returns a 'zoo' series

Or you can calculate returns on the end-of-month values only:
diff(log(x[endpoints(x,'months'),'Close']))

But you need the Close for the last day of 2006-12 in order to
calculate the return for the first day of 2007 and therefore calculate
the year's return by your definition.

Best,
Josh

--
http://quantemplation.blogspot.com


On Wed, Jul 16, 2008 at 4:30 PM, James <j at jtoll.com> wrote:
> Hi,
>
>
> I've been learning to use the XTS package and have run into a problem.  If I
> calculate monthly log normal price relatives as such:
>
>> df<-yahooSeries("QQQQ", from = "2007-01-01", to = "2007-12-31",
>> returnClass=c("data.frame"))
>> x<-as.xts(df)
>> names(df)<-c("Open","High","Low","Close","Volume")
>> period.apply(x$Close, INDEX=endpoints(x, 'months'), FUN=function(x)
>> sum(diff(log(x))))
> 2007-01-31   2007-02-28   2007-03-30   2007-04-30   2007-05-31   2007-06-29
>   2007-07-31   2007-08-31   2007-09-28
>  0.019013286 -0.015344398  0.009231545  0.052943687  0.027803331
>  0.003367007 -0.010464725  0.020048207  0.050668995
>  2007-10-31   2007-11-30   2007-12-31
>  0.056634772 -0.051098382  0.006660162
>
> What happens is that the price change between the last day of the previous
> month and the first day of the current month is ignored for all 12 months.
>  This is a problem because I should, at least in my opinion, be able to add
> all twelve monthly changes to get the yearly change.  And that should be the
> same as:
>
>> period.apply(x$Close, INDEX=endpoints(x, 'years'), FUN=function(x)
>> sum(diff(log(x))))
> 2007-12-31
>  0.1693641
>
> But it's not, because 12 daily returns have been left out.  Is there a way
> to change this behavior, so that any given month, or period, will include
> all the price changes?
>
> Thanks,
>
> James
>
> _______________________________________________
> 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.
>



More information about the R-SIG-Finance mailing list