BarbG
BarbG

Reputation: 9

Loop through list of stocks in yfinance

I want to loop through a long list of stocks in yfinance My while loop is picking up only the first ticker symbol and info. Why won't it iterate? thru all of the list?

symbols = pd.read_csv("symbol_list_short.csv")

counter = 0
while counter <= len(symbols):
   
    for symbol in symbols:
        stock = yf.Ticker(symbol)
        try:
            if stock.info['pegRatio']:
                print(str(stock.info['symbol'] + " : " + str(stock.info['pegRatio'])))
        except KeyError:
                pass
counter += 1

Upvotes: 0

Views: 545

Answers (1)

drg01
drg01

Reputation: 1

There are several reasons why the code above does not work from what I can tell.

  1. counter += 1 needs to be indented
  2. counter += 1 is known to fail in Python so it is safer to use counter=counter+1
  3. yfinance seems to be having problems in accessing Yahoo Finance data OutputFromYourCode
  4. You may need to use another vendor and compute PEG yourself.
  5. The code snippet (and output) below reflects Financial Modelling Prep Cloud
import os
from dotenv import load_dotenv
import fmpsdk # Financial Modeling Prep (FMP)
import pandas as pd
#import yfinance as yf

# Actual API key is stored in a .env file.  
load_dotenv()
apikey = os.environ.get("apikey")

symbols=["AAPL","MSFT","GOOGL"]
counter = 0
print("\n\nTicker\t\t\tEPS\t\t\tREVENUE")
while counter < len(symbols):
    stock = fmpsdk.historical_earning_calendar(apikey=apikey, symbol=symbols[counter], limit=limit) #yf.Ticker(symbol)
    try:
        if stock[0]["symbol"] in symbols:
            print(str(stock[0]["symbol"] + ": \t\t\t" + str(stock[0]["eps"]) + "\t\t" + str(stock[0]["revenue"])))
    except KeyError:
            pass
    counter = counter + 1
OUTPUT
Ticker          EPS         REVENUE
AAPL:           1.88        117154000000
MSFT:           2.32        52747000000
GOOGL:          1.05        76048000000    

Upvotes: -1

Related Questions