This script is designed to extract basic data about all listed stocks on S&P via wikipedia and then use the get symbol to extract price data over a period of time, then calculate log.return over the same period of time, and subsequently aggregate these log return with mean, sd of return and the number of log return data used. These calculations are then added to the list of traded stocks from wikipedia using the filter function and added to a new table called output.
If i run this script individually on stock ticker symbols, it runs without issue. However, when i try to use the for loop function or the Analyze stocks function, the table gives an error or no data is added to the output table. Please i need help to figure this out!
{
library(quantmod)
library(xts)
library(rvest)
library(tidyverse)
library(stringr)
library(forcats)
library(lubridate)
#Extracting from Wikipedia a S&P Data
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()
#Creating an empty tibble table
tbl_colnames <- c("ticker.symbol","security","gics.sector",
"gics.sub.industry", "mean_return", "sd_return", "days")
output <- tibble::tibble(!!!tbl_colnames, .rows = 0, .name_repair = ~ tbl_colnames)
#Sample list of Stock symbols
symbol_list = c("TSLA", "AKAM","ACN")
#Function to analyze stocks symbols
analyze_stocks = function(stocks){
for (i in stocks){
stock_prices_xts <- getSymbols(i, auto.assign = FALSE)
names(stock_prices_xts) <- c("Open", "High", "Low", "Close", "Volume", "Adjusted")
stock_prices <- stock_prices_xts %>%
as_tibble() %>%
rownames_to_column(var = "Date") %>%
mutate(Date = index(stock_prices_xts))
if (!is.xts(stock_prices)) {
x <- xts(stock_prices[,-1], order.by = stock_prices$Date)
}
log_returns_xts <- periodReturn(x$Adjusted, type = 'log', period = 'daily')
names(log_returns_xts) <- "Log.Returns"
log_returns <- log_returns_xts %>%
as_tibble() %>%
rownames_to_column(var = "Date") %>%
mutate(Date = index(log_returns_xts))
stock_prices_xts = merge.xts(stock_prices_xts, log_returns_xts)
output = rbind(output, sp_500 %>% as_tibble() %>%
filter(sp_500$Symbol == stocks(i)) %>%
mutate(mean_return = mean(log_returns_xts), sd_return = sd(log_returns_xts), days = nrow(log_returns_xts)))
}
return(output)
}
analyze_stocks(symbol_list)
}
Sometimes I get these errors when i try to use the for loop or the Analyze stock function.
{
Error in filter()
:
ℹ In argument: sp_500$Symbol == stocks(i)
.
Caused by error in stocks()
:
! could not find function “stocks”
}
Tbiz Adeniyi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.