3

I am trying to download multiple stocks dividend amounts and respective dates using yfianance 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 neccassry 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.

Thanks

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153

2 Answers2

1

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
Josmy
  • 408
  • 3
  • 12
  • 1
    great exactly the way I want. I have now just to think about NaNs, but the above code serve the purpose. Thanks – Rizwan Ahmed Nov 13 '20 at 02:39
  • 1
    @RizwanAhmed I am glad it helped. I guess in this case, NaNs could be just 0s since some companies just don't pay dividends. If it's the case, you can just use `data.fillna(0)` – Josmy Nov 13 '20 at 03:28
  • I agree that will further make it look cleaner. Thanks – Rizwan Ahmed Nov 13 '20 at 23:14
0

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
r-beginners
  • 31,170
  • 3
  • 14
  • 32