0

I write a for loop in order to use getDividends() function from quantmod library. I want to read the symbol and the date of buy from a dataframe and use them to download the dividends from a specific year

this is my tibble "div_dummy"

symbol  shares       date year_2021
symbol shares date year_2021
1 ABT 5.00 2022-02-18 5.894309
2 ABBV 5.00 2021-09-01 5.894309
3 AAPL 5.00 2021-04-30 5.894309
4 KO 5.00 2022-02-18 5.894309
5 MDLZ 5.00 2021-09-01 5.894309
6 CRM 5.00 2022-02-18 5.894309
for (i in 1:nrow(div_dummy)) {
  symbol_dummy <- div_dummy[i,1]
  date_dummy <- div_dummy[i,3]
  div_dummy$year_2021 <- sum(getDividends(symbol_dummy, 
                                      src = "yahoo",
                                      start = date_dummy,
                                      to = "2021-12-31"))
}

in the column "year_2021" I expect to have the sum of all dividends for the year 2021 for each stock. Instead, the for loop return only the sum of the dividends of the last stock symbols "ISP.MI".

How can i fix it?

salvo
  • 11
  • 2

1 Answers1

0

You have multiple tickers with purchase date after the 2021-12-31. How you fetch dividends for them?

Until then, this code fetches the dividends from their purchase date to 2021-12-31 and returns NA if the purchase date is after that. Correct me if I misunderstood the scope

library(magrittr)
library(tidyquant)
library(tidyverse)

get_div = function(ticker, from_date) {
  if (as.Date(from_date) > as.Date("2021-12-31")) {
    NA
  } else {
    tq_get(ticker,
           get = "dividends",
           from = from_date,
           to = "2021-12-31") %$%
      sum(value)
  }
}


df %>%
  mutate(year_2021 = map2_dbl(symbol, date, get_div))
 
# A tibble: 6 × 4
  symbol shares date       year_2021
  <chr>   <dbl> <date>         <dbl>
1 ABT         5 2022-02-18     NA   
2 ABBV        5 2021-09-01      1.3 
3 AAPL        5 2021-04-30      0.66
4 KO          5 2022-02-18     NA   
5 MDLZ        5 2021-09-01      0.7 
6 CRM         5 2022-02-18     NA   
Chamkrai
  • 5,912
  • 1
  • 4
  • 14