Reputation: 1
I'm trying to use tq_get to download the stock prices based on the tickers. Here is the head of my dataset merge_df
. I have more than 300 companies and I need to get their stock price the day before the date.filed.
symbol | company_name | date.filed |
---|---|---|
A | Agilent Technologies | 2020-12-18 |
A | Agilent Technologies | 2019-12-19 |
A | Agilent Technologies | 2021-12-17 |
AA | Alcoa | 2020-02-21 |
AA | Alcoa | 2019-02-26 |
AA | Alcoa | 2021-02-25 |
Here I want to thank to @Tom Hoel who provided one of the solution to me. But when I tried this code, I found it only works when there is only one date for one company. Here is the code:
final_df <- merge_df %>%
mutate(date.filed = date.filed %>% as.Date(),
price_before_filing = map2(.x = symbol,
.y = date.filed,
~ tq_get(.x, from = as.Date(.y) - 1) %>%
slice(1) %>%
pull(adjusted)) %>%
as.numeric()) %>%
select(symbol, company_name, price_before_filing, everything())
The error reported as:
Warning: Problem with `mutate()` column `price_before_filing`.
ℹ `price_before_filing = `%>%`(...)`.
ℹ x = 'BAND', get = 'stock.prices': Error in getSymbols.yahoo(Symbols = "BAND", env = <environment>, verbose = FALSE, : Unable to import “BAND”.
BAND download failed after two attempts. Error message:
HTTP error 401.
Error: Problem with `mutate()` column `price_before_filing`.
ℹ `price_before_filing = `%>%`(...)`.
x no applicable method for 'slice' applied to an object of class "logical"
Run `rlang::last_error()` to see where the error occurred.
Do anyone know why I have this error and how can I fix it?
Much thanks!!
Upvotes: 0
Views: 557
Reputation: 6583
Strange, I do not get any errors. Are your packages up to date?
I am running tidyquant 1.0.4
and tidyverse 1.3.1
library(tidyquant)
library(tidyverse)
df %>%
mutate(date.filed = date.filed %>% as.Date(),
price_before_filing = map2(.x = symbol,
.y = date.filed,
~ tq_get(.x,
from = as.Date(.y) - 1) %>%
slice(1) %>%
pull(adjusted)) %>%
as.numeric())
# A tibble: 6 x 4
symbol company_name date.filed price_before_filing
<chr> <chr> <date> <dbl>
1 A Agilent_Technologies 2020-12-18 118.
2 A Agilent_Technologies 2019-12-19 81.9
3 A Agilent_Technologies 2021-12-17 150.
4 AA Alcoa 2020-02-21 16.0
5 AA Alcoa 2019-02-26 30.6
6 AA Alcoa 2021-02-25 27.1
Upvotes: 0