Reputation: 11
So I am just trying to extra 100 different stocks from YH using yfR and quantmod then calculate the daily returns for these stocks (eventually I will use this data to calculate the mean daily returns of each stock & the covariance to be used in a GA).
This is my code to attempt to do this:
library(yfR)
library(quantmod)
df_ftse <- yf_index_composition("FTSE")
assets <- sample(df_ftse$ticker, 100)
dailyReturns = lapply(assets, function(sym) {
dailyReturn(na.omit(getSymbols(sym, from="2021-01-01", to="2022-01-01", auto.assign=FALSE)))
})
But occaisonally if a Stock has a problem, I get this error from quantmod:
Error in getSymbols.yahoo(Symbols = "ABF", env = <environment>, verbose = FALSE, :
Unable to import “ABF”.
attempt to set an attribute on NULL
i understand sometimes getSymbols can't get data for a stock for whatever reason. Is there a way to exclude the "broken" or error stocks automatically? I thought the na.omit might help but I think I may be using it wrong.
Couldn't find any other solution about this so thought it was worth asking around. Thanks!
Upvotes: 0
Views: 53
Reputation: 6583
Since quantmod
fetches data from Yahoo Finance, we need to match tickers with how they are listed on the website. Therefore, append “.L” to them before calling the function. Note that all except HLN.L are fetched since the company did not go public before July 2022.
library(tidyquant)
library(tidyverse)
tickers <- yfR::yf_index_composition("FTSE") %>%
pull(ticker) %>%
str_c(".L")
df <- tq_get(tickers, from = "2021-01-01", to = "2022-01-01") %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "daily")
# A tibble: 25,017 × 3
# Groups: symbol [99]
symbol date daily.returns
<chr> <date> <dbl>
1 AAF.L 2021-01-04 0
2 AAF.L 2021-01-05 0.0430
3 AAF.L 2021-01-06 0.0348
4 AAF.L 2021-01-07 -0.00747
5 AAF.L 2021-01-08 -0.0188
6 AAF.L 2021-01-11 -0.00767
7 AAF.L 2021-01-12 -0.0155
8 AAF.L 2021-01-13 -0.0118
9 AAF.L 2021-01-14 0.0662
10 AAF.L 2021-01-15 -0.0224
# ℹ 25,007 more rows
# ℹ Use `print(n = ...)` to see more rows
Upvotes: 0