pythonpandasdataframestockyfinance

Adding yfinance historical price data onto dataframe without hard-coding dates (using dates already in the dataframe)


The following code pulls balance sheet data using yfinance. I would like to get the close price as of the corresponding dates in the dataframe on the last row without hard coding dates.

import yfinance as yf

ticker_object = yf.Ticker('AAPL')
balancesheet = ticker_object.balancesheet

# Select specific rows and columns
selected_data = balancesheet.loc[['Share Issued', 'Tangible Book Value']]

selected_data

Current output:

enter image description here

Desired output:

enter image description here

Here is sample code to get price data:

import yfinance as yf

data = yf.download("AAPL", start="2017-01-01", end="2017-04-30")
data.head(3)

Output:

enter image description here


Solution

  • Because trades are close during weekends shift minimal dates for start by 3 days, then select Close columns and add new row by DataFrame.loc with Series.reindex with method='ffill', because Friday's close Price holds until open on Monday.

    import yfinance as yf
    
    ticker_object = yf.Ticker('AAPL')
    balancesheet = ticker_object.balancesheet
    
    start = balancesheet.columns.min() - pd.Timedelta(3, 'days')
    end = balancesheet.columns.max()
    
    data = yf.download("AAPL", period="5y")['Close']
    
    #test data - missing 2023-09-30 because Saturday, so used Friday values
    print (data.loc['2023-09-27':'2023-10-03'])
    Date
    2023-09-27    170.429993
    2023-09-28    170.690002
    2023-09-29    171.210007
    2023-10-02    173.750000
    2023-10-03    172.399994
    Name: Close, dtype: float64
    
    # Select specific rows and columns
    selected_data = balancesheet.loc[['Share Issued', 'Tangible Book Value']]
    selected_data.loc['Price'] = data.reindex(index=selected_data.columns, method='ffill')
    print (selected_data)
                            2023-09-30     2022-09-30     2021-09-30  \
    Share Issued         15550061000.0  15943425000.0  16426786000.0   
    Tangible Book Value  62146000000.0  50672000000.0  63090000000.0   
    Price                   171.210007     138.199997          141.5   
    
                            2020-09-30  
    Share Issued         16976763000.0  
    Tangible Book Value  65339000000.0  
    Price                   115.809998