Home > Software design >  Extract Stock Dividend Data from a List and Convert to Dataframe
Extract Stock Dividend Data from a List and Convert to Dataframe

Time:01-30

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.

CodePudding user response:

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

CodePudding user response:

We may use

library(quantmod)
library(zoo)
out <- do.call(rbind, lapply(Filter(nrow, dividends_list), 
    \(x) {
    x1 <- fortify.zoo(x)
    x1$ticker <- sub("\\.div", "", names(x1)[2])
   names(x1) <- c("date", "dividend", "ticker")
  x1})
)
row.names(out) <- NULL

-output

library(dplyr)
out %>% 
 slice_tail(n = 2, by = 'ticker')
        date dividend ticker
1 2022-08-05     0.23   AAPL
2 2022-11-04     0.23   AAPL
3 2022-08-19     1.49    MMM
4 2022-11-17     1.49    MMM
5 2022-10-21     1.20    CAT
6 2023-01-19     1.20    CAT
7 2022-08-17     0.62   MSFT
8 2022-11-16     0.68   MSFT
  • Related