Export yfinance Balance Sheet Results To CSV

Question:

This code works great to obtain quarterly balance sheet results. But I cannot seem to export company_metrics to a CSV file.

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

print(company_metrics)

I tried altering the above code with the following, but was not successful:

for company in companies:
    try:    
        company_metrics[company] = {}
        
        company_info = yf.Ticker(company)
        company_metrics[company] = company_info.quarterly_balance_sheet
    except:
        pass
        
df = pd.DataFrame.from_dict(company_metrics)
df.to_csv('stocksBS92222.csv')
Asked By: HTMLHelpMe

||

Answers:

This solution it can work for you. I made an excel file containing the info in each sheet for different companies:

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)

I think a CSV file containing the three companies is messy and to_csv do not allow multiple sheets in the same file, so excel is the way to go here. Let me know if it works.

enter image description here

Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.