Search code examples
rxtsquantmod

How to subtract rows in xts


I am using quantmod and I require to find the difference between close value of today and 50th day close value.

I tried like this

library(quantmod) 
tickers = 'AAPL'
symbol = getSymbols(tickers,from="2014-04-01",auto.assign=F)
change =(tail(Cl(symbol), 50)[1]-tail(Cl(symbol), 1)[1])
change

but I am not able to subtract it and getting this error

Data:
numeric(0)

Index:
numeric(0)

Solution

  • For xts objects, the binary math and logical operators always align the two objects by their indexes before performing the operation. Therefore, you need to use lag to appropriately align the index values if you want to use those operators on observations at different timestamps.

    require(xts)
    data(sample_matrix)
    x <- as.xts(sample_matrix)
    x$diff50 <- lag(x$Close, 50) - x$Close
    

    Note that lag.xts breaks the convention of lag.ts and lag.zoo (where a positive k references data in the future) to use the more standard convention of a positive k to reference historical (not future) data.


    If you just want to subtract a scalar value that occurs at a single timestamp of an xts object, you can use coredata to remove the index attribute.

    nr <- nrow(symbol)
    change <- coredata(Cl(symbol)[nr-50]) - Cl(symbol)[nr]