4

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)
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
Eka
  • 14,170
  • 38
  • 128
  • 212

1 Answers1

3

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]
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • Getting this error `Error in hasTsp(x) : attempt to set an attribute on NULL` . For more information i have added the rest of the code – Eka Sep 07 '15 at 17:29
  • @Eka: The code in your question works fine for me using quantmod and xts from both CRAN and GitHub. Please edit into your question the output of `sessionInfo()` and `traceback()` (after the line that throws the error). – Joshua Ulrich Sep 07 '15 at 17:36
  • this is the code `symbol$diff50 <- lag(symbol$Close, 50) - symbol$Close` and traceback result `3: hasTsp(x) 2: lag.default(symbol$Close, 50) 1: lag(symbol$Close, 50)` . I dont know whether you understood me correctly I am expecting only a single variable result that is 50th day close value(previous)- todays/recent market close value – Eka Sep 07 '15 at 17:47
  • 1
    `lag.default` is being dispatched when it shouldn't be. This is likely because you have dplyr attached and it masks `stats::lag`, and breaks method dispatch. – Joshua Ulrich Sep 07 '15 at 18:08