Search code examples
rlistquantmod

Extract Stock Dividend Data from a List and Convert to Dataframe


I am using the getDividends function from the quantmod package in R to bring in dividends for a list of companies. I have this list I want to retrieve dividends for, stored as:

stocks <- c("AAPL", "MMM", "CAT", "MSFT", "TSLA")

When running getDividends on a single ticker:

getDividends("AAPL")

It gives a result looking like this:

enter image description here

I tried to write a function to do the above step for all the tickers in my list:

dividends_list <- sapply(stocks, function(x) try(getDividends(x, auto.assign = FALSE)))

From here, I'd like to convert that list to a dataframe, and be able to get the rownames as well that store the date the dividend was issued.

Hoping for a dataframe output something like this:

date        ticker   dividend
2022-11-04   AAPL     0.23
2022-08-05   AAPL     0.23
2022-11-17   MMM      1.49
2022-08-19   MMM      1.49
2023-01-19   CAT      1.20
2022-10-21   CAT      1.20
etc.

Solution

  • A suggestion with tidyquant

    library(tidyquant)
    library(tidyverse)
    
    stocks <- c("AAPL", "MMM", "CAT", "MSFT", "TSLA")
    
    tq_get(stocks, get = "dividends") %>% 
      group_by(symbol) %>% 
      slice_tail(n = 2)
    
    # A tibble: 8 × 3
    # Groups:   symbol [4]
      symbol date       value
      <chr>  <date>     <dbl>
    1 AAPL   2022-08-05  0.23
    2 AAPL   2022-11-04  0.23
    3 CAT    2022-10-21  1.2 
    4 CAT    2023-01-19  1.2 
    5 MMM    2022-08-19  1.49
    6 MMM    2022-11-17  1.49
    7 MSFT   2022-08-17  0.62
    8 MSFT   2022-11-16  0.68