Search code examples
rquantmodalgorithmic-tradingtrading

How to extract only closing prices with Quantmod


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")


Solution

  • 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]