I used the following code:
getSymbols(c("TSLA", "AAPL", "CSCO", "IBM"))
tsla<-TSLA['2022-01-03::2023-01-03']
aapl=AAPL['2022-01-03::2023-01-03']
csco=CSCO['2022-01-03::2023-01-03']
ibm=IBM['2022-01-03::2023-01-03']
tsla<-tsla$TSLA.Adjusted
aapl<-aapl$AAPL.Adjusted
csco<-csco$CSCO.Adjusted
ibm<-ibm$IBM.Adjusted
stkdata=cbind(tsla, aapl, csco, ibm)
n<-length(stkdata[,1])
rets<-log(stkdata[2:n,]/stkdata[1:(n-1),])
It produces all zeros.
After I assigned stkdata[2:n] to x and stkdata[1:n-1] to y, R shows
x[1,]
TSLA.Adjusted AAPL.Adjusted CSCO.Adjusted IBM.Adjusted
2022-01-04 383.1967 178.3907 59.26239 129.9028
y[1,]
TSLA.Adjusted AAPL.Adjusted CSCO.Adjusted IBM.Adjusted
2022-01-03 399.9267 180.6839 60.75242 128.0392
This is fine. But
x[1,]/y[1,]
Data:
numeric(0)
Index:
Date of length 0
What could be the problem? Thanks ahead!
1) getSymbols
can place the results into a local environment and then we can iterate over its elements using eapply
. Then use diff
with arithmetic=FALSE
causing diff
to perform division rather than subtraction.
If x is the ratio of the current price to the prior price then while it is true that log(x) approximately equals x-1 if the return is small we don't really need to use that approximation and can calculate the return exactly using x-1.
Regarding the question, xts objects do not combine by position but by time. Removing the first or last element of an xts object does not change the times so the code in the question is dividing stkdata
by itself except for the positions on the end which have been removed.
Try the code below.
library(quantmod)
tickers <- c("TSLA", "AAPL", "CSCO", "IBM")
getSymbols(tickers, env = e <- new.env(), from = "2022-01-03", to = "2023-01-03")
stks <- do.call("merge", eapply(e, Ad))
rets <- diff(stks, arithmetic = FALSE) - 1
2) A variation is to use getSymbols
to load the data into the current R workspace, as in the question, and then use mget
.
This assumes that the name of the object created for each ticker symbol is the same as the input symbol and while that is usually true it is not for symbols such as ^SPX
which contain a special character. In that case use solution (1) above, which will always work, or create a suitably modified version of tickers
to use with mget
. For example, if we have tickers <- "^IXIC"
then use tickers.out <- sub("\\^", "", tickers); mget(tickers.out)
in the code below.
library(quantmod)
tickers <- c("TSLA", "AAPL", "CSCO", "IBM")
getSymbols(tickers, from = "2022-01-03", to = "2023-01-03")
stks <- do.call("merge", lapply(mget(tickers), Ad))
rets <- diff(stks, arithmetic = FALSE) - 1