How to extract only closing prices with Quantmod

Viewed 320

I am new to quantmod

I am using quantmod to extract stock prices, however, I want to restrict my extraction only to closing prices. I am wondering if there is a way to do it instead of downloading all default columns.

This is the code I am using

tickers <- c("1COV.DE","ADS.DE","ALV.DE","BAS.DE")
from <- "2014-10-01"
to = "2021-07-29"

getSymbols(tickers,
           src = "yahoo",
           from = from,
           to = to,
           adjust = TRUE,
           periodicity = "daily")

2 Answers

One way is to use tidyquant library and put all four stocks in one data frame. Then you can group by the symbol. In that way, you don't have problems with different lengths of symbols.

library(tidyquant)

tickers <- c("1COV.DE","ADS.DE","ALV.DE","BAS.DE")
from <- "2014-10-01"
to = "2021-07-29"

closed <- tq_get(tickers, 
       from = from, 
       to = to) %>%
  select(symbol, date, close) %>% 
  arrange(date)

You can do it with this pattern:

tickers <- c("1COV.DE", "ADS.DE", "ALV.DE", "BAS.DE")

# Store all data in a new environment
e <- new.env()
getSymbols(tickers, from = "2014-10-01", adjust = TRUE, env = e)

# Combine close prices
prices <- do.call(merge, lapply(e, Cl))
# remove leading "X" created by make.names()
colnames(prices) <- gsub("^X", "", colnames(prices))
# remove ".Close" suffix
colnames(prices) <- gsub(".Close", "", colnames(prices), fixed = TRUE)
# reorder columns to match 'tickers'
prices <- prices[, tickers]
Related