Skip to content
Prev 14970 / 15274 Next

Web Scraping of SPY Stocks

Hi Emeka,

When you convert the dataset to a tibble you are losing the date values
stored in the rownames. I'd recommend storing the dates externally in the
function before before making the conversion then adding them back with the
mutate function:

library(quantmod)
library(dplyr)
library(tibble)
library(rvest)
library(lubridate)

# Web-scrape SP500 stock list
sp_500 <- read_html("
https://en.wikipedia.org/wiki/List_of_S%26P_500_companies") %>%
  html_node("table.wikitable") %>%
  html_table() %>%
  select(`Symbol`, Security, `GICS Sector`, `GICS Sub Industry`) %>%
  as_tibble()

# Format names
names(sp_500) <- sp_500 %>%
  names() %>%
  str_to_lower() %>%
  make.names()

# Show results
sp_500

get_stock_prices <- function(ticker, return_format = "tibble", ...){

  # Get stock prices
  stock_prices_xts <- getSymbols(Symbols = ticker, auto.assign = FALSE, ...)

  dates <- as.Date(rownames(as.matrix(stock_prices_xts)))

  # Rename
  names(stock_prices_xts) <- c("Open", "High", "Low", "Close", "Volume",
"Adjusted")

  # Return in xts format if tibble is not specified
  if (return_format == "tibble") {
    stock_prices <- stock_prices_xts %>%
      as_tibble() %>%
      mutate(Date = dates)
  } else {
    stock_prices <- stock_prices_xts
  }
  stock_prices
}

"MA" %>%
  get_stock_prices(return_format = 'tibble') %>%
  head()

Best,

Matt

On Sat, Sep 26, 2020 at 1:34 PM AIE ATUMA via R-SIG-Finance <
r-sig-finance at r-project.org> wrote: