Home > database >  Yahoo Finance/Pandas For loop pulls the data I want but combines data through the loop instead of se
Yahoo Finance/Pandas For loop pulls the data I want but combines data through the loop instead of se

Time:06-24

I'm building a script to pull data from Yahoo finance on multiple different companies and have run into an issue in my loop:

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

companies = ['AAPL', 'MSFT', 'AMZN', 'PYPL']

xlwriter = pd.ExcelWriter('marketcap.xlsx', engine='openpyxl')
company_metrics = {}
for company in companies:
        company_metrics[company] = {}
        company_info = yf.Ticker(company)
        company_metrics[company]['Market Cap'] = company_info.info['marketCap']
        df = pd.DataFrame.from_dict(company_metrics)
        df.to_excel(xlwriter, sheet_name=company, index=False)

xlwriter.save()

The data pulls fine, but when continuing through the loop, each new company data gets added to the lasts until the last sheet is the new data including all prior data... I would like all my sheets to only include their own data on their own individual sheets.

Thank you for your time to read my post!

CodePudding user response:

Try changing write line to:

df[company].to_excel(xlwriter, sheet_name=company, index=False)
  • Related