The script is meant to extract list of stocks symbols and its corresponding data for analysis but i keep getting error when i get to the map section of the code. The script is given below:
{
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()
colnames(sp_500) <- c("ticker.symbol","security","gics.sector","gics.sub.industry")
get_stock_prices <- function(ticker, return_format = "tibble", ...) {
# Get stock prices
stock_prices_xts <- getSymbols(Symbols = ticker, auto.assign = FALSE, ...)
# 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() %>%
rownames_to_column(var = "Date") %>%
mutate(Date = ymd(Date))
} else {
stock_prices <- stock_prices_xts
}
stock_prices
}
get_log_returns <- function(x, return_format = "tibble", period = 'daily', ...) {
# Convert tibble to xts
if (!is.xts(x)) {
x <- xts(x[,-1], order.by = x$Date)
}
# Get log returns
log_returns_xts <- periodReturn(x = x$Adjusted, type = 'log', period = period, ...)
# Rename
names(log_returns_xts) <- "Log.Returns"
# Return in xts format if tibble is not specified
if (return_format == "tibble") {
log_returns <- log_returns_xts %>%
as_tibble() %>%
rownames_to_column(var = "Date") %>%
mutate(Date = ymd(Date))
} else {
log_returns <- log_returns_xts
}
log_returns
}
# Mapping the Functions --------------------------------------------------------
from <- "2007-01-01"
to <- today()
sp_500 <- sp_500 %>%
mutate(
stock.prices = map(ticker.symbol,
function(.x) get_stock_prices(.x,
return_format = "tibble",
from = from,
to = to)
),
log.returns = map(stock.prices,
function(.x) get_log_returns(.x, return_format = "tibble")),
mean.log.returns = map_dbl(log.returns, ~ mean(.$Log.Returns)),
sd.log.returns = map_dbl(log.returns, ~ sd(.$Log.Returns)),
n.trade.days = map_dbl(stock.prices, nrow)
)
}
The purpose of this code is to list the extracted symbols, the stock prices, log return, mean.log.return. sd.log.returns and n.trade.days and this doesnt work. The map() function, mutate() and getsymbols() keeps throwing up an error message that I cant figure what the solutions is. PlEASE HELP! I keep getting this error message below
Error in mutate()
:
ℹ In argument: stock.prices = map(...)
.
Caused by error in map()
:
ℹ In index: 24.
Caused by error in getSymbols.yahoo()
:
! Unable to import “AMCR”.
Timeout was reached: [query2.finance.yahoo.com] Failed to connect to query2.finance.yahoo.com port 443 after 10001 ms: Timeout was reached`
Tbiz Adeniyi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.