How to subtract lines in xts

I use quantmod, and I need to find the difference between the close value of today and the closing value on the 50th day.

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 can’t subtract it and get this error

Data:
numeric(0)

Index:
numeric(0)
+4
source share
1 answer

For xts objects, binary mathematical and logical operators always align two objects by indices before performing the operation. Therefore, you need to use lagindex alignment for proper alignment if you want to use these operators for observations at different timestamps.

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

, lag.xts lag.ts lag.zoo ( k ), k ( ).


, xts, coredata .

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

Source: https://habr.com/ru/post/1606297/


All Articles