Search code examples
pythonexcelpandasyfinance

Export Lastest Quarter yfinance Balance Sheet Results Into Single Excel Workbook?


The code below is what I have so far, thanks to Luis from my earlier question. The current code creates a separate worksheet for each ticker (and all quarters). Current results are pictured below.

I would like to have one sheet with just the latest quarter results. So the results in column B would be AMZN, column C would be MSFT, column D would be FB, and all from the latest quarter reports (6/30/22 for these particular stocks).

import pandas as pd
import yfinance as yf
import datetime
import time

companies = ['AMZN','MSFT','FB']

company_metrics = {}
for company in companies:
  
        company_metrics[company] = {}
        
        company_info = yf.Ticker(company)
        company_metrics[company] = company_info.quarterly_balance_sheet
        
with pd.ExcelWriter('multiple_stocks.xlsx') as writer:
   for i in companies:
        df = pd.DataFrame(company_metrics[i])
        df.to_excel(writer, sheet_name=i)

enter image description here


Solution

  • This works for me:

    results = []
    
    for i in companies:
            result = company_metrics[i].iloc[:, 0]
            results.append(result)
    

    Then build the dataframe:

    df = pd.DataFrame(results).T
    df.columns = companies
    

    Lastly, build the excel:

    df.to_excel('Output.xlsx')
    

    enter image description here