Search code examples
rreturntime-seriesxts

Calculate Daily return using intraday prices?


I have 1 min prices for each day begining 09:30 to 4:00pm and i need to calculate daily log return i.e. log(close price on the day / opening price on the day)? How to do this using R?

my data looks like

2014-02-03 09:30:00    10.450000
2014-02-03 09:31:00    10.450000
2014-02-03 09:32:00    10.326600
2014-02-03 09:33:00    10.290000
.
.
2014-02-03 04:00:00    10.326500
...
2014-07-31 09:30:00    15.8500
2014-07-31 09:31:00    15.8600
2014-07-31 09:32:00    15.8600
.
2014-07-31 03:50:00    15.9101
2014-07-31 04:00:00    15.9300

Solution

  • You can use apply.daily(). Here's an example using apply.monthly() on daily data. The concept is the same.

    data(sample_matrix)
    x <- as.xts(sample_matrix[,"Close"])
    apply.monthly(x, function(p) log(last(p)/as.numeric(first(p))))
                       [,1]
    2007-01-31  0.002152642
    2007-02-28  0.008169076
    2007-03-31 -0.032065389
    2007-04-30  0.009559690
    2007-05-31 -0.035670840
    2007-06-30  0.002430626
    

    You need the as.numeric() call because arithmetic operations on xts/zoo objects always align by the index first. as.numeric() removes the index.