Dividend rates and dates for multiple stocks at once using python

3k Views Asked by At

I am trying to download multiple stocks dividend amounts and respective dates using yfinance package and trying to save it in a python Data Frame.

I am using following code

import yfinance as yf

data = pd.DataFrame()
stock_list = ['MSFT','GOOG','AAPL']

start = '2019-10-1'
end = '2020-10-30'

for i in stock_list:
    data[i]= yf.Ticker(i).dividends.loc[start:end]

but what I get is :

           MSFT  GOOG  AAPL
Date                        
2019-11-20  0.51   NaN   NaN
2020-02-19  0.51   NaN   NaN
2020-05-20  0.51   NaN   NaN
2020-08-19  0.51   NaN   NaN

if I change the stock position in the stock_list as (AAPL first and MSFT last)

stock_list = ['AAPL','GOOG','MSFT']

I get this:

             AAPL  GOOG  MSFT
Date                          
2019-11-07  0.1925   NaN   NaN
2020-02-07  0.1925   NaN   NaN
2020-05-08  0.8200   NaN   NaN
2020-08-07  0.2050   NaN   NaN

I think the Data Frame set dates for the first stock and as it is not necessary that the subsequent stock paid dividends on the same dates it is shown as NaN.

I would appreciate any help to get all dividends in a given period for a long list of stocks.

2

There are 2 best solutions below

3
Josmy On BEST ANSWER

You could use pd.concat. You can observe that the dividends dates are different that's why you got real values only for the first column.

import yfinance as yf
import pandas as pd

data = pd.DataFrame()
stock_list = ['AAPL', 'MSFT','GOOG']

start = '2019-10-1'
end = '2020-10-30'

for i in stock_list:
    series = yf.Ticker(i).dividends.loc[start:end]
    data = pd.concat([data, series], axis=1)
data.columns = stock_list
1
r-beginners On

Since the date of the first acquisition is combined with the date of the first issue because the date of the dividend is different for each issue, you can see the list by using pd.concat().

data = pd.concat([data,yf.Ticker(i).dividends.loc[start:end]], join='outer',axis=1)

                MSFT    GOOG    AAPL
2019-11-07 00:00:00 NaN NaN 0.1925
2019-11-20 00:00:00 0.51    NaN NaN
2020-02-07 00:00:00 NaN NaN 0.1925
2020-02-19 00:00:00 0.51    NaN NaN
2020-05-08 00:00:00 NaN NaN 0.8200
2020-05-20 00:00:00 0.51    NaN NaN
2020-08-07 00:00:00 NaN NaN 0.2050
2020-08-19 00:00:00 0.51    NaN NaN