Search code examples
pythonpandasdataframeyfinancestock-data

Dividend rates and dates for multiple stocks at once using python


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.


Solution

  • 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